blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
d11e3a13abf887f2d150f6c23aa269f90bec5833
ctl106/AoC-solutions
/2020/12/solution2.py
1,787
3.765625
4
#!/usr/bin/env python3 import sys from math import atan2, sin, cos, radians ACTIONS = { "north": "N", "south": "S", "east": "E", "west": "W", "left": "L", "right": "R", "forward": "F" } def rotate(point, direct, deg): if direct == ACTIONS["right"]: deg = 360 - deg rad = radians(deg) rpoint = atan2(point[1], point[0]) new_rpoint = rpoint + rad scale = (point[0]**2 + point[1]**2)**(1/2) rise = round(sin(new_rpoint)*scale) run = round(cos(new_rpoint)*scale) new_point = type(point)((run, rise)) return new_point def split_actions(inlst): actions = [[x[0], int(x[1:])] for x in inlst] return actions def navigate(actions): location = [0, 0] waypoint = [10, 1] #always relative to location! for action in actions: if action[0] == ACTIONS["north"]: waypoint[1] += action[1] elif action[0] == ACTIONS["south"]: waypoint[1] -= action[1] elif action[0] == ACTIONS["east"]: waypoint[0] += action[1] elif action[0] == ACTIONS["west"]: waypoint[0] -= action[1] elif (action[0] == ACTIONS["left"]) or (action[0] == ACTIONS["right"]): waypoint = rotate(waypoint, action[0], action[1]) elif action[0] == ACTIONS["forward"]: location[0] += (waypoint[0] * action[1]) location[1] += (waypoint[1] * action[1]) return location def read_input_file(): if len(sys.argv) <= 1: print("Please specify an input file.") exit(1) inname = sys.argv[1] inlst = [] infile = open(inname, "r") for line in infile: inlst.append(line.strip()) infile.close return inlst def solve(inlst): output = 0 actions = split_actions(inlst) dest = navigate(actions) output = abs(dest[0]) + abs(dest[1]) return output def main(): inlst = read_input_file() result = solve(inlst) print(result) if __name__ == "__main__": main()
73d430c4889d663384edfed2301d211f1fea41eb
Namrata-Choudhari/FUNCTION
/naman.py
5,983
3.796875
4
# print ("NavGurukul") # def say_hello(): # print ("Hello!") # print ("Aap kaise ho?") # say_hello() # print ("Python is awesome") # say_hello() # print ("Hello…") # say_hello() # print("namrata") # #length # name_list=["fiza","shivam","imtiyaz","deepanshu","rahman"] # print(len(name_list)) # def definition_say_hello(): # print("Navgurukul") # print("Navgururkul mei humein apni learning ki responsibility leni padti hai") # definition_say_hello() # print("navgurukul mei hum sab logo ko ek tarah se treat karte hai.") # definition_say_hello() # def function_say_bye(): # print("Aapka mil ke maza aaya") # print("Bye bye") # function_say_bye() # function_say_bye() # print("Python ka bahot jagah hota hai") # function_say_bye() # function_say_bye() # def definition_hello_again(): # print("Firse Hello:)") # print("Aap kaise ho?") # definition_hello_again() # def ask_question(): # print("ek baar") # ask_question() # ask_question() # ask_question() # ask_question() # ask_question() # def ask_question(): # print("ek baar") # i=0 # while i<=100: # ask_question() # i+=1 # #predefine function # n=[3,5,7,34,2,89,2,5] # print(max(n)) # n=[1,2,3,4,5] # print(sum(n)) # #decending order # unorder_list=[6,8,4,3,9,56,0,34,7,15] # unorder_list.sort(reverse=True) # print(unorder_list) # #accending order # unorder_list=[6,8,4,3,9,56,0,34,7,15] # unorder_list.sort() # print(unorder_list) # # Reverse list # reverse_list=["z","a","a","b","e","m","a","r","d"] # reverse_list.reverse() # print(reverse_list) # # minimum # list=[8,6,4,8,4,50,2,7] # print(min(list)) # # Debugging Question # def sum(): # print(12+13) # sum() # def welcome(): # print("Welcome to function") # welcome() # def isEven(): # if(12%2==0): # print("Even Number") # else: # print("Old Number") # isEven() # def greet(*names): # for name in names: # print("Welcome", name) # greet("Rinki", "Vishal", "Kartik", "Bijender") # def info(name, age ="16"): # print(name + " is " + age + " years old") # info("Sonu") # info("Sana", "17") # info("Umesh", "18") # def studentDetails(name,currentMilestone,mentorName): # print("Hello " , name, "your" , currentMilestone, "concept " , "is clear with the help of ", mentorName) # studentDetails("Nilam","loop","Namrata") # def say_hello(name): # print ("Hello ", name) # print ("Aap kaise ho?") # say_hello("Aatif") # say_hello("namrata") # def add_numbers(number1, number2): # print ("Main do numbers ko add karunga.") # print (number1 + number2) # add_numbers(120, 50) # num_x = "134" # name = "rinki" # add_numbers(num_x, name) # def say_hello_people(name_x, name_y, name_z, name_a): # print ("Namaste ", name_x) # hindi mein # print ("Alah hafiz ", name_y) # urdu mein # print ("Bonjour ", name_z) # french mein # print ("Hello ", name_a) # english mein # say_hello_people("Imitiyaz", "Rishabh", "Rahul", "Vidya") # say_hello_people("Steve", "Saswata", "Shakrundin", "Rajeev") # def icecream(*flavours): # for flavour in flavours: # print("i love"+flavour) # icecream("chocolate", "butterscotch","vanilla","strawberry") # def attendance(name,status="absent"): # print(name,"is",status," today") # attendance("kartik","present") # attendance("sonu") # attendance("vishal","present") # attendance("umesh") # # return value # def add_numbers(number_x, number_y): # number_sum = number_x + number_y # return number_sum # sum1 = add_numbers(20, 40) # print (sum1) # sum2 = add_numbers(560, 23) # a = 1234 # b = 12 # sum3 = add_numbers(a, b) # print (sum2) # print (sum3) # number_a = add_numbers(20, 40) / add_numbers(5, 1) # print (number_a) # def add_numbers_print(number_x, number_y): # number_sum = number_x + number_y # print (number_sum) # sum4 = add_numbers_print(4, 5) # print (sum4) # print (type(sum4)) # def add_numbers_more(number_x, number_y): # number_sum = number_x + number_y # print ("Hello from NavGurukul ;)") # return number_sum # number_sum = number_x + number_x # print ("Kya main yahan tak pahunchunga?") # return number_sum # sum6 = add_numbers_more(100, 20) # def menu(day): # if day == "monday": # return "Butter Chicken" # elif day == "tuesday": # return "Mutton Chaap" # else: # return "Chole Bhature" # print ("Kya main print ho payungi? :-(") # mon_menu = menu("monday") # print (mon_menu) # tues_menu = menu("tuesday") # print (tues_menu) # fri_menu = menu("friday") # print (fri_menu) # def menu(day): # if day == "monday": # food = "Butter Chicken" # elif day == "tuesday": # food = "Mutton Chaap" # else: # food = "Chole Bhature" # print ("Kya main print ho payungi? :-(") # return food # print ("Lekin main toh pakka nahi print hounga :'(") # print(menu("monday")) # # inner function # def f1(): # s = "I Love Navgurukul" # def f2(): # print(s) # f2() # f1() # def first_function(): # s = 'I love India' # def second_function(): # print(s) # second_function() # first_function() # def first_function(): # s = 'I love India' # def second_function(): # s = "MY NAME IS JACK" # print(s) # second_function() # print(s) # first_function() # def add(param1, param2): # return param1+param2 # print(add(1,2)) # def centuryFromYear(year): # if year%100==0: # print(int(year/100)) # else: # print(int(year/100+1)) # year=int(input("Enter the Year:")) # centuryFromYear(year) # def list(a): # print(a) # i=0 # s=[] # while i<10: # a=int(input("enter the number:")) # s.append(a) # i+=1 # print(s) # list(a) # def arrange(a): # i=min(a)+1 # count=0 # while i<max(a): # if i not in a: # count+=1 # i+=1 # print(count) # arrange([6,11,8])
f73472838e6ab97b564a1a0a179b7b2f0667a007
Namrata-Choudhari/FUNCTION
/Q3.Sum and Average.py
228
4.125
4
def sum_average(a,b,c): d=(a+b+c) e=d/3 print("Sum of Numbers",d) print("Average of Number",e) a=int(input("Enter the Number")) b=int(input("Enter the Number")) c=int(input("Enter the Number")) sum_average(a,b,c)
8cf7d33af26683fb2439610a1eb725e4299c3a0b
alters-mit/sticky_mitten_avatar
/sticky_mitten_avatar/transform.py
1,428
3.6875
4
import numpy as np class Transform: """ Transform data for an object, avatar, body part, etc. ```python from sticky_mitten_avatar import StickyMittenAvatarController c = StickyMittenAvatarController() c.init_scene() # Print the position of the avatar. print(c.frame.avatar_transform.position) c.end() ``` *** ## Fields - `position` The position of the object as a numpy array: `[x, y, z]` The position of each object is the bottom-center point of the object. The position of each avatar body part is in the exact center of the body part. `y` is the up direction. - `rotation` The rotation (quaternion) of the object as a numpy array: `[x, y, z, w]` See: [`tdw.tdw_utils.QuaternionUtils`](https://github.com/threedworld-mit/tdw/blob/master/Documentation/python/tdw_utils.md#quaternionutils). - `forward` The forward directional vector of the object as a numpy array: `[x, y, z]` *** ## Functions """ def __init__(self, position: np.array, rotation: np.array, forward: np.array): """ :param position: The position of the object as a numpy array. :param rotation: The rotation (quaternion) of the object as a numpy array. :param forward: The forward directional vector of the object as a numpy array. """ self.position = position self.rotation = rotation self.forward = forward
e1f42b2a424458a27f783078cfa99b8fa4e2bfb1
cairnsh/diffusion-limited-aggregation-simulator
/util_sequence.py
753
3.59375
4
import numpy as np # this is 1/ζ(2) = 6/pi^2 = 1/(1 + 1/4 + 1/9 + ...). INVERSE_ZETA_2 = 6 / np.pi**2 def _slowly_increasing_sequence(): "A sequence that sums to 1, but decreases slowly." index = 1 next_highest_power_of_2 = 2 lg_nhp2 = 1 while True: yield 2 * INVERSE_ZETA_2 / next_highest_power_of_2 / lg_nhp2**2 index += 1 if index == next_highest_power_of_2: next_highest_power_of_2 <<= 1 lg_nhp2 += 1 def slowly_increasing_sequence(add_up_to = 1, smoothness = 128): iterator = _slowly_increasing_sequence() total = 1 for i in range(smoothness): total -= next(iterator) scale = add_up_to / total while True: yield scale * next(iterator)
b6c0dc8523111386006a29074b02d1691cf1e054
shivigupta3/Python
/pythonsimpleprogram.py
1,709
4.15625
4
#!/usr/bin/python2 x=input("press 1 for addition, press 2 to print hello world, press 3 to check whether a number is prime or not, press 4 for calculator, press 5 to find factorial of a number ") if x==1: a=input("enter first number: ") b=input("enter second number: ") c=a+b print ("sum is ",c) if x==2: print("Hello World") if x==3: num=int(input("enter a number to check whether its prime or not")) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") else: print(num,"is a prime number") else: print(num,"is not a prime number") if x==4: print("CALCULATOR") def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = int(input("Enter choice(1/2/3/4):")) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print "invalid input" if x==5: num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial)
9aa1b81bcb80494ea9b0c0b4a728a3981723fa43
eecs110/winter2019
/course-files/practice_exams/final/dictionaries/01_keys.py
337
4.40625
4
translations = {'uno': 'one', 'dos': 'two', 'tres': 'three'} ''' Problem: Given the dictionary above, write a program to print each Spanish word (the key) to the screen. The output should look like this: uno dos tres ''' # option 1: for key in translations: print(key) # option 2: for key in translations.keys(): print(key)
1422c7ddfe16c6e81586dde3db6509e61bea09da
eecs110/winter2019
/course-files/lectures/lecture_11/04_dictionary_lookup_from_file.py
687
3.875
4
import json import sys import os # read lookup table from a file: dir_path = os.path.dirname(sys.argv[0]) file_path = os.path.join(dir_path, 'state_capitals.json') f = open(file_path, 'r') capital_lookup = json.loads(f.read()) def get_state_capital(lookup, state): return lookup[state] # use lookup table to answer some questions: print('The capital of Florida is:', get_state_capital(capital_lookup, 'Florida')) print('The capital of Illinois is:', get_state_capital(capital_lookup, 'Illinois')) print('The capital of California is:', get_state_capital(capital_lookup, 'California')) print('The capital of Massachusetts is:', get_state_capital(capital_lookup, 'Massachusetts'))
f00691a55b3785740316a226fef0c469e6df69a0
eecs110/winter2019
/course-files/lectures/lecture_11/07_twitter_data_print_all_status_updates.py
525
3.625
4
import urllib.request import json import pprint # module that makes it easier to print and look at dictionaries # Challenge: write a program that prints all of the status updates search_term = input('Please enter a search term (defaults to "northwestern"): ') if search_term == '': search_term = 'Northwestern' url = 'https://eecs110-twitter-proxy.herokuapp.com/1.1/search/tweets.json?q=' url += search_term request = urllib.request.urlopen(url) data = json.loads(request.read().decode()) pprint.pprint(data, depth=1)
1f9e30f1591d59011b140c9ef8801fd51468b92a
eecs110/winter2019
/course-files/practice_exams/midterm/exam1_answers.py
3,235
4.09375
4
def _print_title(title): print('\n') print('#' * len(title)) print(title) print('#' * len(title)) def problem_1a(): # infinite loop: _print_title('Problem 1.a.') print('infinite loop!') return # i = 0 # while i < 3: # if i % 2 == 0: # continue # print(i = 0) # i += 1 def problem_1b(): _print_title('Problem 1.b.') notes = [27, 44, 30, 26, 17, 28, 46] for note in notes: if note // 3 == 9: print(note) def problem_1c(): _print_title('Problem 1.c.') j = 5 m = 3 k = j / m if k == 1: print('one') elif k == 2: print('two') elif k == 3: print('three') else: print('default') def problem_2a(): _print_title('Problem 2.a.') def area_of_square(length): return length * length def volume_of_cube(area): area * 6 print( 'Volume of a cube where side=10 feet is:', volume_of_cube(area_of_square(10)), 'feet' ) def problem_2b(): _print_title('Problem 2.b.') def make_mad_lib(exclamation, adverb, noun, adjective): print( exclamation + '! he said adverb as he jumped into his convertible ' + noun + ' and drove off with his ' + adjective + ' wife.' ) make_mad_lib('Move it', 'angrily', 'Mazda Miata', 'annoyed') def problem_2c(): _print_title('Problem 2.c.') nums = [9, 25, 16, 4, 81, 100, 64, 49, 36] new_list = [] def sqrt(n): return int(n ** 0.5) i = 0 while i < len(nums): if i % 3 == 0: new_list.append(sqrt(nums[i])) else: new_list.append(nums[i]) i += 1 print(new_list) def problem_3(): _print_title('Problem 3') values = [5, 2, 5, 0, -2, -4, -7, 4, 7, 8] i = 0 while i < 10: num_neg = 0 num_zero = 0 num_pos = 0 if values[i] < 0: num_neg += 1 elif values[i] == 0: num_zero += 1 else: num_pos += 1 break print('num_neg is:', num_neg) print('num_zero is:', num_zero) print('num_pos is:', num_pos) def problem_4(): _print_title('Problem 4') def pennies_count(num_pennies): return [ num_pennies // 100, num_pennies % 100 ] result = pennies_count(234) print('pennies:', 234) print('dollars:', result[0]) print('cents:', result[1]) def problem_5(): _print_title('Problem 5') def add_it_up(numbers): sum = 0 for n in numbers: sum += n return sum scores = [4.5, 2.5, 0.5, 9.0, 20.0] sum_of_values = add_it_up(scores) print('The sum of values in the list is:', sum_of_values) def problem_6(): _print_title('Problem 6') def print_greeting(text, symbol='*'): print(symbol * (len(text) + 4)) print(symbol, text, symbol) print(symbol * (len(text) + 4)) print_greeting('Hello! How are you doing?') print_greeting('Practice Exam 1', symbol='#') problem_1a() problem_1b() problem_1c() problem_2a() problem_2b() problem_2c() problem_3() problem_4() problem_5() problem_6()
40609fa2337181ed35ca0138a9f77309582b594d
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/14_delete.py
382
3.5625
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute( 'DELETE from airlines WHERE id = ?;', (999,) ) conn.commit() # don't forget to save! # Verify that it worked! cur.execute('SELECT * FROM airlines WHERE id = ?;', (999,)) results = cur.fetchall() cur.close() conn.close() print(results)
f008005f7a3fb2e5625b59469a773c95db17fc39
eecs110/winter2019
/course-files/practice_exams/midterm/conditionals/exercise_03.py
460
3.515625
4
def print_message(key): if key == 0: print(key, ':', 'zero') elif key == 1: print(key, ':', 'one') elif key < 10: print(key, ':', 'less than 10') elif key == 10.0: print(key, ':', 'equal to 10.0') elif key > 10: print(key, ':', 'more than 10') else: print(key, ':', 'IDK') print_message(5) print_message(10.0) print_message(11) print_message(True) print_message(False) print_message(0.0)
ae5cc492fa7ce14c1345c0c97f322723ae8781ba
eecs110/winter2019
/course-files/lectures/lecture_05/d2_my_module.py
1,340
3.609375
4
''' Things to notice: 1. These are all function defintions, but there are no function calls. In other words, none of these functions will run unless they are invoked. 2. Modules can import other modules. Note that this module is making use of the os module ''' import os def get_hypotenuse(side1, side2): return (side1 ** 2 + side2 ** 2) ** 0.5 def get_area(side1, side2): area = (side1 * side2) / 2 return area def get_perimeter(side1, side2): perimeter = 2 * side1 + 2 * side2 return perimeter def write_to_file(side1, side2, file_name='outfile.csv', delimiter=', ', print_header=False, mode='a'): # create a file to write to: dir_path = os.path.dirname(os.path.realpath(__file__)) file_name = os.path.join(dir_path, file_name) out_file = open(file_name, mode) # print a header if the client requests one: if print_header: print( 'side1', 'side2', 'hypotenuse', 'area', 'perimeter', sep=delimiter, file=out_file ) # print the calculations to a file: print( side1, side2, get_hypotenuse(side1, side2), get_area(side1, side2), get_perimeter(side1, side2), sep=delimiter, file=out_file )
bb101394bc45bedac101c7f5b4d55a57d8283005
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/11_query_group_by_having.py
383
4.03125
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute(''' SELECT country, count(country) as airline_count FROM airlines GROUP BY country HAVING airline_count > 60 ORDER BY airline_count desc; ''') results = cur.fetchall() cur.close() conn.close() for row in results: print(row)
ade76ca3d9e3af9cf6b296c611ba3f591eba4bd3
eecs110/winter2019
/course-files/lectures/lecture_13/scripts/01_list_available_tables.py
420
3.578125
4
import sqlite3 import helpers conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db')) cur = conn.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") # put the results of your query into the results variable: results = cur.fetchall() cur.close() conn.close() print(results) # just adding a little formatting: print() print('List Tables:') for row in results: print(row[0])
d6312ccdac607574037b7e0c7fcd3bf1d58b515f
eecs110/winter2019
/course-files/practice_exams/midterm/operators/exercise_02.py
112
3.828125
4
# What will the output of this program be? result = 2 ** 2 * 3 // 5 + 2 print(result) print(type(result)) # int
0fa9fae44540b84cb863749c8307b805e3a8d817
eecs110/winter2019
/course-files/lectures/lecture_03/demo00_operators_data_types.py
327
4.25
4
# example 1: result = 2 * '22' print('The result is:', result) # example 2: result = '2' * 22 print('The result is:', result) # example 3: result = 2 * 22 print('The result is:', result) # example 4: result = max(1, 3, 4 + 8, 9, 3 * 33) # example 5: from operator import add, sub, mul result = sub(100, mul(7, add(8, 4)))
b485405967c080034bd232685ee94e6b7cc84b4f
eecs110/winter2019
/course-files/practice_exams/final/strings/11_find.py
1,027
4.28125
4
# write a function called sentence that takes a sentence # and a word as positional arguments and returns a boolean # value indicating whether or not the word is in the sentence. # Ensure that your function is case in-sensitive. It does not # have to match on a whole word -- just part of a word. # Below, I show how I would call your function and what it would # output to the screen. def is_word_in_sentence(sentence, char_string): if char_string.lower() in sentence.lower(): return True return False def is_word_in_sentence_1(sentence, char_string): if sentence.lower().find(char_string.lower()) != -1: return True return False print('\nMethod 1...') print(is_word_in_sentence('Here is a fox', 'Fox')) print(is_word_in_sentence('Here is a fox', 'bird')) print(is_word_in_sentence('Here is a fox', 'Ox')) print('\nMethod 2...') print(is_word_in_sentence_1('Here is a fox', 'Fox')) print(is_word_in_sentence_1('Here is a fox', 'bird')) print(is_word_in_sentence_1('Here is a fox', 'Ox'))
d33973dc396594314d8c3d4c47c971df79b655fa
anoopo/PracticePython
/RockPaperScissors.py
1,804
4.0625
4
"""Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) Remember the rules: Rock beats scissors Scissors beats paper Paper beats rock """ def winner(user1, user2): if user1 == user2: return "Tied" else: if user1 == "rock": if user2 == "scissors": return "user1" else: return "user2" elif user1 == "scissors": if user2 == "rock": return "user2" else: return "user1" else: if user2 == "scissors": return "user2" else: return "user1" while True: user1Name = input("Enter player1 name : ") user2Name = input("Enter player2 name : ") while True: user1Role = (input("Enter the role for {} (Rock/Scissors/Paper): ".format(user1Name))).lower() if user1Role in ('rock', 'scissors','paper'): break while True: user2Role = (input("Enter the role for {} (Rock/Scissors/Paper): ".format(user2Name))).lower() if user2Role in ('rock', 'scissors','paper'): break game = winner(user1Role,user2Role) if game == "Tied": print ("{} ties with {}".format(user1Name,user2Name)) elif game == "User1": print ("{} is the winner".format(user1Name)) else: print ("{} is the winner".format(user2Name)) choice = input("Do you want to play another game (Y/N)") if choice in ("nNNoNO"): print ("******* Thank You for playing ROCK-SCISSOR-PAPER game. Please come again ******") break
85c1ce46a0f2c9f8b3fcae258d9d786032bcc04c
gabrielle-nunes/exercicios-em-py
/Exercícios em Python/Fatura simples.py
997
3.921875
4
##Exercício simulando uma fatura. fatura = [] total = 0 continuar = 's' valid_preco = False while continuar == 's': prod = input("Digite o nome do produto: ") while valid_preco == False: ##Este While faz a conversão do preço para float através do Try. preco = input("Digite o valor do produto: ") try: preco = float(preco) if preco <= 0: print ("O preço necessita ser maior que zero") else: valid_preco = True except: ## Caso não consiga converter, como por exemplo o usuário digitar um texto, dará a mensagem abaixo. print ("Formato de preço inválido. Use apenas números e separe os centavo com '.'.") fatura.append([prod, preco]) total += preco valid_preco = False continuar = input("Deseja comprar algo mais? Por favor, digite S para sim e N para não: ").lower() for i in fatura: print (i[0], ':', i[1]) print ('O total da fatura é: ', total)
f7e7bf0141b7aace572206a7647f640233d477b9
kei52/kei_test
/image_processing/script/histogram.py
455
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import rospy mu, sigma = 100, 15 print "mu:{0},sigma{1}".format(mu,sigma) x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(1,1,1) #binsの設定 bins=100 ax.hist(x, bins) print "bins{0}".format(bins) ax.set_title('first histogram $\mu=100,\ \sigma=15$') ax.set_xlabel('x') ax.set_ylabel('freq') fig.show() rospy.sleep(20)
fdc2fb28653de3edb53589ef5753ca547a98f9cd
tbrendel/beyond-blocks-competition
/q3.py
375
3.625
4
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def lpf(x): lpf = 2; while (x > lpf): if (x%lpf==0): x = x/lpf lpf = 2 else: lpf+=1; print("Largest Prime Factor: %d" % (lpf)); def main(): x = long(raw_input("Input long int:")) lpf(x); return 0; if __name__ == '__main__': main()
c2c41dbf8728fe5c3e4fd44f46620938ef8b9398
amandameganchan/advent-of-code-2020
/day23/day23code.py
1,791
3.609375
4
#!/bin/env python3 import sys import re from collections import defaultdict def solution(filename): data = [] with open(filename) as f: for x in f: data.extend(list(x.strip())) data = list(map(int, data)) return collectLabels(playGame(data)) def collectLabels(final_cups): # start at 1 and collect cups clockwise # do not include 1 and remember to wrap final_string = final_cups[final_cups.index(1)+1:] final_string.extend(final_cups[:final_cups.index(1)]) return ''.join(list(map(str,final_string))) def playGame(cups): current_cup = cups[0] for _ in range(100): current_cup, cups = makeMove(current_cup,cups) return cups def makeMove(current_cup, cups): # pop next 3 cups starting from after index of current cup pop_cups = [cups.pop((cups.index(current_cup)+1)%len(cups)), cups.pop((cups.index(current_cup)+1)%len(cups)), cups.pop((cups.index(current_cup)+1)%len(cups))] # select destination cup: current_cup's label - 1 dest_cup = current_cup - 1 if current_cup > 1 else 9 # if this cup is one of the removed, subtract 1 again and repeat # note if number goes below 1, wrap aroud to 9 while dest_cup not in cups: dest_cup = dest_cup - 1 if dest_cup > 1 else 9 # place the removed cups next to the destination cup # in the same order and immediately next to dest cup cups[cups.index(dest_cup)+1:cups.index(dest_cup)+1] = pop_cups # select new current_cup: cup immediately clockwise next to current cup new_index = cups.index(current_cup)+1 if cups.index(current_cup) < 8 else 0 new_current = cups[new_index] return new_current, cups if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: python3 day23code.py <data-file>") sys.exit(1) labels = solution(sys.argv[1]) print("Labels on the cups after cup 1: {}".format(labels))
924a34f570b3d5f11f8941d2245f8c85b6509a54
amandameganchan/advent-of-code-2020
/day08/day8code2.py
1,975
3.671875
4
#!/bin/env python3 """ change one jmp instruction to nop or one nop instruction to jmp in order to fix the instructions and let the program terminate without getting into an infinite loop """ import sys import re from collections import defaultdict def solution(filename): # read in input data as tuples of instructions: # (action, quantity) data = [] with open(filename) as f: for x in f: data.append((x.strip()[:3],int(x.strip()[4:]))) answer = 0 # try changing each jmp to nop for d in range(len(data)): # temporarily change jmp to nop if data[d][0] == 'jmp': data[d] = ('nop',data[d][1]) # use this updated dataset to see # if it will result in any loops acc_val, index = getValue(data) # if index indicates that it has # reached the end of the instructions, # we have found the correct change if index >= len(data): answer = acc_val break # else, change nop back to jmp and continue else: data[d] = ('jmp',data[d][1]) # try changing nops to jmps # not needed since above worked :) return answer def getValue(data): curr_index = 0 visitedIndices = [] value = 0 # accumulated value # run through instructions while True: # if current instruction has already been # executed before, break if curr_index >= len(data) or curr_index in visitedIndices: break # add index of current instruction to visted list visitedIndices.append(curr_index) # execute current instruction if data[curr_index][0] == 'nop': curr_index += 1 continue elif data[curr_index][0] == 'acc': value += data[curr_index][1] curr_index += 1 continue elif data[curr_index][0] == 'jmp': curr_index += data[curr_index][1] return value, curr_index if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: python3 day8code2.py <data-file>") sys.exit(1) value = solution(sys.argv[1]) print("The value of the accumulator will be {} after the program terminates.".format(value))
40c91a64b489ecc92af2ee651c0ec3b48eba031e
amandameganchan/advent-of-code-2020
/day15/day15code.py
1,999
4.1875
4
#!/bin/env python3 """ following the rules of the game, determine the nth number spoken by the players rules: -begin by taking turns reading from a list of starting numbers (puzzle input) -then, each turn consists of considering the most recently spoken number: -if that was the first time the number has been spoken, the current player says 0 -otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. """ import sys import re from collections import defaultdict def solution(filename,final_turn): # read in input data data = [] with open(filename) as f: for x in f: data.append(x.strip().split(',')) return getTurn(data,int(final_turn)) def getTurn(data,final_turn): """ simulate playing the game to determine the number spoken at turn final_turn Args: data (list): first starting numbers final_turn (int): desired turn to stop at Returns: int: number spoken aloud at that turn """ finalTurns = [] # do for each set in data for starterset in data: # get number of nums in starter set nums = len(starterset) # keep track of: # current turn number turn = 0 # last 2 turns any number was spoken on (if any) lastTurn = {} nextTurn = {} lastVal = -1 # iterate until desired turn while turn < final_turn: # part 1: 2020, part 2: 30000000 # first starting numbers if turn < nums: currVal = int(starterset[turn]) # subsequent turns else: currVal = nextTurn[lastVal] if currVal in lastTurn.keys(): nextTurn[currVal] = turn-lastTurn[currVal] else: nextTurn[currVal] = 0 lastTurn[currVal] = turn lastVal = currVal turn += 1 finalTurns.append(lastVal) return finalTurns[0] if __name__ == '__main__': if len(sys.argv) < 3: print("Usage: python3 day15code.py <data-file> <turn-number>") sys.exit(1) number = solution(sys.argv[1],sys.argv[2]) print("{} will be the {}th number spoken".format(number,sys.argv[2]))
1313502aaf91d18e16dee34d46296c53c17b2d26
AlexSChapman/GeneFinder
/gene_finder.py
7,966
3.625
4
# -*- coding: utf-8 -*- """ GENE FINDER PROJECT 1 @author: ALEX CHAPMAN """ import random from amino_acids import aa, codons, aa_table from load import load_seq dna_master = load_seq("./data/X73525.fa") def shuffle_string(s): """Shuffles the characters in the input string NOTE: this is a helper function, you do not have to modify this in any way """ return ''.join(random.sample(s, len(s))) # YOU WILL START YOUR IMPLEMENTATION FROM HERE DOWN ### def get_complement(nucleotide): """ Returns the complementary nucleotide nucleotide: a nucleotide (A, C, G, or T) represented as a string returns: the complementary nucleotide >>> get_complement('A') 'T' >>> get_complement('C') 'G' """ # Because python doesnt have case statements :( if nucleotide == 'A': return 'T' elif nucleotide == 'T': return 'A' elif nucleotide == 'C': return 'G' elif nucleotide == 'G': return 'C' else: return 'NA' def get_reverse_complement(dna): """ Computes the reverse complementary sequence of DNA for the specfied DNA sequence dna: a DNA sequence represented as a string returns: the reverse complementary DNA sequence represented as a string >>> get_reverse_complement("ATGCCCGCTTT") 'AAAGCGGGCAT' >>> get_reverse_complement("CCGCGTTCA") 'TGAACGCGG' """ reversed_dna = dna[::-1] # reverses string list_dna = list(reversed_dna) # creates list from string blank_to_return = '' for i in range(0, len(list_dna)): blank_to_return += get_complement(list_dna[i]) return blank_to_return def rest_of_ORF(dna): """ Takes a DNA sequence that is assumed to begin with a start codon and returns the sequence up to but not including the first in frame stop codon. If there is no in frame stop codon, returns the whole string. dna: a DNA sequence returns: the open reading frame represented as a string >>> rest_of_ORF("ATGTGAA") 'ATG' >>> rest_of_ORF("ATGAGATAGG") 'ATGAGA' >>> rest_of_ORF("ATGATATTCG") 'ATGATATTCG' """ # List of stop codons stop_codons = ['TAG', 'TAA', 'TGA'] list_dna = [] ended = False i = 0 while ended is False: # Searches by 3-char intervals i += 3 to_append = dna[i-3:i] list_dna.append for stop_codon in stop_codons: if(to_append == stop_codon): ended = True if(i > len(dna)): return(dna) ended = True # Returns the string instead of the list of codons to_return = dna[0:i-3] return to_return def find_all_ORFs_oneframe(dna): """ Finds all non-nested open reading frames in the given DNA sequence and returns them as a list. This function should only find ORFs that are in the default frame of the sequence (i.e. they start on indices that are multiples of 3). By non-nested we mean that if an ORF occurs entirely within another ORF, it should not be included in the returned list of ORFs. dna: a DNA sequence returns: a list of non-nested ORFs >>> find_all_ORFs_oneframe("ATGCATGAATGTAGATAGATGTGCCC") ['ATGCATGAATGTAGA', 'ATGTGCCC'] >>> find_all_ORFs_oneframe("GCATGAATGTAG") ['ATG'] >>> find_all_ORFs_oneframe("CCCATGTAG") ['ATG'] """ list_dna = [] hold = dna length = int(len(dna)/3) for i in range(0, length): # Seperates out string into codons list_dna.append(dna[:3]) # Adds codon to list dna = dna[3:] # Modifies original DNA string list_dna.append(dna) # Adds the remaining characters back in dna = hold to_return = [] ended = False index = 0 while ended is False: # Similar to previous loop start_index = -1 sample = list_dna[index] if sample == 'ATG': start_index = index # Establishes where the codon starts found_ORF = rest_of_ORF(dna[start_index*3:]) to_return.append(found_ORF) found_ORF_length = len(found_ORF) # Sets the cursor index to the end of the found ORF index += int(found_ORF_length/3) if index >= len(list_dna)-1: ended = True index += 1 return to_return def find_all_ORFs(dna): """ Finds all non-nested open reading frames in the given DNA sequence in all 3 possible frames and returns them as a list. By non-nested we mean that if an ORF occurs entirely within another ORF and they are both in the same frame, it should not be included in the returned list of ORFs. dna: a DNA sequence returns: a list of non-nested ORFs >>> find_all_ORFs("ATGCATGAATGTAG") ['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG'] This test makes sure that if the dna doesn't start with a start codon, it still runs >>> find_all_ORFs("AAAATGCCCTAG") ['ATGCCC'] """ first = find_all_ORFs_oneframe(dna) second = find_all_ORFs_oneframe(dna[1:]) third = find_all_ORFs_oneframe(dna[2:]) solution = first + second + third return solution def find_all_ORFs_both_strands(dna): """ Finds all non-nested open reading frames in the given DNA sequence on both strands. dna: a DNA sequence returns: a list of non-nested ORFs >>> find_all_ORFs_both_strands("ATGCGAATGTAGCATCAAA") ['ATGCGAATG', 'ATGCTACATTCGCAT'] """ base_pair = get_reverse_complement(dna) base = find_all_ORFs(dna) paired = find_all_ORFs(base_pair) to_add = [base, paired] solution = [] for i in to_add: if i is not None: solution += i return solution def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string >>> longest_ORF("ATGCGAATGTAGCATCAAA") 'ATGCTACATTCGCAT' """ solution = find_all_ORFs_both_strands(dna) return(max(solution, key=len)) def longest_ORF_noncoding(dna, num_trials): """ Computes the maximum length of the longest ORF over num_trials shuffles of the specfied DNA sequence dna: a DNA sequence num_trials: the number of random shuffles returns: the maximum length longest ORF """ longest = 0 to_test = [] for i in range(num_trials): shuffled_dna = shuffle_string(dna) to_test.append(longest_ORF(shuffled_dna)) longest = len(max(to_test, key=len)) return longest def coding_strand_to_AA(dna): """ Computes the Protein encoded by a sequence of DNA. This function does not check for start and stop codons (it assumes that the input DNA sequence represents an protein coding region). dna: a DNA sequence represented as a string returns: a string containing the sequence of amino acids encoded by the the input DNA fragment >>> coding_strand_to_AA("ATGCGA") 'MR' >>> coding_strand_to_AA("ATGCCCGCTTT") 'MPA' """ solution = '' for i in range(0, int(len(dna)/3)): tested = dna[:3] dna = dna[3:] solution += aa_table[tested] return solution def gene_finder(dna): """ Returns the amino acid sequences that are likely coded by the specified dna dna: a DNA sequence returns: a list of all amino acid sequences coded by the sequence dna. """ threshold = longest_ORF_noncoding(dna, 1500) longest = find_all_ORFs_both_strands(dna) threshold = 600 protiens = [] for i in longest: if(len(i) > threshold): protiens.append(coding_strand_to_AA(i)) print('PROTIENS BEGIN:', protiens) return protiens if __name__ == "__main__": gene_finder(dna_master) import doctest doctest.testmod()
1747b7161f1f43f059290c8f5f132d5e211b265c
nriteshranjan/Deep-Learning-with-PyTorch
/Intro to PyTorch - Working with single layer Neural network.py
1,211
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 14:57:32 2020 @author: rrite """ #Working with single layer neural network import torch def activation(x): return (1 / (1 + torch.exp(-x))) #Generating some random number torch.manual_seed(7) #manual_seed : Sets the seed for generating random numbers. #Features are 5 random normal variable features = torch.randn((1,5)) #randn : Returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1 #True weights for our data, random normal variable again weights = torch.randn_like(features) #randn_like : Returns a tensor with the same size as input that is filled with random numbers from a normal distribution #and a True bias term bias = torch.randn(1, 1) #Checking variables print(features) print(weights) print(bias) #Creating a simple neural net y = activation(torch.sum(features * weights) + bias) #or y = activation((features * weights).sum() + bias) #linear algebra operation are highly efficient due to GPU acceleration import tensorflow as tensor #print(tensor.shape(weights)) #weights = weights.view(5, 1) #print(tensor.shape(weights)) y = activation(torch.mm(features, weights.view(5, 1)) + bias) print(y)
4a0cd5391dd2af4b16f229dd21829703adedad04
Tejjy624/PythonIntro
/areacodeDemo.py
963
3.953125
4
# main function first building the dictionary # and then calls a function to lookup the dictionary def main(): areaCodeToState = readAllAreaCodes() # print(areaCodeToState) lookupAreaCodes(areaCodeToState) def readAllAreaCodes(): mydict = {} infile = open("areacodes.txt") for linerecord in infile: linerecord = linerecord.strip() lineitems = linerecord.split(',') state = lineitems[0] for num in lineitems[1:]: mydict[num.lstrip()] = state print("Added area code", num, "for state", state) return mydict def lookupAreaCodes(areaCodeToState): while True: areacode = input("Please enter valid area code :") if (areacode == 'done'): break if (areacode in areaCodeToState): print ("The State for that area code is", areaCodeToState[areacode]) else: print("Not a known area code") main()
1321c47e1ea033a5668e940bc87c8916f27055e3
Tejjy624/PythonIntro
/ftoc.py
605
4.375
4
#Homework 1 #Tejvir Sohi #ECS 36A Winter 2019 #The problem in the original code is that 1st: The user input must be changed #into int or float. Float would be the best choice since there are decimals to #work with. The 2nd problem arised due to an extra slash when defining ctemp. #Instead of 5//9, it should be 5/9 to show 5 divided by 9 #User enters temp in fahrenheit ftemp = float(input("Enter degrees in Fahrenheit:")) #Formula calculates the temp in degrees C ctemp = (5/9)*(ftemp - 32) #Summarizes what the temps are print(ftemp, "degrees Fahrenheit is", ctemp, "degrees centigrade")
d019aa1049824a7b977095881b9e5fc2d68ae4dd
Tejjy624/PythonIntro
/HW5pt2.py
1,413
3.828125
4
# Assignment 5 #Tejvir Sohi #ECS 32A Fall 2018 # function that reads population file and builds dictionary def makePopDictionary(): inf = open("world_population_2017.tsv","r") mydict = {} for line in inf: line = line.strip() lineitems = line.split('\t') country = lineitems[1] for pop in lineitems[2:]: pop = int(pop.replace(',','')) #Removes commas and converts to int mydict[pop] = country #Makes dictionary from pop and country return # function that reads drinking water file and prints out # countries that have changed percentage of people with # access, if population is big enough. def readDWdata(): infwater = open("drinkingWater.csv","r") count = 0 #Count is used to skip the first few lines for line in infwater: count = count + 1 line = line.strip() lineitem = line.split(',') if count>3: if lineitem[1] != "" and lineitem[21] != "": #Used to skip the empty values country = lineitem[0] year1990 = int(lineitem[1]) year2010 = int(lineitem[21]) change = (year2010 - year1990) #Used to find the difference in values print(country,year1990,year2010,change) return def main(): makePopDictionary() readDWdata() return main()
56c48e3280da40b79d589a2cbd7028af0e57d2ca
luojiyin1987/codewars-python
/big_int.py
2,047
3.84375
4
# -*- coding: utf-8 -*- def arabic_multiplication(num1, num2): num1_list = [int(i) for i in str(num1)] num2_list = [int(i) for i in str(num2)] int_martix = [[i * j for i in num1_list] for j in num2_list] str_martix = [map(convert_to_str, int_martix[i]) for i in range(len(int_martix))] martix = [[int(str_martix[i][j][z]) for j in range(len(str_martix[i]))] for i in range(len(str_martix)) for z in range(2)] sum_left = summ_left(martix) sum_end = summ_end(martix) sum_left.extend(sum_end) sum_left.reverse() result = take_digit(sum_left) result.reverse() int_result = "".join(result) print "%d*%d=" % (num1, num2) print int_result def convert_to_str(num): if num < 10: return "0" + str(num) else: return str(num) def summ_left(lst): summ = [] x = [i for i in range(len(lst))] y = [j for j in range(len(lst[0]))] sx = [i for i in x if i % 2 == 0] for i in sx: s = 0 j = 0 while i > 0 and j <= y[-1]: s = s + lst[i][j] if i % 2 == 1: j = j + 1 else: j = j i = i - 1 summ.append(s) return summ def summ_end(lst): summ = [] y = [j for j in range(len(lst[0]))] ex = len(lst) - 1 for m in range(len(y)): s = 0 i = ex j = m while i > 0 and j <= y[-1]: s = s + lst[i][j] if i % 2 == 1: j = j + 1 else: j = j i = i - 1 summ.append(s) return summ def take_digit(lst): tmp = 0 digit_list = [] for m in range(len(lst)): lstm = 0 lstm = lst[m] + tmp if lstm < 10: tmp = 0 digit_list.append(str(lstm)) else: tmp = lstm / 10 mm = lstm - tmp * 10 digit_list.append(str(mm)) return digit_list if __name__ == "__main__": arabic_multiplication(469, 37)
819ea31423272f5f95569add5a54e6771a3b3ff1
elohalili/python-course
/03_loops.py
1,158
3.765625
4
#loops item = 'item' for item in range(0, 10): print(item) print(item) print('___________________________') my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total = 0 for num in my_list: total += num print('The total is: ', total) print('___________________________') for i in enumerate({'name': 'Elo', 'age': 23}.items()): print(i) print('___________________________') for index, value in enumerate(list(range(100))): print(index, value) if value == 50 else None i = 0 while i < 50: print(i) i+=1 else: print('loop reached 50') picture = [ [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], ] for x, v in enumerate(picture): line = [] for y, v in enumerate(picture[x]): line.append(' ') if picture[x][y] == 0 else line.append('*') print(''.join(line)) #prettier version for row in picture: for pixel in row: print(' ', end='') if not pixel else print('*', end='') print('') list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] for char in list: if list.count(char) > 1: print(char)
4d6ebcb9aa8cea289eed76c0c44a940d291fc75a
elohalili/python-course
/01_data_types.py
675
3.796875
4
# something = input('Tell me something:') # print('\'' + something + '\' is all you got ?') # print(type(something)) # print('You can do better than this :D ') # print(bin(15)) # name = 'Name' # surname = 'Surname' # age = '23' # birht_year = input('What year were you born? \n') # age = 2020 - int(birht_year) # print(f'''Ok! # I guess your age is {age} # ''') # username = 'Username' # password = '1342' # print(f''' # Hey {username}! # The password you set {'*' * len(password)} is {len(password)} characters long. # ''') li = [1,2,3,4] li.extend([1,2,'elo']) print('elo' in li ) # print(li.pop()) print(list(range(10))) print(' '.join(str(i) for i in li))
953f9e50f7a1676a0256401697402d64a3ea66e6
elohalili/python-course
/05_oop.py
1,218
3.671875
4
class PlayerCharacter: ''' PlayerCharacter Docstring: this part should be the documentation for this class ''' #Class Object attribute (static) membership = True # this is the constructor # self it's the same equivalent to 'this' in js code def __init__(self, name, age=0): #attributes # all attributes and methods are public and can be overridden # the only "convention" to indicate a private var is adding and underscore self._name = name self.age = age # declaring a method def run(self): print('Running') def shout(self): print(f'My name is {self._name}!') ''' These two methods are the equivalent of static methods in Java They can be called referring directly to the class, w/o instantiating an obj ''' @classmethod def getPlayer(cls, num1): return cls('Mario', num1 * 5) #The only difference in this one is that it has no access to the 'cls' attr @staticmethod def getPlayer2(num1): return num1 * 5 print(PlayerCharacter.getPlayer2(2)) # instantiating a new obj player1 = PlayerCharacter('Elo') # executing a method player1.run() player1.shout()
021f1522ab76c4b8da74cb29360c7bcfe8fc33f3
mere-human/core-python-ex
/7/7.10/rot13.py
1,430
3.984375
4
#!/usr/bin/env python3 ''' 7.10 Encryption. Using your solution to the previous problem, and create a "rot13" translator. "rot13" is an old and fairly simplistic encryption routine whereby each letter of the alphabet is rotated 13 characters. Letters in the first half of the alphabet will be rotated to the equivalent letter in the second half and vice versa, retaining case. For example, a goes to n and X goes to K. Obviously, numbers and symbols are immune from translation. ''' import string translate_map = {} def fill_map(map, letters, offset): base = ord(min(letters, key=ord)) size = len(letters) for ch in letters: src_idx = ord(ch) - base dst_idx = (src_idx + offset) % size map[ch] = chr(dst_idx + base) def rot13(text): if not translate_map: # build a map offset = 13 fill_map(translate_map, string.ascii_lowercase, offset) fill_map(translate_map, string.ascii_uppercase, offset) # translate a string res = [] for ch in text: mapch = translate_map.get(ch) if mapch is None: # character is not mapped res.append(ch) else: # translate character res.append(mapch) return ''.join(res) def test(): t = rot13('This is a short sentence.') assert t == 'Guvf vf n fubeg fragrapr.' t = rot13('Guvf vf n fubeg fragrapr.') assert t == 'This is a short sentence.' print('Checks passed OK') if __name__ == '__main__': test()
001a5bc5b5e3cd0355d90d29800fd842fb23ec08
mere-human/core-python-ex
/13/13.20/time60.py
3,808
4.15625
4
''' 13-20. Class Customization. Improve on the time60.py script as seen in Section 13.13.2, Example 13.3. a. Allow "empty" instantiation: If hours and minutes are not passed in, then default to zero hours and zero minutes. b. Zero-fill values to two digits because the current formatting is undesirable. In the case below, displaying wed should output "12:05." >>> wed = Time60(12, 5) >>> wed 12:5 c.In addition to instantiating with hours (HR) and minutes (min), also support time entered as: - A tuple of hours and minutes (10, 30) - A dictionary of hours and minutes ({'HR' : 10, 'min': 30}) - A string representing hours and minutes ("10:30") Extra Credit: Allow for improperly formatted strings like "12:5" as well. d. Do we need to implement __radd__()? Why or why not? If not, when would or should we override it? e. The implementation of __repr__() is flawed and misguided. We only overrode this function so that it displays nicely in the interactive interpreter without having to use the print statement. However, this breaks the charter that repr () should always give a (valid) string representation of an evaluatable Python expression. 12:05 is not a valid Python expression, but Time60('12:05') is. Make it so. f. Add support for sexagesimal (base 60) operations. The output for the following example should be 19:15 not 18:75: >>> thu = Time60(10, 30) >>> fri = Time60(8, 45) >>> thu + fri 18:75 ''' class Time60(object): 'Time60 - track hours and minutes' def __init__(self, hr=0, min=0): 'constructor - takes hours and minutes' if isinstance(hr, tuple): self.hr, self.min = hr elif isinstance(hr, dict): self.hr = hr['HR'] self.min = hr['min'] elif isinstance(hr, str): l = hr.split(':') self.hr = int(l[0]) self.min = int(l[1]) else: self.hr = hr self.min = min def __str__(self): 'string representation' return '%d:%02d' % (self.hr, self.min) def __repr__(self): return "%s(%d, %d)" % (self.__class__.__name__, self.hr, self.min) def __add(self, hr, min): self.hr += hr if self.min >= 24: self.hr = self.hr % 24 self.min += min if self.min >= 60: self.hr += self.min // 60 self.min = self.min % 60 def __add__(self, other): 'overloading the addition operator' if isinstance(other, self.__class__): res = self.__class__(self.hr, self.min) res.__add(other.hr, other.min) return res else: raise ValueError("Not supported operand's type") def __iadd__(self, other): 'overloading in-place addition' if isinstance(other, self.__class__): self.__add(other.hr, other.min) return self else: raise ValueError("Not supported operand's type") # NOTE: __radd__ is not implemented since addition works only if # both operands are of type Time60 def main(): assert str(Time60()) == '0:00' assert str(Time60(12, 5)) == '12:05' assert str(Time60((10, 30))) == '10:30' assert str(Time60({'HR':10, 'min':30})) == '10:30' assert str(Time60('10:30')) == '10:30' assert str(Time60('12:5')) == '12:05' assert str(Time60('10:30') + Time60('11:15')) == '21:45' assert str(Time60('10:30') + Time60('8:45')) == '19:15' assert str(Time60('21:30') + Time60('8:45')) == '6:15' t = Time60('10:05') t += Time60('11:10') assert str(t) == '21:15' t = Time60('10:30') t += Time60('8:45') assert str(t) == '19:15' t = eval(repr(Time60('10:05'))) assert isinstance(t, Time60) assert str(t) == '10:05' if __name__ == '__main__': main()
f78ccdea33a9a4e5d6bfed05913070eaa143e956
mere-human/core-python-ex
/9/9.18/findbyte.py
784
4.03125
4
''' 9-18. Searching Files. Obtain a byte value (0-255) and a filename. Display the number of times that byte appears in the file. ''' import sys def main(): if len(sys.argv) != 3: raise Exception('2 arguments for file name and byte value (0-255) are expected') file_name = sys.argv[1] byte_val = int(sys.argv[2]) if byte_val < 0 or byte_val > 255: raise ValueError('Value %d is out of expected range 0-255' % byte_val) n_bytes = 0 with open(file_name, 'rb') as input_file: while True: input_byte = input_file.read(1) if not input_byte: break if input_byte[0] == byte_val: n_bytes += 1 print('Found %d occurences' % n_bytes) if __name__ == '__main__': main()
606626a3d339adf0eb09008d2004f797f1dcf652
Beeze/AI-class-Projects
/p2/frogs_toads.py
7,494
4.09375
4
import a_star import math ''' Spaces is an class which holds all the logic for altering each space in our puzzle. ''' class Spaces(object): def __init__(self, spaces): if isinstance(spaces, Spaces): self.spaces = spaces.spaces else: self.spaces = spaces ''' Defines what the start state of our game is ''' @staticmethod def make_start(number_of_frogs_and_toads): # We have this number of frogs and toads, so we multiply the given number number_of_spaces = number_of_frogs_and_toads*2+1 space_list = ["_" for i in xrange(number_of_spaces)] if space_list: for space_idx in xrange(number_of_spaces): if (space_idx < (math.floor(number_of_spaces/2))): space_list[space_idx] = ("T") elif (space_idx > math.floor(number_of_spaces/2)): space_list[space_idx] = ("F") return Spaces(space_list) ''' Defines what the goal state of our game is ''' @staticmethod def make_goal(number_of_frogs_and_toads): # We have this number of frogs and toads, so we multiply the given number, and add one for the empty space. number_of_spaces = number_of_frogs_and_toads*2+1 space_list = ["_" for i in xrange(number_of_spaces)] if space_list: for space_idx in xrange(number_of_spaces): if (space_idx < math.floor(number_of_spaces/2)): space_list[space_idx] = ("F") elif (space_idx > math.floor(number_of_spaces/2)): space_list[space_idx] = ("T") return Spaces(space_list) ''' Creates a copy of our classes spaces array for use in functions. ''' def copy(self): return Spaces( [ space for space in self.spaces ]) ''' Glorified swap function that swaps two elements in our array of spaces. ''' def move(self, from_index, to_index): new_spaces = self.copy() #Get items from the indexes we are coming from, and moving to. thing_at_space_we_are_leaving = new_spaces.spaces[ from_index ] thing_at_space_we_are_moving_to = new_spaces.spaces[ to_index ] #Swap these items, and save them to our copy of the spaces list. new_spaces.spaces[from_index], new_spaces.spaces[to_index] = thing_at_space_we_are_moving_to, thing_at_space_we_are_leaving return Spaces(new_spaces) ''' used to print data to the console ''' def __unicode__(self): return repr(self.spaces) ''' used to print data to the console ''' def __repr__(self): return repr(self.spaces) ''' used for internal memory management ''' def __hash__(self): return hash(repr(self)) ''' checks to see if two nodes are equal ''' def __eq__(self, other): return repr(self) == repr(other) ''' This class builds the tree and sets up the heuristic function for our problem. ''' class FrogsAndToadsProblem(a_star.Problem): def __init__(self, number_of_frogs_and_toads=3): self.number_of_frogs_and_toads = number_of_frogs_and_toads ''' This is how we determine the neighbors of a given node. ''' def neighbor_nodes(self, spaces): neighbors = [] space_list = spaces.spaces #Determine the numbers of spaces allocated for this problem number_of_spaces = self.number_of_frogs_and_toads*2+1 #Find the current open space open_space_index = space_list.index('_') #Get the upper and lower indices from which an animal would be able to move upper_bound = open_space_index + 2 #Make sure upper bound is a valid index in the array if upper_bound > len(spaces.spaces) - 1: upper_bound = open_space_index + 1 if (open_space_index + 1 <= len(space_list) - 1) else open_space_index lower_bound = open_space_index - 2 #Make sure lower bound is a valid index in the array if lower_bound < 0: lower_bound = open_space_index - 1 if (open_space_index - 1 >= 0) else open_space_index for i in xrange(number_of_spaces): if (i == open_space_index): continue ''' Here, we think about potential states of the game that would happen after a legal move. For a move to be legal: - you can't jump an animal of the same type - You can jump at most, one animal - you only can move to an empty space, signified by "_" ''' if lower_bound <= i <= upper_bound: # We know this animal can potentially be moved. offset = 0 #Figure out if we are currently positioned before or after the open space. if i < open_space_index: offset = 1 else: offset = -1 ''' Check to see if we are able to move. If so, figure out how many spaces we can move. ''' if space_list[i] != space_list[i+offset] and space_list[i+offset] == "_": neighbor = spaces.move(i, i+offset) neighbors.append(neighbor) elif space_list[i] != space_list[i+offset]: ''' we know we are at most, 2 spaces away from the open space so we'll try to move our animal there ''' new_offset = 2 if offset > 0 else -2 neighbor = spaces.move(i, i+new_offset) neighbors.append(neighbor) return neighbors ''' This is how we measure the effectiveness of each potential move to a neighbor. For ours, we'll score based on how far frogs and toads have moved towards their goal position. Two points if a toad/frog has moved pass the initial empty space One point if a toad/frog is on the initial empty space ''' def heuristic(self, position, goal): number_of_spaces = len(position.spaces) score = 0 for idx, space in enumerate(position.spaces): if idx <= math.floor(number_of_spaces/2) and space == "F": score += 2 elif idx == math.floor(number_of_spaces/2) and space != "_": score += 1 elif idx > math.floor(number_of_spaces/2) and space == "T": score += 2 return score ''' __main__ runs when we do `python frogs_toads.py` ''' if __name__ == '__main__': ''' Works for any number of frogs and toads, although anything greater than 5 takes a bit to complete. ''' number_of_frogs_and_toads = 9 frogs_and_toads = FrogsAndToadsProblem(number_of_frogs_and_toads) # the "points" in the FrogsAndToadsProblem are of type "Spaces", # so the we need to instantiate Spaces for the start and ends points. start = Spaces.make_start(number_of_frogs_and_toads) goal = Spaces.make_goal(number_of_frogs_and_toads) # Find the path using our a_star method. solution = a_star.find_path(frogs_and_toads, start, goal) for position in solution: print position
1d5f8fbdafe41e9b090afb61a83894df598e5574
smithdanielle/p4n2014
/code/ex2Functions.py
897
3.59375
4
# Load psychopy modules from psychopy import visual, event, core # Initialise stimuli win = visual.Window(size=[500, 500]) textStim = visual.TextStim(win) # Messages welcome = 'hi and welcome to this experiment' instruction = 'really, there\'s not much to do. We just show a bunch of messages. Press RETURN to continue.' thanks = 'thank you and goodbye. We hope you enjoyed!' # Create a function to show text def showText(input, acceptedKeys=None): """Presents text and waits for accepted keys""" # Set and display text textStim.setText(input) textStim.draw() win.flip() # Wait for response and return it response = event.waitKeys(keyList=acceptedKeys) if response[0] == 'q': core.quit() return response # Show welcome message showText(welcome) # Show instruction showText(instruction, ['return', 'q']) # Show debriefing showText(thanks)
4745ae44a167d49647d44c2a57dcacc9ed27b75e
cwz3/hangman
/Hangman.py
5,622
4.375
4
''' Description: You must create a Hangman game that allows the user to play and guess a secret word. See the assignment description for details. @author: charles cwz3 ''' def handleUserInputDifficulty(): ''' This function asks the user if they would like to play the game in (h)ard or (e)asy mode, then returns the corresponding number of misses allowed for the game. ''' missesLeft=0 print("How many misses do you want? Hard has 8 and Easy has 12.") difficulty=input("(h)ard or (e)asy> ") if difficulty=='h': missesLeft=8 return 8 else: missesLeft=12 return 12 def getWord(words, length): ''' Selects the secret word that the user must guess. This is done by randomly selecting a word from words that is of length length. ''' import random lengthwords=[] for word in words: if len(word)==length: lengthwords.append(word) x=random.randint(0,len(lengthwords)) return lengthwords[x] def createDisplayString(lettersGuessed, missesLeft, hangmanWord): ''' Creates the string that will be displayed to the user, using the information in the parameters. ''' guess = "" for l in sorted(lettersGuessed): guess += " "+l one="letters you've guessed: " + guess two="misses remaining = " + str(missesLeft) three=" ".join(hangmanWord) return one+"\n"+two+"\n"+three def handleUserInputLetterGuess(lettersGuessed, displayString): ''' Prints displayString, then asks the user to input a letter to guess. This function handles the user input of the new letter guessed and checks if it is a repeated letter. ''' print(displayString) letter=input("letter> ") while letter in lettersGuessed: print("you already guessed that") letter=input("letter> ") return letter def updateHangmanWord(guessedLetter, secretWord, hangmanWord): ''' Updates hangmanWord according to whether guessedLetter is in secretWord and where in secretWord guessedLetter is in. ''' splitsecret=[char for char in secretWord] for i in range(len(splitsecret)): if splitsecret[i]==guessedLetter: hangmanWord[i]=guessedLetter return hangmanWord def processUserGuess(guessedLetter, secretWord, hangmanWord, missesLeft): ''' Uses the information in the parameters to update the user's progress in the hangman game. ''' ret=[] zero= updateHangmanWord(guessedLetter, secretWord, hangmanWord) one= int(missesLeft) if guessedLetter not in secretWord: two= False one-=1 else: two= True ret.append(zero) ret.append(one) ret.append(two) return ret def runGame(filename): ''' This function sets up the game, runs each round, and prints a final message on whether or not the user won. True is returned if the user won the game. If the user lost the game, False is returned. ''' import random f = open(filename) words = [] for line in f: words.append(line.strip()) f.close() missesLeft=handleUserInputDifficulty() missesallowed=missesLeft secretWord=getWord(words,random.randint(5,10)) hangmanWord=[char for char in secretWord] for i in range(len(hangmanWord)): hangmanWord[i]="_" lettersGuessed=[] displayString=createDisplayString(lettersGuessed, missesLeft, hangmanWord) while missesLeft!=0 or secretWord!=" ".join(hangmanWord): guessedLetter=handleUserInputLetterGuess(lettersGuessed, displayString) lettersGuessed.append(guessedLetter) process=processUserGuess(guessedLetter, secretWord, hangmanWord, missesLeft) if process[2]==True: #guessed correctly updateHangmanWord(guessedLetter, secretWord, hangmanWord) displayString=createDisplayString(lettersGuessed, missesLeft, hangmanWord) if process[2]==False: #guessed incorrectly missesLeft-= 1 print("you missed:"+" "+guessedLetter+" not in word") displayString=createDisplayString(lettersGuessed, missesLeft, hangmanWord) if "_" not in hangmanWord: #user won print("you guessed the word: "+secretWord) print("you made "+str(len(lettersGuessed))+" guesses with "+str(missesallowed-missesLeft)+" misses") return True if missesLeft==0: print("you're hung!!") print("word is "+secretWord) print("you made "+str(len(lettersGuessed))+" guesses with "+str(missesallowed-missesLeft)+" misses") return False if __name__ == "__main__": ''' Running Hangman.py should start the game, which is done by calling runGame, therefore, we have provided you this code below. ''' gameswon=0 gameslost=0 playagain='y' while playagain=='y': if runGame('lowerwords.txt')==True: gameswon+=1 else: gameslost+=1 playagain=input("Do you want to play again? y or n> ") print("You won "+str(gameswon)+" game(s) and lost "+str(gameslost))
6b41212668d616636c972ffe7487e84dee359ac2
lucaalexandre/Estudo_de_Revisao_parte1
/Exercicio5.py
87
3.578125
4
idade = int(input("Digite sua idade: ")) nova = "parabens" + idade + "anos" print(nova)
eac8927556f8341bdefa530491ce46571a3cf018
Saurav-Paul/Codeforces-Problem-Solution-By-Saurav-Paul
/A - Hotelier.py
355
3.546875
4
room = [0]*10 def putInLeft(): for i in range(0,10): if room[i]==0: room[i]=1 break def putInRight(): i = 9 while i>=0: if room[i]==0: room[i]=1 break i -= 1 n = int(input()) s = input() #print(room) for x in s: if x=='L': putInLeft() elif x=='R': putInRight() else : room[int(x)]=0 for m in room: print(m,end='')
6c31e0d57b3e232465391bc8455a311dc03a5658
kadhumalrubaye/datastructure
/selection_sort.py
677
3.75
4
#min #compare #swap #[6,1,8,3,10,5] # def swap(a,b): # temp=a # a=b # b=temp #[9,1,8,2,7,3] def selection_sor(lst): length=len(lst) # min=min(lst) #[9,1,8,2,7,3] #[9,1,8,2,7,3] #[1,8,2,7,3,9] pass1 here we need min #-------------------- #i #[9,1,8,2,7,3] min =9 #j #[9,1,8,2,7,3] #[ for i in range(length): minnum=i # for j in range (length): if lst[j]<lst[minnum]: temp=lst[j] lst[j]=lst[minnum] lst[minnum]=temp print(lst) if __name__ == '__main__': lst=[9,1,8,2,7,3,5] selection_sor(lst)
5f6c090cb83401fae49f3d09aa692d4a0cc450cf
Mgomelya/Study
/Алгоритмы/Быстрая_сортировка.py
890
4.09375
4
from random import randint def partition(array, pivot): less = [i for i in array if i < pivot] # элементы array, меньшие pivot center = [i for i in array if i == pivot] # элементы array, равные pivot greater = [i for i in array if i > pivot] # элементы array, большие pivot return less, center, greater def quicksort(array): if len(array) < 2: # базовый случай, return array # массивы с 0 или 1 элементами фактически отсортированы else: # рекурсивный случай pivot = array[randint(0, len(array) - 1)] # опора, случайный элемент из array left, center, right = partition(array, pivot) return quicksort(left) + center + quicksort(right) print(quicksort([1, 3, 98, 54, 20, 8, 10, 2]))
44d18b17cdd57a20036f12ec231ce8d9ec1f7157
Mgomelya/Study
/Алгоритмы/Очередь.py
2,073
4.1875
4
# Очередь основана на концепции FIFO - First in First out class Queue: # Очередь на кольцевом буфере, Сложность: O(1) def __init__(self, n): self.queue = [None] * n self.max_n = n self.head = 0 self.tail = 0 self.size = 0 # В пустой очереди и голова, и хвост указывают на ячейку с индексом 0 def is_empty(self): return self.size == 0 def push(self, x): if self.size != self.max_n: self.queue[self.tail] = x self.tail = (self.tail + 1) % self.max_n self.size += 1 # Хвост всегда указывает на первую свободную для записи ячейку, # а голова — на элемент, добавленный в очередь раньше всех остальных def pop(self): if self.is_empty(): return None x = self.queue[self.head] self.queue[self.head] = None self.head = (self.head + 1) % self.max_n self.size -= 1 return x def peek(self): # Вернуть первый элемент if self.is_empty(): return None return self.queue[self.head] def get_size(self): return self.size q = Queue(8) q.push(1) print(q.queue) # [1, None, None, None, None, None, None, None] print(q.size) # 1 q.push(-1) q.push(0) q.push(11) print(q.queue) # [1, -1, 0, 11, None, None, None, None] print(q.size) # 4 q.pop() print(q.queue) # [None, -1, 0, 11, None, None, None, None] print(q.size) # 3 q.pop() q.pop() q.push(-8) q.push(7) q.push(3) q.push(16) print(q.queue) # [None, None, None, 11, -8, 7, 3, 16] print(q.size) # 5 q.push(12) # Когда пытаемся переполнить очередь, хвост будет указывать на след ячейку по часовой стрелке - 0 print(q.queue) # [12, None, None, 11, -8, 7, 3, 16] print(q.size) # 6
db41b3479156bb3f7cf464aa33b72cb8ad94c128
Mgomelya/Study
/Алгоритмы/Лексикографическая_сортировка.py
2,869
4.09375
4
print("апельсин" < "арбуз") # True st = 'A B C Hello world!' for i in st: print(f'Порядкой номер в Юникоде символа "{i}" - {ord(i)}') print([2, "апельсин"] < [2, "арбуз"]) # Длина слов чисел: ноль, один, два, три ... digit_lengths = [4, 4, 3, 3, 6, 4, 5, 4, 6, 6] # Компаратор [ - <длина слова>, <само число>] def key_for_card(card): return [-digit_lengths[card], card] cards = [2, 3, 7] lex_sort = sorted(cards, key=key_for_card) print(lex_sort) print(sorted(cards, key=lambda card: [-digit_lengths[card], card])) '''При помощи лексикографического порядка легко превратить любую сортировку в стабильную. Для этого мы преобразуем каждый элемент исходного массива в тройку вида [значение ключа сортировки, позиция в исходном массиве, сам элемент]. Затем мы отсортируем массив таких троек. Элементы, у которых значение ключа отличается, будут расположены в соответствии с этим ключом. Элементы, одинаковые по ключу, будут упорядочены по позиции в исходном элементе. До сравнения по последнему элементу тройки дело не дойдёт, поскольку позиции у двух элементов совпасть не могут. Например, чтобы отсортировать по длине слова ['Москва', 'Казань', 'Питер'], сохранив порядок слов одинаковой длины, сопоставим элементам тройки: [[6,0,'Москва'], [6,1,'Казань'], [5,2,'Питер']] При сортировке они будут упорядочены в порядке: [5,2,'Питер'], [6,0,'Москва'], [6,1,'Казань']. Восстановить порядок самих городов теперь можно тривиально, достаточно просто отбросить из троек лишнюю информацию. В итоге получаем порядок ['Питер', 'Москва', 'Казань']. Ключи сортировки в этих тройках сохранять не обязательно, их можно вычислять на лету. А вот исходные позиции сохранить придётся. Поэтому такой способ сделать сортировку стабильной потребует O(n) дополнительной памяти. '''
46de0528be699ffe3a1e28e0d6f8aa32bbcf463f
Mgomelya/Study
/Поиск_согласных_гласных.py
1,280
3.78125
4
str1 = 'asdxzczxaaaaaaaaa' str2 = 'adsszxxzcxzc' key = 'C' def func(str1, str2, key): if key == 'C': vowels_1 = 0 consonants_1 = 0 vowels_2 = 0 consonants_2 = 0 for i in str1: letter = i.lower() if letter == "a" or letter == "e" or \ letter == "i" or letter == "o" or \ letter == "u" or letter == "y": vowels_1 += 1 else: consonants_1 += 1 for i in str2: letter = i.lower() if letter == "a" or letter == "e" or \ letter == "i" or letter == "o" or \ letter == "u" or letter == "y": vowels_2 += 1 else: consonants_2 += 1 if consonants_1 > consonants_2: print('в строке 1 больше согл, чем в строке 2') else: print('в строке 2 больше согл, чем в строке 2') if key == 'a-z': if len(str1) > len(str2): print('в строке 1 больше букв, чем в строке 2') else: print('в строке 2 больше букв, чем в строке 1') func(str1, str2, key)
81548f1facdeeb06bdfe0ede204f1718d0315b59
Mgomelya/Study
/кол-вопрограммистов.py
527
3.65625
4
n = int(input()) b = n%10 if 0 <= n <= 1000: if 111<=n<117 or 211<=n<217 or 311<=n<317 or 411<=n<417 or 511<=n<517 or 611<=n<617 or 711<=n<717 or 811<=n<817 or 911<=n<917: if 9<=n%100<=19: print(n, "программистов") elif b == 1: print(n, "программист") elif 2<=b<=4: print(n, "программиста") elif b == 0 or 5<= b <=9 or 1<=b<=4: print(n, "программистов") else: print('УУУУ, число неправильное')
169a92be719041be83c4a446467626148d4ca1d2
Mgomelya/Study
/Алгоритмы/Связный_список.py
1,794
4.28125
4
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def print_linked_list(node): while node: print(node.value, end=" -> ") node = node.next print("None") # У каждого элемента есть значение и ссылка на следующий элемент списка n3 = Node('third') n2 = Node('second', n3) n1 = Node('first', n2) print_linked_list(n1) # вершина n1 print_linked_list(n2) # вершина n2 def get_node_by_index(node, index): while index: node = node.next index -= 1 return node # Добавление нового элемента по индексу def insert_node(head, index, value): new_node = Node(value) if index == 0: new_node.next = head return new_node previous_node = get_node_by_index(head, index - 1) new_node.next = previous_node.next previous_node.next = new_node return head node, index, value = n1, 2, 'new_node' head = insert_node(node, index, value) print_linked_list(head) # Удаление элемента по индексу def del_node(head, index): if index == 0: head = get_node_by_index(head, 1) return head previous_node = get_node_by_index(head, index - 1) next_node = get_node_by_index(head, index + 1) previous_node.next = next_node return head node, index = n1, 2 head = del_node(node, index) print_linked_list(head) # Поиск индекса по значению def find_val(node, value): index = 0 while node: if node.value == value: return index node = node.next index += 1 else: return -1 head, value = n1, 'third' print(find_val(head, value))
8a0f6c4cb3f44d3ed5e008c276ad1242ad9837e5
brillianti/Leetcode
/两数之和.py
1,253
3.625
4
''' #要求: # 给定一个整数数组 nums 和一个目标值 target # 请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 # 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 #给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum ''' nums = [2, 7, 11, 15] target = 9 def twoSum(nums,target): n = len(nums) # 获取nums的长度,是4 for x in range(n): # 外层循环先取出下标0,对应着数组里的第一个数字 for y in range(x+1,n): # 内层循环取出下标1,对应着数组里的第二个数字 if nums[x] + nums[y] == target: # 如果第一个数字+第二个数字=target return x,y # 上面的判断是对的话,那么就返回下标 break # 并停止程序 else: # 如果上面的条件不满足的话,内层for循环就会继续取出下标2进行判断...如果都不满足,那么外层for循环就会取出下标1...依次类推 continue if __name__ == '__main__': a = twoSum(nums, target) print(a)
c8784fb4c3ffb191d8ccc59330856ca3eedbdbbb
brillianti/Leetcode
/回文字符.py
688
3.71875
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ numbers = '1234567890' letters ='abcdefghijklnmopqrstuvwxyz' s=s.lower() #s = s.lower() 全部转小写// s= s.upper() 全部转大写 res='' for i in s: if i in numbers or i in letters: #选取数字或者字母 res+=i mid=len(res)>>1 for i in range(mid): if res[i]!=res[len(res)-1-i]: return False return True if __name__ == '__main__': so = Solution() b = 'Hi this is a ,,,1221 a si siht ih' a =so.isPalindrome(b) print(a)
b7b7ff8b95c868475054dd56673d3001e824cde9
luisfe12/Seguirdad
/lab_2/desicfrado_vignere.py
2,497
3.609375
4
def Cifrado_solo_letras(cifrado): contador=0 for i in cifrado: if i == ' ' or i == '\n': continue contador+=1 return contador def modulo_descifrado(p_k, p_c): modulo = p_c - p_k modulo = modulo % 27 return modulo def Clave_completa(clave, modulo, divsion): clave_completa = '' for i in range(division): clave_completa+=clave if modulo == 0: return clave_completa for i in range(modulo): clave_completa+=clave[i] return clave_completa def Descifrado_Vignere(clave_modificada, mensaje_cifrado, alfabeto): texto_claro = '' mensaje_i = 0 clave_j = 0 while True: if mensaje_i >= len(mensaje_cifrado): mensaje_i+=1 break asci = ord(mensaje_cifrado[mensaje_i]) #valor en ascci if mensaje_i == ' ' or mensaje_i == '\n': mensaje_i+=1 break elif asci < 65 or asci > 90: if mensaje_cifrado[mensaje_i] != 'Ñ': mensaje_i+=1 continue pos_cif = alfabeto.index(mensaje_cifrado[mensaje_i]) pos_cla = alfabeto.index(clave_modificada[clave_j]) mod = modulo_descifrado(pos_cla, pos_cif) texto_claro+=alfabeto[mod] mensaje_i+=1 clave_j+=1 print(len(texto_claro)) return texto_claro alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] f = open('texto_cifrado.txt', 'r') menssaje_cifrado = f.read() f.close() clave = 'HIELO' division = len(menssaje_cifrado)//len(clave) modulo = Cifrado_solo_letras(menssaje_cifrado) % len(clave) Clave_modificada = Clave_completa(clave, modulo, division) #print(len(Clave_modificada)) #print(len(menssaje_cifrado)) print(Descifrado_Vignere(Clave_modificada, menssaje_cifrado, alfabeto)) d = open ('DEScifrado_ejer_15.txt','w') d.write(Descifrado_Vignere(Clave_modificada, menssaje_cifrado, alfabeto)) d.close()
06ce5b06faf63d5bdebbdb68cf51bf1a6caf2263
hoshitk/pyscripts
/fileio.py
1,056
3.546875
4
# 今のワーキングディレクトリ(作業中のフォルダ) # を調べるために OSモジュールを importします import os # 今のワーキングディレクトリを得て画面に表示します print(os.getcwd()) # 日本語ファイル.txt という名称のファイルを作成し、内容を書き出します f = open('日本語ファイル.txt','w') f.write('日本語\n日本語\n日本語\n ') f.close() # 日本語ファイル.txt を読み込み用にopen して、その内容を表示します f = open('日本語ファイル.txt','r') s = f.read() f.close() print(s) # with open(ファイル名などopen 関数の引数, 'a(append)') as ファイルオブジェクト用変数: # ファイルを操作するブロック with open('日本語ファイル.txt','a') as f: f.write('追記append\n') # 日本語ファイル.txt を読み込み用にopen して、その内容を表示します f = open('日本語ファイル.txt','r') s = f.read() f.close() print(s)
4abcf19a4d16b07d86789a5e0a63101f15066270
jamesedwarddillard-zz/nfpguesses
/bls_reader/bls_reader.py
2,083
3.609375
4
""" Creating a function which reads in html of a BLS report website and returns the key monthly jobs added as a Report data class """ from bs4 import BeautifulSoup from bls_report_classes import * def nfp_table_finder(report_soup): """ Identifies and returns the proper table on the Employment Situation Release """ report_tables = report_soup.find_all('table') nfp_table = report_tables[1] #Table with NFP data is Summary Table B, the second table listed return nfp_table def nfp_month_finder(nfp_table, report): """ Finds the relevant months on the Employment Situation Release a Report object with that information """ nfp_table.header = nfp_table.thead.tr.find_all('th') #Turns the table header into a list of lists report.current.month = str(nfp_table.header[4].contents[0]) report.current.year = str(nfp_table.header[4].contents[2]) report.first_revision.month = str(nfp_table.header[3].contents[0]) report.first_revision.year = str(nfp_table.header[3].contents[2]) report.second_revision.month = str(nfp_table.header[2].contents[0]) report.second_revision.year = str(nfp_table.header[2].contents[2]) return report def nfp_jobs_finder(nfp_table, report): jobs_list = [] #blank list to hold jobs values that come out nfp_jobs_subtable = nfp_table.find_all('tr')[2].find_all('td') for td in nfp_jobs_subtable: jobs_list.append(int(td.span.string)) report.current.jobs = jobs_list[3] report.first_revision.jobs = jobs_list[2] report.second_revision.jobs = jobs_list[1] return report def bls_report_reader(html_file): """ function that reads the html version of the BLS Employment Situation report, identifies the key data and returns a job report data class """ #create JobsData objects current = JobsData() first_revision = JobsData() second_revision = JobsData() #create a Report object report = Report(current, first_revision, second_revision) report_soup = BeautifulSoup(html_file) nfp_table = nfp_table_finder(report_soup) report = nfp_month_finder(nfp_table, report) report = nfp_jobs_finder(nfp_table, report) return report
11fccca54ba988e9c869f3ade9719e99e7dcf174
JordanRex/yaaml
/src/modules/misc.py
13,080
3.6875
4
# misc functions ############################################################################################################################### ## EDA ############################################################################################################################### import math import numpy as np import pandas as pd import seaborn as sns import scipy.stats as ss import matplotlib.pyplot as plt from collections import Counter def conditional_entropy(x, y): """ Calculates the conditional entropy of x given y: S(x|y) Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy :param x: list / NumPy ndarray / Pandas Series A sequence of measurements :param y: list / NumPy ndarray / Pandas Series A sequence of measurements :return: float """ # entropy of x given y y_counter = Counter(y) xy_counter = Counter(list(zip(x,y))) total_occurrences = sum(y_counter.values()) entropy = 0.0 for xy in xy_counter.keys(): p_xy = xy_counter[xy] / total_occurrences p_y = y_counter[xy[1]] / total_occurrences entropy += p_xy * math.log(p_y/p_xy) return entropy def cramers_v(x, y): """ Calculates Cramer's V statistic for categorical-categorical association. Uses correction from Bergsma and Wicher, Journal of the Korean Statistical Society 42 (2013): 323-328. This is a symmetric coefficient: V(x,y) = V(y,x) Original function taken from: https://stackoverflow.com/a/46498792/5863503 Wikipedia: https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V :param x: list / NumPy ndarray / Pandas Series A sequence of categorical measurements :param y: list / NumPy ndarray / Pandas Series A sequence of categorical measurements :return: float in the range of [0,1] """ confusion_matrix = pd.crosstab(x,y) chi2 = ss.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1))) def theils_u(x, y): """ Calculates Theil's U statistic (Uncertainty coefficient) for categorical-categorical association. This is the uncertainty of x given y: value is on the range of [0,1] - where 0 means y provides no information about x, and 1 means y provides full information about x. This is an asymmetric coefficient: U(x,y) != U(y,x) Wikipedia: https://en.wikipedia.org/wiki/Uncertainty_coefficient :param x: list / NumPy ndarray / Pandas Series A sequence of categorical measurements :param y: list / NumPy ndarray / Pandas Series A sequence of categorical measurements :return: float in the range of [0,1] """ s_xy = conditional_entropy(x,y) x_counter = Counter(x) total_occurrences = sum(x_counter.values()) p_x = list(map(lambda n: n/total_occurrences, x_counter.values())) s_x = ss.entropy(p_x) if s_x == 0: return 1 else: return (s_x - s_xy) / s_x def correlation_ratio(categories, measurements): """ Calculates the Correlation Ratio (sometimes marked by the greek letter Eta) for categorical-continuous association. Answers the question - given a continuous value of a measurement, is it possible to know which category is it associated with? Value is in the range [0,1], where 0 means a category cannot be determined by a continuous measurement, and 1 means a category can be determined with absolute certainty. Wikipedia: https://en.wikipedia.org/wiki/Correlation_ratio :param categories: list / NumPy ndarray / Pandas Series A sequence of categorical measurements :param measurements: list / NumPy ndarray / Pandas Series A sequence of continuous measurements :return: float in the range of [0,1] """ categories = convert(categories, 'array') measurements = convert(measurements, 'array') fcat, _ = pd.factorize(categories) cat_num = np.max(fcat)+1 y_avg_array = np.zeros(cat_num) n_array = np.zeros(cat_num) for i in range(0,cat_num): cat_measures = measurements[np.argwhere(fcat == i).flatten()] n_array[i] = len(cat_measures) y_avg_array[i] = np.average(cat_measures) y_total_avg = np.sum(np.multiply(y_avg_array,n_array))/np.sum(n_array) numerator = np.sum(np.multiply(n_array,np.power(np.subtract(y_avg_array,y_total_avg),2))) denominator = np.sum(np.power(np.subtract(measurements,y_total_avg),2)) if numerator == 0: eta = 0.0 else: eta = numerator/denominator return eta def associations(dataset, nominal_columns=None, mark_columns=False, theil_u=False, plot=True, return_results = False, **kwargs): """ Calculate the correlation/strength-of-association of features in data-set with both categorical (eda_tools) and continuous features using: - Pearson's R for continuous-continuous cases - Correlation Ratio for categorical-continuous cases - Cramer's V or Theil's U for categorical-categorical cases :param dataset: NumPy ndarray / Pandas DataFrame The data-set for which the features' correlation is computed :param nominal_columns: string / list / NumPy ndarray Names of columns of the data-set which hold categorical values. Can also be the string 'all' to state that all columns are categorical, or None (default) to state none are categorical :param mark_columns: Boolean (default: False) if True, output's columns' names will have a suffix of '(nom)' or '(con)' based on there type (eda_tools or continuous), as provided by nominal_columns :param theil_u: Boolean (default: False) In the case of categorical-categorical feaures, use Theil's U instead of Cramer's V :param plot: Boolean (default: True) If True, plot a heat-map of the correlation matrix :param return_results: Boolean (default: False) If True, the function will return a Pandas DataFrame of the computed associations :param kwargs: Arguments to be passed to used function and methods :return: Pandas DataFrame A DataFrame of the correlation/strength-of-association between all features """ dataset = convert(dataset, 'dataframe') columns = dataset.columns if nominal_columns is None: nominal_columns = list() elif nominal_columns == 'all': nominal_columns = columns corr = pd.DataFrame(index=columns, columns=columns) for i in range(0,len(columns)): for j in range(i,len(columns)): if i == j: corr[columns[i]][columns[j]] = 1.0 else: if columns[i] in nominal_columns: if columns[j] in nominal_columns: if theil_u: corr[columns[j]][columns[i]] = theils_u(dataset[columns[i]],dataset[columns[j]]) corr[columns[i]][columns[j]] = theils_u(dataset[columns[j]],dataset[columns[i]]) else: cell = cramers_v(dataset[columns[i]],dataset[columns[j]]) corr[columns[i]][columns[j]] = cell corr[columns[j]][columns[i]] = cell else: cell = correlation_ratio(dataset[columns[i]], dataset[columns[j]]) corr[columns[i]][columns[j]] = cell corr[columns[j]][columns[i]] = cell else: if columns[j] in nominal_columns: cell = correlation_ratio(dataset[columns[j]], dataset[columns[i]]) corr[columns[i]][columns[j]] = cell corr[columns[j]][columns[i]] = cell else: cell, _ = ss.pearsonr(dataset[columns[i]], dataset[columns[j]]) corr[columns[i]][columns[j]] = cell corr[columns[j]][columns[i]] = cell corr.fillna(value=np.nan, inplace=True) if mark_columns: marked_columns = ['{} (nom)'.format(col) if col in nominal_columns else '{} (con)'.format(col) for col in columns] corr.columns = marked_columns corr.index = marked_columns if plot: plt.figure(figsize=kwargs.get('figsize',None)) sns.heatmap(corr, annot=kwargs.get('annot',True), fmt=kwargs.get('fmt','.2f')) plt.show() if return_results: return corr ############################################################################################################################### ## ENCODING ############################################################################################################################### """ below class was taken from url=https://www.kaggle.com/superant/oh-my-cat Thermometer encoding (believed to be working really good for GANs) cannot handle unseen values in test. so use for situations where all levels for a cat variable has atleast 1 sample in train """ from sklearn.base import TransformerMixin from itertools import repeat import scipy class ThermometerEncoder(TransformerMixin): """ Assumes all values are known at fit """ def __init__(self, sort_key=None): self.sort_key = sort_key self.value_map_ = None def fit(self, X, y=None): self.value_map_ = {val: i for i, val in enumerate(sorted(X.unique(), key=self.sort_key))} return self def transform(self, X, y=None): values = X.map(self.value_map_) possible_values = sorted(self.value_map_.values()) idx1 = [] idx2 = [] all_indices = np.arange(len(X)) for idx, val in enumerate(possible_values[:-1]): new_idxs = all_indices[values > val] idx1.extend(new_idxs) idx2.extend(repeat(idx, len(new_idxs))) result = scipy.sparse.coo_matrix(([1] * len(idx1), (idx1, idx2)), shape=(len(X), len(possible_values)), dtype="int8") return result ############################################################################################################################### ## MISC ############################################################################################################################### # global function to flatten columns after a grouped operation and aggregation # outside all classes since it is added as an attribute to pandas DataFrames def __my_flatten_cols(self, how="_".join, reset_index=True): how = (lambda iter: list(iter)[-1]) if how == "last" else how self.columns = [how(filter(None, map(str, levels))) for levels in self.columns.values] \ if isinstance(self.columns, pd.MultiIndex) else self.columns return self.reset_index(drop=True) if reset_index else self pd.DataFrame.my_flatten_cols = __my_flatten_cols # find and append multiple dataframes of the type specified in string def append_datasets(cols_to_remove, string=['train', 'valid']): # pass either train or valid as str argument temp_files = [name for name in os.listdir('../input/') if name.startswith(string)] temp_dict = {} for i in temp_files: df_name = re.sub(string=i, pattern='.csv', repl='') temp_dict[df_name] = pd.read_csv(str('../input/' + str(i)), na_values=['No Data', ' ', 'UNKNOWN', '', 'NA', 'nan', 'none']) temp_dict[df_name].columns = map(str.lower, temp_dict[df_name].columns) temp_dict[df_name].drop(cols_to_remove, axis=1, inplace=True) chars_to_remove = [' ', '.', '(', ')', '__', '-'] for j in chars_to_remove: temp_dict[df_name].columns = temp_dict[df_name].columns.str.strip().str.lower().str.replace(j, '_') temp_list = [v for k, v in temp_dict.items()] if len(temp_list) > 1: temp = pd.concat(temp_list, axis=0, sort=True, ignore_index=True) else: temp = temp_list[0] return temp def read_file(path, format='csv', sheet_name='Sheet 1', skiprows=0, sep='|'): if format=='csv': try: x=pd.read_csv(path, na_values=['No Data', ' ', 'UNKNOWN', '', 'Not Rated', 'Not Applicable'], encoding='utf-8', low_memory=False) except: x=pd.read_csv(path, na_values=['No Data', ' ', 'UNKNOWN', '', 'Not Rated', 'Not Applicable'], encoding='latin-1', low_memory=False) pass elif format=='txt': x=pd.read_table(file_path, sep=sep, skiprows=skiprows, na_values=['No Data', ' ', 'UNKNOWN', '', 'Not Rated', 'Not Applicable']) elif format=='xlsx': x=pd.read_excel(file_path, na_values=['No Data', ' ', 'UNKNOWN', '', 'Not Rated', 'Not Applicable'], sheet_name=sheet_name) else: raise ValueError("format not supported") x.columns = x.columns.str.strip().lower().replace(r'[^\w\s]+', '_', regex=True) x.drop_duplicates(inplace=True) print(x.shape) return x
61a4b7daf5eb813d75f7998723a80603bd0113c6
zoharh20-meet/y2s19-mainstream-python-review
/part2.py
524
3.921875
4
# Part 2 of the Python Review lab. def encode(x, y): isprime(x,y) if 1 < y < 250 and 500 < x < 1000 : return x*y coded_message = decode(643,5) else: print ("Invalid input: Outside range.") def isprime(x,y): for i in range(2,y): if (y % i) == 0: print (y, "is not a prime number") y+=1 else: print (y, "is a prime number") for i in range(2,x): if (x % i) == 0: print (x, "is not a prime number") y+=1 else: print (x, "is a prime number") def decode(coded_message): return x/y
4bef41844a271ef1c0766b6d868bff3a8a96430f
MrAliTheGreat/DesignAlgorithms
/Divide&Conquer/3.py
2,014
3.53125
4
import math def divide_by_degree(coordinates): new_subtree = [] min_y_coordinate = min(coordinates , key = lambda y: y[1]) for coordinate in coordinates: if(coordinate == min_y_coordinate): continue degree = math.atan( (coordinate[1] - min_y_coordinate[1]) / (coordinate[0] - min_y_coordinate[0]) ) * (180 / math.pi) if(degree >= 0): new_subtree.append((degree , coordinate[0] , coordinate[1] , coordinate[2])) elif(degree < 0): new_subtree.append((degree + 180 , coordinate[0] , coordinate[1] , coordinate[2])) new_subtree = sorted(new_subtree, key = lambda element: element[0]) i = 0 while(i < len(new_subtree)): new_subtree[i] = new_subtree[i][1 :] i += 1 return new_subtree[0 : (len(new_subtree) - 1) // 2 + 1] , new_subtree[(len(new_subtree) - 1) // 2 + 1 :] , min_y_coordinate def merged_subtrees(root , left_subtree , right_subtree , node_num): left_subtree.extend(right_subtree) left_subtree.append((node_num , root[2])) return left_subtree def draw_tree(coordinates , height , node_num): if(len(coordinates) == 1 or height == 0): return [(node_num , min(coordinates , key = lambda x: x[0])[2])] height -= 1 left_subtree , right_subtree , root = divide_by_degree(coordinates) left_answer = draw_tree(left_subtree , height , 2 * node_num) right_answer = draw_tree(right_subtree , height , 2 * node_num + 1) return merged_subtrees(root , left_answer , right_answer , node_num) def print_answer(answer , num_coordinates , height): final_answer = [0] * num_coordinates num_nodes = 0 for item in answer: final_answer[item[1]] = item[0] for num in final_answer: if(num != 0): num_nodes += 1 if(num_nodes >= 1 and num_nodes <= (2 ** (height + 1)) - 1): for num in final_answer: print(num) else: print(-1) n , k = list(map(int , input().split())) coordinates = [] for index in range(n): new_x , new_y = list(map(int , input().split())) coordinates.append((new_x , new_y , index)) print_answer(draw_tree(coordinates , k , 1) , n , k)
54a62e36a803799a34caa232742c614c41f05ed0
shindekalpesh/streamlit-bmi
/app.py
2,816
3.59375
4
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import accuracy_score,mean_absolute_error,mean_squared_error import streamlit as st df = pd.read_csv("weight-height.csv") df['Gender'] = df['Gender'].replace({'Male':1,'Female':0}) #df['Height'] = round(df['Height'],2) #df['Weight'] = round(df['Weight'],2) ### df['height_inch'] = df['Height'] #df['height_metre'] = round(df['height_inch']/39.37,2) df['height_metre'] = df['height_inch']/39.37 df['weight_pound'] = df['Weight'] #df['weight_kg'] = round(df['weight_pound']/2.205,2) df['weight_kg'] = df['weight_pound']/2.205 ### # The formula to calculate the BMI is: BMI = kg/m2: df['bmi'] = round(df['weight_kg']/(df['height_metre']**2),2) df = df.drop(columns=['Height','Weight','height_inch','weight_pound']) # Splitting the dependant and independant features: X = df.iloc[:,:3] y = df.iloc[:,3:] X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2) ### MODEL linear = LinearRegression() model = linear.fit(X_train,y_train) y_pred = model.predict(X_test) ##################################################### nav = st.sidebar.radio("Navigation Panel",['Home','Prediction']) if nav == 'Home': st.write("**Hello. Welcome to the homepage!**") elif nav == 'Prediction': st.write("**Hello. Welcome to the Prediction Page!**") st.write("**Enter your following details to find out your BMI Score and BMI Output**") gender = st.selectbox("Gender: Select 1 for Male & 0 for Female",df['Gender'].unique()) #select_height = st.radio("Select the metric for Height. ",["Inches","Metres"]) height = st.text_input("Enter your height: ") #select_weight = st.radio("Select the metric for Weight. ",["Pounds","Kilograms"]) weight = st.text_input("Enter your weight: ") if st.button("Submit"): result = model.predict([[gender,height,weight]]) st.write(f"**The BMI Score is {result}.**") if np.array(result) <= 18.4: st.write("**You are underweight.**") elif np.array(result) <= 24.9: st.write("**You are healthy.**") elif np.array(result) <= 29.9: st.write("**You are over weight.**") elif np.array(result) <= 34.9: st.write("**You are severely over weight.**") elif np.array(result) <= 39.9: st.write("**You are obese.**") else: st.write("**You are severely obese.**") #st.write(f"**The Root Mean Square Accuracy of the model is {np.sqrt(mean_squared_error(y_test,y_pred))}.**") #st.write(f"Your Height in Metres is {height}.\nYour Weight in Kilograms is {weight}.\nYour Calculated BMI score is {result}.\n.")
9ba449e05088c2b51010759f48484b37a3153008
AvaniAnand/Python
/BingoGame.py
909
4.09375
4
print("Welcome to the Bingo Game...\n") print("In the game of Bingo, when a player enters a number") print("it is checked against the following list:") n_bingolist = [7,26,40,58,73,14,22,34,55,68] print(n_bingolist) print("if the number exists in the above list it is crossed out") print("When all the numbers have been crossed out, the player receives a BINGO from the system") n_listcount=(len(n_bingolist)) i = 0 while i < (n_listcount): # loop counter less than the listcount n_input=int(input("Please enter a random number between 1 and 80 inclusive:...\n")) #input a no. print("Thank you for your input\n") if n_input in n_bingolist: n_bingolist.remove(n_input) # strike off numbers off the list if there is a match if (len(n_bingolist)) != 0: # if the list is not empty then increment by 1 i += 1 else: # else Bingo print("Bingo!!!") break
d04ead124cbccf3a0a48022ff53e9a9ba5c472e6
archit-55/Python
/problem4.py
298
3.859375
4
#!/usr/bin/python3 import os import string username=input("Enter username:") flag=0 for i in list(username): if i not in string.ascii_letters : print("Incorrect Username!") flag=1 if flag==0 : os.system('sudo useradd'+username) os.system('sudo passwd'+username)
eb0494758c0e4976095ade36025341d9cb3a7131
melnikovay/U2
/u2_z8.py
692
4.15625
4
#Посчитать, сколько раз встречается определенная цифра в #введенной последовательности чисел. Количество вводимых чисел и цифра, #которую необходимо посчитать, задаются вводом с клавиатуры. n = int(input('Введите последовательность натуральных чисел ')) c = int (input ('Введите цифру от 0 до 9 ')) k = 0 while n > 0: x = n % 10 n = n // 10 if c == x: k = k + 1 print ('Цифра' ,c ,'встречается в числе', k ,'раз')
a1dd8790cc6d7ed8a519d9cb009616e3897760d7
wlizama/python-training
/decoradores/decorator_sample02.py
651
4.15625
4
""" Decorador con parametros """ def sum_decorator(exec_func_before=True): def fun_decorator(func): def before_func(): print("Ejecutando acciones ANTES de llamar a función") def after_func(): print("Ejecutando acciones DESPUES de llamar a función") def wrapper(*args, **kwargs): if exec_func_before: before_func() func(*args, **kwargs) after_func() return wrapper return fun_decorator @sum_decorator(exec_func_before=False) def suma_simple(num1, num2): print("Suma simple: {}".format(num1 + num2)) suma_simple(35, 80)
1c8b501916260c15d10c94a76ad1868eaccccbf1
wlizama/python-training
/aleatorio.py
1,461
3.765625
4
import random RSTART = 0 RLIMIT = 1024 CNUMS = 1024 def adivinaAleatorio(): numberFound = False randomNumber = random.randint(RSTART, RLIMIT) while not numberFound: numberInput = int(input("intenta un número: ")) if numberInput == randomNumber: print("¡¡¡Encontraste el número!!!") numberFound = True elif numberInput > randomNumber: print("el número es más pequeño") else: print("El número es mas grande") def randonList(): rnd_list = [random.randint(RSTART, RLIMIT) for i in range(CNUMS)] print(rnd_list) def randonListFnrandrange(): rnd_list = [random.randrange(RSTART, RLIMIT) for i in range(CNUMS)] print(rnd_list) def randonListNoRepeat(): rnd_list = random.sample(range(RSTART, RLIMIT), CNUMS) print(rnd_list) if __name__ == '__main__': option = int(input(""" Prueba de %i números aleatorios generados desde %i hasta %i Seleccionar opcion: [1] Prueba adivinar aleatorio [2] Imprimir lista de aleatorios [3] Imprimir lista de aleatorios con funcion 'randrange' [4] Imprimir lista de aleatorios sin repetir """ % (CNUMS, RSTART, RLIMIT))) if option == 1: adivinaAleatorio() elif option == 2: randonList() elif option == 3: randonListFnrandrange() elif option == 4: randonListNoRepeat() else: print("No existe opción")
a0cfb09711960eb43ed313ce44a408033a67fd39
wlizama/python-training
/Algoritmos/ordenamiento_x_seleccion.py
832
3.65625
4
ARRAY = [48, 84, 2, 12, 54, 10, 32, 44, 1, 78, 65, 8, 27, 81, 76, 62, 15] def swapArray(arr, idx_ant, idx_new): val_ant = arr[idx_ant] arr[idx_ant] = arr[idx_new] arr[idx_new] = val_ant return arr def selectionSort(arr): idx_ini = 0 max_idx = len(arr) for idx_pos_sort in range(idx_ini, max_idx): idx_min = idx_pos_sort for idx_iter in range(idx_pos_sort + 1 , max_idx): if arr[idx_iter] < arr[idx_min]: idx_min = idx_iter arr = swapArray(arr, idx_pos_sort, idx_min) print(arr) return arr def main(): print("Array original:", ARRAY) print("Longitud:", len(ARRAY)) print("Max. Index:", len(ARRAY) - 1) arr_sorted = selectionSort(ARRAY) print("Sorted:", arr_sorted) if __name__ == "__main__": main()
3ab3f91e0eb91e39c3c0436abd372260af0d39a7
Moyosooreoluwa/Simple-SnakeGame-with-Python-Pygame
/SnakeGame.py
4,643
3.6875
4
# I imported the libraries I was going to use. import pygame import time import random # Always have to initialise pygame. pygame.init() # Here I stored the scientific "RGB" format of a number of colours so that if needed I can easily call them as their # colours instead of having to type out the "RGB" format. white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) darkBlue = (0, 0, 128) white = (255, 255, 255) blue = (0, 0, 255) pink = (255, 200, 200) # Display width and height of the window. dis_width = 600 dis_height = 400 # This sets the display dimensions mentiooned above and also gives the window a caption. # I'm a huge batman fan, hence the caption. dis = pygame.display.set_mode((dis_width, dis_height)) pygame.display.set_caption('Snake Game by Wayne Enterprises (c)') # We need a clock because of the speed of the moving snake. clock = pygame.time.Clock() snake_block = 10 snake_speed = 15 font_style = pygame.font.SysFont("aguda", 25) score_font = pygame.font.SysFont("moonhouse", 35) # To display your score. def Your_score(score): value = score_font.render("Moyo's Snake Game! Score: " + str(score), True, pink) dis.blit(value, [0, 0]) # This is to describe the food (rectangular blocks) that the snake would eat. def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, red, [x[0], x[1], snake_block, snake_block]) def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3]) def gameLoop(): # These are false so that the game keeps running game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_List = [] Length_of_snake = 1 # The x and y coordinates of each block has to e randomised... The main point of the game foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 while not game_over: while game_close == True: # What to display whenever you lose. dis.fill(black) message("You Lost :( Press 'C' to Play Again or 'Q' to Quit", red) Your_score(Length_of_snake - 1) pygame.display.update() # The keyboard control interpretations. for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = snake_block x1_change = 0 # To make the snake longer with every food block it eats. if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(black) pygame.draw.rect(dis, white, [foodx, foody, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for x in snake_List[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_List) Your_score(Length_of_snake - 1) pygame.display.update() # After eating a block, random position for the next, and updated length. if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Length_of_snake += 1 clock.tick(snake_speed) pygame.quit() gameLoop()
0d86df6c0184fc21149405f1a387d36a74173d1f
murrayblake/Computational-Thinking-Project
/Utilities.py
2,163
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 22 15:12:39 2021 @author: Blake Murray & Matt Deiss """ from tkinter import * from tkinter import ttk import pandas as pd import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt import csv def getwingraph(): dataframe = pd.read_csv('cbb20.csv', index_col = 2) fig, ax = plt.subplots() dataframe = dataframe.sort_values('W', ascending = False) ax.bar(dataframe.index, dataframe['W']) ax.set_xticklabels(dataframe.index, rotation = 60, horizontalalignment = 'right', fontsize = 12) ax.set_title('Number of Wins by Conference', fontsize = 20) ax.set_ylabel('# Wins', fontsize = 10) ax.set_xlabel('Conference', fontsize = 10) plt.savefig('ConferenceWinsBar.png') plt.show() def findthemax(): input_file = csv.DictReader(open('cbb20.csv')) max_win = None max_team = None for row in input_file: win = int(row['W']) if max_win == None or max_win < win: max_win = win max_team = row['TEAM'] if max_win != None: op = (max_team,max_win) output_text = Label(text = op) output_text.place(x = 150, y = 300) else: print('The file does not contain teams') def champions(): with open('cbb.csv') as file: reader = csv.reader(file) champ = [] for row in reader: if 'Champions' in row: champ.append(row[0]+'-'+row[23]+',') pc = champ output_champ = Label(text=pc) output_champ.place(x=150, y=360) def getshootinggraph(): data = np.genfromtxt("cbb20.csv", delimiter=",", names=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v"]) plt.plot(data["a"], data["i"]) plt.title('Effective Field Goal % Compared to Rank') plt.ylabel('Shooting Percentage') plt.xlabel('End of Season Rank') plt.savefig('ShootingLine.png') plt.show()
fe98d96ca3777e610bb0dd3c99a79319d335924f
s1s1ty/JobShop
/jobshop/simulated_annealing.py
3,713
3.546875
4
from .helper import * import math import random import time class SimulatedAnnealing(object): def __init__(self): pass def __random_schedule(self, j, m): schedule = [i for i in list(range(j)) for _ in range(m)] random.shuffle(schedule) return schedule def __cost(self, jobs, schedule): j = len(jobs) m = len(jobs[0]) tj = [0]*j tm = [0]*m ij = [0]*j for i in schedule: machine, time = jobs[i][ij[i]] ij[i] += 1 start = max(tj[i], tm[machine]) end = start + time tj[i] = end tm[machine] = end return max(tm) def __get_neigbors(self, state, mode="normal"): neighbors = [] for i in range(len(state)-1): n = state[:] if mode == "normal": swap_index = i + 1 elif mode == "random": swap_index = random.randrange(len(state)) n[i], n[swap_index] = n[swap_index], n[i] neighbors.append(n) return neighbors def __simulated_annealing(self, jobs, T, termination, halting, mode, decrease): total_jobs = len(jobs) total_machines = len(jobs[0]) state = self.__random_schedule(total_jobs, total_machines) for i in range(halting): T = decrease * float(T) for k in range(termination): actual_cost = self.__cost(jobs, state) for n in self.__get_neigbors(state, mode): n_cost = self.__cost(jobs, n) if n_cost < actual_cost: state = n actual_cost = n_cost else: probability = math.exp(-n_cost/T) if random.random() < probability: state = n actual_cost = n_cost return actual_cost, state def simulated_annealing_search(self, jobs, max_time=None, T=200, termination=10, halting=10, mode="random", decrease=0.8): num_experiments = 1 solutions = [] best = 10000000 t0 = time.time() total_experiments = 0 j = len(jobs) m = len(jobs[0]) rs = self.__random_schedule(j, m) while True: try: start = time.time() for i in range(num_experiments): cost, schedule = self.__simulated_annealing(jobs, T=T, termination=termination, halting=halting, mode=mode, decrease=decrease) if cost < best: best = cost solutions.append((cost, schedule)) total_experiments += num_experiments if max_time and time.time() - t0 > max_time: raise TimeExceed("Time is over") t = time.time() - start if t > 0: print("Best:", best, "({:.1f} Experiments/s, {:.1f} s)".format( num_experiments/t, time.time() - t0)) if t > 4: num_experiments //= 2 num_experiments = max(num_experiments, 1) elif t < 1.5: num_experiments *= 2 except (KeyboardInterrupt, TimeExceed) as e: print() print("================================================") print("Best solution:") print(solutions[-1][1]) print("Found in {:} experiments in {:.1f}s".format(total_experiments, time.time() - t0)) return solutions[-1]
1b56fdccad3fbbe05698205721c3bddc9247b71b
JamesVera-Soto/BumbleBee
/speachTextAnalyze.py
436
3.609375
4
""" Speech Recognition text2emotion """ import speech_recognition as sr import text2emotion as te r = sr.Recognizer() with sr.Microphone() as source: print('Speak Anything: ') audio = r.listen(source) try: text = r.recognize_google(audio) print('You said: {}'.format(text)) emotions = te.get_emotion(text) print(emotions) except: print('Sorry could not recognize speech')
11b8a8611760549c100779031f905f45e6f83c04
Rupali59/ProgramSnippets
/minimum_path_to_destination.py
3,006
3.734375
4
# PROBLEM STATEMENT - Given the distance matrix, find the shortest distance and path traced from source to destination. import math import os import random import re import sys def distance_to_destination(source, destination, path_array, distance_covered, path_travelled): # Not the most optimum solution if(source == destination): print("distance_to_destination("+str(source)+", "+str(destination)+", path_array, " + str(distance_covered) + ", " +str(path_travelled)+")") return distance_covered,path_travelled; else: possible_destinations = get_connected_elements_to_point(source, path_array, path_travelled) if(len(possible_destinations) == 0): return -1 else: possible_distance_covered = [] for possible_destination in possible_destinations : d = path_array[source][possible_destination] p = (path_travelled[:]) if(possible_destination not in p): p.append(possible_destination) rest_of_the_distance = distance_to_destination(possible_destination, destination, path_array, d, p) possible_distance_covered.append(d+rest_of_the_distance,path_travelled) distance = 1000000 path = [] for item in possible_distance_covered: if item[0]<distance: distance = item[0] position = item[1] return distance,position def get_connected_elements_to_point(source, path_array, path_travelled): destinations = [] for possible_destination in range(len(path_array[source])): if path_array[source][possible_destination] != 0 and possible_destination not in path_travelled: destinations.append(possible_destination) return destinations def number_of_available_cabs(arr): return sum(e==0 for e in arr) def fill_path_array(arr): for i in range(0,len(arr)): for j in range(0,len(arr[i])): arr[j][i] = arr[i][j] return arr if __name__ == '__main__': # source, destination = [int(x) for x in str(raw_input()).split()] path_array = [] source = 0 destination = 5 path_array = [ [ 0, 42, 53, 64, 75, 86, 97, 108, 119 ], [ 0, 0, 11, 12, 13, 14, 15, 16, 17], [ 0, 0, 0, 21, 22, 23, 24, 25, 26], [ 0, 0, 0, 0, 31, 32, 33, 34, 35], [ 0, 0, 0, 0, 0, 41, 42, 43, 44], [ 0, 0, 0, 0, 0, 0, 51, 52, 53], [ 0, 0, 0, 0, 0, 0, 0, 61, 62], [ 0, 0, 0, 0, 0, 0, 0, 0, 71], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ] res = distance_to_destination(source, destination, fill_path_array(path_array) ,0,[source]) print(res)
89f97d630f3c3c3e4614033c66233bf3facd2997
noelledaley/hb-homework
/skills-dictionaries/skills.py
12,050
4.5625
5
# To work on the advanced problems, set to True ADVANCED = True def count_unique(input_string): """Count unique words in a string. This function should take a single string and return a dictionary that has all of the distinct words as keys, and the number of times that word appears in the string as values. For example: >>> print_dict(count_unique("each word appears once")) {'appears': 1, 'each': 1, 'once': 1, 'word': 1} Words that appear more than once should be counted each time: >>> print_dict(count_unique("rose is a rose is a rose")) {'a': 2, 'is': 2, 'rose': 3} It's fine to consider punctuation part of a word (e.g., a comma at the end of a word can be counted as part of that word) and to consider differently-capitalized words as different: >>> print_dict(count_unique("Porcupine see, porcupine do.")) {'Porcupine': 1, 'do.': 1, 'porcupine': 1, 'see,': 1} """ # turn input string into a list so I can iterate by words input_list = input_string.split() distinct_words = {} # add each word to the dictionary with default value of zero. # if word is already in the dictionary, add 1 for word in input_list: distinct_words[word] = distinct_words.get(word, 0) + 1 return distinct_words def find_common_items(list1, list2): """Produce the set of common items in two lists. Given two lists, return a list of the common items shared between the lists. IMPORTANT: you may not not 'if ___ in ___' or the method 'index'. For example: >>> sorted(find_common_items([1, 2, 3, 4], [1, 2])) [1, 2] If an item appears more than once in both lists, return it each time: >>> sorted(find_common_items([1, 2, 3, 4], [1, 1, 2, 2])) [1, 1, 2, 2] (And the order of which has the multiples shouldn't matter, either): >>> sorted(find_common_items([1, 1, 2, 2], [1, 2, 3, 4])) [1, 1, 2, 2] """ common_items = [] # iterate through every item in first list for item in list1: # during each iteration of first list, also iterate through second list # this is terribly inefficient! for second_item in list2: if item == second_item: common_items.append(item) return common_items def find_unique_common_items(list1, list2): """Produce the set of *unique* common items in two lists. Given two lists, return a list of the *unique* common items shared between the lists. IMPORTANT: you may not not 'if ___ in ___' or the method 'index'. Just like `find_common_items`, this should find [1, 2]: >>> sorted(find_unique_common_items([1, 2, 3, 4], [1, 2])) [1, 2] However, now we only want unique items, so for these lists, don't show more than 1 or 2 once: >>> sorted(find_unique_common_items([1, 2, 3, 4], [1, 1, 2, 2])) [1, 2] """ # convert each list to set; will remove duplicates set1 = set(list1) set2 = set(list2) # use & operator to find common values between set1 and set2 unique_set = set1 & set2 return unique_set def get_sum_zero_pairs(input_list): """Given a list of numbers, return list of x,y number pair lists where x + y == 0. Given a list of numbers, add up each individual pair of numbers. Return a list of each pair of numbers that adds up to 0. For example: >>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1]) ) [[-2, 2], [-1, 1]] >>> sort_pairs( get_sum_zero_pairs([3, -3, 2, 1, -2, -1]) ) [[-3, 3], [-2, 2], [-1, 1]] This should always be a unique list, even if there are duplicates in the input list: >>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1, 1, 1]) ) [[-2, 2], [-1, 1]] Of course, if there are one or more zeros to pair together, that's fine, too (even a single zero can pair with itself): >>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1, 1, 1, 0]) ) [[-2, 2], [-1, 1], [0, 0]] """ all_zero_pairs = {} # there has to be a more efficient way to do this... for item in input_list: # iterating over list a second time for other_item in input_list: # if they're a zero pair, add to dictionary if item + other_item == 0: zero_pair = (item, other_item) zero_alt = (other_item, item) if zero_pair not in all_zero_pairs and zero_alt not in all_zero_pairs: all_zero_pairs[zero_pair] = None zero_pairs = all_zero_pairs.keys() return zero_pairs def remove_duplicates(words): """Given a list of words, return the list with duplicates removed without using a Python set. For example: >>> sorted(remove_duplicates( ... ["rose", "is", "a", "rose", "is", "a", "rose"])) ['a', 'is', 'rose'] You should treat differently-capitalized words as different: >>> sorted(remove_duplicates( ... ["Rose", "is", "a", "rose", "is", "a", "rose"])) ['Rose', 'a', 'is', 'rose'] """ no_duplicates = {} # adding all words to a dictionary, since dictionaries cannot contain duplicate keys. for word in words: no_duplicates[word] = None return no_duplicates.keys() def encode(phrase): """Given a phrase, replace all "e" characters with "p", replace "a" characters with "d", replace "t" characters with "o", and "i" characters with "u". Return the encoded string. For example: >>> encode("You are a beautiful, talented, brilliant, powerful musk ox.") 'You drp d bpduouful, odlpnopd, brulludno, powprful musk ox.' """ encode_dict = { 'e': 'p', 'a': 'd', 't': 'o', 'i': 'u' } new_phrase = "" # iterate through letters and replace with desired letter. for letter in phrase: if letter in encode_dict: letter = encode_dict[letter] new_phrase += letter return new_phrase def sort_by_word_length(words): """Given list of words, return list of ascending [(len, [words])]. Given a list of words, return a list of tuples, ordered by word-length. Each tuple should have two items--the length of the words for that word-length, and the list of words of that word length. For example: >>> sort_by_word_length(["ok", "an", "apple", "a", "day"]) [(1, ['a']), (2, ['ok', 'an']), (3, ['day']), (5, ['apple'])] """ word_lengths = {} # iterate through list of words for word in words: # append word lengths to dictionary, set value to word & store in a list if len(word) not in word_lengths: word_lengths[len(word)] = [word] else: # if word length is already in dictionary, append value word_lengths[len(word)].append(word) return word_lengths.items() def get_pirate_talk(phrase): """Translate phrase to pirate talk. Given a phrase, translate each word to the Pirate-speak equivalent. Words that cannot be translated into Pirate-speak should pass through unchanged. Return the resulting sentence. Here's a table of English to Pirate translations: English Pirate ---------- ---------------- sir matey hotel fleabag inn student swabbie boy matey madam proud beauty professor foul blaggart restaurant galley your yer excuse arr students swabbies are be lawyer foul blaggart the th' restroom head my me hello avast is be man matey For example: >>> get_pirate_talk("my student is not a man") 'me swabbie be not a matey' You should treat words with punctuation as if they were different words: >>> get_pirate_talk("my student is not a man!") 'me swabbie be not a man!' """ pirate_dict = {" sir": "matey", "hotel" : "fleabag inn", "student" : "swabbie", "boy" : "matey", "madam" : "proud beauty", "professor" : "foul blaggart", "restaurant" : "galley", "your" : "yer", "excuse" : "arr", "students" : "swabbies", "are": "be", "lawyer" : "foul blaggart", "the": "th\'", "restroom" : "head", "my": "me", "hello" : "avast", "is": "be", "man": "matey"} # split string into list so I can iterate by words. phrase_list = phrase.split() pirate_words = [] for word in phrase_list: # if the word is in pirate dictioary, replace word with its corresponding key. if word in pirate_dict: word = pirate_dict[word] # all all words to the new, 'translated', list. pirate_words.append(word) pirate_words = " ".join(pirate_words) return pirate_words # # End of skills. See below for advanced problems. # # To work on them, set ADVANCED=True at the top of this file. # ############################################################################ def adv_get_top_letter(input_string): """Given an input string, return a list of letter(s) which appear(s) the most the input string. If there is a tie, the order of the letters in the returned list should be alphabetical. For example: >>> adv_get_top_letter("The rain in spain stays mainly in the plain.") ['i', 'n'] If there is not a tie, simply return a list with one item. For example: >>> adv_get_top_letter("Shake it off, shake it off. Shake it off, Shake it off.") ['f'] Spaces do not count as letters. """ # initialize empty dictionary. letter_freq = {} # for each letter in string, add to empty dictionary. for letter in input_string.lower(): if letter == " " or letter in ".,!?#$": pass else: letter_freq[letter] = letter_freq.get(letter, 0) + 1 # turn dictionary into tuples freq_first = [] for letter, freq in letter_freq.items(): freq_first.append((freq, letter)) print sorted(freq_first) # at this point, I have a list of tuples sorted by letter frequency, but not sure what to do. return '' # def adv_alpha_sort_by_word_length(words): # """ # Given a list of words, return a list of tuples, ordered by word-length. # Each tuple should have two items--a number that is a word-length, # and the list of words of that word length. In addition to ordering # the list by word length, order each sub-list of words alphabetically. # Now try doing it with only one call to .sort() or sorted(). What does the # optional "key" argument for .sort() and sorted() do? # # For example: # # >>> adv_alpha_sort_by_word_length(["ok", "an", "apple", "a", "day"]) # [(1, ['a']), (2, ['an', 'ok']), (3, ['day']), (5, ['apple'])] # # """ # # return [] ############################################################################## # You can ignore everything below this. def print_dict(d): # This method is just used to print dictionaries in key-alphabetical # order, and is only used for our documentation tests. You can ignore it. if isinstance(d, dict): print "{" + ", ".join("%r: %r" % (k, d[k]) for k in sorted(d)) + "}" else: print d def sort_pairs(l): # Print sorted list of pairs where the pairs are sorted. This is used only # for documentation tests. You can ignore it. return sorted(sorted(pair) for pair in l) if __name__ == "__main__": print import doctest for k, v in globals().items(): if k[0].isalpha(): if k.startswith('adv_') and not ADVANCED: continue a = doctest.run_docstring_examples(v, globals(), name=k) print "** END OF TEST OUTPUT" print
6da9e9bc2050310c5d6bde6a217378a12bc16e8f
GaganDeepak/PreOpenMarketAnalysis
/2.EveExec.py
990
3.75
4
#!/usr/bin/env python3 #This Program get the market close data for the pre-open stocks for that particular date import pandas as pd from datetime import date from nsepy import get_history #read the pre-open market file to get the stocks symbol pom = pd.read_csv('pom.csv') #create empty dataframe hist = pd.DataFrame() month = date.today().month dt = int(input("enter the preopen market date ")) if dt == date.today().day: enddt = dt+1 else: enddt = dt #get the history data for particular date ,change the end day to next day for getting live date data for ind, row in pom.iterrows(): name = row['symbol'] hist = hist.append(get_history(symbol = name,start = date(2020,month,dt),end = date(2020,month,enddt)),ignore_index = True) print(row) #delete the repeated values in history data hist = hist.drop(['Symbol','Series','Prev Close','Open','Last','Deliverable Volume'],axis=1) #concats the preopen pom = pd.concat([pom,hist],axis=1) pom.to_csv("pom.csv",index=False)
2aed12b43eb3230b69717d981e1a86d33d788c05
mariachefneux/python-challenge
/PyPoll/main.py
2,317
3.890625
4
# Modules import os import csv import sys # Set path for file csvpath = os.path.join('election_data.csv') # Open the CSV with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Read the header row first csv_header = next(csvreader) # Define variables votes_dict = {} total_number_of_votes = 0 # Iterate on each row for vote_row in csvreader: # increase the total number of votes by 1 total_number_of_votes = total_number_of_votes + 1 # get the candidate's name from the 3rd column candidate_name = vote_row[2] # get the candidate's total vote number (get zero if no votes were added to votes_dict yet) candidate_total_vote = votes_dict.get(candidate_name, 0) # increase the number of votes for the candidate in the dict votes_dict[candidate_name] = candidate_total_vote + 1 # print everything to the terminal print('Election Results') print('-------------------------') print('Total Votes: ' + str(total_number_of_votes)) print('-------------------------') winner = '' winner_percentage = 0 for candidate_name in votes_dict: vote_percentage = votes_dict[candidate_name] / total_number_of_votes * 100 print(candidate_name + ': ' + str(round(vote_percentage, 3)) + '% (' + str(votes_dict[candidate_name]) + ')') if winner_percentage < vote_percentage: winner = candidate_name winner_percentage = vote_percentage print('-------------------------') print('Winner: ' + winner) print('-------------------------') # print everything to the results file results_file = open('PyPoll_Results.txt', 'w') sys.stdout = results_file print('Election Results') print('-------------------------') print('Total Votes: ' + str(total_number_of_votes)) print('-------------------------') winner = '' winner_percentage = 0 for candidate_name in votes_dict: vote_percentage = votes_dict[candidate_name] / total_number_of_votes * 100 print(candidate_name + ': ' + str(round(vote_percentage, 3)) + '% (' + str(votes_dict[candidate_name]) + ')') if winner_percentage < vote_percentage: winner = candidate_name winner_percentage = vote_percentage print('-------------------------') print('Winner: ' + winner) print('-------------------------')
4b11d8d1ea2586e08828e69e9759da9cd60dda23
petermooney/datamining
/plotExample1.py
1,798
4.3125
4
### This is source code used for an invited lecture on Data Mining using Python for ### the Institute of Technology at Blanchardstown, Dublin, Ireland ### Lecturer and presenter: Dr. Peter Mooney ### email: peter.mooney@nuim.ie ### Date: November 2013 ### ### The purpose of this lecture is to provide students with an easily accessible overview, with working ### examples of how Python can be used as a tool for data mining. ### For those using these notes and sample code: This code is provided as a means of showing some basic ideas around ### data extraction, data manipulation, and data visualisation with Python. ### The code provided could be written in many different ways as is the Python way. However I have tried to keep things simple and practical so that students can get an understanding of the process of data mining rather than this being a programming course in Python. ### ### If you use this code - please give me a little citation with a link back to the GitHub Repo where you found this piece of code: https://github.com/petermooney/datamining import matplotlib.pyplot as plt # this is a simple example of how to draw a pie chart using Python and MatplotLib # You will need matplotlit installed for this to work. def drawSamplePieChartPlot(): # we have 5 lecturers and we have the number of exam papers which # each of the lecturers have had to mark. lecturers = ['Peter','Laura','James','Jennifer','Patrick'] examPapersMarked = [14, 37, 22, 16,80] colors = ['purple', 'blue', 'green', 'yellow','red'] plt.pie(examPapersMarked, labels=lecturers, colors=colors,autopct='%1.1f%%',startangle=90) plt.axis('equal') # We are going to then save the pie chart as a PNG image file (nice for the web) plt.savefig("PieChartExample.png") def main(): drawSamplePieChartPlot() main()
4abddbae92428bd77a8833967dae19b4e24c4d05
petermooney/datamining
/plotExampleBarChart.py
3,159
4.6875
5
### This is source code used for an invited lecture on Data Mining using Python for ### the Institute of Technology at Blanchardstown, Dublin, Ireland ### Lecturer and presenter: Dr. Peter Mooney ### email: peter.mooney@nuim.ie ### Date: November 2013 ### ### The purpose of this lecture is to provide students with an easily accessible overview, with working ### examples of how Python can be used as a tool for data mining. ### For those using these notes and sample code: This code is provided as a means of showing some basic ideas around ### data extraction, data manipulation, and data visualisation with Python. ### The code provided could be written in many different ways as is the Python way. However I have tried to keep things simple and practical so that students can get an understanding of the process of data mining rather than this being a programming course in Python. ### ### If you use this code - please give me a little citation with a link back to the GitHub Repo where you found this piece of code: https://github.com/petermooney/datamining import csv import matplotlib.pyplot as plt import numpy as np # this is a simple example of how to draw a bar chart using Python and MatplotLib # you will also need a libary called NUMPY - which allows some fancy numerical calculations to be # be performed. # You will need matplotlit installed for this to work. # You will need to ensure you have numpy installed. # As before we will save the output chart as a PNG file. # Again we will have our actual data in the list dataValues # we will have our labels for those data in the list dataLabels # We need to provide a yLabel for the graph so that we can name that axis properly def drawSampleBarChartPlot(dataLabels,dataValues,outputImageFileName,plotTitle,yLabel): fig = plt.figure() ax = fig.add_subplot(111) N = len(dataLabels) # get the number of data values indices = np.arange(N) # the x locations for the groups of data # This is from the numpy library which was imported above. barWidth = 0.45 # the width of the bars ## the bars themselves are rectangles drawn onto the chart rects1 = ax.bar(indices, dataValues, barWidth,color='yellow') ax.set_xlim(0,len(indices)) # the limits of the x axis ax.set_ylim(0,max(dataValues) + 5) # let's set the maximum y value just a little bigger than the maximum # value in the data values which we want to plot. ax.set_ylabel(yLabel) # the y axis label ax.set_title(plotTitle) # the title of the plot ax.set_xticks(indices) # the place where the marks will be on the x axis xtickNames = ax.set_xticklabels(dataLabels) plt.setp(xtickNames, rotation=50, fontsize=9) # the font and rotation of the labels plt.title(plotTitle) # plot title. # We are going to then save the pie chart as a PNG image file (nice for the web) plt.savefig(outputImageFileName) plt.close() def main(): xTickMarks = ["Real M","Paris","Bayern","Atletico","Chelsea","Man. City","Barca","Leverkusen","Napoli"] xValues = [14,13,12,12,11,11,9,8,7] drawSampleBarChartPlot(xTickMarks,xValues,"championsLeagueGoals.png","Goals scored in Champions League - to Nov 2013","Goals Scored") main()
0db7dc9e7553294cc3f09dd5261cd6bbddbaa317
PDXDevCampJuly/Nehemiah-Newell
/Python/Dice/test_die_roll.py
1,759
3.890625
4
__author__ = 'Nehemiah' import unittest from dieClass import Die class die_roll_test(unittest.TestCase): """Test the functionality of the die class roll function""" def setUp(self): self.possible_values = [1,2,3,"Dog",'Cat','Hippo'] self.new_die = Die(self.possible_values) print(self.shortDescription()) def test_roll_once(self): """Roll the die once and make sure that the return value is in possible values""" self.assertIn(self.new_die.roll_die(),self.possible_values, "Rolled value was not in possible values of Die") print("Value in possible values") def test_rolled_value_changes(self): """Roll the a number of times to make sure it changes value""" holding_value = self.new_die.roll_die() for i in range(10): if self.new_die.roll_die() != holding_value: print("Rolled Die Value {} is different from Holding Value {}" .format(self.new_die.currentValue,holding_value)) self.assertTrue(True) return self.assertTrue(False,"Die value did not change from holding value for 10 rolls.") def test_current_value_is_updated_to_rolled_value(self): """Test that current value is updated to rolled value.""" self.new_die.currentValue = "A random string." thisValue = self.new_die.roll_die() self.assertEqual(thisValue,self.new_die.currentValue, "Current and return value differ") print("The current value was updated to the rolled value") def tearDown(self): print("Just ran: ") print(self._testMethodName) print if __name__ == '__main__': unittest.main()
c4a42b89e15d93444771c65bcfd8663cda3e2efe
PDXDevCampJuly/Nehemiah-Newell
/Python/Dice/angry_dice.py
4,580
3.953125
4
# Create and run a game of angry dice from dieClass import Die #Create an Angry Dice object class Angry_Dice: #Set up a game, taking no parameters def __init__(self,): # Declare a master list of die values self.masterlist = ["1","2","ANGRY","4","5","6"] # Declare the dice self.angryDieA = Die(self.masterlist) self.angryDieB = Die(self.masterlist) # set stage to 1 self.currentStage = 1 # set six watchflags to false self.invalidFlagA = False self.invalidFlagB = False #Roll the angry dice def roll_the_dice(self, rollString): returnString = "" # if A in string, roll the A die. if 'a' in rollString.lower(): self.angryDieA.roll_die() #A hasn't been held self.invalidFlagA = False returnString = returnString + 'a' # if B in string, roll the B die. if 'b' in rollString.lower(): self.angryDieB.roll_die() #B hasn't been held self.invalidFlagB = False returnString = returnString + 'b' #return the returnString return returnString #Print round status def print_round(self): print("You rolled:\n a =[ {} ]\n b =[ {} ]\n".format(self.angryDieA.__repr__(),self.angryDieB.__repr__())) #Check and advance through stages def stage_check(self): # get the current dice values into a string currentValues = self.angryDieA.__repr__() + self.angryDieB.__repr__() # if two angrys, recent to stage one if "ANGRYANGRY" == currentValues: self.currentStage = 1 print("WOW, you're ANRGY!\nTime to go back to Stage 1!") #else stage one logic elif self.currentStage == 1: if "1" in currentValues and "2" in currentValues: self.currentStage = 2 #else stage two logic elif self.currentStage == 2: if "ANGRY" in currentValues and "4" in currentValues: self.currentStage = 3 #else stage three logic if self.currentStage == 3: if "5" in currentValues and "6" in currentValues: print("You'be won! Calm down!") exit() #print current stage print("You are in Stage {}".format(str(self.currentStage))) #Make sure only valid dice are held def valid_check(self): if self.currentStage == 1: if self.angryDieA.__repr__() not in '1' and self.angryDieA.__repr__() not in '2': self.invalidFlagA = True if self.angryDieB.__repr__() not in '1' and self.angryDieB.__repr__() not in '2': self.invalidFlagB = True if self.currentStage == 2: if self.angryDieA.__repr__() not in 'ANGRY' and self.angryDieA.__repr__() not in '4': self.invalidFlagA = True if self.angryDieB.__repr__() not in 'ANGRY' and self.angryDieB.__repr__() not in '4': self.invalidFlagB = True if self.currentStage == 3: if self.angryDieA.__repr__() not in '5': self.invalidFlagA = True if self.angryDieB.__repr__() not in '5': self.invalidFlagB = True #Play the game def play(self): #set the roll string to roll both dice rollString = 'ab' #Great the player input("Welcome to Angry Dice! Roll the two dice until you get thru the 3 Stages!\nStage 1 you need to roll 1 & 2\nStage 2 you need to roll ANGRY & 4\nStage 3 you need to roll 5 & 6\nYou can lock a die needed for your current stage and just roll the other one, but beware!\nIf you ever get 2 ANGRY's at once, you have to restart to Stage 1!\nAlso, you can never lock a 6! That's cheating!\nTo roll the dice, simply input the name of the die you want to roll.\nTheir names are a and b.\nTo roll the dice, simply input the name of the die you want to roll.\nTheir names are a and b.\n\nPress ENTER to start.\n") #Roll the dice self.roll_the_dice(rollString) #Enter body of game while True: #as long as they aren't holding a six, coninue the game if self.invalidFlagA == False and self.invalidFlagB == False: #print out round self.print_round() #check the stage conditons to advance the game self.stage_check() else: #Tell them they are cheating if self.invalidFlagA == True and self.invalidFlagB == True: print("You're cheating! You cannot lock both of those dice! you cannot\nwin until you reroll it!") elif self.invalidFlagA == True: print("You're cheating! You cannot lock a {}! you cannot\nwin until you reroll it!".format(self.angryDieA.__repr__())) else: print("You're cheating! You cannot lock a {}! you cannot\nwin until you reroll it!".format(self.angryDieB.__repr__())) #print out round self.print_round() #check for held sixes self.valid_check() #get the input rollString = input("Roll dice: ") #roll the dice self.roll_the_dice(rollString) if __name__ == '__main__': game = Angry_Dice() game.play()
6187d788dd3f6fc9b049ded6d08189e6bb8923ed
lflores0214/Sorting
/src/iterative_sorting/iterative_sorting.py
1,583
4.34375
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements print(arr) for i in range(0, len(arr) - 1): # print(f"I: {i}") cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(cur_index, len(arr)): # check if the array at j is less than the current smallest index # print(f"J: {j}") # print(arr) if arr[j] < arr[smallest_index]: # if it is j becomes the smallest index smallest_index = j # TO-DO: swap arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] # print(arr) return arr my_arr = [1, 5, 8, 4, 2, 9, 6, 0, 7, 3] # print(selection_sort(my_arr)) # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): # loop through array # print(arr) for i in range(len(arr)-1): # check if the element at current index is greater than the element to the right # print(arr) for j in range(len(arr)-1): if arr[j] > arr[j+1]: # if it is than swap the two elements arr[j], arr[j+1] = arr[j+1], arr[j] # run loop again until they are all sorted print(arr) # bubble_sort(arr) return arr print(bubble_sort(my_arr)) # print(f"bubble: {bubble_sort(my_arr)}") # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
ccb6ca40ad86383d8b42521700846b66f2210cf3
tianzhuzhu/mystock
/utils/PC_util.py
450
3.515625
4
import ctypes import os # 获取计算机名 def getname()->str: pcName = ctypes.c_char_p(''.encode('utf-8')) pcSize = 16 pcName = ctypes.cast(pcName, ctypes.c_char_p) try: ctypes.windll.kernel32.GetComputerNameA(pcName, ctypes.byref(ctypes.c_int(pcSize))) except Exception: print("Sth wrong in getname!") return pcName.value.decode('utf-8') def main(): getname() if __name__ == "__main__": main()
83f3810eed3b82a8c9d238e9c8ac7f0d770c9d94
ZaytsevDmitriy/Task-9.1
/main.py
1,819
3.640625
4
import requests from pprint import pprint Super_hero_list = ['Hulk', 'Captain America', 'Thanos'] class super_hero(): def __init__(self, name): self.name = name # self.intelligence def super_hero_request(self): name = self.name url = ("https://superheroapi.com/api/2619421814940190/search/" + name) response = requests.get(url) intelligence = int(response.json()['results'][0]['powerstats']['intelligence']) # ['results']['powerstats']['intelligence'] return intelligence def comparison_intelligence(list): hero_dict = {} for i in list: super_hero1 = super_hero(i) hero_dict[super_hero1.super_hero_request()] = super_hero1.name cleverest_hero = hero_dict[max(hero_dict.keys())] print((f'Самый умный супергерой - {cleverest_hero}')) comparison_intelligence(Super_hero_list) # def comparison_intelligence (name1, name2, name3): # super_hero1 = super_hero(name1) # super_hero1_intelligence = super_hero1.super_hero_request() # super_hero2 = super_hero(name2) # super_hero2_intelligence = super_hero2.super_hero_request() # super_hero3 = super_hero(name3) # super_hero3_intelligence = super_hero3.super_hero_request() # if super_hero3_intelligence > super_hero2_intelligence \ # and super_hero3_intelligence > super_hero1_intelligence: # print((f'Самый умный супергерой - {super_hero3.name}')) # elif super_hero2_intelligence > super_hero1_intelligence \ # and super_hero2_intelligence > super_hero3_intelligence: # print((f'Самый умный супергерой - {super_hero2.name}')) # else: # print((f'Самый умный супергерой - {super_hero1.name}'))
0e6b4293d300816f8d79931a295a6609d366c41e
vinodhinia/CompetitiveCodingChallengeInPython
/SortingWithLambdaFunctions/SortingArrayWithParity.py
137
3.5625
4
def sortArrayPairing(A): A = A.sort(key=lambda a: a % 2) print(A) return A arr = [3, 1, 15, 2] print(sortArrayPairing(arr))
168a9554f9d16b23e68dac5a254354c0c9e4be10
vinodhinia/CompetitiveCodingChallengeInPython
/Stacks/MinStackOptimal.py
1,172
4.15625
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min_stack = [] def push(self, x): """ :type x: int :rtype: void """ if len(self.stack) == 0 and len(self.min_stack) == 0: self.min_stack.append(x) elif len(self.min_stack) != 0 and x <= self.min_stack[-1]: self.min_stack.append(x) self.stack.append(x) def pop(self): """ :rtype: void """ if len(self.min_stack) != 0 and len(self.stack) !=0 and self.stack[-1] == self.min_stack[-1]: self.min_stack.pop() self.stack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ return self.min_stack[-1] if len(self.min_stack) !=0 else None minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) print(minStack.getMin()) #--> Returns -3. minStack.pop() print(minStack.top()) #--> Returns 0. print(minStack.getMin()) #--> Returns -2.
c9b45ba49dab86e76c7153be439c407e7131d244
vinodhinia/CompetitiveCodingChallengeInPython
/GroupAnagrams.py
462
3.609375
4
class Solution: def groupAnagrams(self, strs): if strs is None or len(strs) ==0: return strs str_dict = {} for str in strs: key = ''.join(sorted(str)) if key in str_dict: str_dict[key].append(str) else: str_dict[key] =[str] return str_dict.values() strs = ["eat", "tea", "tan", "ate", "nat", "bat"] s = Solution() print(s.groupAnagrams(strs))
941f2f73af14bba0a991a49ba8e2e1f8740ce1cc
vinodhinia/CompetitiveCodingChallengeInPython
/UniqueEmailAddress.py
1,071
3.53125
4
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ # 1. Anything after + and before @ should be ignored # 2. '.' must be ignored result = set() if emails is None: return emails for email in emails: if email is None or len(email) == 0: return email else: result.add(self.handleSingleEmail(email)) return len(result) def handleSingleEmail(self, email): plus_index = email.find('+') if plus_index != -1: at_index = email.find('@') email = email[0: plus_index] + email[at_index:] at_index = email.find('@') while email.find('.') != -1 and email.find('.') < at_index: dot_index = email.find('.') email = email[0: dot_index] + email[dot_index + 1:] return email if __name__ == '__main__': s = Solution() print(s.numUniqueEmails(["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]))
1883f0aa23cbe35756581d33ff30405dc27bb3e9
vinodhinia/CompetitiveCodingChallengeInPython
/ReverseString.py
550
3.765625
4
class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ if s is None or s.strip() == "": return s start = 0 end = len(s) - 1 str_arr = list(s) while start < end: str_arr[start], str_arr[end] = str_arr[end], str_arr[start] start += 1 end -= 1 return ''.join(str_arr) # "A man, a plan, a canal: Panama" # "amanaP :lanac a ,nalp a ,nam A" s = Solution() print(s.reverseString("A man, a plan, a canal: Panama"))
a216f38152ebac94d682b1a3a5a255cb4ee1dc49
SHASHANK992/Python_Hackerrank_Challenges
/HACKERRANK_PYTHON_LIST.py
1,527
3.671875
4
times = int(input()) list=[] permanent=[] before=[] for i in range(0,times): permanent.append(str(input())) for i in range (0,times): temporary = permanent[i] temporary = temporary.lower() temporary2 = str() #print(before) if(temporary.find("insert",0,len("insert"))!=-1): values = [] values = temporary.split() position = int(values[1]) pos_string = str(position) item = int(values[2]) temporary2 = str(before) list.insert(position,item) #print(list) #before.append(int(position)) if(temporary.find("print",0,len("print"))!=-1): print(list) if(temporary.find("remove",0,len("remove"))!=-1): values = [] values = temporary.split() item = int(values[1]) list.remove(item) if(temporary.find("append",0,len("append"))!=-1): values=[] values=temporary.split() list.append(int(values[1])) if(temporary.find("sort",0,len("sort"))!=-1): list.sort() if(temporary.find("reverse",0,len("reverse"))!=-1): list.reverse() if(temporary.find("pop",0,len("pop"))!=-1): list.pop() if(temporary.find("index",0,len("index"))!=-1): values=[] values=temporary.split() location=values[1] print(list.index(location)) if(temporary.find("count",0,len("count"))!=-1): values=[] values=temporary.split() search_value=values[1] print(list.count(search_value))
9695efec2afdef9c42b85dd77f3939881dce21f6
yufeialex/all_python
/python_study/my/老王练习/基础篇7.py
412
3.84375
4
# coding=utf-8 ''' 今天习题 1: a = 'pyer' b = 'apple' 用字典和format方法实现: my name is pyer, i love apple. 2:打开文件info.txt,并且写入500这个数字。 ''' a = "pyer" b = "apple" print("my name is {name},i love {love}".format(name=a, love=b)) print("my,name is %(name)s, i love %(love)s" % {"name": a, "love": b}) # 2 file = open("info.txt", "w") file.write("500\n") file.close()
48b6f785674c52f25f732acd4759782ceebfb8ff
yufeialex/all_python
/qiyi/dictTest.py
2,285
3.640625
4
# https://segmentfault.com/a/1190000010567015 dict1 = {"lo": "beij"} dict2 = {"mm": "shang"} # 方法1,不好 # 在内存中创建两个列表,再创建第三个列表,拷贝完成后,创建新的dict,删除掉前三个列表。这个方法耗费性能,而且对于python3, # 这个无法成功执行,因为items()返回是个对象。 # 你必须明确的把它强制转换成list,z = dict(list(x.items()) + list(y.items())),这太浪费性能了。 # 另外,想以来于items()返回的list做并集的方法对于python3来说也会失败,而且,并集的方法,导致了重复的key在取值时的不确定,所以, # 如果你对两个dict合并有优先级的要求,这个方法就彻底不合适了。 dictMerged1 = dict(dict1.items() + dict2.items()) x = {'a': 2} y = {'a': 1} dict(x.items() | y.items()) # 可能留下了x,但是我想要y # 方法2,**的意思是基于字典的可变长函数参数。 # 比前面的两步的方法高效多了,但是可阅读性差,不够pythonic,如果当key不是字符串的时候,python3中还是运行失败 # Guido van Rossum 大神说了:宣告dict({}, {1:3})是非法的,因为毕竟是滥用机制。虽然这个方法比较hacker,但是太投机取巧了。 dictMerged2 = dict(dict1, **dict2) # 方法3 dictMerged3 = dict1.copy() dictMerged3.update(dict2) # 方法4,python3.5中支持 dictMerged4 = {**dict1, **dict2} def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z z = merge_two_dicts(x, y) def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result z = merge_dicts(a, b, c, d, e, f, g) # 一些性能较差但是比较优雅的方法 # 下面这些方法,虽然性能差,但也比items方法好多了。并且支持优先级。 {k: v for d in dicts for k, v in d.items()} # python2.6中可以这样 dict((k, v) for d in dicts for k, v in d.items()) # itertools.chain: import itertools z = dict(itertools.chain(x.iteritems(), y.iteritems()))
e721f3f8984fbbd9c897ecf57ba9886be925483b
yufeialex/all_python
/python_study/my/老王练习/基础篇18 周末习题.py
3,624
3.65625
4
# coding=utf-8 ''' 1. 已知字符串 a = "aAsmr3idd4bgs7Dlsf9eAF", 要求如下 1.1 请将a字符串的大写改为小写,小写改为大写。 ''' a = "aAsmr3idd4bgs7Dlsf9eAF" print(a.swapcase()) ''' 1.2 请将a字符串的数字取出,并输出成一个新的字符串。 ''' b = [s for s in a if s.isdigit()] print(''.join(b)) ''' 1.3 请统计a字符串出现的每个字母的出现次数(忽略大小写,a与A是同一个字母),并输出成一个字典。 例 {'a': 4, 'b': 2} ''' a = a.lower() print(dict([(x, a.count(x)) for x in set(a)])) # # [(x,a.count(x)) for x in set(a)] ''' 1.4 请去除a字符串多次出现的字母,仅留最先出现的一个。例 'abcabb',经过去除后,输出'abc' ''' print("=========1.4") a = "aAsmr3idd4bgs7Dlsf9eAF" a_list = list(a) set_list = list(set(a_list)) set_list.sort(key=a_list.index) print(''.join(set_list)) # print(a_list) ''' 1.5 请将a字符串反转并输出。例:'abc' 的反转是 'cba' ''' print("++++++++++++++1.5") a = "aAsmr3idd4bgs7Dlsf9eAF" list_a = list(a) # set_a = list(set(list_a)) list_a.reverse() print(''.join(list_a)) a = "aAsmr3idd4bgs7Dlsf9eAF" print(a[::-1]) ''' 1.6 去除a字符串内的数字后,请将该字符串里的单词重新排序(a - z),并且重新输出一个排序后的字符 串。(保留大小写, a与A的顺序关系为:A在a前面。例:AaBb) ''' print("+++++++++++1.6") a = "aAsmr3idd4bgs7Dlsf9eAFHH" # b = [s for s in a if s.islower()] # c = [s for s in a if s.isupper()] b = sorted(a) upper_list = [] lower_list = [] for x in b: if x.isupper(): upper_list.append(x) elif x.islower(): lower_list.append(x) else: pass for y in upper_list: y_lower = y.lower() if y_lower in lower_list: lower_list.insert(lower_list.index(y_lower), y) print(lower_list.index(y_lower)) print(upper_list) print(''.join(lower_list)) ''' 1.7 请判断 'boy'里出现的每一个字母,是否都出现在a字符串里。如果出现,则输出True,否则,则输出False. ''' print("++++++++++1.7") a = "aAsmr3idd4bgs7Dlsf9eAFoyHH" for i in "boari34bgsy": if i in a: continue else: break else: print("Ture") ''' 1.8 要求如1.7,此时的单词判断,由'boy'改为四个,分别是'boy', 'girl', 'bird', 'dirty',请判断如上这4个字符串里的每个字母,是否都出现在a字符串里。 ''' print("+++++++++++++++1.8") a = "aAsmr3idd4bgs7Dlsf9eAFoyHH" find = ['boy', 'girl', 'bird', 'dirty'] find_set = set(''.join(find)) b = set(a) u = len(b) for i in find_set: b.update(i) if u == len(b): print("Ture") else: print("none") # print(find_set) ''' 1.9 输出a字符串出现频率最高的字母 ''' print("++++++++++1.9") a = "aAsmr3idd4bgs7Dlsf9eAFoyHH" b = [(x, a.count(x)) for x in a] b.sort(key=lambda k: k[1], reverse=True) print(b[0][0]) ''' 2. 在python命令行里,输入import this以后出现的文档,统计该文档中,"be" "is" "than"的出现次数。 ''' print("+++++++++++2.0") import os m = os.popen('python -m this').read() m = m.replace('\n', '') m = m.split(' ') print([(x, m.count(x)) for x in ['be', 'is', 'than']]) ''' 3. 一文件的字节数为 102324123499123,请计算该文件按照kb与mb计算得到的大小。 ''' print("+++++++++3.0") b = 102324123499123 print("%s kb" % (b >> 10)) print("%s mb" % (b >> 20)) ''' 4. 已知 a = [1, 2, 3, 6, 8, 9, 10, 14, 17], 请将该list转换为字符串,例如 '123689101417'. ''' print("++++++++++++++4.0") a = [1, 2, 3, 6, 8, 9, 10, 14, 17] print(str(a)[1:-1].replace(', ', ''))
c87c16ed09866d18fdde4ed2d4566f989bd14393
polowis/text-based-rpg-game
/inventory.py
1,241
3.609375
4
import random class Inventory: def __init__(self, player, app): self.player = player self.bag = ['Potions', 'Postions'] self.size = 300 self.app = app def viewInventory(self, player, app): """View Inventory""" if len(self.bag) < 1: self.app.write("There is nothing to view here") else: for i in self.bag: self.app.write(i) self.app.write("Inventory space available " + str(len(self.bag)) + "/300") def dispose(self, item, app): """Dispose an item, param item_name""" try: for i in self.bag: if i == item: self.bag.remove(item) self.app.write('Successfully removed' + i) else: raise ValueError except ValueError: self.app.write("") def inputItem(self, item, app): """Collect item after battle""" #check if the bag is full if len(self.bag) > self.size: self.app.write("Your bag is full, this item cannot be inserted") self.app.write("Disposing the item...") else: self.bag.append(item)
e5ebc43703c0fa54cda0b5fdaa1a140684a919df
Sami-AlEsh/Sudoku-Solver
/Solver/fast_solve.py
5,058
3.515625
4
# written by Nathan Esau, Aug 2020 import copy def get_possible_values(board, row, col): possible_values = [1,2,3,4,5,6,7,8,9] tl_row = row - row % 3 tl_col = col - col % 3 for i in range(9): if len(board[row][i]) == 1: # entry already solved if board[row][i][0] in possible_values: possible_values.remove(board[row][i][0]) if len(board[i][col]) == 1: # entry already solved if board[i][col][0] in possible_values: possible_values.remove(board[i][col][0]) if len(board[tl_row+i//3][tl_col+i%3]) == 1: # entry already solved if board[tl_row+i//3][tl_col+i%3][0] in possible_values: possible_values.remove(board[tl_row+i//3][tl_col+i%3][0]) return possible_values def fill_missing_entries(board, box): row_start, row_end = (0,2) if box in [0,1,2] else (3,5) if box in [3,4,5] else (6,8) col_start, col_end = (0,2) if box in [0,3,6] else (3,5) if box in [1,4,7] else (6,8) for row in range(row_start, row_end + 1): for col in range(col_start, col_end + 1): if len(board[row][col]) == 1: # entry already solved continue board[row][col] = get_possible_values(board, row, col) def solve_missing_entries(board, box): row_start, row_end = (0,2) if box in [0,1,2] else (3,5) if box in [3,4,5] else (6,8) col_start, col_end = (0,2) if box in [0,3,6] else (3,5) if box in [1,4,7] else (6,8) possible_squares = dict((i, []) for i in range(1, 10, 1)) for row in range(row_start, row_end + 1): for col in range(col_start, col_end + 1): for e in board[row][col]: possible_squares[e].append((row, col)) for (k, v) in possible_squares.items(): if len(v) == 1: row, col = v[0] if len(board[row][col]) != 1: # solve entry board[row][col] = [k] def solve_strategy(board): for _ in range(25): # max_iter = 25 initial_board = copy.deepcopy(board) for box in range(9): fill_missing_entries(board, box) solve_missing_entries(board, box) if board == initial_board: return "stuck" solved = True for i in range(9): for j in range(9): if len(board[i][j]) == 0: return "failed" if len(board[i][j]) != 1: solved = False if solved: return "solved" def get_guess(board): solved_count = {} for i in range(9): # row i, col i, box i rc, cc, bc = 0, 0, 0 for j in range(9): if len(board[i][j]) == 1: rc += 1 if len(board[j][i]) == 1: cc += 1 if len(board[i//3*3 + j//3][i%3*3 + j%3]) == 1: bc += 1 if rc < 9: solved_count["r"+str(i)] = rc if cc < 9: solved_count["c"+str(i)] = cc if bc < 9: solved_count["b"+str(i)] = bc rcb = max(solved_count, key=solved_count.get) square = None options = None t, i = rcb[0], int(rcb[1]) for j in range(9): if t == 'r' and len(board[i][j]) > 1: square, options = [i,j], board[i][j] break if t == 'c' and len(board[j][i]) > 1: square, options = [j,i], board[j][i] break if t == 'b' and len(board[i//3*3+j//3][i%3*3+j%3]) > 1: square, options = [i//3*3+j//3, i%3*3+j%3], board[i//3*3+j//3][i%3*3+j%3] break return {"rcb": rcb, "square": square, "options": options} def apply_guess(board, guess, value): square = guess["square"] board[square[0]][square[1]] = [value] def solve(initial_board): # return solved board board = copy.deepcopy(initial_board) root = {"board":board,"parent":None,"child":None,"depth":0,"guess":None,"value":None} node = root while True: state = solve_strategy(board) if state == "solved": return board if state == "stuck": node["board"] = copy.deepcopy(board) node["child"] = {"board": board, "parent": node, "depth": root["depth"] + 1} node = node["child"] node["guess"] = get_guess(board) node["value"] = node["guess"]["options"][0] apply_guess(board, node["guess"], node["value"]) if state == "failed": # backtrack - change guess while len(node["guess"]["options"]) <= 1: node = node["parent"] board = copy.deepcopy(node["parent"]["board"]) node["board"] = copy.deepcopy(board) node["guess"]["options"] = node["guess"]["options"][1:] node["value"] = node["guess"]["options"][0] apply_guess(board, node["guess"], node["value"]) def print_board(board): for i in range(9): for j in range(9): if len(board[i][j]) == 1: print(board[i][j][0], end= " ") else: print("X", end=" ") print("")
4f1406893d411044dfcc19054483be5693419bc5
atshaman/SF_FPW
/C1/T191/figures.py
1,208
4.09375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """Описание классов геометрических фигур в рамках учебного задания 1.9.1""" import math class Rectangle: def __init__(self, width, height): self.width = width self.height = height @property def width(self): return self._width @width.setter def width(self, value): if isinstance(value, int) and value > 0: self._width = value else: raise ValueError('Ширина должна быть целым положительным числом!') @property def height(self): return self._height @height.setter def height(self, value): if isinstance(value, int) and value > 0: self._height = value else: raise ValueError('Высота должна быть целым положительным числом!') def get_area(self): return self._width * self._height class Square(Rectangle): def __init__(self, side): self.width = self.height = side class Circle(Square): def get_area(self): return self._width ** 2 * math.pi
1f6b68866dc8e31c50294b16b27645a468a72341
mohammadzainabbas/AI-Decision-Support-Systems
/Lab 02/Tree (2).py
399
3.53125
4
class Tree(): def __init__(self): self.left = None self.right = None self.data = None root = Tree() root.data = "root" root.left = Tree() root.left.data = "left" root.right = Tree() root.right.data = "right" root.left.left = Tree() root.left.left.data = "left left" root.left.right = Tree() root.left.right.data = "left-right" print(root.left.left.data)
e6a7ed26ea39b14e337cfdcf969829df9803dbaf
mohammadzainabbas/AI-Decision-Support-Systems
/Lab 05/Task_2.1 Tree Structure.py
1,128
3.8125
4
class Tree(): def __init__(self, val): self.data = val self.left = None self.right = None def PreOrder(self, root): if root: print(root.data) self.PreOrder(root.left) self.PreOrder(root.right) def PreOrderList(self, root, list): if root: list.append(root.data) self.PreOrder(root.left, list) self.PreOrder(root.right, list) else: return list def InOrder(self, root): if root: self.InOrder(root.left) print(root.data) self.InOrder(root.right) def PostOrder(self, root): if root: self.PostOrder(root.left) self.PostOrder(root.right) print(root.data) root = Tree(1) root.left = Tree(2) root.right = Tree(3) root.left.left = Tree(4) root.left.right = Tree(5) root.left.left.left = Tree(6) root.left.right.left = Tree(7) root.left.right.right = Tree(8) print('Pre Order') root.PreOrder(root) print('In Order') root.InOrder(root) print('Post Order') root.PostOrder(root)
34517c82223ec7e295f5139488687615eef77d56
devineni-nani/Nani_python_lerning
/Takung input/input.py
1,162
4.375
4
'''This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python.''' #input() use roll_num= input("enter your roll number:") print (roll_num) ''' How the input function works in Python : When input() function executes program flow will be stopped until the user has given an input. The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional. Whatever you enter as input, input function convert it into a string. if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting. for example: ''' num=input("enter an number:") print (num) name = input ("enter your name:") print (name) #Printing type of input value print ("type of num", type(num)) print ("type of name:", type(name)) num1=type(num) print ("after typecasting num type:", type(num1))
43a9b64fb9048e9556066a8afe3b738d28d3d96a
devineni-nani/Nani_python_lerning
/Data Types/data_type.py
167
4.3125
4
'''Getting the Data Type You can get the data type of any object by using the type() function: Example Print the data type of the variable x:''' x = 5 print(type(x))
99af00d1ed58d0acd6873db13ebe0d1bec920812
mpaluta/Ant-Colony-Optimization
/devices/device.py
857
3.5
4
import numpy as np import random # Define class for type 1 devices class Device: # Initialize class object with power level, duration of required power usage, time at which # task was assigned, window over which task must be completed, and time step for analysis def __init__(self, powerLevel, duration, step = 60): self.powerLevel = powerLevel self.duration = duration # In units of time steps self.step = step self.pred = None self.succ = None self.LS = None self.ES = None self.LF = None self.EF = None self.start = None self.finish = None self.index = None # Method to set start time for when object will begin using power def setStart(self, time): self.start = time # Returns true if device is currently using power def status(self, time): return time > self.start and time < self.start + self.duration
a33aab465be9a23389d4750218b42021b3aebcb4
LoboAnimae/Computer-Graphics
/Lab_2.5_Filling_Polygon/lib/contourcounter.py
738
3.609375
4
def greatercounter(contourp:list, point:list, index:int): """Allows to know the number of points in front of the given point. Args: contourp (list): List of all the points point (list): X-Y-Values array of a singular point index (int): 0 if working on X. 1 if working on Y. Returns: int: How many are behind, how many are in front """ cless = set() cmore = set() ops = 0 if index == 1 else 1 for cpoint in contourp: if cpoint[ops] == point[ops]: if cpoint[index] < point[index]: cless.add(cpoint[index]) if cpoint[index] > point[index]: cmore.add(cpoint[index]) return len(cless), len(cmore)
1d4acda0c046f66dc43f33c3f57b623112815811
Rashid2410/test2
/task_j.py
455
3.875
4
class Things: color = "red" def __init__(self,n,t): self.namething = n self.total = t th1 = Things("table", 5) th2 = Things("computer", 7) print (th1.namething,th1.total) # Вывод: table 5 print (th2.namething,th2.total) # Вывод: computer 7 th1.color = "green" # новое свойство объекта th1 print (th1.color) # Вывод: green print (th2.color) # ОШИБКА: у объекта th2 нет свойства color!
1f96007044613e93a28ccf7937af87536698ef09
albert-cheung/Automation-Projects
/Autosys_Automation_Project/copy_file.py
1,102
3.5
4
#Purpose of this query is to take a large number of queries and parse them out into digestable chunks. lines = [] #Strips a list of customer_ids pasted individually on the .txt file with open("customer_ids.txt") as file: for line in file: line = line.strip() lines.append("'" + line + "'") lines_length = len(lines) #Adds bracket to the string def addBracket(string): return ('(' + string + ')'); # Turns list array into a string myString = ",".join(lines); #Function halflist will add queries into a SQL Query if there are less than 500 queries in the "in" parameter. #Otherwise it will continue to divide the list in half and run the queries again. def halflist(list): list_length = len(list) if (list_length < 500): myString = ",".join(list) mySQLQuery = "select * from TABLE where COLUMN in (QUERY);" myQueries = addBracket(myString) myFinalQuery = mySQLQuery.replace("QUERY", str(myString), 1) print(myFinalQuery) else: half = len(list)//2 return halflist(list[:half]), halflist(list[half:])
463fbd192d59cb8c75c7c69839be80c168ec43fb
Dragonriser/DSA_Practice
/Dynamic Programming/IntelligentGirl.py
517
3.828125
4
#QUESTION: Given a string of integers, find the number of even integers present from each index to the very end. Example: Input: 574674546476 Output: 7 7 7 6 5 5 4 4 3 2 1 1 #CODE: def findCount(s): dp = [0]*len(s) if int(s[0]) % 2 == 0: dp[-1] = 1 for i in range(len(s) - 2, -1, -1): if int(s[0]) % 2 == 0: dp[i] = dp[i + 1] + 1 else: dp[i] = dp[i + 1] return dp s = input() arr = findCount(s) for i in arr: print(i, end="", sep=" ")