blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
55f9b147c48411aae4b6b1609568e459fafdef7b
BrindaSahoo2020/Python-Programs
/Basic_Programs/Average.py
274
4.1875
4
#Calculate the average of numbers in a list lst = [] for i in range(1,20,5): lst.append(i) print(lst) l = len(lst) total = 0 for i in lst: total = total+i print(total) avg = float(total/l) print("Average of the list is ",avg) #Output (Average of the list is 8.5)
9542708331bf8413e0bebd9feca926c04493afb3
ziv1989/my-isc-work-1
/python_work/python_string3.py
327
4.09375
4
#!/bin/env python #3rd exercise from ncas-isc about python strings something="Completely Different" #Counts the number of appearences of 't' something.count('t') #Split the string by the given character split_string=something.split('e') #replace an entire section of the string thing2=something.replace('Different','Silly')
f1b1770e67a5b71e501d89841df6a303dbdf97f1
rkeisling/gladiator_code
/glad_game.py
2,978
4.125
4
from gladiator import Gladiator import random import time names = ['Maximus', 'Brutus', 'Romulus', 'Remus', 'Aurelius', 'Vulpes'] weapons = ['Spear', 'Sword', 'Knife', 'Mace'] def main(): print(""" Welcome to the colloseum! Here you will command your champion to fight to the death against a gladiator of an opposing nation. You may choose your champion's name, weapon, and decide what he is to do during the fight. Begging for mercy and fleeing are signs of cowardice. Begin! """) begin = input("What is your champion's name? ").strip().lower().capitalize() weapon = input(""" Choose your champion's weapon: Spear (7-11 damage) Sword (4-13 damage) Knife (4-7 damage) Mace (9 damage) Fists (The Weapons of Real Men) (2-4 damage) Enter your choice: """).strip().lower().capitalize() if weapon == "Spear": print("Pointy and stabby. Nice!") low = 7 high = 11 elif weapon == "Sword": print("Boring and original. Fantastic.") low = 4 high = 13 elif weapon == "Knife": print("... I mean, if that's what you want.") low = 4 high = 7 elif weapon == "Mace": print("Who needs a sharp edge, huh?") low = 9 high = 10 elif weapon == "Fists": print("You are a brave soul.") low = 2 high = 4 else: print("Not an option!") begin = Gladiator(begin, 100, 0, low, high) name = names[random.randint(0, 5)] opp_weapon = weapons[random.randint(0, 3)] print("Your champion's opponent will be {0}. He will wield a {1}.".format( name, opp_weapon)) if opp_weapon == "Spear": opp_low = 7 opp_high = 11 elif opp_weapon == "Sword": opp_low = 4 opp_high = 13 elif opp_weapon == "Knife": opp_low = 4 opp_high = 7 elif opp_weapon == "Mace": opp_low = 9 opp_high = 10 name = Gladiator(name, 100, 0, opp_low, opp_high) while True: dead_check = begin.isDead(name) if dead_check == 1: print("You have have perished in the fighting pits at the hands of {0}!".format( name.name)) break elif dead_check == 2: print("You have slain {0} and arise a champion!".format(name.name)) break time.sleep(1) choice = input(""" What would you like your champion to do? - Attack - Heal - Beg - Flee """).strip().lower().capitalize() if choice == "Attack": print(begin.attack(name)) elif choice == "Heal": print(begin.heal()) elif choice == "Beg": print(begin.beg()) break elif choice == "Flee": print("You are stabbed in the back and die as you flee.") break print(name.attack(begin)) if __name__ == '__main__': main()
e98829fb451ad3669b2fbca35afee69dfc74065d
norbour/leetcode
/src/reverse-words-in-a-string.py
1,086
3.5625
4
class Solution: # @param s, a string # @return a string def reverse(self, s, st, ed): if s == None or st > ed: return None if st == ed: return s[st] return s[st:ed][::-1] def clear(self, s): st = 0 ed = len(s) - 1 while st < len(s) and s[st] == " ": st = st + 1 while ed > -1 and s[ed] == " ": ed = ed - 1 if st > ed: return "" return s[st:ed + 1] def reverseWords(self, s): if s == None: return None s = self.clear(s) length = len(s) if length == 0: return "" result = "" st = 0 ed = 0 while not st == length: if s[st] == " ": st = st + 1 ed = ed + 1 elif ed == length or s[ed] == " ": result = result + self.reverse(s, st, ed) + " " st = ed else: ed = ed + 1 return self.reverse(result, 0, len(result) - 1)
b25490a77e00539954ca80240770688cdedf4060
RajaSekar1311/Data-Science-and-Visualization-KITS
/Data Frame & Load Excel File/LoadExcelDataIntoPandasDataFrame.py
791
3.6875
4
import pandas myFileName = 'Session2-KITS-Guntur-DataSet.xls' #with is a context manager here # group of instructions will be exexuted in a particular context #In pandas there is a method called as ExcelFile() #ExcelFile() method opens a excel file #With opening the file in read mode perform lines 11 to 15 with pandas.ExcelFile(myFileName) as myExcelFileReadObject: #invoke the read_excel method from pandas library with the file read object and the name of the sheet in the excel workbook myDataFrame1 = pandas.read_excel(myExcelFileReadObject,'Sem1-Marks') myDataFrame2 = pandas.read_excel(myExcelFileReadObject,'Sem2-Marks') print(myDataFrame1) print(myDataFrame2) #if more values are there in the dataframe, only the first and last 5 records
31debebcd11797b8f7f914f17fbf32dc2dcac577
kkaixiao/pythonalgo2
/leet_0219_contains_duplicate_II.py
1,037
3.796875
4
''' Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Example 3: Input: nums = [1,2,3,1,2,3], k = 2 Output: false ''' def contains_duplicate_ii1(nums, k): if len(set(nums)) == len(nums): return False for i in range(len(nums)-1): if nums[i] in nums[i + 1:i + 1 + k]: return True return False def contains_duplicate_ii2(nums, k): mdict = {} for index, value in enumerate(nums): if (value in mdict) and (index - mdict[value] <= k): return True mdict[value] = index return False # nums1 = [1,2,3,1] # should return True # k1 = 3 # # nums1 = [1,2,3,4,5,6,7,8,9,9] # should return True # k1 = 3 nums1 = [13,23,1,2,3] # should return False k1 = 5 print(contains_duplicate_ii2(nums1, k1))
3a53ac8b43bc18398e9902466ce2994b031dcf6f
FilipVidovic763/vjezba
/predavanje6.py/skrivanje.py
243
3.546875
4
class Brojac: __brojac = 0 def broji(self): self._tekst = 'dodajem +1' self.__brojac += 1 print(self.__brojac) brojac = Brojac() brojac.broji() brojac.broji() print(brojac._tekst) print(brojac.__brojac)
ae2ae6f309cc59191a36fd5450687a78cc70c36c
vkvasu25/leetcode
/linked_list/leetcode_ll_implementation.py
4,100
4.15625
4
class Node(object): def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def getValue(self): return self.value def getNextNode(self): return self.next_node def setValue(self, value): self.value = value def setNextNode(self, next_node): self.next_node = next_node class MyLinkedList(object): def __init__(self, value=None): """ Initialize your data structure here. """ self.head_node = Node(value) def get(self, index): """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int """ # print('starting searching for index: ', index) current = self.head_node # print(current.getValue()) localIndex = 0 while current: if localIndex == index: return current else: localIndex +=1 current = current.getNextNode() return current def print_list(self): represent = 'Here is our list: \n' current = self.head_node index = 0 while current: represent += current.getValue() + ' index:' + str(index) + ' --> ' index += 1 current = current.getNextNode() return represent def addAtHead(self, val): """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. :type val: string :rtype: None """ current = Node(val) current.next_node = self.head_node self.head_node = current def addAtTail(self, val): """ Append a node of value val to the last element of the linked list. :type val: int :rtype: None """ last_node = Node(val) current = self.head_node while current.next_node: current = current.next_node current.setNextNode(last_node) def addAtIndex(self, index, val): """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. :type index: int :type val: int :rtype: None """ node_to_insert = Node(val) prev = self.head_node current = prev.getNextNode() start_index = 0 while current: if start_index == index: print('got here') prev.setNextNode(node_to_insert) node_to_insert.setNextNode(current) break else: start_index +=1 prev = prev.getNextNode() current = current.getNextNode() def deleteAtIndex(self, index): """ Delete the index-th node in the linked list, if the index is valid. :type index: int :rtype: None """ print('starting deletion on index: ', index) prev = self.get(index-1) current = self.get(index) next = current.getNextNode() prev.setNextNode(next) # Your MyLinkedList object will be instantiated and called as such: obj = MyLinkedList('first element') # print(obj.head_node.getValue()) # print(obj.get(0).getValue()) obj.addAtHead("second element") obj.addAtHead("third element") obj.addAtHead("fourth element") # print(obj.print_list()) # print(obj.head_node.getValue()) # print(obj.get(1).getValue()) obj.addAtTail('Last element') obj.addAtTail('one more Last element') print(obj.print_list()) # print(obj.get(2).getValue()) # print(obj.print_list()) # obj.addAtIndex(0,'New value inserted') # print(obj.print_list()) obj.deleteAtIndex(2) print(obj.print_list()) # param_1 = obj.get(index) # obj.addAtHead(val) # obj.addAtTail(val) # obj.addAtIndex(index,val) # obj.deleteAtIndex(index)
0896f2ddf92640c57d1bbd678444d12f448debc6
Vaibhavnath-Jha/Hangman-Game
/main.py
2,661
3.84375
4
import os import game import time from Winner import winner class Player: def __init__(self, name, score): self.name = name self.score = score def display(self): print("{:12}{:12d}\n".format(self.name,self.score)) def rules(): #11 print("\n\t\t\t\t-:GAME RULES:-") print("1. You will have 7 tries.\n2. You'll get 1 hint after 3rd try.") print("3. If you decide to enter FULL-NAME of the movie, enter as it is. An incorrect guess here means you're OUT") print("4. You have to press enter after you make a guess.") input('\n\n------------------------------------Press Enter to continue!------------------------------------') os.system('clear') def player_details(): print("\t\tChoose Number of Players") print("1) One Player\t\t\t\t3) Three Players") print("\n2) Two Players\t\t\t\t4) Four Players") num_of_players = int(input("\nEnter your choice: ")) names = ["name_" + str(i) for i in range(num_of_players)] while True: for i in range(num_of_players): names[i] = str(input("\nEnter Player "+str((i+1))+" Name: ")) os.system('clear') print("\nParticipating Players: ") for i in range(num_of_players): print("\n", names[i]) if str(input("\nDo you want to change anything?(Y/N): ")).upper() == "N": break else: os.system('clear') return num_of_players,names def initialize_player(num_of_players, names): player = ['p1','p2','p3','p4'] for i in range(num_of_players): # Initialization player[i] = Player(names[i], 0) return player def start_game(player,num_of_players,names): os.system('clear') rounds = int(input("\nEnter how many rounds you want to play?: ")) os.system('clear') for round_num in range(rounds): for i in range(num_of_players): print("\t-|Round {} Begin|-\n".format(round_num+1)) print("{}'s turn!\n".format(player[i].name)) player[i].score += game.hangman() #Call to the actual game game.counter = True game.exit_token = False time.sleep(3) os.system('clear') print("\n\nScores after round {} are:\n".format(round_num+1)) print("{:12}{:>12}".format("Player","Score")) for i in range(num_of_players): player[i].display() time.sleep(3) os.system('clear') print("\tFinal Score!\n") print("{:12}{:>12}".format("Player","Score")) for i in range(num_of_players): player[i].display() final_score = [] for i in range(num_of_players): final_score.append(player[i].score) winner(final_score, player) print("\n\n\t!Thanks for playing!\n") def main(): rules() num_of_players, names = player_details() player = initialize_player(num_of_players, names) start_game(player, num_of_players, names) if __name__ == '__main__': main()
afb127dab864edc82e04105dfbb49a58ee23d53b
tashbekova/neobis
/hackerrank/alphabet rangli.py
231
3.609375
4
N = map(int(input())) a = input("input character") b = input("input character") for i in range(1,N,2): print((a * (i)).center(N, "-")) print(a.center(N, "-")) for i in range(N-2,-1,-2): print(("b" * (i)).center(N, "-"))
5c659f1c45966745726caaff6361d2f659e659db
superyang713/pcookbook
/03_numbers_dates_and_times/12_convert_days_to_seconds_and_other_basic_time.py
792
4.125
4
""" Problem: You have code that needs to perform simple time conversions, liek days to seconds, hours to minutes, and so on. Solution: Use datatime module. """ from datetime import timedelta from datetime import datetime # Example 1: perform conversions and arithmetic involving different units of # time, use the datetiem module. a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a + b print(c.days) print(c.seconds) print(c.total_seconds() / 3600) # Example 2: represent specific dates and times, create datetime instances # and use the standard mathematical operations to manipulate them. a = datetime(2012, 9, 23) print(a + timedelta(days=10)) b = datetime(2012, 12, 21) d = b - a print(d.days) now = datetime.today() print(now.date()) print(now + timedelta(minutes=10))
a8730900420fca55bceac74513aa53c5465028f0
arhandreu/OOP
/OOP.py
5,156
3.765625
4
def average_grade(grad, course="all"): all_grades = [] if course == "all": for grade in grad.values(): all_grades += grade return sum(all_grades) / len(all_grades) else: return sum(grad[course]) / len(grad[course]) def average_grad_all(course, *units): sum_aver_grades = 0 count_unit = 0 for unit in units: sum_aver_grades += average_grade(unit.grades, course) count_unit += 1 return sum_aver_grades / count_unit class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = [] self.courses_in_progress = [] self.grades = {} def add_courses(self, course_name): self.courses_in_progress.append(course_name) def rate_lector(self, lector, course, grade): if isinstance(lector, Lecturer) and course in lector.courses_attached and course in self.courses_in_progress: if course in lector.grades: lector.grades[course] += [grade] else: lector.grades[course] = [grade] else: return 'Ошибка' def __str__(self): return f'Имя: {self.name} \nФамилия: {self.surname}\n' \ f'Средняя оценка за домашние задания: {average_grade(self.grades)} \n' \ f'Курсы в процессе изучения: {", ".join(self.courses_in_progress)} \n' \ f'Завершенные курсы: {", ".join(self.finished_courses)} \n' def __lt__(self, other): if not isinstance(other, Student): print("Это не студент!") return return average_grade(self.grades) > average_grade(other.grades) class Mentor: def __init__(self, name, surname): self.name = name self.surname = surname self.courses_attached = [] def add_courses(self, course_name): self.courses_attached.append(course_name) class Lecturer(Mentor): def __init__(self, name, surname): super().__init__(name, surname) self.grades = {} def __str__(self): return f'Имя: {self.name} \nФамилия: {self.surname} \nСредняя оценка за лекции: {average_grade(self.grades)}\n' def __lt__(self, other): if not isinstance(other, Lecturer): print("Это не лектор!") return return average_grade(self.grades) < average_grade(other.grades) class Reviewer(Mentor): def rate_hw(self, student, course, grade): if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress: if course in student.grades: student.grades[course] += [grade] else: student.grades[course] = [grade] else: return 'Ошибка' def __str__(self): return f'Имя: {self.name} \nФамилия: {self.surname}\n' student_1 = Student('Andrey', 'Bardukov', 'Men') student_1.courses_in_progress += ['Biology', 'History', 'Physics'] student_1.add_courses('Music') student_2 = Student('Sergei', 'Morozov', 'Men') student_2.courses_in_progress += ['History', 'Physics', 'Biology', 'Music'] review_1 = Reviewer('Review', '_1') review_1.add_courses('History') review_1.add_courses('Physics') review_2 = Reviewer('Review', '_2') review_2.add_courses('Music') review_2.add_courses('Biology') lector_1 = Lecturer('Lector', '_1') lector_1.add_courses('Music') lector_1.add_courses('Biology') lector_1.add_courses('History') lector_1.add_courses('Physics') lector_2 = Lecturer('Lector', '_2') lector_2.add_courses('History') lector_2.add_courses('Physics') lector_2.add_courses('Music') lector_2.add_courses('Biology') student_1.rate_lector(lector_1, 'Music', 8) student_1.rate_lector(lector_2, 'History', 5) student_2.rate_lector(lector_2, 'Physics', 4) student_2.rate_lector(lector_1, 'Biology', 2) student_1.rate_lector(lector_1, 'Music', 2) student_1.rate_lector(lector_2, 'History', 3) student_2.rate_lector(lector_2, 'Physics', 5) student_2.rate_lector(lector_1, 'Biology', 7) student_1.rate_lector(lector_2, 'Music', 4) student_1.rate_lector(lector_1, 'History', 5) student_2.rate_lector(lector_1, 'Physics', 4) student_2.rate_lector(lector_2, 'Biology', 2) student_1.rate_lector(lector_2, 'Music', 2) student_1.rate_lector(lector_1, 'History', 3) student_2.rate_lector(lector_1, 'Physics', 5) student_2.rate_lector(lector_2, 'Biology', 7) review_2.rate_hw(student_1, 'Music', 5) review_1.rate_hw(student_1, 'History', 4) review_1.rate_hw(student_1, 'Physics', 7) review_2.rate_hw(student_1, 'Biology', 9) review_2.rate_hw(student_2, 'Music', 8) review_1.rate_hw(student_2, 'History', 7) review_1.rate_hw(student_2, 'Physics', 6) review_2.rate_hw(student_2, 'Biology', 10) print(review_2) print(student_2) print(lector_1) print(lector_2) print(lector_1 > lector_2) print(average_grad_all('History', student_2, student_1)) print(average_grad_all('Biology', lector_1, lector_2))
f44452d5bd4673542147e977c71a18b90b09c0b5
sethyeboah/RaspberryPi
/HelloWorld.py
122
3.765625
4
x = input("Print welcome? (y|n): ") if x == 'y': print("Hello World") elif x == 'n': print("Exiting..") exit()
dde1fe08ccd7c0a1d2f8346dd70b1d3b8902f7d3
gdoorenbos/twister-spinner
/twister.py
375
3.625
4
from itertools import product from random import randint colors = ["blue", "green", "yellow", "red"] sides = ["right", "left"] appendages = ["hand", "foot"] options = [sides, appendages, colors] options = [' '.join(i) for i in product(*options)] while True: opt_ind = randint(0, len(options)-1) print('{}: {}'.format(opt_ind, options[opt_ind]), end='') input()
b99bfd32461e006ca23ba132a25c17bab08f0275
destinyplan/ZenCloud2
/homework/d20180802_6.py
124
3.84375
4
str1 = "jintianquweinanle !!!" str2 = "tian"; print (str1.find(str2)) print (str1.find(str2, 3)) print (str1.find(str2, 19))
47b95e3dbbd2542e1485a52ae0917dcad9791f9d
Tyzeppelin/Project-Euler
/problem34/problem34.py
785
3.5625
4
def tailFacto(n, r): if n == 0: return r else : return tailFacto(n-1, r*n) def factorial (n): if n == -1: return 0 return tailFacto(n, 1) def cond (a): num = int(''.join(map(str,a))) res = 0 for e in a: res += factorial(e) return num == res def formula (l): l.reverse() exp = 0 res = 0 for e in l: res += (10**exp)*e exp += 1 if __name__ == "__main__": #print factorial(500) a = 0 b = 0 c = 0 d = 1 res = 0 # for e in range -> split -> factorial -> bam # I iterate only until 100000. for e in range (1000000)[3:]: num = [int(i) for i in str(e)] if cond(num): #print 'yata -> ', e res += e print res
e7c8c380169809aeddba540325bf49aeb4a55425
Mart1nDimtrov/DoingMathPython
/03. Describing Data with Statistics/read_search_correlation.py
1,356
3.59375
4
import csv import matplotlib.pyplot as plt def find_corr_x_y(x, y): n = len(x) # Find the sum of the products prod = [] for xi,yi in zip(x,y): prod.append(xi*yi) sum_prod_x_y = sum(prod) sum_x = sum(x) sum_y = sum(y) squared_sum_x = sum_x**2 squared_sum_y = sum_y**2 x_square = [] for xi in x: x_square.append(xi**2) # Find the sum_x x_square_sum = sum(x_square) y_square=[] for yi in y: y_square.append(yi**2) # Find the sum y_square_sum = sum(y_square) # Use the formula to calculate correlation numerator = n*sum_prod_x_y - sum_x*sum_y denominator_term1 = n*x_square_sum - squared_sum_x denominator_term2 = n*y_square_sum - squared_sum_y denominator = (denominator_term1*denominator_term2)**0.5 correlation = numerator / denominator return correlation def scatter_plot(x, y): plt.scatter(x, y) plt.xlabel('Number') plt.ylabel('Square') plt.show() def read_csv(filename): with open(filename) as f: reader = csv.reader(f) next(reader) summer = [] highest_correlated = [] for row in reader: summer.append(float(row[1])) highest_correlated.append(float(row[2])) return highest_correlated summer, highest_correlated = read_csv('correlate-summer.csv') corr = find_corr_x_y(summer, highest_correlated) print('Highest correlation: {0}'.format(corr)) scatter_plot(summer, highest_correlated)
b4a6846edd71a5148c815413785ee0bb9e3fcad4
dav-ell/looptimer
/timing.py
2,313
4.09375
4
import time import types def timing(iterable, every_n=None, every_fraction=None): """Wraps your iterables to give you automatic timing! Want to time this loop? for i in arr: # do things Just write, instead: for i in timing(arr): # do things Et voilà! Your loop is timed! Args: iterable: the thing you're iterating over every_n: an integer saying after how many elements N you'd like to get timing information every_fraction: a float (0 <= x <= 1) saying at what fraction progress through the iterable you'd like timing information. Note: if this argument is specified, the iterable must support the len() operation. """ if every_fraction != None and isinstance(iterable, types.GeneratorType): raise ValueError("Generators and every_fraction timing reports are not possible.") start_time = time.time() times = [] for i, item in enumerate(iterable): start_iter_time = time.time() # The magic line: using a generator lets us run this loop in parallel to the timed loop yield item # Execution returns to this loop when the next element is asked for (i.e. when the timed # loop finishes the iteration) end_iter_time = time.time() total_iter_time = end_iter_time - start_iter_time times.append(total_iter_time) # Print according to arguments do_print = False if every_fraction != None and i % int(len(iterable) * every_fraction) == 0: do_print = True if every_n != None and i % every_n == 0: do_print = True if every_n == None and every_fraction == None: do_print = True if do_print: print("Iteration {0} took {1:.4f}s".format(i, total_iter_time)) end_time = time.time() # Print out statistics total_time = end_time - start_time print("Total runtime: {0:.4f}s".format(total_time)) avg_time = sum(times) / len(times) print("Average runtime per loop: {0:.4f}s".format(avg_time)) min_time = min(times) print("Shortest loop: {0:.4f}s".format(min_time)) max_time = max(times) print("Longest loop: {0:.4f}s".format(max_time))
23fcb4b58a4f3b2580ca5e3015b6b5c72caccba0
luyisimiger/proyecto_sensores
/sensores/client/python_cli/visualize.py
1,300
3.640625
4
def matplotlib_demo(): # Import the necessary packages and modules import matplotlib.pyplot as plt import numpy as np # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') # Add a legend plt.legend() # Show the plot plt.show() def matplotlib_demo2(): import numpy as np import matplotlib.pyplot as plt plt.axis([0, 10, 0, 1]) for i in range(10): y = np.random.random() plt.scatter(i, y) plt.pause(0.1) plt.show() def matplotlib_demo3(): import pylab import time import random import matplotlib.pyplot as plt dat=[0,1] fig = plt.figure() ax = fig.add_subplot(111) Ln, = ax.plot(dat) ax.set_xlim([0,20]) plt.ion() plt.show() for i in range (180): dat.append(random.uniform(0,1)) Ln.set_ydata(dat) Ln.set_xdata(range(len(dat))) plt.pause(0.3) print('done with loop') def pandas_demo(): import pandas as pd iris = pd.read_csv('iris.data', names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']) print(iris.head()) if __name__ == "__main__": # matplotlib_demo() # matplotlib_demo2() matplotlib_demo3() # pandas_demo()
cc462edda955fbc158aa5b6c6f8824ded31864bd
valies/AoC2020
/Day5/seat.py
1,092
3.578125
4
class FileReader(): @classmethod def read_file(cls, file): a = [] with open(file) as my_file: for line in my_file: a.append(line.rstrip()) return a class SeatFinder(): @classmethod def find_available_seat(cls, lines): occupied_seats = [] for line in lines: occupied_seats.append(SeatFinder.get_occupied_seat(line)) min_seat = min(occupied_seats) max_seat = max(occupied_seats) print(max_seat) for seat in range(min_seat, max_seat): if min_seat < seat < max_seat and not(seat in occupied_seats) and seat - 1 in occupied_seats and seat + 1 in occupied_seats: return seat raise Exception("No seat found.") @classmethod def get_occupied_seat(cls, line): line = line.replace("F", "0").replace("B", "1").replace("L", "0").replace("R", "1") return int(line, 2) if __name__ == '__main__': lines = FileReader.read_file("seat/input.txt") seat = SeatFinder.find_available_seat(lines) print(seat)
c6b3f0883ba5c1ed8aff9e3d80a4ace179b110f4
lazyp/pycommon
/logger.py
1,689
3.546875
4
#-*- coding:utf-8 -*- import time class Logger: DEBUG = "DEBUG" INFO = "INFO" ERROR = "ERROR" Level = INFO def print_out(self ,level , msg): localtime = time.localtime() y = localtime.tm_year mon = localtime.tm_mon d = localtime.tm_mday h = localtime.tm_hour m = localtime.tm_min s = localtime.tm_sec if int(mon) < 10: mon = "0"+str(mon) if int(d) < 10: d = "0"+str(d) if int(h) < 10: h = "0"+ str(h) if int(m) < 10: m = "0"+ str(m) if int(s) < 10: s = "0"+ str(s) fmt_time = "%s-%s-%s %s:%s:%s" % (y , mon , d , h , m , s) log = "%s %s %s" %(fmt_time , level , msg) print log def info(self , msg): if Logger.Level == Logger.INFO or Logger.Level == Logger.DEBUG: self.print_out(Logger.INFO , msg) def debug(self , msg): if Logger.Level == Logger.DEBUG: self.print_out(Logger.DEBUG , msg) def error(self , msg): if Logger.Level == Logger.ERROR \ or Logger.Level == Logger.DEBUG or Logger.Level == Logger.INFO: self.print_out(Logger.ERROR , msg) if __name__ == "__main__": print "Logger.Level=%s " % Logger.Level logger = Logger() logger.info("test print log")
6f75c85f3d163369daefbfcd231e63b1431b62fe
msaei/coding
/LeetCode/Top Interview Questions/Arrays and Strings/Group Anagrams.py
461
3.875
4
#Group Anagrams #https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/778/ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for word in strs: key = ''.join(sorted(word)) if key in anagrams.keys(): anagrams[key].append(word) else: anagrams[key] = [word] return anagrams.values()
d01089406fd65e71a5202687600e157400d729b5
apoorvkk/LeetCodeSolutions
/problems/301_remove_invalid_brackets.py
1,330
3.8125
4
''' URL: https://leetcode.com/problems/remove-invalid-parentheses Time complexity: O(2^n) Space complexity: O(n!) ''' from collections import deque class Solution(object): def is_valid(self, s): open = 0 for char in s: if char == "(": open += 1 elif char == ")": if open == 0: return False open -= 1 return open == 0 def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ queue = deque() visited = set() queue.append(s) visited.add(s) valid_brackets = [] found = False while len(queue) > 0: new_text = queue.popleft() if self.is_valid(new_text): valid_brackets.append(new_text) found = True if not found: for i in range(len(new_text)): if new_text[i] not in ("(", ")"): continue removed_bracket_text = new_text[:i] + new_text[i+1:] if removed_bracket_text not in visited: visited.add(removed_bracket_text) queue.append(removed_bracket_text) return valid_brackets
1420aaf0ba7cbba11f56f5de9da2cd18240ebc54
syedasifuddin/CS61A
/assignment/bathtub.py
465
3.53125
4
def bathtub(n): def ducky_annihilator(rate): def ducky(): nonlocal n nonlocal rate n = n - rate return n return ducky return ducky_annihilator def weird_gen(x): if x % 2 == 0: yield x * 2 else: yield x yield from weird_gen(x - 1) def greeter(x): while x % 2 != 0: yield 'hello!' yield x print('goodbye!')
bbb3014f75b85cf2521a5862c5522476d6d15772
davis-mwangi/python-data-structures
/classess_and_objects.py
795
4.21875
4
class MyClass: x = 5 # object p1 = MyClass() print(p1.x) class Person: def __init__(self,name,age): """ This is executed when a class is initiated """ self.name = name self.age = age def myfunc(self): print("Hello my name is "+ self.name) p1 = Person("John", 26) print(p1.name) print(p1.age) p1.myfunc() """ The `self` parameter is a reference to the current instance of the class, and is used to access variables that belong to that class. It does ntot have to be name self but has to the first parametr of any function. """ # Modify Object properties p1.age = 40 print(p1.age) #Delete object properties del p1.age # print(p1.age) # Pass statement class Person2: pass # Delete objects # del p1 print(p1)
f5073f2b369cb6d4db041232019a2148ed965a8f
dev-arthur-g20r/how-to-code-together-using-python
/How to Code Together using Python/PYC/absolutevalue.py
337
3.984375
4
import os class AbsoluteValue: def __init__(self,n): self.n = n def absValue(self): if (self.n < 0): abs = self.n * -1 else: abs = self.n return "Absolute value: {}".format(abs) number = float(input("Number to check its absolute value: ")) x = AbsoluteValue(number) result = x.absValue() print(result) os.system("pause")
953549d0476251f189e7d3596d6700167a91b261
salvadorraymund/Python
/Standard Library/efficient_array.py
221
3.703125
4
from array import array """i at the beginning means you are going to use integer data type""" arr1 = array('i', [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) print(arr1) arr2 = array('i', [elem * 2 for elem in arr1]) print(arr2)
b1cbb8c5802b8bb2610a9e6a1b382b2affa6a074
daniel-reich/turbo-robot
/RvZfGXR3TQHjLy7mN_16.py
787
4.125
4
""" Write the **regular expression** that matches all street addresses. All street addresses begin with a number. Use the character class `\d` in your expression. ### Example txt = "123 Redding Dr. 1560 Knoxville Ave. 3030 Norwalk Dr. 5 South St." pattern = "yourregularexpressionhere" (re.findall(pattern, txt)) ➞ ["123 Redding Dr.", "1560 Knoxville Ave.", "3030 Norwalk Dr.", "5 South St."] ### Notes * You don't need to write a function, just the pattern. * Do **not** remove `import re` from the code. * Find more info on RegEx and character classes in **Resources**. * You can find all the challenges of this series in my [Basic RegEx](https://edabit.com/collection/8PEq2azWDtAZWPFe2) collection. """ import re ​ pattern = '\d+\s\w+\s\w+\.?'
7199d9d5b3d361e52afeec4ba5c3a705b7802063
MerveillesKoina/Python2020
/GUI/TextBoxExample.py
366
3.65625
4
################################### #June2020 #LearnToCode #Author: Merveille Koina Guidingar from tkinter import * import os os.system('clear') root = Tk() root.title('TextBox Example') entry = Entry(root,width=25) entry.insert(0,'Enter your name') entry.grid(row=0,column=0,columnspan=5,padx=5,pady=8) b = Button(root,text='Click Me!') b.grid(row=3,column=3) root.mainloop()
b19a73e943cc2fa5c2d1527668b50a9ca6f74e7f
ladosamushia/PHYS639F19
/NathanMarshall/ODE3/Orbital Motion - Stationary Center Mass.py
1,151
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 1 13:14:58 2019 Nathan Marshall This code simulates the orbit of an object around a stationary central mass. """ #%% import matplotlib.pyplot as plt x0 = 1 #initial x y0 = 0 #initial y vx0 = 0 #initial x velocity vy0 = 0 #initial y velocity t0 = 0 #start time tmax = 10 #stop time dt = 0.001 #time step size G = 1 #gravitational constant M = 1 #mass of central object x = [x0] #list to contain x values y = [y0] #list to contain y values vx = [vx0] #list to contain x velocities vy = [vy0] #list to contain y velocities t = [t0] #list to contain time values def dvxdt(x, y): '''Diff. eq. for x velocity''' return(- G * M * x / ((x**2 + y**2)**(3/2))) def dvydt(x, y): '''Diff. eq. for y velocity''' return(-G * M * y / ((x**2 + y**2)**(3/2))) while t[-1] < tmax: x.append(x[-1] + vx[-1]*dt) y.append(y[-1] + vy[-1]*dt) vx.append(vx[-1] + dvxdt(x[-1], y[-1]) * dt) vy.append(vy[-1] + dvydt(x[-1], y[-1]) * dt) t.append(t[-1] + dt) fig = plt.figure('Orbital Trajectory') plt.title('Orbital Trajectory') plt.xlabel('X (m)') plt.ylabel('Y (m)') plt.plot(x, y)
4775dc3a38827a4615444b6f83158bb2e216c546
Arkzirk/Practice
/final_practice.py
691
3.921875
4
print('Общество в начале XXI века') x = int(input('Сколько Вам лет?')) def myfunc(x): if x >= 0 and x <= 7: t = 'Вам в детский сад' elif x > 7 and x <= 18: t = 'Вам в школу' elif x > 18 and x <= 25: t = 'Вам в профессиональное учебное заведение' elif x > 25 and x <= 60: t = 'Вам на работу' elif x > 60 and x <= 120: t = 'У вас есть выбор' else: i = 0 while i < 5: print('Ошибка! Это программа для людей!') i = i + 1 return t print(myfunc(x))
584f418d76b05c16360a40ff52e2fa983e3f3f3d
shahrukh357/MachineLearning
/Regression/Multiple Linear Regression/multiple_linear_regression.py
2,235
4.03125
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder = LabelEncoder() X[:, 3] = labelencoder.fit_transform(X[:, 3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # Avoiding the Dummy Variable Trap X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42) # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" # Fitting Multiple Linear Regression to the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test) #building The optimal model using Backward Elimination #X=np.append(arr=X,values=np.ones((50,1)).astype(int),axis=1) # an array of would be added in our dataset at the end which will work as b0 in the equation #y=b0+b1x #but if we interchange the values of arr and values ,our bo array will be added at the first #coulmns import statsmodels.formula.api as sm X=np.append(arr=np.ones((50,1)).astype(int),values=X,axis=1) X_opt=X[:,[0,1,2,3,4,5]] regressor_OLS=sm.OLS(endog=y,exog=X_opt).fit() regressor_OLS.summary() X_opt=X[:,[0,1,3,4,5]] regressor_OLS=sm.OLS(endog=y,exog=X_opt).fit() regressor_OLS.summary() X_opt=X[:,[0,3,4,5]] regressor_OLS=sm.OLS(endog=y,exog=X_opt).fit() regressor_OLS.summary() X_opt=X[:,[0,3,5]] regressor_OLS=sm.OLS(endog=y,exog=X_opt).fit() regressor_OLS.summary() X_opt=X[:,[0,3]] regressor_OLS=sm.OLS(endog=y,exog=X_opt).fit() regressor_OLS.summary() # columns no 3 is the R&D . # so the profit columns is mostly dependent on the columns no 3
606491180daf23150d0a65b4e1ce2af1d1e5069d
luciogutierrez/iron-hack
/1-module/9-map-reduce-filter/test.py
216
3.703125
4
from functools import reduce def solution(digits): num_ini = int(reduce(lambda a,b: a if a>b else b , str(digits))) num_fin = num_ini + 3 return digits[num_ini:num_fin] print(solution('19265'))
c2b370a8a66b19aba585e629d16d5e87a7e65534
J-A-S-0-N/1DAY-1COMMIT
/opencv face/when_started.py
307
3.703125
4
import tkinter as tk root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300) canvas1.pack() def hello (): label1 = tk.Label(root, text= 'hello wellcome', fg='green', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 200, window=label1) hello() root.mainloop()
d5cec864958d7396b842729ca13ad24201d72087
jonaschianu/2D-Graphics
/Graphics2d.py
6,692
3.921875
4
################################################################################ # Project: 2D Graphical Outputs using Matrices # # # # Name: Jonas Chianu # # File: Graphics2d.py # # Purpose: Contains the graphical interface classes. # # Description: Creates shapes and drawings given required parameters. # ################################################################################ import math # Importing math module to access mathematical functions import turtle # Importing turtle module import main # Importing main.py file class Drawing(): ''' This class creates drawings from list of shapes ''' def __init__(self, shape_array): ''' Initializes drawing with a list of shapes to be included (Constructor) Passed: List of shapes (List) Returns: None ''' self.__shapes=shape_array # 4c self.bgcolor = "white" # 4a def add_bg_color(self,bgcolor="white"): # 4b ''' Adds a background color to drawing Passed: Background color (str) Returns: None ''' self.bgcolor=bgcolor def display_drawing(self): ''' Creates and displays the drawing Passed: None Returns: None ''' for shape in self.__shapes: # 4d turtle.bgcolor(self.bgcolor) shape.draw_shape() turtle.exitonclick() try: turtle.bye() except Exception: pass def add_border(self,border_color,margin_dimensions): ''' Creates and displays the drawing Passed: Border color (str), Margin dimensions (list) Returns: None ''' pass class Shape(): ''' This class creates a shape given corner coordinates ''' def __init__(self, complex_array): ''' Initializes shape a list of corner coordinates (Constructor) Passed: List of corner coordinates (Matrix) Returns: None ''' self._array=complex_array.get_matrix()[0] self.points_array() self._line_color = "black" self._fill_color = "" def rotate_shape(self,rotation): ''' Rotates the shape Passed: Rotation angle (number) Returns: None ''' x = math.cos(rotation *(math.pi/180)) y = math.sin(rotation*(math.pi/180)) for i in range(len(self._array)): self._array[i]*=main.ComplexNumber(x, y) self.points_array() def move_shape(self,x,y): ''' Moves the shape Passed: Horizontal translation (number), Vertical translation (number) Returns: None ''' for i in range(len(self._array)): self._array[i]+=main.ComplexNumber(x, y) self.points_array() def shape_size(self,ratio): ''' Changes the relative size of shape Passed: Scaling ratio (number) Returns: None ''' for i in range(len(self._array)): self._array[i]*=main.ComplexNumber(ratio, 0) self.points_array() def points_array(self): ''' Changes the matrix with complex numbers coordinates to a list of tuples coordinates Passed: None Returns: None ''' self._points=[] for complex_num in self._array: self._points.append(complex_num.get_complex_Number()) self._points.append(self._array[0].get_complex_Number()) def color(self,line_color = "black",fill_color=""): ''' Assigns a color to the shape Passed: Color of shape's border (str), Color of shape (str) Returns: None ''' self._line_color = line_color self._fill_color = fill_color class Shape_linear(Shape): ''' This class creates a shape drawn using straight lines ''' def draw_shape(self): ''' Draws and displays the shape Passed: None Returns: None ''' turtle.penup() turtle.goto(self._points[0]) turtle.pendown() turtle.color(self._line_color, self._fill_color) turtle.begin_fill() for i in range(len(self._points)-1): turtle.goto(self._points[i+1]) turtle.end_fill() turtle.penup() turtle.hideturtle() def line_style(self,line_style): ''' Changes the line_style Passed: Line style (str) Returns: None ''' pass def remove_section(self,coordinates_to_remove): ''' Remove a section of the line between two points Passed: Coordinates to remove (tuple) Returns: None ''' pass class Shape_arc(Shape): def draw_shape(self): ''' Draws and displays the shape Passed: None Returns: None ''' radius_list=[] angle_list=[] # print(self._array) for i in range(len(self._array)-1): radius_list.append( (self._array[i+1]-self._array[i]).polar_mag/2 ) angle_list.append( (self._array[i+1]-self._array[i]).polar_phase*(180/math.pi) ) # print((self._array[i+1]-self._array[i]).polar_phase ) radius_list.append((self._array[0] - self._array[-1]).polar_mag / 2) angle_list.append((self._array[0] - self._array[-1]).polar_phase * (180 / math.pi)) turtle.penup() turtle.goto(self._points[0]) turtle.pendown() turtle.color(self._line_color,self._fill_color) turtle.begin_fill() for i in range(len(radius_list)): turtle.setheading(angle_list[i]+90) turtle.circle(radius_list[i]*-1, 360) turtle.end_fill() # for i in range(len(self._points)-1): # turtle.goto(self._points[i+1]) turtle.penup() turtle.hideturtle() def arc_bulge(self,bulge_radius): ''' Change the bulge of the arc given bulge radius Passed: Bulge radius (number) Returns: None ''' pass def remove_section(self,angle_range): ''' Remove a section of arc given given desired angle range to remove Passed: Angle range (tuple) Returns: None ''' pass
c268721c43fe1e3c225b40b7ef9fe5af2e79cdf8
topherCarpediem/python
/hello.py
475
3.578125
4
# def exc(): # num = input("number: ") # if float(num) < 0: # raise ValueError("Negative") # # # exc() # # the_file = open("sample.txt", "w") # the_file.writelines("Topher") # the_file.close() another = open("sample.txt", "r") content = another.readline() print(content) another.close() aanother = open("text.txt", "w") aanother.write("Hello this is from hello.y") print(content) aanother.close() squares = {1: 1, 2: 4, 3: 9, 4: 16, 8: 64} print(squares)
43488d6d80af05b1e4d8aec1f57a0fbca7198686
yoojunwoong/python_review01
/test2_02.py
207
3.765625
4
# if else 문을 활용하여, 값의 여부확인 a = int(input('insert Numeber...')); if a > 10: print('big nummber'); print('ok'); else: print('small number'); print('end python.....');
09332092e3c022c872d13e889521b9c11ceb1b0f
hengyangKing/python-skin
/Python基础/code_day_1/列表.py
477
3.5625
4
# coding=utf-8 # 列表类型变量 foo=["foo1","foo2","foo3","foo4"] print foo # 列表类似于c中的数组 但是区别在于可以存储不同类型的数据 更像是NSArray for i in xrange(0,len(foo)): print foo[i] print "..................." # for枚举用法 for j in foo: print "---foo %s"%j # 列表的遍历 names=["dlsandnas",dsakdasdsa,"nsdkjnsandksankdnsak","ndkanskdnka","nskda"] i=0 while i<len(names): print "name %s is %s"%(i,names[i]) i+=1
b12a4a09c28db5f8390196bf96b00e7941adaa60
FarzanaEva/Data-Structure-and-Algorithm-Practice
/InterviewBit Problems/Two Pointers/merge_two_sorted_lists_II.py
1,181
3.921875
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 02:09:52 2021 @author: Farzana Eva """ """ PROBLEM STATEMENT: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. TIP: C users, please malloc the result into a new array and return the result. If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n Example : Input : A : [1 5 8] B : [6 9] Modified A : [1 5 6 8 9] """ def merge(A, B): temp = [0] * (len(A)+len(B)) i = 0 j = 0 k = 0 while i<len(A) and j<len(B): if A[i] < B[j]: temp[k] = A[i] i+=1 k+=1 else: temp[k] = B[j] j+=1 k+=1 for l in range(i, len(A)): temp[k] = A[l] k+=1 for r in range(j, len(B)): temp[k] = B[r] k+=1 A += [0]*len(B) for i in range(len(temp)): A[i] = temp[i] return A A = [1, 1, 1, 1, 2, 7, 9] B = [0, 3, 5, 7, 10] print(merge(A, B))
42768de6149e331e494ce878f39c67c44de56b47
kunamdeepthipriyanka/raspi
/power.py
173
3.875
4
a=10 b=20 c=30 if (a>b) and (b>c): print("a is greater",str(a)) print(a) elif: print("b is greater",str(b)) print(b) else: print("c is greater",str(c))
6539b0d220380616a643d96bbfbf99a86fba3080
dollarkid1/pythonProjectSemicolon
/chp3/ExamAnalyzer.py
402
3.6875
4
def analyzer(): passes = 0 failures = 0 print("enter results (pass = 1 and fail = 2)\n") for i in range(10): result = int(input()) if result == 1: passes += 1 else: failures += 1 print(f'Students Passed = {passes}') print(f'Students Failed = {failures}') if passes > 8: print("Bonus to the Instructor") analyzer()
3bb2eee3b219e51a5f98e7acd069260e0c14facd
ClowDragon/MSCProject
/algorithms/cg.py
802
3.5
4
import numpy as np def cg(A, b, x): """ A function to solve [A]{x} = {b} linear equation system with the conjugate gradient method. ========== Parameters ========== A : matrix A real symmetric positive definite matrix. b : vector The right hand side (RHS) vector of the system. x : vector The starting guess for the solution. """ r = b - np.dot(A, x) p = r rsold = np.dot(np.transpose(r), r) for i in range(len(b)): Ap = np.dot(A, p) alpha = rsold / np.dot(np.transpose(p), Ap) x = x + np.dot(alpha, p) r = r - np.dot(alpha, Ap) rsnew = np.dot(np.transpose(r), r) if np.sqrt(rsnew) < 1e-8: break p = r + (rsnew / rsold) * p rsold = rsnew return x
4bd6967bbeeb67e4d754ec2e1293c37123757d46
asishnayak1999/fispy
/py/numpy.py
336
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 10:13:53 2021 @author: User """ import numpy as np x = np.array([[12,43,65], [32,11,77], [12,90,65], [3,6,99]]) print(x[...,2]) #any row 2 column print(x[2,...]) #2nd row clo 1 onwarnd print(x[...,1:]) #any row 1 onwards
7a35f2bf82d0e76ed6f7edbfc7d6388a47e192ab
adamhartleb/cracking_codes
/caesar.py
1,495
4.34375
4
from string import ascii_letters def encode(word, key, mode): key = key % 26 letters = list(word) encrypted_letters = [] for letter in letters: encrypted_letter = '' if letter == ' ': encrypted_letter = ' ' elif not(letter in ascii_letters): raise ValueError("Word must consist of only letters.") else: encrypted_letter = shift_letter(letter, key, mode) encrypted_letters.append(encrypted_letter) return ''.join(encrypted_letters) def shift_letter(letter, key, mode): isUppercase = letter.isupper() letter = letter.lower() encrypted_letter = '' if mode == "encrypting": if ord(letter) + key > ord('z'): encrypted_letter = chr(ord(letter) - 26 + key) else: encrypted_letter = chr(ord(letter) + key) else: if ord(letter) - key < ord('a'): encrypted_letter = chr(ord(letter) + 26 - key) else: encrypted_letter = chr(ord(letter) - key) return encrypted_letter.upper() if isUppercase else encrypted_letter def main(): plain_text = input("Please enter a word: ") key = input("Enter a shift: ") mode = input("Are we encrypting or decrypting?: ") if mode != "encrypting" and mode != "decrypting": raise ValueError("Unknown mode.") encrypted_text = encode(plain_text, int(key), mode) print(encrypted_text) main()
9a6fc0f5588170554b278f44cb4e2c4cf2cc382a
robbertmijn/kudo_plotter
/auth.py
1,189
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 11 11:47:07 2020 https://medium.com/swlh/using-python-to-connect-to-stravas-api-and-analyse-your-activities-dummies-guide-5f49727aac86 @author: robbertmijn This is the script that creates the json auth tokens. I needed to refresh my code when I ran it again weeks later. refer to link on how to do that. """ import requests import json # Make Strava auth API call with your # client_code, client_secret and code response = requests.post( url = 'https://www.strava.com/oauth/token', data = { 'client_id': [id], 'client_secret': '[]', 'code': '[]', 'grant_type': 'authorization_code' } ) #Save json response as a variable strava_tokens = response.json() # Save tokens to file with open('strava_tokens.json', 'w') as outfile: json.dump(strava_tokens, outfile) # Open JSON file and print the file contents # to check it's worked properly with open('strava_tokens.json') as check: data = json.load(check) print(data)
927998aee9859f8601dec3a632388ac89fb1171a
laddng/NeuralNetwork
/main.py
1,086
3.71875
4
from classes.NeuralNetwork import *; from copy import deepcopy, copy; def main(): """ Run neural network tests """ # 10 different hidden layers for i in range(10): # 10 different epochs epochs = []; RMSE = []; for k in range(10): hidden_layers = (i+1)*10; net = NeuralNetwork(2, 1, hidden_layers); net.run("NXOR", (10*k)); epochs.append(deepcopy(net.epochs)); RMSE.append(deepcopy(net.RMSE)); graphResults(epochs, RMSE, ("# epochs, "+str(hidden_layers)+" hidden layers"), "RMSE"); # 10 different hidden layers time = []; layers = []; for i in range(10): hidden_layers = (i+1)*10; net = NeuralNetwork(2, 1, hidden_layers); # 1000 different epochs net.run("XOR", 1000); time.append(deepcopy(net.training_time)); layers.append(deepcopy(hidden_layers)); graphResults(layers, time, "# hidden layers", "time"); return True; def graphResults(x,y,xlabel,ylabel): """ Given x and y, plots the results to a matplotlib graph for output """ plt.figure("Results"); plt.xlabel(xlabel); plt.ylabel(ylabel); plt.plot(x,y); plt.show(); main();
42cd21f405f0fe7c78e09e500de6e49099545e73
STEEL06/Calculadora_Dieta
/calculo_metabolismo.py
10,919
3.734375
4
print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Calculo da Taxa do Metabolismo Basal (TMB)." lacoTMB = 0 while ( lacoTMB != 1 ): print"" genero = input ("Qual o seu genero? 1-Homem ; 2-Mulher ") while ( genero != 1 and genero != 2 ): print "" print "Escolha um genero existente." print "" genero = input ("Qual o seu genero? 1-Homem ; 2-Mulher ") print "" peso = input ("Qual seu peso em Kg ? ") alturam = input ("Qual sua altura em m ? ") alturacm = ( alturam * 100 ) idade = input ("Qual sua idade em anos ? ") BF = input ("Qual o seu percentual de gordura corporal? Digite 0 caso nao saiba. ") print "" if genero == 1: print "Voce e Homem." elif genero == 2: print "Voce e Mulher." else: print "" print "O seu peso e", peso, "Kgs." print "A sua altura e", alturam, "m." print "A sua idade e", idade, "anos." if BF == 0: print "O seu percentual de gordura nao e conhecido." else: print "O seu percentual de gordura e de ", BF, "%." print"" if BF == 0: if genero == 1: TMB = (( 10 * peso ) + ( 6.25 * alturacm ) - ( 5 * idade ) + 5 ) elif genero == 2: TMB = (( 10 * peso ) + ( 6.25 * alturacm ) - ( 5 * idade ) - 161 ) else: print "" else: TMB = ( 370 + ( 21.6 * ( peso - ( peso * BF * 1/100 )))) print "A sua Taxa Metabolica Basal e", TMB, "kcal." print "" lacoTMB = input ("Esses dados estao corretos? 1-Sim ; 2-Nao ? ") print "" print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Calculo da Ingestao Calorica Recomendada (ICR)." lacoICR = 0 while ( lacoICR != 1 ): print "" print "Com qual item dessa tabela se assemelha sua quantidade de exercicios semanal ?" print "" print "1- Nenhum ou pouco." print "2- Leve, de 1 a 3 vezes por semana." print "3- Moderado, de 3 a 5 vezes por semana." print "4- Pesado, de 6 a 7 vezes por semana." print "5- Extremo, duas vezes ao dia." print "" QES = input ("") # QE = Quantidade de Exercicio Semanal print "" while ( QES != 1 and QES != 2 and QES != 3 and QES != 4 and QES != 5 ): print "" print "Valor invalido, escolha novamente." print "" print "Com qual item dessa tabela se assemelha sua quantidade de exercicios semanal ?" print "" print "1- Nenhum ou pouco." print "2- Leve, de 1 a 3 vezes por semana." print "3- Moderado, de 3 a 5 vezes por semana." print "4- Pesado, de 5 a 7 vezes por semana." print "5- Extremo, mais de uma vez ao dia." print "" QES = input ("") print "" if QES == 1: ICR = ( 1.2 * TMB ) print "Voce nao faz, ou faz pouquissimo exercicio." elif QES == 2: ICR = ( 1.375 * TMB ) print "Voce se exercita de forma leve, de 1 a 3 vezes na semana." elif QES == 3: ICR = ( 1.55 * TMB ) print "Voce se exercita de forma moderada, de 3 a 5 vezes na semana." elif QES == 4: ICR = ( 1.725 * TMB ) print "Voce se exercita de forma pesada, de 5 a 7 vezes na semana." elif QES == 5: ICR = ( 1.9 * TMB ) print "Voce se exercita de forma extrema, mais de uma vez ao dia." else: print "" print "" print "sua Ingestao Calorica Recomendada e de", ICR, "kcal" print "" lacoICR = input ("Esses dados estao corretos? 1-Sim ; 2-Nao ? ") print "" print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Calculo do balanco do Deficit ou Superavit Calorico (DSC)" lacoDSC = 0 while ( lacoDSC != 1 ): print "" print "Escolha o tipo de dieta pretendida:" print "1- Hipocalorica ; 2- Normocalorica ; 3- Hipercalorica" print "" DSC = input ("") while ( DSC != 1 and DSC != 2 and DSC != 3 ): print "Escolha um valor possivel." print "" print "Escolha o tipo de dieta pretendida:" print "1- Hipocalorica ; 2- Normocalorica ; 3- Hipercalorica" print "" DSC = input ("") # DSC: Deficit ou Superavit Calorico / CD: Calorias Diarias print "" if DSC == 1: kcalsem = input ("Quantos kilos pretende perder por semana? ") kcaldia = ( kcalsem * 7700 / 7 ) CD = ( ICR - kcaldia ) print "" print "Voce optou em fazer uma dieta Hipocalorica." print "Voce deseja perder", kcalsem, "kg por semana." elif DSC == 2: CD = ICR print "" print "Voce optou em fazer uma dieta Normocalorica." print "Voce deseja manter seu peso." elif DSC == 3: kcalsem = input ("Quantos kilos pretende ganhar por semana? ") kcaldia = ( kcalsem * 7700 / 7 ) CD = ( ICR + kcaldia ) print "" print "Voce optou em fazer uma dieta Hipercalorica." print "Voce deseja ganhar", kcalsem, "kg por semana." else: print "" print "Sua necessidade Calorica Diaria e", CD, "kcal." print "" lacoDSC = input ("Esses dados estao corretos? 1-Sim ; 2-Nao ? ") print "" print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Calculo dos Macro-Nutrientes." lacoPMC = 0 while ( lacoPMC != 1 ): #________________________Percentuais de cada Macro-Nutriente_____________________________________________________________________________________________ print "" PercCarbo = input ("Qual o percentual de Carboidratos de sua dieta? 0 a 100: ") PercProte = input ("Qual o percentual de Proteinas de sua dieta? 0 a 100: ") PercLipid = input ("Qual o percentual de Lipideos de sua dieta? 0 a 100: ") print "------------------------------------------------------------------------------" print "| Voce escolheu os seguintes percentuais para dividir seus Macro-Nutrientes: |" print "| Carboidratos -", PercCarbo, "%. |" print "| Proteinas -", PercProte, "%. |" print "| Lipideos -", PercLipid, "%. |" print "------------------------------------------------------------------------------" #_______________________________Calorias por Macro-Nutriente_____________________________________________________________________________________________ print "" KcalCarbo = ( PercCarbo * 1.0/100 * CD ) KcalProte = ( PercProte * 1.0/100 * CD ) KcalLipid = ( PercLipid * 1.0/100 * CD ) print "----------------------------------------------------------------------------------" print "| Voce devera consumir os seguintes valores em calorias de cada Macro-Nutriente: |" print "| Carboidratos -", KcalCarbo, "kcal. |" print "| Proteinas -", KcalProte, "kcal. |" print "| Lipideos -", KcalLipid, "kcal. |" print "----------------------------------------------------------------------------------" #____________________________Peso em Gramas por Macro-Nutriente__________________________________________________________________________________________ print "" GramCarbo = ( KcalCarbo * 1.0 / 4.1 ) GramProte = ( KcalProte * 1.0 / 4.3 ) GramLipid = ( KcalLipid * 1.0 / 9.3 ) print "---------------------------------------------------------------------------------" print "| Voce devera consumir a seguinte quantidade em gramas de cada Macro-Nutriente: |" print "| Carboidratos -", GramCarbo, "gramas. |" print "| Proteinas -", GramProte, "gramas. |" print "| Lipideos -", GramLipid, "gramas. |" print "---------------------------------------------------------------------------------" #_______Peso em Gramas de Macro-Nutrientes por kg de peso corporal_______________________________________________________________________________________ GrCarbPkg = ( GramCarbo / peso ) GrProtPkg = ( GramProte / peso ) GrLipiPkg = ( GramLipid / peso ) print "-----------------------------------------------------------------" print "| Sua ingestao de Macro-Nutrientes em gramas por peso em kgs e: |" print "| Carboidratos -", GrCarbPkg, "gr/kg de peso corporal. |" print "| Proteinas -", GrProtPkg, "gr/kg de peso corporal. |" print "| Lipideos -", GrLipiPkg, "gr/kg de peso corporal. |" print "-----------------------------------------------------------------" lacoPMC = input ("Esses dados estao corretos? 1-Sim ; 2-Nao ") print "" print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Divisao de Macro-Nutrientes por numero de refeicoes." lacoDMN = 0 while ( lacoDMN != 1 ): print "" QtRfCarbo = input ("Quantas refeicoes com carboidrato voce fara ao longo do dia? ") QtRfProte = input ("Quantas refeicoes com proteina voce fara ao longo do dia? ") QtRfLipid = input ("Quantas refeicoes com lipideo voce fara ao longo do dia? ") GrCarbPRf = ( GramCarbo / QtRfCarbo ) GrProtPRf = ( GramProte / QtRfProte ) GrLipiPRf = ( GramLipid / QtRfLipid ) print "Voce optou por fazer", QtRfCarbo, "refeicoes de Carboidrato por dia, contendo", GrCarbPRf, "gramas cada uma." print "Voce optou por fazer", QtRfProte, "refeicoes de Proteina por dia, contendo", GrProtPRf, "gramas cada uma." print "Voce optou por fazer", QtRfLipid, "refeicoes de Lipideo por dia, contendo", GrLipiPRf, "gramas cada uma." lacoDMN = input ("Esses dados estao corretos? 1-Sim ; 2-Nao ") print " " print " " print " " print "genero: ", genero, " ; peso: ", peso, " ; altura: ", alturam, " ; idade: ", idade print "QES: ", QES, " ; TMB: ", TMB, " ; ICR: ", ICR print "DSC: ", DSC, " ; CD: ", CD print "PercCarbo, PercProte, PercLipid: ", PercCarbo, " , ", PercProte, " , ", PercLipid, " . " print "KcalCarbo, KcalProte, KcalLipid: ", KcalCarbo, " , ", KcalProte, " , ", KcalLipid, " . " print "GramCarbo, GramProte, GramLipid: ", GramCarbo, " , ", GramProte, " , ", GramLipid, " . " print "GrCarbPkg, GrProtPkg, GrLipiPkg: ", GrCarbPkg, " , ", GrProtPkg, " , ", GrLipiPkg, " . " print "QtRfCarbo, QtRfProte, QtRfLipid: ", QtRfCarbo, " , ", QtRfProte, " , ", QtRfLipid, " . " print "GrCarbPRf, GrProtPRf, GrLipiPRf: ", GrCarbPRf, " , ", GrProtPRf, " , ", GrLipiPRf, " . "
422230d39c8a9518c1da1beb7c60040946c704f3
heitorchang/learn-code
/battles/number_theory/mirrorBase.py
625
3.90625
4
description = """ Given number (in the form of a string) represented in base1, we'd like to determine whether its digits form a palindrome when represented in base2. """ import string as g from collections import deque as q def z(n, b): # change base from decimal int "n" to base b p = g.digits + g.ascii_lowercase r = q() # queue while n > 0: w = n % b # least significant digit r.appendleft(p[w]) n //= b return ''.join(r) def mirrorBase(n, i, j): d = int(n, i) # convert to dec first m = z(d, j) # convert to base 2 return m == m[::-1] # check if palindrome
7d55656d582da78c03b72cef27936a3dbe12cc9b
sbalun/codecademy-homework
/more-list-challenges.py
3,157
4.59375
5
""" 1. Every Three Numbers Create a function called every_three_nums that has one parameter named start. The function should return a list of every third number between start and 100 (inclusive). For example, every_three_nums(91) should return the list [91, 94, 97, 100]. If start is greater than 100, the function should return an empty list. """ def every_three_nums(start): return list(range(start, 101, 3)) print("Testing -- 1. Every three numbers") print(every_three_nums(100)) """ 2. Remove Middle Create a function named remove_middle which has three parameters named lst, start, and end. The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed. For example, the following code should return [4, 23, 42] because elements at indices 1, 2, and 3 have been removed: remove_middle([4, 8 , 15, 16, 23, 42], 1, 3) """ def remove_middle(lst,start,end): del lst[start:end+1] return lst print("Testing -- 2. Remove Middle") print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3)) """ 3. More Frequent Item Create a function named more_frequent_item that has three parameters named lst, item1, and item2. Return either item1 or item2 depending on which item appears more often in lst. If the two items appear the same number of times, return item1. """ def more_frequent_item(lst,item1,item2): count_1 = lst.count(item1) count_2 = lst.count(item2) if count_1 >= count_2: return item1 else: return item2 print("Testing -- 3. More Frequent Items") print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3, 2], 2, 3)) """ 4. Double Index Create a function named double_index that has two parameters: a list named lst and a single number named index. The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst. If index is not a valid index, the function should return the original list. For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled: double_index([1, 2, 3, 4], 2) """ def double_index(lst,index): if index > len(lst)-1: return lst else: double_index_value = lst[index] double_index_value *= 2 del lst[index] lst.insert(index, double_index_value) return lst print("Testing -- 4. Double Index") print(double_index([3, 8, -10, 12], 3)) """ 5. Middle Item Create a function called middle_element that has one parameter named lst. If there are an odd number of elements in lst, the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements. """ def middle_element(lst): if len(lst) % 2 != 0: #Odd number middle_index = len(lst)//2 return lst[middle_index] else: #even number r_middle_index = len(lst)//2 l_middle_index = len(lst)//2 - 1 average = (lst[r_middle_index] + lst[l_middle_index])/2 return average print("Testing -- 5. Middle Item") print(middle_element([5, 2, -10, -4, 4, 5, 6]))
8bb30371ec3b59beab98bfead801f861e21ee61e
thuchimney292/thutran-fundamental-c4ep35
/lesson5/homework/5.py
202
3.890625
4
from turtle import * def draw_star(x,y,length): penup() setpos(x,y) pendown() left(72) for i in range(5): forward(length) right(144) draw_star(100,100,100) mainloop()
9d7575306cfd4eb3aead4bb9f862c93f53ec795b
koles289/Udacity_facial_detection
/models.py
1,827
3.65625
4
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=3, padding=0) # output size = (W-F)/S +1 = (224-5)/3 + 1 = 74 self.pool1 = nn.MaxPool2d(2, 2) # 74/2 = 37 the output Tensor for one image, will have the #dimensions: (16, 37, 37) self.conv2 = nn.Conv2d(16,32,3) #dimensions: (32, 35, 35) self.conv3 = nn.Conv2d(32,64,3) #dimensions: (64, 33, 33) self.pool3 = nn.MaxPool2d(2, 2) #33/2=17 the output Tensor for one image, will have the #dimensions: (64, 17, 17) self.conv4 = nn.Conv2d(64,128,1) #dimensions: (128, 17, 17) self.pool4 = nn.MaxPool2d(2, 2) #dimensions: (256, 9, 9) self.fc1 = nn.Linear(128*8*8, 256) self.fc2 = nn.Linear(256, 136) self.drop2 = nn.Dropout(p = 0.25) self.drop3 = nn.Dropout(p = 0.25) self.drop4 = nn.Dropout(p = 0.25) # define the feedforward behavior def forward(self, x): x = self.pool1(F.relu(self.conv1(x))) x = F.relu(self.conv2(x)) x = self.drop2(x) x = self.pool3(F.relu(self.conv3(x))) x = self.drop3(x) x = self.pool4(F.relu(self.conv4(x))) x = self.drop4(x) x = x.view(x.size(0), -1) x = F.tanh(self.fc1(x)) x = self.fc2(x) # a modified x, having gone through all the layers of your model, should be returned return x
084369e4ad0ce5dd14a6679c6611f8d31b4c4acb
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT2 Srings.py
625
4.1875
4
message = "Hello" print(message) print(len(message)) print(message[0:5:2]) # string slicing print(message.lower()) # string methods print(message.upper()) print(message.find('e')) message = message.replace('Hello', "GoodBye") print(message) greeting = "Hi" name = "nick" message = greeting + ' ' + name print(message) # string formatting message = "{} {}, Welcome!".format(greeting, name) print(message) message = f"{greeting} {name}, Welcome to string formatting!" print(message) # how to find what methods are available s = 'string' print(dir(s)) # help function print(help(str)) print(help(str.format()))
017341ee29dd0126edcce9c868a60ec3eabbfad9
vaipathak/LearnPython
/Python 2.7/ex18.py
2,875
4.6875
5
print "Exercise 18: Names, Variables, Code, Functions" print """Big title, right? I am about to introduce you to the function! Dum dum dah! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now. Functions do three things: They name pieces of code the way variables name strings and numbers. They take arguments the way your scripts take argv. Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands." You can create a function by using the word def in Python. I'm going to have you make four different functions that work like your scripts, and I'll then show you how each one is related. """ #this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) #Side Note: What does the * in *args do? #That tells Python to take all the arguments to the function and then put them #in args as a list. It's like argv that you've been using, but for functions. #It's not normally used too often unless specifically needed. #ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) #this one just takes one argument def print_one(arg1): print "arg1: %r" % arg1 #this one takes no arguments def print_none(): print "I got nothin'." print_two("Vai","Pathak") print_two_again("Vai", "Pathak") print_one("First!") print_none() #Let's break down the first function, "print_two", which is the most similar to #what you already know from making scripts: #First we tell Python we want to make a function using "def" for "define". #On the same line as def we give the function a name. #In this case we just called it "print_two" but it could also be "peanuts". #It doesn't matter, except that your function should have a short name that says #what it does. #Then we tell it we want *args (asterisk args) which is a lot like your #"argv" parameter but for functions. This has to go inside () parentheses to work. #Then we end this line with a : colon, and start indenting. #After the colon all the lines that are indented four spaces #will become attached to this name, print_two. #Our first indented line is one that unpacks the arguments #the same as with your scripts. #To demonstrate how it works we print these arguments out, just like we would #in a script. #The problem with print_two is that it's not the easiest way to make a function. #In Python we can skip the whole unpacking arguments and just use the names we want #right inside (). That's what print_two_again does. #After that you have an example of how you make a function that takes #one argument in print_one. #Finally you have a function that has no arguments in print_none. #Study Drill #def check_list():
1432dba7e8a6757b8e35032983d85af8a511fd06
Aanandi03/15Days-Python-Django-Summer-Internship
/Day_5/Task_Exercise/ex2.py
488
4.21875
4
# Create a class cal2 that will calculate area of a circle. Create setdata() # method that should take radius from the user. Create area() method # that will calculate area . Create display() method that will display area . class Cal2: radius=0 def setdata(self): r = int(input("Enter radius: ")) self.radius=r def display(self): area = 3.14*self.radius * self.radius print("sum is ",area) c = Cal2() c.setdata() c.display()
b23f7f22824a191ff1c2229685b42edc27e956f4
roger6blog/LeetCode
/SourceCode/Python/Problem/00287.Find the Duplicate Number.py
2,029
3.96875
4
''' Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3 Constraints: 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times. ''' class Solution(object): def findDuplicate_not_meet_space_limit(self, nums): """ :type nums: List[int] :rtype: int """ duplicate_num = {} for i in nums: if i not in duplicate_num: duplicate_num[i] = 0 else: return i class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ ''' We use fast/slow ptr method in checking cycle of LinkList Set two ptrs, slow one move 1 step, fast one 2 steps They must meet during traversal Then we set one of ptr to 0 to restart moving from start poing(usually fast ptr) If this pty whcich restart moving from start point still be able to reach other pts It means there is a cycle in LinkList, there is a duplicate number in list as welll Limittion: Integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 1 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n ''' slow = nums[0] fast = nums[nums[0]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] fast = 0 while slow != fast: slow = nums[slow] fast = nums[fast] return slow nums = [1,3,4,2,2] assert 2 == Solution().findDuplicate(nums)
3823b577b1b3d44fb40201be3f6351ced17411f7
AviCodeBoy/MathTools
/primeNList.py
659
3.875
4
def prime_or_not(numberToTest): findFactorsOf = numberToTest divisor = 1 factorList = [] comparator = [1, findFactorsOf] while True: x = findFactorsOf / divisor wholeOrNot = x - int(x) == 0 if wholeOrNot: factorList.append(divisor) divisor = divisor + 1 if divisor > findFactorsOf: break if factorList == comparator: return numberToTest number = 1 primeNums = [] maxim = 200 while True: result = prime_or_not(number) if number > maxim: break if result == number: primeNums.append(number) number = number + 1 print(primeNums)
8e4e3ff1039c1dc4127867afacdc84f8797177ad
hochu-leto/generators
/main.py
1,726
3.5
4
import json import os R_FILE = "countries.json" # Первый вариант, без всяких там классов и итераторов // # R_FILE = "countries.json" # W_FILE = "countries.txt" # URL = 'http://en.wikipedia.org/wiki/' # # with open(R_FILE, "r") as read_file: # data = json.load(read_file) # # url_country = {} # for country in data: # country_name = country['name']['common'] # url_country[country_name] = URL + country_name.replace(' ', '_') # # pprint(url_country) # # with open(W_FILE, "w", encoding='utf-8') as write_file: # for c, u in url_country.items(): # write_file.write(c + ' - ' + u + '\n') # class CountryUrl: URL = 'http://en.wikipedia.org/wiki/' def __init__(self, file): self.url_country = {} self.file = file self.save_file = os.path.splitext(self.file)[0] + '.txt' with open(self.file, "r") as read_file: data = json.load(read_file) i = 0 for country in data: country_name = country['name']['common'] self.url_country[i] = country_name i += 1 def get_url(self, country_name): return self.URL + country_name.replace(' ', '_') def __iter__(self): self.cursor = 0 return self def __next__(self): self.cursor += 1 if self.cursor > len(self.url_country) - 2: raise StopIteration url = self.get_url(self.url_country[self.cursor]) with open(self.save_file, "a", encoding='utf-8') as write_file: write_file.write(self.url_country[self.cursor] + ' - ' + url + '\n') return url countries = CountryUrl(R_FILE) for country in countries: print(country)
edc6072a859611513ec506c71f532ab5cfb98177
samir28/Proyectos-
/funciones con listas.py
737
3.65625
4
def sumar_lista(lista): suma = 0 for x in range(len(lista)): suma = suma + lista[x] return suma def mayor_lista(lista): may = lista[0] for x in range(1,len(lista)): if lista[x] > may: may = lista[x] return may def menor_lista(lista): men = lista[0] for x in range(1,len(lista)): if lista[x] < men: men = lista[x] return men #bloque principal lista_valores = [10, 56, 23, 120, 94] print("la lista completa es: ") print(lista_valores) print("la suma de todos los valores es: ", sumar_lista(lista_valores)) print("el mayor elemento de la lista es: ", mayor_lista(lista_valores)) print("el menor elemento de la lista es: ", menor_lista(lista_valores))
95b098a2ba33cf02160677b5ceb3e871e8548a3d
simzam/solutions_digital_dice
/p15.py
2,470
4.0625
4
"""Problem 15: How Long is the Wait Simulation of a queue in a deli store using FCFS principle. The customers in the queue are served by a number of "workers". The arrival of customers are modeled as Poisson process with a fixed rate. The service time of the workers are also simulated as a Poisson process with a fixed rate. This simulation attempts to answer the following questions: 1) What is the average time (wait+service) for a customer? 2) What is the maximum time for a customer? 3) What is the average length of the waiting queue? 4) What is the maximum length of the waiting queue? 5) What fraction of time is spent idle by the clerk(s)? """ import numpy as np def simulate(workers, opening_seconds, customers_rate, service_rate): queue = [] queue_max = 0 customer_total_amount = 0 customer_total_time = 0 customer_max_time = 0 num_customers = 0 idle_time = 0 for i in range(opening_seconds): customer_total_amount += len(queue) if len(queue) > queue_max: queue_max = len(queue) queue = [waiting_time + 1 for waiting_time in queue] arrival = np.random.poisson(lam=customers_rate) if arrival != 0: queue.append(0) if len(queue) > 0: serve = np.random.poisson(lam=service_rate) if serve > 0: customer_time = queue[0] if customer_time > customer_max_time: customer_max_time = customer_time customer_total_time += customer_time queue.pop(0) num_customers += 1 else: idle_time += 1 average_time_spent = customer_total_time / num_customers average_length_queue = customer_total_amount / opening_seconds percent_no_customers = idle_time / opening_seconds print("average wait time {}".format(average_time_spent)) print("max wait time {}".format(customer_max_time)) print("average queue length {}".format(average_length_queue)) print("maximum queue length {}".format(queue_max)) print("idle time {}".format(percent_no_customers)) def main(): arriving_customers_hour = 30 serving_customers_hour = 40 seconds_hour = 3600 opening_hours = 10 opening_seconds = opening_hours * seconds_hour simulate(1, opening_seconds, arriving_customers_hour / seconds_hour, serving_customers_hour / seconds_hour) if __name__ == '__main__': main()
2f947514b3b1d5c6286ace3edf414cf4016f5d03
allenai/pubmedextract
/pubmedextract/corvid/table.py
9,530
3.8125
4
""" The Table class is a physical representation of tables extracted from documents This code was written by Kyle Lo. https://github.com/allenai/corvid/edit/master/corvid/table/ """ from typing import List, Dict, Tuple, Union, Iterable, Callable import numpy as np def format_grid(grid: List[List[str]]) -> str: """ e.g. input: [['a', 'b', 'c'], ['d', 'e', 'f']] output: 'a\tb\tc\nd\te\tf' printed: > a b c > d e f Source: https://stackoverflow.com/questions/13214809/pretty-print-2d-python-list""" if any([len(row) != len(grid[0]) for row in grid]): raise Exception('Grid missing entries (i.e. different row lengths)') g = [[cell if len(cell) > 0 else ' ' for cell in row] for row in grid] lens = [max(map(len, col)) for col in zip(*g)] fmt = '\t'.join('{{:{}}}'.format(x) for x in lens) return '\n'.join([fmt.format(*row) for row in g]) class Cell(object): """A Cell is a single unit of data in a Table separated from other Cells by whitespace and/or lines. A Cell corresponds to its own row and column index (or indices) disjoint from those of other Cells.""" def __init__(self, tokens: List[str], index_topleft_row: int, index_topleft_col: int, rowspan: int = 1, colspan: int = 1): self.tokens = tokens self.index_topleft_row = index_topleft_row self.index_topleft_col = index_topleft_col self.rowspan = rowspan self.colspan = colspan def __repr__(self): return ' '.join([str(token) for token in self.tokens]) def __str__(self): return ' '.join([str(token) for token in self.tokens]) @property def indices(self) -> List[Tuple[int, int]]: """Returns a list of indices for iterating over the Cell in top-to-bottom, left-to-right order. For example, a 2x2 Cell starting at [1, 2] will return [(1, 2), (1, 3), (2, 2), (2, 3)].""" return [(self.index_topleft_row + i, self.index_topleft_col + j) for i in range(self.rowspan) for j in range(self.colspan)] def to_json(self) -> Dict: """Serialize to JSON dictionary""" json = { 'tokens': self.tokens, 'index_topleft_row': self.index_topleft_row, 'index_topleft_col': self.index_topleft_col, 'rowspan': self.rowspan, 'colspan': self.colspan } return json # TODO: consider analogous method that returns all indices given a (multispan) cell class Table(object): """A Table is a collection of Cells. Visually, it may look like: > | header | > | col1 | col2 | col3 | > row1 | a | b | c | > row2 | d | e | f | These Cells can be stored in two formats within a Table: (*) A grid-style format mimics a 2D matrix-like representation. It provides the concept of rows and columns, which induces a method of indexing using an [i,j] operator. Multirow/column Cells are treated in the grid-style format as having multiple indices that return the same Cell object. For example: > [0,0] | [0,1] header | [0,2] header | [0,3] header | > [1,0] | [1,1] col1 | [1,2] col2 | [1,3] col3 | > [2,0] row1 | [2,1] a | [2,2] b | [2,3] c | > [3,0] row2 | [3,1] d | [3,2] e | [3,3] f | s.t. the same `header` Cell can be access via `[0,1]`, `[0,2]` or `[0,3]` (*) A list-style format handles multirow/column Cells by treating each Cell object (regardless of its size) as an individual item read from the Table in left-to-right, top-to-down fashion. > [0] > [5] col3 > [10] row2 > [1] header > [6] row1 > [11] d > [2] > [7] a > [12] e > [3] col1 > [8] b > [13] f > [4] col2 > [9] c Here, each Cell is treated as a single element of the list, regardless of its row/colspan. """ def __init__(self, grid: Iterable[Iterable[Cell]] = None, cells: Iterable[Cell] = None, nrow: int = None, ncol: int = None): assert bool(grid is not None) ^ bool(cells and nrow and ncol) if grid is not None: self.grid = np.array(grid) assert self.nrow > 0 and self.ncol > 0 self.cells = self._cells_from_grid(grid=self.grid) if cells is not None: self.cells = list(cells) self.grid = self._grid_from_cells(cells=self.cells, nrow=nrow, ncol=ncol) @property def nrow(self) -> int: return self.grid.shape[0] @property def ncol(self) -> int: return self.grid.shape[1] @property def shape(self) -> Tuple[int, int]: return self.grid.shape def __getitem__(self, index: Union[int, slice, Tuple]) -> \ Union[Cell, List[Cell]]: """Indexes Table elements via its grid: * [int, int] returns a single Cell * [slice, int] or [int, slice] returns a List[Cell] or via its cells: * [int] returns a single Cell * [slice] returns a List[Cell] """ if isinstance(index, tuple): grid = self.grid[index] if isinstance(grid, Cell): return grid elif len(grid.shape) == 1: return grid.tolist() else: raise IndexError('Not supporting [slice, slice]') elif isinstance(index, int) or isinstance(index, slice): return self.cells[index] else: raise IndexError('Only integers and slices') def __repr__(self): return str(self) def __str__(self): return format_grid([[str(cell) for cell in row] for row in self.grid]) def _cells_from_grid(self, grid: np.ndarray) -> List[Cell]: """Create List[Cell] from a 2D numpy array of Cells""" cells = [] nrow, ncol = grid.shape is_visited = [[False for _ in range(ncol)] for _ in range(nrow)] for i in range(nrow): for j in range(ncol): if is_visited[i][j]: continue else: cell = grid[i, j] cells.append(cell) for index_row, index_col in cell.indices: is_visited[index_row][index_col] = True return cells def _grid_from_cells(self, cells: List[Cell], nrow: int, ncol: int) -> np.ndarray: """Create 2D numpy array of Cells from a list of Cells & dimensions""" grid = np.array([[None for _ in range(ncol)] for _ in range(nrow)]) for cell in cells: for i, j in cell.indices: if grid[i, j] is None: grid[i, j] = cell else: raise ValueError('Multiple cells inserted into grid[{},{}]' .format(i, j)) for i in range(nrow): for j in range(ncol): if grid[i, j] is None: raise ValueError('No cell in grid[{},{}]'.format(i, j)) # index_row, index_col = 0, 0 # for cell in cells: # # insert copies of cell into grid based on its row/colspan # for i in range(index_row, index_row + cell.rowspan): # for j in range(index_col, index_col + cell.colspan): # grid[i, j] = cell # # # update `index_row` and `index_col` by scanning for next empty cell # # jump index to next row if reach the right-most column # while index_row < nrow and grid[index_row, index_col]: # index_col += 1 # if index_col == ncol: # index_col = 0 # index_row += 1 # # # check that grid is complete (i.e. fully populated with cells) # if not grid[-1, -1]: # raise ValueError('Cells dont fill out the grid') return grid def to_json(self) -> Dict: """Serialize to JSON dictionary""" json = { 'cells': [c.to_json() for c in self.cells], 'nrow': self.nrow, 'ncol': self.ncol } return json """ Handles loading of Tables from inputs other than `grid` or `cells`. Loader design chosen because easier to work with when start subclassing Cell and Table as opposed to needing to override @classmethods """ class CellLoader(object): def __init__(self, cell_type: Callable[..., Cell]): self.cell_type = cell_type def from_json(self, json: Dict) -> Cell: cell = self.cell_type(**json) return cell class TableLoader(object): def __init__(self, table_type: Callable[..., Table], cell_loader: CellLoader): self.table_type = table_type self.cell_loader = cell_loader def from_json(self, json: Dict) -> Table: cells = [self.cell_loader.from_json(d) for d in json['cells']] kwargs = {k: v for k, v in json.items() if k not in 'cells'} table = self.table_type(cells=cells, **kwargs) return table
ba6c9018cdc16a044601c702e07da661a6aeb804
darkerego/solutions
/dashitize.py
872
4.375
4
""" Given a number, return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. Ex: dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5' """ def dashatize(num): """ Gross and hacky, i know, i know """ if num is None: return 'None' if num == 0: return '0' num = str(num) num = num.strip('-') ret = '' c = 0 for digit in str(num): if int(digit) % 2 != 0: if c == 0 and len(str(num)) == 1: ret += digit elif c == 0 and len(str(num)) > 1: ret += digit + '-' elif c == len(str(num)) -1: ret += '-' + digit else: ret += '-' + digit + '-' else: ret += digit c += 1 ret = ret.replace('--', '-') return ret
e035f4cdb9450d143f49b99551e6d5ee91b907ac
toshhPOP/SoftUniCourses
/Python-Advanced/Exam_Practice/list_pureness.py
691
3.5625
4
from collections import deque def best_list_pureness(nums, k): data = {} nums = deque(nums) for rotation in range(k + 1): result = sum([index * number for index, number in enumerate(nums)]) data.update({rotation: result}) nums.rotate(1) max_pureness = max(data.values()) for key, value in data.items(): if max_pureness == value: return f"Best pureness {value} after {key} rotations" test = (('what',4, 3, 2, 6), 4) result = best_list_pureness(*test) print(result) test = ([7, 9, 2, 5, 3, 4], 3) result = best_list_pureness(*test) print(result) test = ([1, 2, 3, 4, 5], 10) result = best_list_pureness(*test) print(result)
7a1691afd8e457fa331edd203eb1af997f91f148
fank-cd/python_leetcode
/Problemset/palindrome-partitioning/palindrome-partitioning.py
470
3.796875
4
# @Title: 分割回文串 (Palindrome Partitioning) # @Author: 2464512446@qq.com # @Date: 2019-12-03 11:48:28 # @Runtime: 92 ms # @Memory: 11.8 MB class Solution: def partition(self, s): res = [] self.helper(s, [],res) return res def helper(self,s, tmp,res): if not s: res.append(tmp) for i in range(1, len(s) + 1): if s[:i] == s[:i][::-1]: self.helper(s[i:], tmp + [s[:i]],res)
a59282ac9a57b82ec060b612d942f2e227acdea1
RustPython/RustPython
/extra_tests/snippets/syntax_nested_control_flow.py
683
3.71875
4
# break from a nested for loop def foo(): sum = 0 for i in range(10): sum += i for j in range(10): sum += j break return sum assert foo() == 45 # continue statement def primes(limit): """Finds all the primes from 2 up to a given number using the Sieve of Eratosthenes.""" sieve = [False] * (limit + 1) for i in range(2, limit + 1): if sieve[i]: continue yield i for j in range(2 * i, limit + 1, i): sieve[j] = True assert list(primes(1)) == [] assert list(primes(2)) == [2] assert list(primes(10)) == [2, 3, 5, 7] assert list(primes(13)) == [2, 3, 5, 7, 11, 13]
06e83803a3678f52b9440d3f4638f62ff150544a
lgauthereau/lgauthereau.github.io
/python/trialmethod.py
306
3.734375
4
def method_one(): print("look I'm a method") def method_two(name): #because it is executed in line 8, name is defined as "Brandon" print("about to call our first method for " + name) method_one() #above is where the method is inside the method method_two("Brandon")
f1acef2e2802c79c6ffd74b1b357fb84aeaf2d26
Kyrylo-Kotelevets/NIX_python
/Trainee/9.py
762
4.46875
4
""" создайте функцию-генератор, которая принимает на вход два числа, первое - старт, второе - end. генератор в каждом цикле должен возвращать число и увеличивать его на 1 при итерации генератор должен начать с числа start и закончить итерации на числе end т.е. при вызове for i in my_generator(1, 3): print(i) в консоли должно быть: 1 2 3 """ def my_generator(start, end): """Function-generator with range of numbers""" for item in range(start, end + 1): yield item for i in my_generator(1, 3): print(i)
68cc613981da30f88de98d70544c627a36320f3d
lpgarzonr/PythonKatas
/reverseOnlyLetters.py
407
3.734375
4
from queue import LifoQueue def reverseOnlyLetters(string): stack = LifoQueue() reversedStr = '' for char in string: if char.isalpha(): stack.put(char) for char in string: if char.isalpha(): lastLetter = stack.get(char) reversedStr += lastLetter else: reversedStr += char return reversedStr print('expect: Qedo1ct-eeLg=ntse-T!') print(reverseOnlyLetters('Test1ng-Leet=code-Q!'))
3efc83e32ce761116a15a9108141520fb1ecc492
yuseungwoo/baekjoon
/10474.py
133
3.625
4
# coding: utf-8 while True: a, b = map(int, input().split()) if not a and not b: break print(a//b, a%b, "/", b)
70dd9be154cb948fa4638589e034ea5977f57994
MaryJane-Ifunanya/Cursoemvideo
/exercicio052.py
527
3.984375
4
print('''Faça um programa que leia um número inteiro e diga se ele é ou não um número primo''') cont = 0 num = int(input('Digite um numero:')) for c in range(1, num+1): if num % c == 0: print('\033[33m', end='') cont += 1 else: print('\033[31m', end='') print('{}'.format(c), end=' ') print('\n\033[mO número {} foi divisivel {} vazes'.format(num, cont)) if cont == 2: print('E por isso ele é \033[35mPRIMO!\033[m') else: print('E por isso ele não é \033[35mPRIMO!\033[m')
aaff2840112da2ff60a32ba852d181885249aa3c
CrissDefaz001/03_DesktopApps
/04_Python/01_Formas/Rombos.py
656
3.53125
4
print('Rombo normal:') num = 8 if(num%2 == 0): num2 = int(num/2) else: num2 = int((num+1)/2) for i in range(num2, 0, -1): for j in range(i, num2): print('* ', end="") print('') for i in range(0, num2): for j in range(i, num2): print ('* ',end="") print('') print('\nRombo con forma:\n') if(num%2 == 0): num +=1 for i in range(0, num, 2): for j in range(i+2,num, 2): print('. ', end='') #Remover '.' por '' for k in range(0, i+1): print('* ', end='') print('') for i in range(num, 1, -2): for j in range(num+2, i, -2): print('. ', end='') for k in range(i-2, 0, -1): print('* ',end='') print('')
7dbc3798cd8eacbf3383578e7ba6af486bf04b73
BubuYo/religious
/array/219. Contains Duplicate II.py
491
3.5
4
class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ l, remain = len(nums), 0 for idx, i in enumerate(nums): if idx + i + 1 >= l: return True remain = max(i, remain - 1) if not any([i, remain]): return False return True if __name__ == '__main__': s = Solution() nums = [3, 2, 1, 0, 4] a = s.canJump(nums) print(a)
3f3be192651ae5345fe41b48f121840d0e53522a
franklaercio/Python-PC-UFRN
/Lista 02/questao02.py
379
4.0625
4
contador = 0 numero = 0 maior = 0 menor = 0 while(contador < 4): numero = int(input("Informe um número: ")) if contador == 0: maior = numero menor = numero if numero < menor: menor = numero if numero > maior: maior = numero contador += 1 else: print("--------------------------") print("O maior número é: ", maior) print("O menor número é: ", menor)
82b94fffc093bf25c4bf8a174c877c6c249ca398
doubledherin/datastructs_algorithms_exercises
/Chapter03_BasicDataStructures/isPalindrome.py
390
3.671875
4
from deque import Deque def isPalindrome(s): d = Deque() for char in s: d.addFront(char) while d.size() > 1: item1 = d.removeFront() item2 = d.removeRear() if item1 != item2: return False return True if __name__ == '__main__': print isPalindrome("radar") print isPalindrome("hannah") print isPalindrome("boat")
e830a75ff3a5648e839e5fe92fada4ed0bd847b9
abalcorin/DevNet_vCC_assignments
/abalcorin_DevNet_vCC_Team0_Camp1_Day2_assign1_Assignment_02.py
638
3.921875
4
""" Programmability Black Belt Apprentice (Level1) https://github.com/Devanampriya/DevNet_vCC_Team0/blob/master/Camp1_Day2_assign2 Participant: ALBREN ALCORIN Assignment Write a program (in Python 3) to guess a randomly generated number between 1 and 10. For Example: Guess the number: 4 Wrong, try again! Guess the number: 8 Correct! Hint: Figure out which library the “randint” function belongs to. """ #Code from random import randint number=(randint(1, 10)) while True: numinput = input('Guess the number: ') if str(number) != numinput: print ('Wrong, try again!') else: print('Correct!') break
a3548cba0549c0e475ab89cdb506c7baee03a25b
brunopontes90/Cursos
/Python/Mundo 1/desafios/desafio04.py
484
4.15625
4
print('===== desafio 04 ====='.upper()) ler = input('Digite algo: ') print('O tipo primitivo é? ', type(ler)) print('É alfabetico? ', ler.isalpha()) print('É alfa numerico? ', ler.isnumeric()) print('Pode ser impresso? ', ler.isprintable()) print('É apenas numeros? ', ler.isnumeric()) print('Esta em minusculo? ', ler.islower()) print('Esta em maiusculo? ', ler.isupper()) print('Somente espaços? ', ler.isspace()) print('Esta capitalizada (Titulo)? ', ler.istitle())
c91f5c4e9efe10d796cb52e0c2cf95541eacbc63
barbarahf/Python_DAW
/Practicas/Adivina.py
1,373
3.890625
4
# Ejercicio 5 import random __author__ = "Barbara Herrera Flores" continuar = True while continuar == True: # El usuario decide con que rango de valores jugar print("Introduce un rango de dos numeros para jugar, por ejemplo entre 5 y 18 ") num1 = input("Numero 1: ") num2 = input("Numero 2: ") # Comprobar intups para evitar salida abrupta en caso de error while num1.isdigit() == False or int(num1) < 1 or int(num2) == int(num1): num1 = input("Error, numero 1: ") num2 = input("Error, numero 2: ") if int(num1) > int(num2): aux = num1 num1 = num2 num2 = aux # Hay que castear los inputs, son strings en python. pensado = random.randrange(int(num1), int(num2)) # Generar valores aleatorios jugada = input("Introduce un numero para adivinar entre " + num1 + " y " + num2 + " :") if int(pensado) == int(jugada): print("Felicidades, adivinaste el numero ", pensado) continuar = False else: again = "" # Bucle para jugar otra vez en caso de no acertar while again not in ("S", "N"): # Upercase para aceptar minusculas. again = input("Lo siento, no lo has adivinados ¿quieres jugar otra vez? S/N ").upper() if "S" == again: continuar = True elif again == "N": continuar = False
d8737c0f1c80dfb403b01cf2e5750ea554df6f6b
xiaohuanlin/Algorithms
/Leetcode/257. Binary Tree Paths.py
979
4.03125
4
''' Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if root is None: return [] result = [] self.dfs(root, "", result) return result def dfs(self, root, pre_str, result): if root.left is None and root.right is None: result.append(pre_str + str(root.val)) if root.left: self.dfs(root.left, pre_str + str(root.val) + "->", result) if root.right: self.dfs(root.right, pre_str + str(root.val) + "->", result)
4d997f791daad95d180516ead2c396ec173d0b12
pgupta371/104
/median.py
695
3.6875
4
import csv with open("data104.csv", newline = "") as f: reader = csv.reader(f) fileData = list(reader) fileData.pop(0) #print(file_data) #sorting data to get the height of people newData = [] for i in range(len(fileData)): num = fileData[i][1] newData.append(float(num)) # get the median n=len(newData) newData.sort() #use floor division to ge thte nearest whole number #floor div is shown by // if n%2 == 0: #1st number median1=float(newData[n//2]) #2nd number median2=float(newData[n//2-1]) median=(median1+median2)/2 else: median=newData[n//2] print(n) print("median is -"+ str(median)) print
cf6125e1b39d2412551269caa1408dbf3938762d
jro867/project3
/ArrayQueue.py
637
3.578125
4
#!/usr/bin/python3 import pprint class ArrayQueue: def __init__(self): self.list = [] # # print("NODE:") # print(self.list) # for node in self.list.getNodes(): # print("NODE: ") # print(node) # def point_sorting(self, point): # print('X value: ', point.x()) # return point.x() def is_empty(self): return False #If the size of the array is not zero #retun false : True def dumper(self): print("Content2: ", self.list) def insert(self, node): self.list.append(node) print("WHAT??: ", self.list)
ff1985c0ecc2c15c78142e04b6337facf68f19e4
redherring2141/Python_Study
/Python_200/Intermediate/ex_076_1.py
125
3.859375
4
# Ex076 - Extracting a string from specific range of a string txt = 'python' for i in range(len(txt)): print(txt[:i+1])
957ed02ad10d1bce62e7215d2a6283e8b16a6996
siyan/starbucks
/src/com/sywood/starbucks/andi/Python/ucfcontest/plates.py
694
3.515625
4
def update(poles, i): temp = list(poles) for j in range(n): temp[j] -= 2.5 temp[i] = speed return tuple(temp) def possible(poles): if any([i <= 0 for i in poles]): return False if poles in memo: return True else: memo.add(poles) return any(possible(update(poles, i)) for i in range(n)) for i in range(int(input())): n, speed = [int(i) for i in input().split()] poles = tuple([speed for i in range(n)]) memo = set() # not dp, just a record to see if chester ever comes back to a certain state print("Circus Act " + str(i + 1) + ":") print("Chester can do it!" if possible(poles) else "Chester will fail!")
2b5709c6045d2e2814b8d06694c355f34bc08547
guillechuma/bioinformatics
/rosalind/reverse_complement.py
526
4.4375
4
# This program calculates the reverse complement of a DNA sequence import sys complement = { 'A':'T', 'T':'A', 'G':'C', 'C':'G' } def reverse_complement(dna): ''' This function recives a DNA string and returns its reverse complement ''' reverse_dna = dna[::-1] reverse_complement = '' for i in reverse_dna: reverse_complement += complement[i] return reverse_complement if __name__ == "__main__": # Take input from user dna = input("Type DNA sequence:") print(f"Reverse complement: {reverse_complement(dna)}")
9b18734c527b3a75ffcfea045e64bd573b931cc8
michaelChen07/studyPython
/cn/wensi/idle/QuickSort.py
2,373
3.640625
4
# coding=utf-8 """快速排序""" # 校验函数,对输入的列表或者元组进行校验 def list_check(pend_list): if not isinstance(pend_list, list) and not isinstance(pend_list, tuple): # 元组列表才能排序 print("输入必须输入列表或者元组") return if isinstance(pend_list, tuple): # 元组转成列表 pend_list = list(pend_list) return pend_list # 三个列表递归实现快排: 优点是比较好理解,小的放到左边,大的放到右边,一样的放到中间, 然后将三个列表加起来变成一个 # 时间复杂度:最理想 O(nlogn) 最差时间O(n^2) def quick_sort(pend_list): if len(pend_list) < 1: return pend_list # 终止条件,没有这个条件就会一直跑下去直到数组越界 key = pend_list[0] left_list = [] middle_list = [] right_list = [] for i in range(0, len(pend_list)): if key > pend_list[i]: left_list.append(pend_list[i]) elif key < pend_list[i]: right_list.append(pend_list[i]) else: middle_list.append(pend_list[i]) return quick_sort(left_list) + middle_list + quick_sort(right_list) # 三行代码搞定快速排序 def quick_sort2(L): if len(L) <= 1: return L return quick_sort2([lt for lt in L[1:] if lt < L[0]]) + [L[0]] + quick_sort2([ge for ge in L[1:] if ge >= L[0]]) # 标准快排 # 递归: # 1. 原问题可以被划分为类似子问题 # 2. 结束条件: i >= j def quick_sort3(L, low, high): i = low # 游标 i j = high # 游标 j if i >= j: return L key = L[low] # 比较的参考值 while i < j: while i < j and L[j] >= key: # j 不断向前,小的放到前面 j -= 1 L[i] = L[j] while i < j and L[i] < key: # i 不断向后, 大的放到后面 i += 1 L[j] = L[i] L[i] = key quick_sort3(L, low, i-1) quick_sort3(L, j+1, high) return L real_list = [3, 34, 1, 45, 12, 3, 6] print("******************* 三个列表递归实现快排 *********************") print(quick_sort(real_list)) print("******************* 三行代码搞定快速排序 *********************") print(quick_sort2(real_list)) print("******************* 标准快速 *********************") print(quick_sort3(real_list, 0, len(real_list)-1))
8cf46ea28080cd13860b49f43b925b73227ff866
masterawr/Python-3-Scripts
/convert_xlsx_csv.py
385
3.578125
4
# Converts all xlsx files in a directory to csv import glob,os import pandas as pd inputdirectory = input('Enter the directory: ') for xls_file in glob.glob(os.path.join(inputdirectory,"*.xls*")): data_xls = pd.read_excel(xls_file, 'Sheet1', index_col=None) csv_file = os.path.splitext(xls_file)[0]+".csv" data_xls.to_csv(csv_file, encoding='utf-8', index=False)
955d3d65ded72ddbc32281bfd1008bc0d5d4d0ff
victoriaBelokobylskaya/PythonBase
/lesson1_6.py
1,050
4
4
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который результат спортсмена составит не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. dist_a = int(input('Введите результат пробежки за первый день: ')) dist_b = int(input('Введите желаемый результат: ')) i = 1 while dist_a < dist_b: dist_a += dist_a / 10 i += 1 print(f'На {i}-й день спортсмен достиг результата — не менее {dist_b} км')
3e38b19deb3f74b8cc72756583dccf2e95a5d3ee
Kabur/bc
/tests.py
273
3.90625
4
import numpy as np x1 = np.array([1, 2, 3, 4, 5]) x2 = np.array([5, 4, 3]) print("x1: ") print(x1) # x1_new = x1[:, np.newaxis] x1_new = x1[np.newaxis, :] # now the shape of s1_new is (5, 1) print("x1_new: ") print(x1_new) # print("x1_new + x2: ") # print(x1_new + x2)
4415d16bd657a447b6993ba8cea39c0405bc95f2
AsuwathamanRC/Python-Programs
/Turtle/PongGame/main.py
1,164
3.703125
4
from turtle import Turtle, Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=800,height=600) screen.bgcolor("black") screen.title("Pong") screen.tracer(0) rightPaddle = Paddle(350,0) leftPaddle = Paddle(-350,0) ball = Ball() score = Scoreboard() screen.listen() screen.onkey(rightPaddle.move_up,"Up") screen.onkey(rightPaddle.move_down,"Down") screen.onkey(leftPaddle.move_up,"w") screen.onkey(leftPaddle.move_down,"s") game_is_on = True while game_is_on: time.sleep(ball.move_speed) screen.update() ball.move() # Detect collision with right and left paddle x_pos = ball.xcor() if x_pos>=330 and ball.distance(rightPaddle)<=50 or x_pos<=-330 and ball.distance(leftPaddle)<=50: ball.x *= -1 ball.move_speed *= 0.9 # Detect if ball misses the paddle if x_pos>=380 or x_pos<=-380: if x_pos>=380: score.l_point() else: score.r_point() ball.resetBall() if score.lScore>=10 or score.rScore>=10: score.updateWinner() game_is_on = False screen.exitonclick()
c8afb1f86e5c73d5291cd7bca2cbf34a297da7ff
mahmudz/UriJudge
/URI/URI/2313.py
573
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 21 12:16:30 2017 @author: Matheus """ a,b,c = input().split() a,b,c = int(a),int(b),int(c) entrou = False if(a==b and b==c): print ("Valido-Equilatero") entrou = True elif(a==b or b==c or a==c): print ("Valido-Isoceles") entrou = True elif((a+b)>c and (a+c)>b and (b+c)>a): print ("Valido-Escaleno") entrou = True if(entrou == True): if((a*a)==(b*b+c*c) or (b*b)==(a*a+c*c) or (c*c)==(a*a+b*b)): print ("Retangulo: S") else: print ("Retangulo: N") else: print ("Invalido")
724b821e5c842a7d13b0d78c011a6456711dec63
HoangTan351/hoangtan_btpython_buoi2
/Bai 2.py
572
3.71875
4
# bai 2 import math print("nhap x: ",end="") x=float(input()) print("nhap n: ",end="") n=int(input()) s1=s2=s3=0.0 print("S1 = 1 + x + x^2 + x^3 + ... + x^n=",end="") for i in range(n+1): s1+= pow(x,i) i+=1 print(s1) print("S2 = 1 - x + x^2 - x^3 +...+(-1)^n*x^n=",end="") for i in range(n+1): if i%2==0: s2+= pow(x,i) else: s2+= (-1)*pow(x,i) i+=1 print(s2) print("S3 = 1 + x/(1!) + x^2/(2!) + x^3/(3!) +...+x^n/(n!)=",end="") for i in range(n+1): s3+=(pow(x,i)/math.factorial(i)) i+=1 print(s3)
18609ece35c5896dfeeb82e00fa2908698615e13
99003607/Advanced-python
/11_exception_handle.py
1,046
3.734375
4
# exception handling ''' print("before"); i=10; j=0; #here divsion by zero is not possible so it will give exception k= i/j; print("k value:",k); print("after"); ''' ''' output=. Traceback (most recent call last): File "11_exception_handle.py", line 6, in <module> k= i/j; ZeroDivisionError: division by zero ''' ''' 1)name error 2)index error 3)zerodivision error etc ''' #syntax ''' try: statement(s) except ExceptionType: handle here ''' #exception i=10; j=0; #put j=1; and run l= [1,2,3,4]; try: print("before"); i=i+x; # name error->no expection for name l[10]=100; #index error k= i/j; #ZeroDivisionError #print("k value:",k); except ZeroDivisionError as ex: print("ZeroDivisionError:",ex.args); except IndexError as ex: print("IndexError",ex.args); except Exception as ex: print("Main Exception",ex.args); else: print("in else:no exception");#print if no expection finally: print("program end"); #print after all ends
dacc30c673932f5e92a7b2ad14d03bc4f85949f2
demo112/1807
/regex/project/ID_check.py
489
3.546875
4
import re ID_card = input("请输入身份证号") if len(ID_card) == 18: pattern = r"(?P<province>\d{4})(?P<city>\d{2})(?P<date>\d{8})(?P<code>\d{4}|\d{3}X)" province = re.search(pattern, ID_card).group('province') city = re.search(pattern, ID_card).group('city') date = re.search(pattern, ID_card).group('date') code = re.search(pattern, ID_card).group('code') print(province, city, date, code) else: print("您输入的身份证号有误请重新输入")
c1cc5acfbec4d262bfc002565428cd8a679a2773
aker4m/c_algorithm
/python3/ch02/intary.py
352
3.65625
4
NUMBER = 5 def int_input(string): return int(input(string)) if __name__ == '__main__': list_number = [] for i in range(0, NUMBER): list_number.append(int_input("list_number[{}] : ".format(i))) print("각 요소의 값") for i in range(0, len(list_number)): print("list_number[{}] = {}".format(i, list_number[i]))
f0cffd02d79fc735a791dd338e2e39a8ed90a848
csYuryV/geekbrains_PyBasic
/04 Lesson/PracticalTask/01 Exercise.py
1,010
4.375
4
""" Python Basic Lesson 04, Exercise 01 Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. 20191019 Sikorskiy Yuriy cs.yury.v@pn.me """ payroll = lambda productionInHours, paymentRatePerHour, premium: (productionInHours * paymentRatePerHour) + premium try: wage = payroll(float(input('Выработка в часах: ')), float(input('Ставка в час: ')), float(input('Премия: '))) except ValueError: print('Ошибка значения') exit() print(f'Расчет заработной платы сотрудника: {wage:.2f}')
f4c314ed3d0efb1a4ce2a977327dc92c7337bcf3
lcqbit11/algorithms
/medium/binary-tree-preorder-traversal.py
1,485
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.treeNode import TreeNode def binary_tree_pre_order_traversal2(root): res = [] s = [] if root: s.append(root) while s: root = s.pop() res.append(root.val) if root.right: s.append(root.right) if root.left: s.append(root.left) return res def binary_tree_pre_order_traversal1(root, res): if root: res.append(root.val) binary_tree_pre_order_traversal1(root.left, res) binary_tree_pre_order_traversal1(root.right, res) def binary_tree_pre_order_traversal(root): """ 给定一棵树,返回其前序遍历的结点的数值。 :param root: TreeNode(int) :return: List[int] """ res = [] tmp = [(1, root)] while tmp: p = tmp.pop() if not p[1]: continue if p[0]: tmp.extend([(1, p[1].right), (1, p[1].left), (0, p[1])]) else: res.append(p[1].val) return res if __name__ == "__main__": """ 1 4 2 3 6 """ root = TreeNode(1) root.left = layer2_left = TreeNode(4) root.right = layer2_right = TreeNode(2) layer2_left.left = TreeNode(3) layer2_left.right = TreeNode(6) # print(binary_tree_pre_order_traversal(root)) # res = [] # binary_tree_pre_order_traversal1(root, res) # print(res) print(binary_tree_pre_order_traversal2(root))
b21db48d5f25c5f558d7db33150553179379628e
yhx0105/leetcode
/05_liangbiao/02_liangbiaozhongdaoshudikgejiedian.py
1,088
3.75
4
""" 输入一个链表,输出该链表中倒数第k个结点。 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: #读出来放到,列表里面,完成操作,空间时间复杂度O(n) def FindKthToTail1(self, head, k): # write code here #判断是否为空 if not head: return None res=[] while head: res.insert(0,head) head=head.next if k>len(res) or k==0: return None return res[k-1] def FindKthToTail2(self, head, k): p1=head p2=head if not p1 or k<=0: return None while k>1: if p2.next!=None: p2=p2.next k-=1 else: return None while p2.next: p1=p1.next p2=p2.next return p1 if __name__ == '__main__': l1=ListNode(1) l2=ListNode(2) l3=ListNode(3) l1.next=l2 l2.next=l3 s=Solution() print(s.FindKthToTail2(l1,1))
343c0f44c05302445634cc99c1147dfa0c3dd13c
ne1son172/GB2-algo-and-data-structures
/HW1/task8.py
498
4.0625
4
# Определить, является ли год, который ввел пользователем, високосным или не високосным while True: year = input('Enter q for quit or enter some year >>> ') if year == 'Q' or year == 'q': break else: year = int(year) temp = year % 4 if temp == 0: print('{} year is leap-year'.format(year)) else: print("{} is regualr year".format(year))
d829c9de800808d0f52455b4db878156880c74fa
tchimih/link_query
/engine/analyse.py
5,088
3.6875
4
# coding: utf-8 from __future__ import division import re def get_stat_eff(n ,m, t): """ This function will compute the : - Worst; - Best; - Random. Efficiencies according the input variables, as follow: ------------------------------------------------------ (1) n: # Nodes (2) m: # Edges (3) t: # Tests """ density = ((2*m)/(n*(n-1))) # Density that will be used in rand strategy max_links = (n*(n-1))/2 # It will be used in worst strategy best_eff = 0 worst_eff = 0 rand_eff = 0 shift = 1 cpt = 1 cpt_rand = 1 RAND_MAX_ITER = max_links - m for i in range(0, t+1): # Now we will accumulate our best, worst and rand strategies if ( i <= t ): # We are in the case that not all links have been discovered # Accumulate the best_eff if (i <= m): # cause we started at 0 # Not all links had been discovered best_eff += i else: # All links have been discovered best_eff += m if ( i > (RAND_MAX_ITER)): # Now we are in the case where the worst strategy operates and start # to accumulate, Note the the maximum number of possible links is # n*n-1/2 and the worst will discover the links at the # end. worst_eff += cpt cpt += 1 else: rand_eff += shift # Random efficacity using linear equation rand_eff = density*0.5*t*t return best_eff, rand_eff, worst_eff def get_max_eff(nTest, m): """ This function will try to get the max efficiency using the best strategy formula and try to compute the surfaces Variables: ---------- (1) nTest: Number of tests used ! (2) m : Number of the graph links! """ max_val = 0 if (nTest <= m): for i in (0, nTest): max_val += i return max_val else: for i in range(0,m): max_val += i max_val += (nTest-m)*m return max_val def get_min_eff(nTest, m, n): """ This function will try to get the min efficiency using the worst strategy formula and try to compute the surfaces Variables: ---------- (1) nTest: Number of tests used ! (2) m : Number of the graph links ! (3) n : Number of nodes ! """ MAX_LINKS = (n*(n-1))/2 min_val = 0 if (nTest < MAX_LINKS): return 0 else: MAX_ITER = nTest * ( ( n * ( n - 1 ) / 2 ) - m ) for i in range(1, int(MAX_ITER)): min_val += i return min_val def get_rand_eff(nTest, m, n): """ This function will try to get the random efficiency using the pure random strategy formula and try to compute the surfaces Variables: ---------- (1) nTest: Number of tests used ! (2) m : Number of the graph links ! (3) n : Number of nodes ! """ rand_val = 0 d = (2*m)/(n*(n-1)) return int(0.5*d*pow(nTest,2)) def extract_eff(fin, n, m): """ This function will compute the relative, absolute and normalized efficiencies from a file given as an input of the function [1] -------------------------------------- [1]: fin is the file given as an input """ file_in = open(fin, "r") t = {} abs_eff = 0 rel_eff = 0 norm_eff = 0 rand_eff = 0 tmp1 = 0 compteur = 0 shift = 1 tp = 0 fp = 0 density = ((2*m)/(n*(n-1))) * 100 for text in file_in: text = text.replace('\n','') tmp = re.split(' ', text) if int(tmp[0]) in list(t.keys()): # It mens that in this iteration another node has been discovered t[int(tmp[0])] += 1 else: t[int(tmp[0])] = 1 for i in range(0, int(max(t.keys())+1)): # At each step we check how many links have been discovered :) if i in t.keys(): abs_eff = abs_eff + 1 + compteur compteur += 1 tp += 1 #tmp1 = abs_eff #print i, " ", abs_eff else: fp += 1 abs_eff = abs_eff + compteur nTest = int(max(t.keys())) min_val = get_min_eff(nTest, m, n) max_val = get_max_eff(nTest, m) rand_val= get_rand_eff(nTest, m, n) norm_eff = (abs_eff - min_val) / (max_val-min_val) norm_eff_rand = (rand_val - min_val) / (max_val-min_val) rel_eff = (norm_eff) / (norm_eff_rand) prec = tp / (tp+fp) recall = tp / m fscore = (2*prec*recall) / (prec+recall) print "---------------------------------------------------" print " Statistical Informations" print "- Precision:\t", prec print "- Fscore:\t", fscore print "- Recall:\t", recall print "---------------------------------------------------" file_in.close() print " NOMBRE DE TEST:", nTest return abs_eff, rel_eff, norm_eff
b7bfbbc130f2d70c826a76066ad57e5daa5ec562
WardMaes/aoc-2020
/day_01/01.py
968
4.09375
4
def get_tuple(arr, sum): # Returns a tuple. The sum of these 2 values equals sum arr_sorted = sorted(arr) l = 0 r = len(arr) - 1 while l < r: if (arr_sorted[l] + arr_sorted[r] == sum): return [arr_sorted[l], arr_sorted[r]] elif (arr_sorted[l] + arr_sorted[r] < sum): l += 1 else: r -= 1 return [-1, -1] def get_triple(arr, sum): # Returns a triple. The sum of these 3 values equals sum arr_sorted = sorted(arr) i = 0 l = 0 r = len(arr) - 1 while(l < r): val1, val2 = get_tuple(arr_sorted, sum - arr_sorted[i]) if (val1 > -1): return arr_sorted[i], val1, val2 else: l += 1 i += 1 return -1, -1, -1 lines = open("input.txt", "r") strings = lines.read().splitlines() numbers = list(map(int, strings)) # Part 1 val1, val2 = get_tuple(numbers, 2020) print(val1, val2, " => ", val1 * val2) # Part 2 v1, v2, v3 = get_triple(numbers, 2020) print(v1, v2, v3, " => ", v1 * v2 * v3)
45b9882b581d7965febbc27263d07f084365a8ef
iidodson/MOA-Python
/python-cheatsheet.py
4,733
3.9375
4
from sys import argv from os.path import exists ############# Print Statements ############# print("hello World") ### Multi-line prints print(""" Alight, so you said you like food ad you just figuted out how to do multi-line prints Nice! """) ############# Operators ### Mdoulo remainder = 10%3 print(remainder) ### Addition num1 = 1 num1 += 1 #num1 = num1 + 1 ### Comparators print("is 2 greater than 5", 2>=5) ############# Formatting ############# ### Float float = float(5/2) num = 3 print(num+float) ### F string type_of_people = 10 x = f"There are {type_of_people} types of people." print (x) ### format hilarious = True joke_evaluation = "Isn't this fun? {}" print(joke_evaluation.format(hilarious)) #Converts value to string then concatinates to string its being called by ### Concatination end1 = "H" end2 = "i" print(end1 + end2) ### New Line print("Jan\nFeb\nMar") ### Escape characters \ backlash_cat = "I'm \\ a \\ cat." print(backlash_cat) ### Round function float_num = 3.4444444444 print(round(float_num,2)) ############# Inputs ############# bill = float(input("Tell me, how much was the bill? $")) ### Multi-line input print("How much do you weigh?", end=' ') weight = input() ### Inputs with printf answer = input(f"So your {weight}. Is that right? ") ### sys and argv (inputs from cmd line) script, first = argv # make sure to import argv from sys print(f"The script is called {script}") print(f"Your first variable is {first}") ############# If/Elif/Else Statements ############# answer = input("Am I smart?") if answer == "yes" or answer == "Yes" or answer == "y" or answer == "Y": print("ヽ(´▽`)ノ \n Whoooohoooooo! \n I'm smart") #Or you could do # if answer in ['y','Y', 'yes','Yes']: elif answer == "no" or answer == "No" or answer == "n" or answer == "N": print("*flips table* \n(╯°□°)╯ ┻━┻ \n You gotta be kidding me!") ############# Files ############# ##### Opening a file txt = input("Please enter the filename :") file = open(filename) # default read ### Opening a file for write file = open(filename, 'w') ### Exists if exists(filename) == False: print("It does not exist") ### Writing to a file file.write("Hello World") ### Opening a file for read file = open(filename, 'r') ### Erasing an entire filen file.truncate() ### Reading a file (ouputting it) print(f"Here's your file {txt}:") print(file.read()) ### Sets the position of the file to the first character file.seek(0) ### Prints the current line that is pointed to # consecutive readlines() move the pointer to the next line (like a for loop) # seek can also change the line of the pointer print(file.readline(), end ='') # end = '' removes the \n character that is returned ### Closing a file file.close() ############# Functions #############\ ###nT Taking all arguements as a list def print_two(*args): #don't use numbers in function names arg1, arg2 =args print(f"arg1: {arg1}, arg2: {arg2}") print_two("Indya", "Dodson") ### Normal Functions def print_two_again(arg1, arg2): # standard is to have five arguements or less print(f"arg1: {arg1}, arg2: {arg2}") print_two_again("Indya", "Dodson") def print_none(): print("I got nothing.") print_none() # Returning values def add(num1, num2): return num1 + num2 print(f"1 + 2 = {add(2, 1)}") # Function Looping def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding,errors) return main(language_file, encoding,errors) # Function tuple and Format def test(a, b, c): return a, b, c formula_test = test(1,2,3) print("We'd have {} beans, {} jars and {} crates.".format(*formula_test)) # sotring values from returned values def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates beans, cans, boxes = secret_formula(100) ############# Encoding ############# #a ”byte” a sequence of 8 bits (1s and 0s). # ASCII. This standard maps a number to a letter. # Unicode 32-bit numbe 2^33 or 4,294,967,295 characters # utf-8 means Unicode Transformation Format 8 Bits # f you have raw bytes, then you must use .decode() to get the string # encode() function is used from string to raw_bytes # ”DBES” mnemonic. ”Decode Bytes, Encode Strings” def print_line(line, encoding, errors): next_lang = line.strip() raw_bytes = next_lang.encode(encoding,errors=errors) #encode strings, this turns it into bytes cooked_string = raw_bytes.decode(encoding, errors=errors) #decode bytes, this turns it into strings print(raw_bytes, "<=========>", cooked_string) ############# Encoding ############# split
ea3696c88325d137e823551f72db27469729eb96
Kfirinb/Computational-Biology-Course
/Project 2 - Genetic Algorithms/gridRefactor.py
26,516
3.640625
4
""" Computational Biology: Second Assignment. Developed by CUCUMBER an OrSN Company and Kfir Inbal May 2021. UNAUTHORIZED REPLICATION OF THIS WORK IS STRICTLY PROHIBITED. """ from sys import argv # Basic grid design, courtesy of Auctux: https://www.youtube.com/watch?v=d73z8U0iUYE import pygame import pygame.font import numpy as np import random class Grid: def __init__(self, width, height, offset, screen): self.chuncks_flag = 0 self.columns = 33 self.rows = 33 self.screen = screen self.scale = width / (self.columns) self.size = (self.rows, self.columns) self.grid_array = np.ndarray(shape=(self.size)).astype(int) self.offset = offset self.conditionsArray = [] # Filled @ Def SetConditions self.totalDesiredPopulation = 0 self.setConditions() self.solutionsNextGeneration = [] self.solutionsCurrentGeneration = [] self.currentGrade = 0 # Represents the grade of the best solution self.stuckRate = 0 # Determines for how many iterations the currentGrade field didn't changed. self.bestSolution = 0 self.numberOfSolutionsToHandle = 10 self.expanderRate = 0 self.mode = int(argv[2]) self.iteration_num = 0 def setConditions(self): # Reads the conditions from the input file. counter = 0 file = open(argv[1], "r+") for line in file: if (counter == 50): break lineOfConditions = [] for condition in line.split(): lineOfConditions.append(int(condition)) self.totalDesiredPopulation += int(condition) while len(lineOfConditions) < 8: lineOfConditions.append(int(0)) self.conditionsArray.append(lineOfConditions) counter += 1 file.close() self.totalDesiredPopulation = int(self.totalDesiredPopulation / 2) self.properSorter() def properSorter(self): # Correctly format the conditions (0's before the rest). for lineOfConditions in self.conditionsArray: properFlag = 0 # This flag checks for the sanity of the conditions array. It gives a green light to proceed # iff all 0's are before the non zero conditions. while properFlag == 0: somethingChangedFlag = 0 for index in range(len(lineOfConditions)): if index < len(lineOfConditions) - 1: if lineOfConditions[index] != 0 and lineOfConditions[index + 1] == 0: lineOfConditions[index + 1] = lineOfConditions[index] lineOfConditions[index] = 0 somethingChangedFlag = 1 if somethingChangedFlag == 0: properFlag = 1 def templateConstructor(self): # Creates a basic pattern of solution consisting the conditions. matrixToModify = np.ndarray(shape=(self.size)).astype(int) for x in range(self.rows): for y in range(self.columns): if ((x < 8) and (y < 8)): matrixToModify[x][y] = 3 elif ((x < 8) or (y < 8)): matrixToModify[x][y] = 2 else: matrixToModify[x][y] = 0 return matrixToModify def random2d_array(self, numberOfSolutions=None): # Fills the sub-matrix of 25 X 25 randomly # fulfilling the columns requirements if (numberOfSolutions == None): numberOfSolutions = self.numberOfSolutionsToHandle for _ in range(numberOfSolutions): matrixToModify = self.templateConstructor() col = 0 row = 8 for line in self.conditionsArray: conditionsSum = sum(line) numberOfConditions = len([i for i in line if (i > 0)]) numberOfFreeIndexes = 25 - (conditionsSum + (numberOfConditions - 1)) indexStarter = random.randint(0, numberOfFreeIndexes) if col < 25: for i in range(8): if (line[i] > 0): for j in range(line[i]): matrixToModify[row + indexStarter][col + 8] = 1 row += 1 else: continue conditionsSum = conditionsSum - line[i] numberOfConditions = numberOfConditions - 1 num = 32 - (row + indexStarter) - ((conditionsSum) + (numberOfConditions)) + 2 randnum = random.randint(1, num) for r in range(randnum): row += 1 else: break col += 1 row = 8 if self.mode == 2: # Working on LeMark if len(self.solutionsCurrentGeneration) > 1: bestCurrentSolution = np.copy(self.solutionsCurrentGeneration[-1][0]) gradeMatrixBefore = self.matrixGrade(matrixToModify) gradeCurrentBefore = self.matrixGrade(bestCurrentSolution) copymatrixToModify, copybestCurrentSolution = self.optimizer(np.copy(matrixToModify), np.copy(bestCurrentSolution)) if (self.matrixGrade(copymatrixToModify) > gradeMatrixBefore): matrixToModify = copymatrixToModify if (self.matrixGrade(copybestCurrentSolution) > gradeCurrentBefore): bestCurrentSolution = copybestCurrentSolution self.solutionsCurrentGeneration[-1][0] = bestCurrentSolution self.solutionsCurrentGeneration[-1][1] = self.matrixGrade(bestCurrentSolution) solution = [matrixToModify, 0] solution[1] = self.matrixGrade(solution[0]) if self.mode == 1: # Working on Darwin if len(self.solutionsCurrentGeneration) > 1: bestCurrentSolution = np.copy(self.solutionsCurrentGeneration[-1][0]) gradeMatrixBefore = self.matrixGrade(matrixToModify) gradeCurrentBefore = self.matrixGrade(bestCurrentSolution) copymatrixToModify, copybestCurrentSolution = self.optimizer(np.copy(matrixToModify), np.copy(bestCurrentSolution)) if (self.matrixGrade(copymatrixToModify) > gradeMatrixBefore): matrixToModify = copymatrixToModify if (self.matrixGrade(copybestCurrentSolution) > gradeCurrentBefore): bestCurrentSolution = copybestCurrentSolution self.solutionsCurrentGeneration[-1][0] = bestCurrentSolution # self.solutionsCurrentGeneration[-1][1] = self.matrixGrade(bestCurrentSolution) solution[0] = matrixToModify self.solutionsCurrentGeneration.append(solution) def specificColInitializer(self, numberOfCol, solution): # Executes the mutation mechanic. for row in range(8, 33): solution[row][numberOfCol] = 0 row = 8 line = self.conditionsArray[numberOfCol - 8] conditionsSum = sum(line) numberOfConditions = len([i for i in line if (i > 0)]) numberOfFreeIndexes = 25 - (conditionsSum + (numberOfConditions - 1)) indexStarter = random.randint(0, numberOfFreeIndexes) for i in range(8): if (line[i] > 0): for j in range(line[i]): solution[row + indexStarter][numberOfCol] = 1 row += 1 else: continue conditionsSum = conditionsSum - line[i] numberOfConditions = numberOfConditions - 1 num = 32 - (row + indexStarter) - ((conditionsSum) + (numberOfConditions)) + 2 randnum = random.randint(1, num) for r in range(randnum): row += 1 def gridUpdater(self, off_color, on_color, surface): # Updates the screen with the next solution. if (self.stuckRate >= 10): self.solutionsCurrentGeneration = sorted(self.solutionsCurrentGeneration, key=lambda tup: tup[1]) self.stuckSolver() self.stuckRate = 0 self.solutionsCurrentGeneration = sorted(self.solutionsCurrentGeneration, key=lambda tup: tup[1]) self.grid_array = self.solutionsCurrentGeneration[-1][0] self.bestSolution = self.solutionsCurrentGeneration[-1] bestCurrentGrade = self.matrixGrade(self.grid_array) if (bestCurrentGrade > 95 or self.iteration_num >= 5000): pauser = input("PAUSED") # print([self.solutionsCurrentGeneration[i][1] for i in range(10)]) self.iteration_num += 1 print("Iteration " + str(self.iteration_num) + ", best solution score: " + str(bestCurrentGrade)) if (bestCurrentGrade - self.currentGrade) == 0: self.stuckRate += 1 self.expanderRate += 1 else: self.stuckRate = 0 self.expanderRate = 0 # print(self.stuckRate) self.currentGrade = bestCurrentGrade for x in range(self.rows): for y in range(self.columns): y_pos = (y) * self.scale yScale = self.scale - self.offset x_pos = (x) * self.scale xScale = self.scale - self.offset if self.grid_array[x][y] == 3: # Corner cell pygame.draw.rect(surface, (0, 0, 0), [y_pos, x_pos, xScale, yScale]) elif self.grid_array[x][y] == 2: # Conditional cell pygame.draw.rect(surface, off_color, [x_pos, y_pos, xScale, yScale]) font = pygame.font.SysFont(None, 20) if (y < 8): # Lines 0-24 try: if (self.conditionsArray[x - 8][y] != 0): img = font.render(str(self.conditionsArray[x - 8][y]), True, (0, 0, 0)) self.screen.blit(img, (x_pos, y_pos)) # If condition is 0, we omit it and leaving the cell empty. except: # Handles the event the customer didn't included a condition at all. continue else: # Lines 25-49 try: if (self.conditionsArray[y + 17][x] != 0): img = font.render(str(self.conditionsArray[y + 17][x]), True, (0, 0, 0)) self.screen.blit(img, (x_pos, y_pos)) # If condition is 0, we omit it and leaving the cell empty. except: continue elif self.grid_array[x][y] == 1: pygame.draw.rect(surface, on_color, [y_pos, x_pos, xScale, yScale]) elif self.grid_array[x][y] == 0: pygame.draw.rect(surface, off_color, [y_pos, x_pos, xScale, yScale]) self.solutionComposer() self.solutionsCurrentGeneration = self.solutionsNextGeneration self.solutionsNextGeneration = [] #################COMPOSING SOLUTION#################################### def solutionComposer(self): # Creates the next collection of solutions. replicationMutationIndexes = [] firstCrossOverFlag = 1 new_solution = self.mutation(np.copy(self.solutionsCurrentGeneration[-1][0])) # Mutation on best self.solutionsNextGeneration.append([new_solution, self.matrixGrade(new_solution)]) self.solutionsNextGeneration.append(self.solutionsCurrentGeneration[-1]) replicationMutationIndexes.append(self.numberOfSolutionsToHandle - 1) if (self.stuckRate > 0): Pmutation = 25 + self.stuckRate * 5 if (Pmutation > 100): Pmutation = 100 else: Pmutation = 25 for index in range(1, self.numberOfSolutionsToHandle - 7 - (self.numberOfSolutionsToHandle - 10)): destiny = random.randint(0, 100) if destiny < Pmutation: # Mutation on the solution new_solution = self.mutation(np.copy(self.solutionsCurrentGeneration[-1 - index][0])) self.solutionsNextGeneration.append([new_solution, self.matrixGrade(new_solution)]) replicationMutationIndexes.append(self.numberOfSolutionsToHandle - index) else: # replication on the solution self.solutionsNextGeneration.append(self.solutionsCurrentGeneration[-1 - index]) replicationMutationIndexes.append(self.numberOfSolutionsToHandle - index) crossOverSkipFlag = 0 for index in range(self.numberOfSolutionsToHandle - 4): if crossOverSkipFlag == 1: crossOverSkipFlag = 0 continue if (self.stuckRate > 0): Pmutation = 50 + self.stuckRate * 3 if Pmutation > 95: Pmutation = 95 else: Pmutation = 50 if index == self.numberOfSolutionsToHandle - 5: PforIndex5 = Pmutation - 1 thingToDo = random.randint(1, PforIndex5) # 1% replication, 99% mutation, unable to do crossover else: thingToDo = random.randint(1, 100) # 1% replication, 50% mutation, 49% crossover if thingToDo < Pmutation: # Preparing a winner winner = random.randint(0, self.numberOfSolutionsToHandle - 4) while winner in replicationMutationIndexes: winner = random.randint(0, self.numberOfSolutionsToHandle - 4) if thingToDo == 1: # replication self.solutionsNextGeneration.append(self.solutionsCurrentGeneration[winner]) replicationMutationIndexes.append(winner) elif thingToDo > 1 and thingToDo < Pmutation: # Mutation new_solution = self.mutation(np.copy(self.solutionsCurrentGeneration[winner][0])) self.solutionsNextGeneration.append([new_solution, self.matrixGrade(new_solution)]) replicationMutationIndexes.append(winner) else: # Crossover: self.crossOverPrepare(firstCrossOverFlag) firstCrossOverFlag = 0 crossOverSkipFlag = 1 def crossOverPrepare(self, flag): # Preparing a cross over. mode = random.randint(1, 2) # Determining if crossover is going to be on column or row pivot = random.randint(8, 32) # Determining the the point in which we perform the cross over. if flag == 1: index1 = self.numberOfSolutionsToHandle - 1 index2 = self.numberOfSolutionsToHandle - 2 else: index1 = random.randint(0, self.numberOfSolutionsToHandle - 1) index2 = random.randint(0, self.numberOfSolutionsToHandle - 1) while index2 == index1: index2 = random.randint(0, self.numberOfSolutionsToHandle - 1) self.crossOver(mode, pivot, self.solutionsCurrentGeneration[index1][0], self.solutionsCurrentGeneration[index2][0]) def crossOver(self, mode, pivot, firstParty, secondParty): # Generates a cross over solution. part1 = firstParty[:, 0:pivot] part2 = secondParty[:, pivot:33] solution1 = np.concatenate((part1, part2), axis=1) part1 = secondParty[:, 0:pivot] part2 = firstParty[:, pivot:33] solution2 = np.concatenate((part1, part2), axis=1) tuple1 = [solution1, 0] tuple1[1] = self.matrixGrade(solution1) tuple2 = [solution2, 0] tuple2[1] = self.matrixGrade(solution2) self.solutionsNextGeneration.append(tuple1) self.solutionsNextGeneration.append(tuple2) def mutation(self, solution): # Prepares a mutation. col = random.randint(8, 32) self.specificColInitializer(col, solution) return solution def stuckSolver(self): # Resolves an early covariance situation if (self.expanderRate >= 100): firstBest = self.solutionsCurrentGeneration[self.numberOfSolutionsToHandle - 1] firstBestGrade = self.matrixGrade(firstBest[0]) secondBest = firstBest # flagCanOptimize = 1 for i in range(self.numberOfSolutionsToHandle - 2, -1, -1): secondBest = self.solutionsCurrentGeneration[i] if (firstBestGrade - self.matrixGrade(secondBest[0]) > 2): break self.numberOfSolutionsToHandle += 5 self.expanderRate = 0 else: firstBest = self.solutionsCurrentGeneration[self.numberOfSolutionsToHandle - 1] secondBest = self.solutionsCurrentGeneration[self.numberOfSolutionsToHandle - 2] self.solutionsCurrentGeneration = [] self.random2d_array(self.numberOfSolutionsToHandle - 2) self.solutionsCurrentGeneration.append(secondBest) self.solutionsCurrentGeneration.append(firstBest) ################################################################################################################### def comparePopulation(self, solution): # Comparing the size of population in rows to the required size of population. # print(self.conditionsArray) counter = 0 distanceAtColsFromDesiredPopulation = [] distanceAtRowsFromDesiredPopulation = [] for line in self.conditionsArray: desiredPopulation = 0 for condition in line: desiredPopulation += condition # print(desiredPopulation) if counter < 25: # Working on columns population = 0 for y in range(8, self.rows): population += solution[y][8 + counter] # print("Actual population of column " + str(counter) + " is " + str(population) # + " while the desired population is: " + str(desiredPopulation)) distanceAtColsFromDesiredPopulation.append(population - desiredPopulation) else: # Working on rows population = 0 for x in range(8, self.columns): population += solution[counter - 17][x] # print("Actual population of row " + str(counter - 25) + " is " + str(population) # + " while the desired population is: " + str(desiredPopulation)) distanceAtRowsFromDesiredPopulation.append(population - desiredPopulation) counter += 1 # Proceeding to the next column/row. distancesToReturn = [] distancesToReturn.append(distanceAtRowsFromDesiredPopulation) distancesToReturn.append(distanceAtColsFromDesiredPopulation) return distancesToReturn # This array consists of the following members: [0] At Rows, [1] At Cols. def chuncksCounter(self, solution): # Counting the fragments (Chuncks) in each line. # Creates a list containing 2 lists, each of 25 items, all set to 0 w, h = 25, 2; chuncksArray = [[0 for x in range(w)] for y in range(h)] ###CHUNCKS IN ROWS### i = 0 j = 0 for row in range(8, self.rows): rows_chuncks = [] rows_counter = 0 for column in range(8, self.columns): if (solution[row][column] == 1): rows_counter += 1 elif (solution[row][column] == 0): if (rows_counter > 0): rows_chuncks.append(rows_counter) rows_counter = 0 if (rows_counter > 0): rows_chuncks.append(rows_counter) while (len(rows_chuncks) < 8): rows_chuncks.insert(0, 0) # The first 0 reflects the position to which we insert the member # - i.e the beginning of the array. The second 0 represents the member we're inserting. chuncksArray[i][j] = rows_chuncks j += 1 ###CHUNCKS IN COLUMNS### i = 1 j = 0 for column in range(8, self.columns): cols_chuncks = [] cols_counter = 0 for row in range(8, self.rows): if (solution[row][column] == 1): cols_counter += 1 elif (solution[row][column] == 0): if (cols_counter > 0): cols_chuncks.append(cols_counter) cols_counter = 0 if (cols_counter > 0): cols_chuncks.append(cols_counter) while (len(cols_chuncks) < 8): cols_chuncks.insert(0, 0) chuncksArray[i][j] = cols_chuncks j += 1 return chuncksArray def compareLists(self, listConditions, listActual): # Given a proposed solution and requirements, we compare them. difference = 0 IsOverlyLong = False if (len(listActual) > 8): # If there are more than 8 chunks in the solution, the IsOverlyLong flag raise. # GradeReduction = 0.0625 IsOverlyLong = True for i in range(8): # Checks how many chunks are different between the requirements and the actual solution. if (listConditions[i] != listActual[i]): difference += 1 return (difference, IsOverlyLong) def compareConditions(self, solution): # Compares the conditions to the proposed solution # Creates a list containing 2 lists, each of 25 items, all set to 0 w, h = 25, 2; compareConditionsArray = [[0 for x in range(w)] for y in range(h)] i = 0 chuncksArray = self.chuncksCounter(solution) for line in self.conditionsArray: if i < 25: # Working on cols result = self.compareLists(line, chuncksArray[1][ i]) # Returns a Tuple consisting of: [0] the number of chunks different # [1] A flag indicates if there are more than 8 chucks in a given row/col in the solution. if (result[1]): # result[1] consists of the flag, (True or false). If Flag == True then... compareConditionsArray[1][i] = 0.5 - 0.0625 * result[ 0] # If the flag is raised the reduction is harsher. else: compareConditionsArray[1][i] = 0.5 - (0.0625 / 2) * result[0] else: # Working on rows result = self.compareLists(line, chuncksArray[0][i - 25]) if (result[1]): compareConditionsArray[0][i - 25] = 0.5 - 0.0625 * result[0] else: compareConditionsArray[0][i - 25] = 0.5 - (0.0625 / 2) * result[0] # compareConditionsArray[1][i-25] = len(set(chuncksArray[0][i]) & set(line)) i += 1 return compareConditionsArray def gradeForConditions(self, solution): # Generating a grade according to the accuracy of the proposed solution # Creates a list containing 2 lists, each of 25 items, all set to 0 # will be array for all grades for each column and row according to the conditions file order(meaning this array length will be 50) w, h = 25, 2 gradesArray = [[0 for x in range(w)] for y in range(h)] # grade will be build by 50% comparePopulation and 50% chuncks comparasion comparePopulationArray = self.comparePopulation(solution) # consists population differences compareConditionsArray = self.compareConditions(solution) # consists grades already for i in range(0, 1): # 0 for rows, 1 for cols for j in range(0, 25): absoulte_difference = abs(comparePopulationArray[i][j]) if absoulte_difference == 0: gradesArray[i][j] = 0.5 + compareConditionsArray[i][j] else: gradesArray[i][j] = 0.5 - 0.5 * (absoulte_difference / 25) + compareConditionsArray[i][j] return gradesArray def gradeCalculator(self, gradesArray): # Taking the data from the other functions, this one calculated the final grade. grade = 0 for i in range(0, 1): for j in range(0, 25): grade += gradesArray[i][j] grade /= 25 # Calculating the average after going through the 2D array return grade # A float def matrixGrade(self, solution): # Starting a grading flow for a solution. grade = self.gradeCalculator(self.gradeForConditions(solution)) # Expecting to get a float to grade1 return grade * 100 def specificCrossOver(self, col, solution1, solution2): # Creating a cross over between two cols. col1 = solution1[:, col] col2 = solution2[:, col] solution1[:, col] = np.copy(col2) solution2[:, col] = np.copy(col1) return solution1, solution2 def optimizer(self, solution1, solution2): # Our optimizer function, used in Darwin mode and LeMark mode. solution1Grade = self.matrixGrade(solution1) solution2Grade = self.matrixGrade(solution2) newSolution1Grade = solution1Grade newSolution2Grade = solution2Grade timeout = 0 while (newSolution1Grade <= solution1Grade and newSolution2Grade <= solution2Grade): if (timeout >= 64): # print("NO SUCCESS........................................................") copySolution1 = solution1 copySolution2 = solution2 break col = random.randint(8, 32) copySolution1, copySolution2 = self.specificCrossOver(col, np.copy(solution1), np.copy(solution2)) newSolution1Grade = self.matrixGrade(copySolution1) newSolution2Grade = self.matrixGrade(copySolution2) timeout += 1 # if (timeout < 64): # print("SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") return copySolution1, copySolution2