blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
35efedd7c042fae42156fe88503c8d35aff1357f
|
RodionLe/homework
|
/5/5.10.py
| 125 | 3.671875 | 4 |
x = int(input("Введите курс доллара: "))
for i in range(1,21):
print(str(i)+"$ =", str(i * x) + "р.")
|
a0f4b3fb4f1b56f21cb3c03d4e4536919d05ceb6
|
bkalcho/python-crash-course
|
/sum_million.py
| 418 | 3.765625 | 4 |
# Author: Bojan G. Kalicanin
# Date: 28-Sep-2016
# Sum first million of numbers. Also determine min and max of the list of the
# first million numbers, to make sure that list begins with one and ends
# with one million
numbers = list(range(1, 1000001))
print("Minimum element of the list is: " + str(min(numbers)))
print("Maximum element of the list is: " + str(max(numbers)))
print("Sum of the list is: " + str(sum(numbers)))
|
0edbf83fbee4fe16e45cd0e6555f6b8fce45c25f
|
EndriwMichel/estudoPython
|
/PythonDsa/cap14/web_to_pandas.py
| 572 | 3.59375 | 4 |
# Convertendo páginas web para pandas
import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
res = requests.get('http://www.nationmaster.com/country-info/stats/Media/Internet-users')
soup = BeautifulSoup(res.content, 'lxml')
table = soup.find_all('table')[0]
# Convertendo para pandas
df = pd.read_html(str(table))
print(df)
# Conversão do pandas para um objeto Json
print(df[0].to_json(orient='records'))
# Utilizando o tabulate para formatar a saida da informação
print(tabulate(df[0], headers='keys', tablefmt='psql'))
|
d35bdeed9138c9643ad21e44717eb995dadde5a2
|
oprk/project-euler
|
/p048_self_powers/self_powers.py
| 341 | 3.53125 | 4 |
# Self powers
# Problem 48
# The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
# Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
import time
t0 = time.time()
result = str(sum(i**i for i in xrange(1000 + 1)))[-10:]
t1 = time.time()
print(result)
print('time %f' % (t1 - t0))
# 9110846701
# time 0.008385
|
d39aaaf9e99039598d6ac89587d699f9edb0b72e
|
xuguoliang1995/leetCodePython
|
/python_know/normal/demo9_9.py
| 620 | 4.375 | 4 |
# 布尔测试__bool__ __len__
"""
python3首次尝试__bool__来获取一个直接的布尔值,没有的话再使用__len__类
根据对象的长度确定一个真值,
"""
class Truth:
def __bool__(self): return True
def __len__(self): return 0
X = Truth()
if X: print("yes")
# 对象的析构函数 __del__
"""
每当实例空间回收的时候(垃圾收集时),析构函数就会自动执行。
"""
class Life:
def __init__(self, name="ukown"):
print("hello", name)
self.name = name
def __del__(self):
print("Goodbye", self.name)
brain = Life("brain")
|
968be3dc66f378c644314b9648b7ea6c1bd81ab4
|
Rex-Arnab/compititive-challenges
|
/CodeWars/ip-validation.py
| 1,204 | 3.546875 | 4 |
# Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.
# Input to the function is guaranteed to be a single string.
#! Examples
#* Valid inputs:
#* 1.2.3.4
#* 123.45.67.89
#* Invalid inputs:
#* 1.2.3
#* 1.2.3.4.5
#* 123.456.78.90
#* 123.045.067.089
#TODO Note that leading zeros (e.g. 01.02.03.04) are considered invalid.
#TODO THis one was my first solution
# def is_valid_IP(ip):
# octt = ip.split('.')
# if len(octt) != 4: return False
# for octet in octt:
# if not is_valid_octet(octet):
# return False
# return True
# def is_valid_octet(octet):
# if not octet.isdigit():
# return False
# if len(octet) > 1 and octet[0] == '0':
# return False
# octet = int(octet)
# if octet >= 0 and octet <= 255:
# return True
# else:
# return False
#TODO Solution 2 (optimized)
def is_valid_IP(strng):
lst = strng.split('.')
passed = 0
for sect in lst:
if sect.isdigit():
if sect[0] != '0':
if 0 < int(sect) <= 255:
passed += 1
return passed == 4
|
9ac87d1079a2ee219424ef640ca506fae2e1239f
|
RomanEngeler1805/Data-Structures-Algorithms
|
/V5-Sorting/HeapSort.py
| 738 | 3.78125 | 4 |
import numpy as np
from copy import deepcopy
def SiftDown(arr, i, m):
while 2*i < m: # XXX
j = 2*i
if j< m and arr[j] < arr[j+1]:
j+= 1
if arr[i] < arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i = j
else:
i = m
return arr
def HeapSort(arr, n):
for i in range(int(n/2)-1, 0, -1):
arr = SiftDown(arr, i, n)
for i in range(n-1, 0,-1):
temp = arr[0]
arr[0] = arr[i]
arr[i] = temp
arr = SiftDown(arr, 0, i-1)
return arr
if __name__ == "__main__":
#arr = np.array([7, 6, 4, 5, 1, 2])
arr = np.array([7, 2, 5, 4, 3, 6, 1])
#arr = np.array([2, 6, 3, 1, 4, 5])
arr_sorted = HeapSort(deepcopy(arr), len(arr))
print('Unsorted array: '+ str(arr))
print('Sorted array: '+ str(arr_sorted))
|
ccb3b388bb011dbf0566444921536fe16f6ca30a
|
Iftakharpy/Data-Structures-Algorithms
|
/section 14 implementaion_of_Breath_First_Search(BFS).py
| 1,243 | 3.75 | 4 |
def breath_first_search(binary_tree,vertex):
visited_vertex = [] #list to keep track of visited vertesies
queue = [] #queue to keep track of all the sub trees/child nodes of the tree.
queue.append(binary_tree)
while queue:
#adding sub tree to the queue
binary_tree = queue.pop(0)
#adding the tree value to the visited_vertex list
visited_vertex.append(binary_tree['value'])
if visited_vertex[-1]==vertex:
print('vertex is found!')
break
#if left child node exists then add it to the queue
if binary_tree['low']:
queue.append(binary_tree['low'])
#if right child node exists then add it to the queue
if binary_tree['high']:
queue.append(binary_tree['high'])
return visited_vertex
#test
#tree of the graph should look like this
# 9
# / \
# 4 20
# / \ / \
# 1 6 15 200
graph = {'value': 9, 'high': {'value': 20, 'high': {'value': 200, 'high': None, 'low': None}, 'low': {'value': 15, 'high': None, 'low': None}}, 'low': {'value': 4, 'high': {'value': 6, 'high': None, 'low': None}, 'low': {'value': 1, 'high': None, 'low': None}}}
vertex = 200
breath_first_search(graph,vertex)
|
e9558534c29d55bdbdde56196c87fa5cec796003
|
schiob/TestingSistemas
|
/ago-dic-2018/Ernesto Vela/Practica1/contar.py
| 779 | 3.609375 | 4 |
pos = 0
neg = 0
par = 0
imp = 0
list = []
import sys
tot = int(input('¿Con cuántos números vamos a trabajar? '))
num = input('Escribe los números separados por un espacio: ')
list=[int(tot) for tot in num.split(" ")]
for i in range(0,tot):
n = list[i]
if len(list) > tot:
print('Escribiste números de mas!!!')
sys.exit()
if len(list) < tot:
print('Te faltaron números por escribir!!!')
sys.exit()
if n % 2 == 0:
par = par + 1
if n % 2 != 0:
imp = imp + 1
if n > 0:
pos = pos + 1
if n < 0:
neg = neg + 1
print(str(par) + " Numero(s) Par" + '\n' + str(imp) + " Numero(s) Impar" + '\n' + str(pos) + " Numero(s) Positivos" + '\n' + str(neg) + " Numero(s) Negativos")
|
2f2fe636142d1859b49195d440d60e6641a45bc9
|
inwk6312fall2018/programmingtask2-hanishreddy999
|
/crime.py
| 685 | 3.515625 | 4 |
from tabulate import tabulate #to print the output in table format
def crime_list(a): #function definition
file=open(a,"r") #open csv file in read mode
c1=dict()
c2=dict()
lst1=[]
lst2=[]
for line in file:
line.strip()
for lines in line.split(','):
lst1.append(lines[-1])
lst2.append(lines[-2])
for b in lst1:
if b not in c1:
c1[b]=1
else:
c1[b]=c1[b]+1
for c in lst2:
if c not in c2:
c2[c]=1
else:
c2[c]=c2[c]+1
print(tabulate(headers=['CrimeType', 'CrimeId', 'CrimeCount']))
for k1,v in c1.items():
for k2,v in c2.items():
x=[k1,k2,v] #tabular format
print(tabulate(x))
file_name="Crime.csv"
crime_list(file_name)
|
f0fa4676e033a5fabb1d4ae89dbdeeeb72b83a8a
|
MarcosBan/IMPACTA-PROGRAMACAO
|
/Atividade-Aula-25-03.py
| 389 | 3.65625 | 4 |
def exibe_status(n_aluno, f_aluno):
if n_aluno >= 5.0 and f_aluno <= 25:
if n_aluno >= 7.0:
print('Aluno aprovado!')
else:
print('Aluno em recuperação!')
else:
print('Aluno reprovado!')
return
nota = float(input('Insira a sua nota: '))
presenca = int(input('Insira a sua quantidade de faltas: '))
exibe_status(nota, presenca)
|
866fb7e08a7651867e885d7db4be1b2d48789c3a
|
mayank888k/Python
|
/Multilevel_Inheritence.py
| 593 | 3.84375 | 4 |
class Grandfather():
A=1 #In Multilevel inheritence Father can access GrandFather
def __init__(self): #son can access father so {both Grandfather and father}
self.gfname="Late Roopram"
class Father(Grandfather):
B=2
def __init__(self):
Grandfather.__init__(self)
self.fname="Arvind Kumar"
class Me(Father):
C=3
def __init__(self):
Father.__init__(self)
self.name="Mayank Kumar"
person=Me()
print(person.name,person.A)
print(person.fname,person.B)
print(person.gfname,person.C)
|
ab2cc4eafb8aea847f2079a66bf1e6702981853e
|
ottoguz/My-studies-in-Python
|
/ex009.py
| 581 | 4.09375 | 4 |
#MULTIPLICATION TABLE OF AN ENTIRE NUMBER
n = int(input('Type a number'))
mt1 = '{}x1 = {}'.format(n, n*1)
mt2 = '{}x2 = {}'.format(n, n*2)
mt3 = '{}x3 = {}' .format(n, n*3)
mt4 = '{}x4 = {}' .format(n, n*4)
mt5 = '{}x5 = {}' .format(n,n*5)
mt6 = '{}x6 = {}' .format(n, n*6)
mt7 = '{}x7 = {}' .format(n, n*7)
mt8 = '{}x8 = {}' .format(n, n*8)
mt9 = '{}x9 = {}' .format(n, n*9)
mt10 = '{}x10 = {}' .format(n, n*10)
print('-'*10)
print(mt1)
print(mt2)
print(mt3)
print(mt4)
print(mt5)
print(mt6)
print(mt7)
print(mt8)
print(mt9)
print(mt10)
print('-'*10)
|
ecb61affd34a60e8a0ee3f3ee68c82dae39ce417
|
hidrokit/hidrokit
|
/hidrokit/contrib/taruma/hk79.py
| 2,721 | 3.65625 | 4 |
"""manual:
https://gist.github.com/taruma/05dab67fac8313a94134ac02d0398897
"""
import pandas as pd
import numpy as np
from calendar import monthrange
from hidrokit.contrib.taruma import hk43
# ref: https://www.reddit.com/r/learnpython/comments/485h1p/
from collections.abc import Sequence
def _index_hourly(year, freq='60min'):
"""Create DatetimeIndex with specific year or [year_start, year_end]"""
if isinstance(year, Sequence):
year_start, year_end = year
else:
year_start, year_end = year, year
period = '{}0101 00:00,{}1231 23:00'.format(
year_start, year_end).split(',')
return pd.date_range(*period, freq=freq)
def _melt_to_array(df):
return df.melt().drop('variable', axis=1)['value'].values
def _get_array_in_month(df, year, month):
n_days = monthrange(year, month)[1]
mask_month = slice(None, n_days)
df_month = df.iloc[mask_month, :].T
return _melt_to_array(df_month)
def _get_year(df, loc=(0, 1)):
return df.iloc[loc]
def _get_array_in_year(df, year):
n_rows, _ = df.shape
# configuration (view the excel)
n_month = 1 # number of row to monthID
n_gap = 2 # number of row between month pivot table
n_lines = 31 + n_gap # number of row each month
data = []
for row in range(1, n_rows, n_lines):
mask_start = row + n_month
mask_end = row + n_lines
month = df.iloc[mask_start, 1]
mask_row = slice(mask_start, mask_end)
df_month = df.iloc[mask_row, 4:]
array_month = _get_array_in_month(df_month, year, month)
data.append(array_month)
return np.hstack(data)
def _get_info(file, config_sheet=None):
excel = pd.ExcelFile(file)
first_sheet = excel.sheet_names[0]
config_sheet = first_sheet if config_sheet is None else config_sheet
df = pd.read_excel(
excel, sheet_name=config_sheet, header=None, usecols='A:B'
)
info = {}
for index, _ in df.iterrows():
key = df.iloc[index, 0].lower()
value = df.iloc[index, 1]
info[str(key)] = value
return info
def read_excel_hourly(file, station=None):
excel = pd.ExcelFile(file)
# CONFIG
years = hk43._get_years(excel)
station = 'NA' if station is None else station
# READ DATA
data = []
for year in years:
sheet = pd.read_excel(
excel, sheet_name=str(year),
header=None, nrows=396,
usecols='A:AB'
)
array = _get_array_in_year(sheet, year)
df_year = pd.DataFrame(
data=array,
columns=[station],
index=_index_hourly(year)
)
data.append(df_year)
return pd.concat(data, axis=0)
|
8c4f7e9914ac031acf427e6f7cc56d6352626300
|
Starfloat/Practice-Python-Solutions
|
/01-character-input.py
| 785 | 4.25 | 4 |
# https://www.practicepython.org/exercise/2014/01/29/01-character-input.html
"""
Exercise 1 (and Solution)
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old.
Extras:
1. Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.
2. Print out that many copies of the previous message on separate lines.
"""
from datetime import date
name = input('Enter your name: ')
age = int(input('Enter your age: '))
today = date.today()
year = today.year
age_difference_from_100 = 100-age
year_to_be_100 = year + age_difference_from_100
print(name + ', you will be age 100 in the year', + year_to_be_100)
|
2ace15c4aec7b09fe56898f6a69a077759aa551b
|
phibzy/InterviewQPractice
|
/Solutions/MergeTwoLists/mergeTwoLists.py
| 2,035 | 4.03125 | 4 |
#!/usr/bin/python3
"""
Given two sorted singly linked lists, merge them into one ordered list
Return head of sorted list
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# Two approaches:
# 1 - Create dummy head and just keep adding on
# 2 - Use one of the existing heads
# Approach 1
# def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# newL = None
# if l1 is None and l2 is None: return None
# if l1 and not l2: return l1
# if l2 and not l1: return l2
# if l1.val < l2.val:
# head = l1
# newL = l1
# l1 = l1.next
# else:
# head = l2
# newL = l2
# l2 = l2.next
# newL.next = None
# while l1 and l2:
# if l1.val < l2.val:
# newL.next = l1
# l1 = l1.next
# else:
# newL.next = l2
# l2 = l2.next
# newL = newL.next
# newL.next = None
# if l1: newL.next = l1
# if l2: newL.next = l2
# return head
# Approach 2
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2: return None
if not l1 and l2: return l2
if l1 and not l2: return l1
if l2.val < l1.val:
temp = l2
l2 = l1
l1 = temp
head = l1
while l1.next and l2:
if l2.val < l1.next.val:
rest1 = l1.next
rest2 = l2.next
l1.next = l2
l1.next.next = rest1
l2 = rest2
l1 = l1.next
if l2: l1.next = l2
return head
def printList(self, l):
while l:
print(f" {l.val} -->", end='')
print()
|
de9d99d5e3e4d1ce17d9190eeb4a2c687305b9b9
|
Raeebikash/python_class1
|
/python_class/for_loop_practice30.py
| 338 | 4.0625 | 4 |
#practice for loop
# ask user a number like 1235
# calculate sum of digits ---->1+2+3+4
#l#"1256"---->logic
#num = "!@56", length = 4
#int (num[0])--->1
#int(num[1])---->2
#int(num[2])---->3
#(num[3])---->6
#i--->o to 3
total = 0
num = input("enter the number:")
for i in range(0, len(num)):
total += int(num[i])
print(total)
|
9c018be438320dad66c1cda5bd2c46312225402b
|
NUsav77/Python-Exercises
|
/Crash Course/Chapter 6 - Dictionaries/6.2_favorite_number.py
| 556 | 4.28125 | 4 |
'''Use a dictionary to store people's favorite numbers. Think of five names, and use them as keys in oyur dictionary.
Think of a favorite number for each person, and store each as value in your dictionary. Print each person's name and
their favorite number. For even more fun, poll a few friends and get some actual data for your program. '''
favorite_numbers = {
'steven': 77,
'pa': 1986,
'evolet': 330,
'lorelei': 58,
'dan': 55,
}
[print(f"{name.title()}'s favorite number is {number}") for name, number in favorite_numbers.items()]
|
a96c376d2eca98dab4979f1f60251bdd5f697bc8
|
tddontje/wordsearch
|
/WordSearch.py
| 16,805 | 4.09375 | 4 |
"""
WordSearch - This program searches a given grid of letters for words contained
in a given dictionary file.
* The grid of letters will be randomly generated.
* The search for words have the following constraints:
* Words will be search forwards, backwards, up, down and diaganol
* Words will not be tested for wrapping of the edge of grid
* Dictionary will be given as a file (defaulting to words.txt)
"""
import unittest
import os.path
import argparse
import string
import random
class WordSearch():
"""
WordSearch:
__init__ : setup object with defined grid
find_words : find words in grid that matches dictionary
"""
def __init__(self, dict_file: str, xsize: int = 15, ysize: int = 15):
"""
Setup WordSearch object
* initialize random grid using xsize and ysize values
* load dictionary file to be used in word search
:param dict_file: Filename of dictionary to load
:param xsize: X-axis size of word grid
:param ysize: Y-axis size of word grid
"""
print("initializing WordSearch")
self.xsize = xsize
self.ysize = ysize
self.words_dictionary = self._load_dictionary(dict_file)
self.letter_grid = self._generate_grid()
self.found_words = set()
def _load_dictionary(self, dict_file: str) -> list:
"""
Load dictionary from file and order by length
:param dict_file: Filename of dictionary to load
:return: list of dictionary words in size order
:exceptions: if dictionary contains no words
"""
words_dictionary = list()
# load dictionary from file
with open(dict_file, 'rt') as dictionary:
words_dictionary = [word.split('\n')[0] for word in dictionary]
# check for no entries in dictionary
if len(words_dictionary) == 0:
message = "No words in dictionary, need to specify a dictionary with at least 1 word."
raise ValueError(message)
else:
print("loaded {} words in dictionary".format(len(words_dictionary)))
# return sorted dictionary from shortest words to longest
return sorted(words_dictionary, key=len)
def _generate_grid(self):
"""
Generate a random grid of letters to be searched based on object's xsize and ysize
:return: 2d list of lists containing the grid of letters
"""
letter_grid = [[random.choice(string.ascii_lowercase) for i in range(self.xsize)] for j in range(self.ysize)]
return letter_grid
def find_words(self) -> set:
"""
Find words in grid.
Using the grid of letter we will search the grid horizontally and diagonally forwards
and backwards. Since we are not worried about finding the exact location we can search
for words based on a full slice instead of trying to searching through each position.
:return:
"""
# generate comparison string lists from grid
print('generating grid comparision string list')
comp_strings = list()
comp_strings.extend(self._get_horizontal_str())
comp_strings.extend(self._get_vertical_str())
comp_strings.extend(self._get_diagonal_str())
# find all dictionary words that occur in the comp_strings
print('searching for words in comparison string list')
for word_to_cmp in self.words_dictionary:
if any(word_to_cmp in curr_string for curr_string in comp_strings):
self.found_words.add(word_to_cmp)
return self.found_words
# Search methods.
def _get_horizontal_str(self)->list:
"""
get strings for horizontal comparisons
:return: string_list of all horizontal strings forward and backward
"""
string_list = list()
for char_list in self.letter_grid:
curr_string = ''.join(char_list)
string_list.append(curr_string)
bwd_string = ''.join(reversed(curr_string))
string_list.append(bwd_string)
return string_list
def _get_vertical_str(self)->list:
"""
get strings for vertical comparisons
Currently
:return: string_list of all vertical strings forward and backward
"""
string_list = list()
for curr_x in range(self.xsize):
char_list = [self.letter_grid[y][curr_x] for y in range(self.ysize)]
curr_string = ''.join(char_list)
string_list.append(curr_string)
bwd_string = ''.join(reversed(curr_string))
string_list.append(bwd_string)
return string_list
def _get_diagonal_str(self)->list:
"""
get strings for diagonal comparisons
- Currently only getting diagonals that start at the top row
:return: string_list of all diagonal strings to the right and left, forward and backward
"""
string_list = list()
# get diagonal from top row going to the right and then left
for curr_x in range(self.xsize):
d_upper_right = [self.letter_grid[inc][curr_x + inc] for inc in range(self.xsize - curr_x)]
curr_string = ''.join(d_upper_right)
string_list.append(curr_string)
bwd_string = ''.join(reversed(curr_string))
string_list.append(bwd_string)
d_upper_left = [self.letter_grid[inc][(self.xsize - 1 - curr_x) - inc] for inc in range(self.xsize - curr_x)]
curr_string = ''.join(d_upper_left)
string_list.append(curr_string)
bwd_string = ''.join(reversed(curr_string))
string_list.append(bwd_string)
return string_list
def check_axis(arg):
try:
value = int(arg)
except ValueError as err:
raise argparse.ArgumentTypeError(str(err))
if value <= 0:
message = "Expected value > 0, got value = {}".format(value)
raise argparse.ArgumentTypeError(message)
return value
def check_file(arg):
try:
value = str(arg)
except ValueError as err:
raise argparse.ArgumentTypeError(str(err))
if not os.path.isfile(value):
message = "Could not find dictionary file {}".format(value)
raise argparse.ArgumentTypeError(message)
return value
def main():
parser = argparse.ArgumentParser('WordSearch a randomly generated grid')
parser.add_argument('--xsize', dest='xsize', default=15, type=check_axis,
help='X-Axis size')
parser.add_argument('--ysize', dest='ysize', default=15, type=check_axis,
help='Y-Axis size')
parser.add_argument('--dictionary', dest='dict_file', default='words.txt', type=check_file,
help='dictionary filename')
args = parser.parse_args()
print("Xsize={}, Ysize={}, Dictionary={}".format(args.xsize, args.ysize, args.dict_file))
grid = WordSearch(args.dict_file, args.xsize, args.ysize)
found = grid.find_words()
print("found following {} words:".format(len(found)))
print(found)
if __name__ == '__main__':
main()
class TestWordSearch(unittest.TestCase):
def test_create_with_no_words(self):
"""
Test for object creation with dictionary of no words.
"""
# verify the right exception is done
self.assertRaises(ValueError, WordSearch, "nowords.txt")
def test_create_default_grid(self):
"""
Test for object creation using defaults
"""
grid = WordSearch("words.txt")
# verify dictionary is set
self.assertTrue(len(grid.words_dictionary) > 0)
# verify x-axis length
self.assertTrue(len(grid.letter_grid) == 15)
# verify y-axis length
self.assertTrue(len(grid.letter_grid[0]) == 15)
def test_create_1x100_grid(self):
"""
Test for object creation of a grid that is 1 row and 100 chars
"""
grid = WordSearch("words.txt", 1, 100)
# verify dictionary is set
self.assertTrue(len(grid.words_dictionary) > 0)
# verify x-axis length
self.assertTrue(len(grid.letter_grid) == 100)
# verify y-axis length
self.assertTrue(len(grid.letter_grid[0]) == 1)
def test_create_100x1_grid(self):
"""
Test for object creation of a grid that is 100 rows and 1 char
"""
grid = WordSearch("words.txt", 100, 1)
# verify dictionary is set
self.assertTrue(len(grid.words_dictionary) > 0)
# verify x-axis length
self.assertTrue(len(grid.letter_grid) == 1)
# verify y-axis length
self.assertTrue(len(grid.letter_grid[0]) == 100)
def test_create_100x100_grid(self):
"""
Test for object creation of a grid that is 100 rows and 100 chars
"""
grid = WordSearch("words.txt", 100, 100)
# verify dictionary is set
self.assertTrue(len(grid.words_dictionary) > 0)
# verify x-axis length
self.assertTrue(len(grid.letter_grid) == 100)
# verify y-axis length
self.assertTrue(len(grid.letter_grid[0]) == 100)
def test__get_horizontal_str(self):
"""
Test that the string_list returned is of the right value.
We force the grid to be a numeral string and then validate that the
returned list looks correct.
"""
input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)]
expect_strings = ['abcdefghi',
'ihgfedcba',
'abcdefghi',
'ihgfedcba'
]
grid = WordSearch("words.txt", 9, 9)
grid.letter_grid = input_grid
actual_strings = grid._get_horizontal_str()
print(actual_strings)
print("---")
print(expect_strings)
self.assertTrue(actual_strings[0] == expect_strings[0])
self.assertTrue(actual_strings[1] == expect_strings[1])
self.assertTrue(actual_strings[16] == expect_strings[2])
self.assertTrue(actual_strings[17] == expect_strings[3])
def test__get_vertical_str(self):
"""
Test that the string_list returned is of the right value.
We force the grid to be a numeral string and then validate that the
returned list looks correct.
"""
input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)]
expect_strings = ['aaaaaaaaa',
'aaaaaaaaa',
'iiiiiiiii',
'iiiiiiiii'
]
grid = WordSearch("words.txt", 9, 9)
grid.letter_grid = input_grid
actual_strings = grid._get_vertical_str()
print(actual_strings)
print("---")
print(expect_strings)
self.assertTrue(actual_strings[0] == expect_strings[0])
self.assertTrue(actual_strings[1] == expect_strings[1])
self.assertTrue(actual_strings[16] == expect_strings[2])
self.assertTrue(actual_strings[17] == expect_strings[3])
def test__get_diagonal_str(self):
"""
Test that the string_list returned is of the right value.
We force the grid to be a numeral string and then validate that the
returned list looks correct.
"""
input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)]
expect_strings = ['abcdefghi', # upper left to lower right
'ihgfedcba', # ul2lr backwards
'ihgfedcba', # upper right to lower left
'abcdefghi', # ul2lr backwards
'bcdefghi', # upper left to lower right (shift by one)
'ihgfedcb', # ul2lr backwards
'hgfedcba', # upper right to lower left (shift by one)
'abcdefgh', # ul2lr backwards
'i', # upper left last character
'i', # upper left last character backwards
'a', # upper right last character
'a' # upper right last character backwards
]
grid = WordSearch("words.txt", 9, 9)
grid.letter_grid = input_grid
actual_strings = grid._get_diagonal_str()
print(actual_strings)
print("---")
print(expect_strings)
self.assertTrue(actual_strings[0] == expect_strings[0])
self.assertTrue(actual_strings[1] == expect_strings[1])
self.assertTrue(actual_strings[2] == expect_strings[2])
self.assertTrue(actual_strings[3] == expect_strings[3])
self.assertTrue(actual_strings[4] == expect_strings[4])
self.assertTrue(actual_strings[5] == expect_strings[5])
self.assertTrue(actual_strings[6] == expect_strings[6])
self.assertTrue(actual_strings[7] == expect_strings[7])
self.assertTrue(actual_strings[32] == expect_strings[8])
self.assertTrue(actual_strings[33] == expect_strings[9])
self.assertTrue(actual_strings[34] == expect_strings[10])
self.assertTrue(actual_strings[35] == expect_strings[11])
def test_search_horizontal_fwd(self):
"""
Test searching grid horizontal forward
Checking the following conditions:
1. word at start
2. word in middle
3. word at end
4. word non-existant
"""
input_grid = [['a','b','a','t','e','f','g','h','i'],
['a', 'b', 'c', 'c', 'a', 'n', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'i', 'r', 'e', 'c', 't'],
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']]
expected_words = {'can', 'abate', 'direct'}
grid = WordSearch("testwords.txt", 9, 9)
grid.letter_grid = input_grid
actual_words = grid.find_words()
self.assertTrue(len(expected_words) == len(actual_words))
def test_search_vertical_fwd(self):
"""
Test searching grid vertical forward
Checking the following conditions:
1. word at top
2. word in middle
3. word at end
4. word non-existant
"""
input_grid = [['c','b','a','t','e','f','g','h','i'],
['o', 'b', 'c', 'c', 'a', 'n', 'g', 'h', 'i'],
['m', 'b', 'c', 'p', 'e', 'f', 'g', 'h', 'i'],
['p', 'b', 'c', 'y', 'e', 'f', 'g', 'a', 'i'],
['u', 'b', 'c', 't', 'e', 'f', 'g', 'b', 'i'],
['t', 'b', 'c', 'h', 'e', 'f', 'g', 'a', 'i'],
['e', 'b', 'c', 'o', 'c', 'f', 'g', 't', 'i'],
['r', 'b', 'c', 'n', 'a', 'r', 'e', 'e', 't'],
['a', 'b', 'c', 'd', 'n', 'f', 'g', 'h', 'i']]
expected_words = {'can', 'abate', 'computer', 'python'}
grid = WordSearch("testwords.txt", 9, 9)
grid.letter_grid = input_grid
actual_words = grid.find_words()
self.assertTrue(len(expected_words) == len(actual_words))
def test_search_diagonal_fwd(self):
"""
Test searching grid diagonal forward
Checking the following conditions:
1. word at start
2. word in middle
3. word at end
4. word non-existant
"""
input_grid = [['d','b','a','t','e','f','g','h','n'],
['a', 'i', 'c', 'c', 'a', 'n', 'g', 'a', 'i'],
['a', 'b', 'r', 'd', 'e', 'f', 'c', 'h', 'i'],
['a', 'b', 'c', 'e', 'e', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'c', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'e', 't', 'g', 'h', 'i'],
['a', 'b', 'c', 'd', 'a', 'f', 'g', 'h', 'i'],
['a', 'b', 'c', 'b', 'i', 'r', 'e', 'c', 't'],
['a', 'b', 'a', 'd', 'e', 'f', 'g', 'h', 'i']]
expected_words = {'can', 'direct'}
grid = WordSearch("testwords.txt", 9, 9)
grid.letter_grid = input_grid
actual_words = grid.find_words()
self.assertTrue(len(expected_words) == len(actual_words))
|
47fc4f4b36fcc11ea1942cf15de878673f462ca0
|
LONEZAD/Flappy-Bird
|
/src/game/game_objects/rigid_body.py
| 537 | 3.5625 | 4 |
from abc import ABC, abstractmethod
from src.game.game_objects.move_able_game_object import MoveAbleGameObject
class RectangleRigidBody(MoveAbleGameObject, ABC):
@property
@abstractmethod
def size(self) -> [float, float]:
"""Should return the width, height"""
class CircularRigidBody(MoveAbleGameObject, ABC):
def __init__(self):
super().__init__()
self._set_image("images/circle_default.png")
@property
@abstractmethod
def radius(self) -> float:
"""Should return the """
|
9de1cd2891e67cd9b0fd7d2c52b6f04f8542b943
|
dkruchinin/problems
|
/projecteuler/problem26/problem26.py
| 620 | 3.796875 | 4 |
#!/usr/bin/env python3
def find_cycle(num):
rems = []
div = 1
rem = 0
while True:
rem = div % num
if rem == 0:
return 0
if rem in rems:
return len(rems) - rems.index(rem)
rems.append(rem)
div *= 10
def main():
longest_cycle = 0
result = -1
for i in range(1, 1001):
cycle_len = find_cycle(i)
if cycle_len > longest_cycle:
longest_cycle = cycle_len
result = i
print("%d gives longest cycle, length %d" %
(result, longest_cycle))
if __name__ == '__main__':
main()
|
aefe702bc325381855e4040ec69fc6195b2dd69d
|
slavo3dev/python_100_exercises
|
/88.py
| 364 | 3.875 | 4 |
'''
Create a script that uses the attached countries_by_area.txt
file as data source and prints out the top 5 most densely populated countries.
'''
import pandas as pd
f = pd.read_csv('88.txt')
f["density"] = f["population_2013"] / f["area_sqkm"]
f = f.sort_values(by='density',ascending=False )
for index, row in f[:5].iterrows():
print(row["country"])
|
7136b1cd615f1a661b630d11c6e93c44b6c6f76d
|
iftrush/CLRS
|
/CH10/SimplifiedQueue.py
| 1,620 | 3.921875 | 4 |
# ERROR
class Empty(Exception): pass
class Full(Exception): pass
# QUEUE
class Queue:
# CONSTRUCTOR
def __init__(self, capacity = 100, head = -1, tail = 0):
self.head = head
self.tail = tail
self.capacity = capacity
self.Q = [None] * capacity
self.size = 0
# METHOD OVERRIDING
def __len__(self):
return len(self.Q)
# METHOD OVERRIDING
def __str__(self):
return str(self.Q)
# QUEUE-EMPTY
def isEmpty(self):
return True if self.head == -1 else False
# QUEUE-FULL
def isFull(self):
return True if self.head == (self.tail + 1) % self.capacity else False
# ENQUEUE
def enqueue(self, x):
if self.isFull(): raise Full("Queue Overflow")
else:
if self.head == -1:
self.head = 0
elif self.tail == self.capacity:
self.tail = 0
else:
self.tail += 1
self.Q[self.tail] = x
# DEQUEUE
def dequeue(self):
if self.isEmpty(): raise Empty("Queue Underflow")
else:
x = self.Q[self.head]
if self.head == self.tail:
self.head = -1
else:
if self.head == self.capacity-1:
self.head = 0
else:
self.head += 1
return x
# DRIVER
A = Queue()
B = Queue()
for i in range(100):
A.enqueue(i)
print(A)
for i in range(len(A)):
B.enqueue(A.dequeue())
print(B)
|
932667d5ef371b19f86103b5361f66b177926140
|
bsarden/461l-final-project
|
/backend/flask/src/application/models/UserModel.py
| 1,135 | 3.5625 | 4 |
from google.appengine.api import users
from google.appengine.ext import ndb
"""
The UserModel serves as a the database representation for what we want a User
object to be able to store. We have built this User object off of the google
user login so that a user can log in with their google account. The User object
will include:
trips - a list of Trip objects that are associated with the User
distance - the maximum distance that we can search off of a route for
isLeader - whether or not the User is the leader of a caravan
"""
from TripModel import TripModel
from BaseModel import *
# Information on how to create the oneToMany Relationship was taken from here:
# http://stackoverflow.com/questions/10077300/one-to-many-example-in-ndb
# Information on how to create the manyToMany Relationship was taken from here:
# http://stackoverflow.com/questions/24392270/many-to-many-relationship-in-ndb
class User(BaseModel):
email = ndb.StringProperty(default="[email protected]")
trip_ids = ndb.KeyProperty(kind='TripModel', repeated=True)
distance = ndb.FloatProperty(default=5.0)
isleader = ndb.BooleanProperty(default=True)
|
c7ad9302e6889a3ac917dcdc443c812eb159ad57
|
weverson23/ifpi-ads-algoritmos2020
|
/Atividade_Semana_08_e_09/uri_1175.py
| 320 | 3.875 | 4 |
def main():
vet1 = []
vet2 = []
i = 0
# entrada dos valores
for i in range(20):
vet1.append(int(input()))
# armazena os valores de vet1 em vet2 de forma inversa
vet2 = vet1[::-1]
# saída
for i in range(20):
print('N[{}] = {}'.format(i,vet2[i]))
main()
|
7dc6dbcaa857e311abcbaa042c80ad855a8ab073
|
shuvro-baset/Assignment
|
/assignment_4/task13.py
| 178 | 3.84375 | 4 |
dict = {'A': [1,2,3], 'b': ['1', '2'], "c": [4, 5, 6, 7]}
total = 0
for value in dict:
value_list = dict[value]
count = len(value_list)
total += count
print(total)
|
532eea4a81fa3151ea92a0f3f00d9b0dc71bccb4
|
PedroSantana2/curso-python-canal-curso-em-video
|
/mundo-1/ex008.py
| 379 | 4.15625 | 4 |
'''
Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
'''
#Recebendo valores:
metros = float(input('Digite o valor em metros: '))
#Declarando variaveis
centimetros = metros * 100
milimetros = metros * 1000
#Informando resultado:
print('{} metros é: \n{} centímetros\n{} milímetros'.format(metros, centimetros, milimetros))
|
33bfb3ee57406338e323555da6474fc826c6eaee
|
bhishan/LinuxPasswordCracker
|
/linux_pwd_cracker.py
| 1,537 | 3.625 | 4 |
import crypt
import sys
def crack_pwd(user, pwd_dictionary, shadow_file):
"""Tries to authenticate a user.
Returns True if the authentication succeeds, else the reason
(string) is returned."""
is_user_available = False
encrypted_pwd = ''
with open(shadow_file, 'rb') as f:
for each_line in f:
each_line = each_line.replace('\n', '')
if user in each_line:
is_user_available = True
encrypted_pwd = each_line.split(':')[1]
break
if not is_user_available:
print "No user found with username", user
sys.exit(1)
if encrypted_pwd in ["NP", "!", "", None]:
print "User", user, "has no password"
sys.exit(1)
if encrypted_pwd in ["LK", "*"]:
print "Account is locked"
sys.exit(1)
if encrypted_pwd == "!!":
print "Password has expired"
sys.exit(1)
with open(pwd_dictionary, 'rb') as f:
for each_pass in f:
each_pass = each_pass.replace('\n', '')
if crypt.crypt(each_pass, encrypted_pwd) == encrypted_pwd:
print "Password found: ", each_pass
sys.exit(1)
print "Password not found"
if __name__ == "__main__":
username = raw_input("Username: ")
pwd_dictionary = raw_input("Password dictionary file path: ")
shadow_file = raw_input("Linux password file path(hint /etc/shadow) : ") #pass /etc/shadow
crack_pwd(username, pwd_dictionary, shadow_file)
|
49ade560335982f3655e76e33a6e13c634aee710
|
daniel-reich/turbo-robot
|
/Mm8SK7DCvzissCF2s_23.py
| 724 | 4.09375 | 4 |
"""
Create a function that takes a string and returns `True` if the sum of the
position of every letter in the alphabet is even and `False` if the sum is
odd.
### Examples
is_alpha("i'am king") ➞ True
# 9 + 1 + 13 + 11 + 9 + 14 + 7 = 64 (even)
is_alpha("True") ➞ True
# 20 + 18 + 21 + 5= 64 (even)
is_alpha("alexa") ➞ False
# 1 + 12 + 5 + 24 + 1= 43 (odd)
### Notes
* Case insensitive.
* Ignore non-letter symbols.
"""
import string
def in_alpha(word):
nums = list(enumerate(string.ascii_lowercase, 1))
letters = [i.lower() for i in word if i.isalpha()]
summ = 0
for i in letters:
for a, b in nums:
if b == i:
summ += a
return not summ % 2
|
c75f52f2bfb1ef9d4a73618a1ee0b0e2e383b3f9
|
HusanYariyev/Python_darslari
|
/51-masala.py
| 537 | 3.578125 | 4 |
# SyntaxError
# print("Hello Word"
#IndentationError
#for i in range(10):
#print(i)
#NameError
#try:
# ism = "Husan"
# print(ims)
#except NameError:
# print("Xato -> NameError")
#ValueError
#try:
# x = 1.3
# int(x)
#except:
# print("Xato -> ValouError"
a = 0
try:
a = 0
ism = input("Ismingizni kiriting ")
print("Salom ", imm)
except:
a +=1
print("Xato")
finally:
if a == 0 :
print("Dasturda xatolik yo`q")
else:
print("Dasturda xatolik bor")
|
140f7e0ef9668b868aacb9bfec5a6ab2343e286a
|
ifaniwahida/1810530234-ujian-abj
|
/interfaces.py
| 673 | 3.5 | 4 |
ulang = "ya"
while ulang == "ya":
pilih = input("Input data Trunk Interface baru [yes/no]?: ")
if pilih == "yes":
hostname = input("Masukkan Hostname Switch: ")
hostname = input("Masukkan Nama Interface: ")
file = open("db-interface.txt", 'a')
file.write("\n" +interface)
else:
file = open("db-interface.txt", 'r')
print(file.read())
break;
x = hostname[Hostname Switch]
y = hostname[Interface]
#print(x)
if isinstance(x, str):
print("hostname = "+ kelas +" ("+ x +")")
else:
print("Class IP = "+ kelas +" ("+ x['NetID'] +" bit NetID, " + x['HostID'] +" bit HostID)")
|
f4d7aba73990519ab1ca0b1025197965906ab5fb
|
julianfrancor/holbertonschool-higher_level_programming
|
/0x0F-python-object_relational_mapping/2-my_filter_states.py
| 1,442 | 3.5 | 4 |
#!/usr/bin/python3
"""
script that takes in an argument and displays all values in the states
table of hbtn_0e_0_usa where name matches the argument.
"""
import MySQLdb
import sys
def connect_to_database():
"""Function that reads arguments from stdout
and creates a connection to the MySQL server
running on the local machine via a
UNIX socket(host and port) (or named pipe),
the user name = args[1], password = args[2],
and selects the database args[3].
Function that gets the arguments form stdout
Return: db object
"""
args = sys.argv
host = "localhost"
port = 3306
user = args[1]
password = args[2]
database = args[3]
matching_argument = args[4]
db = MySQLdb.connect(host=host, port=port, passwd=password,
user=user, db=database)
return db, matching_argument
def query_select(db, matching_argument):
"""Selects all the row from the database and sorts them
in ascending order by states.id and displays them"""
db.query("""SELECT * FROM states WHERE name REGEXP '{}'
ORDER BY id ASC""".format(matching_argument))
result = db.store_result()
for row in result.fetch_row(0):
if row[1] == matching_argument:
print(row)
if __name__ == "__main__":
db, matching_argument = connect_to_database()
query_select(db, matching_argument)
db.close()
|
e5fad15c2e5df03c05baecc6f55aaa64e4dd353d
|
BhagyashreeKarale/loop
|
/36outputques3.py
| 373 | 3.921875 | 4 |
#Niche diye gye code snippet ki output kya hoga?
# i = 2
# while (i<num):
# if (num%i == 0):
# print(num, 'is not a prime number')
# break
# i = i + 1
# else:
# print(num, 'is a prime number')
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<OUTPUT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>#
#NameError as name 'num' is not defined
|
7d52c7e3a65dc9be6125b6f25ca6ae7ffe5c7127
|
mhee4321/python_algorithm
|
/programmers/Level1/getRidOfMinimumNumber.py
| 439 | 3.515625 | 4 |
# 시간초과
def solution(arr):
result = []
for num in arr:
if num == min(arr):
continue
else:
result.append(num)
if not result:
result.append(-1)
return result
def solution2(arr):
answer = []
minVal = min(arr)
arr.remove(minVal)
# arr이 빈배열이라면
if not arr:
arr.insert(0,-1)
return arr
arr = [4, 3, 2, 1]
print(solution(arr))
|
b43696ac3b6bb621de506916f8d6c86287ee8d1c
|
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
|
/students/sbolsen/lesson03/mailroom.py
| 2,193 | 3.921875 | 4 |
#!/usr/bin/env python3
donors = [
['Jesse Johnson', [150, 345]],
['Mary May', [1000, 750]],
['Spencer Samuels', [50, 200, 1100]],
['Zach Zillow', [85]],
['Tina Thompson', [76, 250, 300]]
]
def donor_list():
for donor in donors:
print(donor[0])
def prompt_user():
choice = input('Please select from the following: \n1) Send a Thank You \n2) Create a Report \n3) Quit\n')
return choice
def thank_you():
select_user = input('Enter a full name: ')
if select_user == 'list':
donor_list()
select_user = input('Enter a full name: ')
return select_user
def user(select_user):
user_exists = False
for item in donors:
for donor in item:
if select_user == donor:
user_exists = True
if user_exists:
pass
else:
donors.append([select_user, []])
update_donation = int(input('Please enter donation: '))
for donor in donors:
donations = False
for i in donor:
if not donations:
donations = True
continue
else:
if select_user in donor:
i.append(update_donation)
print('Thank you {} for your thoughtful donation of ${}.'.format(select_user, update_donation))
def create_report():
title = ('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')
print('{:20} | {:>17} | {:>17} | {:>17}'.format(*title))
print('{:-<80}'.format(''))
for donor in donors:
a = sum(donor[1])
b = len(donor[1])
total = a // b
print('{:20} $ {:>17} $ {:>17} $ {:>17}'.format(donor[0], a, b, total))
def main():
while True:
try:
users_choice = prompt_user()
if users_choice == '1':
thanked_user = thank_you()
user(thanked_user)
elif users_choice == '2':
create_report()
prompt_user()
elif users_choice == '3':
quit()
else:
prompt_user()
except Exception as e:
print("Exception [{}]".format(e))
if __name__ == "__main__":
main()
|
0fd79481e17cdd2f3d45bbfb38c9ff6127cd4522
|
whugue/dsp
|
/math/matrix_algebra.py
| 1,629 | 4.09375 | 4 |
# Matrix Algebra
##Define Matrices as listed in exercises using NumPy
import numpy
A=numpy.matrix([[1,2,3],[2,7,4]])
B=numpy.matrix([[1,-1],[0,1]])
C=numpy.matrix([[5,-1],[9,1],[6,0]])
D=numpy.matrix([[3,-2,-1],[1,2,3]])
u=numpy.array([6,2,-3,5])
v=numpy.array([3,5,-1,4])
w=numpy.matrix([[1],[8],[0],[5]])
##Part 1: Matrix Dimentions
print "Dimention of A:", A.shape #Dimention of A: (2,3)
print "Dimention of B:", B.shape #Dimention of B: (2,2)
print "Dimention of C:", C.shape #Dimention of C: (3,2)
print "Dimention of D:", D.shape #Dimention of D: (2,3)
print "Dimention of u:", u.shape #Dimention of u: (4,) (aka 1,4 if was written as matrix not array) :)
print "Dimention of w:", w.shape #Dimention of w: (4,1) :)
##Part 2: Vector Operations
print u+v #[9,7,-4,9]
print u-v #[3,-3,-2,1]
print 6*u #[36,12,-18,30]
print numpy.dot(u,v) #51
print numpy.linalg.norm(u)**2 #74 (so norm is sqrt(74))
##Part 3: Matrix Operations
print A+C #Not defined (ValueError: operands could not be broadcast together with shapes (2,3) (3,2))
print A-(numpy.matrix.transpose(C)) #[[-4 -7 -3], [ 3 6 4]]
print (numpy.matrix.transpose(C))+(3*D) #[[14 3 3], [ 2 7 9]]
print B*A #[[-1 -5 -1], [ 2 7 4]]
print B*(numpy.matrix.transpose(A)) #Not defined (ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0))
print B*C #Not defined (ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0))
print C*B #[[ 5 -6], [ 9 -8], [ 6 -6]]
print B**4 #[[ 1 -4], [ 0 1]]
print A*(numpy.matrix.transpose(A)) #[[14 28], [28 69]]
print (numpy.matrix.transpose(D))*D #[[10 -4 0], [-4 8 8], [ 0 8 10]]
|
c5bb9ea670baa09b05f893b7801e0155086a03ec
|
davnav/crackingthecodinginterview
|
/chapter4/treebasics.py
| 1,082 | 4.0625 | 4 |
#Basic Tree operations will be implemented here.datetime A combination of a date and a time.
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def create_node(element):
return Node(element)
class BinaryTree:
def __init__(self,root):
self.root = root
# @classmethod
def create(self):
current = self.root
while current.left != None:
current = current.left
e1 = input("input a value for the Tree:")
current.left = create_node(e1)
current = self.root
while current.right != None:
current = current.right
e2 = input("input a value for the Tree:")
current.right = create_node(e2)
root = Node(18)
tree = BinaryTree(root)
tree.create()
print(tree.root.value)
print(tree.root.left.value)
print(tree.root.right.value)
tree.create()
# print(tree.root.value)
print(tree.root.left.left.value)
print(tree.root.right.right.value)
|
8a5ac1c92b5c4a54d6ce0ddeea7388d0f1edf84b
|
ShunKaiZhang/LeetCode
|
/delete_operation_for_two_strings.py
| 966 | 3.84375 | 4 |
# python3
# Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same,
# where in each step you can delete one character in either string.
# Example 1:
# Input: "sea", "eat"
# Output: 2
# Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
# Note:
# The length of given words won't exceed 500.
# Characters in given words can only be lower-case letters.
# My solution
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
dp = [[0 for j in range(len(word1) + 1)] for i in range(len(word2) + 1)]
for i in range(len(word2)):
for j in range(len(word1)):
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i][j] + (word1[j] == word2[i]), dp[i + 1][j])
return len(word1) + len(word2) - 2 * dp[-1][-1]
|
39d77acc49eaab734efc9ef85fcc299de5caefb5
|
hossamasaad/Console-Projects
|
/Time Calculator/time_calculator.py
| 2,026 | 3.921875 | 4 |
def add_time(start, duration, day = None):
# get Current time period and update the start string
p = start[-2:]
start = start[:-3]
# split time
start_hour, start_minute = splitTime(start)
hour, minute = splitTime(duration)
# if p = 'PM' add 12
if p == 'PM':
start_hour += 12
# add duration
total_hour = start_hour + hour
total_minute = start_minute + minute
if total_minute > 59:
total_hour += 1
total_minute -= 60
# calaculate no of days
no_of_days = total_hour // 24
total_hour = total_hour % 24
# calculate 'PM' or 'AM'
new_p = ""
if total_hour >= 12:
new_p = 'PM'
if total_hour > 12:
total_hour -= 12
else:
if total_hour == 0:
total_hour = 12
new_p = 'AM'
# minute format
if total_minute < 10:
total_minute = '0' + str(total_minute)
else:
total_minute = str(total_minute)
# new time format
new_time = str(total_hour) + ':' + total_minute + ' ' + new_p
if no_of_days == 0:
if day != None:
new_time += ', ' + day
else:
if day != None:
day = getDay(day, no_of_days)
new_time += ', ' + day
if no_of_days == 1:
new_time += ' (next day)'
else:
new_time += ' (' + str(no_of_days) + ' days later)'
return new_time
def splitTime(s):
h = ""
m = ""
state = False
for char in s:
if char == ":":
state = True
else:
if state is False:
h += char
else:
m += char
return int(h), int(m)
def getDay(day, no_of_days):
days = ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
day_n = {'wednesday':0, 'thursday':1, 'friday':2,
'saturday':3, 'sunday':4, 'monday':5, 'tuesday':6}
no = (day_n[day.lower()] + no_of_days ) % 7
return days[no]
|
143534d4a9b255a6468fe029c030a3a7424bca7f
|
DingGuodong/LinuxBashShellScriptForOps
|
/functions/net/tcp/port/checkRemoteHostPortStatus.py
| 1,856 | 3.765625 | 4 |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
import socket
import sys
# import os
import time
host = ""
port = 0
timeout = 3
retry = 3
def usage():
print("""
Function: check remote host's tcp port if is open
Usage: %s <host ipaddress> <tcp port>
Example: python %s 127.0.0.1 22
Others useful cli:
strace time:
strace -q -f -c python checkRemoteHostPortStatus.py 127.0.0.1 22
Bash shell implement:
nc -w 3 127.0.0.1 22 >/dev/null 2>&1 && echo ok || echo failed
nmap 127.0.0.1 -p 22 | grep open >/dev/null 2>&1 && echo ok || echo failed
""") % (__file__, sys.argv[0])
sys.exit(0)
argc = len(sys.argv)
if not (argc == 1 or argc == 3):
print("Error: incorrect number of arguments or unrecognized option")
usage()
if argc == 1:
pass
else:
if sys.argv[1] is not None:
host = sys.argv[1]
if sys.argv[2] is not None:
try:
port = int(sys.argv[2])
except ValueError:
pass
while True:
if host == "":
print "host is empty, please sign new one."
host = raw_input("HOST: ")
elif port == 0 or not isinstance(port, int):
print "port is empty or illegal, please sign new one."
try:
port = int(raw_input("PORT: "))
except ValueError:
pass
else:
break
print "checking server %s port %s status." % (host, port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
for attempt in range(0, retry):
try:
s.connect((str(host), int(port)))
print "connect to server %s port %s successfully!" % (host, port)
break
except Exception as e:
print "connect to server %s port %s failed in %s times! " % (host, port, attempt + 1)
# os.system("sleep 1")
time.sleep(1)
s.close()
|
bbfb4018d61fc3ff379e84021927c2cdff1ec316
|
learndevops19/pythonTraining-CalsoftInc
|
/training_assignments/Day_01/Nitesh_Mahajan/data_types_7.py
| 670 | 4.3125 | 4 |
#!usr/bin/env python
def replace_last_value(input_list):
"""
This function replaces last value of tuples in a list by 100
Args: input_list
Returns: output_list
"""
output_list = []
for tup in input_list:
new_list = list(tup[:-1]) # Convert each tuple into a list leaving last element
new_list.append(100) # Appends 100 to each new_list
new_tup = tuple(new_list) # Again type cast from list to tuple
output_list.append(new_tup) # Appends each new_tup in the output_list
return output_list
input_list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
output = replace_last_value(input_list)
print(output)
|
fa0c2e4b2cc6558b624b4bf4b9fd334fbe875bab
|
floydchenchen/leetcode
|
/977-squares-of-a-sorted-array.py
| 774 | 3.75 | 4 |
# 977. Squares of a Sorted Array
# Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
# Example 1:
# Input: [-4,-1,0,3,10]
# Output: [0,1,9,16,100]
# Example 2:
# Input: [-7,-3,2,3,11]
# Output: [4,9,9,49,121]
class Solution:
# two pointers, following negative and non-negative numbers
def sortedSquares(self, A: List[int]) -> List[int]:
result = []
l, r = 0, len(A) - 1
while l <= r:
left, right = abs(A[l]), abs(A[r])
if left > right:
result.insert(0, left * left)
l += 1
else:
result.insert(0, right * right)
r -= 1
return result
|
6c9883cf8eb874e01cb03dc4ec0a566c5f6d79ec
|
SSJohns/klustering-using-nn
|
/src/kmeans.py
| 4,181 | 3.5 | 4 |
#Ben Gunning
#Assignment 2
#Professor Wang
import fileinput
import json
import ast
"""
*Need to take tweets as inputs into an array
*Need to splice tweets into an array of words
*Need to take each tweet and find Jaccard Distance to centroids; Find minimum and add to cluster
*Need to recompute cluster centroids
*Repeat process until centroids are stable
"""
tweetTxt = open('../data/paris_shooting.txt' , 'r') # Tweet input text
tweetsIn = [] # Very raw input of tweets given in the input text
tweetSpl = [] # Dictionary of tweets, each of which is associated with an id number and a list of words (strings)
for line in tweetTxt:
line = ast.literal_eval(line)
line = json.dumps(line)
tweetsIn.append(json.loads(line))
tweetTxt.close()
vals = set()
for tweet in tweetsIn:
id = tweet["id"]
words = []
for word in tweet["text"].split():
words.append(word)
tweetSpl.append({'id': id , 'words': words}) # Define each tweet as it will be stored in tweetSpl dictionary
vals.add(id)
vals = list(vals)
import random
from datetime import datetime
random.seed(datetime.now())
print(len(vals))
with open('../data/parisinit.txt' , 'w') as centerTxt:# Text file containing IDs of initial selection of centroids
centroid = [] # This stores the IDs of the centroids
for i in range(10000):
j = random.randint(0,291407-1)
print(j)
centroid.append(int(vals[j])) # Read each ID in integer form into the centroid list
centerTxt.write(str(vals[j]))
centerTxt.write("\n")
isStable = 0
toll = 0
while isStable == 0 and toll < 100:
print('here')
isStable = 1 # Initialize isStable and only remake instability if any of the centroids change
clusters = [] # List of list of tweet IDs
for cluster in centroid:
clusters.append([cluster]) # Append a list, one for each centroid, to the cluster list of lists of tweet IDs
for tweet in tweetSpl:
if tweet['id'] not in centroid: # If the tweet is not a centroid, it has not been assigned to a list in clusters
Jaccard = [] # List of Jaccard distances between a particular tweet and each centroid
for cluster in centroid: # cluster would be an ID for a centroid within the centroid list
for centerTweet in tweetSpl: # centerTweet would be the tweet in the dictionary belonging to the Id of cluster, in the centroid
if cluster == centerTweet['id']: # Match between cluster centroid and the centerTweet's ID
intersect = 0
for word in tweet['words']:
if word in centerTweet['words']:
intersect += 1
union = len(tweet['words']) + len(centerTweet['words']) - intersect
Jaccard.append((union-intersect)/float(union)) # Calculate and add Jaccard value to the list of these values
clusters[Jaccard.index(min(Jaccard))].append(tweet['id']) # Find the centroid (cluster) with the minimum Jaccard distance to tweet and add tweet there
count = 0
for idGroup in clusters: # Recalculate new centroid for each list in our list of lists of IDS (clusters)
JaccardList = [] # JaccardList is a list of the sum of all Jaccard distances for each tweet in the idGroup
for tweet in idGroup: # tweet will be run for each ID contained within the idGroup
for tweetMatch in tweetSpl:
if tweet == tweetMatch['id']:
tweetJaccard = 0 # tweetJaccard is a sum of the Jaccard distances from tweet to all other tweets in idGroup
for otherTweet in idGroup:
for tweetinDict in tweetSpl:
if otherTweet == tweetinDict['id']:
intersect = 0
for word in tweetMatch['words']:
if word in tweetinDict['words']:
intersect += 1
union = len(tweetMatch['words']) + len(tweetinDict['words']) - intersect
tweetJaccard += (union-intersect)/float(union)
JaccardList.append(tweetJaccard)
if centroid[count] != idGroup[JaccardList.index(min(JaccardList))]:
isStable = 0
centroid[count] = idGroup[JaccardList.index(min(JaccardList))]
count += 1
toll += 1
print("Percent remaining: ", toll/50)
target = open('../data/parisout' , 'w')
count = 0
for idGroup in clusters:
target.write(str(centroid[count]))
target.write(": ")
for idNum in idGroup:
target.write(str(idNum))
target.write(" ")
target.write("\n")
count += 1
|
09ca7768a1a31dc184290ba5de95f5417759cf7d
|
aganpython/laopo3.5
|
/Test/124.py
| 177 | 3.546875 | 4 |
# -*- coding: UTF-8 -*-
import pandas as pd
import numpy as np
data = pd.DataFrame(np.arange(99).reshape(11,9),index=list('abcdefghigk'),columns=list('ABCDEFGHI'))
print(data)
|
4efa0d279c7ebb0fc7961be02bb0092c5d867f31
|
Styfjion/code
|
/BFS_a最短路径长度.py
| 1,502 | 3.53125 | 4 |
class Node:
def __init__(self,x,y,step):
self.x = x
self.y = y
self.step = step
class BFS:
dir = [[0,1],[0,-1],[1,0],[-1,0]]
def bfs_operation(self,matrix,beginX,beginY,endX,endY):
rows = len(matrix)
cols = len(matrix[0])
matrix[beginX][beginY] = '#'
queue = []
begin = Node(beginX,beginY,0)
queue.append(begin)
while queue:
top = queue.pop(0)
if top.x == endX and top.y == endY:
return top.step
for i in range(4):
nx = top.x + self.dir[i][0]
ny = top.y + self.dir[i][1]
if nx>=0 and nx<rows and ny>=0 and ny<cols and matrix[nx][ny] != '#':
matrix[nx][ny] = '#'
queue.append(Node(nx,ny,top.step+1))
return -1
if __name__ == "__main__":
N = int(input())
matrix = []
beginX = -1
beginY = -1
endX = -1
endY = -1
for i in range(N):
rows = list(input())
for j in range(len(rows)):
if rows[j] == 'S':
beginX = i
beginY = j
if rows[j] == 'E':
endX = i
endY = j
matrix.append(rows)
bfs = BFS()
result = bfs.bfs_operation(matrix,beginX,beginY,endX,endY)
print(result)
"""
测试样例:
10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...E#
"""
|
d801062f7f8a04cc5649cfa0a3f0d43d226bc1a9
|
sbollap1/pythondurga
|
/inputOutput1.py
| 106 | 3.6875 | 4 |
a,b = [int(i) for i in input("Enter 2 numbers separated by space: ").split(" ")]
print("Sum is: ", a + b)
|
e184a44ce8a90f37c9ea0d74e427fb16e7551423
|
lilsweetcaligula/sandbox-codewars
|
/solutions/python/73.py
| 178 | 3.65625 | 4 |
def validate_word(word):
from collections import Counter
frequencies = Counter(word.lower()).values()
return all(a == b for a, b in zip(frequencies, frequencies[1:]))
|
03f53bf4b38b87442cea6108b78bfcc5b40f507c
|
atozto9/algorithm
|
/programmers/programmers/hash-02.py
| 699 | 3.65625 | 4 |
def solution(phone_book):
def _hash_sol(phone_book):
answer = True
hash_map = {}
for p_n in phone_book:
hash_map[p_n] = [1]
for p_n in phone_book:
c_seq = ""
for c in p_n:
c_seq += c
if c_seq in hash_map and c_seq != p_n:
return False
return answer
answer = True
phone_book.sort(key=len)
for i, p_1 in enumerate(phone_book[:-1]):
# if any([p_2.startswith(p_1) for p_2 in phone_book[i+1:]]):
# return False
for p_2 in phone_book[i + 1:]:
if p_2.startswith(p_1):
return False
return answer
|
ea28f3f50f2e4220cbc9df0f2bf567196405b50f
|
gomilinux/python-ThinkPython
|
/Chapter02/ThinkPythonEx2.4.1.py
| 186 | 4.21875 | 4 |
#Think Python Exercise 2.12
#Find the volume of a sphere
print('What is the radius?')
radius = input()
VolSphere = float(4.0/3.0)*(3.14)*(pow(float(radius), 3))
print float(VolSphere)
|
fff4b8fe2417a836f55ad2490c2a6c3976cd7cb3
|
hc973591409/python_high_level
|
/03_闭包理解.py
| 933 | 3.828125 | 4 |
def test(num):
print("%d ----test----" % num)
def test_in(num_in):
print("-----内函数返回-----")
res = num + num_in
return res
print("-----外函数 返回-----")
return test_in
# 限定一个ret <===> ret = test_in(x(占位))
# 此处的20是给到外函数
ret = test(20)
# 通过上面定义的函数访问内部函数,此处的100给到内函数
print(ret(100))
print(ret(200))
def counter(start=0):
count = [start]
def incr():
count[0] += 1
return count[0]
return incr
c = counter(5)
print(c())
print(c())
print(c())
print(c())
# 利用闭包实现对一次函数的求解,
# 分析 y=a*x+b 给出(a,b),可以得到一条曲线, 当给出x的值就可以得到y
def fun(a, b):
def fun_in(x):
return a*x + b
return fun_in
fun1 = fun(1, 2)
fun2 = fun(0.5, 4)
fun3 = fun(-1, 2)
print(fun1(2))
print(fun2(2))
print(fun3(2))
|
1f916ef40333c091824d9f1ca134db614a168c7a
|
samarthjj/PreCourse_2
|
/Exercise_1.py
| 1,396 | 3.859375 | 4 |
# Time Complexity : O(log(n))
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
def iterativeBinarySearch(arr, l, r, x):
# for every iteration eliminating half the search space by choosing
# a mid value depending on the value of x since arr is sorted
left = l
right = r
while left <= right:
mid = left + (right - left) / 2
if x == arr[mid]:
return mid
elif x < arr[mid]:
right = mid - 1
elif x > arr[mid]:
left = mid + 1
return -1
def recursiveBinarySearch(arr, l, r, x):
if l <= r:
mid = l + (r - l) / 2
if x == arr[mid]:
return mid
elif x < arr[mid]:
return recursiveBinarySearch(arr, l, mid-1, x)
elif x > arr[mid]:
return recursiveBinarySearch(arr, mid+1, r, x)
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 40
# Function call
result = iterativeBinarySearch(arr, 0, len(arr)-1, x)
result1 = recursiveBinarySearch(arr, 0, len(arr)-1, x)
if result != -1 and result1 != -1:
print "For Iterative search element is present at index % d" % result
print "For Recursive search element is present at index % d" % result1
else:
print "Element is not present in array"
|
2e64887d2964508ef8cfed528b1be30f2db3c5eb
|
fhulu84/Python_Crs
|
/Exercises/S01/Set01/05.py
| 265 | 3.921875 | 4 |
# Given a list of ints, return True if first and last number of a list is same
def is_first_last_same(li):
return li[0] == li[-1]
my_list = [1,2,3,4,5,1]
print(f'is the first and last number of {my_list} same?')
print(f'Result is {is_first_last_same(my_list)}')
|
dae7c4ea3ede12352b25a7c9debecebd3c693081
|
JoaoPedroSoares/Atividades_lic
|
/MF João Pedro Soares 235678.py
| 402 | 3.59375 | 4 |
a1 = float(input('Nota A1'))
a2 = float (input('Nota A2'))
p1 = float(input('Nota P1'))
p2 = float(input('Nota P2'))
def media_final (a1,p1,a2,p2):
MF = (2*a1 + 4*p1 + 3*a2 + 3*p2) / 12
if a1 >= 0 < 10 and a2 >= 0 < 10 and p1 >= 0 < 10 and p2 >= 0 < 10:
print('A1:',a1,'P1:', p1)
print('A2:',a2, 'P2:',p2)
print('MF:', MF)
media_final (a1,p1,a2,p2)
|
5e2ff344ad364a64e8b05eb81cb76bdadf0b454c
|
fishleongxhh/LeetCode
|
/HashTable/771_JewelsAndStones.py
| 340 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
# Author: Xu Hanhui
# 此程序用来求解LeetCode771: Jewels and Stones问题
def numJewelsInStones(J,S):
jewels, cnt = set(J), 0
for item in S:
if item in jewels:
cnt += 1
return cnt
if __name__ == "__main__":
J = ''
S = ''
print(J, S)
print(numJewelsInStones(J,S))
|
bcee42e5a97fb1b9bf9af01e48fcad7708f23c78
|
Daan97/Sandbox
|
/oddName.py
| 158 | 4.03125 | 4 |
"""Daan Felton-Busch"""
name = str(input("Enter your name: "))
while name == "":
print("Invalid name!")
name = str(input("Enter your name: "))
print(name[0::2])
|
411f46f358f30e0b2e87d5c6f63964af577c5538
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20150828C.py
| 1,581 | 3.609375 | 4 |
"""
[2015-08-28] Challenge #229 [Hard] Divisible by 7
https://www.reddit.com/r/dailyprogrammer/comments/3irzsi/20150828_challenge_229_hard_divisible_by_7/
# Description
Consider positive integers that are divisible by 7, and are also divisible by 7 when you reverse the digits. For
instance, `259` counts, because `952` is also divisible by 7. The list of all such numbers between 0 and 10^3 is:
7 70 77 161 168 252 259 343 434 525 595 616 686 700 707 770 777 861 868 952 959
The sum of these numbers is 10,787.
Find the sum of all such numbers betwen 0 and 10^(11).
# Notes
I learned this one from an old ITA Software hiring puzzle. The solution appears in a few places online, so if you want
to avoid spoilers, take care when searching. You can check that you got the right answer pretty easily by searching for
your answer online. Also the sum of the digits in the answer is 85.
The answer has 21 digits, so a big integer library would help here, as would brushing up on your modular arithmetic.
# Optional challenge
Make your program work for an upper limit of 10^N for any N, and be able to efficiently handle N's much larger than 11.
Post the sum of the digits in the answer for N = 10,000. (There's no strict speed goal here, but for reference, my
Python program handles N = 10,000 in about 30 seconds.)
EDIT: A few people asked about my solution. [I've put it up on
github](https://github.com/cosmologicon/problems/tree/master/lucky7s), along with a detailed derivation that's
hopefully understandable.
"""
def main():
pass
if __name__ == "__main__":
main()
|
ecfb35bfea3678bac831e0b03f7470b16a6eb797
|
ankurpathania/Training
|
/list_slicing.py
| 93 | 3.765625 | 4 |
a = [1,2,3,4,5,6,7,8,9]
print("Original List: ",a)
print(a[2:8:2])
print(a[::2])
print(a[::])
|
85b3c9c2781dff82bb29c9b0dc8317181f85831b
|
Skd10/Python_Projects
|
/eight_ball_fancy (1).py
| 475 | 3.59375 | 4 |
import random
import sys
while True:
userQuestion = input("What is your question? enter q to quit ")
response = random.randint(1, 5)
if userQuestion == "q":
sys.exit()
if response == 1:
print ("It is certain.")
if response == 2:
print ("Ask again later")
if response == 3:
print ("My sources say no")
if response == 4:
print ("Yes, definitely")
if response == 5:
print ("Very doubtful")
|
11d05da99d5e09973a641999e7bb78a648d91903
|
ankitt010/File_operation
|
/code/ankit.py
| 1,657 | 3.96875 | 4 |
# # def print_weekdays(week_list):
# # for week in week_list:
# # yield week
# # week_list = ['mon','tue','wed','thurs','fri','sat','sun']
# # my_num = print_weekdays(week_list)
# # print(my_num)
# # print(next(my_num))
# # print(next(my_num))
# # print(next(my_num))
# # print(next(my_num))
# # print(next(my_num))
# # print(next(my_num))
# # print(next(my_num))
# Input = {'a', 'b', 'c', 'd'}
# demo_list = list(Input)
# # demo_values = [3,2,8,4,7,9,0,4,5,6,7]
# num = 2
# rem = 4
# another_list = []
# new_list = []
# def func(demo_values):
# if len(demo_values) < rem:
# new_list.append(demo_values[:])
# return
# else:
# another_list.append(demo_values[:4])
# func(demo_values[rem:])
# func([3,2,8,4,7,9,0,4,5,6,7])
# print(another_list)
# # Output: {'a':[3,2,8], 'b':[4,7,9], c:[0,4,5], 'd':[6,7]}
# demo_dict = {}
# len_dict = len(demo_values) % num
# if len_dict == 0:
# for key in demo_list:
# for values in demo_values:
# demo_dict[key] =
# elif len_dict != 0:
# pass
# for key in Input:
# print(key)
# yield key word
# Input : {'a', 'b', 'c', 'd'}
# [3,2,8,4,7,9,0,4,5,6,7]
# Output: {'a':[3,2,8], 'b':[4,7,9], c:[0,4,5], 'd':[6,7]}
input = ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'd', 'a']
Output = ['a', 2, 'b', 4, 'c', 2, 'd', 1, 'a', 1]
output_list = []
count = 1
for num in range(len(input)-1):
if input[num] == input[num+1]:
count += 1
else:
output_list.append(input[num])
output_list.append(count)
count = 1
output_list.append(input[num+1])
output_list.append(count)
print(output_list)
|
9dc7708a9525c5f3138db9de97522ca72f8aea2e
|
LeninCarabali/ahorcado-phyton
|
/juego_ahorcado.py
| 1,396 | 3.640625 | 4 |
import random, os
def read():
list_palabras = []
with open("./archivos/data1.txt", "r", encoding="utf-8") as f:
for line in f:
list_palabras.append(line)
palabra = random.choice(list_palabras)
doclines = palabra.splitlines()
doc_rejoined = ''.join(doclines)
return doc_rejoined
def dividir_palabra(palabra):
palabra_dividia = {}
for i, palabra in (enumerate(palabra)):
if palabra != "\n":
palabra_dividia[i] = palabra
return palabra_dividia
def nueva_letra():
letra = input("\nEscribe una letra: ")
try:
if len(letra) >= 2:
raise ValueError("Sólo números naturales")
except ValueError as e:
print(e)
return False
return letra
def acomodar(palabra):
hecho2 = {}
for i in range(len(palabra)):
hecho2[i] = "-"
return hecho2
def run():
palabra = read()
acomodar_palabra = acomodar(palabra)
while acomodar_palabra != dividir_palabra(palabra):
print("Adivina la palabra\n")
print(acomodar_palabra)
letra = nueva_letra()
for value in dividir_palabra(palabra):
if dividir_palabra(palabra).get(value) == letra:
acomodar_palabra[value] = letra
# os.system("cls")
print("Correcto, la palabra es", palabra)
if __name__ == "__main__":
run()
|
fd9033a81e88ed6f2e6309e5cbc82519aa8adda0
|
ivanromanv/manuales
|
/Python/Edx_Course/Introduction to Programming Using Python/Excercises/W5_Function_lista_raiz_cubica.py
| 775 | 4.5 | 4 |
# Write a function that accepts a positive integer k and returns the ascending sorted list of cube root values of all the numbers from 1 to k (including 1 and not including k). [if k is 1, your program should return an empty list]
#
def funcion_lista_raiz_cubica(number):
import math
# my_index=int(0)
# contador=int(0)
resultado_sqrt3=float(0)
lista_sqrt3=[]
for numero in range(1,number):
resultado_sqrt3 = numero**(1/3)
lista_sqrt3.append(resultado_sqrt3)
# my_index = lista_sqrt.index(numero)
# lista_sqrt.reverse()
return lista_sqrt3
# OJO SOLO LA FUNCION!!!
# Main Program #
number = int(input("Enter the number: "))
evalua_funcion_lista_raiz_cubica = funcion_lista_raiz_cubica(number)
print(evalua_funcion_lista_raiz_cubica)
|
ecfff1d5fa3c08e22d9a8555dcc47c860b68b302
|
ZQ774747876/AID1904
|
/untitled/day04/file_read.py
| 677 | 3.71875 | 4 |
"""
# """
# word=input("请输入单词:")
# f=open('dict.txt','r')
# for line in f:
# tmp=line.split(' ')[0]
# if tmp>word:
# print("没有找到该单词")
# break
# elif tmp==word:
# print(line)
# break
# else:
# print("没有找到")
# f=open('file','w')
# # f.write("hello word\n".encode())
# # f.write('nihao sdifdks\n'.encode())
# # f.write("sdjkfjo.".encode())
# f.writelines(['abv','dsf'])
with open('file','r+') as f:
f.write("dsjfhsdj\n" )
f.write("hello\n" )
f.write("I am so suprised\n" )
f.
while True:
DATA=f.readline()
print(DATA)
if not DATA:
break
|
285d818e39f17e10cb9f08dc58322f9cdcfe8ac8
|
DojoFatecSP/Dojos
|
/2018/20180504 - robo - python/robo.py
| 397 | 3.90625 | 4 |
#coding:utf-8
numeroDePassos = int(input("Insira o número de passos: "))
entradas=[]
while(numeroDePassos>0):
numeroDePassos -=1
passo = raw_input("Digite o passo: ")
if(passo == "E"):
entradas.append(-1)
elif(passo == "D"):
entradas.append(1)
else:
batata = entradas[int(passo)-1]
entradas.append(batata)
print(entradas)
print(sum(entradas))
|
5bd4093de17416783391a89537d540bd24c57f1b
|
Matteomnd/TPrecursivite
|
/EXERCICE4.py
| 143 | 3.65625 | 4 |
def listSum(I):
if len(I)==0 :
return 0
else:
return I[0]+listSum(I[1:])
print(listSum([1,2,3]))
print(listSum([]))
|
12e03abd8146db5d88ff8db1f6d500c7d6389edd
|
anildhaker/hackerrank
|
/InterviewPractice/comonString.py
| 387 | 3.9375 | 4 |
# Given two strings, determine if they share a common substring.
# A substring may be as small as one character.
# For example, the words "a", "and", "art" share the common substring .
# The words "be" and "cat" do not share a substring.
def twoStrings(s1, s2):
s1 = set(s1)
s2 = set(s2)
result = s1.intersection(s2)
if result:
return "YES"
return "NO"
|
51d7fe3ac41360b983772e74e1e30490ca19700f
|
EUmbr/Py
|
/Books/Stepic/primes.py
| 277 | 3.515625 | 4 |
import itertools
def primes():
i = 2
while True:
var = 0
for j in range(1, i+1):
if i % j == 0:
var += 1
if var == 2:
yield i
i += 1
print(list(itertools.takewhile(lambda x: x <= 5, primes())))
|
f40264d213ddccd8f04d2fb3e0b2e4b30df9cf9e
|
KumaAlex/PP2_2021_Spring
|
/week3/day1/1.py
| 81 | 3.5 | 4 |
x = input().split()
i = 0
while i < len(x):
print(x[i], end = " ")
i += 2
|
352c67c81decf6e79f6d2849199963babdc3cda1
|
wintangt/MyPortofolio
|
/SimplePy1.py
| 3,273 | 3.78125 | 4 |
#Soal Nomor 1
print("="*50)
print("Soal Nomor Satu")
try:
jumlahHari = int(input('Masukkan jumlah hari :'))
#Output nyatakan jumlah hari tersebut dalam
#.... Tahun ... Bulan .... minggu ... hari
tahun = 365 #hari
bulan = 30 #hari
pekan = 7 #hari
sisaHari = 0
jumlahTahun = jumlahHari//tahun
sisaHari = jumlahHari%tahun #Menggunakan Modulus untuk melihat sisa
jumlahBulan = sisaHari//bulan
sisaHari = sisaHari%bulan #Menggunakan Modulus untuk melihat sisa
jumlahPekan = sisaHari//pekan
sisaHari = sisaHari%pekan #Menggunakan Modulus untuk melihat sisa
if jumlahHari<=0:
print('Jumlah Hari dibawah Batas Minimal')
elif jumlahHari >=4000:
print('Jumlah diatas batas maksimal')
else:
print(f'{"0"+str(jumlahTahun)} Tahun, {(jumlahBulan)} Bulan, {(jumlahPekan)} Minggu, {(sisaHari)} hari')
except:
print('jumlah hari salah')
#Soal Nomor 2
print("="*50)
print("Soal Nomor Dua")
try:
tinggiBadan =float(input('Masukan Tinggi Badan (dalam cm): '))
beratBadan =float(input('Masukan Berat Badan(dalam kg): '))
if beratBadan <= 0 or tinggiBadan <= 0 :
print("berat badan atau tinggi badan tidak bisa negatif")
exit()
elif beratBadan > 250 or tinggiBadan >300 :
print("Batas maksimal berat : 250 KG dan Batas maksimal tinggi : 300 CM")
exit()
# Tinggi badan anda ... (meter) dan berat anda ... (kg),
# BMI anda ...(nilai BMI)... (dibulatkan 2 angka dibelakang koma)....
# dan anda termasuk .... (sesuai kondisi)....
bmi= round(beratBadan / (tinggiBadan/100)**2, 2) #Dibagi 100 karena untuk merubahnya ke satuan METER, (,2) itu untuk round 2 angka d belakang koma
tinggiMeter=tinggiBadan/100
print(f'Tinggi Badan Anda {tinggiMeter} Meter dan berat anda {beratBadan} kg, BMI anda {bmi}')
if bmi <= 18.4:
print("dan berat badan anda termasuk Kurang")
elif bmi <= 24.9:
print ("dan berat badan anda termasuk Ideal")
elif bmi <= 29.9:
print('dan berat badan anda termasuk Berlebih')
elif bmi <= 39.9:
print("dan berat badan anda termasuk Sangat Berlebih")
else:
print(" dan berat badan anda termasuk Obesitas")
except:
print("Angka yang anda masukan salah")
#Soal Nomor 3
print("="*50)
print("Soal Nomor Tiga")
try:
nilai=float(input('Masukan Nilai : '))
if nilai >= 90 :
print(f'Nilai anda {nilai} dan Anda Grade A')
elif nilai >= 85 and nilai < 90 :
print(f'Nilai anda {nilai} dan Anda Grade A-')
elif nilai >= 80 and nilai < 85 :
print (f'Nilai anda {nilai} dan Anda grade B')
elif nilai >= 75 and nilai < 80 :
print(f'Nilai anda {nilai} dan Anda grade B-')
elif nilai >=70 and nilai < 75 :
print(f'Nilai anda {nilai} dan Anda grade C')
elif nilai >=65 and nilai < 70 :
print(f'Nilai anda {nilai} dan Anda grade D')
elif nilai >=40 and nilai < 65 :
print(f'Nilai anda {nilai} dan Anda Perlu REMEDIAL')
elif nilai > 100:
print(f'Nilai anda diluar jangkauan')
elif nilai < 0:
print(f'tidak menerima angka negatif')
else:
print(f'Nilai anda {nilai} dan Anda Tidak LULUS')
except:
print("Angka yang anda masukan salah")
'''
|
f9dd4aec5c2893d7329eb25fb3d12c1f42799176
|
gabee1987/codewars
|
/CodeWars/7kyu/find_count.py
| 787 | 3.828125 | 4 |
coll = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
coll2 = []
#def most_frequent_item_count(collection):
#counted_db = []
#duplicates = []
#counter = 0
#for item in collection:
#if item not in counted_db:
#counted_db.append(item)
#else:
#duplicates.append(item)
#for number in (counted_db and duplicates):
#if number in (counted_db and duplicates):
#counter += 1
#return counter
#def most_frequent_item_count(collection):
#max(zip((collections.count(item) for item in set(collection))
def most_frequent_item_count(collection):
dict = {x:collection.count(x) for x in collection}
dict_val = dict.values()
max_val = max(dict_val)
print(dict_val)
most_frequent_item_count(coll)
|
900374ebfdea9eaae61bda444d6a8fb5ef1595a7
|
maheshwari2Anant/WhileLoop
|
/WhileUsage.py
| 413 | 4.1875 | 4 |
while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
input()
|
7e77e92f088407f27c34760e6ff3d67533c7efb5
|
Blublac/univelcity
|
/list_class.py
| 1,701 | 4.25 | 4 |
#16-SEPT-2021
#list
# a list is ordered and its changeble and can be indexed
a = [0,1,5,20,1,2,0,False]
a[3] = 6000
a[7]= True
b = [4,1,5,"hi",False]
#c = [a+b]
a.extend(b)
print(a)
#create a new list of usernames.
# Then write a program to get input from the user requesting his first name and last name
# genetate a username for him. the username should comprise of the first 3 words of his last name and the last 2 words of his first name
#Add his usere name to the list of username and print an output telling him his account has been created.
#hello, user's firstname thank you for signind up your account has sucessfully been created cheers admin
usernames = ["Frank3","Henro","blacky3"]
First_name = input("Enter your first name\n>")
Last_name = input("Enter your last name\n>")
userid = Last_name[0:3]+First_name[-2:]
usernames.append(userid)
print(usernames)
print(f"Hello, {First_name.title()}:.\n\tThank you for signing up. Your account has successfully been created.\n\tYour account ID is {userid}.\n\t\tCHEERS....\n\t\tAdmin")
#GIVEN THE LIST BELOW
#[500,200,[200,500,700,[250,800],250][1000]]
NUMBERS = [500,200,[200,500,700,[250,800],250],[1000]]
X = NUMBERS[2][2]+NUMBERS[2][3][1]
print(X)
NUMBERS[3].append(X)
print(NUMBERS)
str1= "Emma is a Data scientist who knows python. Emma works at google."
str2 = str1.rindex("Emma")
print(f"Last occurrance of Emma starts at index {str2}")
a=["hello","h","gg"]
b= a
ist=a.copy()
a[0]="jjj"
print(a)
print(b)
print(ist)
removed_element =a.remove("jjj")
popped_element = a.pop(-1)
a.pop(-1)
print(a)
print(popped_element)
print(removed_element)
new_list = [3136]
new_list.insert(0,4546)
print(new_list)
new_list.sort()
print(new_list)
|
28979fa56cfb090275654e02a0f8da0ee2947ddf
|
KaisChebata/Computing-in-Python-III-Data-Structures-GTx-CS1301xIII-Exercises
|
/Chapter 4.4 - File Input and Output/Examples/append_to_files.py
| 326 | 3.515625 | 4 |
myint1 = 12
myint2 = 23
myint3 = 34
myList = ["David", "Lucy", "Vrushali", "Ping",
"Natalie", "Dana", "Addison", "Jasmine"]
output_file = open('output_file.txt', 'a')
for num in (myint1, myint2, myint3):
output_file.write(str(num) + '\n')
for name in myList:
print(name, file=output_file)
output_file.close()
|
c624d9b8e7b909ada391cf773a61008c741a83a9
|
abriggs914/CS2613
|
/Labs/lab19/test_fibonacci.py
| 439 | 3.578125 | 4 |
from fibonacci import fib, fib2, fib3
def test_fib1():
fun = fib2(1000)
lst2 = []
while True:
n = fun()
if n!=None:
lst2.append(n)
else:
break
assert lst2 == list(fib(1000))
def test_fib2():
fun = fib2(1000)
lst2 = []
while True:
n = fun()
if n!=None:
lst2.append(n)
else:
break
assert lst2 == list(fib3(1000))
|
181f683e1444e4ca8adcd6ae889f37148cc2b08c
|
gxmls/Python_NOI
|
/NOI2-2-03.py
| 820 | 3.65625 | 4 |
'''
描述
给出一个正整数a,要求分解成若干个正整数的乘积,即a = a1 * a2 * a3 * ... * an,并且1 < a1 <= a2 <= a3 <= ... <= an,
问这样的分解的种数有多少。注意到a = a也是一种分解。
输入
第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a (1 < a < 32768)
输出
n行,每行输出对应一个输入。输出应是一个正整数,指明满足要求的分解的种数
样例输入
2
2
20
样例输出
1
4
'''
def factor(n,p):
sum=1
for i in range(p,int(n**0.5)+1):
if n%i==0:
sum+=factor(n//i,i)
return sum
n=eval(input())
s=[]
for i in range(n):
s.append(eval(input()))
for i in range(n):
print(factor(s[i],2))
|
57f77f85bc5a8128560149ee402d9178bf6e522f
|
tbcodes/python_how_to_find_the_sum_of_all_even_odd_numbers_from_zero_to_n
|
/16-Find_sum_of_even_odd_numbers.py
| 1,171 | 4.1875 | 4 |
# How to calculate the sum of all even/odd numbers from zero to 'n'
# Youtube URL: https://youtu.be/xcu-1cO014Q
# **********************************************************************
# Sum all even numbers from zero to 'n'
total = 0
# num = 500
num = int(input("Please, enter a number: "))
even_numbers = []
for i in range(0, num + 1):
if i % 2 == 0:
even_numbers.append(i)
total += i
print(f"All even numbers from 0 to {num} is: {even_numbers}")
print("········································")
print("The sum of even numbers from 0 to {} is: {}".format(num, total))
# **********************************************************************
# Sum all odd numbers from zero to 'n'
total = 0
# num = 500
num = int(input("Please, enter a number: "))
even_numbers = []
for i in range(0, num + 1):
if i % 2 == 1:
even_numbers.append(i)
total += i
print(f"All odd numbers from 0 to {num} is: {even_numbers}")
print("········································")
print("The sum of odd numbers from 0 to {} is: {}".format(num, total))
|
12b5a2078cd22ab2e5f5b04d72ab2b1830f3212f
|
jorchube/GameEngine
|
/game_engine/visual/rgb.py
| 755 | 3.515625 | 4 |
import random
class RGB(object):
def __init__(self, red, green, blue):
self.__red = red
self.__green = green
self.__blue = blue
@property
def red(self):
return self.__red
@property
def green(self):
return self.__green
@property
def blue(self):
return self.__blue
@red.setter
def red(self, value):
self.__red = value
@green.setter
def green(self, value):
self.__green = value
@blue.setter
def blue(self, value):
self.__blue = value
@classmethod
def random(cls):
return RGB(
random.randint(0, 10) * 0.1,
random.randint(0, 10) * 0.1,
random.randint(0, 10) * 0.1,
)
|
6fbaba2ccbb99d9af165bb7eede66fe97bd4f419
|
jasonposner/Network-Science-Project
|
/collaborator_writer.py
| 827 | 3.59375 | 4 |
# this code reads the "performers" data set and writes
# a csv which contains only only_collaborators.
import csv
collaborators = []
# create a list which considers only musicians who collaborate
with open('performers.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\n', quotechar='|')
index = 0
for row in spamreader:
# fetch the performer string we are going to look at
s = row[index]
# find '&' symbol (don't worry about how many yet)
if " & " in s:
# uniqueness modifier
if s not in collaborators:
collaborators.append(s)
collaborators.sort()
with open('only_collaborators_raw.csv', 'w', newline='\n') as csvfile:
spamwriter = csv.writer(csvfile, delimiter='\n')
spamwriter.writerow(collaborators)
|
a2e9029c4cdeb0e9a9094dde4a29054ba8728ed2
|
shach934/leetcode
|
/leet592.py
| 2,444 | 4.25 | 4 |
592. Fraction Addition and Subtraction
Given a string representing an expression of fraction addition and subtraction,
you need to return the calculation result in string format. The final result should be irreducible fraction.
If your final result is an integer, say 2, you need to change it to the format of fraction that has
denominator 1. So in this case, 2 should be converted to 2/1.
Example 1:
Input:"-1/2+1/2"
Output: "0/1"
Example 2:
Input:"-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input:"1/3-1/2"
Output: "-1/6"
Example 4:
Input:"5/3+1/3"
Output: "2/1"
Note:
The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the
output is positive, then '+' will be omitted.
The input only contains valid irreducible fractions, where the numerator and denominator of each
fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually
an integer in a fraction format defined above.
The number of given fractions will be in the range [1,10].
The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
class Solution(object):
def fractionAddition(self, expression):
"""
:type expression: str
:rtype: str
"""
digits, nums = '', []
for i in expression:
if i == '+' or i == '-':
if digits:
nums.append(digits)
digits = i
elif i == '/':
if digits:
nums.append(digits)
digits = ''
else:
digits += i
if digits:
nums.append(digits)
denor, numer = int(nums.pop()), int(nums.pop())
while nums:
b, a = int(nums.pop()), int(nums.pop())
numer = numer * b + denor * a
denor = denor * b
if numer == 0:
return '0/1'
if numer >= denor:
x = self.gcd(numer, denor)
else:
x = self.gcd(denor, numer)
if numer<0:
x = -x
denor /= x
numer /= x
return str(numer)+'/'+str(denor)
def gcd(self, a, b):
if b == 0:
return a
return self.gcd(b, a%b)
|
bca006b7038539d18762b6b517375f47c47f086c
|
ninjaofpython/back_to_basics
|
/python-basics/sets.py
| 129 | 3.78125 | 4 |
my_set = {"January", "February", "March"}
my_set.add("April")
my_set.remove("February")
for element in my_set:
print(element)
|
60251967a4cf56c2ffee77f4790e80c253f6d173
|
manasa0917/python_code
|
/Assigments/dict1_solution.py
| 371 | 3.828125 | 4 |
mydict={5443:"Rahu",7786:"Jimmy",8762:"Manasha",6675:"Mukund",9876:"Sheshadri"}
mylist=[]
mylist=list(mydict.values())
print(mylist)
mylist.sort()
reversedict={}
print(mylist)
for key in mydict:
val=mydict[key]
reversedict[val]=key
result=[]
for item in mylist:
tmp=[]
tmp.append(item)
tmp.append(reversedict[item])
result.append(tmp)
print(result)
|
cec10206c6766589c049202b6657484c08612697
|
ed-p-patch/Python
|
/Python Work/Python - 1/strings-lists.py
| 657 | 3.875 | 4 |
# E Patch
words = "It's thanksgiving day. It's my birthday,too!"
print words.find('day') # returns 18
print words.find('day', 19) # returns 36
print words.replace('day', 'month') # replaces day for month
x = [2,54,-2,7,12,98]
print min(x) # returns -2
print max(x) # returns 98
y = ["hello",2,54,-2,7,12,98,"world"]
print y[0], y[-1] # returns hello world
z = [19,2,54,-2,7,12,98,32,10,-3,6]
z.sort()
length = (len(z)/2) # rounded down
w = []
for index in range(0, length): # obtain the first half of the list
w.append(z[index])
for index in range(1, length): # delete each index except the one we will insert the new list
del z[0]
z[0] = w
print z
|
b1f05b03ff6ee3fa422af31e1cc7899b95c61df2
|
Aasthaengg/IBMdataset
|
/Python_codes/p03018/s154379157.py
| 201 | 3.578125 | 4 |
s = input()
s = s.replace('BC','D')
A_count = 0
ans = 0
for i in s:
if i == 'A':
A_count += 1
elif i == 'B' or i == 'C':
A_count = 0
else:
ans += A_count
print(ans)
|
9ce3bb0a525057d868960b24bfeda7deca5e17c9
|
RutujaWanjari/Python_Basics
|
/python_strings.py
| 681 | 3.828125 | 4 |
# 01234567890123456789012345
# 65432109876543210987654321
alphabet = "abcdefghijklmnopqrstuvwxyz"
# alphabet = ""
print('reverse - ', alphabet[::-1]) # Perfect idiom to reverse string
print('slices - ', alphabet[0:25:2])
print('reverse slices - ', alphabet[26:0:-2])
print('qpo - ', alphabet[16:13:-1])
# OR
print('qpo - ', alphabet[-10:-13:-1])
print('edcba - ', alphabet[-22:-27:-1])
# OR
print('edcba - ', alphabet[4::-1])
print('reverse last 8 chars - ', alphabet[:-9:-1])
# OR
print('reverse last 8 chars - ', alphabet[:17:-1])
print('first char - ', alphabet[:1])
# OR
print('first char - ', alphabet[0]) # throws exception if string is empty
|
76d7e093f32c31794629abd9813467ef75dda821
|
noob643/Truss-Solver
|
/solver.py
| 8,288 | 3.5 | 4 |
# Write your code here :-)
import math
import numpy as np
import copy
class Support:
supportCount=0
def __init__(self, point, sup_type):
self.point=point
self.sup_type=sup_type
def sup_cols_rows(self):
if self.sup_type=='PIN':
return[self.point*2-1, self.point*2]
if self.sup_type=='ROLLERX':
return[self.point*2-1]
else:
return[self.point*2]
class Point:
pointCount=0
def __init__(self, name, x, y, serial, xforce, yforce):
self.name=name
self.x=x
self.y=y
self.serial=serial
self.xforce=xforce
self.yforce=yforce
Point.pointCount+=1
def __del__(self):
Point.pointCount-=1
class_name = self.name
#print (class_name, "deleted")
def coordinates(self):
print('Coordinate for X: ',self.x,'\nCoordinate for Y: ',self.y)
def xy(self):
return [self.x, self.y]
def force(self):
return [self.xforce, self.yforce]
def force_display(self):
print('Applied forces at point '+str(self.name+1)+"""
Fx = """ +str(self.xforce)+"""kN
Fy = """ +str(self.yforce)+'kN')
class steelElement:
elemCount =0
def __init__(self, name, point_start, point_end, area):
self.name=name
self.startx=point_start.xy()[0]
self.starty=point_start.xy()[1]
self.endx=point_end.xy()[0]
self.endy=point_end.xy()[1]
self.startpos=point_start.serial
self.endpos=point_end.serial
self.area=area
self.density=7800
self.poi_rat=0.3
self.youngs=1
steelElement.elemCount+=1
def length(self):
length=math.sqrt((self.endx-self.startx)**2+(self.endy-self.starty)**2)
return length
def weight(self):
weight = self.area*self.length()*self.density
return weight
def position(self):
print('Start at x=',self.startx,' y=',self.starty,'\nEnd at x=',
self.endx,' y=',self.endy)
def orientation(self):
sin_alpha = (self.starty-self.endy)/self.length()
cos_alpha = (self.startx-self.endx)/self.length()
return [sin_alpha, cos_alpha]
def stiffness(self):
k=self.area*self.youngs/self.length()
return k
def connectivity(self):
return [self.startpos, self.endpos]
dictionary = {
'p1': [0, 0, 0, 0],
'p2': [3, 0, 10, -10],
'p3': [6, 0, 0, 0],
'p4': [1.5, 3, 0, 0],
'p5': [4.5, 3, 0, 0]
}
all_points = []
for i in range(len(list(dictionary.items()))):
all_points.append(
Point(i,
list(dictionary.items())[i][1][0],
list(dictionary.items())[i][1][1],
list(enumerate(list(dictionary.values())))[i][0],
list(dictionary.items())[i][1][2],
list(dictionary.items())[i][1][3]
))
dictionary_element = {
'elem1': [1, 4, 1],
'elem2': [4, 5, 1],
'elem3': [5, 3, 1],
'elem4': [2, 4, 1],
'elem5': [2, 5, 1],
'elem6': [1, 2, 1],
'elem7': [2, 3, 1]
}
all_elements = []
for i in range(len(list(dictionary_element.items()))):
all_elements.append(
steelElement(i+1,
all_points[list(dictionary_element.items())[i][1][0]-1],
all_points[list(dictionary_element.items())[i][1][1]-1],
list(dictionary_element.items())[i][1][2]
))
supports ={
'support1': [1, 'PIN'],
'support2': [3, 'PIN']
}
all_supports=[]
for i in range(len(list(supports.items()))):
all_supports.append(
Support(
list(supports.values())[i][0],
list(supports.values())[i][1]
))
blank_smatrix=[]
for y in range(len(all_points)*2):
row=[]
for x in range(len(all_points)*2):
row.append(0.0)
blank_smatrix.append(row)
# create overall stiffenss matrix for the truss
for i in range(len(all_elements)):
blank_smatrix[all_elements[i].startpos*2][all_elements[i].startpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]**2
blank_smatrix[all_elements[i].startpos*2][all_elements[i].startpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]
blank_smatrix[all_elements[i].startpos*2+1][all_elements[i].startpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]
blank_smatrix[all_elements[i].startpos*2+1][all_elements[i].startpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[0]**2
blank_smatrix[all_elements[i].endpos*2][all_elements[i].endpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]**2
blank_smatrix[all_elements[i].endpos*2][all_elements[i].endpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]
blank_smatrix[all_elements[i].endpos*2+1][all_elements[i].endpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]
blank_smatrix[all_elements[i].endpos*2+1][all_elements[i].endpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[0]**2
blank_smatrix[all_elements[i].startpos*2][all_elements[i].endpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]**2*(-1)
blank_smatrix[all_elements[i].startpos*2][all_elements[i].endpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]*(-1)
blank_smatrix[all_elements[i].startpos*2+1][all_elements[i].endpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]*(-1)
blank_smatrix[all_elements[i].startpos*2+1][all_elements[i].endpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[0]**2*(-1)
blank_smatrix[all_elements[i].endpos*2][all_elements[i].startpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]**2*(-1)
blank_smatrix[all_elements[i].endpos*2][all_elements[i].startpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]*(-1)
blank_smatrix[all_elements[i].endpos*2+1][all_elements[i].startpos*2]+=all_elements[i].stiffness()*all_elements[i].orientation()[1]*all_elements[i].orientation()[0]*(-1)
blank_smatrix[all_elements[i].endpos*2+1][all_elements[i].startpos*2+1]+=all_elements[i].stiffness()*all_elements[i].orientation()[0]**2*(-1)
# create force vector matrix
# create empty force matrix
all_forces=[]
for i in all_points:
all_forces+=i.force()
force_matrix=[]
for z in range(len(all_forces)):
force_matrix.append([all_forces[z]])
#print(force_matrix)
for z in range(8):
print(str(z+1).rjust(5),end='|')
print()
print('------------------------------------------------')
for i in blank_smatrix:
for z in i:
print(str(round(z,2)).rjust(5),end='|')
print()
sup_to_del=[]
for elem in all_supports:
sup_to_del+=elem.sup_cols_rows()
sup_to_del.sort(reverse=True)
analysis_matrix=copy.deepcopy(blank_smatrix)
for z in range(len(analysis_matrix)):
for i in sup_to_del:
del analysis_matrix[z][i-1]
for i in sup_to_del:
del analysis_matrix[i-1]
del force_matrix[i-1]
#calculate displacements
A=np.array(analysis_matrix)
x=np.array(force_matrix)
B=np.linalg.solve(A, x)
val_to_ins=sorted(sup_to_del)
B = B.tolist()
B_full=B
displacement=B_full
for i in val_to_ins:
B_full.insert(i-1, [0.0])
B_full=np.array(B_full)
#print(B_full)
#calculate reactions
reactions_matrix=np.dot(blank_smatrix, B_full)
#reactions_matrix=reactions_matrix.tolist()
#print(reactions_matrix)
#element force calculation
all_elements_force=[]
for i in all_elements:
force=np.dot(i.stiffness()*np.array(
[i.orientation()[1],i.orientation()[0],-i.orientation()[1],-i.orientation()[0]]
),(
1/(i.area*i.youngs)
)*np.array(
[displacement[i.startpos*2],displacement[i.startpos*2+1],displacement[i.endpos*2],displacement[i.endpos*2+1]]))
all_elements_force.append(force)
print(all_elements_force)
|
f458a0fcb0704e3c49989ed03daa329c07a1f5cd
|
kaushiknishant/problem-solving
|
/sort_colors.py
| 741 | 3.875 | 4 |
# dutch flag algo
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
low = 0
mid = 0
high = len(nums)-1
while mid<=high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low +=1
mid +=1
elif nums[mid] == 1:
mid +=1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -=1
return nums
if __name__ == '__main__':
sol = Solution()
nums = [0,1,1,0,1,1,2,1,2,0,0,0,1]
res = sol.sortColors(nums)
print(res)
|
f126eaf36048533826f940ea3c01057a08f12192
|
cgmorton/the-game
|
/players.py
| 7,119 | 4 | 4 |
import itertools
import logging
import random
def random_player(hand, pile_dict, min_cards=2, max_cards=6):
"""Randomly play a card on a pile
Args:
hand (list):
pile_dict (dict):
min_cards (int):
max_cards (int):
Return
boolean: return True if there is a valid move
"""
logging.debug(' Hand: {}'.format(' '.join(map(str, hand))))
# The player hand is already random, so only shuffle the pile keys
piles = sorted(pile_dict.keys(), key=lambda *args: random.random())
# piles = sorted(pile_dict.keys(), key=os.urandom)
# Iterate through all possible pairs of cards and piles
cards_played = []
for card, pile in itertools.product(hand, piles):
if card in cards_played:
# Skip card if it was already played
continue
elif (('up' in pile and card > pile_dict[pile][-1]) or
('down' in pile and card < pile_dict[pile][-1])):
logging.debug(' Play: {} {}'.format(card, pile))
pile_dict[pile].append(card)
hand.remove(card)
cards_played.append(card)
# Player can't play more than the max number of cards
if len(cards_played) >= max_cards:
break
else:
continue
# Game is over if the player can't play the minimum number of cards
if len(cards_played) < min_cards:
return False
else:
return True
def random_updown_player(hand, pile_dict, min_cards=2, max_cards=6):
"""First try playing sorted hand on the up piles,
then play reverse sorted hand on the down piles
Args:
hand (list):
pile_dict (dict):
min_cards (int):
max_cards (int):
Return
boolean: return True if there is a valid move
"""
cards_played = []
logging.debug(' Hand: {}'.format(' '.join(map(str, hand))))
up_piles = sorted(
[k for k in pile_dict.keys() if 'up' in k],
key=lambda *args: random.random())
down_piles = sorted(
[k for k in pile_dict.keys() if 'down' in k],
key=lambda *args: random.random())
# Try playing sorted hand on the up piles
sorted_hand = sorted(hand[:])
logging.debug(' Hand: {}'.format(' '.join(map(str, sorted_hand))))
for card, pile in itertools.product(sorted_hand, up_piles):
if len(cards_played) >= max_cards:
break
elif card in cards_played:
# Skip card if it was already played
continue
elif card > pile_dict[pile][-1]:
logging.debug(' Play: {} {}'.format(card, pile))
pile_dict[pile].append(card)
hand.remove(card)
cards_played.append(card)
# Then try playing reverse sorted hand on the down piles
sorted_hand = sorted(hand[:], reverse=True)
logging.debug(' Hand: {}'.format(' '.join(map(str, sorted_hand))))
for card, pile in itertools.product(hand, down_piles):
# Player can't play more than the max number of cards
if len(cards_played) >= max_cards:
break
elif card in cards_played:
# Skip card if it was already played
continue
elif card < pile_dict[pile][-1]:
logging.debug(' Play: {} {}'.format(card, pile))
pile_dict[pile].append(card)
hand.remove(card)
cards_played.append(card)
# Game is over if the player can't play the minimum number of cards
if len(cards_played) < min_cards:
return False
else:
return True
def min_diff_player(hand, pile_dict, min_cards=2, max_cards=6):
"""Play cards closest to the pile cards
Args:
hand (list):
pile_dict (dict):
min_cards (int):
max_cards (int):
Return
boolean: return True if there is a valid move
"""
cards_played = []
logging.debug(' Hand: {}'.format(' '.join(map(str, hand))))
while len(cards_played) < max_cards:
play_list = []
# Compute difference between piles and cards in hand
# Put diff as first value in nested list to sort on
for p_name, p_cards in pile_dict.items():
if 'up' in p_name:
diff = [
[h_card - p_cards[-1], p_name, h_card]
for h_card in hand if h_card > p_cards[-1]]
elif 'down' in p_name:
diff = [
[p_cards[-1] - h_card, p_name, h_card]
for h_card in hand if h_card < p_cards[-1]]
play_list.extend(diff)
# Place the card with the lowest difference on a pile
if play_list:
diff, pile, card = sorted(play_list)[0]
logging.debug(' Play: {} {}'.format(card, pile))
pile_dict[pile].append(card)
hand.remove(card)
cards_played.append(card)
else:
break
# Game is over if the player can't play the minimum number of cards
if len(cards_played) < min_cards:
return False
else:
return True
def min_diff_mod_player(hand, pile_dict, min_cards=2, max_cards=6,
play_tens=True):
"""Play cards closest to the pile cards
Args:
hand (list):
pile_dict (dict):
min_cards (int):
max_cards (int):
play_tens (bool): Play -10s when possible
Return
boolean: return True if there is a valid move
"""
cards_played = []
logging.debug(' Hand: {}'.format(' '.join(map(str, hand))))
# while len(cards_played) < max_cards:
while len(cards_played) < max_cards:
play_list = []
# Compute difference between piles and cards in hand
# Put diff as first value in nested list to sort on
for p_name, p_cards in pile_dict.items():
if 'up' in p_name:
diff = [
[h_card - p_cards[-1], p_name, h_card]
for h_card in hand
if h_card > p_cards[-1] or ((p_cards[-1] - h_card) == 10)]
elif 'down' in p_name:
diff = [
[p_cards[-1] - h_card, p_name, h_card]
for h_card in hand
if h_card < p_cards[-1] or ((p_cards[-1] - h_card) == 10)]
play_list.extend(diff)
# Place the card with the lowest difference on a pile
if play_list:
tens_list = [plays for plays in play_list if plays[0] == -10]
if play_tens and tens_list:
diff, pile, card = tens_list[0]
logging.info(' Ten: {} {}'.format(card, pile))
else:
diff, pile, card = sorted(play_list)[0]
logging.debug(' Play: {} {}'.format(card, pile))
pile_dict[pile].append(card)
hand.remove(card)
cards_played.append(card)
else:
break
# Game is over if the player can't play the minimum number of cards
if len(cards_played) < min_cards:
return False
else:
return True
|
fd27b3e000ffc08436cfd1c9d1133103157faee6
|
YiseBoge/CompetitiveProgramming2
|
/Weeks/Week3/bt_for_preorder_traversal.py
| 842 | 3.5 | 4 |
from Types.__tree_node__ import TreeNode
class Solution:
def flipMatchVoyage(self, root: TreeNode, voyage: list) -> list:
index, impossible = 0, False
result = []
def traverse(node):
nonlocal voyage, index, result, impossible
if index >= len(voyage) or node.val != voyage[index]:
impossible = True
return
index += 1
if (index < len(voyage)
and node.left
and node.left.val != voyage[index]):
node.left, node.right = node.right, node.left
result.append(node.val)
if node.left:
traverse(node.left)
if node.right:
traverse(node.right)
traverse(root)
return [-1] if impossible else result
|
0e47942e08a5ef8ffb74a28806a741fb92695dcc
|
Angelofmystra/dnd-tools-py
|
/dice2.py
| 706 | 3.609375 | 4 |
import random
def d6(sides, faces):
n = 0
for i in range(sides):
n += random.randint(1, faces)
return n
def room():
n = d6(1,6)
m = d6(1,6)
if n==1 or n == 2:
print ("monster in room")
if m == 1 or m == 2 or m == 3:
print ("treasure present")
else:
print ("empty")
if m == 1:
print ("treasure present")
def rollHMStats():
print ("Str:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Dex:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Con:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Int:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Wis:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Cha:"+str(d6(3,6))+"//"+str(d6(1,100)))
print ("Com:"+str(d6(3,6))+"//"+str(d6(1,100)))
rollHMStats()
|
f56b6df37cfc7978e8c8b6dc7dfeb9e95ad352c9
|
aadhi24/python-snake-game-
|
/score.py
| 655 | 3.65625 | 4 |
from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.scores = 0
self.hideturtle()
self.color("white")
self.penup()
self.goto(0, 250)
self.times = 0.2
self.write(f"score {self.scores}", align="center", font=("Aral", 24, "normal"))
def current_score(self):
self.clear()
self.scores += 1
self.write(f'score {self.scores}', align="center", font=("Arial", 24, "normal"))
def game_over(self):
self.goto(0, 0)
self.write('game Over', align="center", font=("Arial", 28, "normal"))
|
74eaf70857725b5385572553acadacfa15dbab32
|
NeonMiami271/Work_JINR
|
/Python/treug.py
| 511 | 3.96875 | 4 |
# Треугольник тип
import sys
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
if (a + b < c) or (a + c < b) or (c+ b < a):
print("Такого треугольника не сущствует")
sys.exit(0)
if (a == b == c):
print("Треугольник равносторонний")
elif (a != b) and (a != c) and (c != b):
print("Треугольник разносторонний")
else:
print("Треугольник равнобедренный")
|
e3e3542c4e3bb1cd99535e195b4ac6c8b473098c
|
wrideveloper/gitting-started-2020
|
/src/EM2CIQ2/rangoli.py
| 393 | 3.71875 | 4 |
"""
Rangoli
https://en.wikipedia.org/wiki/Rangoli
"""
import string
def print_rangoli(size):
strings = string.ascii_lowercase[0:size]
for i in range(size-1, -size, -1):
x = abs(i)
if x >= 0:
line = strings[size:x:-1]+strings[x:size]
print ("--"*x+ '-'.join(line)+"--"*x)
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
|
6d68c99149ba7656c6fc2595693cfd475d1a1e00
|
Amanjot25/M03
|
/division-exacta.py
| 438 | 3.984375 | 4 |
#Coding: utf-8
dividendo = int(input("Escribe el dividendo: "))
divisor = int(input("Escribe el divisor: "))
if divisor == 0:
print("No puedes dividir por 0")
else:
cociente= dividendo // divisor
resto= dividendo % divisor
if dividendo % divisor == 0:
print("La división es exacta. cociente:" ,cociente ,"resto:" ,resto)
else:
print("La división no es exacta. cociente:" ,cociente ,"resto:" ,resto)
|
fcf2ba2bbcd1b20e6bda3141eb05c7e6bb042cff
|
peter-wangxu/python_play
|
/test/metatest/meta_derive.py
| 519 | 3.625 | 4 |
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class ClassBase(object):
@abc.abstractmethod
def fun_a(self):
"""This function must be implemented by subclass"""
pass
def fun_b(self):
pass
def fun_d(self):
pass
class ClassDerive(ClassBase):
def fun_c(self):
print "Fun c"
@six.add_metaclass(abc.ABCMeta)
class ClassBase2(object):
def fun_e(self):
print "fun_e"
print issubclass(ClassBase2, ClassBase)
d = ClassDerive()
d.fun_c()
|
02c2af5a6daf918c0e78d20787180f04a4d8ff10
|
Luolingwei/LeetCode
|
/Stack/Q921_Minimum Add to Make Parentheses Valid.py
| 518 | 3.671875 | 4 |
# Input: "((("
# Output: 3
# 思路: left和right分别表示没有配对的左括号和右括号的个数.
class Solution:
def minAddToMakeValid(self, S):
left=right=0
for char in S:
if char==')':
if not left:right+=1
else: left-=1
else:
left+=1
return left+right
a=Solution()
print(a.minAddToMakeValid("())"))
print(a.minAddToMakeValid("((("))
print(a.minAddToMakeValid('()'))
print(a.minAddToMakeValid("()))(("))
|
141b6d72a3890b96f51838d1b4806763f0c60684
|
sivaneshl/python_ps
|
/tuple.py
| 801 | 4.25 | 4 |
t = ('Norway', 4.953, 4) # similar to list, but use ( )
print(t[1]) # access the elements of a tuple using []
print(len(t)) # length of a tuple
for item in t: # items in a tuple can be accessed using a for
print(item)
print(t + (747, 'Bench')) # can be concatenated using + operator
print(t) # immutable
print(t * 3) # can be used with multiply operator
# nested tuples
a = ((120, 567), (747, 950), (474, 748), (747,738)) # nested tuples
print(a[3])
print(a[3][1])
# single element tuple
h = (849)
print(h, type(h)) # this is treated as a int as a math exp
h = (858,) # single element tuple with trailing comma
print(h, type(h))
e = () # empty tuple
print(e, type(e))
# parenthesis of literal tuples may be omitted
p = 1, 1, 3, 5, 6, 9
print(p, type(p))
|
1d1491e2301ef344d82253c593dc849e93440ea6
|
rishinkaku/advanced_python
|
/decorators/decorators_p2.py
| 572 | 4.0625 | 4 |
# Make a Sandwich with the help of decorators
def bread(func):
def wrapper():
print("|---bread---|")
func()
print("|---bread---|")
return wrapper
def ingredients(func):
def wrapper():
print('|~~tomates~~|')
func()
print('|~~~salad~~~|')
return wrapper
def cheese(func):
def wrapper():
print('|===cheese==|')
func()
return wrapper
@bread
@ingredients
@cheese
def func():
print('|~~~~meat~~~|')
print("Our Sandwich has ready")
print('-'*50)
func() # Our Sandwich has ready
|
f3824023d3b4d2132dbdd4ea2bdd357e865d90f2
|
Owaisaaa/Python_Basics
|
/test_script.py
| 356 | 3.875 | 4 |
# Read n and the scores from STDIN
n = int(input())
scores = list(map(int, input().split()))
# Sort the scores in descending order
scores.sort(reverse=True)
# Find the second highest score
runner_up = -1
for score in scores:
if score < scores[0]:
runner_up = score
#print(runner_up)
break
# Print the result
print(runner_up)
|
7c09ebcce46b1a9fdf7f8d2cf02561043ebc103c
|
connorlunsford/text-based-adventure-game
|
/create_bottom_floor.py
| 52,095 | 3.546875 | 4 |
import system
import room
import object
import feature
import person
# DESC
# This python file will use everything from the system to generate the json files for the game
# simply instantiate the rooms and interactables you want to create, then add them to the system
# the system will then call a command to save the base gamefiles you have created
# list of possible interactions for reference
# interactions = {
# 'use': {
# 'object_id': 'insert how this object would interact with this feature',
# },
# 'ask': {
# 'object_id': 'insert in character response for the player asking them about this object',
# 'feature_id': 'insert in character response for the player asking them about this feature',
# 'person_id': 'insert in character response for the player asking them about this person',
# },
# 'read': 'insert the text that would be on this object IE: the letter says "dearest Ava..."',
# 'open': {
# 'locked': 'insert what happens if the player tries to open this object while it is locked',
# 'unlocked': 'insert what happens if the player tries to open this object while it is unlocked',
# },
# 'search': 'insert what the player finds if they search through the feature',
# 'touch': 'insert what the player feels when they touch this object',
# 'taste': 'insert what the player tastes when they lick this object',
# 'smell': 'insert what the player smells when they sniff this object',
# 'listen': 'insert what the players can hear when they listen to this object',
# }
if __name__ == '__main__':
# instantiates the system
sys = system.System()
# R01 The Grand Foyer
# creates the grand foyer
R01 = room.Room('R01', 'Grand Foyer',
'The large empty expanse of the grand foyer stretches out in front of you. Impressively clean '
'marble floors, dark stained wood panel walls, and a large double-sided curved staircase make '
'up the architecture of this massive entrance. The walls are decorated with several paintings, '
'some of which look to be quite expensive. \n'
'To the south is the entrance to the house. You know you cannot leave until the murder has been '
'solved.\n'
'To the west appears to be the entrance to a gleaming white kitchen.\n'
'To the east seems to be a library of sorts.\n'
'To the north is the upstairs hallway.',
'The grand foyer stretches out in front of you. To the west is the kitchen, to the east is the '
'library, and going upstairs to the north will take you to the upstairs hallway.')
# sets the connections for the room
R01.set_connections({
'west': 'R02', # kitchen
'east': 'R03', # library
'north': 'R11' # hallway
})
# sets the objects in the room
R01.set_objects(['O02', # rusty key
])
# sets the features in the room
R01.set_features(['F01R01', # victims body
'F02R01', # side table
'F03R01', # rotary phone
])
# no people so no need to set the people list
# sets the interactions
R01.set_interactions({
'search': "You walk around the foyer, inspecting every nook and cranny. As far as you can tell, "
"the only things in the room are the victim's body, an end table, a rotary phone, and some gaudy old furniture.",
'touch': 'You run your hands along the floor, careful to avoid the puddle of blood. It feels cool '
'to the touch. Placing your hands upon the wood paneling of the wall reveals it is sturdy dark wood. '
'This building was clearly quite expensive to construct.',
'taste': 'You get on all fours and lean down to touch the marble with your tongue. It tastes similar to some '
'kind of floor polish.',
'smell': 'For the first time since entering the room, you notice the smell of the blood. It smells acrid '
'and metallic. You recoil and turn your nose out of surprise.',
'listen': 'You can hear the creaks and groans of an old house. You stand in silence for a minute before you '
'hear someone speaking in the library. You cannot make out what they are saying.',
})
sys.add_room(R01)
# F01R01 the victims body
F01R01 = feature.Feature('F01R01', "Victim's Body",
'You turn the body over to get a better look, careful not to touch the blood. '
'Examining his face closely, you can tell he is an older man in his 50s '
'with graying hair and wrinkles. In life, he may have been quite handsome, '
'but the shock of death has left him pale with a purple tinge around his lips. ',
"The victim's body lays face down on the floor in the middle of the room. He is wearing "
"a green sweater with gray slacks. You can see a little dirt around the collar of his "
"sweater. Judging by the large gash on the back of his head, "
"he was likely struck by some sort of object. A small pool of blood has surrounded "
"him, slowly congealing on the cold floor.",
{
'search': 'You pat the body down, searching his pockets for any belongings he may '
'have been carrying. You quickly discover that in his front left pocket is a '
'rusty metal key.',
'touch': "You place your fingers on the victim's neck. He is still slightly warm. "
"You are unable to locate a pulse.",
'taste': "You place two fingers in the pool of blood around the victim. Touching "
"them to your tongue immediately confirms that this is blood. You may want "
"to get tested when you get home.",
'smell': 'Smelling the body reveals the overwhelming scent of a deep musky cologne. Although... '
'you can detect hints of another less powerful smell: one that is more '
'flowery and delicate.',
'listen': "You place your ear to the victim's chest. You can hear no heartbeat.",
},
False)
sys.add_feature(F01R01)
# F02R01 the end table
F02R01 = feature.Feature('F02R01', "End Table",
'Examining the end table closer reveals nothing out of the ordinary at first. You '
'open the window to allow a beam of light to enter the room so you can get a better look. '
'The light reveals a thin layer of dust on the table, almost imperceptible. Next to the '
'candlestick is a void in the dust, where a similar shaped object appears to have been recently.',
'A small end table sits in the corner of the room near the entrance to the kitchen. '
'A single candlestick sits on top of it.',
{
'touch': 'You run a finger along the top of the end table. You feel a little bit of '
'dust between your fingers.',
'taste': 'You bend down and run your tongue along the table. It tastes as if it has '
'not been cleaned in a little while.',
'smell': 'The table smells dusty. You recoil as you begin to sneeze.',
},
False)
sys.add_feature(F02R01)
# F03R01 the rotary phone
F03R01 = feature.Feature('F03R01', "Rotary Phone",
'You examine the phone closely. It is an older model of phone, maybe from the 50s or 60s. '
'It is shiny black, although its age shows through the dulling of the glossy surface.',
'A rotary phone sits on a table near the front door of the house.',
{
'touch': 'You touch the handle of the earpiece. A layer of dust has settled on it. Clearly '
'the victim has not called anyone in quite a while.',
'taste': 'You raise the earpiece and run your tongue over the end you talk into. You '
'realize that doing this may seem a bit weird to others.',
'smell': 'The phone has no distinct smell.',
'listen': 'You bring the earpiece to your ear and listen for a second. A harsh dial tone '
'sounds in your ear as you realize you may need to input a number into the phone. '
'(Hint: Try the "call" command to call the police and end the game.)'
},
False)
sys.add_feature(F03R01)
# O02 the rusty key
O02 = object.Object('O02', 'rusty key',
'The key is quite old. Examining it in your hands reveals that it is made of some sort of metal. '
'Nearly the entire key has rusted. It is smaller than a normal door key.',
'A rusty key sits on the ground.',
{
'touch': 'The key is old and rough. The years have been unkind to it as rust has eaten '
'through the top layer of metal.',
'taste': 'The key feels rough and tastes metallic on your tongue. The only question '
'running through your mind is, "Am I up to date on my tetanus shot?"',
'smell': 'The key lacks any distinct smell.',
},
True)
sys.add_obj(O02)
# R02 The Kitchen
R02 = room.Room('R02', 'Kitchen',
"The bright whiteness of the kitchen almost blinds you. Under different circumstances, this would "
"excite you in anticipation for a weekend of great meals. However, due to Norman Bates' "
"untimely demise, the kitchen just seems cold and empty. Large stainless steel appliances sit "
"unused amongst the white marble counters.\n"
"To the west is an entrance you suspect leads to the garage.\n"
"To the southeast is an archway that leads back to the grand foyer.\n"
"To the northeast is the entrance to the dining room.",
'You enter the kitchen, glancing around to see the white countertops and stainless steel '
'appliances. To the west is the garage, to the southeast is '
'the grand foyer, and to the northeast is the dining room.'
)
R02.set_connections({
'west': 'R08', # garage
'southeast': 'R01', # grand foyer
'northeast': 'R05' # dining room
})
R02.set_features(['F01R02', # the pantry
'F02R02', # the dishes
])
R02.set_people(['P06', # Ava Scarlett (the killer)
])
R02.set_interactions({
'search': "You walk around the room, opening cabinet doors and drawers. The cabinets are filled with various "
"cooking utensils and dishes. You do not sense anything out of the ordinary.",
'touch': 'You run your hands along the cold marble counters and the warm metal top of the stove. The room has '
'been impeccably cleaned. Aside from a small pile of dishes, there is not a spot of grease to be found.',
'taste': 'You place your tongue on the marble countertop and lick, confirming that the marble has recently '
'been cleaned.',
'smell': 'The room has recently been used to cook. You can smell hints of garlic and butter wafting from the '
'dishes near the sink.',
'listen': 'You can hear the electric hum of the appliances and not much else.',
})
sys.add_room(R02)
# F01R02 pantry
F01R02 = feature.Feature('F01R02', "Pantry",
'Opening the door to the pantry and switching on the light, you can see it is well-'
'stocked. Every kind of food imaginable is stored in this pantry: boxes of pasta, bags of '
'potatoes, a bin of onions and garlic, and several large sacks of flour. Those who live '
'in the house full-time clearly do not go hungry.',
'The door to a large open pantry is cracked open. You can see many boxes of food inside.',
{
'search': 'You take a minute to comb through every box and bag in the pantry. You do not '
'notice anything out of the ordinary stored in here.',
'touch': 'You touch a few of the boxes in the pantry. It appears to be normal food.',
'taste': 'You open up a box of crackers and take one out. Examining it reveals that '
'it is a normal water cracker. You take a bite and determine that it is a '
'little bland.',
'smell': 'The pantry smells of dried food that has been stored for quite a while.',
'listen': 'You do not hear anything out of the ordinary in the pantry.',
},
False)
sys.add_feature(F01R02)
# F02R02 dishes
F02R02 = feature.Feature('F02R02', "Dishes",
'Examining the pile of dishes closely, you can see that they were recently used to cook a '
'full meal. You see several pans that have been used to cook many different things.',
'A pile of dirty dishes sits by the sink, recently used.',
{
'search': 'You look through the pile of dirty dishes, absentmindedly searching for '
'something. You see several substances stuck on the pans: bits of meat, '
'grease, purple flower petals, and veggie scraps.',
'touch': 'You touch one of the pans. It is coated in grease and oil.',
'taste': 'You take one of the pans and bring it up to your mouth, tasting the '
'substance inside it. It coats your tongue with a greasy, bitter taste '
'that takes a bit of time to dissipate.',
'smell': 'The pans smell strongly of grease.',
},
False)
sys.add_feature(F02R02)
# P06 Ava Scarlett (The Killer)
P06 = person.Person('P06', 'Ava Scarlett',
'You take a step closer to the woman who introduced herself earlier as Ava Scarlett. '
'She is in her early to mid 30s, young but with some wrinkles starting to '
'appear. She keeps her hair cut short and dyed a deep '
'shade of black with red highlights. Her makeup has been carefully done, with charcoal '
'eyeliner and red lipstick. She is wearing a patterned, dark t-shirt with jeans and '
'black boots. She only has one earring in. She seems a bit annoyed by your presence '
'as she reads a novel in a small breakfast nook near the window.',
'Ava Scarlett sits near the window in a breakfast nook reading a novel.',
{
'ask': {
'P01': "You question Ava about Alice. Ava responds, 'Well, I don't know much about her. "
"I only just met her when I got here. If you ask me, though, I think her and our "
"recently deceased host were 'well acquainted' if you know what I mean.'",
'P02': "You question Ava about Adam, the victim's son. Ava's eyebrows raise as she says, "
"'You didn't hear it from me, but I heard him and his dad fighting before we found "
"the body. I'm not sure if he's the one that killed his dad, but I can tell you "
"that they did not have the best relationship.'",
'P03': "You question Ava about Sam. She looks annoyed, stating 'I don't like that guy. "
"We arrived together, and he had a bad attitude. Not only that, but he just looks "
"like a thug. What a weird guy.'",
'P04': "You ask Ava about the gardener, Al. Ava responds, 'To be honest, I don't "
"really know much about him. He seems like a bit of a loner.'",
'P05': "You question Ava about Heather. Ava states, 'She seems pretty cheery. Kind of odd "
"that she's not more upset about the murder though, isn't it?'",
'P06': "You ask Ava about herself. 'Me?' she says. 'Well, I work as a software developer "
"at a tech company in the city. It's a lot of screen time, so every once in a while "
"I like to get out of the office and do a retreat like this one.' She pauses. 'This "
"is the first time I've been to this retreat though. I wish it could have been "
"under better circumstances...'",
'F01R01': "You question Ava about Norman. She quickly answers, 'I didn't know him "
"very well. I only spoke with him once over the phone when I called to set up "
"this weekend. I'm sorry to say, he seemed like a great guy.'",
'O01': "You ask Ava about the candlestick. Her eyes widen, and she quickly glances toward "
"the door. 'Isn't that the gaudy candlestick from the foyer? Why'd you pick it up?'",
'O05': "You question Ava about the earring. She snatches it from your hand and looks it "
"over. She says, 'Where did you find this? The bathroom, huh? I must have lost it "
"when I washed my face earlier. If it helps your investigation, you're welcome to "
"keep it until we leave.'",
'O06': "You show Ava the bloodied washcloth. She recoils. 'Gross! Keep that away from me. "
"I can't stand the sight of blood.'",
'O09': "You ask Ava about the letter. Her face goes blank. She sheepishly looks around and "
"sighs. 'Okay,' she says 'You caught me. My motives for coming here weren't exactly "
"one hundred percent genuine. Norman and I used to be lovers when I was in my "
"twenties. It didn't end well... I came here so I could confront him. I swear I'm "
"not the one who killed him though! Before I even got to talk to him, he was "
"murdered! The only reason I've been lying was because I didn't want to be pegged "
"as the killer. I'm not a bad person, I promise. You have to believe me!'",
'O11': "You ask Ava about the will. 'What's that?' she says. 'Norman's will? Does it say "
"he's giving everything to Alice? I wonder what could possess him to do something "
"like that instead of giving it to his son.'",
'O12': "You question Ava about the FBI badge. 'Oh, no way!' she says excitedly. 'Someone "
"here is an FBI agent? I wonder who it is. Wait, you don't think I'm an FBI Agent, "
"do you? I wish! That would be a great gig.'"
},
'search': 'You ask Ava if she has any belongings that could help in your investigation. '
'She turns her pockets inside out, showing that she has nothing on her. She shrugs '
"and says, 'Sorry I can't be of more help.'",
'touch': 'As you walk up to her, hand outstretched, Ava holds her hand up and says, '
"'I would prefer if you didn't.'",
'smell': 'You walk up to Ava and sniff. You smell a slightly floral perfume. As you '
'look up, Ava is staring at you with a concerned look on her face.',
'listen': 'Ava is remarkably silent as she reads her book.',
})
sys.add_person(P06)
# R03 The Library
R03 = room.Room('R03', 'Library',
'You walk into a massive double-story room lined with bookcases. Each wall is covered by books of every '
'size and color. In the center of the room is a large red fabric couch and two matching chairs. '
'Between them sits an oak coffee table.\n'
'To the southwest is the entrance to the grand foyer.\n'
'To the northwest you can see the ridiculously oversized table of the dining room.\n'
'To the north is the exit that leads outside to the patio.',
'You enter the library and marvel at the wall-to-wall bookcases filled with books. To the southwest is '
'the entrance to the grand foyer, to the northwest is the dining room, '
'and to the north is the exit leading to the patio.')
# sets the connections for the room
R03.set_connections({
'north': 'R06', # patio
'southwest': 'R01', # grand foyer
'northwest': 'R05', # dining room
# secret room is to the east, and will get added by the open command
})
R03.set_features(['F01R03', # bookcase
'F02R03', # book on table
'F03R03', # button
'F04R03', # gun
])
R03.set_people([
'P05' # Heather Poirot, the FBI Agent
])
R03.set_interactions({
'search': "You walk around the room, looking for any objects that seem out of the ordinary. You realize that you "
"may need to get a closer look at the massive bookcase if you want to find anything of interest.",
'touch': 'You run your hands along the soft green carpet of the room. It is clearly high-quality.',
'taste': 'You get on all fours and lean down to lick the carpet. You realize you probably should not have done '
'this as the carpet tastes a bit dirty.',
'smell': 'The smell of paper and old books is unmistakable. Someone has used a perfume or air freshener to make '
'the room smell a little less musty.',
'listen': 'The room is eerily quiet. Heather coughs, looking to break the uncomfortable silence.',
})
sys.add_room(R03)
# F01R03 bookcase
F01R03 = feature.Feature('F01R03', "Bookcase",
'The bookcase has books of every size and color. You absentmindedly look through the books, '
'examining them. You see a set of encyclopedias, a few classic novels, and some books on '
'nonfiction topics like horticulture and cooking.',
'A massive wooden bookcase lines the eastern wall of the room.',
{
'search': "You run your hands along the bookcase, pulling out a few books and searching "
"along the back and undersides of the shelves. You're almost ready to give up "
"when you pull out one last book, revealing a small red button behind it.",
'touch': 'You run your hands along the books. Nothing appears to be out of the ordinary. '
'You then touch a book that seems oddly stiff and out of place. Maybe you should '
'search the bookcase a little more.',
'smell': 'The bookcase smells of old wood and paper that has been sitting for a long time.',
'listen': 'The bookcase is strangely silent.',
'open': {
'unlocked': 'You grab the bookcase, using the small indented handle on the side. '
'As you pull, the bookcase easily swings away, revealing an entrance to '
'a secret room behind it.',
'locked': 'You attempt to grab the bookcase to pull on it, but you cannot get a good '
'grip on the wood around it. Maybe there is another way to open it...',
'room_ids': [['east','R04']]
},
'use': {
'F03R03': 'You press the button and hear a satisfying click as the bookshelf shifts '
'slightly toward you, revealing a small indented handle on the side. '
'Maybe the bookcase can be opened now...',
}
},
False)
F01R03.add_condition(False)
sys.add_feature(F01R03)
# F02R03 book
F02R03 = feature.Feature('F02R03', "Book",
'The book has a green cover. The title states it is a book on gardening and horticulture. '
'You take a closer look. It appears the book has a page ripped out of it in the plant '
'section.',
'A book with a green cover is sitting on the coffee table.',
{
'touch': 'The book is made of a rough paper. It appears to be some kind of organic '
'recycled material.',
'smell': 'The book smells slightly fragrant, as if it had been around flowers recently.',
'listen': 'The book does not sound like anything.',
'use': {
'O10': 'You take the piece of paper and hold it up to the torn page in the book. Although the '
'paper has been damaged by water, you are able to tell that this book is '
'where the page came from.'
},
'read': 'The book mostly talks about gardening and horticulture. Several pages cover the '
'correct times to plant and water flowers, where to plant them, and many other '
"topics that don't really interest you. You do find a torn page with some words "
"still on it. You can make out chunks of letters that spell out 'wolfs-' and "
"'poi-'.",
},
False)
sys.add_feature(F02R03)
# F03R03 button
F03R03 = feature.Feature('F03R03', "Button",
'A small, red button sits at the back of the shelf. It would be all but hidden if the '
'books were in their normal spot.',
'A button peers out from where a book used to be on the massive bookcase.',
{
'touch': 'Touching the button reveals that it is able to be pressed. (Hint: perhaps you '
"could try to 'use' the button on the bookcase.)",
},
True)
sys.add_feature(F03R03)
F04R03 = feature.Feature('F04R03', 'Gun',
'You attempt to take a closer look at the gun Heather is carrying. Unfortunately, her coat '
'hides everything beyond a brief flash of it when she moves around quickly.',
"Though she is trying to hide it, you can see the hilt of a gun peaking out of Heather's coat.",
{
},
True)
sys.add_feature(F04R03)
# P05 Heather Poirot
P05 = person.Person('P05', 'Heather Poirot',
'You take a look at Heather and scan her up and down, trying to get a read on who she is. She appears '
'middle aged, maybe early 30s. She is tall, with long brown hair pulled back into a ponytail. She '
"doesn't appear to be wearing that much makeup, and her outfit is plain as well: just a simple "
"long tan coat with jeans and brown boots. She acts a bit nervous, like she doesn't know what "
"to be doing when you walk into the room. She looks away when she notices you staring at her.",
'A woman who you recognize as Heather Poirot sits in one of the chairs, staring at the window.',
{
'ask': {
'F04R03': 'You ask Heather about the gun she is carrying. She seems surprised then responds, '
"'I was asked to come to a creepy retreat by my boss, and you expect me not to "
"bring a weapon? Clearly, I was right to come armed since someone already died. "
"I'm not the one that killed him though. He didn't die of a gunshot.'",
'P01': "You ask Heather about Alice. She responds, 'I don't know much about her. She seemed "
"really broken up by the death though. I wonder how she's doing.'",
'P02': "You ask Heather about Adam. She says, 'That guy seems like a hothead. I can't "
"believe he's the son of that kind old man.'",
'P03': "You ask Heather about Sam. She responds, 'I don't really know about that guy. He "
"seems pretty shady. I saw him snooping around the library and outside area "
"before you arrived. I wonder what he was doing.'",
'P04': "You ask Heather about Al. She states, 'The gardener? He seems nice, but I "
"noticed he was complaining about being underpaid earlier.'",
'P05': "You ask Heather about herself. She states, 'Well, I'm a single mom and I work as a "
"lawyer. My life is a little... stressful. My boss sent me on this trip in order "
"to get me away from it all. To be honest, I think it's kind of a waste of time, "
"especially since it looks like this is going to be more stressful than working, for "
"obvious reasons.'",
'P06': "You ask Heather about Ava. She responds, 'She seems off. Too calm in this situation.'",
'F01R01': "You ask Heather about the victim. 'Mr. Bates seemed really nice. He greeted me "
"at the door and seemed very excited to spend the weekend with everyone. I'm "
"surprised someone would even want to kill him...'",
'O01': "You ask Heather about the candlestick. 'Oh, man. That thing is ugly. Why are you "
"carrying it around?'",
'O05': "You question Heather about the earring. 'Oh? That's not mine. I only brought one "
"pair, and they're still in.' You check her earlobes and can see two pearl "
"earrings in place.",
'O06': "You show Heather the bloodied washcloth. She seems surprised. 'Oh!' she exclaims. "
"'Could you take that away? I really can't stand the sight of blood.'",
'O09': "You show Heather the letter. She takes a second to glance over it, blushing "
"slightly. 'This is... a little scandalous,' she says.",
'O10': "You show Heather the smudged drawing. 'Huh,' she says. 'It looks like it could "
"have been ripped out of one of the books in here.'",
'O11': "You ask Heather about the will. She says, 'Sorry, all this lawyer speak is above "
"my head. Not sure how I could help.'",
'O12': "You show the FBI badge to Heather. Her eyes widen as she pats a pocket in her "
"jacket. 'Shit!' she exclaims. 'My first big case and I manage to lose my badge,' she "
"mutters under her breath. 'Well, you caught me. I was sent here to investigate "
"Mr. Bates for tax fraud, but before I could even start the investigation, he was "
"murdered. I'm sorry for hindering the investigation, but some people tend to "
"get... angry when we reveal that we were lying to them, so I decided it was for the "
"best. Let me know if there is anything else I can do to help.'"
},
'touch': "You take a step closer to Heather and touch her arm. She recoils and jumps back, "
"surprised that you would touch her. 'Please don't do that!' she says, taking a second to "
"calm down and adjust her coat. As she is adjusting, you do see something interesting: "
"the hilt of a pistol poking through a shoulder holster under her left arm.",
'smell': 'You take a step toward Heather and sniff. She gives you a strange look and takes a '
'step back. She does not appear to be wearing any perfume.',
'listen': 'Heather does not appear to be making any noise besides the odd cough to break the '
'silence every once in a while.',
'search': 'You ask Heather if you can pat her down to check if she has any items that could '
"help the investigation. She stops you and says, 'No, if you want to search me, you're "
"going to have to have the police come here and do it themselves, sorry.'",
})
sys.add_person(P05)
# R04 Secret Room
R04 = room.Room('R04', 'Secret Room',
'You see a cold windowless room in front of you. It was clearly designated as a secret room by the '
'owner of the house. The sides of the room are made of rough brick with a wood '
'floor. The room is dark. A single lamp stands near the exit to the library. You switch it on '
'to allow yourself to get a better look at the room. The room is bare, with few decorations and '
'only a single side table and chair as furniture. \n'
'The library is behind you to the west.',
'The secret room is cold and dark. The only thing inside is some sparse furniture. '
'The library is behind you to the west.')
R04.set_features([
'F01R04', # Picture
'F02R04', # Fireplace
'F03R04', # Safe
])
R04.set_objects([
'O03', # Golden Key
'O11', # Will
])
R04.set_interactions({
'search': 'You look over every inch of the room. It does not take long since the room is already remarkably bare. '
'You do not notice anything out of the ordinary until you notice the frame to the painting is thicker '
'than it initially seems. Perhaps there is more to it than meets the eye.',
'touch': 'The room is made of rough brick and wood. It is unclear if this was a finished room or added on as an '
'expansion. Perhaps the owner of the house had it custom made.',
'smell': 'The room smells dusty. It has clearly been quite some time since it was last cleaned.',
'listen': "You listen. It is silent at first, then you hear someone speak in one of the other rooms. 'The target "
"has been eliminated. Unsure of the next actions to take,' whispers a voice you recognize as Heather "
"from the library. She appears to be talking to someone else.",
'taste': 'You touch your finger to the floor and draw a line in the dust. You bring it to your mouth and almost '
'begin to lick it before you decide it is probably not the best idea to go around tasting everything you '
'see.',
})
R04.set_connections({
'west': 'R03'
})
sys.add_room(R04)
# F01R04 painting
F01R04 = feature.Feature('F01R04', 'Painting',
'You step up to take a closer look at the painting. It is a wonderful painted portrait of '
'what appears to be the victim in his youth. '
'You notice that the frame of the painting is thicker than it should be. '
'It sticks out from the wall a good two to three inches.',
'A painting of a young man in a nice suit is on the northern wall.',
{
'search': 'As you touch the painting, you notice it has a small latch on one side and '
'hinges on the other side. '
'It appears to be hiding something behind it. '
'Perhaps you could try to open it.',
'touch': 'You run your hand along the frame of the painting. Your fingers touch '
'a latch on the side of the painting. '
'Perhaps you could open the latch.',
'open': {
'unlocked': 'The latch easily comes undone and you swing the painting open on the '
'hinges, revealing an electronic safe behind it.'
},
'smell': 'The painting smells of old paint and wood.',
'taste': 'You stick your tongue out and lick the paint. Not only does it taste bad, '
'but you likely just ruined an old, old painting.',
},
False)
F01R04.add_condition(True)
sys.add_feature(F01R04)
# F02R04
F02R04 = feature.Feature('F02R04', 'Fireplace',
'You glance at the cold fireplace. It is made of brick and flagstone with an iron grate in '
'the hearth. '
'The hearth is filled with ashes. It clearly has been used many times before without being '
'cleaned out.',
'A cold fireplace is built into the eastern wall, filled with ashes.',
{
'search': 'You sift through the ashes of the fireplace, searching for something. You '
'almost give up '
'before your dirty fingers grasp something. It appears to be a golden key.',
'touch': 'You press your hand into the ash. It appears to be cold as if it has not been '
'used in a while.',
'smell': 'The fireplace smells like burnt wood.',
'taste': 'You touch the ash and lick your fingers. You can be absolutely sure that this '
'is ash.',
'listen': 'If the fireplace was active, you would be able to hear the sound of a '
'crackling fire. '
'Currently, it is silent.',
},
False)
sys.add_feature(F02R04)
# F03R04 The Safe
F03R04 = feature.Feature('F03R04', 'Safe',
'You get a closer look at the safe. It has a simple electronic lock with a normal keypad. '
'The safe is made of strong looking steel.',
'A safe sits in the wall behind the painting that has been swung open.',
{
'use': {
'O04': 'You take the code written on the envelope and type it into the keypad on the '
'safe. It beeps three times, and the small red light on the front turns green.'
},
'open': {
'locked': 'You attempt to open the safe. It is locked up tight. You clearly need to find '
'the code in order to unlock it.',
'unlocked': 'You grasp the handle of the safe and swing it open, revealing the contents '
"of the safe: several thick, black rubber bands with '$10,000' "
"written on them in white writing and a piece of high-quality paper with "
"\"Last Will and Testament of Norman Bates\" written on it in bold lettering.",
'obj_ids': ['O11'],
},
},
True)
F03R04.add_condition(False)
sys.add_feature(F03R04)
# O03 The Golden Key
O03 = object.Object('O03', 'golden key',
'The key is large and made of high quality material. It is plated in gold with a single red gem '
'placed on the hilt of the key.',
'A golden key sits undisturbed on the floor.',
{
'touch': 'The key is made of high quality material. It is smooth to the touch.',
'smell': 'The key does not smell.',
'taste': 'The key tastes metallic.'
},
True)
sys.add_obj(O03)
# O11 The Will
O11 = object.Object('O11', "victim's will",
"The victim's will is complicated and written with very technical vocabulary. "
"Maybe you should read it if you have not already.",
"The victim's will sits, waiting to be read.",
{
'touch': 'The will is made of high-quality paper.',
'smell': 'The will smells of ink. It must have been created or edited relatively recently.',
'read': 'The will is complicated, with very technical writing. You look it over, trying to understand '
'it. It contains the normal information on what to do with the body in the event of '
'death, as well as some additional information on to whom various items have been left. '
'You skip to the bottom of the page and read an interesting line: '
"'I, Norman Bates, hereby remove any inheritance from my son, Adam Bates, and instead "
"relinquish my estate and all my remaining possessions to my dear friend and business "
"partner, Alice Stone, in the event of my death.'"
},
True)
O11.add_condition(False)
sys.add_obj(O11)
# R05 Dining Room
R05 = room.Room('R05', 'Dining Room',
'The incredibly lavish dining room is well-lit and beautifully decorated. Huge windows line the '
'northern wall, allowing you to peer into the backyard of the house. '
'A large table made of expensive dark wood sits in the center of the room, surrounded by eight chairs. '
'A fully stocked bar stands along the far west wall. Clearly, it has been well used as many of the bottles are half full.\n'
'Through an entrance to the west is the kitchen.\n'
'To the east is the library.',
'The dining room is lavish and beautiful, with a large table and a fully stocked bar at one end. '
'To the west is the kitchen, to the east is the library.')
R05.set_features([
'F01R05', # Food
'F02R05', # Glasses
])
R05.set_interactions({
'search': 'You search under the table and behind the bar. You cannot find anything out of the ordinary in this '
'room.',
'touch': 'You run your hand along the beautiful wood of the table and bar. It is smooth and sturdy.',
'smell': 'The room smells of food that has recently been cooked.',
'listen': "You attempt to listen to the room. The room is silent aside from the wind howling against the windows outside.",
'taste': 'You lick the table. It tastes of a bitter varnish.',
})
R05.set_connections({
'west': 'R02', # the kitchen
'east': 'R03', # the library
})
sys.add_room(R05)
# F01R05 The Food
F01R05 = feature.Feature('F01R05','Plate of Food',
'You examine the food more closely. It was made within the last few hours, although it '
'has long since gone cold. The steak is cooked rare with a flowery pepper cream sauce. '
'The mashed potatoes have been seasoned with garlic and bits of greenish herbs. The '
'salad is coated in an oily vinaigrette with a lot of purple flowers used as garnish. '
'Only a few bites have been taken off of the plate.',
'A plate of food sits barely touched on the table.',
{
'touch': 'The food has long since gone cold.',
'taste': 'The food tastes off somehow. The steak is cooked rare, and the rest of the food '
'is well seasoned, but there is a bitter aftertaste that holds in the back of '
'your mouth as you try a bite of the salad.',
'smell': 'The food smells delicious. You almost want to take a bite to try it for yourself.',
'search': 'Combing through the mashed potatoes and salad with a fork does not reveal '
'anything hidden within, although, for some reason, the purple flowers strike '
'you as odd.'
},
False)
sys.add_feature(F01R05)
# F02R05 The Glasses
F02R05 = feature.Feature('F02R05','Glasses',
'You examine the glasses on the bar more closely. Both are half full--one with a red liquid '
'and the other with an amber colored liquid. The glass with the red liquid appears to '
'have lipstick on the rim of the glass.',
'Two glasses rest on the bar, each half empty.',
{
'touch': 'The glasses are warm to the touch. They have been sitting out for a while.',
'taste': 'You individually bring each of the glasses to your lips, tasting the liquids '
'inside. The red glass contains a bitter red wine, while the amber glass contains '
'a slightly watered down sweet whiskey.',
'smell': 'It quickly becomes very clear to you as you bring the glasses to your nose that '
'these drinks are alcoholic.',
},
False)
sys.add_feature(F02R05)
# This command saves the base files in the game
sys.save_base_game_files()
|
308c51376ab2720cbad7b0392829d99ba787b2af
|
GuilhermeSilvaCarpi/exercicios-programacao
|
/treinamento progrmação/Python/cursoemvideo/exercicios/ex036.py
| 500 | 3.734375 | 4 |
#aula 12
#inputs
vCasa = float(input('valor de casa pra comprar: '))
vSalario = float(input('salário de um hipotético comprador: '))
quantosAnos = int(input('anos de financiamento da casa: '))
#calculo prestação
prestacao = vCasa / (quantosAnos * 12)
print('para pagar uma casa de R${:.2f} em {} anos a prestação da casa será de R${:.2f}'.format(vCasa,quantosAnos,prestacao))
#aprovação da compra
print('emprestimo aprovado'if prestacao <= (vSalario / 100 * 30) else'emprestimo negado')
|
a7998e1dc29363b6cd19ced788534097a6eb44ee
|
sunquan9301/pythonLearn
|
/day8/Student.py
| 428 | 3.71875 | 4 |
class stu:
def __init__(self, name, age):
self.name = name
self.__age = age
def study(self, subject):
print('I am studying class %s' % subject)
# 访问器 - getter方法
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
def info(self):
print('my name is %s,I am %s year old' % (self.name, self.__age))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.