blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
22de806668c99419b3de64c23f91b450aeafcd73
brittani-ericksen/dec2020-dir
/week_01/python2/small_exercises.py
383
4.03125
4
# python 102 small exercises numbers = [-2, -1, 0, 1, 2, 3, 4, 5, 6] #1 sum of numbers sum_of_all_numbers = sum(numbers) #print(sum_of_all_numbers) #2 largest number max_number = max(numbers) #print(max_number) #3 smallest number min_number = min(numbers) #print(min_number) #4 even numbers #5 positive numbers #6 positive numbers 2 #7 multiply a list #8 reverse a string
69c622768ed49e6180ddd9484322d528fdc784ad
kuralayenes/PythonUygulama
/Uygulama11.py
624
3.5
4
rs = input("Romen rakamlarıyla sayıyı giriniz: ") k1 = 0 sy = 0 print("\n") for i in range(0,len(rs),1): k2 = k1 deger = rs[i] if (deger == 'I'): k1 = 1 elif (deger == 'V'): k1 = 5 elif (deger == 'X'): k1 = 10 elif (deger == 'L'): k1 = 50 elif (deger == 'C'): k1 = 100 elif (deger == 'D'): k1 = 500 elif (deger == 'M'): k1 = 1000 if (k1 > k2): k3 = -2 * k2 else: k3 = 0 sy = sy + k1 + k3 print("sayi = ", sy)
f8a5b047d10bb1fdf12283857e226b4c4b31774e
tcarrio/cse233-dicts-sets
/prog3.py
1,755
3.859375
4
# Author: Tom Carrio # Course: CSE-233 import sys def setup_files(): if(len(sys.argv)==4): infile=sys.argv[2] outfile=sys.argv[3] return infile,outfile else: fail_message("Not the correct number of args") return def setup_ciphers(): tmp_cipher=[c for c in "lpDzQ2FEnOJXCHAPc8Rb16j5i3LogGBU7Im0V9duYsyTa4KSxveh"] encCipher={} decCipher={} for letter,offset in {'a':0,'A':26}.items(): for i in range(26): encCipher[letter]=tmp_cipher[i+offset] decCipher[tmp_cipher[i+offset]]=letter letter=chr(ord(letter)+1) encCipher['__type']="encrypt" decCipher['__type']="decrypt" return (encCipher,decCipher) def do_the_thing(cipher,readfile,writefile): f=open(readfile,'r') o=open(writefile,'w') fin=f.read() print("File in:\n{}".format(fin)) for c in fin: o.write(cipher.get(c,c)) f.close() o.close() with open(writefile,'r') as fout: print("File out:\n{}".format(fout.read())) def fail_message(msg=""): print("You have input functionality that is not supported") print("Error: {}".format(msg)) print("""The syntax to this command is: python 3.py [encrypt/decrypt] fileIn fileOut""") def main(): if(sys.argv[1]=='encrypt'): this_cipher=setup_ciphers()[0] elif(sys.argv[1]=='decrypt'): this_cipher=setup_ciphers()[1] else: fail_message("Not a valid option") return try: print("The cipher type in use is '{}''".format(this_cipher['__type'])) infile,outfile=setup_files() do_the_thing(this_cipher,infile,outfile) except Exception as e: fail_message("Failed in using files, {}".format(str(e))) return if __name__ == "__main__": main()
2413127b081dc6fddf49bec5ee1e545a1047f6a1
caylemh/Python
/chapter_6/pg171_TryItYourself.py
3,737
4.15625
4
# People - Create a list(people) of dictionaries (person_*) and display them print('People and their info:') person_0 = { 'firstname': 'Caylem', 'lastname': 'Harris', 'age': 36, 'city': 'JHB', } person_1 = { 'firstname': 'Courtney', 'lastname': 'Alexander', 'age': 17, 'city': 'JHB', } person_2 = { 'firstname': 'Tatenda', 'lastname': 'Kumbula', 'age': 18, 'city': 'JHB', } people = [person_0, person_1, person_2] for person in people: print(f'\t{person}') # Pets - Create a list(pets) of dictionaries (animal_*) and display them print('\nPets and their owners:') animal_0 = { 'type': 'cat', 'owner': 'angie', } animal_1 = { 'type': 'dog', 'owner': 'tatenda', } animal_2 = { 'type': 'monkey', 'owner': 'ruben', } pets = [animal_0, animal_1, animal_2] for animal in pets: print(f'\t{animal}') ''' Favourite Places - making a list(places) for each key(person) in the dictionary (favourite places) ''' print('\nPeople and their favourite places:') favorite_places = { 'caylem': ['peru', 'bora bora'], 'mpho': ['lagos'], 'juan': ['antigua bay', 'seychelles', 'taiwan'], } for person, locations in favorite_places.items(): if len(locations) < 2: print(f'\n\t{person.title()}\'s favourite location is: ') else: print(f'\n\t{person.title()}\'s favourite locations are: ') for location in locations: print(f'\t\t{location.title()}') # Favourite Numbers print('\nPeople and their favourite numbers:') favorite_nums = { 'caylem': [7,8,10], 'courtney': [13,16,33], 'juan': [21,5], 'ruben': [27,17], 'vusi': [12,24,30], } for person, numbers in favorite_nums.items(): print(f'\n\t{person.title()}\'s favourite numbers are: ') for number in numbers: print(f'\t\t{number}') # Cities print('\nCities and their information:') cities = { 'lima': {'country': "peru", 'population':40000, 'fact': 'Three-quarters ' 'of the world\'s alpaca population lives in Peru. The national animal is\n' '\t\t\tthe vicuna, a small camelid similar to the alpaca. It comes in 22 natural\n' '\t\t\tcolors and its wool is considered the world\'s most luxurious fabric.', }, 'victoria': {'country': 'seychelles', 'population':98000, 'fact': 'Some of ' 'the rarest species of birds can be found in Seychelles, including the\n' '\t\t\tbare-legged Scops Owl or Syer.', }, 'abuja': {'country': 'nigeria', 'population':201000, 'fact': 'The country\'s' ' film industry, known as Nollywood, is one of the largest film producers\n' '\t\t\tin the world, second only to India\'s Bollywood.', }, } for city, info in cities.items(): country = info['country'].upper() population = info['population'] fact = info['fact'] print(f'\n\tWelcome to {city.title()}, in {country}.\n') print(f'\tPopulation:\t{population}') print(f'\n\tFact:\t{fact}.\n') # Extensions print('\nExtending the \'favourite_languages.py\' program:') favorite_languages = { 'jen': { 'language': ['python', 'c++'], 'experience': 8, }, 'sarah': { 'language': ['ruby'], 'experience': 5, }, 'edward': { 'language': ['c++'], 'experience': 2, }, 'phil': { 'language': ['python', 'ruby'], 'experience': 6, }, } for name, lang_info in favorite_languages.items(): language = lang_info['language'] exp = lang_info['experience'] if len(language) < 2: print(f'\n{name.title()}\'s favorite language is:') else: print(f'\n{name.title()}\'s favorite languages are:') print(f'\tLanguage:\t{language}') print(f'\tExperience:\t{exp}')
38eaf2876b6aaec5b3d3fa39722bee69a7f64583
saeidp/Data-Structure-Algorithm
/Stack and Queue/StackDecimalToMultipleBase.py
821
3.90625
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) class DecimalToMultipeBase: def convert(self, num, numBase): digits = Stack() while True: digits.push(num % numBase) num //= numBase if(num== 0): break while digits.isEmpty() != True: print(digits.pop(), end='') decimalToBase = DecimalToMultipeBase() decimalToBase.convert(12, 10) # 1 2 print() decimalToBase.convert(12, 2) # 1 1 0 0
bec5371bf938991bca1eb5b42bed4409513e2d92
swaraj1999/python
/chap 4 function/greatest_function.py
441
4.25
4
# to find the greatest number #function inside function def greater(a,b): if a>b: return a return b #it is finding the greater function in two number def greatest(a,b,c): return greater(greater(a,b),c) #it will find among three print(greatest(100000000,200,1200)) #we can do it withoput calling greater ; its an example of function inside a function
68d30964085fd5a3802bfd83ba93aea64ea7b1cb
nbuyanova/stepik_exercises
/exercise_2_6__1.py
757
4.21875
4
# Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел # не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел. # # Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать # не нужно. a = int(input()) if a == 0: print(a * a) else: s = a s2 = a * a while s != 0: a = int(input()) s += a s2 += a * a print(s2)
8f8d61a23e300797e5d9ec658a2cbd37e9f84dfe
Stefiya/python
/upper.py
148
3.6875
4
a=input("enter a word") class A: def __init__(self,upper): self.upper=upper def up(self): print(a.upper()) d=A(a) d.up()
2c62d333a823eae6bedaa93e22e7923fc2c526d1
spoty/Checkio
/MINE/08_Painting_wall.py
3,159
3.671875
4
# from bisect import bisect_left # def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi # hi = hi or len(a) # hi defaults to len(a) # pos = bisect_left(a,x,lo,hi) # find insertion position # return pos if pos != hi and a[pos] == x else -1 # don't walk off the end # def checkio(required, operations): # l = [] # for i, x in enumerate(operations): # for y in xrange(x[0],x[1]+1): # if binary_search(sorted(l),y) == -1: # l.append(y) # if len(l) >= required: return i + 1 # return -1 def checkio(num, data): numbers = sorted([n for start, end in data for n in (start, end + 1)]) segments = [(n1, n2 - 1) for n1, n2 in zip(numbers[:-1], numbers[1:])] painted = set() for i, (start, end) in enumerate(data): painted |= {(s, e) for s, e in segments if start <= s and e <= end} if sum([e - s + 1 for s, e in painted]) >= num: return i + 1 return -1 from bisect import bisect def count_painted(ranges): """ Precondition: ranges has even number of elements """ return sum(r - l + 1 for l, r in zip(ranges[::2], ranges[1::2])) def checkio(required, operations): painted_ranges = [] # it contains ranges as a flat list for step, op in enumerate(operations): left, right = op left_index = bisect(painted_ranges, left) right_index = bisect(painted_ranges, right) if left_index % 2: if not right_index % 2: painted_ranges.insert(right_index, right) else: painted_ranges.insert(left_index, left) left_index += 1 if not right_index % 2: painted_ranges.insert(right_index + 1, right) right_index += 1 painted_ranges = painted_ranges[:left_index] + painted_ranges[right_index:] print painted_ranges if count_painted(painted_ranges) >= required: return step + 1 return -1 # from itertools import accumulate # def painted(ranges): # last = counter = total = 0 # for pos, d in sorted(sum((((i-1, +1), (j, -1)) for (i, j) in ranges), ())): # if counter: # total += pos - last # counter += d # last = pos # return total # def checkio(num, ranges): # for i, prefix in enumerate(accumulate([i] for i in ranges), start=1): # if painted(prefix) >= num: # return i # return -1 #print checkio(5, [[1,5], [11,15], [2,14], [21,25]]) == 1 # The first operation will paint 5 meter long. #print checkio(6, [[1,5], [11,15], [2,14], [21,25]])# == 2 # The second operation will paint 5 meter long. The sum is 10. # checkio(11, [[1,5], [11,15], [2,14], [21,25]]) == 3 # After the third operation, the range 1-15 will be painted. print checkio(16, [[1,5], [11,15], [2,14], [21,25]]) == 4 # Note the overlapped range must be counted only once. #checkio(21, [[1,5], [11,15], [2,14], [21,25]]) == -1 # There are no ways to paint for 21 meters from this list. #print checkio(111, [[1, 100], [11, 110]]) == -1 # One of the huge test cases.
71b438d41458431f9cad540083ad717687fe0edf
JacobRammer/CIS122
/assignments/Assignment 4/cis122-assign04-yearday-v2.py
9,713
4.375
4
''' CIS 122 Fall 2018 Assignment 4 Author: Jacob Rammer Partner: None Description: Assignment 4 version 2 ''' def is_leap_year(year): """Determine is inputted year is a leap year Tests if year is a leap year Args: year (Int): information to test Returns: True if true or False if false """ if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True return True else: return False def valid_year(year): """Validates year validates that year is greater than 0. If not, prints error message Args: year (Int): year that is being tested Returns: True if year is greater than 0. False for all other situations """ if year > 0: return True else: print("Year must be > 0") return False def valid_day_of_year(year, day_of_year): """validates that the day of the year is valid validates that day of the year is greater than 0 Args: year (Int): Not used. Just coded since it was included in instructions day_of_year (Int): number to be tested to see if it's greater than 0 Returns: True if day_of_year is greater than 0. False for all other situations """ if day_of_year > 0: return True else: print("Day of year must be > 0") return False def input_year(): """Input the year Prompt the user to input the year Returns: year as an integer. Else 0 if year is not valid """ year = int(input("Enter year: ")) while year <= 0: print("Day of year must be > 0") year = int(input("Enter year: ")) if valid_year(year) is True: return year def get_days_in_year(year): """Get number of days in year Get the day of the year depending on if year is a leap year or not Args: year (Int): Year to be tested for leap year status Returns: Day of year as an integer. 0 for unknown situations """ if is_leap_year(year) is True: return 366 if is_leap_year(year) is False: return 365 else: return 0 def input_day_of_year(year): """input the day of the year Prompt the user to input year and validate input Args: year (Int): Uses the year from input_year to determine if day inputted is valid Returns: day as an integer, or 0 if input is invalid """ day = int(input("Enter day of year: ")) if is_leap_year(year) is True: while day > get_days_in_year(year) or day <= 0: while day > get_days_in_year(year): print("Day must be <= 366") day = int(input("Enter day of year: ")) while day <= 0: print("Day must be > 0") day = int(input("Enter day of year: ")) if valid_year(year) and valid_day_of_year(year, day) and day <= get_days_in_year(year): return day elif is_leap_year(year) is False: while day > get_days_in_year(year) or day <= 0: while day > get_days_in_year(year): print("Day must be <= 365") day = int(input("Enter day of year: ")) while day <= 0: print("Day must be > 0") day = int(input("Enter day of year: ")) if valid_year(year) and valid_day_of_year(year, day) and day <= get_days_in_year(year): return day else: return 0 def valid_month(month): """Determines if month is valid Not used. Nut function determine if month value is between 1 and 12 Args: month (Int): Month to test Returns: True if month is valid, False if month is not valid """ if 0 < month <= 12: return True elif month <= 0: print("Month must be > 0") return False elif month >= 12: print("Month must be <= 12") return False def translate_month(month): """Translate the month Not used. But will translate month depending on the inputted value Args: month (Str): Associate month with correct month string Returns: Month as a string """ if valid_month(month) is True: if month == 1: return "January" elif month == 2: return "February" elif month == 3: return "March" elif month == 4: return "April" elif month == 5: return "May" elif month == 6: return "June" elif month == 7: return "July" elif month == 8: return "August" elif month == 9: return "September" elif month == 10: return "October" elif month == 11: return "November" elif month == 12: return "December" else: return '' def get_days_in_month(year, month): """Get days in a month based on input Not used. Will return the days in each month based if the date is a leap year or not Args: year (Int): Will test if year is a leap year ot not month (Int): Tests the value of each month Returns: Day of month as an integer """ if month == 1: return 31 elif is_leap_year(year) is True and valid_month(month) is True and month == 2: # If it's a leap year return 29 elif is_leap_year(year) is False and valid_month(month) is True and month == 2: # If it's not a leap year return 28 elif month == 3: return 31 elif month == 4: return 30 elif month == 5: return 31 elif month == 6: return 30 elif month == 7: return 31 elif month == 8: return 31 elif month == 9: return 30 elif month == 10: return 31 elif month == 11: return 30 elif month == 12: return 31 else: return 0 def valid_day(year, month, day): """Determine if the date string is valid Test to see if valid_year, valid_month, and valid_day_of_year is True Args: year (Int): Year to test id valid month (Int): Month to test if valid day (Int): Day to test if valid Returns: True if true, False if false """ if valid_year(year) is True and valid_month(month) is True and valid_day_of_year(year, day) is True: return True else: return False def get_date_string(year, month, day): """Print the date Print the date as a string based upon user input. Tests user input to see what the string is Args: year (Int): Year to print in string month (Str): Month to print in string day (Int): Day to print in string Returns: void """ if is_leap_year(year) is True and valid_year(year) is True: if (day == 1) or (day <= 31): month = "January" elif (day == 32) or (day <= 60): month = "February" day = day - 31 elif (day == 61) or (day <= 91): month = "March" day = day - 60 elif (day == 92) or (day <= 121): month = "April" day = day - 91 elif (day == 122) or (day <= 152): month = "May" day = day - 121 elif (day == 153) or (day <= 182): month = "June" day = day - 152 elif (day == 183) or (day <= 213): month = "July" day = day - 182 elif (day == 214) or (day <= 244): month = "August" day = day - 213 elif (day == 245) or (day <= 274): month = "September" day = day - 244 elif (day == 275) or (day <= 305): month = "October" day = day - 274 elif (day == 306) or (day <= 335): month = "November" day = day - 305 elif (day == 336) or (day <= 366): month = "December" day = day - 335 print(month, str(day) + ",", year) if is_leap_year(year) is False and valid_year(year) is True: if (day == 1) or (day <= 31): month = "January" elif (day == 32) or (day <= 59): month = "February" day = day - 31 elif (day == 60) or (day <= 90): month = "March" day = day - 59 elif (day == 91) or (day <= 120): month = "April" day = day - 90 elif (day == 121) or (day <= 151): month = "May" day = day - 120 elif (day == 152) or (day <= 181): month = "June" day = day - 151 elif (day == 182) or (day <= 212): month = "July" day = day - 181 elif (day == 213) or (day <= 243): month = "August" day = day - 212 elif (day == 244) or (day <= 273): month = "September" day = day - 243 elif (day == 274) or (day <= 304): month = "October" day = day - 273 elif (day == 305) or (day <= 334): month = "November" day = day - 304 elif (day == 335) or (day <= 365): month = "December" day = day - 334 print(month, str(day) + ",", year) def start(): """Brings together all functions Calls all functions needed to complete program Returns: Void """ month = get_date_string year = input_year() get_date_string(year, month, input_day_of_year(year)) start() # valid_day(2020, 2, 20) # print(input_day_of_year(input_year())) # input_year() # print(valid_day_of_year(2020, 2020))
3b5260f915b40e19b1f2a23b67e9ac35baf9b434
SulabhAgarwal007/Python_Machine_Learning
/Bokeh/Bokeh_Select_Dropdown.py
1,398
3.609375
4
# Perform necessary imports from bokeh.models import ColumnDataSource, Select from bokeh.plotting import figure from bokeh.io import curdoc from bokeh.layouts import row import pandas as pd data = pd.read_csv('literacy_birth_rate.csv') fertility = data['fertility'].values female_literacy = data['female literacy'] population = data['population'] # Create ColumnDataSource: source source = ColumnDataSource(data={ 'x': fertility, 'y': female_literacy }) # Create a new plot: plot plot = figure() # Add circles to the plot plot.circle('x', 'y', source=source) def update_plot(attr, old, new): # Define a callback function: update_plot # If the new Selection is 'female_literacy', update 'y' to female_literacy if new == 'female_literacy': source.data = { 'x': fertility, 'y': female_literacy } # Else, update 'y' to population else: source.data = { 'x': fertility, 'y': population } # Create a dropdown Select widget: select select = Select(title="distribution", options=['female_literacy', 'population'], value='female_literacy') # Attach the update_plot callback to the 'value' property of select select.on_change('value', update_plot) # Create layout and add to current document layout = row(select, plot) curdoc().add_root(layout)
829804bcf14a0aec6ec9a95042040760578d27fc
yosuke-ippo/Atcoder
/submissions/abc201/b.py
238
3.53125
4
N = int(input()) yama_list =[] for i in range(N): namae, takasa = input().split() takasa = int(takasa) yama_list.append([namae,takasa]) ans_list = sorted(yama_list, reverse= True, key=lambda x: x[1]) print(ans_list[1][0])
cdbb96e8d7a25f82e492f84c9f1f6340dfd7145d
miriamnwachukwu/TestRepo
/Script.py
321
3.96875
4
greeting = 'Hello' name = 'Michael' message = greeting + ', ' + name + '. Welcome!' #message = f'{greeting}, {name}. Welcome!' print(f'The value of pi is approximately {name}.') print(message) # x = '''Bobby was a good kid # until he got to university''' # print(x) # print(help(str)) #new line #another new line
543e64f2c1cef0715a989453659eac6447b7d52e
mrapacz/ntgen
/ntgen/utils.py
2,133
3.9375
4
import re from typing import Optional def normalize_field_name(name: str, leading_undescores_prefix: Optional[str] = None) -> str: """ Normalize a string to take a Pythonic form. Normalize a string to take a Pythonic form by: - replacing leading underscores with a given (optional) prefix - converting the name so snake_case """ return convert_to_snake_case(replace_leading_underscores(name, prefix=leading_undescores_prefix)) def convert_to_snake_case(name: str) -> str: """ Convert a given string to snake_case. Converts a given string to snake_case from camel case or kebab case >>> normalize_field_name('SomeCamelCase') 'some_camel_case' >>> normalize_field_name('sample-kebab-case') 'sample_kebab_case' """ return re.sub(r"(?<!^)(?=[A-Z])", "_", name).replace("-", "_").lower() def normalize_class_name(name: str) -> str: """ Normalize class name by converting it to PascalCase. >>> normalize_class_name('some_hyphen_case') 'SomeHyphenCase' """ if re.match(r"(?:[A-Z][a-z]+)+", name): return name return "".join([fragment.capitalize() for fragment in normalize_field_name(name).split("_")]) def replace_leading_underscores(name: str, prefix: Optional[str] = None) -> str: """ Replace leading underscores with a given prefix. Replaces leading underscores with a given prefix. If no prefix is specified, the leading underscores are removed. >>> replace_leading_underscores('_private_field') 'private_field' >>> replace_leading_underscores('__private_field', prefix='dunder') 'dunder_private_field' """ return re.sub(r"^_+", f"{prefix}_" if prefix else "", name) def indent_statement(indent: int, statement: str) -> str: """ Indents the given string by a specified number of indents. Indents the given string by a specified number of indents, e.g. indenting by 1 will preprend the string with 4 space characters: >>> indent_statement(0, 'x = 3') 'x = 3' >>> indent_statement(1, 'x = 3') ' x = 3' """ return " " * 4 * indent + statement
75ff28ffa6678faffa6608e069c351e5449ac274
ctanamas/cs50_houses
/import.py
822
3.90625
4
# Imports needed classes import csv from sys import argv, exit from cs50 import SQL def main(): # Checks correct usage if len(argv) != 2: print("Usage: python import.py data.csv") exit(1) # Opens the csv and the database db = SQL("sqlite:///students.db") with open(argv[1], "r") as file: reader = csv.DictReader(file) for row in reader: # Insert the names names = row["name"].split(" ") first = names[0] middle = None last = names[len(names) - 1] if len(names) == 3: middle = names[1] db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, row["house"], int(row["birth"])) main()
3754a73176e4f14f402a1808e474ef661fd18757
nickeyinho/Python_course
/PY1_Lesson_2.1/week_temperature_by_city.py
550
3.765625
4
# пример того, как читать сложные файлы # pretty print - красивое печатет словари, списки и пр. from pprint import pprint cities = {} with open('week_temperature.txt') as f_week_temperature: for city in f_week_temperature: temperatures = f_week_temperature.readline() cities[city.strip()] = temperatures.split() # pprint(cities) for city, temperatures in cities.items(): avg = 0 for t in temperatures: avg += int(t) avg = avg / len(temperatures) print (city, "%.2f" % avg)
cd827ea903961d564401166da589fc460ad1a888
nestor2502/Modelado
/python/oop.py
391
3.828125
4
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first+'.'+last+'@company.com' def fullName(self): return '{} {}'.format(self.first,self.last) emp_1 = Employee('Corey', 'schafer', 5000) emp_2 = Employee('vazquez', 'nestor', 6000) #print(emp_1.email) #print(emp_1.fullName()) print(Employee.fullName(emp_2))
95c656aae6a654a20dd08a344dbedc6463abbb3c
vavronet/python-for-beginners
/functions/examples/example_5.py
343
4.0625
4
import datetime def greetings(): now = datetime.datetime.now() hour = now.hour if hour <= 11 and hour >= 3: return 'Good morning' elif hour >= 12 and hour <= 18: return 'Good afternoon' elif hour >= 19 and hour <= 21: return 'Good evening' else: return 'Good night' print(greetings())
aa75186085b3d22af2778dfd33352fd0166661c5
umeshgeeta/Python
/FindPathsInGraph.py
4,993
3.859375
4
# author: Umesh Patil # November 9, 2019 # Finds number of paths and cycles in a random generated graph. Edge is redirections. # When a value in the adjecancy graph cell [i][j] is > -1; it means there is an edge # goinf from 'i' node to 'j' node. Nodes will be numbered from 0 to m-1 for m nodes graph. # # Assumptions: # 1. We want to go from Node '0' to Node 'size -1'. # imports random module import random # Creates a 2 dimensional array initialized to 0. def matrix(size): # Creates a list containing size lists, each of size items, all set to 0 w, h = size, size; matrix = [[-1 for x in range(w)] for y in range(h)] return matrix # Prints the matrix as m lines, each with m columns separated by a single space. def printmatrix(m, size): for i in range(size): line = '' for j in range(size): line = line + str(m[i][j]) + ' ' print(line) def createrandomgraph(m, size, edgecount): edge = 0 while edge < edgecount: i = random.randrange(0, size) j = random.randrange(0, size) while i == j: j = random.randrange(0, size) if m[i][j] < 0: m[i][j] = 0 edge = edge + 1 def findzeroinrow(m, size, row, nonexhaustednodes): col = -1 j = 0 while col < 0 and j < size: #print('m['+str(row)+']['+str(j)+'] ='+str(m[row][j])) if m[row][j] == 0: col = j j = j + 1 added = False while j < size and not added: if m[row][j] == 0: #there are more edges to be explored from this node nonexhaustednodes.add(row) added = True j = j + 1 return col def findunexplorededge(m, size, row, exhaustedsegments): print('exhaustedsegments ' + str(exhaustedsegments)) unexplorededge = -1 j = 0 while unexplorededge < 0 and j < size: segid = m[row][j] if segid > -1 and segid not in exhaustedsegments: unexplorededge = j # note it is the destination of that non-exhausted edge j = j + 1 return unexplorededge # Whether we do backtracking or always forward going; in the end number of steps will be same. # As more and more paths get traversed, edges which are not considered will be harder to find. # We use adjacency graph to comput the paths. Basically, starting from Node 0, keeping trying # to find a fresh path. As you traverse, 'segments' (set of edges) are numbered. The actual # path can be one single segment (i.e. one single > 0 number) or combination of multiple # segments. We continue to find path until we come to know that there are no more nodes left # with '0' edge - STARTING FROM NODE 0. def traversegraph(m, size): pathsfound = [] cyclesfound = [] crtsegmentid = 0 exhaustedsegments = set() nonexhaustednodes = set() # add the starting node nonexhaustednodes.add(0) # keep identifying new segments and path until there are no more nodes with # non-travelled edges iteration = 1 while len(nonexhaustednodes) > 0: print('run: ' + str(iteration)) print(nonexhaustednodes) crtsegmentid = crtsegmentid + 1 curpath = set(); done = False currow = 0 # always start from node 0 lastedge = -1 while not done: curpath.add(currow) zerocol = findzeroinrow(m, size, currow, nonexhaustednodes) print('findzeroinrow: ' + str(zerocol)) if zerocol == -1: # we did not find any unexplored edge # we will have to pick an edge which down the line has atleast # some part unexplored zerocol = findunexplorededge(m, size, currow, exhaustedsegments) if zerocol == -1: # we are done here, it is a dead end; we cannot go anywhere done = True # for the current node either there are any zeros nor any non-exhausted edges # we need to remove it from the nonexhausted node list nonexhaustednodes.remove(currow) print('removed ' + str(currow)) else: if m[currow][zerocol] == lastedge and lastedge > -1: print ('actually we are done with this edge since it did not yield any zeros') exhaustedsegments.add(lastedge) done = True else: lastedge = m[currow][zerocol] print('findunexplorededge: ' + str(zerocol) + ' edge is: ' + str(lastedge)) currow = zerocol else: # clear out any edge used since we did find zero lastedge = -1 m[currow][zerocol] = crtsegmentid # are we at destination? if zerocol == size-1: # we have reached our destination, this the 'path' print('reached destination') pathsfound.append(curpath) ##we are done here done = True else: if zerocol in curpath: # we got a cycle print('got cycle') curpath.add(zerocol) cyclesfound.append(curpath) done = True else: # we have to still to move forward print('keep moving') currow = zerocol iteration = iteration + 1 if iteration == 25: print('going in the loop probably...') done = True print('found cycles:') print(cyclesfound) print('found paths:') print(pathsfound) size = 3 # no edge from 0th element m = [[-1, 0, -1], [-1, -1, 0], [-1, -1, -1]] printmatrix(m, size) traversegraph(m, size)
00a16a27332244fd3aad683f1630c71fc9acbde3
LucasLeone/tp1-algoritmos
/estructura_secuencial/es5.py
435
4.03125
4
''' Si un lote de terreno tiene X metros de frente por Y metros de fondo: calcular e imprimir la cantidad da metros de alambre para cercarlo. (X e Y serán leídos al comenzar el programa). ''' x = float(input('Cuantos metros de frente tiene el terreno? ')) y = float(input('Cuantos metros de fondo tiene el terreno? ')) total = (x*2 + y*2) print('La cantidad de metros de alambre que se va a necesitar es: ', total)
864f3525b6108ea7eb7bd987748ad65ec40c5c14
bqth29/simulated-bifurcation-algorithm
/src/simulated_bifurcation/simulated_bifurcation.py
33,248
3.625
4
""" Module defining high-level routines for a basic usage of the simulated_bifurcation package. Available routines ------------------ optimize: Optimize a multivariate degree 2 polynomial using the SB algorithm. minimize: Minimize a multivariate degree 2 polynomial using the SB algorithm. maximize: Maximize a multivariate degree 2 polynomial using the SB algorithm. build_model: Instantiate a multivariate degree 2 polynomial over a given domain. """ import re from typing import Tuple, Union import torch from numpy import ndarray from .polynomial import ( BinaryPolynomial, IntegerPolynomial, IsingPolynomialInterface, SpinPolynomial, ) def optimize( matrix: Union[torch.Tensor, ndarray], vector: Union[torch.Tensor, ndarray, None] = None, constant: Union[int, float, None] = None, input_type: str = "spin", dtype: torch.dtype = torch.float32, device: str = "cpu", agents: int = 128, max_steps: int = 10_000, best_only: bool = True, ballistic: bool = False, heated: bool = False, minimize: bool = True, verbose: bool = True, *, use_window: bool = True, sampling_period: int = 50, convergence_threshold: int = 50, ) -> Tuple[torch.Tensor, Union[float, torch.Tensor]]: r""" Optimize a multivariate degree 2 polynomial using the SB algorithm. The simulated bifurcated (SB) algorithm is a randomized approximation algorithm for combinatorial optimization problems. The optimization can either be a minimization or a maximization, and it is done over a discrete domain specified through `input_type`. The polynomial is the sum of a quadratic form and a linear form plus a constant term: `ΣΣ Q(i,j)x(i)x(j) + Σ l(i)x(i) + c` or `x.T Q x + l.T x + c` in matrix notation, where `Q` is a square matrix, `l` a vector a `c` a constant. Parameters ---------- matrix : (M, M) Tensor | ndarray Matrix corresponding to the quadratic terms of the polynomial (quadratic form). It should be a square matrix, but not necessarily symmetric. vector : (M,) Tensor | ndarray | None, optional Vector corresponding to the linear terms of the polynomial (linear form). The default is None which signifies there are no linear terms, that is `vector` is the null vector. constant : int | float | None, optional Constant of the polynomial. The default is None which signifies there is no constant term, that is `constant` = 0. input_type : {"spin", "binary", "int(\d+)"}, default=spin Domain over which the optimization is done. • "spin" : Optimize the polynomial over vectors whose entries are in {-1, 1}. • "binary" : Optimize the polynomial over vectors whose entries are in {0, 1}. • "int(\d+)" : Optimize the polynomial over vectors whose entries are n-bits non-negative integers, that is integers between 0 and 2^n - 1 inclusive. "int(\d+)" represents any string starting with "int" and followed by a positive integer n, e.g. "int3", "int42". dtype : torch.dtype, default=torch.float32 Data-type used for running the computations in the SB algorithm. device : str | torch.device, default="cpu" Device on which the SB algorithm is run. If available, use "cuda" to run the SB algorithm on GPU (much faster, especially for high dimensional instances or when running the algorithm with many agents). agents : int, default=128 Number of simultaneous execution of the SB algorithm. This is much faster than sequentially running the SB algorithm `agents` times. max_steps : int, default=10_000 Number of iterations after which the algorithm is stopped regardless of whether convergence has been achieved. best_only : bool, default=True If True, return only the best vector found and the value of the polynomial at this vector. Otherwise, returns all the vectors found by the SB algorithm and the values of polynomial at these points. ballistic : bool, default=False Whether to use the ballistic or the discrete SB algorithm. See Notes for further information about the variants of the SB algorithm. heated : bool, default=False Whether to use the heated or non-heated SB algorithm. See Notes for further information about the variants of the SB algorithm. minimize : bool, default=True If True, minimizes the polynomial over the specified domain. Otherwise, the polynomial is maximized. verbose : bool, default=True Whether to display a progress bar to monitor the progress of the algorithm. Returns ------- result : ([`agents`], M) Tensor Best vector found, or all the vectors found is `best_only` is False. evaluation : float | (`agents`) Tensor Value of the polynomial at `result`. Other Parameters ---------------- use_window : bool, default=True Whether to use the window as a stopping criterion. sampling_period : int, default=50 Number of iterations between two consecutive spin samplings by the window. convergence_threshold : int, default=50 Number of consecutive identical spin samplings considered as a proof of convergence by the window. Hyperparameters corresponding to physical constants : These parameters have been fine-tuned (Goto et al.) to give the best results most of the time. Nevertheless, the relevance of specific hyperparameters may vary depending on the properties of the instances. They can respectively be modified and reset through the `set_env` and `reset_env` functions. Raises ------ ValueError If `input_type` is not one of {"spin", "binary", "int(\d+)"}. Warns ----- If `use_window` is True and no agent has reached the convergence criterion defined by `sampling_period` and `convergence_threshold` within `max_steps` iterations, a warning is logged in the console. This is just an indication however; the returned solutions may still be of good quality. If the returned solutions are not of good quality, solutions include increasing `max_steps` (at the expense of runtime), changing the values of `ballistic` and `heated` to use different variants of the SB algorithm and changing the values of some hyperparameters corresponding to physical constants (advanced usage, see Other Parameters). Warnings -------- The SB algorithm is an approximation algorithm, which implies that the returned values may not correspond to global optima. Therefore, if some constraints are embedded as penalties in the polynomial, that is adding terms that ensure that any global optimum satisfies the constraints, the return values may violate these constraints. See Also -------- minimize : Alias for optimize(*args, **kwargs, minimize=True). maximize : Alias for optimize(*args, **kwargs, minimize=False). build_model : Create a polynomial object. models : Module containing the implementation of several common combinatorial optimization problems. Notes ----- The original version of the SB algorithm [1] is not implemented since it is less efficient than the more recent variants of the SB algorithm described in [2]: ballistic SB : Uses the position of the particles for the position-based update of the momentums ; usually faster but less accurate. Use this variant by setting `ballistic=True`. discrete SB : Uses the sign of the position of the particles for the position-based update of the momentums ; usually slower but more accurate. Use this variant by setting `ballistic=False`. On top of these two variants, an additional thermal fluctuation term can be added in order to help escape local optima [3]. Use this additional term by setting `heated=True`. The time complexity is O(`max_steps` * `agents` * M^2) where M is the dimension of the instance. The space complexity O(M^2 + `agents` * N). For instances in low dimension (~100), running computations on GPU is slower than running computations on CPU unless a large number of agents (~2000) is used. References ---------- [1] Hayato Goto et al., "Combinatorial optimization by simulating adiabatic bifurcations in nonlinear Hamiltonian systems". Sci. Adv.5, eaav2372(2019). DOI:10.1126/sciadv.aav2372 [2] Hayato Goto et al., "High-performance combinatorial optimization based on classical mechanics". Sci. Adv.7, eabe7953(2021). DOI:10.1126/sciadv.abe7953 [3] Kanao, T., Goto, H. "Simulated bifurcation assisted by thermal fluctuation". Commun Phys 5, 153 (2022). https://doi.org/10.1038/s42005-022-00929-9 Examples -------- Maximize a polynomial over {0, 1} x {0, 1} >>> Q = torch.tensor([[1, -2], ... [0, 3]]) >>> best_vector, best_value = sb.optimize( ... Q, minimize=False, input_type="binary" ... ) >>> best_vector tensor([0, 1]) >>> best_value 3 Minimize Q and return all the solutions found using 42 agents >>> best_vectors, best_values = sb.optimize( ... Q, input_type="binary", agents=42, best_only=False ... ) >>> best_vectors.shape # (agents, dimension of the instance) (42, 2) >>> best_values.shape # (agents,) (42,) """ model = build_model( matrix=matrix, vector=vector, constant=constant, input_type=input_type, dtype=dtype, device=device, ) result, evaluation = model.optimize( agents=agents, max_steps=max_steps, best_only=best_only, ballistic=ballistic, heated=heated, minimize=minimize, verbose=verbose, use_window=use_window, sampling_period=sampling_period, convergence_threshold=convergence_threshold, ) return result, evaluation def minimize( matrix: Union[torch.Tensor, ndarray], vector: Union[torch.Tensor, ndarray, None] = None, constant: Union[int, float, None] = None, input_type: str = "spin", dtype: torch.dtype = torch.float32, device: str = "cpu", agents: int = 128, max_steps: int = 10_000, best_only: bool = True, ballistic: bool = False, heated: bool = False, verbose: bool = True, *, use_window: bool = True, sampling_period: int = 50, convergence_threshold: int = 50, ) -> Tuple[torch.Tensor, Union[float, torch.Tensor]]: r""" Minimize a multivariate degree 2 polynomial using the SB algorithm. The simulated bifurcated (SB) algorithm is a randomized approximation algorithm for combinatorial optimization problems. The minimization is done over a discrete domain specified through `input_type`. The polynomial is the sum of a quadratic form and a linear form plus a constant term: `ΣΣ Q(i,j)x(i)x(j) + Σ l(i)x(i) + c` or `x.T Q x + l.T x + c` in matrix notation, where `Q` is a square matrix, `l` a vector a `c` a constant. Parameters ---------- matrix : (M, M) Tensor | ndarray Matrix corresponding to the quadratic terms of the polynomial (quadratic form). It should be a square matrix, but not necessarily symmetric. vector : (M,) Tensor | ndarray | None, optional Vector corresponding to the linear terms of the polynomial (linear form). The default is None which signifies there are no linear terms, that is `vector` is the null vector. constant : int | float | None, optional Constant of the polynomial. The default is None which signifies there is no constant term, that is `constant` = 0. input_type : {"spin", "binary", "int(\d+)"}, default=spin Domain over which the minimization is done. • "spin" : Minimize the polynomial over vectors whose entries are in {-1, 1}. • "binary" : Minimize the polynomial over vectors whose entries are in {0, 1}. • "int(\d+)" : Minimize the polynomial over vectors whose entries are n-bits non-negative integers, that is integers between 0 and 2^n - 1 inclusive. "int(\d+)" represents any string starting with "int" and followed by a positive integer n, e.g. "int3", "int42". dtype : torch.dtype, default=torch.float32 Data-type used for running the computations in the SB algorithm. device : str | torch.device, default="cpu" Device on which the SB algorithm is run. If available, use "cuda" to run the SB algorithm on GPU (much faster, especially for high dimensional instances or when running the algorithm with many agents). agents : int, default=128 Number of simultaneous execution of the SB algorithm. This is much faster than sequentially running the SB algorithm `agents` times. max_steps : int, default=10_000 Number of iterations after which the algorithm is stopped regardless of whether convergence has been achieved. best_only : bool, default=True If True, return only the best vector found and the value of the polynomial at this vector. Otherwise, returns all the vectors found by the SB algorithm and the values of polynomial at these points. ballistic : bool, default=False Whether to use the ballistic or the discrete SB algorithm. See Notes for further information about the variants of the SB algorithm. heated : bool, default=False Whether to use the heated or non-heated SB algorithm. See Notes for further information about the variants of the SB algorithm. verbose : bool, default=True Whether to display a progress bar to monitor the progress of the algorithm. Returns ------- result : ([`agents`], M) Tensor Best vector found, or all the vectors found is `best_only` is False. evaluation : float | (`agents`) Tensor Value of the polynomial at `result`. Other Parameters ---------------- use_window : bool, default=True Whether to use the window as a stopping criterion. sampling_period : int, default=50 Number of iterations between two consecutive spin samplings by the window. convergence_threshold : int, default=50 Number of consecutive identical spin samplings considered as a proof of convergence by the window. Hyperparameters corresponding to physical constants : These parameters have been fine-tuned (Goto et al.) to give the best results most of the time. Nevertheless, the relevance of specific hyperparameters may vary depending on the properties of the instances. They can respectively be modified and reset through the `set_env` and `reset_env` functions. Raises ------ ValueError If `input_type` is not one of {"spin", "binary", "int(\d+)"}. Warns ----- If `use_window` is True and no agent has reached the convergence criterion defined by `sampling_period` and `convergence_threshold` within `max_steps` iterations, a warning is logged in the console. This is just an indication however; the returned solutions may still be of good quality. If the returned solutions are not of good quality, solutions include increasing `max_steps` (at the expense of runtime), changing the values of `ballistic` and `heated` to use different variants of the SB algorithm and changing the values of some hyperparameters corresponding to physical constants (advanced usage, see Other Parameters). Warnings -------- The SB algorithm is an approximation algorithm, which implies that the returned values may not correspond to global minima. Therefore, if some constraints are embedded as penalties in the polynomial, that is adding terms that ensure that any global minimum satisfies the constraints, the return values may violate these constraints. See Also -------- maximize : Maximize a polynomial. build_model : Create a polynomial object. models : Module containing the implementation of several common combinatorial optimization problems. Notes ----- The original version of the SB algorithm [1] is not implemented since it is less efficient than the more recent variants of the SB algorithm described in [2]: ballistic SB : Uses the position of the particles for the position-based update of the momentums ; usually faster but less accurate. Use this variant by setting `ballistic=True`. discrete SB : Uses the sign of the position of the particles for the position-based update of the momentums ; usually slower but more accurate. Use this variant by setting `ballistic=False`. On top of these two variants, an additional thermal fluctuation term can be added in order to help escape local minima [3]. Use this additional term by setting `heated=True`. The time complexity is O(`max_steps` * `agents` * M^2) where M is the dimension of the instance. The space complexity O(M^2 + `agents` * N). For instances in low dimension (~100), running computations on GPU is slower than running computations on CPU unless a large number of agents (~2000) is used. References ---------- [1] Hayato Goto et al., "Combinatorial optimization by simulating adiabatic bifurcations in nonlinear Hamiltonian systems". Sci. Adv.5, eaav2372(2019). DOI:10.1126/sciadv.aav2372 [2] Hayato Goto et al., "High-performance combinatorial optimization based on classical mechanics". Sci. Adv.7, eabe7953(2021). DOI:10.1126/sciadv.abe7953 [3] Kanao, T., Goto, H. "Simulated bifurcation assisted by thermal fluctuation". Commun Phys 5, 153 (2022). https://doi.org/10.1038/s42005-022-00929-9 Examples -------- Minimize a polynomial over {0, 1} x {0, 1} >>> Q = torch.tensor([[1, -2], ... [0, 3]]) >>> best_vector, best_value = sb.minimize(Q, input_type="binary") >>> best_vector tensor([0, 0]) >>> best_value 0 Return all the solutions found using 42 agents >>> best_vectors, best_values = sb.minimize( ... Q, input_type="binary", agents=42, best_only=False ... ) >>> best_vectors.shape # (agents, dimension of the instance) (42, 2) >>> best_values.shape # (agents,) (42,) """ return optimize( matrix, vector, constant, input_type, dtype, device, agents, max_steps, best_only, ballistic, heated, True, verbose, use_window=use_window, sampling_period=sampling_period, convergence_threshold=convergence_threshold, ) def maximize( matrix: Union[torch.Tensor, ndarray], vector: Union[torch.Tensor, ndarray, None] = None, constant: Union[int, float, None] = None, input_type: str = "spin", dtype: torch.dtype = torch.float32, device: str = "cpu", agents: int = 128, max_steps: int = 10_000, best_only: bool = True, ballistic: bool = False, heated: bool = False, verbose: bool = True, *, use_window: bool = True, sampling_period: int = 50, convergence_threshold: int = 50, ) -> Tuple[torch.Tensor, Union[float, torch.Tensor]]: r""" Maximize a multivariate degree 2 polynomial using the SB algorithm. The simulated bifurcated (SB) algorithm is a randomized approximation algorithm for combinatorial optimization problems. The maximization is done over a discrete domain specified through `input_type`. The polynomial is the sum of a quadratic form and a linear form plus a constant term: `ΣΣ Q(i,j)x(i)x(j) + Σ l(i)x(i) + c` or `x.T Q x + l.T x + c` in matrix notation, where `Q` is a square matrix, `l` a vector a `c` a constant. Parameters ---------- matrix : (M, M) Tensor | ndarray Matrix corresponding to the quadratic terms of the polynomial (quadratic form). It should be a square matrix, but not necessarily symmetric. vector : (M,) Tensor | ndarray | None, optional Vector corresponding to the linear terms of the polynomial (linear form). The default is None which signifies there are no linear terms, that is `vector` is the null vector. constant : int | float | None, optional Constant of the polynomial. The default is None which signifies there is no constant term, that is `constant` = 0. input_type : {"spin", "binary", "int(\d+)"}, default=spin Domain over which the maximization is done. • "spin" : Maximize the polynomial over vectors whose entries are in {-1, 1}. • "binary" : Maximize the polynomial over vectors whose entries are in {0, 1}. • "int(\d+)" : Maximize the polynomial over vectors whose entries are n-bits non-negative integers, that is integers between 0 and 2^n - 1 inclusive. "int(\d+)" represents any string starting with "int" and followed by a positive integer n, e.g. "int3", "int42". dtype : torch.dtype, default=torch.float32 Data-type used for running the computations in the SB algorithm. device : str | torch.device, default="cpu" Device on which the SB algorithm is run. If available, use "cuda" to run the SB algorithm on GPU (much faster, especially for high dimensional instances or when running the algorithm with many agents). agents : int, default=128 Number of simultaneous execution of the SB algorithm. This is much faster than sequentially running the SB algorithm `agents` times. max_steps : int, default=10_000 Number of iterations after which the algorithm is stopped regardless of whether convergence has been achieved. best_only : bool, default=True If True, return only the best vector found and the value of the polynomial at this vector. Otherwise, returns all the vectors found by the SB algorithm and the values of polynomial at these points. ballistic : bool, default=False Whether to use the ballistic or the discrete SB algorithm. See Notes for further information about the variants of the SB algorithm. heated : bool, default=False Whether to use the heated or non-heated SB algorithm. See Notes for further information about the variants of the SB algorithm. verbose : bool, default=True Whether to display a progress bar to monitor the progress of the algorithm. Returns ------- result : ([`agents`], M) Tensor Best vector found, or all the vectors found is `best_only` is False. evaluation : float | (`agents`) Tensor Value of the polynomial at `result`. Other Parameters ---------------- use_window : bool, default=True Whether to use the window as a stopping criterion. sampling_period : int, default=50 Number of iterations between two consecutive spin samplings by the window. convergence_threshold : int, default=50 Number of consecutive identical spin samplings considered as a proof of convergence by the window. Hyperparameters corresponding to physical constants : These parameters have been fine-tuned (Goto et al.) to give the best results most of the time. Nevertheless, the relevance of specific hyperparameters may vary depending on the properties of the instances. They can respectively be modified and reset through the `set_env` and `reset_env` functions. Raises ------ ValueError If `input_type` is not one of {"spin", "binary", "int(\d+)"}. Warns ----- If `use_window` is True and no agent has reached the convergence criterion defined by `sampling_period` and `convergence_threshold` within `max_steps` iterations, a warning is logged in the console. This is just an indication however; the returned solutions may still be of good quality. If the returned solutions are not of good quality, solutions include increasing `max_steps` (at the expense of runtime), changing the values of `ballistic` and `heated` to use different variants of the SB algorithm and changing the values of some hyperparameters corresponding to physical constants (advanced usage, see Other Parameters). Warnings -------- The SB algorithm is an approximation algorithm, which implies that the returned values may not correspond to global maxima. Therefore, if some constraints are embedded as penalties in the polynomial, that is adding terms that ensure that any global maximum satisfies the constraints, the return values may violate these constraints. See Also -------- minimize : Minimize a polynomial. build_model : Create a polynomial object. models : Module containing the implementation of several common combinatorial optimization problems. Notes ----- The original version of the SB algorithm [1] is not implemented since it is less efficient than the more recent variants of the SB algorithm described in [2]: ballistic SB : Uses the position of the particles for the position-based update of the momentums ; usually faster but less accurate. Use this variant by setting `ballistic=True`. discrete SB : Uses the sign of the position of the particles for the position-based update of the momentums ; usually slower but more accurate. Use this variant by setting `ballistic=False`. On top of these two variants, an additional thermal fluctuation term can be added in order to help escape local maxima [3]. Use this additional term by setting `heated=True`. The time complexity is O(`max_steps` * `agents` * M^2) where M is the dimension of the instance. The space complexity O(M^2 + `agents` * N). For instances in low dimension (~100), running computations on GPU is slower than running computations on CPU unless a large number of agents (~2000) is used. References ---------- [1] Hayato Goto et al., "Combinatorial optimization by simulating adiabatic bifurcations in nonlinear Hamiltonian systems". Sci. Adv.5, eaav2372(2019). DOI:10.1126/sciadv.aav2372 [2] Hayato Goto et al., "High-performance combinatorial optimization based on classical mechanics". Sci. Adv.7, eabe7953(2021). DOI:10.1126/sciadv.abe7953 [3] Kanao, T., Goto, H. "Simulated bifurcation assisted by thermal fluctuation". Commun Phys 5, 153 (2022). https://doi.org/10.1038/s42005-022-00929-9 Examples -------- Maximize a polynomial over {0, 1} x {0, 1} >>> Q = torch.tensor([[1, -2], ... [0, 3]]) >>> best_vector, best_value = sb.maximize(Q, input_type="binary") >>> best_vector tensor([0, 1]) >>> best_value 3 Return all the solutions found using 42 agents >>> best_vectors, best_values = sb.maximize( ... Q, input_type="binary", agents=42, best_only=False ... ) >>> best_vectors.shape # (agents, dimension of the instance) (42, 2) >>> best_values.shape # (agents,) (42,) """ return optimize( matrix, vector, constant, input_type, dtype, device, agents, max_steps, best_only, ballistic, heated, False, verbose, use_window=use_window, sampling_period=sampling_period, convergence_threshold=convergence_threshold, ) def build_model( matrix: Union[torch.Tensor, ndarray], vector: Union[torch.Tensor, ndarray, None] = None, constant: Union[int, float, None] = None, input_type: str = "spin", dtype: torch.dtype = torch.float32, device: str = "cpu", ) -> IsingPolynomialInterface: r""" Instantiate a multivariate degree 2 polynomial over a given domain. The polynomial is the sum of a quadratic form and a linear form plus a constant term: `ΣΣ Q(i,j)x(i)x(j) + Σ l(i)x(i) + c` or `x.T Q x + l.T x + c` in matrix notation, where `Q` is a square matrix, `l` a vector a `c` a constant. Parameters ---------- matrix : (M, M) Tensor | ndarray Matrix corresponding to the quadratic terms of the polynomial (quadratic form). It should be a square matrix, but not necessarily symmetric. vector : (M,) Tensor | ndarray | None, optional Vector corresponding to the linear terms of the polynomial (linear form). The default is None which signifies there are no linear terms, that is `vector` is the null vector. constant : int | float | None, optional Constant of the polynomial. The default is None which signifies there is no constant term, that is `constant` = 0. input_type : {"spin", "binary", "int(\d+)"}, default=spin Domain over which the maximization is done. - "spin" : Polynomial over vectors whose entries are in {-1, 1}. - "binary" : Polynomial over vectors whose entries are in {0, 1}. - "int(\d+)" : Polynomial over vectors whose entries are n-bits non-negative integers, that is integers between 0 and 2^n - 1 inclusive. "int(\d+)" represents any string starting with "int" and followed by a positive integer n, e.g. "int3", "int42", ... dtype : torch.dtype, default=torch.float32 Data-type used for storing the coefficients of the polynomial. device : str | torch.device, default="cpu" Device on which the polynomial is located. If available, use "cuda" to use the polynomial on a GPU. Returns ------- SpinPolynomial | BinaryPolynomial | IntegerPolynomial The polynomial described by `matrix`, `vector` and `constant` on the domain specified by `input_type`. - `input_type="spin"` : SpinPolynomial. - `input_type="binary"` : BinaryPolynomial. - `input_type="binary"` : IntegerPolynomial. Raises ------ ValueError If `input_type` is not one of {"spin", "binary", "int(\d+)"}. Warnings -------- Calling a polynomial on a vector containing values which do not belong to the domain of the polynomial raises a ValueError, unless it is called while explicitly passing `input_values_check=False`. See Also -------- minimize, maximize, optimize : Shorthands for polynomial creation and optimization. polynomial : Module providing some polynomial types as well as an abstract polynomial class `IsingPolynomialInterface`. models : Module containing the implementation of several common combinatorial optimization problems. Examples -------- Instantiate a polynomial over {0, 1} x {0, 1} >>> Q = torch.tensor([[1, -2], ... [0, 3]]) >>> poly = sb.build_model(Q, input_type="binary") Maximize the polynomial >>> best_vector, best_value = poly.maximize() >>> best_vector tensor([0, 1]) >>> best_value 3 Return all the solutions found using 42 agents >>> best_vectors, best_values = poly.maximize( ... agents=42, best_only=False ... ) >>> best_vectors.shape # (agents, dimension of the instance) (42, 2) >>> best_values.shape # (agents,) (42,) Evaluate the polynomial at a single point >>> point = torch.tensor([1, 1], dtype=torch.float32) >>> poly(point) 2 Evaluate the polynomial at several points simultaneously >>> points = torch.tensor( ... [[0, 0], [0, 1], [1, 0], [1, 1]], ... dtype=torch.float32, ... ) >>> poly(points) tensor([0, 3, 1, 2]) """ int_type_regex = re.compile(r"int(\d+)") if input_type == "spin": return SpinPolynomial( matrix=matrix, vector=vector, constant=constant, dtype=dtype, device=device ) if input_type == "binary": return BinaryPolynomial( matrix=matrix, vector=vector, constant=constant, dtype=dtype, device=device ) if int_type_regex.match(input_type): number_of_bits = int(int_type_regex.findall(input_type)[0]) return IntegerPolynomial( matrix=matrix, vector=vector, constant=constant, dtype=dtype, device=device, number_of_bits=number_of_bits, ) raise ValueError(r'Input type must match "spin", "binary" or "int(\d+)".')
fa8b56d81d03077d615920df4df46669cfca8b0d
blane612/-variables
/example_code.py
2,062
4.75
5
# author: elia deppe # date: 6/6/21 # # description: example code for variable exercises # Saving a String to a variable. name = 'elia' # ----- Printing the contents of the variable. print('my name is', name) # using regular strings print(f'my name is {name}') # using f-strings # When inserting a variable into an f-string, simply surround the name of the variable with {} # Notice that the color of the curly braces and the variable aren't the same color as the string. This helps us # identify what is and what isn't a string. Notice also that the curly braces aren't printed either, only the contents # of the variable. # ----- Saving a number to a variable. num1 = 7 num2 = 11.5 num3 = -21 print('here are a few numbers:', num1, num2, num3) # regular string print(f'here are a few numbers: {num1}, {num2}, {num3}') # f-string # ----- Overwriting Variables (Re-Use) num1 = 121 num2 = 4.422 num3 = -31.23 # Variables can switch types at any point, so feel free to save whatever you want to any variable! print('here are the same variables, but now with different values:', num1, num2, num3) print(f'here are the same variables, but now with different values: {num1}, {num2}, {num3}') # ----- Saving the Result of an Operation to a Variable num1 = 15 - 2 num2 = 12 / 3 num3 = -2 * 4.5 print('nums:', num1, num2, num3) print(f'nums: {num1}, {num2}, {num3}') # ----- Using Variables in Operations num1 = num2 + num3 num2 = num1 - 15 num3 = num3 * 2 # You can use a variable in an operation that is assigning to itself! print(f'nums: {num1}, {num2}, {num3}') # ----- String Duplication # String duplication is where you duplicate strings using multiplication. # For example, if I wanted to duplicate 'cat' 5 times then: print('cat' * 5) # Yes, you're allowed to do operations in functions, remember that the result is what matters! print('dog' * 3, 'gone' * 3) # If you want to duplicate a string inside a variable, simply multiply the variable by a number cash = '$' hashtag = '#' print(cash * 5, hashtag * 3, cash * 5)
b19231bf909e93a44a8a67e3d8aa5baef1864951
WeDias/RespCEV
/Exercicios-Mundo1/ex016.py
74
3.859375
4
num1 = float(input('Digite algum numero: ')) print('{:.0f}'.format(num1))
3946afc72e6ed2a4dd023130639a9d2b1f310aed
buy/cc150
/1.8.is_rotation.py
381
4.125
4
def isSubstring(string1, string2): return string1 in string2 def isRotation(string1, string2): if type('') is not type(string1) or type('') is not type(string2): raise Exception('Not Strings!') if len(string1) is not len(string2): return False else: return isSubstring(string1, string1 + string2) if __name__ == '__main__': print isRotation('abc', 'bca')
a0be796a375d94927bc6b234f57b459bd94fbc0d
dw2008/coding365
/201904/0419.py
501
4.15625
4
#Given an array A of integers, return true if and only if it is sorted in ascending order. # #sorted means: A[0] < A[1] < ... A[i-1] < A[i] #Example 1: #Input: [2,1] #Output: false #Example 2: #Input: [3,5,5] #Output: true #Example 3: #Input: [0,3,2,1] #Output: false def isSorted(alist) : for i in range(1, len(alist)) : if alist[i] >= alist[i -1] : continue else : return False return True numbers = [-1, 29, 3, 4, 5] print(isSorted(numbers))
b2093b426a215b0c86c004d49d3edde56922d092
hansrajdas/algorithms
/Level-1/gcd_and_lcm.py
397
4.09375
4
#!/usr/bin/python # Date: 2018-09-23 # # Description: # Find GCD(or HCF) and LCM of 2 numbers. def gcd(a, b): return gcd(b, a % b) if b else a def main(): a = int(input('Enter first number: ')) b = int(input('Enter second number: ')) g = gcd(a, b) print('GCD is: %d' % g) l = (a * b) / g # Because a*b = lcm*hcf print('LCM is: %d' % l) if __name__ == '__main__': main()
0b34f9a9ff7d6f106c47cb9b41048d4e1a248334
ArchAiA/lpthw
/ex19.py
1,200
4.40625
4
#The variables in a function, and the arguments identified in a function definition are not connected #unless they are explicitly passed #this is the function definition. It takes two arguments, and outputs them in strings def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" #this is an example of calling the function with values print "We can just give the function numbers directly:" cheese_and_crackers(20, 30) #this is an example of calling the function using variables print "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) #this is an example of calling a function using functions acting on values print "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 + 6) #this is an example of calling a function using functions acting on a combination of values and variables print "And we can combine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
268cc75ed772c79ce00ebd3fbf7345f6a3faa1c4
Jeffrey1202/comp9021
/midterm/z5141180.files/question_5.py
1,619
4.34375
4
def f(word): ''' Recall that if c is an ascii character then ord(c) returns its ascii code. Will be tested on nonempty strings of lowercase letters only. >>> f('x') The longest substring of consecutive letters has a length of 1. The leftmost such substring is x. >>> f('xy') The longest substring of consecutive letters has a length of 1. The leftmost such substring is x. >>> f('ababcuvwaba') The longest substring of consecutive letters has a length of 3. The leftmost such substring is abc. >>> f('abbcedffghiefghiaaabbcdefgg') The longest substring of consecutive letters has a length of 6. The leftmost such substring is bcdefg. >>> f('abcabccdefcdefghacdef') The longest substring of consecutive letters has a length of 6. The leftmost such substring is cdefgh. ''' desired_length = 0 desired_substring = '' # Insert your code here S=[] R=[] R2=[] for e in word: S.append(ord(e)) R1=[S[0]] for i in range(1,len(S)): if S[i]==S[i-1]+1: R1.append(S[i]) else: R.append(R1) R1=[S[i]] R.append(R1) for e in R: if len(e)>desired_length: desired_length=len(e) R2=e for i in R2: desired_substring+=chr(i) print(f'The longest substring of consecutive letters has a length of {desired_length}.') print(f'The leftmost such substring is {desired_substring}.') if __name__ == '__main__': import doctest doctest.testmod()
17601d36f7cc6cde5f46175e37042d5fbad59dbb
cryoMike90s/Daily_warm_up
/Dictionaries/ex_38_average_instead.py
512
3.90625
4
"""Write a Python program to replace dictionary values with their average.""" student_details= [ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74}, {'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86} ] def average_me(number_1: float, number_2: float): number_3 = (number_2 + number_1)/2 return number_3 for i in student_details: i['average'] = average_me(i['V'], i['VI']) i.pop('V') i.pop('VI') print(student_details)
bdf81e6144246f4d627f9c341a63b61b92c3499a
KaterinaMutafova/SoftUni
/Programming Basics with Python/Conditional_statements/Condex_ex1_minute_sec.py
315
3.890625
4
first_sec = int(input()) second_sec = int(input()) third_sec = int(input()) total_sec = first_sec + second_sec + third_sec total_minutes = total_sec // 60 left_sec = total_sec % 60 if left_sec > 9: print(f"{total_minutes}:{left_sec}") else: print(f"{total_minutes}:0{left_sec}")
b6585d63f634ac0486c969377483ba562b5d0fcb
rafaelperazzo/programacao-web
/moodledata/vpl_data/55/usersdata/133/24237/submittedfiles/av2_p3_civil.py
801
3.78125
4
# -*- coding: utf-8 -*- from __future__ import division import numpy as np # calcula o peso da matriz para um elemento na posição de linha a e coluna b def peso(X, a, b): s = 0 t = 0 for j in range(0, X.shape[0], 1): if(j!=b): s = s + X[a,j] for i in range(0, X.shape[0], 1): if(i!=a): t = t + X[i,b] p = s + t return p #Main n = input('Dimensão da matriz:') x = input('Digite o índice da linha que se deja descobrir o peso:') y = input('Digite o índice da coluna que se deja descobrir o peso:') X = np.zeros((n,n)) print('Os elementos da matrizes são inseridos linha a linha.') for i in range(0, n, 1): for j in range(0, n, 1): X[i,j] = input('Valor do elemento:') print ('O peso é:%d' %peso(X, x, y))
415acca1654e9d78abf8bdba3f65e3bd68d3c730
Gracekanagaraj/positive
/s8.py
64
3.515625
4
num=int(input()) ss=0 for i in range(1,num+1): ss+=i print(ss)
ebd4d5883f5292e4236429869089db9530ac2b85
asterinwl/2021-K-Digital-Training_selfstudy
/5.26/13_Bulit-in-function/fun_ext.py
2,028
4
4
#재귀함수 ''' def selfCall(): print('ha', end='') selfCall() selfCall() #ha 계속 생기고 오류생김 ''' def selfcall(num): if num==0: return else: print('ha', end="") selfcall(num-1) selfcall(5) print('') #팩토리얼 계산 def fact(num) : if num==1: return 1 else : return num*fact(num-1) print(fact(5)) #자연수를 입력받으면 해당하는 자연수까지 출력 #49 입력하면 1~49 출력 def count(num): a=[] for i in range(1,num+1): a.append(i) return a print(count(5)) #내부함수 : 함수 내에서 정의된 함수 def outFunc(x,y): def inFunc(a,b): return a+b return inFunc(x,y) print(outFunc(10,20)) #print(inFunc(10,20)) #함수 안에서 지정되어있는 함수이므로 오류가 생긴다. # def hap(x,y): return x+y print(hap(10,50)) print((lambda x,y : x+y)(10,50)) hap2=lambda x,y : x+y print(hap2(10,20)) def hap(x=10,y=20): return x+y print(hap()) print(hap(30,100)) hap3=lambda x=10, y=20 : x+y print(hap3()) print(hap3(9,10)) #print((lambda x : y=10 ,x+y)(10)) 오류 발생 #람다함수 안에서 변수를 생성할 수 없다. y=10 print((lambda x:x+y)(1)) #람다함수 list 사용 for i in [1,2,3] : print(i) lambda x:print(x) #리스트의 값에 각각 10을 더하는 람다함수를 작성 #10을 더하는 함수 def addTen(x): return x + 10 print(list(map(addTen,[1,3,4]))) print(list(map(lambda x:x+10,[1,3,4]))) #2)lambda 표현식 정의 list1=[1,2,3,4] list2=[10,20,30,40] def addList(x,y): a=[] for i in range(4): a.append(int(x[i])+int(y[i])) return a print(addList(list1,list2)) def hap(a, b): return [x + y for x, y in zip(a, b)] print(hap(list1, list2)) print(list(map(lambda x,y:x+y,list1,list2))) #print([(lambda x: x[0]+i[1])(i) for i in zip(list1,list2)])
48ce18e4d21154fb7284e810d158c355653f06b0
babiswas/Practise2
/test76.py
421
3.625
4
import sys def string_splitter(str1,chunk_size): l=[] index=0 if len(str1)>=chunk_size: while (chunk_size+index)<len(str1): l.append(str1[index:chunk_size+index]) index=index+chunk_size if str1[index:]: l.append(str1[index:]) return l if __name__=="__main__": m=string_splitter(sys.argv[1],int(sys.argv[2])) print(m)
62b243c60cf3275f0fd7df6c9beff3efed080ff2
nb341/algo-toolbox
/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py
860
4.09375
4
# Uses python3 # properties of fib numbers >= 60 import sys def fibonacci_sum_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current return sum % 10 def pisano(m): #n2 values previous, current = 0, 1 for i in range(0, m*m): previous, current = current, (previous + current)%m if previous==0 and current==1: return i+1 def fibonacci_sum(n): if n <= 1: return n n = n%pisano(10) previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current return sum % 10 if __name__ == '__main__': input = input() n = int(input) print(fibonacci_sum(n))
b505d955ac06b2a84414b6295c34d11d9fcfaa39
zhenguo96/test1
/Python基础笔记/4/作业4/中级2.py
378
3.65625
4
''' 2.输出1000以内的所有水仙花数: 水仙花数:一个三位数各个位上的立方之和,等于本身。 例如: 153 = 1(3) + 5(3)+ 3(3) = 1+125+27 = 153 ''' num = 100 while num < 1000: a = num % 10 b = num // 10 % 10 c = num // 100 if num == a ** 3 + b ** 3 + c ** 3: print(num) num += 1
3cc783a460a50eff7b41fe5ef5782d037f9dbb08
devchoplife/DataScience-Python
/Libraries/Python/pyfunctions.py
2,240
4.25
4
type ()#data type is #retruns true or false e.g x is y will retun true if they are equal print()#print results float()#convert to floats int()# convert to integers complex()#convert to complex int# a whole number float # decimal number complex # complex numbers booleans # used together with the numerical operations to test expressions #examples are : test = (3 < 4) # test #this returns a true or false expression range(start:stop:stride) round(number, ndigits)#you can add the number of d.p after the number seperated by a comma listname[start:stop:stride]#shows the numbers specified excluding the stop item listname.append() # adds an item to the list listname.pop() # remove and return the last item listname.extend() #also adds items to the list list(listname) #used to copy a list instead of referencing it listname.reverse()#shows the list from the last to the first. also = listname[::-1] listname + listname #joins two lists listname * 2 #the list duplicate is joined sorted(listname)# sorts the listname (alphabetically by default) listname.sort()#also to sort lists listname.count()#counts the no of items in the list listname.remove()#remove an item from the list listname.index()#shows the position of an item in the list listname.insert(position, element) #inserts an element into the list string.replace(oldvalue, new value) string.capitalize()#tonverts the first letter to uppercase string.casefold()#converts the string to lowercase string.count(value, start, end) string.find()#find a specific value in the string string.islower()#returns true if all the strings are in lowercase string.isupper()#returns if all the characters are uppercase string.lower()#convert to lowercase string.startswith()#returns true if it starts with the specified value string.endswith()#returns true if it ends with the specified character string.upper()#convert to uppercase strung.split()#splits a string into lists len(string)#length of a string #CONTROL FLOW if condition: expression elif condition: expression else : expression importlib.reload(module)#to reload a ccreated module after the contents has been modified \ #used for breaking long lines of codes into multiple lines
30c632898475e00ad3ef1fba0b0738095ca424a0
serenabooth/DistributedComputing
/LogicalClocks/clock.py
10,551
3.5625
4
from datetime import datetime from threading import * import sys, time, socket, random, Queue # cite: http://stackoverflow.com/questions/19846332/python-threading-inside-a-class # yay decorators def threaded(fn): """ Creates a new thread to run the function fn """ def wrapper(*args, **kwargs): Thread(target=fn, args=args, kwargs=kwargs).start() return wrapper class Clock(Thread): """ Sets up a machine """ # shared between all processes / logical clocks # keeps track of server connections that can be binded to global socket_connections socket_connections = {} def __init__(self, id, ticks_per_min, logbook, port_client, port_server): """ Initialize a clock that runs at the speed of ticks_per_min (a random number between 1 and 6 determined in main.py). Set the log file to logbook, the client socket port to port_client, and the server socket port to port_sever. The client socket will be used to connect to other servers and the server socket will be listening for connections. Store id, ticks_per_min, logbook, port_client, and port_server as instance variables. params: id: int ticks_per_min: int logbook: string port_client: int port_server: int return: void """ print "Clock " + str(id) + " started with clock time " + str(ticks_per_min) self.id = id self.ticks_per_min = ticks_per_min self.logbook = logbook f = open(self.logbook, 'a') f.write("\n\n\n\n\n\n\n\n STARTUP " + str(datetime.now()) + " with clock time " + str(ticks_per_min) + "\n") f.close() # the current logical clock time for this particular clock self.clock_time = 0 # a queue of all the messages received by this clock that have not # yet been processed self.msg_queue = Queue.Queue() # keep track of the ports self.port_client = port_client self.port_server = port_server global socket_connections socket_connections[self.id] = self.port_server Thread.__init__(self) @threaded def perform_clock_instruction(self): """ Perform a random action unless there is a message in msg_queue. The probability of each action is defined by the assignment specification. params: Clock returns: void """ if not self.msg_queue.empty(): self.receive_event() else: op = random.randint(1,10) # create a list that includes all the server ports except the # server port for this clock set_of_clocks_excluding_me = socket_connections.keys() set_of_clocks_excluding_me.remove(self.id) # send a message to clock A if op == 1: self.send_event([set_of_clocks_excluding_me[0]]) # send a message to clock B elif op == 2: self.send_event([set_of_clocks_excluding_me[1]]) # send a message to clocks A and B elif op == 3: self.send_event(set_of_clocks_excluding_me) # internal event else: self.internal_event() def start_server_socket(self, time): """ Start up the server socket with a timeout of time, binding it to self.port_server. params: self: Clock time: float returns: void """ try: self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.settimeout(time) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self.server.bind(('', self.port_server)) except socket.error as msg: print "Bind failed. Error Code : " \ + str(msg[0]) + " Message : " + str(msg[1]) sys.exit() self.server.listen(10) except Exception, e: print "Exception: " + str(e) self.start_server_socket() def run(self): """ Start up the server socket and accept connections for self.ticks_per_min. When the socket times out, perform a random action in a new thread and start up the server socket again. params: self: Clock returns: void """ global socket_connections self.start_server_socket(self.ticks_per_min) while True: try: # keep track of the time that the server started start_time = time.time() c, addr = self.server.accept() data, addr_2 = c.recvfrom(1024) self.server.shutdown(socket.SHUT_RDWR) self.server.close() # keep track of the time that the server finishes receiving # a request end_time = time.time() # set the timeout of the server to end_time - start_time to get # around the GIL self.start_server_socket(end_time - start_time) data = data.decode() # add the received message to the msg_queue if data: self.msg_queue.put(data) print str(self.id) + " got some! " + data # every time the socket timesout, callback to the clock's instruction except Exception, e: # shutdown the server first try: self.server.shutdown(socket.SHUT_RDWR) except: pass self.server.close() print "exception: " + str(e) print "complete an instruction" self.perform_clock_instruction() # restart server self.start_server_socket(self.ticks_per_min) def log(self, msg=None): """ Writes the appropriate information to the clock log params: self: Clock msg: string returns: void """ f = open(self.logbook, 'a') # if send or receive, write message if msg: f.write(" System time: " + str(datetime.now()) + " Logical clock time: " + str(self.clock_time) + " " + str(msg) + '\n') # if it is an internal event just write the system time and current # logical clock time else: f.write(" System time: " + str(datetime.now()) + " Logical clock time: " + str(self.clock_time) + '\n') f.close() def connect_client_socket(self, dst): """ Starts up the client socket with no timeout, binded to the port dst params: self: clock_time dst: socket port, int returns: void """ try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.settimeout(None) self.client.connect(('', dst)) except Exception, e: print "Connecting to client socket exception " + str(e) self.connect_client_socket(dst) def send_event_helper(self, dsts): """ Attempt to connect to each dst in dsts and send a message, one at a time. Retry the connection if the server is not available. params: self: Clock dsts: socket port (int) returns: void """ # for each server in dsts for dst in dsts: # connect the client socket to the server self.connect_client_socket(dst) # attempt to send a message with the clock id and logical clock time # shutdown the server when finished try: msg="" + str(self.id) + ": " + str(self.clock_time) self.client.send(msg.encode()) self.client.shutdown(socket.SHUT_RDWR) self.client.close() # if message is not sent, recursively attempt to send it again except Exception, e: print "(EXCEPTING) My id is " + str(self.id) + str(e) self.send_event_helper([dst]) def send_event(self, dsts): """ Sends a message to dsts, which can be one machine or multiple params: self: Clock dsts: list of clock ids (list of ints) returns: void """ # get a list of the port numbers to send a message to if dsts: dsts_copy = dsts dsts = [socket_connections[clock_id] for clock_id in dsts] self.send_event_helper(dsts) # keep track of the logical clock time when the message was sent # so that it can be put in the log cur_time = self.clock_time # update the logical clock time self.clock_time += 1 # log sending the message self.log(" Sending to " + str(dsts_copy) + " at LC time: " + str(cur_time)) def receive_event(self): """ Process a received message by putting it into msg_queue and updating the logical clock time appropriately. params: self: Clock return: void """ msg = self.msg_queue.get() # get the logical clock time of the machine that sent the message other_system_clock = msg[msg.index(":") + 1:] # set the clock time to the maximum of self's clock time and other # system's clock time self.clock_time = max(self.clock_time, int(other_system_clock)) # increment the logical clock time and log that a message was received self.clock_time += 1 self.log(" Received message from " + str(msg[:msg.index(":")]) + " with LC time " + str(msg[msg.index(":") + 2:]) + "; messages left to process: " + str(self.msg_queue.qsize())) def internal_event (self): """ Perform an internal event, which increases the logical clock time and logs the the current system time and logical clock time. params: self: Clock returns: void """ self.clock_time += 1 self.log()
77f15c28252b89d77de38af29f72e383ab872095
chunkityip/CodingBat-
/String-2.py
2,503
4.21875
4
double_char #Given a string, return a string where for every char in the original, there are two chars. def double_char(str): count='' for x in str: count+=x*2 return count ------------------------------------------------------------------------------------------------------------------------------------------- count_hi #Return the number of times that the string "hi" appears anywhere in the given string. def count_hi(str): count=0 for x in range(len(str)-1): if str[x:x+2] == 'hi': count+=1 return count --------------------------------------------------------------------------------------------------------------------------------------------- cat_dog #Return True if the string "cat" and "dog" appear the same number of times in the given string. def cat_dog(str): cat =0 dog =0 for x in range(len(str)): if str[x:x+3] =='cat': cat+=1 elif str[x:x+3] =='dog': dog+=1 return cat == dog ------------------------------------------------------------------------------------------------------------------------------------------- count_code #Return the number of times that the string "code" appears anywhere in the given string, #except we'll accept any letter for the 'd', so "cope" and "cooe" count. def count_code(str): count=0 for x in range(0,len(str)-3): if str[x:x+2] == 'co' and str[x+3] =='e': count+=1 return count ---------------------------------------------------------------------------------------------------------------------------------------- end_other #Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). #Note: s.lower() returns the lowercase version of a string. def end_other(a, b): a=a.lower() b=b.lower() return (a.endswith(b) or b.endswith(a)) #The endswith() method returns True if a string ends with the specified suffix. If not, it returns False. ---------------------------------------------------------------------------------------------------------------------------------------- xyz_there #Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). #So "xxyz" counts but "x.xyz" does not. def xyz_there(str): for x in range(len(str)): if str[x]!= '.' and str[x+1:x+4]=='xyz': return True elif str[0:3]=='xyz': return True return False
e9d6bca8a5d67c8d14911b02d88f259a4638260c
Epistemological/practice_projects
/h_course/w2/Classes.py
372
3.875
4
#normal usage of methods ml = [5,9,3,6,8,11,4,3] ml.sort() min(ml) max(ml) ml.remove(5) #create new class class mylist(list): def remove_min(self): #instance method self.remove(min(self)) def remove_max(self): #instance method self.remove(max(self)) x = [1,2,3,4,5,6,7,8] y = mylist(x) dir(y) y.remove_min() print(y) y.remove_max() print(y)
d3f5f225e7dca2e14aa0946d3a462925fa4e3991
CiaranPlusPlus/Assur-Graphs-and-Rigidity-Circuits
/AssurGenerator.py
26,154
3.65625
4
#!/usr/bin/env python """ Generate a list of all Assur Graphs. Author: Ciaran Mc Glue Date of creation start: 25/03/2020 The purpose of this script is to create a comprehensive list of all possible combinations of Assur Graphs starting with the smallest 'basic' Assur Graphs up to a graph size of N. This program will be using the definitions and methods set forth in the paper "Combinatorial Characterization of the Assur Graphs from Engineering" by Servatius et al. Assur Graphs will be created using a calculated number of rigidity graphs that can then be modified to have a set of pinned vertices. Graphs of a vertex size N are stored in text files labelled by the vertex count (cumulative count of pinned and unpinned vertices) in the format of: [[(n,n+1), ...], [(n, {'pinned':BOOLEAN}), (n+1, {'pinned':BOOLEAN}), ...]] This is two lists, the first is the edge set, the second is the vertex set. The edge set is listed as the pair of connected vertices while the vertex set maintains information about whether a vertex is pinned or not using a boolean dictionary key value pair. This minimises impact to storage space while maintaining a somewhat human-readable format. """ """ ------------------- Imports -------------------- """ import argparse import ast import os import itertools import networkx as nx import networkx.algorithms.isomorphism as iso from os import listdir from os.path import isfile, join """ ---------------- Global Constants ---------------- """ DIR = "AssurGraphFiles/" ASSUR_DIR = DIR + "AssurGraphs/" CIRCUIT_DIR = DIR + "RigidityCircuits/" ASSUR_FILENAME = "AssurGraphsOf_" CIRCUIT_FILENAME = "RigidityCircuitsOf_" """ --------------- Graphing Functions ---------------- """ # edge_split: # Splits an edge, adds a new vertex, and connects it to the two vertices # that the edge was removed from, as well as a third pre-existing vertex. # Returns a new graph created by this operation def edge_split(graph, a, b, c): # Arrays start at zero, so the size will return the next integer to be used as a node. enum = len(graph) # maintains the original used graph integrity h = graph.copy() h.remove_edge(a, b) # Remove the edge from the nodes supplied h.add_node(enum) # add new node to the graph # add edges from this new node to the previous two nodes plus the third supplied one h.add_edge(a, enum) h.add_edge(b, enum) h.add_edge(c, enum) return h # two_sum # Takes in an argument of two graphs and the edges of each where the graphs will be # joined together and then returns the newly created graph. The size of the graph returned # will be the total sum of the vertices between the two minus 2: (|G(V)| + |H(V)|) - 2. # Graphs will have their nodes relabelled to make it clear which nodes belong to which graph. # Then depending on the edges where the sum is going to be the respective nodes are labelled # the same so that a graph union can be applied to cause the graphs to be "glued" along # those respective edges. nx.compose does not relabel all edges after composing so they will # need to be renumbered so graph storage format is maintained. def two_sum(ga, gb, a, b): # copying graphs avoids risk of modifying the original object grapha = ga.copy() graphb = gb.copy() # create lists for vertex label mapping mapa = [] mapb = [] # relabel tuple edge information to relabel nodes to be unionised a = ("G1_" + str(a[0]), "G1_" + str(a[1])) b = ("G2_" + str(b[0]), "G2_" + str(b[1])) # relabel the nodes in each graph to keep each set unique # creates a mapping for each graph and then applies it so each # vertex has a G#_ as a prefix to the original vertex numbers for num1 in list(grapha.nodes): mapa.append("G1_" + str(num1)) for num2 in list(graphb.nodes): mapb.append("G2_" + str(num2)) g1_mapping = dict(zip(grapha, mapa)) g1 = nx.relabel_nodes(grapha, g1_mapping) # Composing two graphs does not remove edges so we need to do it manually g1.remove_edge(a[0], a[1]) # These two lines label the nodes to be joined at 'a' and 'b' so a compose of the two # graphs will result in a two sum of the graphs g1_union_nodes = {a[0]: 'a', a[1]: 'b'} g1 = nx.relabel_nodes(g1, g1_union_nodes, copy=False) g2_mapping = dict(zip(graphb, mapb)) g2 = nx.relabel_nodes(graphb, g2_mapping) # Composing two graphs does not remove edges so we need to do it manually g2.remove_edge(b[0], b[1]) # These two lines label the nodes to be joined at 'a' and 'b' so a compose of the two # graphs will result in a two sum of the graphs g2_union_nodes = {b[0]: 'a', b[1]: 'b'} g2 = nx.relabel_nodes(g2, g2_union_nodes, copy=False) # compose the two graphs so they will be joined at the common nodes and edge u = nx.compose(g1, g2) # relabel the graphs from 0 - N so they can be stored correctly u = nx.convert_node_labels_to_integers(u, first_label=0, ordering="default") return u # basic_graphs # There are a few basic known Assur Graphs. The AG on three vertices is the # smallest AG possible. The complete graph of 4 vertices k_4 is used to create # all possible rigidity circuits which are in turn used to create assur graphs. # This function is run only to replace these graphs in in the list, and to # create them on the first time running. def basic_graphs(): # Create the most basic AG of three vertices where 2 are pinned # This hardcoded as it is the exception that cannot be generated from a # rigidity circuit. ag_3 = nx.Graph() ag_3.add_nodes_from([(0, {'pinned': True}), (1, {'pinned': False}), (2, {'pinned': True})]) ag_3.add_edges_from([(0, 1), (1, 2)]) if not duplicate_or_isomorphic(ag_3, ASSUR_DIR + ASSUR_FILENAME, "assur"): write_graph_to_file(ag_3, ASSUR_DIR + ASSUR_FILENAME) # Create the complete graph on 4 vertices and write it to # the rigidity circuit files to create more rigidity circuits k_4 = nx.complete_graph(4) if not duplicate_or_isomorphic(k_4, CIRCUIT_DIR + CIRCUIT_FILENAME, "rigidity"): write_graph_to_file(k_4, CIRCUIT_DIR + CIRCUIT_FILENAME) # create_rigidity_circuits # This function creates all possible rigidity circuits of the integer input # argument to the script using two_sum and edge_splits. def create_rigidity_circuits(rc_size): # To create graphs of size N, the edge split has to be performed on graphs of # size N-1 since it only ever adds one more vertex. N has to be 5 at the # absolute minimum for this section. edge_split_file = CIRCUIT_DIR + CIRCUIT_FILENAME + str(rc_size - 1) + ".txt" with open(edge_split_file, "r") as graphs_to_edge_split: for graph in graphs_to_edge_split: edge_list = ast.literal_eval(graph) g = nx.Graph() g.add_edges_from(edge_list[0]) nodes = list(nx.nodes(g)) for edge in edge_list[0]: # copy list so items can be removed without affecting the source list temp_nodes = nodes.copy() a, b = edge temp_nodes.remove(a) temp_nodes.remove(b) for node in temp_nodes: new_temp_graph = edge_split(g, a, b, node) if not duplicate_or_isomorphic(new_temp_graph, CIRCUIT_DIR + CIRCUIT_FILENAME, "rigidity"): write_graph_to_file(new_temp_graph, CIRCUIT_DIR + CIRCUIT_FILENAME) # To achieve a correct two sum for the desired graph size, the two circuits being summed # together cannot have a total vertex count of size larger than the desired size plus 2. # Exceptions can be made since graphs smaller than 4 do not exist for creating Assur Graphs # outside of the AG_3 exception, which cannot be made from smaller graphs anyway. two_sum_addends = get_set_of_number_combinations(rc_size) for addends in two_sum_addends: num1, num2 = addends graph_file_1 = CIRCUIT_DIR + CIRCUIT_FILENAME + str(num1) + ".txt" graph_file_2 = CIRCUIT_DIR + CIRCUIT_FILENAME + str(num2) + ".txt" with open(graph_file_1, "r") as file_1: with open(graph_file_2, "r") as file_2: # These nested loops will create 2-sums for all graphs contained in the files # For each graph in the first file it will perform a 2 sum operation for each # graph in the second. A 2-sum will be performed for each edge of each graph # so this method is a brute-force approach and could become time-expensive # for large sets of graphs. Only unique graphs that no isomorphisms already # exist for will be added to the file of all graphs of that length for lines_1 in file_1: edge_list_1 = ast.literal_eval(lines_1) h = nx.Graph() h.add_edges_from(edge_list_1[0]) for lines_2 in file_2: edge_list_2 = ast.literal_eval(lines_2) i = nx.Graph() i.add_edges_from(edge_list_2[0]) for edge_h in edge_list_1[0]: for edge_i in edge_list_2[0]: temp_graph_2sum_result = two_sum(h, i, edge_h, edge_i) if not duplicate_or_isomorphic(temp_graph_2sum_result, CIRCUIT_DIR + CIRCUIT_FILENAME, "rigidity"): write_graph_to_file(temp_graph_2sum_result, CIRCUIT_DIR + CIRCUIT_FILENAME) # Now check the 2-sum with one graph flipped edge_i_flipped = tuple(reversed(edge_i)) temp_graph_2sum_result_flip = two_sum(h, i, edge_h, edge_i_flipped) if not duplicate_or_isomorphic(temp_graph_2sum_result_flip, CIRCUIT_DIR + CIRCUIT_FILENAME, "rigidity"): write_graph_to_file(temp_graph_2sum_result, CIRCUIT_DIR + CIRCUIT_FILENAME) # create_assur_graphs # This function takes in the desired Assur Graph size and will generate all Assur Graphs # for that size. It does this by using the rigidity circuits that are of size less than # this. For each graph, each node of that graph will be 'split' such that the resulting # graph is of the desired size. The function does this by checking for how many nodes # it needs to add to the initial rigidity circuit and then creates resulting pinned # graphs for every possible combination of the edges that connected to the node that # was split. def create_assur_graphs(ag_size): files = [] # To create graphs of size N, we need to look at all rigidity circuits that are # smaller than the desired assur graph size so that we can split out nodes # and pin them. for x in range(1, ag_size): temp_name = CIRCUIT_FILENAME + str(x) + ".txt" # If that generated file name exists, it will be added to the list of files to be parsed if temp_name in os.listdir(CIRCUIT_DIR): files.append(os.path.abspath(CIRCUIT_DIR + temp_name)) # this loop parses though the rigidity circuits in each of the files and creates # Assur Graphs from them, then it it check the destination files for isomorphic # graphs and write them if the graph is unique for file in files: with open(file) as graph_file: for graph in graph_file: edge_list = ast.literal_eval(graph) g = nx.Graph() # graph object to hold the temporary graph g.add_edges_from(edge_list[0]) nodes = list(nx.nodes(g)) # The number of nodes to add to get the desired size nodes_to_add = ag_size - len(g) for node in nodes: # this creates a list of all possible Assur Graphs for this rigidity circuit assur_graphs = split_vertex_combinations(g, node, nodes_to_add) # check for isometric graphs in the file before writing for ag in assur_graphs: if not duplicate_or_isomorphic(ag, ASSUR_DIR + ASSUR_FILENAME, "assur"): write_graph_to_file(ag, ASSUR_DIR + ASSUR_FILENAME) # split_vertex_combinations # This takes in a graph, a node on that graph, and the number of vertices to add. Using # this information, it will split the node into the set number of vertices and then for # each combination of distributed edges it will create a graph with a set of pinned # and unpinned edges and return the list of all of the graphs created this way. This # should result in a list of Assur Graphs with some possible isomorphic entries. def split_vertex_combinations(h, n, m): a_graphs = [] # list of graphs being created by this function pinned_node_list = [n] # this is a list of the split nodes i = h.copy() # Copy the input graph to avoid original object changes # this loop adds in new nodes to the graph so it meets the size requirements for x in range(0, m): # The next node will be one integer higher than what is already there, nodes start at '0' enum = len(i) # add a new node labelled sequentially higher than the ones already in the graph i.add_node(enum) pinned_node_list.append(enum) # this sets a bound for how many combinations of edges there can be valence = i.degree[n] # If the valence of the node being 'split' is equal to the number of # nodes being added then there is not enough edges for all of these # nodes and the graph cannot be split as there cannot be isolates. if valence <= m: a_graphs = [] return a_graphs # This sets each node to have a true or false pinned status attributes_dict = {} for node in i.nodes: if node in pinned_node_list: attributes_dict[node] = {'pinned': True} else: attributes_dict[node] = {'pinned': False} nx.set_node_attributes(i, attributes_dict) # apply the node attributes # get all combinations of edges distributed among the pinned vertices set_of_edge_combinations = edge_combinations(list(i.edges(n)), pinned_node_list) # remove the edges that will be replaced from the original graph edges_to_remove = list(i.edges(n)) i.remove_edges_from(edges_to_remove) for combo in set_of_edge_combinations: j = i.copy() # copy i so the loop does not affect the base graph object j.add_edges_from(combo) # add the set of edges for this iteration a_graphs.append(j) return a_graphs # edge_combinations # This takes in the list of edges adjacent to the vertex being split, it then creates # a list of all possible combinations of edge connections between the set of pinned # vertices, leaving no pinned vertex unconnected to avoid isolates. This functions works # by getting the list of edges connected to the node of interest, and then creates a full # list of all combinations, replacing the number that represents the node of interest in # each edge connection data structure with one of the nodes that is pinned. It returns a # list of lists that contains the pinned nodes edges that can just be applied to a graph # data structure where the old edges have been removed. This gets all possible Assur Graphs # for that graph configuration, even isometric entries. def edge_combinations(list_of_edges, list_of_nodes): number_combinations = [] combinations = [] edge_count = len(list_of_edges) # To get all useful combinations without leaving an isolate, we get the product # of the list repeated for the number of edges that need to be distributed. We # then check for isolated vertices and ignore these combinations as they will not # result in valid Assur Graphs for n in itertools.product(list_of_nodes, repeat=edge_count): result = set(list_of_nodes).issubset(n) # This makes sure there are no isolates if result: number_combinations.append(n) # This nested loop will create the set of edge connection combinations for combo in number_combinations: temp_list = [] for e, edge in enumerate(list_of_edges): new_edge = combo[e], edge[1] # create the new edge combination temp_list.append(new_edge) combinations.append(temp_list) # add this set of combinations to the list to return return combinations # duplicate_or_isomorphic # this accepts a graph as an argument and returns a boolean result based on # whether that graph has already been created and stored. It will check for # a duplicate graph first before checking for isomorphism between graphs. def duplicate_or_isomorphic(graph_to_check, graph_type_filename, mode): filename = graph_type_filename + str(len(graph_to_check)) + ".txt" # create the file if it does not already exist if not os.path.exists(filename): with open(filename, "w"): pass with open(filename, "r+") as temp_file: for line_number, line in enumerate(temp_file): try: temp_graph = nx.Graph() temp_list = ast.literal_eval(line) temp_graph.add_edges_from(temp_list[0]) temp_graph.add_nodes_from(temp_list[1]) # Since graphs are stored slightly differently the Assur Graphs themselves # require a node match check for their pinned vertices. While rigidity # circuits do not use any status for the nodes as it is not needed. if mode == "assur": nm = iso.categorical_node_match('pinned', [True, False]) # if a graph is isomorphic then it is a duplicate entry if nx.is_isomorphic(temp_graph, graph_to_check, node_match=nm): return True elif mode == "rigidity": # if a graph is isomorphic then it is a duplicate entry if nx.is_isomorphic(temp_graph, graph_to_check): return True except Exception as error: print("Error with graph line: " + str(error)) print("Error line string is: \n" + line) # it would be useful here to delete the error line and # then just continue the parsing of the file but it # is both difficult and possibly dangerous to edit a # file while parsing it. Easier to remove the error line # manually after being alerted by an error handler. return False """ --------------- Utility Functions ---------------- """ # write_graph_to_file # Creates a list format of the set of edges and node information of the graph. # this is useful because we can then reconstruct the graphs from this format, # and it is human readable from the text files they are stored in. def write_graph_to_file(graph_to_write, graph_type_filename): filename = graph_type_filename + str(len(graph_to_write)) + ".txt" # create the file if it does not already exist if not os.path.exists(filename): with open(filenamen, 'w'): pass edge_list = list(graph_to_write.edges) node_info_list = list(graph_to_write.nodes.data()) graph = [edge_list, node_info_list] with open(filename, "a") as temp_file: temp_file.write(str(graph) + "\n") # validate_files # This function checks to see if all directories and sub-directories # exist for containing the files that host the set of graphs for each # vertex count. It uses the program input to check if all files # below that desired number exist and replace them if they do not. def validate_files(input_num): # Check to see if the directory for the graph files exists try: # Create target file Directory os.mkdir(DIR) print("Directory " + DIR + " Created.\n") except Exception: print("Directory " + DIR + " already exists \n") try: # Create target rigidity circuit Directory os.mkdir(CIRCUIT_DIR) print("Directory " + CIRCUIT_DIR + " Created.\n") except Exception: print("Directory " + CIRCUIT_DIR + " already exists \n") try: # Create target assur graph Directory os.mkdir(ASSUR_DIR) print("Directory " + ASSUR_DIR + " Created.\n") except Exception: print("Directory " + ASSUR_DIR + " already exists \n") # Check for files for the rigidity circuits. These files need to exist # to create the circuits the Assur Graphs are generated from. for rc_num in range(4, input_num): # if the input num is 3 or 4 just make sure the basic graph set is done if rc_num <= 4: basic_graphs() continue file_name_rc_num = CIRCUIT_DIR + CIRCUIT_FILENAME + str(rc_num) + ".txt" if not os.path.exists(file_name_rc_num): # if the files are not there, create them print("Creating sub-files for rigidity circuits of size " + str(rc_num) + "...\n") create_rigidity_circuits(rc_num) # get_set_of_number_combinations # This function takes in a number and finds the list of all possible two # number combinations that can add up to a certain number. This is useful # for determining what graphs to 2-sum together to find a resulting graph # of a desired size. For example, getting 2-summed graphs of total vertex # count 10 requires the list of all two summed numbers that result in 12, # since two vertices are "lost" in the 2-sum operation. def get_set_of_number_combinations(max_num): number_list = [] # when performing a 2-sum 2 vertices will be lost from the total as they # are "glued" together in a sense, so the max number has an offset of 2 offset_max = max_num + 2 cap = round(offset_max/2)+1 # it starts at 4 because that is the smallest rigidity circuit available. for num in range(4, cap): result = offset_max - num if result >= 4 and num >= 4: combo = num, result number_list.append(combo) return number_list # apply_arg_parser # setup to make sure the use supplies the program with an integer argument # when calling the script Also has a -h flag to tell a user what the arguments # are for and their format. def apply_arg_parser(): parser = argparse.ArgumentParser(description='Will calculate the Assur Graphs for all inner ' 'vertex counts from 3 up until the supplied ' 'integer argument n.') parser.add_argument('integer', metavar='n', type=int, nargs=1, help='The largest Assur Graph of total vertex count n to be generated. ' 'A value less than 3 will not generate any Assur graphs, and will ' 'result in no output.') return parser # handle_args # Used to handle any arguments supplied by a user on the command line. # Some conditions like when the integer input is less than 1 will be # accounted for here by just abandoning the executing of the script to # avoid crashes or wasting time. def handle_args(arg_parser): arg, unknown = arg_parser.parse_known_args() unknowns = "" for unknown_arg in unknown: unknowns = unknowns + unknown_arg + " " if unknowns is not "": print("Ignoring unrecognised arguments: " + unknowns) print("Using first argument: " + str(arg.integer[0])) if arg.integer[0] <= 2: print("Invalid input of " + str(arg.integer[0]) + ". Use an input of n > 2") exit() if arg.integer[0] == 0: print("No Assur Graphs on 4 vertices exist.") exit() return arg.integer[0] """ --------------- Main Call ---------------- """ # main # This is the top most function being called. It functions as the flow control # of all other functions. It is called below the Main Call line. def main(): # Get the input arguments supplied to the program on the command line arguments = apply_arg_parser() vertex_count = handle_args(arguments) # if he input was larger than the current set of files that exist # this method will create the smaller rigidity circuit files validate_files(vertex_count) # This checks the size of the input. At less than 3 the arg_parser will fail # At 3, the basic set of graphs will be created. At 5+ it will create those # sets of Assur Graphs. Also if vertex_count >= 4: create_assur_graphs(vertex_count) else: basic_graphs() # General execution catch error handling. try: main() except Exception as mainExecuteError: print(mainExecuteError)
06ba92945f0ffec726ab33072e848a30029c29ae
lazsecu/PyGame-Snake
/snake.py
3,050
3.53125
4
import pygame import sys import random import time pygame.init() width = 400 height = 400 green = (0, 255, 0) red = (255, 0, 0) white = (255, 255, 255) background_color = (0, 0, 0) pygame.display.set_caption('Snek') screen = pygame.display.set_mode([width, height]) clock = pygame.time.Clock() game_exit = False font = pygame.font.SysFont(None, 25) def snake(snakelist): for XnY in snakelist: pygame.draw.rect(screen, green, (XnY[0], XnY[1], 10, 10)) def message_to_screen(msg, color): screen_text = font.render(msg, True, color) screen.blit(screen_text, [200, 200]) def game_loop(): game_exit = False lead_x = 200 lead_y = 200 lead_x_change = 0 lead_y_change = 0 snakelist = [] snakelength = 1 randAppleX = round(random.randrange(0, width - 10)/10.0) * 10.0 randAppleY = round(random.randrange(0, height - 10)/10.0) * 10.0 game_over = False while not game_exit: while game_over == True: screen.fill(white) message_to_screen("Game over", red) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_exit = True game_over = False if event.key == pygame.K_c: game_loop() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x_change = -10 lead_y_change = 0 elif event.key == pygame.K_RIGHT: lead_x_change = 10 lead_y_change = 0 elif event.key == pygame.K_UP: lead_y_change = -10 lead_x_change = 0 elif event.key == pygame.K_DOWN: lead_y_change = 10 lead_x_change = 0 if lead_x >= 400 or lead_x< 0 or lead_y >= 400 or lead_y < 0: game_over = True lead_x += lead_x_change lead_y += lead_y_change screen.fill(background_color) pygame.draw.rect(screen, red, [randAppleX, randAppleY, 10, 10]) pygame.draw.rect(screen, green, (lead_x, lead_y, 10, 10)) snakehead= [] snakehead.append(lead_x) snakehead.append(lead_y) snakelist.append(snakehead) if len(snakelist) > snakelength: del snakelist[0] for eachSegment in snakelist[:-1]: if eachSegment == snakehead: game_over = True snake(snakelist) pygame.display.update() if lead_x == randAppleX and lead_y == randAppleY: randAppleX = round(random.randrange(0, width - 10)/10.0) * 10.0 randAppleY = round(random.randrange(0, height - 10)/10.0) * 10.0 snakelength += 1 clock.tick(10) game_loop()
b05d4a8427da78bedb0cc9cf0b254f503fb8cf47
xaviruvpadhiyar98/Python-Assignments
/largestContinuousSum().py
367
3.890625
4
#largest Continues SUM problem in given array including negative numbers def large_cont_sum(arr): if len(arr)==0: return 0 max_sum=current_sum=arr[0] for num in arr[1:]: current_sum=max(current_sum+num,num) max_sum=max(current_sum,max_sum) print(max_sum) large_cont_sum([1,2,-1,3,4,-1])
cb471cfb4b4c98957e315ad860be4b5a82cf5f13
savadev/leetcode-2
/non_leetcode/fibonacci.py
651
3.75
4
class Solution(): def recursive(self, n): def f(x): if x in [0,1]: return x return f(x-1) + f(x-2) return f(n) def iterative(self, n): array = [0 for _ in range(n+1)] array[1] = 1 for i in range(2, n + 1): array[i] = array[i-1] + array[i-2] return array[n] def iterative_2(self, n): a = 0 b = 1 for _ in range(1, n + 1): tmp = b b += a a = tmp return a r = Solution() res1 = r.recursive(5) res2 = r.iterative(5) res3 = r.iterative_2(5) print (res1, res2,res3)
42f42fa820fa5b3f1c4172f07155660cdbec0a5a
aka-luana/AulaEntra21_Luana
/Outros/URI/uri_1045.py
603
3.90625
4
a, b, c = input().split() a = float(a) b = float(b) c = float(c) lista = [a, b, c] lista.sort(reverse = True) a = lista[0] b = lista[1] c = lista[2] if (a >= b + c): print("NAO FORMA TRIANGULO") else: if(a ** 2 == b ** 2 + c ** 2): print("TRIANGULO RETANGULO") if(a ** 2 > b ** 2 + c ** 2): print("TRIANGULO OBTUSANGULO") if(a ** 2 < b ** 2 + c ** 2): print("TRIANGULO ACUTANGULO") if(a == b and b == c): print("TRIANGULO EQUILATERO") if((a == b and b != c) or (a == c and b != c) or (b == c and c != a)): print("TRIANGULO ISOSCELES")
302315a10b03e89b72b9a6518258eab425362380
Nicholas-Fabugais-Inaba/Sudoku
/sudokusolverGUI.py
14,397
3.625
4
import pygame from sudokusolver import solver, valid_num, create_puzzle, finish_grid, start_grid, find_empty import time pygame.font.init() def generate_Board(): #generate random puzzle return create_puzzle(finish_grid(start_grid())) class Grid: def __init__(self, rows, columns, width, height): #initialize board values self.board = generate_Board() self.rows = rows self.columns = columns self.width = width self.height = height self.squares = [[Square(self.board[i][j], i, j, width, height) for j in range(columns)] for i in range(rows)] self.model = None self.selected = None def new_board(self, window, board, time, button1, button2): #generates a new board self.board = generate_Board() self.rows = board.rows self.columns = board.columns self.width = board.width self.height = board.height self.squares = [[Square(self.board[i][j], i, j, self.width, self.height) for j in range(self.columns)] for i in range(self.rows)] self.model = None self.selected = None redraw_window(window, board, time, button1, button2) pygame.display.update() def update_model(self): #updates the board model self.model = [[self.squares[i][j].num for j in range(self.columns)] for i in range(self.rows)] def place(self, num): #places inputted number into the board row, column = self.selected if self.squares[row][column].num == 0: self.squares[row][column].set(num) self.update_model() if valid_num(self.model, num, (row, column)) and solver(self.model): return True else: self.squares[row][column].set(0) self.squares[row][column].set_temp(0) self.update_model() return False def sketch(self, num): #places a 'sketched/temporary' value to aid the user row, column = self.selected self.squares[row][column].set_temp(num) def draw(self, window): #draws the board gap = self.width / 9 for i in range(self.rows + 1): if i % 3 == 0 and i != 0: thick = 4 else: thick = 1 pygame.draw.line(window, (0,0,0), (0, i*gap), (self.width, i*gap), thick) pygame.draw.line(window, (0,0,0), (i*gap, 0), (i*gap, self.height), thick) for i in range(self.rows): for j in range(self.columns): self.squares[i][j].draw(window) def select(self, row, column): #sets every square to be unselected 'False' and the actual row, column #of the selected square to be selected 'True' try: for i in range(self.rows): for j in range(self.columns): self.squares[i][j].selected = False self.squares[row][column].selected = True self.selected = (row, column) except IndexError: self.selected = None def clear(self): #clears the selected square to become empty '0' row, column = self.selected if self.squares[row][column].num == 0: self.squares[row][column].set_temp(0) def click(self, position): #returns the position on the board that is selected if position[0] < self.width and position[1] < self.height: gap = self.width / 9 x = position[0] // gap y = position[1] // gap return (int(y), int(x)) else: return None def is_finished(self): #checks each value and if all values are not empty '0' board is finished for i in range(self.rows): for j in range(self.columns): if self.squares[i][j].num == 0: return False return True def solve_board(self, window, board, time, button1, button2): for event in pygame.event.get(): if event.type == pygame.QUIT: exit() empty = find_empty(self.board) if not empty: return True #base case else: row, column = empty for num in range(1, 10): if valid_num(self.board, num, (row,column)): self.select(row, column) self.board[row][column] = num self.squares[row][column].set(num) pygame.time.delay(63) redraw_window(window, board, time, button1, button2) pygame.display.update() if self.solve_board(window, board, time, button1, button2): #if solution found solver finishes return True self.select(row, column) self.board[row][column] = 0 self.squares[row][column].set(0) pygame.time.delay(63) redraw_window(window, board, time, button1, button2) pygame.display.update() return False class Square: rows = 9 columns = 9 def __init__(self, num, row, column, width, height): #initialize individual num values self.row = row self.column = column self.width = width self.height = height self.num = num self.temp = 0 self.selected = False def draw(self, window): font = pygame.font.SysFont("comicsans", 40) gap = self.width / 9 x = self.column * gap y = self.row * gap #draw sketch if self.temp != 0 and self.num == 0: text = font.render(str(self.temp), 1, (128, 128, 128)) window.blit(text, (x+5, y+5)) #draw board num value elif not(self.num == 0): text = font.render(str(self.num), 1, (0, 0, 0)) window.blit(text, (x + (gap/2 - text.get_width()/2), y + (gap/2 - text.get_height()/2))) #draw red border around selected square if self.selected: pygame.draw.rect(window, (0, 0, 255), (x, y, gap, gap), 3) def set(self, num): #set num value to num self.num = num def set_temp(self, num): #set temp num value to num self.temp = num class Button: def __init__(self, color, x, y, width, height, text=''): #initialize values to button object properties self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text def draw(self, window, outline=None): #draw button outline and text if outline: pygame.draw.rect(window, outline, (self.x-2, self.y-2, self.width+4), 0) pygame.draw.rect(window, self.color, (self.x, self.y, self.width, self.height), 0) if self.text != '': font = pygame.font.SysFont('comicsans', 40) text = font.render(self.text, 1, (0,0,0)) window.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))) def hover(self, position): #return if the button is hovered over with mouse or not if position[0] > self.x and position[0] < self.x + self.width: if position[1] > self.y and position[1] < self.y + self.height: return True return False def redraw_window(window, board, time, button1, button2): #draw background window white window.fill((255, 255, 255)) font = pygame.font.SysFont('Bahnschrift', 40) text = font.render(str(time), 1, (0,0,0)) window.blit(text, (374, 542)) button1.draw(window) button2.draw(window) board.draw(window) def main(): #initialize what will be displayed in the window window = pygame.display.set_mode((540, 600)) pygame.display.set_caption("Sudoku") solveButton = Button((255, 255, 255), 195, 545, 150, 50, 'SOLVE') new_gameButton = Button((255, 255, 255), 0, 545, 180, 50, 'NEW GAME') board = Grid(9, 9, 540, 540) x_arrow_movement = 0 y_arrow_movement = 0 key = None running = True start = time.time() #allows window to keep running until board is finished while running: time_passed = round(time.time() - start) play_time = time.strftime('%H:%M:%S', time.gmtime(time_passed)) for event in pygame.event.get(): position = pygame.mouse.get_pos() if event.type == pygame.QUIT: #quits out of pygame window running = False if event.type == pygame.MOUSEBUTTONDOWN: #if solve button is pressed, visually solves the board using a recursive backtracking algorithm if solveButton.hover(position): if board.is_finished(): print("GAME OVER!") else: print("SOLVING...") board.solve_board(window, board, play_time, solveButton, new_gameButton) print("SOLVED!") #if new game button is pressed, creates a new board if new_gameButton.hover(position): board.new_board(window, board, play_time, solveButton, new_gameButton) print("NEW GAME!") start = time.time() x_arrow_movement = 0 y_arrow_movement = 0 if event.type == pygame.MOUSEMOTION: #buttons change color when mouse is hovering over their position if solveButton.hover(position): solveButton.color = (180, 180, 180) else: solveButton.color = (255, 255, 255) if new_gameButton.hover(position): new_gameButton.color = (180, 180, 180) else: new_gameButton.color = (255, 255, 255) if event.type == pygame.KEYDOWN: #number keys pressed set key to number, arrow keys pressed move in arrow key direction #backspace clears number from board, if sketched #return key enters in sketched number if event.key == pygame.K_UP: try: y_arrow_movement-=1 board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) key = None except (UnboundLocalError, TypeError): clicked = (5, 4) board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) if event.key == pygame.K_DOWN: try: y_arrow_movement+=1 board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) key = None except (UnboundLocalError, TypeError): clicked = (3, 4) board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) if event.key == pygame.K_LEFT: try: x_arrow_movement-=1 board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) key = None except (UnboundLocalError, TypeError): clicked = (4, 5) board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) if event.key == pygame.K_RIGHT: try: x_arrow_movement+=1 board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) key = None except (UnboundLocalError, TypeError): clicked = (4, 3) board.select(clicked[0]+y_arrow_movement, clicked[1]+x_arrow_movement) if event.key == pygame.K_1: key = 1 if event.key == pygame.K_2: key = 2 if event.key == pygame.K_3: key = 3 if event.key == pygame.K_4: key = 4 if event.key == pygame.K_5: key = 5 if event.key == pygame.K_6: key = 6 if event.key == pygame.K_7: key = 7 if event.key == pygame.K_8: key = 8 if event.key == pygame.K_9: key = 9 if event.key == pygame.K_BACKSPACE: board.clear() key = None if event.key == pygame.K_RETURN: i, j = board.selected if board.squares[i][j].temp != 0: if board.place(board.squares[i][j].temp): print("SUCCESS!") else: print("WRONG") key = None if board.is_finished(): print("GAME OVER!") #selects square clicked on by mouse if event.type == pygame.MOUSEBUTTONDOWN: clicked = board.click(position) if clicked: board.select(clicked[0], clicked[1]) key = None #key sketched into square if board.selected and key != None: board.sketch(key) redraw_window(window, board, play_time, solveButton, new_gameButton) pygame.display.update() main() pygame.quit()
af82f0999388418b9bd9a33a4b7e092638c2d593
jennifersong/advent_of_code
/3/day3a.py
1,562
3.859375
4
import os from collections import defaultdict # Santa is delivering presents to an infinite two-dimensional grid of houses. # # He begins by delivering a present to the house at his starting location, and then an # elf at the North Pole calls him via radio and tells him where to move next. Moves are # always exactly one house to the north (^), south (v), east (>), or west (<). After each # move, he delivers another present to the house at his new location. # Location notation doesn't really matter as long as you are consistent about how # you traverse according to the directions, but we'll start with (0, 0) and modify the # y-coordinate when going up and down and the x-coordinate when going right and left def deliver_presents(location, directions): presents_delivered = defaultdict(int) # Deliver a present to the starting location presents_delivered[location] += 1 for direction in directions: if direction == '^': location = (location[0], location[1] + 1) elif direction == 'v': location = (location[0], location[1] - 1) elif direction == '>': location = (location[0] + 1, location[1]) elif direction == '<': location = (location[0] - 1, location[1]) presents_delivered[location] += 1 # Return a hash of {location: num_presents_delivered} return presents_delivered starting_location = (0, 0) with open(os.path.dirname(os.path.abspath(__file__)) + '/day3input.txt') as file: for line in file: total_presents = deliver_presents(starting_location, line) print len(total_presents.keys())
1c8b52b56cea57fe490e87cfc5624f0c934553f3
talesritz/Learning-Python---Guanabara-classes
/Exercises - Module I/EX024 - Verificando as primeiras letras de um texto.py
363
4.09375
4
#Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'SANTO' print('-=-'*13) print('EX024 - Verificando as Primeiras Letras') print('-=-'*13) print('\n') name = input('type your citys name here: ').strip() splited = name.split() print('Does the name of the city starts with Santo?: ', 'SANTO' in splited.upper())
5fcd5710f47340e1b526f59e19f0a5e2430793c3
JerryHu1994/LeetCode-Practice
/Solutions/445-Add-Two-Numbers-II/python.py
1,101
3.65625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ stack1, stack2 = [], [] curr1, curr2 = l1, l2 while curr1!=None: stack1.append(curr1.val) curr1 = curr1.next while curr2!=None: stack2.append(curr2.val) curr2 = curr2.next ret = None carry = 0 while len(stack1)!=0 or len(stack2)!=0: val1 = stack1.pop() if len(stack1)!=0 else 0 val2 = stack2.pop() if len(stack2)!=0 else 0 currsum = val1 + val2 + carry carry = 1 if currsum >= 10 else 0 node = ListNode(currsum%10) node.next = ret ret = node if carry==1: node = ListNode(1) node.next = ret ret = node return ret
4cb471751bec4c0436b050323c549a193092a561
karthik-siru/practice-simple
/trees/unique_lines_in_binary_tree.py
1,203
4.21875
4
#question ''' Given a binary tree root, return the number of unique vertical lines that can be drawn such that every node has a line intersecting it. Each left child is angled at 45 degrees to its left, while the right child is angled at 45 degrees to the right. For example, root and root.left.right are on the same vertical line. Constraints 1 ≤ n ≤ 100,000 where n is the number of nodes in root Example 1: Input root = [1, [2, [3, null, null], null], [4, null, [5, null, null]]] Output 5 ''' ''' Traverse each node, keeping track of its position along the X axis. Store each position X into a Set, since it holds only unique integers. We can do this with DFS having 2 params -> node & positionX. Finally after traversing all nodes (and storing all unique positions via the set), return the size of the set . Note::: I found this good approach in binary_search ... ''' def solve(self, root): lines = set() def dfs(root, x): nonlocal lines if not root: return lines.add(x) dfs(root.left, x - 1) dfs(root.right, x + 1) dfs(root, 0) return len(lines)
9edf429620d081d02b9e27dd4d119b7327ee4e0c
oldomario/CursoEmVideoPython
/desafio23.py
581
4.1875
4
""" Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. """ numero = int(input('Digite um número de 0 a 9999: ')) while numero < 0 or numero > 9999: numero = int(input('Número inválido!!! Digite um número de 0 a 9999: ')) unidade = numero // 1 % 10 dezena = numero // 10 % 10 centena = numero // 100 % 10 milhar = numero // 1000 % 10 print('Analisando o número {}'.format(numero)) print('Unidade: {}'.format(unidade)) print('Dezena: {}'.format(dezena)) print('Centena: {}'.format(centena)) print('Milhar: {}'.format(milhar))
c3aaff3842144d6e9f5f1de7082e0be48d90a07e
Cameron-Calpin/Code
/Python - learning/Classes/set_functions.py
1,022
3.8125
4
class Set: def __init__(self, value = []): # constructor self.data = [] # manages a list self.concat(value) def intersect(self, other): # other is any sequence res = [] # self is the subject for x in self.data: if x in other: # pick common items res.append(x) return Set(res) # return a new Set def union(self, other): # other is any sequence res = self.data[:] # copy of my list for x in other: # add items in other if not x in res: res.append(x) return Set(res) def concat(self, value): # value: list, Set... for x in value: # removes duplicates if not x in self.data: self.data.append(x) def __len__(self): # on len(self) return len(self.data) def __getitem__(self, key): # on self[i] return self.data[key] def __and__(self, other): # on self & other return self.intersect(other) def __or__(self, other): # on self | other return self.union(other) def __repr__(self): return 'Set: %s' % self.data # on print
4dbda697cfafeaab669386ebdd499a47ae5d26de
S-V-Naidu/Projects
/Python Codes/StockSelecting.py
921
3.578125
4
def selectStock(saving, currentvalue, futurevalue): y=[] for i in range(len(currentvalue)): c = futurevalue[i] - currentvalue[i] y.append(c) y = y.sort(reverse=True) print(type(y)) print(y) sum=0 if y is not None: for i in range(len(y)): if y[i]<=0: continue if(sum<saving and currentvalue[i]<=saving): sum += currentvalue[currentvalue.index(y[i])] return sum saving = int(raw_input("Enter the savings:")) length = int(raw_input("Enter the lenght:")) print("Enter the current values: ") currentvalue=[] futurevalue=[] i=length while i!=0: currentvalue.append(int(raw_input())) i = i-1 print("Enter the future values: ") i=length while i!=0: futurevalue.append(int(raw_input())) i = i-1 print(selectStock(saving,currentvalue,futurevalue))
7fe17823a5386d16268e7b348e8eaec89e338ae0
tian5017/LX
/suanfa/动态规划.py
2,742
3.859375
4
# 动态规划-求两个字符串的最长公共子串(相同字符个数) # 计算公式:如果对应位置两个字符相等,则此处网格的值位左上角网格的值加1,如果不相等,则为0 def dynamic_str(str1, str2): if str1 == "" or len(str1) == 0 or str2 == "" or len(str2) == 0: return 0 row_l = min(len(str1), len(str2)) col_l = max(len(str1), len(str2)) str_arr = [[0 for _ in range(col_l)] for _ in range(row_l)] tmp_str1 = str1 if len(str1) == row_l else str2 tmp_str2 = str2 if len(str2) == col_l else str1 return_num = 0 for i in range(row_l): for j in range(col_l): if tmp_str1[i] == tmp_str2[j]: if i > 0 and j > 0: str_arr[i][j] = str_arr[i-1][j-1] + 1 else: str_arr[i][j] = 1 if str_arr[i][j] > return_num: return_num = str_arr[i][j] return return_num # 动态规划-求两个字符串的最长公共子序列(对应位置相同字符个数) # 计算公式:如果对应位置两个字符相等,则此处网格的值位左上角网格的值加1,如果不相等,则选择上方和左方邻居中大的那个 def dynamic_seq(str1, str2): if str1 == "" or len(str1) == 0 or str2 == "" or len(str2) == 0: return 0 row_l = min(len(str1), len(str2)) col_l = max(len(str1), len(str2)) str_arr = [[0 for _ in range(col_l)] for _ in range(row_l)] tmp_str1 = str1 if len(str1) == row_l else str2 tmp_str2 = str2 if len(str2) == col_l else str1 return_num = 0 for i in range(row_l): for j in range(col_l): if tmp_str1[i] == tmp_str2[j]: if i > 0 and j > 0: str_arr[i][j] = str_arr[i-1][j-1] + 1 if str_arr[i][j] > return_num: return_num = str_arr[i][j] else: str_arr[i][j] = 1 else: if i > 0 and j > 0: str_arr[i][j] = max(str_arr[i-1][j], str_arr[i][j-1]) elif i > 0 and j == 0: str_arr[i][j] = str_arr[i - 1][j] elif i == 0 and j > 0: str_arr[i][j] = str_arr[i][j - 1] if str_arr[i][j] > return_num: return_num = str_arr[i][j] return return_num # 利用最长公共子序列求编辑距离 def leven_str(str1, str2): if str1 == "" or len(str1) == 0 or str2 == "" or len(str2) == 0: return 0 return_num = dynamic_seq(str1, str2) return max(len(str1), len(str2)) - return_num if __name__ == "__main__": print("编辑距离:" + str(leven_str("哈哈", "中华共和国")))
da136451160c455372b529450114b97572a4b0bc
sanskriti-agrawal/python-lab
/pt2.py
72
3.53125
4
h=int(input()) for i in range(1,h+1): print(' '*(h-i)+'*'*(i)) print()
4da0a3f599de32bec9e1d1d9a63b310234c3b349
ruddysimon/Python_bank_analysis
/ByBank/main.py
2,447
4.0625
4
import os import csv # CSV FILE csv_file = os.path.join("Resources","budget_data.csv") # LIST TO STORE DATA total_month = [] net_total = [] average_change_total= [] average_change = [] great_pdecrease = [] great_pincrease = [] # OPEN AND READ THE CSV FILE with open(csv_file, newline="") as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") # SKIP THE ROW IF THERE IS NO HEADER csv_header = next(csv_reader) # print(f"CSV HEADER : {csv_header}") # LOOPING THROUGH THE ROWS IN ORDER TO FIND THE TOTAL NET AND TOTAL MONTHS for row in csv_reader: net_total.append(float(row[1])) total_month.append(row[0]) # PRINT THE TOTAL MONTHS AND TOTAL REVENUE print("Financial Analysis") print("_________________________") print("Total Months :", len(total_month)) print("Total Revenue : $", sum(net_total)) #TOTAL DIFFERENCE OF AVERAGE for i in range(1,len(net_total)): average_change.append(net_total[i] - net_total[i-1]) average_change_total = sum(average_change)/len(average_change) # PRINT THE AVERAGE CHANGE print("Average Change : $" , float(average_change_total)) # FIND GREATEST INCREASE AND DECREASE CHANGE great_pdecrease = min(average_change) great_pincrease = max(average_change) # FIND GREATEST INCREASE AND DECREASE DATES max_increase_date = str(total_month[average_change.index(max(average_change))]) min_decrease_date = str(total_month[average_change.index(min(average_change))]) # PRINT THE MAXIMUM INCREASE DATE AND MINIMUM INCREASE DATE print("Greatest Increase In Profits :",max_increase_date,"($" , great_pincrease,")") print("Greatest Decrease In Profits :",min_decrease_date,"($" , great_pdecrease,")") # PRINT AS TEXT FILE text_export = os.path.join("Data_financial.csv") with open(text_export,"w",newline="") as text_file: csv_writer = csv.writer(text_file) csv_writer.writerow(["Financial Analysis"]) csv_writer.writerow(["_________________________"]) csv_writer.writerow(["Total Months :", len(total_month)]) csv_writer.writerow(["Total Revenue : $", sum(net_total)]) csv_writer.writerow(["Average Change : $" , float(average_change_total)]) csv_writer.writerow(["Greatest Increase In Profits :",max_increase_date,"($" , great_pincrease,")"]) csv_writer.writerow(["Greatest Decrease In Profits :",min_decrease_date,"($" , great_pdecrease,")"])
883bbd0fa617f00c8296854f51829fa2789d3d00
hjh0915/toronto_exercise
/q6.py
732
3.796875
4
HIT = 'X' MISS = 'M' def count_hits_and_misses(board): """ (list of list of str) -> list of int Precondition: board != [] and each list in board has len(board) Return a list that contains the number of occurrences of the HIT or MISS symbol in each row of board. >>> board = [['-','M','-'], ['X','M','-'], ['-','-','-']] >>> count_hits_and_misses(board) [1, 2, 0] """ s = [] #遍历 for i in board: #累加 num = 0 for j in i: if j == HIT or j == MISS: num = num + 1 s.append(num) return s if __name__ == '__main__': board = [['-','M','-'], ['X','M','-'], ['-','-','-']] print(count_hits_and_misses(board))
0447d2a3760ff795f387802c8e41f5d6c099de7c
mrslwiseman/python
/printTable.py
504
3.84375
4
tableData = [ ['apples', 'oranges', 'cherries', 'bananas'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose'] ] def printTable(data): for cell in range(len(data[0])): longestWord = 0 for line in data: for x in line: if len(x) > longestWord: longestWord = len(x) for line in range(len(data)): print(data[line][cell].rjust(longestWord), end=" ") print() printTable(tableData)
0fda4f79f00a182406a7de168c425d27c8b92127
Matheus872/Python
/Learning/ex034 (Aumentos múltiplos).py
153
3.78125
4
s = float(input('Insira o salário atual: ')) if s>1250: sa = 1.1*s else: sa = 1.15*s print('O salário com aumento é de: R${:.2f}'.format(sa))
8df5b547cdb45a613d7c0df4cf14b9ef0149e95e
angelortiz0398/dada2020-1
/Examenes/A-1.py
737
3.59375
4
def numfalta(L,e): Lc = [0,1,2,3,4,5,6,7,8,9] s = 0 res = 0 List = L if len(List) < 9: if List != Lc: for i in range(e): Lc.remove(List[i]) print("Los elementos que faltan ",Lc) else: if len(List) == 10: print("No falta ninguno") else: for i in range(e): s += int(List[i]) res = -1 * (s - 45) print("El numero que falta es: " + str(res)) def main(): L = [] print("Cantidad de elementos: ") e = int(input()) for i in range(e): L.append(int((input("Dame tu elemento: ")))) numfalta(L,e) if __name__ == '__main__': main()
64cb2afa79fd3d6a4bd00b69c683bd3ac92a41ca
junfeiZTE/pythonCode
/列表用法.py
198
3.703125
4
a=[1,2,3,4,5,6] print(a) a.append(7) print(a) a.insert(1,8) print(a) a.remove(4) print(a) print(a[3]) print(a.index(8)) print(a.count(4)) a.sort() print(a) a.reverse() print(a)
cd69992f6136bb4071feb6771c281f02b5857327
unet-echelon/by_of_python_lesson
/Molchanov/functions.py
555
3.640625
4
# movie = 'The good, the bad, adn the ugly' # rating = 100 # resault = f'Movie: "{movie}", rating: {rating}' # print(resault) # movie = 'Alien' # rating = 200 # resault = f'Movie: "{movie}", rating: {rating}' # print(resault) greeting = 'Hello' to = "World" def greet(message, name): # print('Hello', name) resault = f'{message}, {name}' # print(resault) return resault g = greet(greeting, to).title() print(g) def movies(movie, rating): resault = f'Movie: {movie}, rating: {rating}' return resault ss = movies("alien", "254") print(ss)
1c5e6580163614935e51745d20f6898360d46992
bondiano/skillsmart-py
/algorithms/stack.py
1,289
3.890625
4
class Stack: def __init__(self): self.stack = [] def size(self): return len(self.stack) def pop(self): if (self.size() == 0): return None # если стек пустой return self.stack.pop(0) def push(self, value): self.stack.insert(0, value) def peek(self): if (self.size() == 0): return None # если стек пустой return self.stack[0] def is_balanced(string: str) -> bool: brackets_stack = Stack() for char in string: if char == '(': brackets_stack.push(char) elif char == ')' and not brackets_stack.pop(): return False return not brackets_stack.size() def postfix_calc(string: str) -> int: operations = { "+": lambda a, b: a + b, "*": lambda a, b: a * b, "/": lambda a, b: b / a, "-": lambda a, b: b - a } number_stack = Stack() for char in string.split(' '): if char.isdigit(): number_stack.push(int(char)) elif char == '=': return number_stack.peek() else: a = number_stack.pop() b = number_stack.pop() result = operations[char](a, b) number_stack.push(result)
d011a84e5b641515eb0da381a9f01f464e28e67f
pygogogo/author_zmt
/public/str_to_format.py
841
3.78125
4
def strFormatNum(num_format): new_num = 0 try: if '亿' in num_format: new_num = float(num_format.replace('亿', '')) new_num = new_num * 100000000 new_num = int(new_num) # return new_num elif 'w' in num_format: new_num = float(num_format.replace('w', '')) new_num = new_num * 10000 new_num = int(new_num) # return new_num elif '万' in num_format: new_num = float(num_format.replace('万', '')) new_num = new_num * 10000 new_num = int(new_num) else: new_num = int(num_format) # return new_num except Exception as e: print(e) finally: return new_num if __name__ == '__main__': a = strFormatNum('1万') print( a)
79c05f9f20ae94059e0b4b4bc63ee75bead0ca40
aaliyah-jardien/python-art
/123.py
1,100
3.765625
4
from tkinter import * root = Tk() root.geometry("300x300") # functions choice=None def one(): global choice choice='Choice 1' def two(): global choice choice='Choice 2' def start(): global choice if choice=='Choice 1': elif choice=='Choice 2': else: #do something else since they didn't press either # butons Choice_1_Button=Button(root, text='Choice 1', command=one) #what should it do? Choice_2_Button=Button(root, text='Choice 2', command=two) Start_Button=Button(root, text='Start', command=start) #and what about this? root.mainloop() # If you want to use radio buttons, it will make it easier: # # def start(choice): # if choice=='Choice 1': # foo1() # elif choice=='Choice 2': # foo2() # else: # #do something else since they didn't press either # var=StringVar(root) # var.set(None) # Radiobutton(root, text='Choice 1', value='Choice 1', variable=var).pack() # Radiobutton(root, text='Choice 2', value='Choice 2', variable=var).pack() # Button(self.frame, text='Start', command=lambda: start(var.get())).pack()
90889b7165fb49caf8c9575c1c43d233796a16c9
maits/25-small-python-projects
/guess-number-2.py
490
4.03125
4
import random secret_num = random.randint(1, 1000) i = 1 user_num = input("Hey there! I'm thinking of a number betweetn 1 and 1000. Do you want to guess it? ") while secret_num != user_num: if user_num < secret_num: print ("Too low. Guess again!") i += 1 user_num = input("Guess a number ") elif user_num > secret_num: print ("Too high! Guess again!") i += 1 user_num = input("Guess a number ") print ("You got it right. It took you {0} times to guess it.".format(i))
41457f3c1924b1896f64716c39b7d2c44fddde10
vjvarada/Tipo-Braille-Keyboard
/brailleDotToBin.py
206
3.9375
4
while True: brailleKeys =0 print("Enter Braille Dot Numbers") string = str(input()) for char in string: brailleKeys = brailleKeys | 1 << (6-int(char)) print(bin(brailleKeys))
757911cc0b8e5adf42f261a1909ef1b4b52ad5b8
zhqsherry/Coursera-PY4E
/Sp3 Using Python to Access Web Data/ex_wk6_JSON.py
739
4.03125
4
# Actual data: http://py4e-data.dr-chuck.net/comments_555761.json # The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: import json import urllib.request data = ''' [ { "id" : "001", "x" : "2", "name" : "Chuck" } , { "id" : "009", "x" : "7", "name" : "Brent" } ]''' count = 0 sum = 0 url = input("Enter url - ") data = urllib.request.urlopen(url).read() print(data) info = json.loads(data) for i in info['comments']: count = count + 1 sum = sum + i['count'] print('Sum', sum) print('count', count)
d463d5ebfd0a83b4907b74aee1b6233efa325a02
SafonovMikhail/python_000577
/001703StepPyStudy/Step001703PyStudyсh10_sets_TASK03_20210304_setsIntersec.py
1,161
3.859375
4
''' Задача «Пересечение множеств» Условие Даны два списка чисел. Найдите все числа, которые входят как в первый, так и во второй список и выведите их в порядке возрастания. Примечание. И даже эту задачу на Питоне можно решить в одну строчку. ''' a = input() b = input() a1 = a.split() b1 = b.split() l1 = (list(set(a1) & set(b1))) # print('l1',l1) l2 = [int(elem) for elem in l1] l2.sort() # print('l2',l2) l3 = [str(elem) for elem in l2] print(' '.join(l3)) # решение разработчиков print(*sorted(set(input().split()) & set(input().split()), key=int)) # Yana Charuyskaya a = [int(i) for i in (set(input().split()) & set(input().split()))] a.sort() print(' '.join(str(i) for i in a)) # Леся Фундак A = set([int(n) for n in input().split()]) B = set([int(n) for n in input().split()]) C = sorted(A & B) for i in C: print(i, end=' ') # Альбина Минибаева a = set([int(i) for i in input().split()]) b = set([int(i) for i in input().split()]) r = a & b print(*sorted(r))
3f2615f09a5411389a888acf81f810f0d8d0d3f1
kurenov/algorithms-2
/w1-p1-greedy-schedule.py
1,158
3.71875
4
### # Code by Olzhas Kurenov # Implementation of Greedy Task Scheduler # W1 P1 # 1: 69119377652 # 2: 67311454237 ### print '\n~~~~~~~~~Greedy Task Scheduler~~~~~~~~~\n' # Compares jobs based on score=w-l # if two scores are the same compares by weight def comparerDifference(a, b): # print a, b if (a[2] == b[2]): return b[0] - a[0] else: return b[2] - a[2] def computeWeightedTotal(jobs): weightedCompletionTime = 0 time = 0 for job in jobs: weightedCompletionTime += job[0] * (job[1] + time) time += job[1] return weightedCompletionTime # IO f = open('jobs.txt', 'r') n = int(f.readline()) # preallocating memory jobs = [[0, 0, 0, 0]] * n index = 0 # reading the input for line in f.readlines(): w, l = [float(x) for x in line.split()] jobs[index] = [int(w), int(l), int(w - l), w / l] index += 1 f.close() # sort by difference score jobsByDifference = sorted(jobs, cmp=comparerDifference) print computeWeightedTotal(jobsByDifference) # sort by precomputed division score jobsByDivision = sorted(jobs, key=lambda x:-x[3]) print computeWeightedTotal(jobsByDivision)
1ec5502f2f45fdc128171c4b784d10853229c5a3
mummyli/python_practice
/concurrent_programing/check_thread_start_with_event.py
627
3.65625
4
from threading import Thread, Event import time ''' Event对象包含一个可以有线程设置的信号标志 初始状态下Event的信号标志设置为False 线程会一直等待Event信号标志位True event对象最好单次使用 ''' def countdown(n: int, started_evt: Event) -> None: print("countdown starting") started_evt.set() while(n>0): print("T-minus", n) n -= 1 time.sleep(5) started_evt = Event() print("Launching countdown") t = Thread(target=countdown, args=(10, started_evt)) t.start() started_evt.wait() print("countdown is runnning")
47af14b06661970a66a453c3a5e0e314cae24a58
garlock402/MonsterSlash
/game.py
2,218
3.6875
4
import random from actors import Player, Enemy, Ogre, Imp class Game: def __init__(self, player, enemies): self.player = player self.enemies = enemies def main(): print_intro() play() def print_intro(): print(''' Monster Slash!!! Ready Player One! [Press Enter to Continue] ''') input() def play(): enemies = [ Enemy('Ogre', 1), Enemy('Imp', 1) ] player = Player('Hercules', 1) print(enemies) print(player) while True: next_enemy = random.choice(enemies) cmd = input('You see a {}. [R]un, [A]ttack, [P]ass ').format(next_enemy.kind) if cmd == 'R': print('{} runs away!'.format(player.name)) print('{} heals thyself!'.format(self.player.name)) self.player.heal() print(self.player.hp) elif cmd == 'A': self.player.attacks(next_enemy if not next_enemy.is_alive(): self.enemies.remove(next_enemy) next_enemy = None if next_enemy: next_enemy_attacks(self.player) if not self.player.is_alive(): print('Game over!') break elif cmd == 'P': print ('You are still considering your next move') if random.randint(1,11) < 5: next_enemy.attacks(self.player) else: print('Please choose a valid option'); self.print_linebreak() self.player.stats() for e in self.enemies: e.stats() self.print.linebreak() print() print('*'*30) print() if not enemies: print('You win! Congrats!') break; if __name__ == '__main__': main() enemies = [ Enemy('Bob', 1, , 'Ogre'), Enemy('Alice', 1, 'Imp') ] player = Player('Hercules', 1) game = Game(player, enemies) print (game.player) print (game.enemies)
3436539628248a97f88100936dafb6e4b9d6fb36
peiyanz/Assessment2_object-orientation
/assessment.py
5,262
4.65625
5
""" Part 1: Discussion 1. What are the three main design advantages that object orientation can provide? Explain each concept. Answer: 1.Encapsulation: Whenever we create an instance, all the attribute and methods come with it. 2.Abstraction: We do not need to know specific info for a method used internally. Hide details from user. 3.Polymorphism: Flexibility of types without conditions. 2. What is a class? Answer: Class is a type of something. Ex: Animal is a class, dog is a instance of Animal class. 3. What is an instance attribute? Answer: Instance attribute is the variable/character/feature attached on that particular instance. 4. What is a method? Answer: A function defined within a class. 5. What is an instance in object orientation?: Answer: an instance is an individual occurrence of a class. It is a more concrete thing. 6. How is a class attribute different than an instance attribute? Give an example of when you might use each. Answer: Class attributes are the same for many instance, but instance attribute is only for that instance use only. Ex: for the class of Human(), the attribute num_of_eys = 2 should be a class attribute since most people have 2 eyes, but if someone has 3 eyes, then he/she should use a instance attribute to override the class attribute. """ # Parts 2 through 5: # Create your classes and class methods class Student(object): """Create student instances with first name, last name and address""" def __init__(self, first_name, last_name, address): self.first_name = first_name self.last_name = last_name self.address = address class Question(object): """Create Question instances with question and correct_answer. It also has a ask_and_evaluate method that check if the user's answer is the same as the correct answer.""" def __init__(self, question, correct_answer): self.question = question self.correct_answer = correct_answer def ask_and_evaluate(self, question, correct_answer): user_answer = raw_input("%s: " % question) if user_answer == correct_answer: return True else: return False class Exam(Question): """Create Exam instance with a exam name. It has method add_question that create list of Question instances. It also has a administer method which keep tracking of how well the user did.""" def __init__(self, name): self.name = name self.questions = [] def add_question(self, question, correct_answer): self.questions.append(Question(question, correct_answer)) def administer(self): self.score = 0 for question in self.questions: if super(Exam, self).ask_and_evaluate(question.question,question.correct_answer): self.score += 1 percentage_score = float(self.score)/len(self.questions) print "Your accuracy is %.2f." % percentage_score return percentage_score class Quiz(Exam): """Create Quiz instance that inherient from Exam Class It has its own version of the administer method, which evaluates if the user has passed/failed the quiz.""" def administer(self): self.quiz_score = 0 for question in self.questions: if super(Exam, self).ask_and_evaluate(question.question,question.correct_answer): self.quiz_score += 1 percentage_score = float(self.quiz_score)/len(self.questions) if percentage_score >= 0.5: print "Congrats! You have passed the quiz!" return True else: print "Failed! You have failed the quiz, please try harder next time!" return False """Test One""" print "Now you are taking an Exam" exam = Exam("final_exam") exam.add_question("What is the method for adding an element to a set?", ".add()") exam.add_question("What is the method for adding an additional element into the list?", ".append()") exam.add_question("What is the method for adding a list of elements to a list?", ".extend()") student = Student("Amy","White", "1304 Post St. San Francisco CA 94113") def take_test(exam, student): score = exam.administer() Student.score = score take_test(exam, student) """Test Two""" print "Now you are taking the second exam." def example(): new_exam = Exam("second_final") new_exam.add_question("What is the method for sorting a list in place?", ".sort()") new_exam.add_question("What is the method for sorting a list not in place?", "sorted()") new_exam.add_question("What is the method for poping an element from a list?", ".pop()") new_student = Student("peiyan", "zhao", "668 Sutter St. San Francisco, CA, 94102") take_test(new_exam, new_student) example() """Test Three -- Quiz""" print "Now you are taking a quiz." q1 = Quiz("first quiz") q1.add_question("How to get the length of a list?", "len()") q1.add_question("How to get all the keys from a dictionary?", ".keys()") q1.add_question("How to check if the key existed in the dictionary?", ".get()") def starting_quiz(q1): q1.administer() starting_quiz(q1)
6e36c13dc5e26e2ca2f316ebb342aab301a07181
zaslavskayaeg/geek-python
/lesson03/homework3/task6.py
1,578
3.84375
4
# 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, # но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. # Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. # Каждое слово состоит из латинских букв в нижнем регистре. # Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо # использовать написанную ранее функцию int_func(). def int_func(word): ''' Преобразование слова из маленьких латинских букв в слово с прописной первой буквой :param word: слово из маленьких латинских букв :return: слово с прописной первой буквой. Если параметр функции введен некорректно возвращает None :rtype: str или None ''' if word.islower(): return word.capitalize() else: return print(int_func('Text')) input_str = input("Введите строку >>> ") words = list(input_str.split(" ")) for word in words: print(int_func(word), end=' ')
af90781bca56b57ed70c9567b2c44d6ca3a165b8
mohmad011/Other_Interstent
/all_of_project-master/python/mypyton/prject5.py
641
3.9375
4
class calc: def __init__(self,a,b): self.a = a self.b = b def add(self): return self.a + self.b def mul(self): return self.a * self.b class powering(calc): def power(self): return pow(self.a , self.b) key = 'yes' while key == 'yes': p = powering(int(input('inter first number ')),int(input('inter second number '))) print('the addtion is ( {} ) '.format(p.add())) print('the muliblication is ( {} ) '.format(p.mul())) print('the powering is ( {} ) '.format(p.power())) key = input('do you want return the process ?? ( yes or no ) \n')
edf01996d1666d1c86a9dd488770c23a84c8ac8a
yingxingtianxia/python
/PycharmProjects/my_python_v03/base1/zhan.py
968
4.03125
4
#!/usr/bin/env python3 #--*--coding: utf8--*-- import sys stack = [] def push_it(): item = input('压栈数据:') stack.append(item) return stack def pop_it(): stack.pop() return stack def view_it(): print(stack) def show_menu(): prompt = """请做出如下选择: 【0】:压栈 【1】:出栈 【2】:查询 【3】:退出 请在(0/1/2/3)中选择:""" cmds = {'0': push_it, '1': pop_it, '2': view_it} while True: choice = input(prompt).strip()[0] if choice not in '0123': print('输入必须在(0/1/2/3)中选择') continue if choice == '3': sys.exit() cmds[choice]() # elif choice == '3': # sys.exit() # elif choice == '0': # push_it() # elif choice == '1': # pop_it() # elif choice == '2': # view_it() if __name__ == '__main__': show_menu()
44d5e5e402f1760d25e0be0477358e242dcb0820
chinuteja/CSPP1
/cspp1-practice/cspp1 assignment/m6/p2/special_char.py
388
3.984375
4
''' author : teja date : 4/8/2018 ''' def main(): ''' Read string from the input, store it in variable str_input. ''' n_n = input() s_s = " " for i_i in n_n: if i_i in "!@#$%^&*/-" : i_i = ' ' s_s = s_s + i_i else: i_i = i_i s_s = s_s + i_i print(s_s) if __name__ == "__main__": main()
a2589fea35afdc908b225d94c0b1db0e84af39b8
Josh999999/python-pi-example
/Main.py
186
3.734375
4
print("Hello World") print("Goodbye World") def main(msg): print(msg) #No longer need comments # Print a message main("Hello People") # This is the next Comment # Another comment
63a16daaa360e324d2d2ff1d8ab56e0dbd5cb29d
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/plltam005/question3.py
270
4.09375
4
import math k=0 pi=2.0 x=5 while (2/x)!=1: if k!=0: pi=pi*(2/k) k=math.sqrt(2+k) x=k print("Approximation of pi:",round(math.pi,3)) radius=eval(input("Enter the radius:\n")) print("Area:",round(pi*radius*radius,3))
ad2ddc9a6f58615d99ac903783a1b6bd9e961250
godori16/PRML_code
/Chapter3/BasisFunction.py
457
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 4 14:47:16 2018 @author: TJ """ import numpy.matlib as matlib import numpy as np def BasisFunction(x, basis_name='polynomial', *options): if basis_name == 'polynomial': basis_function = np.power(matlib.repmat(x, options[0]+1, 1).transpose(), matlib.repmat(np.arange(0, options[0]+1), x.shape[0], 1) ) return basis_function
bf9816b2238b3f3eb01d0706103d2bc3be9e56bb
valeriaGratt/Python
/prikluchenie.py
4,413
4.0625
4
print('Забавная история') print() h=int(input("""Одним дивным-дивным вечером девушка прогуливалась по центру города. Вдруг она заметила какое-то движение в с свою сторону. Это был человек странной внешности. 1-Не обращать внимания и пройти мимо 2-Проявить интерес к нему. (введите цифру вашего ответа)- """)) if h==1: print("Не раскрыв тайну личности, врнуться домой") elif h==2: print('') q=int(input("""Девушка остановилась, чтобы разглядеть его. Проблемы заключалась в том, что из-за солнца, которое было еще со сторон спины, не было видно человека 1-надеть очки 2-тупо пялиться, сжигая глаза, на 'тень' -""")) if q==1: w=int(input(""""Этот объект приблизился к ней и остановился. Её поверг шок от того кто перед ней. Ведь это... 1-Фатиг 2-Одногруппник 3-Звезда -""")) if w==1: print('Эй, твой лебл - херня') elif w==2: print('Сказать, что его отчислили и уйти') elif w==3: e=int(input("""Это оказлся МИХАЙЛОВ.Мужчина остановился. Попровил свои длинные завитые волосы, он проевел своей мощной левой рукой по груди, задвая блестки волосиками и очень внимательно посмотрел на девушку. Издали ему показалось, что Алла, но он ошибся. 1-Начать задавать вопросы 2-Устремить взгляд вперед и уехать -""")) if e==2: print('Закончить арку') elif e==1: t=int(input("""Неожиданно для девушки, он стал задавть вопрос про конференции её матери, про отца и многое другое, связанное с её семьёй 1-Запаниковать и уйти 2-Выслушать вопросы и вскользь отвечать на вопросы -""")) if t==1: print('Закончить арку') elif t==2: print('Узнав ответы на свои вопросы, мужчина встал на детский самокат и уехал в закат') elif q==2: w=int(input(""""Этот объект приблизился к ней и остановился. Её поверг шок от того кто перед ней. Ведь это... 1-Фатиг 2-Одногруппник 3-Звезда -""")) if w==1: print('Эй, твой лебл - херня') elif w==2: print('Сказать, что его отчислили и уйти') elif w==3: e=int(input("""Это оказлся КИРКОРОВ.Мужчина остановился. Попровил свои длинные завитые волосы, он проевел своей мощной левой рукой по груди, задвая блестки волосиками и очень внимательно посмотрел на девушку. Издали ему показалось, что Алла, но он ошибся. 1-Начать задавать вопросы 2-Устремить взгляд вперед и уехать -""")) if e==2: print('Закончить арку') elif e==1: t=int(input("""Неожиданно для девушки, он стал задавть вопрос про конференции её матери, про отца и многое другое, связанное с её семьёй 1-Запаниковать и уйти 2-Выслушать вопросы и вскользь отвечать на вопросы -""")) if t==1: print('Закончить арку') elif t==2: print('Узнав ответы на свои вопросы, мужчина встал на детский самокат и уехал в закат')
acf79d7dba2ede23ed74b40e27e4731ca00b1432
Priya-dharshini-r/practice
/matrix_diagoanl.py
853
3.5625
4
import math list1 = [[1,2,3],[4,5,6],[7,8,9]] n = len(list1) # result = 0 # result2 = 0 # odd_length = math.floor(n/2) p_d = [] s_d = [] for i in range(n): result = list1[i][i] p_d.append(result) print("Primary diagonals",sum(p_d)) # secondary diagonal for i in range(n): result2 = list1[i][n-i-1] # sum1+=result s_d.append(result2) print("Secondary diagonal",sum(s_d)) final_op = p_d + s_d print(sum(final_op)) # print(op) for i in range(n): if n%2 == 1: position = math.floor(n/2) res = list1[position][position] print(res) result = sum(final_op) - res print(result) # for i in range(n): # if n%2 == 1: # result = list1[math.floor(n/2)[i]] # result = sum-list1[[math.floor(n/2)[i]]list1[math.floor(n/2)][i]] # print(result) # e_l = [] # for i in final_op: # if i not in e_l: # e_l.append(i) # print(sum(e_l))
092a9d28eec093e96cb39f72886f7a9e8a855564
Abusagit/practise
/Rosalind/rabbits.py
241
3.734375
4
def rabbits(n, k): # old = 0 on month 1 old1 = 1 # month n old2 = 1 #month 2 old for _ in range(n - 2): old1, old2 = old2, old1 * k + old2 return old2 if __name__ == '__main__': print(rabbits(5,3))
573172a82a3457e67795b5f4567f9462cb7b7f0f
tytea/itp-u6-c2-oop-hangman-game
/hangman/game.py
3,392
3.625
4
from .exceptions import * import random class GuessAttempt(object): def __init__(self, letter, hit=None, miss=None): if hit and miss: raise InvalidGuessAttempt("Can't be both hit and miss") self.letter = letter self.hit = hit self.miss = miss def is_hit(self): return bool(self.hit) def is_miss(self): return bool(self.miss) class GuessWord(object): def __init__(self, answer): if answer == '': raise InvalidWordException("Words are empty") self.answer = answer self.masked = len(answer)*"*" def perform_attempt(self, letter): if len(letter) > 1: raise InvalidGuessedLetterException("Character to guess has len() > 1") def uncover(self, letter): unmask = "" for a, m in zip(self.answer,self.masked): if a.lower() == m.lower(): unmask += a.lower() elif letter.lower() == a.lower() and m == "*": unmask += a.lower() else: unmask += m.lower() return unmask if letter.lower() in self.answer.lower() and letter.lower() not in self.masked.lower(): self.masked = uncover(self, letter) if letter.lower() not in self.answer.lower(): return GuessAttempt(letter, miss=True) return GuessAttempt(letter, hit=True) class HangmanGame(object): WORD_LIST = ['rmotr', 'python', 'awesome'] def __init__(self, list_of_words=WORD_LIST, number_of_guesses=5): if not list_of_words: list_of_words = self.WORD_LIST self.list_of_words = list_of_words self.previous_guesses = [] self.remaining_misses = number_of_guesses self.word = GuessWord(self.select_random_word(list_of_words)) def is_won(self): return self.word.answer == self.word.masked def is_lost(self): return self.remaining_misses == 0 def is_finished(self): return self.is_won() or self.is_lost() def guess(self, letter): letter = letter.lower() if self.is_finished(): raise GameFinishedException() if letter in self.previous_guesses: raise InvalidGuessedLetterException() self.previous_guesses.append(letter) attempt = self.word.perform_attempt(letter) if attempt.is_miss(): self.remaining_misses -= 1 if self.is_won(): raise GameWonException() if self.is_lost(): raise GameLostException() return attempt @classmethod def select_random_word(cls, word_list): if not word_list: raise InvalidListOfWordsException() return random.choice(word_list) # # list_of_words = ['python', 'cat', 'dog'] # test2 = HangmanGame(['hippo']) # test2.guess('p') # test2.guess('o') # print(test2) # # print(isinstance(test2.word, GuessWord)) # # print(test2.word.masked) # print(test2.previous_guesses) # # print(type(test2)) # # print(test3.previous_guesses) # # print(test3) # # print(type(test3))
58cdd9e9474c3f1fc32978dbd2b89732e905c7cb
YuriiKhomych/ITEA_course
/artem_zhuchenko/2_data_types/hw/artem_zhuchenko_data_types.py
1,376
4.4375
4
#creating car price car = 100000 #warning the user of increase print("Price start from 100000$. Please type your parameters. Each one costs 10$.") #Get car brand: desired_brand = input("Please type desired car brand: ") car += 10 #Get car model desired_model = input("Please type desired model: ") car += 10 #Get color desired_color = input("Please type desired color: ") car += 10 #Get car year desired_year = input("Please type year: ") car += 10 #Get engine volume desired_engine_volume = input("Please type desired engine volume: ") car += 10 #Get odometer value desired_odometer_value = input("Please type odometer value: ") car += 10 #Get customer phone number user_input_phone_number = input("Please enter your phone number: ") car += 10 #to view price after specifying parameters print(car) #to calculate final price after applying some coefficients total = ((car*10)/100) #transform user input year from string into integer: year = int(desired_year) #decrease year year -= 2 #transform user input engine volume from string into integer: odometer = int(desired_odometer_value) #decrease volume odometer -= 20000 #showing car summary print("Your selection is: ", desired_brand, desired_model, "of ", year, "in ",desired_color, "with ", desired_engine_volume, "L engine and of ", odometer, "miles experience") print("Price: ", total) #the end.
6bfd3a64721b314f7a779eacb389a3179c5bfc31
alexdsaguiar/faculdade-impacta
/linguagem_programacao_01/ac04_01.py
159
3.734375
4
s=("abc ") vowel=0 consonant=0 for letter in s: if letter in "aeiou": vowel=vowel+1 else: consonant=consonant+1 print(vowel+consonant)
d57d920aa6501b1ee443b2b02cf3d46efd17fc70
dexman/AdventOfCode
/2016/aoc09.py
5,887
3.5625
4
# --- Day 9: Explosives in Cyberspace --- # Wandering around a secure area, you come across a datalink port to a new part # of the network. After briefly scanning it for interesting files, you find one # file in particular that catches your attention. It's compressed with an # experimental format, but fortunately, the documentation for the format is # nearby. # The format compresses a sequence of characters. Whitespace is ignored. To # indicate that some sequence should be repeated, a marker is added to the # file, like (10x2). To decompress this marker, take the subsequent 10 # characters and repeat them 2 times. Then, continue reading the file after the # repeated data. The marker itself is not included in the decompressed output. # If parentheses or other characters appear within the data referenced by a # marker, that's okay - treat it like normal data, not a marker, and then # resume looking for markers after the decompressed section. # For example: # ADVENT contains no markers and decompresses to itself with no changes, # resulting in a decompressed length of 6. # A(1x5)BC repeats only the B a total of 5 times, becoming ABBBBBC for a # decompressed length of 7. # (3x3)XYZ becomes XYZXYZXYZ for a decompressed length of 9. # A(2x2)BCD(2x2)EFG doubles the BC and EF, becoming ABCBCDEFEFG for a # decompressed length of 11. # (6x1)(1x3)A simply becomes (1x3)A - the (1x3) looks like a marker, but # because it's within a data section of another marker, it is not treated any # differently from the A that comes after it. It has a decompressed length of # 6. # X(8x2)(3x3)ABCY becomes X(3x3)ABC(3x3)ABCY (for a decompressed length of 18), # because the decompressed data from the (8x2) marker (the (3x3)ABC) is skipped # and not processed further. # What is the decompressed length of the file (your puzzle input)? Don't count # whitespace. # --- Part Two --- # Apparently, the file actually uses version two of the format. # In version two, the only difference is that markers within decompressed data # are decompressed. This, the documentation explains, provides much more # substantial compression capabilities, allowing many-gigabyte files to be # stored in only a few kilobytes. # For example: # (3x3)XYZ still becomes XYZXYZXYZ, as the decompressed section contains no # markers. # X(8x2)(3x3)ABCY becomes XABCABCABCABCABCABCY, because the decompressed data # from the (8x2) marker is then further decompressed, thus triggering the (3x3) # marker twice for a total of six ABC sequences. # (27x12)(20x12)(13x14)(7x10)(1x12)A decompresses into a string of A repeated # 241920 times. # (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN becomes 445 # characters long. # Unfortunately, the computer you brought probably doesn't have enough memory # to actually decompress the file; you'll have to come up with another way to # get its decompressed length. # What is the decompressed length of the file using this improved format? ################################################################################ import enum class DecompressState(enum.Enum): normal = 0 marker_length = 1 marker_count = 2 repeated = 3 def decompress(characters, initial, weight, reducer, decompress_repeated): state = DecompressState.normal marker_length, marker_count, repeated = 0, 0, '' result = initial for character in characters: if state is DecompressState.normal: if character == '(': state = DecompressState.marker_length else: result = reducer(result, weight, character) elif state is DecompressState.marker_length: if character.isdigit(): marker_length = marker_length * 10 + int(character) elif character == 'x': state = DecompressState.marker_count else: assert False elif state is DecompressState.marker_count: if character.isdigit(): marker_count = marker_count * 10 + int(character) elif character == ')': state = DecompressState.repeated else: assert False elif state is DecompressState.repeated: repeated += character if len(repeated) == marker_length: if decompress_repeated: result = decompress(repeated, result, weight * marker_count, reducer, decompress_repeated=True) else: result = reducer(result, weight * marker_count, repeated) marker_length, marker_count, repeated = 0, 0, '' state = DecompressState.normal else: assert False return result # test_strings = [ # 'ADVENT', # 'A(1x5)BC', # '(3x3)XYZ', # 'A(2x2)BCD(2x2)EFG', # '(6x1)(1x3)A', # 'X(8x2)(3x3)ABCY', # '(27x12)(20x12)(13x14)(7x10)(1x12)A', # '(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN', # ] # for test_string in test_strings: # def string_reducer(result, chars): # result += chars # return result # result = decompress(test_string, '', string_reducer, True) # print(f'{test_string} => {result}') # def length_reducer(result, chars): # result += len(chars) # return result # result = decompress(test_string, 0, length_reducer, True) # print(f'{test_string} => {result}') with open('aoc09.txt', 'r') as f: def length_reducer(result, weight, chars): result += weight * len(chars) return result input_data = f.read().strip() length1 = decompress(input_data, 0, 1, length_reducer, False) length2 = decompress(input_data, 0, 1, length_reducer, True) print(f'Part 1: The decompressed data is {length1} characters.') print(f'Part 2: The decompressed data is {length2} characters.')
5fd9b25c5f0af45b86959b43ecc8ed1143d5273b
urandu/kattis-challenges
/aboveaverage/aboveaverage.py
478
3.65625
4
classes = input() output1 = [] for i in range(int(classes)): class_data = input() marks = class_data.split(" ") y = 0 total_students = int(marks[0]) marks.pop(0) marks = list(map(int, marks)) average = sum(marks)/float(len(marks)) for x in marks: x = int(x) if x > average: y = y+1 output = (y/float(total_students))*100.000 output1.append(format(output, ".3f")) for t in output1: print("{}%".format(t))
cc5ab26fba846fcf0524afdeb7307327a1c345fd
wangchongsheng/fullstack
/week6/day24/继承.py
1,898
3.5625
4
# __author__: wang_chongsheng # date: 2017/10/25 0025 #子承父类 """ class F: #父类,基类 def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): #子类,派生类 def s1(self): print('S.s1') obj=S() obj.s1() obj.f2() """ #子类只继承父类的某些特性 class F: #父类,基类 def f1(self): print('F.f1') def f2(self): print('F.f2') class S(F): #子类,派生类 def s1(self): print('S.s1') def f2(self): # super(S,self).f2()#执行父类或者基类中的f2方法 (推荐使用) F.f2(self) #执行父类或者基类中的f2方法 print('S.f2') """ obj=S() obj.s1() obj.f2() """ """ obj = S() obj.s1() #s1中的self是形参,此时代指 obj obj.f2() #self用于指调用方法的调用者 """ """ #同时执行子类和父类的f2 obj = S() obj.f2() """ """ #多继承 class F0: def b(self): print('F0.b') class F1(F0): def a(self): print('F1.a') class F2: def a(self): print('F2.a') class S1(F1,F2): #从左到右,按顺序继承 pass obj = S1() obj.b() """ #多继承的执行关系 class BaseRequest(): def __init__(self): print('BaseRequest.init') class RequestHandler(BaseRequest): def __init__(self): print('RequestHandler.init') #2 def server_forver(self): #self是obj。。。一定要记住self是谁的obj print('RequestHandler.server_forver') #3 self.process_request() def process_request(self): print('RequestHandler.process_request') class Minx: def process_request(self): print('minx.process_request') #5 class Son(Minx,RequestHandler): #4 pass obj = Son() #1 obj.server_forver() #6 # import socketserver # # obj = socketserver.TCPServer(1,2) #创建对象,init # obj.serve_forever()
db0eebb22daecdf2e457f6c0da59ca8b3fab94bf
aloksahoo92/learnandbuild
/lnbmerge.py
1,350
4.09375
4
''' 14.MAKE A PROGRAM TO MERGE TWO LIST INTO A SINGLE DICTIONARIES ● Take inputs from the user ● Any one list must contain unique elements ● both the list should be of the same size ● both the list should be a combination of numbers and names ● Name of dictionary you can take it accordingly ● file name should be in lnbmerge.py ● commit the code on github link under pythonbasic branch ''' namelist=[] marklist=[] studict={} studno=int(input("\nEnter the number of student :")) for i in range(studno): name=input(f"Enter the name of student {i+1} :") mark=int(input(f"Enter the mark of studend {i+1} :")) namelist.append(name) marklist.append(mark) studict[name]=mark print(f"Name of the student :{namelist}") print(f"Mark of the student :{marklist}") print(f"Detail of the student :{studict}") ''' Sample Output Enter the number of student :4 Enter the name of student 1 :RAJ Enter the mark of studend 1 :45 Enter the name of student 2 :RAHUL Enter the mark of studend 2 :55 Enter the name of student 3 :RAVI Enter the mark of studend 3 :56 Enter the name of student 4 :RAKESH Enter the mark of studend 4 :66 Name of the student :['RAJ', 'RAHUL', 'RAVI', 'RAKESH'] Mark of the student :[45, 55, 56, 66] Detail of the student :{'RAJ': 45, 'RAHUL': 55, 'RAVI': 56, 'RAKESH': 66} '''
fb998c3b96b29df38e11292ba012f9a6dc3c4617
Max-Stevo/Learning-
/Boolean Table.py
172
4.28125
4
true = True false = False if true and false is False: print('true') else: print('false') if true or false is False: print('true') else: print('false')
a11c03c51cd3ab0ae8a0ee9e647e35526ea8631b
coolcatco888/cmpt414-term-project
/character-recognition/prototypes/cley/testwork/layer.py
2,293
3.765625
4
from neuron import Neuron class Layer: size = 0 # size of layer aka number of neurons in layer number_of_inputs = 100 # number of inputs for each neuron aka size of previous # layer neurons = [] # list of neurons in layer def __init__(self, size, number_of_inputs): self.size = size self.number_of_inputs = number_of_inputs self.__initialize_neurons() def __initialize_neurons(self): neurons = [] for i in range(self.size): # TODO: hard-coded weight and threshold gains to 10%, need to fix neurons.append(Neuron(self.number_of_inputs, 0.1, 0.1)) self.neurons = neurons def get_neurons(self): return self.neurons def get_size(self): return self.size def learn(self, x, s): for i in range(len(self.neurons)): neuron = self.neurons[i] neuron.learn(x, s[i]) break return # output - list of outputs for this layer # d - desired output if this is a top layer def calculate_error_terms_for_top_layer(self, output, d): weights = [] s = [] y = output #if len(output) == len(self.neurons): for i in range(len(output)): # calculate error term s.append(y[i] * (1.0 - y[i]) * (d[i] - y[i])) #store weights in layer weights.append(self.neurons[i].getWeights()); return [s, weights] # errors - error terms for all neurons above this layer # layers - reference to the list of layers for the network def calculate_error_terms_for_hidden_layer(self, weights_times_error_sum, x): weights = [] s = [] if len(x) == len(self.neurons): for i in len(self.neurons): # calculate error term s.append(x[i] * (1 - x[i]) * weights_times_error_sum) #store weights in layer weights.append(self.neurons[i].getWeights()); return [s, weights] def calculate(self, inputs): output = [] for neuron in self.neurons: r = neuron.calculate(inputs) output.append(r) return output
e7236b20f385028fc298af384c58aeabe4422e49
guilhermemaas/guanabara-pythonworlds
/exercicios/ex082.py
922
3.9375
4
""" Crie um programa que vai ler varios numeros e colocar em uma lista. Depois disso, crie duas listas extras que vao conter apenas os valores pares e os impares digitados, respectivamente. Ao final, mostre o conteudo das tres listas geradas. """ lista = [] while True: lista.append(int(input('Informe um valor para adicionar a lista: '))) continuar = ' ' while continuar not in 'SN': continuar = str(input('Continuar? [S/N]')).strip().upper()[0] if continuar == 'N': break impares = [] pares = [] for val in range(0, len(lista)): if lista[val] % 2 == 0: pares.append(lista[val]) else: impares.append(lista[val]) print(f'\nTodos os numeros: {lista}.') print(f'Todos os pares: {pares}') print(f'Todos os impares: {impares}') #Guanabara: for i, v in enumerate(lista): if v % 2 == 0: pares.append(v) elif v % 2 == 1: impares.append(v)
8dffa5898317ecfcb4b6588aed74646571627b40
DurgaMahesh31/Python
/source/Control_Statement.py
1,087
3.875
4
logger.info("=============== ATM Application ============== #") logger.info("Insert your card") logger.info("Enter your password:") pass_word = input() # Get Card password from db # To validate the entered password # Get card account details and balance balance = 20000 while True: # while True/Falsee logger.info("Enter option to continue") logger.info("1.Withdraw\t2.Balance Check") option = int(input()) if option == 1: logger.info("Enter amount to Withdraw:") withdraw_amount = int(input()) if withdraw_amount <= balance: balance = balance - withdraw_amount logger.info("Collect Amount: %s", withdraw_amount) else: logger.warning("You entered amount more than available balance") continue elif option == 2: logger.info(balance) else: logger.info("You have selected wrong option, Try again") continue logger.info("Do you want to continuew y/n") continue_option = input() if continue_option == "n": break
0753dd3fbe932d9f480dc7c498a4e5d2856c4128
0xTiefer-Atem/Algorithm-DataStructure-Python
/batch_1/leet_code_168.py
652
3.84375
4
""" Excel表列名称 给定一个正整数,返回它在 Excel 表中相对应的列名称。 例如, 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... 示例 1: 输入: 1 输出: "A" 示例 2: 输入: 28 输出: "AB" 示例 3: 输入: 701 输出: "ZY" """ class Solution: def convertToTitle(self, columnNumber: int) -> str: s = '' while columnNumber: columnNumber -= 1 s = chr(columnNumber % 26 + 65) + s columnNumber = columnNumber // 26 return s if __name__ == '__main__': sol = Solution() print(sol.convertToTitle(777))
4957dcc53977e29f7a2c330b13da84a739901e87
guofei9987/leetcode_python
/solved/[784][Letter Case Permutation][Easy].py
611
3.671875
4
# https://leetcode.com/problems/letter-case-permutation class Solution: def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ if S: if S[0] in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ': return [char+j for char in [S[0].lower(),S[0].upper()] for j in self.letterCasePermutation(S[1:])] else: return [S[0]+j for j in self.letterCasePermutation(S[1:])] else: return [''] S="a1b2" Solution().letterCasePermutation(S) # # Solution().letterCasePermutation('2')
ba6709c5dde9f35180414bb455fd817eed619ff5
Arjun2001/coding
/codechef Bouncing balls.py
208
3.5625
4
import math test=int(input()) while(test): m=int(input()) ctr=0 while(m>0): temp=int(math.log(m,2)) m-=int(math.pow(2,temp)) ctr+=1 print(ctr-1) test-=1
d83887577d4b55edc81cb5f77e316c93f08a8605
andrewghaddad/OOP
/OOP/Notes/Week7/myprogram.py
1,292
4.375
4
# importing """ the import statement tells Python to load the functions that exist within a specific module into memory and make them available to use (import random to use random.randint function) Because you don't see the inner workings of a function inside of a module, we sometimes call them "black boxes" A "black box" describes a mechanism that accepts input and performs an operation that can't be seen using that input and produces some kind of output """ # creating your own module """ Create a new Python script (e.g. myfunctions.py) Place your function defintions inside this script Create new Python script (e.g. myprogram.py) Import your function module using the import statement in myprogram.py import myfunctions Call your functions using the dot notation myfunctions.function1() myfunctions.does_something_else(arg1, arg2) """ """ Create a module called geometry_helper Write two functions in this module - area_of_circle - circumference_of_circle Each function takes on argument (the radius) and returns the result Assume that pi = 3.14 """ import geometry_helper radius = float(input("Please enter a radius: ")) area = geometry_helper.area_of_circle(radius) circumference = geometry_helper.circumference_of_circle(radius) print(area, circumference)
01a7026976f8ef20da7fa3001498174dc8309d15
yddong/Py3L
/src/Week1/test3.py
373
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mytext = "hello world" print(mytext[1]) print(mytext[2:4]) print( mytext[0: : 2 ] ) print(mytext.center(80)) print("Number of es in mytext:", mytext.count("e") ) print("Number of lds in mytext:", mytext.count("ld") ) print(mytext.endswith("ing")) print(mytext.capitalize()) mytext = mytext.capitalize() print(mytext)
a26aee7c1460872e8e2fca2db4fce8f5f4a82c39
MrHamdulay/csc3-capstone
/examples/data/Assignment_1/fnsdan001/question2.py
306
4.15625
4
hours = eval(input("Enter the hours: \n")) minutes = eval(input("Enter the minutes: \n")) sec = eval(input("Enter the seconds: \n")) if hours<=23 and hours>=0 and minutes <=59 and minutes>=0 and sec <=60 and sec>=0: print ("Your time is valid.") else: print ("Your time is invalid.")