blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9e57a0f694622cd1b0b67e17f4adcd790535b2f2
himal8848/Python-Beginner-Projects
/comprehensions.py
496
4.28125
4
#List comprehensions lst = [i for i in range(100) if i % 3 ==0] print(lst) #dictionry comprehension dict = {i:f"item{i}" for i in range(5)} print(dict) dict1 = {value:key for key,value in dict.items() } print(dict1) #Set comprehensions #It does not print repeatable value st = {i for i in [2,4,5,3,3,4,5,3] if i % 2 == 0} print(st) #Generator comprehensions #It only iterate only ones evens = ( i for i in range(20) if i%4 == 0) print(type(evens)) for even in evens: print(even,end=" ")
a9ac520b1a01cdacea55462697ad5cbd64db577e
typemegan/Python
/CorePythonProgramming_2nd/ch08_loops/countWords.py
244
3.984375
4
#!/usr/bin/python ''' script for counting words of a given file key point: list comprehensions ''' fname = raw_input('enter a file path> ') count = sum(len(words) for line in open(fname,'r') for words in line.split()) print 'words:',count
4d0167519427aeaee1ac31fa5a65ad455cbfd8dd
Mgtcaleb/Health-Management-System-1.0
/HMS.py
3,324
3.921875
4
#This is the code to execute simple data whiuch is based on food and exercise of individual person #Author:Caleb Gore; Date of Code Creation: 11:50 A.M, 20.08.2020. """ Notes: 1.Time stamp contains both number and : so predefine the data type as string 2. It is important to import built-in function (datetime) so that we don't create another same function and waste time. """ #_______________________Part 2___________________________________ import datetime #datetime is built-in function def gettime():#user has defined return datetime.datetime.now() try:#to handle error #_______________________Part 3.1___________________________________ def logs(l): if l==1: a=int(input("Enter any one number below:\n 1-Exercise\n 2-Food\nEnter Here:")) if a==1: exercise1=input("Enter here:\n") with open("Caleb's Log.txt","a")as f: a1=f.write(str([str(gettime())])+"\n"+"Exercise:"+exercise1+"\n") print("Logged Successfully") elif a==2: food1=input("Enter Here:\n") with open("Caleb's Log.txt","a")as f: a1 = f.write(str([str(gettime())])+"\n"+"Food:"+food1+"\n") print("Logged Successfully") elif l==2: a = int(input("Enter any one number below:\n 1-Exercise\n 2-Food\n Enter Here:")) if a == 1: exercise1 = input("Enter here:\n") with open("Harry's Log.txt", "a")as f: a1 = f.write(str([str(gettime())])+"\n"+"Exercise:"+ exercise1+"\n") print("Logged Successfully") elif a==2: food1 = input("Enter Here:\n") with open("Harry's Log.txt", "a")as f: a1 = f.write(str([str(gettime())]) +"\n"+"Food:"+ food1+"\n") print("Logged Successfully") # _______________________Part 3.2___________________________________ def retrive(r): if r==1: with open("Caleb's Log.txt") as f: a1=f.read() print(a1) elif r==2: with open("Harry's Log.txt") as f: a1 = f.read() print(a1) #_______________________Part 1___________________________________ print("Current Timestamp:",gettime()) #Front-end of the code, which user can see. print("Welcome to Health Management System: 1.0\n") a=int(input("Please enter the input\n 1-Log\n 2-Retrive\nEnter Here:")) if a==1:#since we provide two options 1-Log and 2-Retrive,hence developed condition statement. b=int(input("Please choose the number below to enter the log\n1-Caleb\n2-Harry\nEnter only number here:")) logs(b)#user defined function to enter the log in text file with time stamp. elif a==2:#if first condition is false (i.e. a==1) exceute second condition if it is true (i.e a==2) b=int(input("Please choose the number below to retrive the log\n1-Caleb\n2-Harry\nEnter only number here:")) retrive(b)#user defined function to retrive log with time stamp. except Exception as e: print(e,"Kindly Restart the program because you have entered string or float")
94b82e69a4a57360362b4c729f1236d07933a00a
sagarrjadhav/Problem-Solving-in-Data-Structures-Algorithms-using-Python
/Heap/MedianHeap.py
1,939
3.59375
4
#!/usr/bin/env python import heapq class MedianHeap(object): def __init__(self): self.minHeap = [] self.maxHeap = [] def MinHeapInsert(self, value): heapq.heappush(self.minHeap, value) def MaxHeapInsert(self, value): heapq.heappush(self.maxHeap, -1 * value) def MaxHeapPeek(self): return -1 * self.maxHeap[0] def MinHeapPeek(self): return self.minHeap[0] def MinHeapRemove(self): return heapq.heappop(self.minHeap) def MaxHeapRemove(self): return -1 * heapq.heappop(self.maxHeap) # Other Methods. def insert(self, value): if len(self.maxHeap) == 0 or self.MaxHeapPeek() >= value: self.MaxHeapInsert(value) else: self.MinHeapInsert(value) # size balancing if len(self.maxHeap) > len(self.minHeap) + 1: value = self.MaxHeapRemove() self.MinHeapInsert(value) if len(self.minHeap) > len(self.maxHeap) + 1: value = self.MinHeapRemove() self.MaxHeapInsert(value) def getMedian(self): if len(self.maxHeap) == 0 and len(self.minHeap) == 0: return sys.maxint if len(self.maxHeap) == len(self.minHeap): return (self.MaxHeapPeek() + self.MinHeapPeek()) / 2 elif len(self.maxHeap) > len(self.minHeap): return self.MaxHeapPeek() else: return self.MinHeapPeek() @classmethod def main(cls, args): arr = [1, 9, 2, 8, 3, 7, 4, 6, 5, 1, 9, 2, 8, 3, 7, 4, 6, 5, 10, 10] hp = MedianHeap() i = 0 while i < 20: hp.insert(arr[i]) print "Median after insertion of " , arr[i] , " is " , hp.getMedian() i += 1 if __name__ == '__main__': import sys MedianHeap.main(sys.argv)
26c9f7e383cce71cde211cd35562d951f7c64c54
RAJARANJITH1999/Python-Programs
/even.py
214
4.1875
4
value=int(input("enter the value to check whether even or odd")) if(value%2==0): print(value,"is a even number") else: print(value,"is odd number") print("vaule have been checked successfully")
d067d0f200cf65ab05128444894a24191db2ac93
RoseMagura/AlgorithmNotes
/Python_Exercises/heap_sort.py
5,363
4
4
from collections import deque class Node(object): def __init__(self,value = None): self.value = value self.left = None self.right = None def set_value(self,value): self.value = value def get_value(self): return self.value def set_left_child(self,left): self.left = left def set_right_child(self, right): self.right = right def get_left_child(self): return self.left def get_right_child(self): return self.right def has_left_child(self): return self.left != None def has_right_child(self): return self.right != None # define __repr_ to decide what a print statement displays for a Node object def __repr__(self): return f"Node({self.get_value()})" def __str__(self): return f"Node({self.get_value()})" class Queue(): def __init__(self): self.q = deque() def enq(self,value): self.q.appendleft(value) def deq(self): if len(self.q) > 0: return self.q.pop() else: return None def __len__(self): return len(self.q) def __repr__(self): if len(self.q) > 0: s = "<enqueue here>\n_________________\n" s += "\n_________________\n".join([str(item) for item in self.q]) s += "\n_________________\n<dequeue here>" return s else: return "<queue is empty>" class Tree(): def __init__(self): self.root = None def set_root(self,value): self.root = Node(value) def get_root(self): return self.root def compare(self,node, new_node): """ 0 means new_node equals node -1 means new node less than existing node 1 means new node greater than existing node """ if new_node.get_value() == node.get_value(): return 0 elif new_node.get_value() < node.get_value(): return -1 else: return 1 def insert(self, new_value): new_node = Node(new_value) current_node = self.get_root() if current_node == None: self.root = new_node return while current_node: comparision = self.compare(current_node, new_node) if comparision == 0: current_node.set_value(new_node.get_value()) break elif comparision == 1: if(current_node.get_left_child() == None): current_node.set_left_child(new_node) break else: current_node = current_node.get_left_child() else: if(current_node.get_right_child() == None): current_node.set_right_child(new_node) break else: current_node = current_node.get_right_child() def __repr__(self): level = 0 q = Queue() visit_order = list() node = self.get_root() q.enq( (node,level) ) while(len(q) > 0): node, level = q.deq() if node == None: visit_order.append( ("<empty>", level)) continue visit_order.append( (node, level) ) if node.has_left_child(): q.enq( (node.get_left_child(), level +1 )) else: q.enq( (None, level +1) ) if node.has_right_child(): q.enq( (node.get_right_child(), level +1 )) else: q.enq( (None, level +1) ) s = "Tree\n" previous_level = -1 for i in range(len(visit_order)): node, level = visit_order[i] if level == previous_level: s += " | " + str(node) else: s += "\n" + str(node) previous_level = level return s def heapsort(arr): heapify(arr, len(arr), 0) def heapify(arr, n, i): """ :param: arr - array to heapify n -- number of elements in the array i -- index of the current node TODO: Converts an array (in place) into a maxheap, a complete binary tree with the largest values at the top """ tree = Tree() if i == 0: tree.set_root(arr[i]) while i < n: # if(arr[i] > tree.get_root().value): # tree.set_root(arr[i]) # else: # tree.insert(arr[i]) tree.insert(arr[i]) i+= 1 print(tree) def test_function(test_case): heapsort(test_case[0]) if test_case[0] == test_case[1]: print("Pass") else: print("False") heapsort([1, 3, 2]) arr = [3, 7, 4, 6, 1, 0, 9, 8, 9, 4, 3, 5] solution = [0, 1, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9] test_case = [arr, solution] # test_function(test_case) arr = [5, 5, 5, 3, 3, 3, 4, 4, 4, 4] solution = [3, 3, 3, 4, 4, 4, 4, 5, 5, 5] test_case = [arr, solution] # test_function(test_case) arr = [99] solution = [99] test_case = [arr, solution] # test_function(test_case) arr = [0, 1, 2, 5, 12, 21, 0] solution = [0, 0, 1, 2, 5, 12, 21] test_case = [arr, solution] # test_function(test_case)
c7fabd810b612e7d86760814041a1a4acc5f8201
jan-2018-py1/Python_Anton
/Python/Fun with Functions.py
650
4.21875
4
#Odd/Even: def odd_even(): for i in range(1,2001): if i%2 == 0: print "Number is ", i, "This is an even number" else: print "Number is ", i, "This is an odd number" #odd_even() def multiply(incoming_list, value): result=[] for key in incoming_list: result.append(key*value) return result a = [2,4,10,16] b = multiply(a, 5) print b #Hacker Challenge def layered_multiples(arr): new_array = [] for i in range(0, len(arr)): l = [] for j in range(0, arr[i]): l.append(1) new_array.append(l) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
48a554771654d67bce5b298070d58ccfc790da50
Naveduran/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/5-filter_cities.py
977
3.515625
4
#!/usr/bin/python3 '''my module 1''' import MySQLdb from sys import argv def Filter_Cities(username, password, db_name, state_name): '''receive a city name as argument and list it's cities''' # Open database connection db = MySQLdb.connect(host="localhost", port=3306, user=username, passwd=password, db=db_name, charset="utf8") # prepare a cursor object using cursor() method cur = db.cursor() # execute SQL query using execute() method. cur.execute("""SELECT cities.name FROM states INNER JOIN cities ON cities.state_id = states.id WHERE states.name = %(state_name)s ORDER BY cities.id ASC""", { 'state_name': state_name }) query_rows = cur.fetchall() for row in query_rows: if query_rows[0] != row: print(', ', end='') print(row[0], end='') print() cur.close() if __name__ == "__main__": Filter_Cities(argv[1], argv[2], argv[3], argv[4])
60e268d79364768ec389988f9268edba0145eddb
mkoundo/Automate_the_Boring_Stuff
/chapter_19_Images/custom_seating.py
2,771
4.40625
4
#! python3 # custom_seating.py # Author: Michael Koundouros """ Chapter 15 included a practice project to create custom invitations from a list of guests in a plaintext file. As an additional project, use the pillow module to create images for custom seating cards for your guests. For each of the guests listed in the guests.txt file from the resources at https://nostarch.com/automatestuff2/, generate an image file with the guest name and some flowery decoration. A public domain flower image is also available in the book's resources. To ensure that each seating card is the same size, add a black rectangle on the edges of the invitation image so that when the image is printed out, there will be a guideline for cutting. The PNG files that Pillow produces are set to 72 pixels per inch, so a 4×5-inch card would require a 288×360-pixel image. usage: python custom_seating.py <file> where <file> is a text file containing a list of names to be printed on the seating cards. """ import sys from PIL import Image, ImageDraw, ImageFont def seating_card(guest_name): # Function returns image object of seating card for given guest name # Define seating card dimensions (pixels) card_width = 360 card_height = 288 # Card decoration image flower_image = Image.open('morning-glory2.jpg') flower_width, flower_height = flower_image.size # Create seating card card = Image.new('RGBA', (card_width, card_height), 'white') # Add decoration to top and bottom of card card.paste(flower_image, (0, 0)) card.paste(flower_image, (0, card_height-flower_height)) # Add border draw = ImageDraw.Draw(card) draw.rectangle((0, 0, card_width-1, card_height-1), outline='black') # Add name brushscript = ImageFont.truetype('BRUSHSCI.TTF', 42) w, h = draw.textsize(guest_name, font=brushscript) # Width and height of text draw.text(((card_width-w)/2, (card_height-h)/2), guest_name, fill='black', font=brushscript) return card def main(): # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if len(args) != 1: print('usage: python custom_seating.py <file>') sys.exit(1) # Create seating cards using text file containing list of names filename = args[0] i = 1 try: with open(filename, 'r') as file: for guest in file: name = guest.strip('\n') seating_card(name).save(f'seating_card_{i}.png') print(f"Creating Seating card for: {name} as: seating_card_{i}.png") i += 1 print('Done!') except FileNotFoundError: print('file not found!') if __name__ == '__main__': main()
91d54b639a5399c5f5067a7e51675d14b7853c79
Kalliojumala/School-Work
/Week 3/Week3_hard/hard3.3.py
746
4.03125
4
#even or odd number def even_or_odd(num: int): return num % 2 == 0 def even_and_compare(): #takes 2 numbers as input num = int(input("Syötä kokonaisluku: ")) compare = int(input("\nSyötä vertailuluku: ")) #comparison block, self explanatory imo! if even_or_odd(num): print("\nSyöttämäsi luku on parillinen.\n") else: print("\nSyöttämäsi luku on pariton.\n") if num > compare: print(f"Luku {compare} on pienempi kuin {num}.") elif num < compare: print(f"Luku {compare} on suurempi kuin {num}.") else: print(f"Luvut {compare} ja {num} ovat yhtäsuuria!") print("\nKiitos ohjelman käytöstä!") if __name__ == '__main__': even_and_compare()
2029516113189f6ff938ed936c698dbf5ed754db
damonchen/pytimer
/timer.py
3,882
3.515625
4
#!/usr/bin/env python # coding=utf-8 # author: damonchen # date: 2018-02-07 # 给公司内部做培训,编写一个Hierarchical Timing Wheels的timer的实现 class Slot(list): pass class Wheel(object): def __init__(self, size): self.size = size # 0~59, or 0~23 self.pointer = 0 # wheel指针,达到wheel_buffer尾部后会重新重头开始 self._init_wheel_buffer(size) def _init_wheel_buffer(self, size): self.wheel_buffer = [Slot() for i in xrange(size)] def add(self, index, time, data): i = index % self.size self.wheel_buffer[i].append((time, data)) def ticket(self): self.pointer = (self.pointer + 1) % self.size slot = self.wheel_buffer[self.pointer] self.wheel_buffer[self.pointer] = Slot() return slot def is_end(self): return (self.pointer + 1) % self.size == 0 class SecondWheel(Wheel): def __init__(self): super(SecondWheel, self).__init__(60) class MinuteWheel(Wheel): def __init__(self): super(MinuteWheel, self).__init__(60) class HourWheel(Wheel): def __init__(self): super(HourWheel, self).__init__(24) class DayWheel(Wheel): def __init__(self): super(DayWheel, self).__init__(365) class InvalidTime(StandardError): pass class Time(object): def __init__(self, second, minute=0, hour=0, day=0): self.second = second self.minute = minute self.hour = hour self.day = day def __repr__(self): return '<time %dd-%dh-%dd-%ds>' % (self.day, self.hour, self.minute, self.second) class WheelTimer(object): def __init__(self): self.second_wheel = SecondWheel() self.minute_wheel = MinuteWheel() self.hour_wheel = HourWheel() self.day_wheel = DayWheel() def adjust_second(self, time): day = time.day hour = time.hour minute = time.minute second = time.second second = self.second_wheel.pointer + second if second >= 60: second -= 60 minute += 1 if minute >= 60: minute -= 60 hour += 1 if hour >= 24: hour -= 24 day += 1 if day > 365: raise InvalidTime("invalid time") return Time(second, minute, hour, day) def add(self, time, data): time = self.adjust_second(time) if time.day > 0 and time.day < 365: self.day_wheel.add(time.day, time, data) elif time.hour > 0: self.hour_wheel.add(time.hour, time, data) elif time.minute > 0: self.minute_wheel.add(time.minute, time, data) elif time.second > 0: self.second_wheel.add(time.second, time, data) else: raise InvalidTime('invalid time %s', time) def second_ticket(self): if self.second_wheel.is_end(): minute_slot = self.minute_ticket() for time, data in minute_slot: self.second_wheel.add(time.second, time, data) slot = self.second_wheel.ticket() return slot def minute_ticket(self): if self.minute_wheel.is_end(): hour_slot = self.hour_ticket() for time, data in hour_slot: self.minute_wheel.add(time.minute, time, data) slot = self.minute_wheel.ticket() return slot def hour_ticket(self): if self.hour_wheel.is_end(): day_slot = self.day_ticket() for time, data in day_slot: self.hour_wheel.add(time.hour, time, data) slot = self.hour_wheel.ticket() return slot def day_ticket(self): slot = self.day_wheel.ticket() return slot def ticket(self): slot = self.second_ticket() return slot
d122e317db05f4bc6646a27fe9e6cf975f4e25df
Punit-Choudhary/Python-PatternHouse
/Series Patterns/CodeFiles/Pattern8.py
442
4.21875
4
""" In this program, we print the series of prime numbers up to 'n'. * First we check each number (1 to n) for prime number. * If the number is prime we print it. """ n = 10 # size num = 1 count = 0 while (num <= n): for x in range(1, num + 1): if (num % x == 0): count += 1 if (count == 2): # true for prime print(" " + str(num), end="") count = 0 num += 1 """ OUTPUT: 2 3 5 7 """
dbfb52350d52c7834c25eae0d49ef1fd604f919e
allenfrostline/Tetris-AI
/genetic_algorithms.py
6,357
3.5
4
# chromosome = heuristics dictionary # populations = [chromosome] # fitness function = score/lines # selection = top X (elitism)/tournament/roulette/others # crossover = pick attributes from parents randomly/average attributes/others # mutation = assign random value/random variance from tetris import TetrisApp from ai import AI from random import randrange, randint import random import sys from enum import Enum class SelectionMethod(Enum): roulette = 1 class CrossoverMethod(Enum): random_attributes = 1 average_attributes = 2 # Config POPULATION_SIZE = 20 GAMES_TO_AVG = 2 SURVIVORS_PER_GENERATION = 6 # crossover probability = NEWBORNS / POPULATION_SIZE NEWBORNS_PER_GENERATION = POPULATION_SIZE - SURVIVORS_PER_GENERATION SELECTION_METHOD = SelectionMethod.roulette CROSSOVER_METHOD = CrossoverMethod.random_attributes MUTATION_PASSES = 3 MUTATION_RATE = 20 # mutation probability for a given chromosome is MUTATION_PASSES / MUTATION_RATE CONVERGED_THRESHOLD = 15 def __generate_name(): current_name = 1 while True: yield current_name current_name += 1 _generate_name = __generate_name() class Chromosome(object): def __init__(self, heuristics): self.name = next(_generate_name) self.heuristics = heuristics self.total_fitness = 0 self.games = 0 def avg_fitness(self): return self.total_fitness / self.games class GeneticAlgorithms(object): def __init__(self): self.app = TetrisApp(self) self.ai = AI(self.app) self.app.ai = self.ai self.population = [self.random_chromosome() for _ in range(POPULATION_SIZE)] self.current_chromosome = 0 self.current_generation = 1 self.ai.heuristics = self.population[self.current_chromosome].heuristics def run(self): self.app.run() def next_ai(self): self.current_chromosome += 1 if self.current_chromosome >= POPULATION_SIZE: self.current_chromosome = 0 self.next_generation() self.ai.heuristics = self.population[self.current_chromosome].heuristics def on_game_over(self, score): chromosome = self.population[self.current_chromosome] chromosome.games += 1 chromosome.total_fitness += score if chromosome.games % GAMES_TO_AVG == 0: self.next_ai() self.app.start_game() def population_has_converged(self): t = CONVERGED_THRESHOLD pop = self.population return all(all(pop[0].heuristics[f] - t < w < pop[0].heuristics[f] + t for f, w in c.heuristics.items()) for c in pop) def next_generation(self): print("__________________\n") if self.population_has_converged(): print("Population has converged on generation %s.\n values: %s" % (self.current_generation, [(f.__name__, w) for f, w in self.population[0].heuristics.items()])) sys.exit() print("GENERATION %s COMPLETE" % self.current_generation) print("AVG FITNESS", sum([c.avg_fitness() for c in self.population]) / POPULATION_SIZE) self.current_generation += 1 for c in self.population: print("chromosome", c.name, "fitness", c.avg_fitness()) best_chromosome = max(self.population, key=lambda c: c.avg_fitness()) print("Fittest chromosome:", best_chromosome.name, "fitness", best_chromosome.avg_fitness(), "\n%s" % [(f.__name__, w) for f, w in best_chromosome.heuristics.items()]) print("\nEVOLUTION") new_population = self.selection(SURVIVORS_PER_GENERATION, SELECTION_METHOD) for c in new_population: print("chromosome", c.name, "fitness", c.avg_fitness(), "SURVIVED") for _ in range(NEWBORNS_PER_GENERATION): parents = self.selection(2, SELECTION_METHOD) new_population.append(self.crossover(parents[0], parents[1], CROSSOVER_METHOD)) print(parents[0].name, "and", parents[1].name, "PRODUCED", new_population[-1].name) for _ in range(MUTATION_PASSES): for chromosome in new_population: self.mutation(chromosome, MUTATION_RATE / MUTATION_PASSES) print("__________________\n") assert len(new_population) == len(self.population), "SURVIVORS_PER_GENERATION + NEWBORNS_PER_GENERATION != POPULATION_SIZE" self.population = new_population def selection(self, num_selected, method): def roulette(population): total_fitness = sum([c.avg_fitness() for c in population]) winner = randrange(int(total_fitness)) fitness_so_far = 0 for chromosome in population: fitness_so_far += chromosome.avg_fitness() if fitness_so_far > winner: return chromosome if method == SelectionMethod.roulette: survivors = [] for _ in range(num_selected): survivors.append(roulette([c for c in self.population if c not in survivors])) return survivors raise ValueError('SelectionMethod %s not implemented' % method) def crossover(self, c1, c2, method): def random_attributes(): heuristics = {} for fun, _ in c1.heuristics.items(): heuristics[fun] = random.choice((c1, c2)).heuristics[fun] return Chromosome(heuristics) def average_attributes(): heuristics = {} for fun, _ in c1.heuristics.items(): heuristics[fun] = (c1.heuristics[fun] + c2.heuristics[fun]) / 2 return Chromosome(heuristics) if method == CrossoverMethod.random_attributes: return random_attributes() if method == CrossoverMethod.average_attributes: return average_attributes() raise ValueError('CrossoverMethod %s not implemented' % method) def mutation(self, chromosome, mutation_rate): if randint(0, int(mutation_rate)) == 0: h = chromosome.heuristics h[random.choice(list(h.keys()))] = randrange(-1000, 1000) print(chromosome.name, "MUTATED") def random_chromosome(self): return Chromosome({fun: randrange(-1000, 1000) for fun, weight in self.ai.heuristics.items()}) if __name__ == '__main__': GeneticAlgorithms().run()
4780d5db192141091b881ba6071f7a51c9e15eb4
evanpelfrey00/python-assignments
/HW06_EvanPelfrey.py
2,507
3.6875
4
#Exercise 1 def twoWords(length, firstLetter): returnList = [] word = input('A ' + str(length) + '-letter word, please: ') if len(word) != length: while len(word) != length: word = input('A ' + str(length) + '-letter word, please: ') if len(word) == length: break returnList.append(word) word = input('A letter that starts with ' + firstLetter + ', please') if word[0] != firstLetter: while word[0] != firstLetter: word = input('A letter that starts with ' + firstLetter + ', please') if word[0] == firstLetter: break returnList.append(word) return(returnList) print(twoWords(4, 'b')) #Exercise 2 def twoWordsV2(length, firstLetter): returnList = [] word = input('A ' + str(length) + '-letter word, please: ') while len(word) != length: word = input('A ' + str(length) + '-letter word, please: ') returnList.append(word) word = ('A letter that starts with ' + firstLetter + ', please') while word[0] != firstLetter: word = input('A letter that starts with ' + firstLetter + ', please') returnList.append(word) return(returnList) print(twoWordsV2(4, 'b')) #Exercise 3 def geometric(lst): common = lst[-1] / lst[-2] x = 0 y = True for i in range(len(lst)-1): if lst[x] * common == lst[x+1]: x = x + 1 continue else: y = False return(y) print(geometric([2, 4, 8, 16, 32, 64, 128, 256])) print(geometric([2, 4, 6, 8])) #Exercise 4 def Mystery(num): count = 0 while num >1: num = num // 2 count += 1 return(count) print(Mystery(4)) print(Mystery(11)) print(Mystery(25)) #Exercise 5 def enterNewPassword(): digits = "0123456789" digit = False password = (input("Password")) while len(password) < 8 or len(password) > 15 or digit == False: digit = False for i in password: if i in digits: digit = True break if digit == False: print("Password must contain at least one digit") if len(password) < 8 or len(password) > 15: print("Password must be between 8 and 15 characters") if digit == True and (len(password) >= 8 and len(password) <=15): break password = (input("Password")) print("Success") enterNewPassword()
4725a9282852fdbeef337745a9090a42fe1bd5e9
Cunningham-Wayne-Jeremy/lpthw
/022/ex22.py
2,806
4.59375
5
# List all of the key words and symbols that I now know and write its # name and what it does next to the code. MAKE A COMPLETE LIST print("This is my list of code that I now know for Python: ") print("# is the comment character") print("print will echo to the terminal") print("""f can be used in every single function out there and can be used to format the output by calling variables in {} """) print("""eval() will evaluate string values. OBVIOUSLY they must be strings and therfore must be in 's or "s """) print("int() and float() will convert strings into numbers") print("def funcname(): tab or 4 spaces will declare a function") print("+= will add something to itself x=1; x+=2; x is now 3") print("Common math operators +-*/ are obvious. % is remainder, ** is ^") print("""* can be used in functions for positional arguments which looks somethin like: def functionname(*args) var1, var2 = args """) print("""* can also be used to multiply strings say I wanted to do HELLO ten times. I would do: print("HELLO"*10) """) print("three \" or three ' can make a multiline string") print("""\\t can tab something, \\n can break to a new line, \\r is a carriage return, There are other \'s for formating different strings """) print("import is a command that can import various modules from python libraries") print("from sys import argv is used to assign parameters to a script at execute") print("; semi colon can be used to keep all of the data on one line of code") print("As mentined the \\ is the escape character") print("var = something is how you declare a variable") print("""open(filename,"mode") will open a file and either write, append, or read it. It also creates a FILE OBJECT """) print("""The are many attributes that can be used on open files. .close(closes an open file), .truncate(overrites a file), .write(overrites and writes something to a file), .read(reads a file), .readline(readsline by line, everytime its ran it runs the next line until a \n) and seek(goes to a point in a file measured in bytes) """) print("<,>,<=,>= are all in python and are obvious as to what they do") print("+ will concatenate strings but will have a line breaki at the end") print("Testing something:") print("The first one is: {} the second one is: {}".format("first?","second?")) print(""" end="" will ensure that whatever the output is its will be on a new line end ="" is usually used with a comma like so print(x,end="") """) print(""" userinput = input("Enter something here") User input is easy and can be blank like so input(), assigned to a variable like this: var = input(). When its not assigned to a variable its can be used as a pause """) print("DONT FORGET PYDOC its useful and is a command used from the command line") print("Python is case sensitive and also space sensitive")
cf03db1459a35800854dc3ee76a455d96a0f99f6
dvanderk/twitter_analysis
/top_ten.py
1,136
3.65625
4
# Computes ten most frquently occuring hashtags from a json file of twitter data # Runs from the comnand line: python top_ten.py <tweetfile> import os import json import sys import types def main(): tweets = open(sys.argv[1]) #read in command line argument -- file from twitter stream hashtag_freq = {} #hashtags and their frequency for line in tweets: tweet = json.loads(line) if 'entities' in tweet and type(tweet['entities']) is not types.NoneType: if 'hashtags' in tweet['entities'] and type(tweet['entities']['hashtags']) is not types.NoneType: hashtags = tweet['entities']['hashtags'] for hashtag in hashtags: htag = hashtag['text'].encode('utf-8') if htag not in hashtag_freq: hashtag_freq[htag] = 1 else: hashtag_freq[htag] += 1 count = 0 #sorted(hashtag_freq.items(), key = lambda x: x:x[1], reverse=True) while count < 11: print sorted(hashtag_freq.items(), key = lambda x:x[1], reverse=True)[count][0], print " ", print sorted(hashtag_freq.items(), key = lambda x:x[1], reverse=True)[count][1] count += 1 if __name__ == '__main__': main()
15c028fa81a3add76da690197035ce42e4f8bb4d
UMKCRobotics/2016-2017-TunnelGeneral
/Competition Game/src/Grid_Util.py
1,444
3.59375
4
# Utility classes for using a grid GRID_WIDTH = 7 GRID_HEIGHT = 7 DISPLAY_WIDTH = 8 DISPLAY_HEIGHT = 8 # this is an enumeration, but we can't use enumerations because someone doesn't update their python class Knowledge: # class Knowledge(IntEnum): def __init__(self): pass unknown = -1 yes = 1 no = 0 class Coordinate: def __init__(self, _x=0, _y=0): self.x = _x self.y = _y def __eq__(self, other): return isinstance(other, Coordinate) and self.x == other.x and self.y == other.y def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return self.x * DISPLAY_WIDTH + self.y def __add__(self, other): return Coordinate(self.x + other.x, self.y + other.y) def __repr__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" # this is an enumeration, but we can't use enumerations because someone doesn't update their python class Direction: # class Direction(IntEnum): def __init__(self): pass east = 0 north = 1 west = 2 south = 3 count = 4 @staticmethod def opposite(given): return (given + 2) % 4 # To get the next coordinate in a given direction, add this coordinate COORDINATE_CHANGE = { Direction.east: Coordinate(1, 0), Direction.west: Coordinate(-1, 0), Direction.north: Coordinate(0, 1), Direction.south: Coordinate(0, -1) }
2d5d4da584dd1e87a2b205dec8d1e1df69f97744
brenopolanski/labs
/python/basic/lambda.py
235
3.75
4
lamb = lambda x: x ** 3 print(lamb(3)) def writer(): title = 'Sir' name = (lambda x: title + ' ' + x) return name w = writer() print(w('Breno Polanski')) L = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x**4] for f in L: print(f(3))
82d7a60738be069d790b8131899f043cb1977b2f
BParesh89/The_Modern_Python3_Bootcamp
/decorators/delay.py
289
3.5625
4
from functools import wraps from time import sleep def delay(time): def inner(fn): @wraps(fn) def wrapper(): print(f"Waiting {time}s before running {fn.__name__}") sleep(time) return fn() return wrapper return inner @delay(3) def say_hi(): return "hi" print(say_hi())
453c942eda820ad7715f141d743167c4cb6fa638
athena15/leetcode
/longest_substring.py
574
3.53125
4
from collections import defaultdict class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = defaultdict(int) start = 0 stop = 1 length = 0 longest = 0 while s[start] == s[stop]: stop += 1 length += 1 if length > longest: longest = length if s[start] == s[stop]: start += 1 length = 0 print(longest) return longest solution = Solution() solution.lengthOfLongestSubstring('pwwkew') def test_string(): solution = Solution() assert solution.lengthOfLongestSubstring('abcefabc') == 5
ceaf3208a60663be216e95ea415b97a7b6797409
garciaac/Hackerrank-Challenges
/Implementation/Easy/caesar-cipher/caesar_cipher.py
433
3.765625
4
if __name__ == "__main__": n = int(input()) s = input() k = int(input()) encrypted = "" for ii in range(n): if s[ii].isalpha(): if s[ii].isupper(): encrypted += chr(ord("A") + (ord(s[ii])-ord("A")+k)%26) else: encrypted += chr(ord("a") + (ord(s[ii])-ord("a")+k)%26) else: encrypted += s[ii] print(encrypted)
014f962cbc866c84008399d910b9d78ffbbe0601
sonamk15/codesignal_questions
/adjacentElementsProduct.py
237
3.609375
4
def adjacentElementsProduct(array): num=-100 i=0 while i<len(array)-1: if array[i]*array[i+1]>=num: num=array[i]*array[i+1] i+=1 return num print (adjacentElementsProduct([5, 1, 2, 3, 1, 4]))
0b8b553a9dd25de1fd2bd9e009eba3e2b791b0d9
TMcMac/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
148
3.84375
4
#!/usr/bin/python3 def uniq_add(my_list=[]): uniq_list = set(my_list) sum = 0 for num in uniq_list: sum += num return sum
197c54999a1958ac595a386f1d0f4f86ba612150
davelasquez12/PythonPractice
/algos/sliding_window.py
3,327
3.53125
4
def longestSubStrWithAtLeastKRepeatedChars(s, k): if k > len(s): return 0 max_unique = len(set(s)) result = 0 for num_unique_expected in range(1, max_unique + 1): count_map = [0] * 26 window_start, window_end, alphabet_index, num_curr_unique_in_window, numCharsInWindowWithAtLeastKRepeats = 0, 0, 0, 0, 0 while window_end < len(s): if num_curr_unique_in_window <= num_unique_expected: # if true, this flow expands the sliding window alphabet_index = ord(s[window_end]) - ord('a') # provides the position (index) of where in the alphabet the current letter is char_count = count_map[alphabet_index] if char_count == 0: num_curr_unique_in_window += 1 new_char_count = char_count + 1 count_map[alphabet_index] = new_char_count # new char in window has been processed so update the count_map if new_char_count == k: numCharsInWindowWithAtLeastKRepeats += 1 window_end += 1 else: # shrinks the sliding window alphabet_index = ord(s[window_start]) - ord('a') char_count = count_map[alphabet_index] if char_count == k: numCharsInWindowWithAtLeastKRepeats -= 1 new_char_count = char_count - 1 count_map[alphabet_index] = new_char_count if new_char_count == 0: num_curr_unique_in_window -= 1 window_start += 1 if num_curr_unique_in_window == num_unique_expected and num_curr_unique_in_window == numCharsInWindowWithAtLeastKRepeats: result = max(result, window_end - window_start) return result def longestSubStrWithAtLeastKRepeatedCharsV2(s, k): if len(s) < k: return 0 max_unique = len(set(s)) result = 0 for num_unique_expected in range(1, max_unique + 1): count_map = [0] * 26 start, end, num_repeated_chars_in_window_at_least_k, num_unique_in_window = 0, 0, 0, 0 while end < len(s): if num_unique_in_window <= num_unique_expected: alphabet_index = ord(s[end]) - ord('a') num_chars = count_map[alphabet_index] if num_chars == 0: num_unique_in_window += 1 num_chars += 1 count_map[alphabet_index] = num_chars if num_chars == k: num_repeated_chars_in_window_at_least_k += 1 end += 1 else: alphabet_index = ord(s[start]) - ord('a') num_chars = count_map[alphabet_index] if num_chars == k: num_repeated_chars_in_window_at_least_k -= 1 num_chars -= 1 if num_chars == 0: num_unique_in_window -= 1 count_map[alphabet_index] = num_chars start += 1 if num_unique_in_window == num_unique_expected and num_unique_in_window == num_repeated_chars_in_window_at_least_k: result = max(result, end - start) return result
54cbed599b642c36c3c54ec50bd073b54bb428b5
abdulkaderm11/BlackMagician
/PythonBasic/Find_Angle_MBC.py
663
4.1875
4
''' ABC = 90° Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find MBC in degrees. Input Format The first line contains the length of side AB. The second line contains the length of side BC. Output Format Output MBC in degrees. Sample Input 10 10 Sample Output 45° ''' ''' example: >>> round(2.5) 2 >>> round(3.5) 4 >>> round(4.5) 4 mac: shift + option + 8 -> '°' ''' import math if __name__ == "__main__": AB = int(input()) BC = int(input()) AC = math.sqrt(AB**2 + BC**2) BM = AC / 2.0 h = BC / 2.0 print(str(int(round(math.degrees(math.acos(h/BM))))) + '°')
b1ff068536ee0e488edd932a82ea1692e36b1176
fernandodmaqueda/practicasprofexo
/C - Trabajo práctico 1/TP34.py
2,732
3.625
4
#TP34 #Problema: TP34 - Escribí funciones que dada una cadena y un carácter: # a) Inserte el caracter entre cada letra de la cadena. Ej: 'separar' y debería devolver ’s,e,p,a,r,a,r' # b) Reemplace todos los espacios por el caracter. Ej: 'mi archivo de texto.txt' y '_' debería devolver ‘mi_archivo_de_texto.txt' # c) Reemplace todos los dígitos en la cadena por el caracter. Ej: 'su clave es: 1540' y 'X' debería devolver 'su clave es: XXXX' # d) Inserte el caracter cada 3 dígitos en la cadena Ej. '2552552550' y '.' debería devolver '255.255.255.0' def ingreso_a(): print("Función a) - Inserta el caracter entre cada letra de la cadena. (Ejemplo: 'separar' y ',' debe devolver 's,e,p,a,r,a,r'") cadena=input("Ingrese la cadena. (Ejemplo: 'separar'): ") caracter=input("Ingrese el caracter. (Ejemplo: ','): ") str=funcion_a(cadena,caracter) return str def funcion_a(cadena,caracter): cadena=cadena=cadena[0] + cadena[1:-1:].replace("",caracter) + cadena[len(cadena)-1] return cadena def ingreso_b(): print("") print("Función b) - Reemplaza todos los espacios por el caracter. (Ejemplo: 'mi archivo de texto.txt' y '_' debe devolver 'mi_archivo_de_texto.txt'") cadena=input("Ingrese la cadena. (Ejemplo: 'mi archivo de texto.txt'): ") caracter=input("Ingrese el caracter. (Ejemplo: '_'): ") str=funcion_b(cadena,caracter) return str def funcion_b(cadena,caracter): cadena=cadena.replace(" ",caracter) return cadena def ingreso_c(): print("") print("Función c) - Reemplaza todos los espacios por el caracter. (Ejemplo: 'su clave es: 1540' y 'X' debe devolver 'su clave es: XXXX'") cadena=input("Ingrese la cadena. (Ejemplo: 'su clave es: 1540'): ") caracter=input("Ingrese el caracter. (Ejemplo: 'X'): ") str=funcion_c(cadena,caracter) return str def funcion_c(cadena,caracter): for x in range(len(cadena)): if(cadena[x].isdigit()==True): cadena=cadena.replace(cadena[x],caracter,1) return cadena def ingreso_d(): print("") print("Función d) - Inserta el caracter cada 3 dígitos en la cadena. (Ejemplo: '2552552550' y '.' debe devolver '255.255.255.0'") cadena=input("Ingrese la cadena. (Ejemplo: '2552552550'): ") caracter=input("Ingrese el caracter. (Ejemplo: '.'): ") str=funcion_d(cadena,caracter) return str def funcion_d(cadena,caracter): contador=0 str="" for x in cadena: if contador!=0 and contador%3==0: str=str+caracter str=str+x contador=contador+1 return(str) resultado=ingreso_a() print("Resultado -",resultado) resultado=ingreso_b() print("Resultado -",resultado) resultado=ingreso_c() print("Resultado -",resultado) resultado=ingreso_d() print("Resultado -",resultado)
f7eb89931f071c0c79f70cfdf46f7df50a885cb0
Ralph-Wang/MyPythonCookBook
/modules/use_pipe.py
354
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # pipe 库需要额外安装 from pipe import * def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b # 小于 1000 的斐波那契数的奇数和 answer = fib() |\ take_while(lambda x : x < 1000) |\ where(lambda x : x%2 == 1) |\ add print answer
ea2d7f4c42d0d61382afeb3efbfc21bade41f8df
robotlightsyou/pfb-resources
/sessions/002-session-strings/exercises/string_methods_video.py
665
4.0625
4
#! /usr/bin/env python3 ''' Ask the user for input, modify the return ''' #print("helloworld") import sys global_var = "howdy" def main(data): print_some_word(data) data = 'test' print_some_word(data) def print_some_word(word): print(word) if __name__ == "__main__": someword = 'blue' main(someword) ''' def swap_case(): print("Please enter a string to alter. ") start = input(">") end = "" for letter in start: if letter.isupper(): end += letter.lower() elif letter.islower(): end += letter.upper() else: end += letter return end '''
923ae602bfb9982100192b7eb0fb0d5ce178c2ef
garuan2/Algorythms
/nearest_zero.py
817
3.625
4
# passed tests ID: 52304665 def nearest_zero(length, numbers): left_array, right_array = [], [] counter = length - 1 for item in numbers: if item == 0: counter = 0 else: counter += 1 left_array.append(counter) counter = length - 1 for item in reversed(numbers): if item == 0: counter = 0 else: counter += 1 right_array.append(counter) right_array = right_array[::-1] range_to_zero = [ min(left, right) for left, right in zip(left_array, right_array) ] return range_to_zero if __name__ == '__main__': a = int(input()) b = list(int(x) for x in input().split()) print(' '.join(map(str, nearest_zero(a, b))))
7c89a8fd3525d0577e9fc3534a3025375479ff44
1286211699/mmc_code
/1_10_面向对象的三大特征/03_game_test.py
1,072
3.640625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2019/4/15 21:08 # @Author : Xuegod Teacher For # @File : 03_game_test.py # @Software: PyCharm # 简单的游戏,利用一个类创建Game类? # 要求: # 1、 玩家可以自己输入自己的名字和姓名 # 2、 登录后开始游戏就会打印“帮助信息” # 3、 帮助信息的下方会出现最高分 # 4、 启动游戏会打印欢迎字句 # 5、 利用类方法,静态方法完成 class Game: def __init__(self,player_name): self.player_name = player_name Game.show_help() Game.show_top_score() @staticmethod def show_help(): print('------------') print('|查看帮助信息|') print('------------') @classmethod def show_top_score(cls): print('-------------') print('|最高分数:1111|') print('-------------') def start_game(self): print('%s 开始的游戏'%self.player_name) if __name__ == '__main__': tom = Game('for') tom.start_game()
62711d5d30533221556db171bbde2684d91b7ad9
tututuana/MazeGenerator
/main.py
6,418
3.65625
4
import random from colorama import Fore, init def printMaze(maze): for i in range(0, height): for j in range(0, width): if (maze[i][j] == 'u'): print(Fore.WHITE + str(maze[i][j]), end="") elif (maze[i][j] == 'c'): print(Fore.GREEN + str(maze[i][j]), end="") else: print(Fore.RED + str(maze[i][j]), end="") print('\n') def surroundingCells(rand_wall): s_cells = 0 if (maze[rand_wall[0]-1][rand_wall[1]] == 'c'): s_cells += 1 if (maze[rand_wall[0]+1][rand_wall[1]] == 'c'): s_cells += 1 if (maze[rand_wall[0]][rand_wall[1]-1] == 'c'): s_cells +=1 if (maze[rand_wall[0]][rand_wall[1]+1] == 'c'): s_cells += 1 return s_cells wall = '#' cell = 'c' unvisited = 'u' height = int(input("Height: ")) width = int(input("Width: ")) print("Loading...") maze = [] init() for i in range(0, height): line = [] for j in range(0, width): line.append(unvisited) maze.append(line) starting_height = int(random.random()*height) starting_width = int(random.random()*width) if (starting_height == 0): starting_height += 1 if (starting_height == height-1): starting_height -= 1 if (starting_width == 0): starting_width += 1 if (starting_width == width-1): starting_width -= 1 maze[starting_height][starting_width] = cell walls = [] walls.append([starting_height - 1, starting_width]) walls.append([starting_height, starting_width - 1]) walls.append([starting_height, starting_width + 1]) walls.append([starting_height + 1, starting_width]) maze[starting_height-1][starting_width] = '#' maze[starting_height][starting_width - 1] = '#' maze[starting_height][starting_width + 1] = '#' maze[starting_height + 1][starting_width] = '#' while (walls): rand_wall = walls[int(random.random()*len(walls))-1] if (rand_wall[1] != 0): if (maze[rand_wall[0]][rand_wall[1]-1] == 'u' and maze[rand_wall[0]][rand_wall[1]+1] == 'c'): s_cells = surroundingCells(rand_wall) if (s_cells < 2): maze[rand_wall[0]][rand_wall[1]] = 'c' if (rand_wall[0] != 0): if (maze[rand_wall[0]-1][rand_wall[1]] != 'c'): maze[rand_wall[0]-1][rand_wall[1]] = '#' if ([rand_wall[0]-1, rand_wall[1]] not in walls): walls.append([rand_wall[0]-1, rand_wall[1]]) if (rand_wall[0] != height-1): if (maze[rand_wall[0]+1][rand_wall[1]] != 'c'): maze[rand_wall[0]+1][rand_wall[1]] = '#' if ([rand_wall[0]+1, rand_wall[1]] not in walls): walls.append([rand_wall[0]+1, rand_wall[1]]) if (rand_wall[1] != 0): if (maze[rand_wall[0]][rand_wall[1]-1] != 'c'): maze[rand_wall[0]][rand_wall[1]-1] = '#' if ([rand_wall[0], rand_wall[1]-1] not in walls): walls.append([rand_wall[0], rand_wall[1]-1]) for wall in walls: if (wall[0] == rand_wall[0] and wall[1] == rand_wall[1]): walls.remove(wall) continue if (rand_wall[0] != 0): if (maze[rand_wall[0]-1][rand_wall[1]] == 'u' and maze[rand_wall[0]+1][rand_wall[1]] == 'c'): s_cells = surroundingCells(rand_wall) if (s_cells < 2): maze[rand_wall[0]][rand_wall[1]] = 'c' if (rand_wall[0] != 0): if (maze[rand_wall[0]-1][rand_wall[1]] != 'c'): maze[rand_wall[0]-1][rand_wall[1]] = '#' if ([rand_wall[0]-1, rand_wall[1]] not in walls): walls.append([rand_wall[0]-1, rand_wall[1]]) if (rand_wall[1] != 0): if (maze[rand_wall[0]][rand_wall[1]-1] != 'c'): maze[rand_wall[0]][rand_wall[1]-1] = '#' if ([rand_wall[0], rand_wall[1]-1] not in walls): walls.append([rand_wall[0], rand_wall[1]-1]) if (rand_wall[1] != width-1): if (maze[rand_wall[0]][rand_wall[1]+1] != 'c'): maze[rand_wall[0]][rand_wall[1]+1] = '#' if ([rand_wall[0], rand_wall[1]+1] not in walls): walls.append([rand_wall[0], rand_wall[1]+1]) for wall in walls: if (wall[0] == rand_wall[0] and wall[1] == rand_wall[1]): walls.remove(wall) continue if (rand_wall[0] != height-1): if (maze[rand_wall[0]+1][rand_wall[1]] == 'u' and maze[rand_wall[0]-1][rand_wall[1]] == 'c'): s_cells = surroundingCells(rand_wall) if (s_cells < 2): maze[rand_wall[0]][rand_wall[1]] = 'c' if (rand_wall[0] != height-1): if (maze[rand_wall[0]+1][rand_wall[1]] != 'c'): maze[rand_wall[0]+1][rand_wall[1]] = '#' if ([rand_wall[0]+1, rand_wall[1]] not in walls): walls.append([rand_wall[0]+1, rand_wall[1]]) if (rand_wall[1] != 0): if (maze[rand_wall[0]][rand_wall[1]-1] != 'c'): maze[rand_wall[0]][rand_wall[1]-1] = '#' if ([rand_wall[0], rand_wall[1]-1] not in walls): walls.append([rand_wall[0], rand_wall[1]-1]) if (rand_wall[1] != width-1): if (maze[rand_wall[0]][rand_wall[1]+1] != 'c'): maze[rand_wall[0]][rand_wall[1]+1] = '#' if ([rand_wall[0], rand_wall[1]+1] not in walls): walls.append([rand_wall[0], rand_wall[1]+1]) for wall in walls: if (wall[0] == rand_wall[0] and wall[1] == rand_wall[1]): walls.remove(wall) continue if (rand_wall[1] != width-1): if (maze[rand_wall[0]][rand_wall[1]+1] == 'u' and maze[rand_wall[0]][rand_wall[1]-1] == 'c'): s_cells = surroundingCells(rand_wall) if (s_cells < 2): maze[rand_wall[0]][rand_wall[1]] = 'c' if (rand_wall[1] != width-1): if (maze[rand_wall[0]][rand_wall[1]+1] != 'c'): maze[rand_wall[0]][rand_wall[1]+1] = '#' if ([rand_wall[0], rand_wall[1]+1] not in walls): walls.append([rand_wall[0], rand_wall[1]+1]) if (rand_wall[0] != height-1): if (maze[rand_wall[0]+1][rand_wall[1]] != 'c'): maze[rand_wall[0]+1][rand_wall[1]] = '#' if ([rand_wall[0]+1, rand_wall[1]] not in walls): walls.append([rand_wall[0]+1, rand_wall[1]]) if (rand_wall[0] != 0): if (maze[rand_wall[0]-1][rand_wall[1]] != 'c'): maze[rand_wall[0]-1][rand_wall[1]] = '#' if ([rand_wall[0]-1, rand_wall[1]] not in walls): walls.append([rand_wall[0]-1, rand_wall[1]]) for wall in walls: if (wall[0] == rand_wall[0] and wall[1] == rand_wall[1]): walls.remove(wall) continue for wall in walls: if (wall[0] == rand_wall[0] and wall[1] == rand_wall[1]): walls.remove(wall) for i in range(0, height): for j in range(0, width): if (maze[i][j] == 'u'): maze[i][j] = '#' for i in range(0, width): if (maze[1][i] == 'c'): maze[0][i] = 'c' break for i in range(width-1, 0, -1): if (maze[height-2][i] == 'c'): maze[height-1][i] = 'c' break printMaze(maze)
02e044728fe04d2754221f08ca5af2ce248d5f29
ReneNyffenegger/about-python
/types/set/set-operators.py
243
3.796875
4
even = { 2, 4, 6, 8, 10, 12 } odd = { 1, 3, 5, 7, 9, 11 } prime = { 2, 3, 5, 7, 11 } print(prime - odd) # # {2} print(prime & even) # # {2} print(even | prime) # # {2, 3, 4, 5, 6, 7, 8, 10, 11, 12} print(odd ^ prime) # # {1, 2, 9}
6f6b6b8c3226b1f98af94c66635376fdfcda1c4e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Python_Hand-on_Solve_200_Problems/Section 15 Sort/merge_sort_implement_solution.py
1,560
3.859375
4
# # To add a new cell, type '# %%' # # To add a new markdown cell, type '# %% [markdown]' # # %% # # Write a Python program to sort a list of elements using the merge sort algorithm. # # Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an O (n log n) # # comparison-based sorting algorithm. Most implementations produce a stable sort, which means that # # the implementation preserves the input order of equal elements in the sorted output." # # # Algorithm: # # Conceptually, a merge sort works as follows : # # # Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). # # Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list. # # # # %% # ___ mergeSort nlist # print("Splitting " ? # __ le. ? > 1 # mid _ le. ? // 2 # lefthalf _ ? |? # righthalf _ ? ?| # # ? ? # ? ? # i_j_k_0 # w___ i < le. ? an. j < le. ? # __ ? ? < ? ? # ? k _ ? ? # i _ ?+1 # ____ # ? k _ ? ? # j _ ?+1 # k _ ?+1 # # w___ i < le. ? # ? k _ ? ? # i _ ? + 1 # k _ ? + 1 # # w___ j < le. ? # ? k _ ? ? # j _ ? + 1 # k_ ? + 1 # print("Merging " ? # # nlist _ [14,46,43,27,57,41,45,21,70] # ? ? # print ? # # # %% [markdown] # # ![merge_sort.png](attachment:merge_sort.png) #
b74c5ad63523c58a2189bb4477362b007672eb24
yrmt/python
/b-设计模式/b_16_迭代子模式.py
771
3.9375
4
# 迭代器 class Iterator(object): def __init__(self, collection): self.names = collection self.index = 0 def __iter__(self): self.index = 0 return self def __next__(self): if len(self.names) > self.index: name = self.names[self.index] self.index += 1 return name else: # 扔出StopIteration 会停止迭代 raise StopIteration class Collection(list): def iterator(self): return Iterator(self) def get(self, i): return self[i] def size(self): return len(self) c = Collection() c.append("sadf1") c.append("sadf2") c.append("sadf3") print(c.size()) print(c.get(1)) print("*" * 30) for it in c.iterator(): print(it)
39b146d0acbca2a9576b85e38f978c6e93c7a49a
JCVANKER/anthonyLearnPython
/learning_Python/basis/异常/ZeroDivisionError/ZeroDivisionError.py
991
4.125
4
""" 异常的特殊对象管理程序执行期间发生的错误 每当发生让Python不知所措的错误时,都会创建一个异常对象 try-except代码块: 如果try代码块中的代码出现错误,执行except,若except指定的错误与引发的错误 相同,则运行其中的代码; try-except-else代码块: ...;如果try代码块中的代码执行成功,则运行else代码块内代码 可能引发异常的代码才需要放入try语句中,在try代码块成功执行时才需要运行else代码块 中的代码。 """ print("Give me two number, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("\nSecond_number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError:#异常对象可以不注明 print("\nYou can't divide by 0!") else: print("\n" + str(answer))
4df318e97ad8c36e103a5ba30fa36b0b1393dcfb
joeyhachem/Treasure-Maze-Search
/Bfs-A-Star-Search.py
5,847
3.59375
4
import sys import helper from functools import cmp_to_key start = 13, 2 treasure = 5, 23 bfs_path = [] nodes_explored = 0 path_hash_map = {} # Returns the cost from node passed to start node def get_cost_from_node_to_start(j: int, i: int): # Print path from start to end current = (i, j) counter = 0 while current is not None and current[0] != start[0] or current[1] != start[1]: current = path_hash_map.get(current) if current is None: break counter += 1 return counter # h(n) def calculate_manhattan_distance(x_coord: int, y_coord: int): return abs(x_coord - treasure[1]) + abs(y_coord - (treasure[0])) # Calculates f(n) = g(n) + h(n), where g(n) is the cost of the path from the current node to start node, # and h(n) is the manhattan distance formula def heuristic(first_tuple_coord: list[int], second_tuple_coord: list[int]): if (calculate_manhattan_distance(first_tuple_coord[1], first_tuple_coord[0]) + get_cost_from_node_to_start(first_tuple_coord[1], first_tuple_coord[0])) \ < (calculate_manhattan_distance(second_tuple_coord[1], second_tuple_coord[0]) + get_cost_from_node_to_start(second_tuple_coord[1], second_tuple_coord[0])): return -1 elif (calculate_manhattan_distance(first_tuple_coord[1], first_tuple_coord[0]) + get_cost_from_node_to_start(first_tuple_coord[1], first_tuple_coord[0])) \ > (calculate_manhattan_distance(second_tuple_coord[1], second_tuple_coord[0]) + get_cost_from_node_to_start(second_tuple_coord[1], second_tuple_coord[0])): return 1 else: return 0 def bfs(is_a_star_search) -> bool: queue = [[start[0], start[1]]] # Need a fifo structure for bfs -> queue global nodes_explored, path_hash_map while queue: queue_size = len(queue) for index in range(queue_size): if is_a_star_search and len(queue) > 1: # Apply heuristic function here, sort the queue size based on the lowest value of the f(n) = g(n) + # h(n). Here, g(n) which is usually the cost from one node to the next, is the same for all # directions, cost of 1 queue.sort(key=cmp_to_key(heuristic)) tuple_coord: [int, int] = queue.pop(0) # fifo nodes_explored += 1 # if we're at the treasure location, success! if tuple_coord[0] == treasure[0] and tuple_coord[1] == treasure[1]: return True helper.visited[tuple_coord[0]][tuple_coord[1]] = 1 helper.draw_maze(start, treasure) # go right, check if there is no wall. if tuple_coord[1] < len(helper.maze) - 1 and helper.maze[tuple_coord[0]][tuple_coord[1] + 1] == 0: if (tuple_coord[0], tuple_coord[1] + 1) not in path_hash_map: queue.append([tuple_coord[0], tuple_coord[1] + 1]) path_hash_map[(tuple_coord[0], tuple_coord[1] + 1)] = (tuple_coord[0], tuple_coord[1]) # Keep # track of parent for final path later # go up, check if there is no wall. if tuple_coord[0] > 0 and helper.maze[tuple_coord[0] - 1][tuple_coord[1]] == 0: if (tuple_coord[0] - 1, tuple_coord[1]) not in path_hash_map: queue.append([tuple_coord[0] - 1, tuple_coord[1]]) path_hash_map[(tuple_coord[0] - 1, tuple_coord[1])] = (tuple_coord[0], tuple_coord[1]) # go down, check if there is no wall. if tuple_coord[0] < len(helper.maze) - 1 and helper.maze[tuple_coord[0] + 1][tuple_coord[1]] == 0: if (tuple_coord[0] + 1, tuple_coord[1]) not in path_hash_map: queue.append([tuple_coord[0] + 1, tuple_coord[1]]) path_hash_map[(tuple_coord[0] + 1, tuple_coord[1])] = (tuple_coord[0], tuple_coord[1]) # go left, check if there is no wall. if tuple_coord[1] > 0 and helper.maze[tuple_coord[0]][tuple_coord[1] - 1] == 0: if (tuple_coord[0], tuple_coord[1] - 1) not in path_hash_map: queue.append([tuple_coord[0], tuple_coord[1] - 1]) path_hash_map[(tuple_coord[0], tuple_coord[1] - 1)] = (tuple_coord[0], tuple_coord[1]) return False def main(): global start, treasure gif_file_name = "bfs-maze.gif" is_a_star_search = False # Setup start and treasure positions based on run parameters if sys.argv[1] is not None: start = int(sys.argv[1]), int(sys.argv[2]) treasure = int(sys.argv[3]), int(sys.argv[4]) if len(sys.argv) > 5 and sys.argv[5] == "a": is_a_star_search = True gif_file_name = "a_star_search.gif" # ******************************** BFS, A* Search ******************************** global path_hash_map row, col = start path_hash_map = {(row, col): None} # dictionary that uses the current node being traversed as the key, and its # parent as the value. This is so we can print the path from end to start later on. if bfs(is_a_star_search): print("Found End!!") # Print path from start to end current = (treasure[0], treasure[1]) path = [(treasure[0], treasure[1])] while current is not None and current[0] != start[0] or current[1] != start[1]: current = path_hash_map.get(current) path.insert(0, current) helper.draw_maze(start, treasure, path) print("Path cost:", len(path) - 1) print("Path: ", path) print("Number of nodes explored before finding exit: ", nodes_explored) else: print("Couldn't find treasure") helper.create_and_save_gif(gif_file_name) if __name__ == "__main__": main()
ad31f0e98a97adb13b83302761675232f4606545
sonalinegi/Training-With-Acadview
/regular.py
1,449
3.8125
4
#Extract user id,domain name and suffix from the given email addresses. emails="zuck@facebook.com page33@google.com jeff42@amazon.com" import re pattern=r'(\w+)@([A-Z0-9]+)\.([A-Z]{2,4})' print("Output:") print(re.findall(pattern,emails,re.IGNORECASE)) #Retrieve all words starting with 'b' or 'B' from the given text. text = 'Betty bought a bit of butter, But the butter was so bitter , So she bought some better butter, To make the bitter butter better.' #print(text) import re print(re.findall(r'\bB\w+',text,flags=re.IGNORECASE)) #Split the given irregular sentence into words. import re sentence='"A,very very;irregular_sentence"' num=re.sub(r'[_,;]'," ",sentence) print("Output_Sentence :",num) #Clean up the given tweet so that it contains only user's message. Remove all URLs,hashtags,mentions,punctuations,RTs and CCs. tweet="'Good advice! RT @TheNextWeb: What I would do differently if I was learning to code today http://t.co/lbwej0pxOd cc: @garybernhardt #rstats'" import re def clean_tweets(tweet): #remove URLs tweet=re.sub('http\S+\s*',' ',tweet) #remove RT and cc tweet = re.sub('RT|cc', ' ', tweet) #remove hashtags tweet = re.sub('#\S+', ' ', tweet) #remove mentions tweet = re.sub('@\S+', ' ', tweet) #remove punctuations tweet = re.sub('[%s]' % re.escape("""!"#$%&'()*+,-./:;<=>?@[\]^_'{|}~"""), ' ', tweet) #remove extra whitespace tweet=re.sub('\s+',' ',tweet) return tweet print(clean_tweets(tweet))
ed6fcb9c2ae8e9521c9b4592e78337f145392b48
himanshu2922t/FSDP_2019
/DAY-02/translate.py
457
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 15:05:28 2019 @author: Himanshu Rathore """ def translate(string): translated_string = "" for char in string: if char in ('bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'): translated_string += char+'o'+char else: translated_string += char return translated_string input_string = input("Enter a string: ") print("Translated String:",translate(input_string))
b82805c0e4b17bfd1df4244f44f9782bef1014c7
in3xes/projecteuler
/problem97.py
326
3.6875
4
#!/usr/bin/env python #Problem ## 97 # #To find lat 10 digits we should only care about last 11 digits #To be safe consider 13 digits def l(num): return int(str(a)[-13:]) a = 2 ** 100 for x in range(101, 7830458): a = l(a) a = a * 2 if x%10000 == 0: print a, x a = a * 28433 a = a +1 print a
07f0f22caa9aac78355c13b4a67861875a4fbbbf
guhaigg/python
/month01/day04/exercise08.py
375
3.75
4
""" 练习: 循环录入编码值打印文字,直到输入空字符串停止。 效果: 请输入数字:113 q 请输入数字:116 t 请输入数字: Process finished with exit code 0 """ while True: str_code = input("请输入编码值:") if str_code == "": break code = int(str_code) print(chr(code))
2bc18fa38097abcdbc7b159d14b9d23cad1de919
Krdshvsk/python_less
/7.functions.py
2,877
4.21875
4
# *** Функции *** # встроенная функция ввода данных # data = input('введите данные: ') # print(f"Вы ввеели вот это - {data}") # 1 вариант. Функция, принимающие данные (обладдающаяя аргументами) def func_1(arg_1): s = arg_1 ** 2 w = s + 10 print(f"результат: {w}") # вызов функции # func_1(1000) def func_2(a, b, c): res = a + b + c res += 290 print(res) # func_2(120, 38, 1120) # аргумент может иметь значения по умолчанию def func_3(arg_1, arg_2=100): print(arg_1 * arg_2) # func_3(20, 10) # func_3(100) # func_3(3.14) # 2 вариант. Функции, возвращающая данные def func_4(arg_1, arg_2): res = arg_1 + arg_2 return res # d = func_4(10, 10) def func_5(x, y): res_1 = x * y res_2 = x / y return res_1, res_2, x #первый способ приема данных d_1 = func_5(28, 14) # второй способ приема данных a, b, c = func_5(28,14) # print(d_1) # print(d_1[0]) # print(d_1[2]) # print(a, b, c) # print(b) # *** безумынные функции (лямда-выражения, лямбда-функции) # особенности: # - всегда обладают аргументами # - всегда возваращает результат # Пример 1. лямбда внутри генератора списка my_list = [(lambda arg_1: arg_1.upper())(i) for i in "hello"] # print(my_list) # пример 2. словарь лямбда-выражений my_lambdas = { "*": lambda arg_1, arg_2: arg_1 * arg_2, "+": lambda w, z: w + z } # print(my_lambdas['+'](5, 2)) # print(my_lambdas['*'](5, 2)) # *** декоратор *** # декоратор это функция, которя обертвующая другую функцию # для того, чтобы придать таргетные фу-ции (доп.функционал) # декоратор def my_decorator(func_object): # функия обертка def wrapper(w): # доп функциональность ДО ВЫЗОВА print('Before') w = w + 2 # вызов целевой функции func_object(w) # доп функциональность ПОСЛЕ print("After") # возврат объекта функции-обертки return wrapper # новый способ применения декоратора @my_decorator # целевая функция (таргтная) def target_func(arg_1): print("hello! i am target func :)", arg_1) # старый способ применения декоратора # target_func = my_decorator(target_func) target_func(10)
1555c62758ea8daed9b4c26d9e4af73452cfccb3
arianjewel/python_begin
/Python/function.py
233
3.984375
4
'''def add(n1,n2): return n1+n2 n=int(input('enter a number: ')) m=int(input("enter another number: ")) #result=add(n,m) print('your result is ',add(n,m))''' def strchar(num): num-=1 print(a[num]) a='ahfdghdm' strchar(5)
88bcbc62847eadd799c8a760d65f5fbf6b9f7a56
davidf1000/dataanalyticsiot
/dtdavid/statistical-gis-boundaries-london/convert.py
1,033
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 25 21:40:22 2020 @author: davidfauzi """ #example : January 11, 2020 at 07:33PM timeinput=input() print(timeinput) _,_,_,_,time=timeinput.split() print(time) time=time[:-2]+":00 "+time[-2:] print(time) # Python program to convert time # from 12 hour to 24 hour format # Function to convert the date format def convert24(str1): # Checking if last two elements of time # is AM and first two elements are 12 if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] # remove the AM elif str1[-2:] == "AM": return str1[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: # add 12 to hours and remove PM return str(int(str1[:2]) + 12) + str1[2:8] # Driver Code out=convert24(time) print(out)
1f3d008861cda3cdeede7c1c072baefb0874762b
deepaksharma9dev/DSA
/Step7/change_case.py
814
3.890625
4
#method 1 # string = "AbC" # for i in range(len(string)): # string = list(string) # if ord(string[i])<=90 and ord(string[i])>=65: # string[i] = chr(ord(string[i])+32) # elif ord(string[i])<=122 and ord(string[i])>=97: # string[i] = chr(ord(string[i])-32) # print(string) # print(''.join(string)) # method 2 string = "Abc" user = input("enter in which case you wanna change the string: \n1. UPPERCASE\n2. lowercase\n3. Titlecase") string = list(string) if user == "1": for i in range(len(string)): if ord(string[i])>=97 and ord(string[i])<=122: string[i] = chr(ord(string[i])-32) elif user == "2": for i in range(len(string)): if ord(string[i])<=90 and ord(string[i])>=65 : string[i] = chr(ord(string[i])+32) print(''.join(string))
fffa3475e5a157303efe44d8bd76d6994d13ab23
Darlan-Freire/Python-Language
/exe69 - Análise de dados do grupo.py
952
3.859375
4
#Crie um prog que leia a IDADE e o SEXO de VÁRIAS PESSOAS. #A cada pessoa cadastrada, o prog deverá perguntar se o USUÁRIO quer ou não continuar. #No final, mostre: # (a) Quantas pessoas tem mais de 18 ANOS. # (b) Quantos HOMENS foram cadastrados. # (c) Quantas MULHERES tem menos de 20 ANOS. M18anos = totalhomens = mulheresmenor20 = 0 while True: idade = int(input('digite idade: ')) sexo = ' ' while sexo not in 'FM': sexo = str(input('digite o sexo:')).strip().upper()[0] if idade >= 18: M18anos += 1 if sexo == 'M': totalhomens += 1 if sexo == 'F' and idade < 20: mulheresmenor20 += 1 op = ' ' while op not in 'SN': op = str(input('quer continuar?:')).strip().upper()[0] if op == 'N': break print('\nPessoas Maiores de 18anos: ',M18anos) print('Total de Homens: ',totalhomens) print('Mulheres com menos de 20anos: ',mulheresmenor20)
edadb46ce028a894d4f0f84331fe2482388007f4
GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes
/modulos-padroes.py
966
4.40625
4
""" Um módulo é im arquivo contendo definições e instruções Python que podem ser importados para utilização de seus recursos Permitem expandir as funcionalidades da linguagem além dos recursos padrões 1) É possível utilizar módulos padrões do Python 2) É possível instalar módulos https://docs.python.org/pt-br/3/py-modindex.html """ # import random from random import randint # ctrl + space mostra todos itens dentro do import do random # Caso clique com o botão direiro no random selecionat go to e implementação # voce cnseguirá ver a implementação do modulo random # print(random.randint(1, 10)) print(randint(1, 10)) # from functools import reduce # from datetime import datetime as date #date é um apelido # print(date.now()) # from math import sqrt # print(sqrt(64)) """ PIP pip é um sistema de gerenciamento de pacotes em python pip3 install --upgrade pip pip install nome-pacote pip uninstall nome-pacote """ import pymysql
c19a8d49d35221d00bc1f27a33f2744d61d58bb6
sycLin/LeetCode-Solutions
/412.py
717
3.5625
4
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ret = [] three_counter = 0 five_counter = 0 for i in range(n): three_counter += 1 five_counter += 1 three_counter -= 3 if three_counter == 3 else 0 five_counter -= 5 if five_counter == 5 else 0 if three_counter == 0 and five_counter == 0: ret.append('FizzBuzz') elif three_counter == 0: ret.append('Fizz') elif five_counter == 0: ret.append('Buzz') else: ret.append(str(i+1)) return ret
25efd1d33a79639bf9d8f629e7ad8c91c9de982d
ozzutest/miw2021
/src/kNN.py
6,892
3.921875
4
import math import copy from operator import itemgetter from collections import Counter, defaultdict class kNearestNeighbors: """ The k - Nearest Neighbor machine learning classificator. The supervised algorithm for classification. Available metrics are with provided examples of attributes: - Euclidean - 'euclidean', - Minkowski - 'minkowski', - Manhattan - 'manhattan'. Constructor parameters: - k - defnies the number of the nearest neighbors (example: k = 3), - distance - defines the metric to use (example: distance = 'minkowski'). The implementation of this algorithm is based on 1st variation (The amount of k neighbors decides about the decision class). """ __METRICS = ['euclidean', 'manhattan', 'minkowski'] def __init__(self, k=3, metric='euclidean'): """ The constructor for algorithm """ self.__fit_data = [] if not isinstance(k, int): raise TypeError("Wrong type of k parameter") if k < 0: raise ValueError("The 'k' paramter should be greater than 0.") if metric.lower() not in self.__METRICS: raise ValueError("Inaproperiate metric value.") self.k = int(k) self.metric = metric # Euclidean metric function def __euclidean(self, v_1, v_2): distance = 0.0 # foreach index of vectors for value in range(len(v_1)): distance += math.pow(v_1[value] - v_2[value], 2) return math.sqrt(distance) # Manhattan metric function def __manhattan(self, v_1, v_2): distance = 0.0 for value in range(len(v_1)): distance += abs(v_1[value] - v_2[value]) return distance # Minkowski metric function def __minkowski(self, v_1, v_2): distance = 0.0 for value in range(len(v_1)): distance += abs(v_1[value] - v_2[value]) ** 3 return distance ** 0.3333333333333333 # Function responsible for choosing the metric def __count_distance(self, v_1, v_2): # shorten switch case metrics = {'euclidean': self.__euclidean, 'manhattan': self.__manhattan, 'minkowski': self.__minkowski} # choose the matching metric metric = metrics.get(self.metric, None) if not metric: raise ValueError(f'The metric is inaproperiate.') return metric(v_1, v_2) def fit(self, X_train_set, y_train_set): assert len(X_train_set) == len(y_train_set), "The length of training sets must be equal." # Train knn model with training sets self.X_train = X_train_set self.y_train = y_train_set if len(self.y_train) < self.k: raise ValueError(f"Expected n_samples >= n_neighbors, but... n_samples: {len(self.y_train)}, n_neighbors: {self.k}") def __predict_alt(self, x): decisions = {} for i in range(len(self.X_train)): if self.y_train[i][0] not in decisions: decisions[self.y_train[i][0]] = [] decisions[self.y_train[i][0]].append(self.__count_distance(self.X_train[i], x)) sums = {} for key in decisions.keys(): decisions[key].sort() decisions[key] = decisions[key][:self.k] sums[key] = sum(decisions[key]) del decisions decision = list(sums.keys())[0] for key, value in sums.items(): if value < decision: decision = key return decision def predict(self, X): """ Predict function based on k-nearest neighbors """ # foreach point count the distance predicts = [[self.__predict(x)] for x in X] return predicts def ppredict(self, X): """ Predict function based on k-nearest in second version """ # get predictions predictions = [[self.__predict_alt(x)] for x in X] return predictions def choose_version(self, func): """ Function defines the version of algorithm. """ # default is the first version func_obj = self.predict if func != 'first': func_obj = self.ppredict return func_obj def __predict(self, x): # compute the distances distances = [self.__count_distance(x, x_train) for x_train in self.X_train] # get the sorted distances and group them by its index k_nearest = sorted(range(len(distances)), key=lambda f: distances[f])[:self.k] # get the labels based on index of training samples k_neighbors = [self.y_train[k_nearest[index]] for index, value in enumerate(k_nearest)] # to one dimmension array flat = [value for _list in k_neighbors for value in _list] # get the most common neighbors most_common = Counter(flat).most_common(1)[0][0] return most_common def OneVsRest(self, X_set, y_set, version='first'): assert len(X_set) == len(y_set), "The length of both - decision and input columns should be the same." if not isinstance(version, str): raise TypeError("Version {version} is not the string object.") if not ('first' in version or 'second' in version): raise ValueError(f'The value {version} of parameter is invalid.') # default mode is first predict = self.choose_version(version) # pick the kNN version if version.lower() == 'second': predict = self.choose_version(version) n_row = 0 acc = 0 for n in range(len(X_set)): # testing sample based on n X_train_probe, y_train_probe = copy.deepcopy(X_set), copy.deepcopy(y_set) del X_train_probe[n] del y_train_probe[n] # rest are the train samples X_test_probe, y_test_probe = X_set[n], y_set[n] # take the train samples self.fit(X_train_probe, y_train_probe) # predict the x_test sample if version == 'second': predicted = predict([X_test_probe]) else: # predict the X_test sample predicted = predict([X_test_probe]) # if predict is succesfull if predicted[0] == y_test_probe: acc += 1 n_row += 1 print("Accuracy score: {:.2f}%,\nCovering dataset: {:.2f}".format(acc / len(X_set) * 100, len(X_set) / n_row)) return predicted
adc3ed7c037b3eaaa103a0c9841860b9181121d3
gsimoes91/Python-para-Zumbi
/Lista de Exercícios 1/Exercício_4.py
439
3.59375
4
'Exercício 4 - Faça um programa que calcule o aumento de um salário. Ele deve solicitar o valor do salário e a porcentagem do aumento. Exiba o valor do aumento e do novo salário' salario = float(input('Digite o salário em R$: ')) aumento = float(input('Digite o percentual do aumento: ')) aumento = salario * (aumento / 100) novosalario = salario + aumento print(f'Aumento: R$ {aumento:.2f}', f'Novo salario: R$ {novosalario:.2f}')
e23b5e474cc3ccfd16004b2738dda665c725133c
Zerl1990/python_algorithms
/problem_solving/cracking_the_code_interview/linked_lists/partition.py
1,034
4.34375
4
# Partition: Write code to partition a linked list around a value x. # such that all nodes less than x come before all nodes greater # than or equal to x. import os import sys from Node import head # 1->2->3->4->5->2->3->4->5 def partition(head, partition): left_side = None right_side = None it = head r_head = None while it: next_node = it.next it.next = None # Append to a side of the list if it.value < partition: if left_side: left_side.next = it left_side = left_side.next else: left_side = it head = left_side else: if right_side: right_side.next = it right_side = right_side.next else: right_side = it r_head = right_side it = next_node left_side.next = r_head if __name__ == '__main__': head.print_list() partition(head, 5) head.print_list()
4a8428404b8913d0fa96cdf9119c34a39f48811d
406project/FastCampus-Python-Django
/Week-2/02_if.py
882
3.875
4
if True: print("True") if False: print("False") a = 13 b = 12 if a < b: print("a({a})가 b({b})보다 작다.".format( a=a, b=b)) else: print"a({a})가 b({b})보다 크다.".format( a=a, b=b)) # in, not in animals = ["강아지", "고양이", "이구아나"] if "이구아나" in animals: print("이구아나를 키우고 있습니다.") else: print("이구아나를 키우고 있지 않습니다.") "이구아나" in animals # True "카멜레온" not in animals # True age = 20 while age < 30: print("20대에 나이를 먹었습니다. 현재나이:{age}".format(age=age)) age += 1 list( range(10) # [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] animals = ["강아지", "고양이"] for animal in animals: print("{animal}".format(animal=animal)) # 변수 값을 사용안할때 for _ in range(10): print("Hello World") # 별찍기
f8ef3c39e8a9fdbfe23f0316bab1378faa4a00b9
DoNotBiBi/Basic
/Error.py
924
4.25
4
# try/except # try/except...else # try-finally # try:执行代码 # except 发生异常时执行的代码 # else 没有异常时执行的代码 # finally 不管有没异常都会执行的代码 # 抛出异常 def test(): x = 3 if x > 5: raise Exception(f'x 不能大于 5。x 的值为: {x}') def error_test(): try: test() except AssertionError as error: print(error) else: try: print("没有异常") except AssertionError as error: print("还行") finally: # 相当于清理行为 print("这句话有没有异常都会执行") # 用户自定义异常 class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # try: # raise MyError(2 * 2) # except MyError as e: # print('My exception occurred, value:', e.value)
0caafec24b3fab413906682a05630a8eadaa2b20
BolajiOlajide/python-automation
/automateCSV.py
802
3.953125
4
import os import csv import json # ADAH Adah adah AdaH ADAH => Adah csv_name = input('Please provide the name for your CSV: ') file_path = 'csv/' + csv_name + '.csv' # csv/bolaji.csv if not os.path.exists(file_path): print('The CSV doesnt exist. Ensure the CSV exists in the csv folder of the project') else: print('The CSV exists.') search_name = input('What name would you like to search for? ').capitalize() # boy => Boy csv_file = csv.DictReader(open(file_path, 'r')) json_list = [] for row in csv_file: # [json_list.append(row) for row in csv_file] json_list.append(row) data = [value for value in json_list if value.get(csv_name) == search_name] if data: print(data[0].get(csv_name) + ' exists') else: print('Data doesn\'t exist')
c8cc20970a0166d5929c202da102a113fee9d3b2
DustinFlynn297/Intro-to-python
/IntroToPythonWorksheet1.py
1,850
4.5
4
import random # 1. create a function that takes user input for "favorite programming language" and compares it to a list, if the users input matches the list, return and print result to console. #create function #create list of programming languages #create prompt that takes user input #compare user input to list of programming languages #if/else statement, if user input matches an item in the list return and print to console. # def favorite_programming_language (user_input): # user_input = input('Enter your favorite programming language: ') # programming_languages = ["java", "c++", "swift", "javascript", "c#", "c", "swift", "go", "ruby", ] # for i in range(len(programming_languages)): # if user_input.lower() == programming_languages[i]: # return (user_input + ' is one of our favorite programming languages too!') # print(favorite_programming_language('input')) # 2. create a function that takes in a minimum number and maximum number, and return a random number between the min and max range. #create a function with two parameters, #create variable to hold randomly generated number #return variable/random number # def random_number_given_min_max (min_number, max_number): # random_number = random.randint(min_number, max_number) # return random_number # print(random_number_given_min_max(2, 25)) # 3. create a function that takes ina word and returns the reversal of the word. # create function that takes one parameter # create a variable to hold the user input # iterate over the word in reverse def string_reversal (original_string): original_string = input('Enter any word and we will display it spelled backwards. ') input_length = len(original_string) sliced_input =original_string[input_length::-1] print (sliced_input) string_reversal('any')
b96096c122cf1f88b194efc99741e21fe5833356
Sen2k9/Algorithm-and-Problem-Solving
/leetcode_problems/401_Binary_Watch.py
2,099
4.125
4
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. Example: Input: n = 1 Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] Note: The order of output does not matter. The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". """ class Solution: def readBinaryWatch(self, num: int): # result = [] # if num > 10 or num < 1: # return result # for i in range(12): # for j in range(60): # if bin(i).count("1") + bin(j).count("1") == num: # h = str(i) # if j < 10: # m = "0" + str(j) # else: # m = str(j) # result.append(h + ":" + m) # return result # Solution 2: backtracking import itertools def dfs(num, hours, result): if hours > num: return for hour in itertools.combinations([1, 2, 4, 8], hours): h = sum(hour) if h >= 12: continue for minute in itertools.combinations([1, 2, 4, 8, 16, 32], num - hours): m = sum(minute) if m >= 60: continue result.append("%d:%02d" % (h, m)) dfs(num, hours + 1, result) result = [] dfs(num, 0, result) return result sol = Solution() num = 3 print(sol.readBinaryWatch(num))
22beeb891e772e888c40b89761211f05b04b0a6e
Fiskmasen/prog1-kap3
/program.py
486
3.671875
4
print("Välj mellan:\n\tolles\n\tcoop\n\tmax") eat = input("Var vill du äta? ").lower() if eat == "olles": print("Du äter, grattis") elif eat == "max": print("Du sparar inte på studiebidraget") elif eat == "coop": print("Dagens motion!") coop = input("2 vitlöksbröd för 20kr? [ja/nej]").lower() if coop[0] == "j": print("Evigt ätande") elif coop[0] == "n": print("NÄHÄ!") else: print("hungrig") else: print("Sadface ")
27d07551453748063ed49e34a5dd7d3a8a50914c
ryanbrown358/PythonStuff
/Python Tutorial/test.py
240
3.8125
4
print("Hello world") """ This is a multiline comment """ #this is a single line comment #print substrings print("Hello World"[0:4]) #print numbers print(2) print(1,2,3,"Hello world") #print on a new line print("Line1\nLine2\nLine3")
804edd2835f7f4cf2e626f429cc1a2332abb2e7c
Eben2020-hp/Bangalore-Air-Quality-Index
/Data_Collection.py
1,340
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon July 12 8:30:45 2021 @author: Eben Emmanuel """ import os import time import requests ## Helps us to download the required page in the form of html. import sys ## To retrieve Data def retrive_html(): for year in range(2013, 2019): for month in range (1,13): if (month < 10): url= 'https://en.tutiempo.net/climate/0{}-{}/ws-432950.html'.format(month, year) else: url= 'https://en.tutiempo.net/climate/{}-{}/ws-432950.html'.format(month, year) texts= requests.get(url) ## To retrieve the url. text_utf= texts.text.encode('utf=8') ## We need to do UTF encoding due to some characters in the html that we need to fix. if not os.path.exists("Data/Html_Data/{}".format(year)): ## Will check if our folder is there.. If not then we will create it. os.makedirs("Data/Html_Data/{}".format(year)) with open("Data/Html_Data/{}/{}.html".format(year, month), "wb") as output: output.write(text_utf) sys.stdout.flush() if __name__ == '__main__': start_time = time.time() retrive_html() stop_time = time.time() print('Time Taken: ',stop_time-start_time)
76be895a758f86b84f7bae5bd6a5883d4691de61
julianapereira99/AAB
/Automata.py
2,487
3.859375
4
class Automata: #Construir tabela onde vamos ter um dicionário da sequencia em que os matches são construídos def __init__(self, alphabet, pattern): self.numstates = len(pattern) + 1 self.alphabet = alphabet self.transitionTable = {} self.buildTransitionTable(pattern) def buildTransitionTable(self, pattern): """ Construção da tabela de transições - Esta tabela está representada como um dicionário onde as chaves são tuplos (estado onterior, simbolo) e os values são o próximo estado """ for q in range(self.numstates): for a in self.alphabet: self.transitionTable[(q, a)] = overlap(pattern[:q] + a, pattern) def printAutomata(self): print("States: ", self.numstates) print("Alphabet: ", self.alphabet) print("Transition table:") for k in self.transitionTable.keys(): print(k[0], ",", k[1], " -> ", self.transitionTable[k]) def nextState(self, current, symbol): return self.transitionTable[(current, symbol)] def applySeq(self, seq): #guarda numa lista os estados do algoritmo à medida que processa a sequencia q = 0 res = [q] for c in seq: q = self.nextState(q, c) res.append(q) return res def occurencesPattern(self, text): #retorna a lista das posições em que o padrão se encontra na sequência q = 0 res = [] for c in range(len(text)): q = self.nextState(q, text[c]) if q == self.numstates-1: #Quando se encontrar uma ocorrência é necessário encontrar a posição inicial. Para isso subtrai-se ao tamanho do padrão res.append(c - self.numstates + 2) return res def overlap(s1, s2): #Encontra a maior sebreposição entre duas sequencias maxov = min(len(s1), len(s2)) for i in range(maxov, 0, -1): if s1[-i:] == s2[:i]: return i return 0 def test(): auto = Automata("AC", "ACA") auto.printAutomata() print(auto.applySeq("CACAACAA")) print(auto.occurencesPattern("CACAACAA")) test() # States: 4 # Alphabet: AC # Transition table: # 0 , A -> 1 # 0 , C -> 0 # 1 , A -> 1 # 1 , C -> 2 # 2 , A -> 3 # 2 , C -> 0 # 3 , A -> 1 # 3 , C -> 2 # [0, 0, 1, 2, 3, 1, 2, 3, 1] # [1, 4]
31a751edad8f06f532c6a2ae4fbdaef3dd4ab84b
geometrian/QualityCpp
/rules/leading_space.py
578
3.65625
4
#Any line beginning with at least one leading space is marked. class RuleLeadingSpace(object): NAME = "Leading Space" @staticmethod def get_description(line_numbers): result = "Beginning with space(s) on line" if len(line_numbers)>1: result+="s" return result @staticmethod def rule(path,lines): result = [] line_number = 1 for line in lines: if len(line)>=2 and line[0]==" ": result.append(line_number) line_number += 1 return result
f2fe53479e36fb6b08d5e5d4b9135166d689449d
stevestar888/leetcode-problems
/771-jewels_and_stones.py
1,403
3.71875
4
""" https://leetcode.com/problems/jewels-and-stones/ """ class Solution(object): """ Strat: Make a set to store occurances for each jewel. Then, iterate through each stone to see if it is a jewel. Stats: O(J + S) time, O(J) space -- iterate thru J and S + set of size J to store Jewels Runtime: 36 ms, faster than 6.54% of Python online submissions for Jewels and Stones. Memory Usage: 12.7 MB, less than 76.19% of Python online submissions for Jewels and Stones. """ def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ jewels = set() for jewel in J: jewels.add(jewel) num_jewels = 0 for stone in S: if stone in jewels: num_jewels += 1 return num_jewels """ (it is apparently faster if you actually do a brute force and not make a dictionary) Stats: O(J * S) time, O(1) space Runtime: 20 ms, faster than 69.03% of Python online submissions for Jewels and Stones. Memory Usage: 12.8 MB, less than 36.28% of Python online submissions for Jewels and Stones. """ def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ return sum([1 for s in S if s in list(J)])
cc3f5719f92d6c7af2105778b2d70e4a4f0ebc60
AAM77/100-days-of-code
/round 1 code/r1d18_files/one.py
986
3.9375
4
#one.py # There is no main() function in Python # Instead, everything gets run implicitly # from the very first line of a file # In Python, there is a built in variable # called __name__ # This variable (__name__) gets assigned # a string, depending on how you are # running the actual script # For example, # if you went to the command line and # wrote out 'python one.py' # it will set __name__ = "__main__" # This lets us use an if-statement # if __name__ == "__main__": # myfunc() def func(): print("FUNC() IN ONE.PY") def function1(): pass def function2(): pass # print("TOP LEVEL IN ONE.PY") # if __name__ == '__main__': # print('ONE.PY is being run directly!') # else: # print('ONE.PY has been imported!') # in Python files, the code is structured about # and then, the " if __name__ == '__main__': " # statement is used to execute the program # in a logical way # if __name__ == '__main__': # RUN THE SCRIPT! function2() function1()
8054c69afddd4b6c960d517dbae92cb557da8a4d
vinay10949/DataStructuresAndAlgorithms
/Problems/Stacks/DesignStackWithGetMinimumO1.py
2,752
4.03125
4
''' Problem Statement: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example 1: Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 Constraints: Methods pop, top and getMin operations will always be called on non-empty stacks. ''' import sys class node: def __init__(self, info): self.info = info self.next = None class Stack: def __init__(self): self.top = None self.minimum=None def isEmpty(self): if self.top is None: return True return False def getMin(self): if self.top is None: return "Stack is empty" else: print("Minimum Element in the stack is: {}" .format(self.minimum)) def push(self,data): if self.top==None: self.top=node(data) self.minimum=data elif data < self.minimum: temp = (2 * data) - self.minimum new_node = node(temp) new_node.next = self.top self.top = new_node self.minimum = data else: new_node = node(data) new_node.next = self.top self.top = new_node def pop(self): if self.isEmpty(): print("Stack Underflow") sys.exit(0) temp = self.top.info self.top = self.top.next if temp < self.minimum: value=self.minimum self.minimum = ( ( 2 * self.minimum ) - temp ) return value else: return temp def peek(self): if self.isEmpty(): print("Stack Underflow") sys.exit(0) d=self.top.info return d def display(self): if self.isEmpty(): print("Stack Underflow") sys.exit(0) self.p=self.top while self.p is not None: print(self.p.info) self.p=self.p.next if __name__=='__main__': stack=Stack() stack.push(0) stack.push(25) stack.push(5) stack.getMin() ele=stack.pop() print("poped Element in the stack is: {}" .format(ele)) stack.push(-1) stack.getMin()
742fb5f77df16aadc2cea98336743c770ea32fe3
farhad-dalirani/AUT_Machine_Learning
/machineLearning3/logistic regression regularization.py
18,781
3.65625
4
def ten_fold_cross_validation(learningFunction, _lambda, xtrain, ytrain, threshold, iteration, learningRate): """ This function use 10-fold-cv to evaluate learningFunction which can be logistic regression, and any other learning function. :param learningFunction: Is a function that learns from data to predict label of new inputs. It can be any Machine Learning algorithms like KNN, decisionTree, SVM, LR and ... :param _lambda: parameter of regularization :param xtrain: training data :param ytrain: class of training data :param learningRate: learning rate of gradient decent :param iteration: maximum number of iteration for gradient decent :return: return average 10-fold cv error """ from math import floor import copy import numpy as np # average error on 10 folds averageError = 0 # calculate size of each fold foldsize = floor(np.shape(xtrain)[0]/10) # A list that contain 10 folds folds=[] yfolds=[] # Divide dataSet to ten fold for fold in range(9): folds.append(xtrain[fold*foldsize:(fold+1)*foldsize]) yfolds.append(ytrain[fold * foldsize:(fold + 1) * foldsize]) folds.append(xtrain[(10-1) * foldsize::]) yfolds.append(ytrain[(10 - 1) * foldsize::]) argumentOFLearningFunction = {} # Train and test learning function with 10 different forms for index1, i in enumerate(folds): # Test contains fold[i] test = copy.deepcopy(i) ytest = copy.deepcopy(yfolds[index1]) # Train contains all folds except fold[i] train = np.ndarray([]) yprimetrain = np.ndarray([]) first = True for index2, j in enumerate(folds): if index2 != index1: if first == True: first = False train = copy.deepcopy(j) yprimetrain = copy.deepcopy(yfolds[index2]) else: train = np.vstack((train, copy.deepcopy(j))) #print('> ',yprimetrain,'\n>',copy.deepcopy(yfolds[index2])) yprimetrain = np.concatenate((yprimetrain, copy.deepcopy(yfolds[index2])),axis=0) #xTrain, yTrain, numberOfIter, learningRate, xTest, yTest, _lambda # Add point to argument of learningFunction argumentOFLearningFunction['xTrain'] = copy.deepcopy(train) argumentOFLearningFunction['yTrain'] = copy.deepcopy(yprimetrain) argumentOFLearningFunction['numberOfIter'] = copy.deepcopy(iteration) argumentOFLearningFunction['learningRate'] = copy.deepcopy(learningRate) argumentOFLearningFunction['xTest'] = copy.deepcopy(test) argumentOFLearningFunction['yTest'] = copy.deepcopy(ytest) argumentOFLearningFunction['_lambda'] = copy.deepcopy(_lambda) argumentOFLearningFunction['threshold'] = copy.deepcopy(threshold) # learn parameter weight, scales, costOfTrainDataSet, accuracyOfTestDataSet, rateForRoc = \ learningFunction(**argumentOFLearningFunction) averageError += (1-accuracyOfTestDataSet) averageError /= 10 return averageError def sigmoid(x): """ Sigmoid function :param x: :return: 1/(1+e^(-x)) """ import numpy as np e = np.exp(-1 * x) if e != -1: return 1/(1 + e) else: return 1/0.0001 def cost_function(thetaVec, xMat, y, _lambda): """ This function calculates cross Entropy Error :param thetaVec: weight vector :param xMat: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :return: return a scalar """ import numpy as np # Initial output error = 0 for i, x in enumerate(xMat): # Calculate cross entropy of h(x(i)) and y(i) sig = sigmoid(np.dot(x, thetaVec)) if sig == 0 or sig == 1: sig += 0.0001 signalError = -(y[i])*(np.log(sig)/np.log(2))\ -(1-y[i])*(np.log(1-sig)/np.log(2)) # Add error of i th input to total error error += signalError # Calculate entropy cost function error = (1 / (len(xMat) * 2.0)) * error #print(np.sum([theta**2 for theta in thetaVec])) # regularization error += (_lambda/(len(xMat) * 2.0))*(np.sum([theta**2 for theta in thetaVec])) # Return error return error def accuracy_of_test(thetaVec, xMat, y, threshold): """ This function calculates accuracy of test: correct classifications/total :param thetaVec: weight vector :param xMat: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :param threshold: it's a cut-off for classification :return: return a scalar """ import numpy as np # Initial output accuracy = 0 for i, x in enumerate(xMat): # Calculate cross entropy of h(x(i)) and y(i) if sigmoid(np.dot(x, thetaVec)) >= threshold and y[i]==1: accuracy += 1 elif sigmoid(np.dot(x, thetaVec)) < threshold and y[i]==0: accuracy +=1 # Calculate 1-accuracy accuracy = accuracy / len(xMat) # Return accuracy return accuracy def tpr_fpr_of_test(thetaVec, xMat, y, threshold): """ This function calculates true positive rate and false positive rate of test :param thetaVec: weight vector :param xMat: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :param cut-off for classification :return: return a [False positive rate, True positive rate] """ import numpy as np # Initial output tp = 0 fp = 0 tn = 0 fn = 0 for i, x in enumerate(xMat): # calculate tp, fp, tn, fn sig = sigmoid(np.dot(x, thetaVec)) if sig >= threshold and y[i]==1: tp += 1 if sig >= threshold and y[i]==0: fp +=1 if sig < threshold and y[i]==0: tn += 1 if sig < threshold and y[i]==1: fn +=1 # True Positive Rate if tp!=0: TPR = tp / (tp+fn) else: TPR = 0 # false Positive Rate if tn != 0: FPR = 1- tn/(tn+fp) else: FPR = 1 # Return return [FPR,TPR] def gradients(thetaVec, xMat, y, _lambda): """ This function calculates gradient of cost function :param thetaVec: weight vector :param xMat: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :return: return a vector which i th element of it, is derivative of cost function on theta[i] """ import numpy as np # Initial output newTheta = [0] * len(thetaVec) for i, x in enumerate(xMat): # Calculate difference of h(x) and y signalError = (sigmoid(np.dot(x, thetaVec)) - y[i]) / (len(xMat) * 1.0) # Update derivatives of cost function for all # parameters. d J(theta[0],theta[1], ...,theta(n)]/d(theta[index] for index, theta in enumerate(thetaVec): newTheta[index] += signalError * x[index] # Consider regularization if index != 0: newTheta[index] += _lambda/(len(xMat)*1.0) * (thetaVec[index]) # return derivatives of cost function return newTheta def gradient_descent(xMat, y, numberOfIter, learningRate, _lambda): """ This function use gradient descent to minimize cost function j over theta parameters. :param xMat: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :param numberOfIter: This argument determines number of iteration that gradient descent allowed to do for minimizing cost function :param: indicates learningRate :return: return Theta vector and a list of values of cost function in each iteration """ import numpy as np # Randomly, initial theta vector, Use normanl distribution(0,1) # for choosing weight independently. #thetaVec = np.random.normal(loc=0, scale=1, size=len(xMat[0])) thetaVec = [0] * len(xMat[0]) # values of cost function in each iteration iterCost = [cost_function(xMat=xMat, thetaVec=thetaVec, y=y, _lambda= _lambda)] # In each iteration update weight vector for iter in range(numberOfIter): # Calculate gradients gradientsOfthetaVec = gradients(thetaVec=thetaVec, xMat=xMat, y=y, _lambda= _lambda) # Update weights for index, theta in enumerate(thetaVec): thetaVec[index] = theta - learningRate * gradientsOfthetaVec[index] #print thetaVec,'*' # Update learning rate #learningRate = learningRate * 0.95 #print np.sqrt(np.dot(gradientsOfthetaVec,gradientsOfthetaVec)) # Add value of cost function to list of weight iterCost.append(cost_function(xMat=xMat, thetaVec=thetaVec, y=y,_lambda=_lambda)) # Return list of weight and costs in each iteration #print thetaVec return thetaVec, iterCost def logistic_gradient_descent(xTrain, yTrain, numberOfIter, learningRate, xTest, yTest, _lambda, threshold): """ This function use gradient descent to minimize cost function j over theta parameters. Before starting fradient descent it does a nonlinear transformation. :param xTrain: Train data, each row is a train data and each column represent a feature :param y: A vector that its rows are value of corresponding rows of x. :param numberOfIter: This argument determines number of iteration that gradient descent allowed to do for minimizing cost function :param learningRate: indicates learning rate :param xTest, yTest: for plotting :param threshold: cut-off of logistic regression :return: Return weight [Theta0,...,Theta(n)], scale of each feature, cost on train, cost on test """ import matplotlib.pylab as plt import numpy as np x_train = np.copy(xTrain) x_test = np.copy(xTest) x_train = np.transpose(x_train) x_test = np.transpose(x_test) # Find mean, min, max for normalization each feature scales = {} for index, feature in enumerate(x_train): meanOfFeature = np.mean(feature) maxOfFeature = np.max(feature) minOfFeature = np.min(feature) scales[index] = (meanOfFeature, minOfFeature, maxOfFeature) if index == 0: continue # Normalize each feature of train set and test set for i, element in enumerate(x_train[index]): if maxOfFeature != minOfFeature: x_train[index][i] = (element - meanOfFeature) / (1.0 * (maxOfFeature - minOfFeature)) else: x_train[index][i] = (element - meanOfFeature) / 1.0 for i, element in enumerate(x_test[index]): if maxOfFeature != minOfFeature: x_test[index][i] = (element - meanOfFeature) / (1.0 * (maxOfFeature - minOfFeature)) else: x_test[index][i] = (element - meanOfFeature) / 1.0 # After transpose each row is point and each column is a feature x_train = np.transpose(x_train) x_test = np.transpose(x_test) # Do gradient Descent weight, errors = gradient_descent(xMat=x_train, y=yTrain, numberOfIter=numberOfIter, learningRate=learningRate, _lambda=_lambda) ##################### # Plot error rate for each Iteration #plt.plot(errors, 'b--') #plt.title('Cost Function during training:\n Iteration: {},Alpha: {}, Lambda: {}'.format( # numberOfIter, learningRate, _lambda)) #plt.ylabel('Cross Entropy') #plt.xlabel('Each step during training') ############ #plt.show() ############ ############ ##################### # Cost function value for train data set costOfTrainDataSet = errors[ len(errors)-1] # Cost function value for test data set accuracyOfTestDataSet = accuracy_of_test(thetaVec=weight,xMat=x_test,y=yTest, threshold=threshold) #TPR, FPR rateForROC = tpr_fpr_of_test(thetaVec=weight,xMat=x_test,y=yTest, threshold=threshold) # Return weight, scale of each feature, cost on train, accuracy on test #print('>', costOfTrainDataSet, accuracyOfTestDataSet) return weight,scales, costOfTrainDataSet, accuracyOfTestDataSet,rateForROC def runCode(): """ Main function which I read inputs and calls different function for training and testing :return: none """ import scipy.io import numpy as np import matplotlib.pylab as plt numberOfIteration = 100 learningRate = 0.5 # Read Train and Test file. which are .mat files # Read Train mat = scipy.io.loadmat('Train_data.mat') train = mat['train'] # Shuffle Data np.random.shuffle(train) # Separate Label from train train = np.transpose(train) yTrain = train[len(train)-1] train = train[0:-1] # Add feature X0 which is all one RowOfOnes = np.array([1.0]*np.shape(train)[1]) train = np.vstack([RowOfOnes, train]) train = np.transpose(train) yTrain = np.transpose(yTrain) # Convert labels from -1,1 to 0,1 for ind, y in enumerate(yTrain): if y == -1: yTrain[ind] = 0 # Read Test mat = scipy.io.loadmat('Test_Data.mat') test = mat['test'] # Shuffle Data np.random.shuffle(test) # Separate Label from train test = np.transpose(test) yTest = test[len(test) - 1] test = test[0:-1] # Add feature X0 which is all one RowOfOnes = np.array([1.0] * np.shape(test)[1]) test = np.vstack([RowOfOnes, test]) test = np.transpose(test) yTest = np.transpose(yTest) # Convert labels from -1,1 to 0,1 for ind, y in enumerate(yTest): if y == -1: yTest[ind] = 0 result=[] for _lambda in [0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10]: # Use Gradient Decent to minimize optimal weights #print('Doing LR:') #weight, scales, costOfTrainDataSet, accuracyOfTestDataSet,rateForRoc = logistic_gradient_descent(xTrain=train, # yTrain=yTrain, numberOfIter=100, # learningRate=0.1, xTest=test, yTest=yTest, _lambda=_lambda,threshold=0.5) #print("Lambda: {}".format(_lambda)) #result.append([costOfTrainDataSet, accuracyOfTestDataSet,rateForRoc]) #print('Weight: ', weight, '\nScales: ', scales, '\nCostOfTrainDataSet', costOfTrainDataSet, # 'AccuracyOfTestDataSet:', accuracyOfTestDataSet, # '\nRate for ROC:', rateForRoc) # Do ten fold cross validation for each lambda errorOfThenFold_cv = ten_fold_cross_validation(learningFunction=logistic_gradient_descent, _lambda=_lambda, xtrain=train, ytrain=yTrain, threshold=0.5, iteration=numberOfIteration, learningRate=learningRate) print("=====Lambda:",_lambda,"=========") print("10-fold-CV Training Error For Test: ", errorOfThenFold_cv) print("10-fold-CV Training Error Accuracy For Test: ", 1-errorOfThenFold_cv) print("================================") result.append([errorOfThenFold_cv, _lambda]) # Best lambda result = sorted(result) print('Best Lambda is: {}, Its accuracy is:{}'.format(result[0][1],1-result[0][0])) # Use Gradient Decent to minimize optimal weights for best lambda with different threshold # print('Doing LR for best lambda:') rocPoints = [[0,0],[1,1]] for threshold in [0.5, 0.4,0.6,0.3,0.7]: weight, scales, costOfTrainDataSet, accuracyOfTestDataSet,rateForRoc = logistic_gradient_descent(xTrain=train, yTrain=yTrain, numberOfIter=numberOfIteration, learningRate=learningRate, xTest=test, yTest=yTest, _lambda=result[0][1],threshold=threshold) rocPoints.append(rateForRoc) # plot roc rocPoints = sorted(rocPoints) print(rocPoints) plt.plot([fpr[0] for fpr in rocPoints], [tpr[1] for tpr in rocPoints], 'b-') plt.plot(np.linspace(start=0,stop=1,num=100), np.linspace(start=0,stop=1,num=100), 'r--') plt.title('ROC for lambda: {}'.format(result[0][1])) plt.xlabel('FPR') plt.ylabel('TPR') plt.show() # Use Gradient Decent to minimize optimal weights for lambda 0 with different threshold # print('Doing LR for lambda: 0') rocPoints = [[0, 0], [1, 1]] for threshold in [0.5, 0.4, 0.6, 0.3, 0.7]: weight, scales, costOfTrainDataSet, accuracyOfTestDataSet, rateForRoc = logistic_gradient_descent(xTrain=train, yTrain=yTrain, numberOfIter=numberOfIteration, learningRate=learningRate, xTest=test, yTest=yTest, _lambda=0, threshold=threshold) rocPoints.append(rateForRoc) # plot roc rocPoints = sorted(rocPoints) print(rocPoints) plt.plot([fpr[0] for fpr in rocPoints], [tpr[1] for tpr in rocPoints], 'b-') plt.plot(np.linspace(start=0, stop=1, num=100), np.linspace(start=0, stop=1, num=100), 'r--') plt.title('ROC for lambda: {}'.format(0)) plt.xlabel('FPR') plt.ylabel('TPR') plt.show() if __name__ == '__main__': runCode()
c72275f0282e16123532d125a71abf24a0855291
gengwg/Python
/list2dict.py
808
4
4
# Convert List to Dictionary: Even items as keys, odd items as values # Example: # inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4] # I want to create a dictionary from this list, # where the items in the even positions (apples, oranges, limes, bananas, grapes) are the keys, # and the items in the odd positions (2, 3, 10, 7, 4) are the values. # inv_dict = {'apples':2, 'oranges':3, 'limes':10, 'bananas':7, 'grapes':4} # https://stackoverflow.com/questions/38194403/list-to-dictionary-even-items-as-keys-odd-items-as-values with open('input.txt') as f: content = f.readlines() content = [x.strip() for x in content] #print(content) content_dict = dict(zip(content[::2], content[1::2])) print(content_dict) for k, v in content_dict.items(): print('{}, {}'.format(k, v))
2c31f91ec35087fab4d98444d52430c50a5d34f4
bstelly/PythonPractice
/main.py
790
3.765625
4
#pylint: disable = E1101 #pylint: disable = W0312 import os def add(lhs, rhs): return lhs + rhs def subtract(lhs, rhs): return lhs - rhs def multiply(lhs, rhs): return lhs * rhs def divide(lhs, rhs): return lhs/rhs user_input = 0 while user_input != 5: print "What would you like to do? Input number.\n" print "1. Add 2.Subtract 3.Multiply 4.Divide 5. EXIT\n" user_input = input("Input Selection\n") os.system('cls') if user_input != 5: lhs = input("Input a number\n") rhs = input("Input another number \n") os.system('cls') if user_input is 1: print add(lhs, rhs) elif user_input is 2: print subtract(lhs, rhs) elif user_input is 3: print multiply(lhs, rhs) elif user_input is 4: print divide(lhs, rhs) os.system('pause') os.system('cls')
b15d68c4c8eecbb27b6c94b075983dcfdb583aac
ianpaulleong/collatz
/collatz.py
340
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 16:27:31 2019 @author: GAMEZ """ def collatz(theNum): curNum = theNum numList = list([curNum]) while curNum > 1: if curNum%2 == 1: curNum = int(curNum*3 + 1) else: curNum = int(curNum/2) numList.append(curNum) return numList
6ca1fb87730b30078a8647d7744d9d21061009f9
kanekyo1234/AtCoder_solve
/ABC/110/C-1.py
296
3.53125
4
import collections s=input() t=input() s= collections.Counter(s) t= collections.Counter(t) #print(s) sans=[] tans=[] for v in s.values(): sans.append(v) for v in t.values(): tans.append(v) sans.sort() tans.sort() #print(sans,tans) if sans==tans: print('Yes') else: print('No')
3381a36c4153ff56061800530ae8b6d92b66f225
jvtamm/online-judges
/hackerrank/warmup/repeatedstring.py
995
3.921875
4
#!/bin/python3 import os # Complete the repeatedString function below. def repeatedString(s, n): current_index = 0 #Stores the number of a's seen until index i lpa = [] for digit in s: if(digit == 'a'): if(not lpa): lpa.append(1) else: lpa.append(lpa[current_index - 1] + 1) else: if(not lpa): lpa.append(0) else: lpa.append(lpa[current_index - 1]) current_index += 1 # Calculates the amount of the word s fits in n full_word = int(n / current_index) # Calculates the amount of letters that should sum to full word to equal n remainder = n % current_index if(remainder == 0): return full_word * lpa[-1] else: return full_word * lpa[-1] + lpa[remainder - 1] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() n = int(input()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close()
96c8440ab12b5bf6d78e7b52be2f086db5758714
mseidenberg13/python_challenge
/PyBank/main.py
2,044
3.578125
4
import os import csv PyBank_csv = os.path.join("Resources","budget_data.csv") profit = [] monthly_changes = [] date = [] count = 0 total = 0 total_change = 0 initial_profit = 0 with open(PyBank_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) for row in csvreader: count = count + 1 date.append(row[0]) profit.append(row[1]) total = total + int(row[1]) final_profit = int(row[1]) monthly_change_total = final_profit - initial_profit monthly_changes.append(monthly_change_total) total_change = total + monthly_change_total initial_profit = final_profit average_change = (total_change/count) most_increase = max(monthly_changes) most_decrease = min(monthly_changes) increase_date = date[monthly_changes.index(most_increase)] decrease_date = date[monthly_changes.index(most_decrease)] print("Financial Analysis") print("----------------------------------------------------------") print("Total Months: " + str(count)) print("Total: " + "$" + str(total)) print("Average Change: " + "$" + str(int(average_change))) print("Greatest Increase in Profits: " + str(increase_date) + " ($" + str(most_increase) + ")") print("Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(most_decrease)+ ")") with open('PyBank_analysis.txt', 'w') as text: text.write("Financial Analysis"+ "\n") text.write("----------------------------------------------------------\n\n") text.write("Total Months: " + str(count) + "\n") text.write("Total: " + "$" + str(total) +"\n") text.write("Average Change: " + '$' + str(int(average_change)) + "\n") text.write("Greatest Increase in Profits: " + str(increase_date) + " ($" + str(most_increase) + ")\n") text.write("Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(most_decrease) + ")\n")
8c35008e3eafc6f0877dd65325ee051cea3afaf3
ggrecco/python
/basico/zumbis/jogo_2.py
291
3.734375
4
from random import randint secreta = randint(1, 100) while True: chute = int(input("Chute:")) if chute == secreta: print("parabéns, vc acertou o número {}".format(secreta)) break else: print("Alto" if chute > secreta else "Baixo") print("Fim do jogo")
d8a230f48b0d4ba259d17e6045c24c97f5e9f41f
pmontesd/katando_python
/20180915/02_enclavedeJa/03/enclavedeja.py
949
3.609375
4
def add_to_discount_list(season, discount_lists): for discount_list in discount_lists: if season not in discount_list: discount_list.append(season) return discount_lists.append([season]) return def get_series_price(seasons): prices = { "0": 2.5, "1": 3, "2": 3.5, "3": 4, "4": 4.5, "5": 5 } discount = { "1": 1, "2": 1, "3": .9, "4": .8, "5": .7, "6": .7 } curr_discount = discount[str(len(seasons))] return curr_discount * sum([prices[str(season)] for season in seasons if season != 5]) + seasons.count(5) * prices["5"] def get_price(seasons): discount_lists = [] for season in seasons: add_to_discount_list(season, discount_lists) print(discount_lists) return round(sum([get_series_price(discount_list) for discount_list in discount_lists]), 2)
be9f0456747d5663ff42173a9c675a9414464937
berman82312/google-foobar
/level4_1 - Running with Bunnies/solution.py
2,063
3.59375
4
def carry_in_remain(distance, remains, start, end, time_left): if len(remains) == 0: time_spent = distance[start][end] if time_spent <= time_left: return [start] else: return False else: time_spent = distance[start][end] max_carried = [] can_reach = False if time_spent <= time_left: # if directly go to exit max_carried.append(start) can_reach = True for m in remains: time_spent = distance[start][m] current_left = remains[:] current_left.remove(m) carry = carry_in_remain(distance, current_left, m, end, time_left - time_spent) if carry: carry.append(start) if len(carry) > len(max_carried): max_carried = carry can_reach = True if can_reach: return max_carried else: return False def solution(times, times_limit): distance = [] # Bellman-Ford for every i->j for m in xrange(len(times)): shortest = times[m] for _ in xrange(len(times)): for i in xrange(len(times)): for j in xrange(len(times)): if i == j: continue temp = shortest[i] + times[i][j] if temp < shortest[j]: shortest[j] = temp distance.append(shortest) # do one more to check negative circle for i in xrange(len(times)): for j in xrange(len(times)): if i == j: continue temp = distance[0][i] + times[i][j] if temp < distance[0][j]: # print(range(len(times) - 2)) return range(len(times) - 2) remains = list(range(1, len(times) - 1)) max_carried = [] start = 0 end = len(times) - 1 # find the longest path we can travel for m in remains: time_spent = distance[start][m] current_left = remains[:] current_left.remove(m) carry = carry_in_remain(distance, current_left, m, end, times_limit - time_spent) if carry: if len(carry) > len(max_carried): max_carried = carry[:] max_carried.sort() result = [x - 1 for x in max_carried] # print(result) return result
79e165e32cb1872266410ce6b7f66e48d05886fc
dnootana/Python
/Interview/MatrixFindNoOfIslands.py
382
4.28125
4
#!/usr/bin/env python3.8 """ Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Example: Input : mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}} Output : 5 """
93f4e1a023a0c213a5c8d551c185c20864b8215f
anantkaushik/Competitive_Programming
/Python/GeeksforGeeks/repetitive-addition-of-digits.py
879
4
4
""" Problem Link: https://practice.geeksforgeeks.org/problems/repetitive-addition-of-digits/0 Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Input: The first line contains 'T' denoting the number of testcases. Then follows description of testcases. The next T lines contains a single integer N denoting the value of N. Output: Output the sum of all its digit until the result has only one digit. Constraints: 1<=T<=30 1<=n<=10^9 Example: Input : 2 1 98 Output : 1 8 Explanation: For example, if we conisder 98, we get 9+8 = 17 after first addition. Then we get 1+7 = 8. We stop at this point because we are left with one digit. """ def addDigit(n): if n == 0: return 0 elif n % 9 == 0: return 9 return n % 9 for _ in range(int(input())): n = int(input()) print(addDigit(n))
838831687906f18fc97f546f57cc44a636c51724
smallfishxz/Practice_Algorithm
/List/String_Compression.py
1,371
3.828125
4
# Iterate through the string char by char, and count its repeats. When next char is not the same as the current one, append the char and its repeats to the result string. # In the end return the result string only when it is shorter. def str_compression1(s): # In order to improve, check ahead of time before generating the compressed string anyways, using the folling three lines of code. # The function count_compression also have quite a few of dup codes as the main function, so it is debatable whehter this is worth. # final_l = count_compression(s) # if final_l > len(s): # return s result = "" count_consecutive = 0 size = len(s) for i in range(size): count_consecutive += 1 if i+1 == size or s[i] != s[i+1]: result += s[i] result += str(count_consecutive) count_consecutive = 0 return result if len(result) < len(s) else s def count_compression(s): compressed_l = 0 count_consecutive = 0 size = len(s) for i in range(size): count_consecutive += 1 if i+1 == size or s[i] != s[i+1]: compressed_l += 1 + len(str(count_consecutive)) count_consecutive = 0 return compressed_l print(str_compression1('aabcccccaaaaaaaaaaaaaaaaaaa')) print(count_compression('aabcccccaaaaaaaaaaaaaaaaaaa')) print(str_compression1('aab')) print(count_compression('aab'))
dffbe05d5c54b9d24558ee6f4ba91d05007238e9
FarazHossein/RallyGame
/main.py
9,292
3.515625
4
""" This is the main program to be run to run the game. Contributors: Siddharth - car, checkpoints Faraz - sounds, music, liaison classes implementation Rick - different screens, scores, times Shraddha - testing """ import pygame from images import * from carControl import Car import button import score_board import key_input import GameOver from Instructions import instruction_screen, render_text pygame.init() # Sets up screen fps_clock = pygame.time.Clock() # Used to control fps of program screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # Program variables frame_rate = 60 screen_width = pygame.display.get_surface().get_size()[0] screen_height = pygame.display.get_surface().get_size()[1] width = screen_width // 2 height = screen_height // 2 pygame.display.set_caption("Mahmoud Rally 8 Supreme") # Sets window caption screen_control = 0 counter = 0 # Counter used for screen switches and countdowns; unrelated to player's lap time x = 800 y = 800 # set the x,y coordinates for the checkpoints (separated by horizontal and vertical road checkpoints) checks_hor = [[width - 50, height + 197], [width - 346, height - 72], [width - 100, height - 316], [width + 300, height - 120]] checks_ver = [[width - 339, height + 100], [width - 441, height - 150], [width + 125, height - 170], [width + 373, height + 100]] # create the player object player = Car(width + 150, height + 230, 310, 0) # Player info name = "" time = 0 # Time of round (divide by frame_rate to get time in seconds) scores = score_board.ScoreBoard("score_board.txt") # set the phase for checking the checkpoints check_phase = 1 # create an instance for the game over function gameover = GameOver.Game_Over() # Buttons play_button = button.Button(pygame.image.load("graphics/play_button.png"), screen_width // 2, screen_height // 2 + 120, 400, 160) exit_button = button.Button(pygame.image.load("graphics/exit_button.png"), screen_width // 2, screen_height // 2 + 320, 400, 160) okay_button = button.Button(pygame.image.load("graphics/okay_button.png"), screen_width // 2, screen_height // 2 + 320, 400, 160) retry_button = button.Button(pygame.image.load("graphics/retry_button.png"), screen_width // 2, screen_height // 2 + 120, 400, 160) menu_button = button.Button(pygame.image.load("graphics/menu_button.png"), screen_width // 2, screen_height // 2 + 320, 400, 160) # Music pygame.mixer.music.load('music/Music.mp3') pygame.mixer.music.play() # set the font for the on screen text font = pygame.font.Font("arial.ttf", 48) font_l = pygame.font.Font("arial.ttf", 144) white = (255, 255, 255) black = (0, 0, 0) # Main program loop running = True while running: # Checks for events for event in pygame.event.get(): if event.type == pygame.QUIT: # If the user clicks quit, stops the program loop running = False screen.fill(white) # Sets background mouse_x, mouse_y = pygame.mouse.get_pos() # Gets mouse coordinates and saves to shorter variable l_click = pygame.mouse.get_pressed()[0] # Gets left click true/false and saves to shorter variable keys = pygame.key.get_pressed() # Gets all keys being pressed # Loading screen if screen_control == 0: pygame.Surface.blit(screen, loading_image, (0, 0)) # Loading background # Switches to next screen after 1 second if counter >= 1 * frame_rate: screen_control = 1 # Title screen elif screen_control == 1: pygame.Surface.blit(screen, menu_image, (0, 0)) # Menu background # Draws buttons play_button.draw(screen) exit_button.draw(screen) # Goes to next screen when play button is clicked if play_button.detect_click(mouse_x, mouse_y, l_click): screen_control = 1.5 # Closes when exit button is clicked if exit_button.detect_click(mouse_x, mouse_y, l_click): running = False # Enter name screen elif screen_control == 1.5: pygame.Surface.blit(screen, menu_image, (0, 0)) # deisplay Menu background name = key_input.key_input(name, keys) # Gets all keyboard and uses it to update name text = font.render("Enter Name: " + name, True, white) pygame.Surface.blit(screen, text, (screen_width // 5, screen_height // 2)) # Draws buttons okay_button.draw(screen) # Goes to instructions screen when okay button is clicked if okay_button.detect_click(mouse_x, mouse_y, l_click): # If the player did not enter a name, set it to Player if len(name) == 0: name = "Player" screen_control = 2 # Instructions screen elif screen_control == 2: pygame.Surface.blit(screen, Instruction, (0, 0)) # Loading background # Draws buttons okay_button.draw(screen) # call the instruction_screen function fro Instructions.py instruction_screen('instructions.txt') # Calling function # Goes to game screen when okay button is clicked if okay_button.detect_click(mouse_x, mouse_y, l_click): screen_control = 3 player.reset() time = 0 counter = 0 # Game screen elif screen_control == 3: # this draws the background image pygame.draw.rect(screen, (255, 207, 158), [0, 0, screen_width, screen_height]) # Track background pygame.Surface.blit(screen, track_image, (screen_width // 2 - 500, screen_height // 2 - 400)) # Track # this establishes the count down before the game commences if 0 <= counter // frame_rate < 1: text = font_l.render("3", True, black) pygame.Surface.blit(screen, text, (screen_width // 2 - 30, screen_height // 2 - 30)) elif 1 <= counter // frame_rate < 2: text = font_l.render("2", True, black) pygame.Surface.blit(screen, text, (screen_width // 2 - 30, screen_height // 2 - 30)) elif 2 <= counter // frame_rate < 3: text = font_l.render("1", True, black) pygame.Surface.blit(screen, text, (screen_width // 2 - 30, screen_height // 2 - 30)) else: # Increases and displays time time += 1 text = font.render(str(int(100 * time / frame_rate) / 100), True, (0, 0, 0)) # draw the first 2 checkpoints pygame.draw.rect(screen,(255,0,0),[checks_hor[0][0],checks_hor[0][1],20,93]) pygame.draw.rect(screen,(255,0,0),[checks_ver[0][0],checks_ver[0][1],102,20]) # draw the remaining horizontal checkpoints for i in range(3): pygame.draw.rect(screen,(255,0,0),[checks_hor[i+1][0],checks_hor[i+1][1],20,90]) # draw the remaining vertical checkpoints for p in range(3): pygame.draw.rect(screen,(255,0,0),[checks_ver[p+1][0],checks_ver[p+1][1],96,20]) # if the check_phase is 1: if check_phase == 1: # call the checkpoint detection function player.detect() # call the function that checks if all the checkpoints have been crossed player.checker() # if the return value of checker is True... if player.checker() is True: # If the player finishes scores.add_entry(name, time / frame_rate) # Adds player's score to scoreboard scores.sort_ascending() # Sorts by ascending, since the players with the lowest times are better scores.export_score_board() # Saves new scores to file screen_control = 4 # call the move function from player player.move() pygame.Surface.blit(screen, text, (25, 25)) # End screen elif screen_control == 4: pygame.Surface.blit(screen, game_over_image, (0, 0)) # Game over background pygame.mixer.pause() TEXT_COLOUR = (255, 255, 255) BUTTON_COLOUR = (100, 0, 110) BUTTON_COLOUR_HIGHLIGHT = (120, 72, 124) # Draws time text = font.render("Final Time: " + str(int(100 * time / frame_rate) / 100), True, white) pygame.Surface.blit(screen, text, (20, 20)) # Draws scoreboards of time (top 10) scores.draw(screen, screen_width // 2 - 80, screen_height // 2 - 300, "arial.ttf", 24, white, 10) # Calling GameOver class functions (Button and mouse detection for retry and menu button) gameover.game_over() gameover.play_again() # Mouse detection for menu button and resetting variables if menu_button.detect_click(mouse_x, mouse_y, l_click): # If the player did not enter a name, set it to Player screen_control = 1 player.reset() time = 0 counter = 0 name = "" elif retry_button.detect_click(mouse_x, mouse_y, l_click): # If the player did not enter a name, set it to Player screen_control = 3 player.reset() time = 0 counter = 0 pygame.display.flip() # Updates screen fps_clock.tick(frame_rate) # Sets program to 60fps counter += 1 pygame.quit() # Quits at the end
13f6f0c8d8832c23d76921855f216d8972a08a54
rustytwilight/sandypi
/server/utils/buffered_timeout.py
1,310
3.5625
4
from threading import Thread, Lock import time # this thread calls a function after a timeout but only if the "update" method is not called before that timeout expires class BufferTimeout(Thread): def __init__(self, timeout_delta, function, group=None, target=None, name=None, args=(), kwargs=None): super(BufferTimeout, self).__init__(group=group, target=target, name=name) self.name = "buffered_timeout" self.timeout_delta = timeout_delta self.callback = function self.mutex = Lock() self.is_running = False self.setDaemon(True) self.update() def set_timeout_period(self, val): self.timeout_delta = val def update(self): with self.mutex: self.timeout_time = time.time() + self.timeout_delta def stop(self): with self.mutex: self.is_running = False def run(self): self.is_running = True while self.is_running: with self.mutex: timeout = self.timeout_time current_time = time.time() if current_time > timeout: self.callback() self.update() with self.mutex: timeout = self.timeout_time time.sleep(timeout - current_time)
0702d5c22eee8ae1c180f93e2699d6a2490cd3cf
hc388/calculator_Team
/Calculator/Calculator.py
1,169
3.5625
4
import math from MathOperations.Addition import Addition from MathOperations.Subtraction import Subtraction from MathOperations.Division import Division from MathOperations.Multiplication import Multiplication from MathOperations.Logarithm import Logarithm from MathOperations.Exponentiation import Exponentiation from MathOperations.nthRoot import nthRoot class Calculator: result = 0 def __init__(self): pass def addition(self, a, b): self.result = Addition.sum(a, b) return self.result def subtraction(self, a, b): self.result = Subtraction.difference(a, b) return self.result def multiplication(self, a, b): self.result = Multiplication.multiply(a, b) return self.result def divide(self, a, b): self.result = Division.divide(a, b) return self.result def nthRoot(self, a, b): self.result = nthRoot.rooting(a, b) return self.result def exponentiate(self, a, b): self.result = Exponentiation.power(a, b) return self.result def logger(self, a, b): self.result = Logarithm.log(a, b) return self.result
8700650e4841478f35f30e35459fa1c2ee74a82d
thelsandroantunes/EST-UEA
/LPI/Listas/L2_LPI - repetição e condicionais/exe55l2.py
612
3.953125
4
# Autor: Thelsandro Antunes # Data: 13/05/2017 # EST-UEA # Disciplina: LP1 # Professora: Elloa B. Guedes # 2 Lista de Exercicios (06/04/2015) # Questao 55: Escrever um programa para ler um numero inteiro do usuario e exibir # o maior numero primo que seja menor do que o numero digitado. from __future__ import print_function n = int(input("n?")) while(True): n=n-1 ehprimo = True if((n<=1) or ((n%2==0) and (n!=2))): ehprimo = False else: for d in range(3,(n//2)+1,2): if((n%d)==0): ehprimo=False break if(ehprimo): print(n) print("Eh primo") break
de09cf1c729e3ad2a9fdc5075eef63a5fd2e8ec5
TheAlgorithms/Python
/strings/wildcard_pattern_matching.py
3,348
4.4375
4
""" Implementation of regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). """ def match_pattern(input_string: str, pattern: str) -> bool: """ uses bottom-up dynamic programming solution for matching the input string with a given pattern. Runtime: O(len(input_string)*len(pattern)) Arguments -------- input_string: str, any string which should be compared with the pattern pattern: str, the string that represents a pattern and may contain '.' for single character matches and '*' for zero or more of preceding character matches Note ---- the pattern cannot start with a '*', because there should be at least one character before * Returns ------- A Boolean denoting whether the given string follows the pattern Examples ------- >>> match_pattern("aab", "c*a*b") True >>> match_pattern("dabc", "*abc") False >>> match_pattern("aaa", "aa") False >>> match_pattern("aaa", "a.a") True >>> match_pattern("aaab", "aa*") False >>> match_pattern("aaab", ".*") True >>> match_pattern("a", "bbbb") False >>> match_pattern("", "bbbb") False >>> match_pattern("a", "") False >>> match_pattern("", "") True """ len_string = len(input_string) + 1 len_pattern = len(pattern) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. dp = [[0 for i in range(len_pattern)] for j in range(len_string)] # since string of zero length match pattern of zero length dp[0][0] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1, len_string): dp[i][0] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1, len_pattern): dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1, len_string): for j in range(1, len_pattern): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: dp[i][j] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): dp[i][j] = dp[i - 1][j] else: dp[i][j] = 0 else: dp[i][j] = 0 return bool(dp[-1][-1]) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") input_string = "aab" pattern = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"{input_string} matches the given pattern {pattern}") else: print(f"{input_string} does not match with the given pattern {pattern}")
323357a32f8b508e9f3582576b6fa40fd44a0e07
JakobKallestad/Python-Kattis
/src/Veci.py
332
3.5
4
import sys raw_n = input() n = int(raw_n) digit_list = [c for c in raw_n] if raw_n == ''.join(sorted(raw_n))[::-1]: print(0) sys.exit(0) current = n+1 while True: i = str(current) if len(i) != len(raw_n): continue if sorted(i) == sorted(raw_n): print(current) break current += 1
91e269b36fe61885766ebd5de049f2bbc80a87b2
joobond/ExerPython
/URI/1008.py
113
3.5
4
n = int(input()) h = int(input()) v = float(input()) sal = h*v print(("NUMBER = %d\nSALARY = U$ %.2f")%(n,sal))
46a5b705cc56953719e939eb7845bebccfb4991c
Sviatoslav-Lobanov/Python_learning
/X and O.py
2,103
3.96875
4
def print_step (table): # Печать игрового поля print (' | 1 | 2 | 3 |') print ('---------------') for i in range(len(table)): print(f'{i+1} | {table[i][0]} | {table[i][1]} | {table[i][2]} |') print('---------------') def check (a): # Проверка введенных координат point = input(f'Введите {a} :') if (point == '1') or (point == '2') or ((point == '3')) : return int(point) else: print('Введите числа 1, 2 или 3') return check (a) def choose(a): # выбор ячейки на игровом поле print(f'Ходит {a}') x = check('горизонталь')-1 y = check('вертикаль')-1 if square[x][y] == ' ': square[x][y] = a else: print('Клетка занята, нужно изменить выбор') choose(a) def winner (): combo = [[(0,0),(0,1),(0,2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], [(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)]] for i in range(8): if square[combo[i][0][0]][combo[i][0][1]]==square[combo[i][1][0]][combo[i][1][1]]==square[combo[i][2][0]][combo[i][2][1]]!=' ': print(i, square[combo[i][0][0]][combo[i][0][1]], square[combo[i][1][0]][combo[i][1][1]], square[combo[i][2][0]][combo[i][2][1]], combo[i]) return combo[i] # New game square = [[' ']*3 for i in range(3)] print('Привет, это ваше поле', 'Первыми ходят X, вторыми O','Для хода введите координаты',sep='\n') print_step(square) champion = None for i in range(9): mark = 'X' if i % 2 == 0 else 'O' choose(mark) print_step(square) champion = winner() if champion: print(f'Победил {mark} с комбинацией {champion}') break if champion is None: print('Ничья')
14181605223993953f0d338b549ab218af9d1238
myf-algorithm/Leetcode
/Huawei/106.求解立方根.py
152
3.90625
4
import math while True: try: num = float(input()) num2 = math.pow(num, 1.0/3) print('%.1f' % num2) except: break
ecec82f7d6a458418140579021abfe8fd06af04d
waithope/codewars
/CodeWars.py
12,745
3.796875
4
# 0123456789 # 0########## # 1## ## # 2# # # # # 3# # # # # 4# ## # # 5# ## # # 6# # # # # 7# # # # # 8## ## # 9########## # rowCount = 10 # columnCount = 10 # for i in range(rowCount): # for j in range(columnCount): # if i == 0 or i == rowCount - 1 or j == 0 or \ # j == columnCount - 1 or i == j or j == columnCount - i - 1: # print("#", end='') # else: # print(" ", end='') # print() def high_and_low(numbers): # l = numbers.split(' ') # print(l) # min = int(l[0]) # max = int(l[0]) # for num in l: # if int(num) < min: # min = int(num) # if int(num) > max: # max = int(num) # more clever l = [int(num) for num in numbers.split(' ')] return str(max(l)) + ' ' + str(min(l)) # print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")) ## Descending Order # def Descending_Order(num): # return int(''.join(sorted(str(num), reverse=True))) # print(Descending_Order(10147237031)) # # initialize # a = [] # # create the table (name, age, job) # a.append(["Nick", 30, "Doctor"]) # a.append(["John", 8, "Student"]) # a.append(["Paul", 22, "Car Dealer"]) # a.append(["Mark", 66, "Retired"]) # # sort the table by age # import operator # a.sort(key=operator.itemgetter(0, 1), reverse=True) # # print the table # print(a) def DNA_strand(dna): dna_map = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' } return ''.join([dna_map[sym] for sym in dna]) def DNA_strand_v2(dna): return dna.translate(str.maketrans('ATCG', 'TAGC')) # assert(DNA_strand('ATTGC') == 'TAACC') ## Given a string, replace every letter with its position in the alphabet. ## a being 1, b being 2, etc. def alphabet_position(text): return ' '.join([str(ord(item.lower()) - ord('a') + 1) \ for item in text if item.isalpha() \ ]) # print(alphabet_position('asdjfak')) ## Take a list of non-negative integers and strings ## Returns a new list with the strings filtered out. def filter_list(l): return [item for item in l if item is not str(item)] def filter_list_v2(l): return [item for item in l if not isinstance(item, str)] # print(filter_list([1,2,'aasf','1','123',123]) == [1,2,123]) ## Decode morse_code MORSE_CODE = { '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '-----': '0', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '.-.-.-': '.', '--..--': ',', '..--..': '?', '.----.': "'", '-.-.--': '!', '-..-.': '/', '-.--.': '(', '-.--.-': ')', '.-...': '&', '---...': ':', '-.-.-.': ';', '-...-': '=', '.-.-.': '+', '-....-': '-', '..--.-': '_', '.-..-.': '"', '...-..-': '$', '.--.-.': '@', '...---...': 'SOS' } def decodeMorse(morse_code): morse_code_part = morse_code.strip().split(' ') space_cnt = 0 output = '' for ele in morse_code_part: if ele is '': space_cnt += 1 if space_cnt == 2: space_cnt = 0 output += ' ' else: output += MORSE_CODE[ele] return output def decodeMorse_v2(morse_code): return ' '.join([ ''.join([MORSE_CODE[code] for code in word.split(' ')]) for word in morse_code.strip().split(' ') ]) # print(decodeMorse_v2(".... . -.-- .--- ..- -.. .")) ## persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126, ## # 1*2*6 = 12, and finally 1*2 = 2. def persistence(n): factors = list(str(n)) cnt = 0 if len(factors) <= 1: return 0 res = int(factors[0]) for i in range(1, len(factors)): res *= int(factors[i]) cnt = persistence(res) return cnt + 1 from functools import reduce ## reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5) def persistence_v2(n): factors = [int(x) for x in str(n)] i = 0 while len(factors) > 1: res = reduce(lambda x, y: x*y, factors) i += 1 factors = [int(x) for x in str(res)] return i # print(persistence_v2(999)) def get_sign(x): return (x > 0) - (x < 0) # print(get_sign(-1)) ## Write a function to calculate the absolute value of a 32-bit integer def myabs(x): high_bit_mask = x >> 31 return (x ^ high_bit_mask) - high_bit_mask # print(myabs(7)) # import random # print(random.randrange(10)) ## Dig Pow 89 = 8^1 + 9^2 def sum_dig_pow(a, b):# range(a, b + 1) will be studied by the function output = [] for num in range(a, b+1): parts = list(str(num)) new_num = 0 for exp, base in enumerate(parts, 1): new_num += (int(base))**exp if num == new_num: output.append(num) return output def dig_pow(n): return sum([int(y)**x for x, y in enumerate(str(n), 1)]) def sum_dig_pow_v2(a, b): return [num for num in range(a, b+1) if num == dig_pow(num)] # print(sum_dig_pow_v2(89,135)) def countBits(n): count = 0 while n > 0: n = n & (n - 1) count += 1 return count # unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] # unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] # unique_in_order([1,2,2,3,3]) == [1,2,3] def unique_in_order(iterable): unique = [] prev = None for char in iterable: if char != prev: unique.append(char) prev = char return unique # print(unique_in_order([])) def duplicate_count(text): ## str.count(sub) count the ocurrences of substring occurs = [text.lower().count(char_cnt) for char_cnt in list(set(list(text.lower)))] cnt = 0 for num in occurs: if num > 1: cnt += 1 return cnt def duplicate_count_v2(text): return len([c for c in set(text.lower()) if text.lower().count(c) > 1]) # print(duplicate_count_v2("aaBbccddeeffgg")) # add 2 integers using bitwise operations # but need to deal with special case a < 0; b > 0 abs(a) < b def add(a, b): while a: b, a = b ^ a, (b & a) << 1 return b print(add(-1, -800)) def reverseWords(str): return ' '.join(str.split(' ')[::-1]) # print(reverseWords("hello world")) ## if a portion of str1 characters can be rearranged to match str2, ## otherwise returns false. # Only lower case letters will be used (a-z). # No punctuation or digits will be included. # Performance needs to be considered. # scramble('rkqodlw', 'world') ==> True # scramble('katas', 'steak') ==> False ##cost time 4861ms def scramble_v1(s1,s2): for c in set(s2): if s1.count(c) < s2.count(c): return False return True ##cost time 5865ms def scramble_v2(s1, s2): s1_dict = {} s2_dict = {} for char in s1: if char in s1_dict: s1_dict[char] += 1 else: s1_dict[char] = 1 for char in s2: if char in s2_dict: s2_dict[char] += 1 else: s2_dict[char] = 1 for k, v in s2_dict.items(): if s1_dict.get(k, 0) >= v: continue else: return False return True ## cost time 6396ms def scramble_v3(s1, s2): h = [0] * 26 for char in s1: h[ord(char) - 97] += 1 for char in s2: h[ord(char) - 97] -= 1 for i in h: if i < 0: return False return True ## Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. ## These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. ## The sum of the squared divisors is 2500 which is 50 * 50, a square! ## Given two integers m, n (1 <= m <= n) we want to find all integers between m and n ## whose sum of squared divisors is itself a square. 42 is such a number. import math def list_squared(m, n): res = [] for num in range(m, n+1): i = 1 sum = 0 while i <= math.sqrt(num): # all the divisors present in pairs if num % i == 0: div = num // i sum += i**2 if div != i: sum += div**2 i += 1 if math.sqrt(sum).is_integer(): res.append([num, sum]) return res ## If the input number is already a palindrome, the number of steps is 0. ## Input will always be a positive integer. ##For example, start with 87: ## 87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884 ##4884 is a palindrome and we needed 4 steps to obtain it, so palindrome_chain_length(87) == 4 def is_palindrome(n): return str(n) == str(n)[::-1] def palindrome_chain_length(n): step = 0 while not is_palindrome(n): n += int(str(n)[::-1]) step += 1 return step # print(palindrome_chain_length(87)) ## Breadcrumb Generator ignore_words = ["the", "of", "in", "from", "by", "with", "and", "or", "for", "to", "at", "a" ] def generate_bc(url, separator): if url.startswith("http"): url = url.split("//")[1] crumb = url.split('/') crumb[-1] = crumb[-1].split('.')[0].split('?')[0].split('#')[0] if crumb[-1] in ('', 'index'): crumb.pop() n = len(crumb) processed_parts = [] for i, level in enumerate(crumb): aux = level if i == 0: if n == 1: processed_parts.append('<span class="active">HOME</span>') else: processed_parts.append('<a href="/">HOME</a>') else: if len(level) > 30: aux = ''.join([entry[0] for entry in level.split('-') if entry not in ignore_words ]) else: aux = ' '.join(aux.split('-')) if i > 1 and i <= n - 2: level = "/".join(crumb[1:i+1]) if i == n - 1: processed_parts.append('<span class="active">%s</span>' % aux.upper()) else: processed_parts.append('<a href="/%s/">%s</a>' % (level, aux.upper())) return separator.join(processed_parts) ## hamming number # Write a function that computes the nth smallest Hamming number. # Specifically: # The first smallest Hamming number is 1 = 2^0 * 3^0 * 5^0 # The second smallest Hamming number is 2 = 2^1 * 3^0 * 5^0 # The third smallest Hamming number is 3 = 203150 # The fourth smallest Hamming number is 4 = 223050 # The fifth smallest Hamming number is 5 = 203051 def hamming(n): hamm = [0 for num in range(n)] hamm[0] = 1 a, b, c = 0, 0, 0 for i in range(1, n): hamm[i] = min(hamm[a] * 2, hamm[b] * 3, hamm[c] * 5) if hamm[i] == hamm[a] * 2: a += 1 if hamm[i] == hamm[b] * 3: b += 1 if hamm[i] == hamm[c] * 5: c += 1 return hamm[-1] ## original version also bad code hamset = {1:1} divisors = [2, 3, 5] def hamming_v2(n): if hamset.get(n) is not None: return hamset[n] i = list(hamset.keys())[-1] + 1 while i <= n: now = hamset[i - 1] find = False while not find: now += 1 rem = now for div in divisors: while (rem / div).is_integer(): rem = rem / div if rem == 1: hamset[i] = now find = True break if find is True: break i += 1 return hamset[n] # Strip Comments # result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" def solution(string,markers): parts = string.split('\n') for m in markers: parts = [p.split(m)[0].rstrip() for p in parts] print(parts) return '\n'.join(parts) # solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # Original Version def solution_v2(string,markers): strip = 0 s = list(string) for i in range(len(string)): if s[i] in markers: strip = 1 if s[i - 1] == ' ': s[i - 1] = '' if s[i] == "\n": strip = 0 if strip == 1: s[i] = '' return ''.join(s) # How many numbers III? # Generate all the numbers of three digits that: # the value of adding their corresponding ones(digits) is equal to 10. # their digits are in increasing order (the numbers may have two or more equal contiguous digits) # The numbers that fulfill the two above constraints are: 118, 127, 136, 145, 226, 235, 244, 334 # recursion def find_all(sum_dig, digs): res = [''.join([str(num) for num in x]) for x in gen(digs) if sum(x) == sum_dig] if not res: return [] return [len(res), int(res[0]), int(res[-1])] def gen(d, start=1): if d == 1: for x in range(start, 10): yield [x] else: for x in range(start, 10): for y in gen(d - 1, x): yield [x] + y # built-in import itertools def find_all_v2(sum_dig, digs): res = [] aux = list(itertools.combinations_with_replacement(range(1, 10), digs)) res = [''.join([str(num) for num in t]) for t in aux if sum(t) == sum_dig] if not res: return [] return [len(res), int(res[0]), int(res[-1])]
d3c25e265a105788d6b8ee85324e5a6745243ff4
Elton86/ExerciciosPython
/ExerciciosComStrings/Exe07.py
541
3.90625
4
"""Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços em branco), conte: quantos espaços em branco existem na frase. quantas vezes aparecem as vogais a, e, i, o, u.""" frase = input("Digite a frase: ") cont_esp = cont_vog = 0 for f in frase: if f == " ": cont_esp += 1 elif f.lower() in ("a", "e", "i", "o", "u"): cont_vog += 1 print("Frase: {}".format(frase)) print("Total de espaços em branco: {}".format(cont_esp)) print("Total de vogais: {}".format(cont_vog))
42fde8fea9d4073226f40af828e6477c4cf5baa1
stuycs-softdev/classcode
/7/regex/regtest.py
652
4.1875
4
import re def find_phone(s): """Return a list of valid phone numbers given a string of text Arguments: s: A string of text Returns: An empty list or a list of strings each one being a phone number >>> find_phone("") [] >>> find_phone("111-111-1111") ['111-111-1111'] >>> find_phone("stuff 222-222-2222 stuff") ['222-222-2222'] >>> find_phone("111-111-1111 and 222-222-22252") ['111-111-1111', '222-222-2225'] """ pattern = "[0-9]{3}-[0-9]{3}-[0-9]{4}" result = re.findall(pattern,s) return result if __name__=="__main__": import doctest doctest.testmod()
a704c66997229d74c036bd07ba671f733374bda0
anassinator/markov-sentence-correction
/sentence.py
1,928
3.890625
4
# -*- coding: utf-8 -*- class Sentence(object): """Sentence.""" START = "<s>" STOP = "</s>" LEFT_SIDED_SYMBOLS = set('"\',.-/:;<>?!)]}$%') RIGHT_SIDED_SYMBOLS = set('"\'-/<>([{') SYMBOLS = LEFT_SIDED_SYMBOLS.union(RIGHT_SIDED_SYMBOLS) def __init__(self): "Constructs a Sentence.""" self._word_list = [Sentence.START] self._sentence = "" def __str__(self): """Returns a string representation of the sentence.""" return self._sentence def __len__(self): """Returns the number of words in a sentence.""" return len(self._word_list) def __iter__(self): """Iterates through the sentence word by word.""" return iter(self._word_list) @property def complete(self): """Whether the sentence is complete or not.""" return self._word_list[-1] == Sentence.STOP def add(self, word): """Adds a word to the sentence. Args: word: Word. """ self._word_list.append(word) if word != Sentence.STOP: if (word[0] not in Sentence.LEFT_SIDED_SYMBOLS and self._sentence and self._sentence[-1] not in Sentence.RIGHT_SIDED_SYMBOLS): self._sentence += ' ' self._sentence += word def get_last(self, n): """Returns the indices of the last n words in the sentence. Args: n: Number of last words to get from the sentence. """ return tuple(self._word_list[-n:]) @classmethod def from_line(self, line): """Constructs a Sentence from a line of text. Args: line: Line of text. Returns: Sentence. """ sentence = Sentence() words = line.split(' ') sentence._word_list.extend(words) sentence._sentence = line return sentence
c479a71f2860c1214693a38716e8460efd806f4c
josueocampol/introprogramacion
/practico_flujo_condicional_y_ciclico/ejercicio_11.py
301
3.625
4
print("Ingrese su fecha de nacimiento.") dia = int(input("Día: ")) mes = int(input("Mes: ")) año = int(input("Año: ")) from time import localtime t = localtime() t.tm_mday 11 t.tm_mon 10 t.tm_year 2020 if año<2020: print(f"Usted tiene {-año+2020} años y su cumpleaños es el {dia} de {mes}")
b293468e54ded3646abbfc2a5fe94fd6901b4704
Paul9inee/Elementary_Algorithm
/sanghwa_week4/[4주차] 가장 큰 수.py
262
3.5
4
def solution(numbers): numbers = [str(x) for x in numbers] numbers.sort(key=lambda x:(x*4)[:4], reverse = True) answer = ''.join(numbers) if answer == '0' * len(numbers): return '0' return answer print(solution([0,0,0,0,0,0,0,0,0]))
9eb6e28495760fe20df5d5175b308de048e096ed
jabhax/python-data-structures-and-algorithms
/OOP/Flyweight.py
1,229
3.84375
4
# Design Patterns ''' The Flyweight Pattern provides a way to decrease object count. It includes features that help in improving application structure. The most important feature of the Flyweight objects is immutabilty; they cannot be modified once constructed. The pattern uses a HashMap to store reference objects. ''' class ComplexGenes(object): def __init__(self): pass def genes(self, gene_code): return f'ComplexPattern{gene_code}TooHugeInSize' class Families(object): _family = {} def __new__(cls, name, fid): try: id = cls._family[fid] except KeyError: id = object.__new__(cls) cls._family[fid] = id return id def set_gen_info(self, gen_info): cg = ComplexGenes() self._genetic_info = cg.genes(gen_info) def get_gen_info(self): return self._genetic_info def main(): data, families = (('a', 1, 'ATAG'), ('a', 2, 'AAGT'), ('b', 1, 'ATAG')), [] for i in data: obj = Families(i[0], i[1]) obj.set_gen_info(i[2]) families.append(obj) for i in families: print(f'id: {str(id(i))}') print(f'{i.get_gen_info()}') if __name__ == '__main__': main()
6f44998992bdbb419e527cc6bd16135ba6c8b3c6
bcollins5/mis3640
/play_around.py
299
3.859375
4
# team = 'New England Patriots' # win_pct = 65 # print('%s %d' % (team, win_pct)) def check_team(team): if team == ('Patriots' and 'New England Patriots'): return 'Good' else: return 'Bad' team = input('Enter your favorite team: ').lower() print(check_team(team))
76a488f4952fb679fa3a30b86c309da1e9781185
atrox3d/python-corey-schafer-tutorials
/01-python-basics/11-slicing.py
2,721
4.25
4
# # https://www.youtube.com/watch?v=ajrtAuDg3yw # # Python Tutorial: Slicing Lists and Strings # ################################################################################# my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # POSITIVE INDEXES # -10,-9,-8,-7,-6,-5,-4,-3,-2,-1 # NEGATIVE INDEXES # syntax: list[start:end:step] # where: # start: start index, positive or negative # end : end index, positive or negative # step : takes each nth element # create indexes list to iterate positive_indexes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] negative_indexes = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] negative_indexes.reverse() # [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10] print('#' * 80) ################################################################################# print(' ' * 9, end='') # show positive indexes formatted for p in positive_indexes: # OUTPUT | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, print(f'{p:>3},', end='') print() print(' ' * 9, end='') # show negative indexes formatted for n in negative_indexes: # OUTPUT | -1, -2, -3, -4, -5, -6, -7, -8, -9,-10, print(f'{n:>3},', end='') print() print('#' * 80) ################################################################################# # OUTPUT | [(0, -1), (1, -2), (2, -3), (3, -4), (4, -5), (5, -6), (6, -7), (7, -8), (8, -9), (9, -10)] print(list(zip(positive_indexes, negative_indexes))) for start, end in zip( positive_indexes, negative_indexes): # loop over the two list of indexes simultaneously print(f'[{start:>3}:{end:>3}]', end='') # always show the range if len(my_list[start:end]): # if the range contains data print(f'{" ," * start}', end='') # print offset in spaces for x in my_list[start:end]: # print all the matching elements formatted print(f'{x:>3},', end='') print() ################################################################################# print('#' * 80) ################################################################################# print(f'my_list : {my_list}') for start in range(0, len(my_list)): # loop through list's elements for end in range(0, len(my_list)): # sub-loop through list's elements print(f'range[{start}:{end}] : ', end='') # print current range print(f'{my_list[start:end]},', end='') # print current slice print() print() print()
68af8dee7647e86450c2da7d97ab385bd4fceb6f
JimmyRomero/AT06_API_Testing
/JimmyRomero/Python/Session3/Practice8.py
281
4.09375
4
def replace(text, letter, letter_to_change): text_splitted = text.split(letter) print(letter_to_change.join(text_splitted)) replace("Mississippi", "i", "I") song = "I love spom! Spom is my favorite food.Spom, spom, yum!" replace(song, "om", "am") replace(song, "o", "a")
8b516c1a3ea5c32f9d1a9bc22a833f9545523e7c
JIMBLYB/Tinkering_Graphics_Teams
/Contract #4/SpriteReskinning.py
1,602
3.671875
4
# This script has been made by Joseph Broughton. import pygame from pygame.tests.test_utils import png pygame.init() # This will create the display that is the same size as my sprite i'm editing. main = pygame.display.set_mode((400, 200)) # This surface is the one that actually loads th image. my_sprite = pygame.image.load('Platform.png').convert() # colours WHITE = (255, 255, 255) # This function will get the x and y pixels and then set them to a different colour. def entity_colour_change(surface=pygame.Surface((1, 1))): pixel = pygame.Color(0, 0, 0) for x in range(surface.get_width()): for y in range(surface.get_height()): pixel = surface.get_at((x, y)) surface.set_at( (x, y), # This is the line that actually changes the colours, 0-1 means there's less colour and 1-2 is more. pygame.Color(int(pixel.r * 2), int(pixel.g * 0.40), int(pixel.b * 0.10)) ) # I actually call the function here and put in the sprite surface. entity_colour_change(my_sprite) # Next i save the new sprite as a png to the project folder pygame.image.save(my_sprite, 'main.png') # This simple game loop will be checking for if the player tries to quit the game and will close the app. running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False main.fill(WHITE) # Overlays the new sprite over the main background surface. main.blit(my_sprite, (0, 0)) # Now it will update the display. pygame.display.update() pygame.quit()
7e1b28a8ab33e2cb3bbeaf11efce32f5bee953e3
stosik/coding-challenges
/leet-code/first-unique-char.py
493
3.828125
4
# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. # Examples: # s = "leetcode" # return 0. # s = "loveleetcode", # return 2. def solution(s): hash_table = {} for i in s: if i not in hash_table: print(i) hash_table[i] += 1 else: hash_table[i] = 1 for i in range(0, len(s)): if hash_table[s[i]] == 1: return i return 0 print(solution("leetcode"))
f233fc81cebee7c25d58e03e1cbdd0b89b741a01
Barracudayao/pythonbasic
/python3_list/python_list_notebook.py
2,371
4.34375
4
# Lists list1 = ["Cisco", "Juniper", "Avaya", 10, 10.5, -11] # creating a list len(list) # returns the number of elements in the list list1[0] # returns "Cisco" which is the first element in the list (index 0) list1[0] = "HP" # replacing the first element in the list with another value # Lists - methods list2 = [-11, 2, 12] min(list2) # returns the smallest element (value) in the list max(list2) # returns the largest element (value) in the list list1 = ["Cisco", "Juniper", "Avaya", 10, 10.5, -11] list1.append(100) # appending a new element to the list del list1[4] # removing an element from the list by index list1.pop(0) # removing an element from the list by index list1.remove("HP") # removing an element from the list by value list1.insert(2, "Nortel") # inserting an element at a particular index list1.extend(list2) # appending a list to another list list1.index(-11) # returns the index of element -11 list1.count(10) # returns the number of times element 10 is in the list list2 = [9, 99, 999, 1, 25, 500] list2.sort() # sorts the list elements in ascending order; modifies the list in place list2.reverse() # reverses the elements of the list sorted(list2) # sorts the elements of a list in ascending order and creates a new list at the same time sorted(list2, reverse=True) # sorts the elements of a list in descending order and creates a new list at the same time list1 + list2 # concatenating two lists list1 * 3 # repetition of a list # Lists - slicing (works the same as string slicing, but with list elements instead of string characters) a_list[ 5:15] # slice starting at index 5 up to, but NOT including, index 15; so index 14 represents the last element in the slice a_list[5:] # slice starting at index 5 up to the end of the list a_list[:10] # slice starting at the beginning of the list up to, but NOT including, index 10 a_list[:] # returns the entire list a_list[-1] # returns the last element in the list a_list[-2] # returns the second to last element in the list a_list[-9:-1] # extracts a certain sublist using negative indexes a_list[-5:] # returns the last 5 elements in the list a_list[:-5] # returns the list minus its last 5 elements a_list[::2] # adds a third element called step; skips every second element of the list a_list[::-1] # returns a_list's elements in reverse order
a91340f921ad5da19817162cb88c35c21fcbe890
gongzhiyao/FirstTest
/venv/test/practice5.py
6,707
3.984375
4
#!/usr/bin/env python # coding=utf-8 # 函数式编程 print "函数式编程" # 高阶函数 # 变量可以指向函数 print abs(-120) print abs # 可见,abs(-10)是函数调用,而abs是函数本身。 # 要获得函数调用结果,我们可以把结果赋值给变量: x = abs(-100) print x # 如果把函数自身赋值给变量 a = abs print a # 结论:函数本身也可以赋值给变量,即:变量可以指向函数。 # 如果一个变量指向了一个函数,那么,可否通过该变量来调用这个函数?用代码验证一下: print a(-10000) # 成功!说明变量f现在已经指向了abs函数本身。 # 函数名也是变量 # 那么函数名是什么呢?函数名其实就是指向函数的变量!对于abs()这个函数,完全可以把函数名abs看成变量,它指向一个可以计算绝对值的函数! # 如果把abs指向其他对象,会有什么情况发生? # abs = 10 print abs(-100) # 把abs指向10后,就无法通过abs(-10) # 调用该函数了!因为abs这个变量已经不指向求绝对值函数了! # 当然实际代码绝对不能这么写,这里是为了说明函数名也是变量。要恢复abs函数,请重启Python交互环境。 # 注:由于abs函数实际上是定义在__builtin__模块中的,所以要让修改abs变量的指向在其它模块也生效,要用__builtin__.abs = 10。 # 传入函数 # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。 # 一个最简单的高阶函数 # 把函数作为参数传进去,称为高阶函数 def add(x, y, f): return f(x) + f(y) abs_result = add(1, -1113, abs) print abs_result # 小结 # 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。 # # map/reduce def f(x): if isinstance(x, (int, float)): return x * x else: return 0 L = [1, 2, 3, 4, 5, 5, 66, "a", "b2", "c"] print map(f, L) # 如果不使用map的话 同样可以使用for循环来实现 S = [] for i in L: if not isinstance(i, (int, float)): i = 0 S.append(i * i); print S # 的确可以,但是,从上面的循环代码,能一眼看明白“把f(x)作用在list的每一个元素并把结果生成一个新的list”吗? # 所以,map()作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数,比如,把这个list所有数字转为字符串: print map(str, [1, 2, 3, 445, 5, 6, 6, 67, 7, 78, 8, 8, 8, 8, ]) # 这样子的话 只需要一行代码 # #再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: # reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) # 比如给一个序列求和,可以使用reduce来实现 def abs_add(x, y): if isinstance(x, (int, float)) & isinstance(y, (int, float)): return abs(x) + abs(y) else: return abs(x) + 0 print reduce(abs_add, [1, 2, 3, 3, 4, 4, 556, 6, "SDSDSSSS", 33333]) # 当然求和运算可以使用sum 不用使用reduce就可以 # 但是如果是进行复杂的运算 就得用reduce了 def change_big_num(x, y): return x * 10 + y print reduce(change_big_num, [1, 2, 3, 4, 5, 6, 6]) # 这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数: def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}[s] # 这个是 reduce和map 结合 print reduce(change_big_num, map(char2num, ['1', '2', '3'])) print {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}['1'] # 下面整合成一个str2int 的方法是 def str2int(s): def change_big_num(x, y): return x * 10 + y def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] return reduce(change_big_num, map(char2num, s)) print str2int('0123456789') # 可以使用lambda 函数进行简化 # todo def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def char2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) # filter 用于过滤 # Python内建的filter()函数用于过滤序列。 # 和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 # 例如在一个list里面,删除偶数,只保留奇数。 def is_odd(x): return x % 2 == 1 L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2] print filter(is_odd, L) # 删除数组中的空串 def is_not_blank(s): return s and s.strip() print filter(is_not_blank, ["", "1", "2", "2", "3", "33333"]) def is_suShu(n): for i in range(2, n): if n % i == 0: return False return True print filter(is_suShu, range(2, 100)) # sort 排序算法 # Python内置的sorted()函数就可以对list进行排序: print sorted([99, 23, 3, 4, 1, 0]) # 此外,sorted()函数也是一个高阶函数,它还可以接收一个比较函数来实现自定义的排序。比如,如果要倒序排序,我们就可以自定义一个reversed_cmp函数: def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 else: return 0 print sorted([1, 2, 32, 34, 4, 5, 52, 32, 34, 1123, 42, 4131, 1], reversed_cmp) # 按照acsII 码进行排序 先是数字 然后大写字母 然后小写字母 print sorted(["ZSSSS", "a", "A", 1223, "zssddf"]) # 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。 # 现在,我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能定义出忽略大小写的比较算法就可以 def cmp_ignore_case(s1, s2): u1 = s1.upper() u2 = s2.upper() if u1 > u2: return -1 if u1 < u2: return 1 else: return 0 # 忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较。 # 这样,我们给sorted传入上述比较函数,即可实现忽略大小写的排序: print sorted(["A", "a", "s", "Z"], cmp_ignore_case)
631959c8d29fd1630bff5881d09fc1dce4b34057
lzs1314/pythonWeb
/week3/生成器/index.py
532
3.703125
4
# coding:utf-8 #@FileName: index.py #@Author :辰晨 #@Time :2019/4/17 11:02 s = (s*2 for s in range(10)) print(next(s)) for i in s: print(i) def foo(): print('ok') yield 1 g=foo() print(g) #<generator object foo at 0x000001DD5860A390> next(g) for i in foo(): print(i) #什么是可迭代对象(对象拥有__iter__方法的) def fib(max): n,before, after = 0,0,1 while n<max: # print(after) yield before before,after = after,before+after n=n+1 print(fib(8))