blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
991fd2fe91a1b0d1e79685102eca3c1d3d0fab04
alexandraback/datacollection
/solutions_5738606668808192_0/Python/aggelgian/C.py
758
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools, math def prep(): print ("Case #1:") n, nums = 16, [] nums = ["".join(num) for num in itertools.product('01', repeat=n) if num[0] != '0' and num[n-1] != '0'] i, found, expected = 0, 0, 50 while found < expected: sol = solve(nums[i]) if sol != None: found += 1 print ("{} {}".format(nums[i], sol)) i += 1 def divisor(n): if n % 2 == 0 and n > 2: return 2 for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return i return None def solve(num): divs = [] for b in range(2, 11): d = divisor(int(num, b)) if d == None: return None divs.append(str(d)) return " ".join(divs) if __name__=="__main__": prep()
51a365210f8885fbb9e06e112924140d37debdaf
Schnei1811/PythonScripts
/TutorialSeries/ReinforcementLearning/FishSchools/FishSchools.py
10,374
3.53125
4
import pygame import numpy as np import logging import random import time from math import sqrt, fabs, atan2, degrees, pi #np.set_printoptions(threshold=10000) class Animal: def __init__(self, color, x_boundary, y_boundary): self.score = 0 self.hunger = 100 self.currentdirection = random.randrange(0, 7) self.movementcounter = 0 self.rewardcounter = 0 self.color = color self.x_boundary = x_boundary self.y_boundary = y_boundary self.x = random.randrange(0, self.x_boundary) self.y = random.randrange(0, self.y_boundary) self.ecosystemdata = np.zeros(6) self.counter = 0 def check_bounds(self): if self.x < 0: self.x = self.x_boundary elif self.x > self.x_boundary: self.x = 0 if self.y < 0: self.y = self.y_boundary elif self.y > self.y_boundary: self.y = 0 def __repr__(self): return 'Animal({}, {}, ({},{}))'.format(self.color, self.radius, self.x, self.y) def __str__(self): return 'Animal of location: ({},{})), colour: {}, score:{}'.format(self.x, self.y, self.color, self.score) class Fish(Animal): def __init__(self, x_boundary, y_boundary): Animal.__init__(self, COLOUR_FISH, x_boundary, y_boundary) self.radius = 6 self.perceiveforward = 50 self.perceivewidth = 50 self.perceiveradius = self.radius + 30 self.index = 0 self.Q = np.zeros([289, 8]) self.state = 0 self.action = random.randrange(0, 7) self.reward = 0 self.learningrate = .85 self.discount = .99 def __add__(self, other_blob): if other_blob.color == COLOUR_SHARK: self.radius -= 50 self.score = time.time() - starttime def perceive(self, other_animal): if other_animal.color == COLOUR_SHARK: distx = other_animal.x - self.x disty = other_animal.y - self.y disttot = int(sqrt(fabs(distx) + fabs(disty))) if (disttot & 1): disttot -= 1 radshark = atan2(disty, distx) radshark %= 2 * pi degshark = int(5 * int(degrees(radshark)/5)) if disttot == 4: self.index = (degshark / 5) if disttot == 6: self.index = (degshark / 5) + 72 if disttot == 8: self.index = (degshark / 5) + 144 if disttot == 10: self.index = (degshark / 5) + 216 else: self.index = 0 def QLearnAction(self): self.action = int(np.argmax(self.Q[self.state, :] + np.random.randn(1, 8) * (1./(self.index+1)))) def QLearnUpdate(self): self.Q[self.state, self.action] += \ self.learningrate * (self.reward + self.discount * np.max(self.Q[self.index, :]) - self.Q[self.state, self.action]) def Respawn(self): print(self.index, np.count_nonzero(self.Q)) self.reward = 0 self.x = random.randrange(0, self.x_boundary) self.y = random.randrange(0, self.y_boundary) self.radius += 50 def move(self): self.currentdirection = self.action if self.rewardcounter == 20: self.reward += 1 self.rewardcounter = 0 self.rewardcounter += 1 if self.currentdirection == 0: self.headx = self.x self.heady = self.y - self.radius self.move_x = 0 self.move_y = -3 elif self.currentdirection == 1: self.headx = self.x + self.radius / 2 self.heady = self.y - self.radius / 2 self.move_x = 1 self.move_y = -1 elif self.currentdirection == 2: self.headx = self.x + self.radius self.heady = self.y self.move_x = 3 self.move_y = 0 elif self.currentdirection == 3: self.headx = self.x + self.radius / 2 self.heady = self.y + self.radius / 2 self.move_x = 1 self.move_y = 1 elif self.currentdirection == 4: self.headx = self.x self.heady = self.y + self.radius self.move_x = 0 self.move_y = 3 elif self.currentdirection == 5: self.headx = self.x - self.radius / 2 self.heady = self.y + self.radius / 2 self.move_x = -1 self.move_y = 1 elif self.currentdirection == 6: self.headx = self.x - self.radius self.heady = self.y self.move_x = -3 self.move_y = 0 elif self.currentdirection == 7: self.headx = self.x - self.radius / 2 self.heady = self.y - self.radius / 2 self.move_x = -1 self.move_y = -1 else: self.move_x = 0 self.move_y = 0 self.x += self.move_x self.y += self.move_y class Shark(Animal): hungerscore = 100 hungercounter = 0 def __init__(self, x_boundary, y_boundary): Animal.__init__(self, COLOUR_SHARK, x_boundary, y_boundary) self.radius = 12 self.perceiveforward = 60 self.perceivewidth = 60 self.perceiveradius = self.radius + 40 def __add__(self, other_blob): if other_blob.color == COLOUR_SHARK: self.hunger += 50 def hunger(self): if self.hungercounter == 10: self.hungerscore -= 1 self.hungercounter = 0 if self.hungerscore < 0: self.score = time.time() - starttime self.hungercounter += 1 def move(self): if self.movementcounter == 10: self.currentdirection = self.currentdirection + random.randrange(-1, 2) self.movementcounter = 0 self.score += 1 self.movementcounter += 1 if self.currentdirection == -1: self.currentdirection = 7 elif self.currentdirection == 9: self.currentdirection = 0 if self.currentdirection == 0: self.headx = self.x self.heady = self.y - self.radius self.move_x = 0 self.move_y = -3 elif self.currentdirection == 1: self.headx = self.x + self.radius / 2 self.heady = self.y - self.radius / 2 self.move_x = 1 self.move_y = -1 elif self.currentdirection == 2: self.headx = self.x + self.radius self.heady = self.y self.move_x = 3 self.move_y = 0 elif self.currentdirection == 3: self.headx = self.x + self.radius / 2 self.heady = self.y + self.radius / 2 self.move_x = 1 self.move_y = 1 elif self.currentdirection == 4: self.headx = self.x self.heady = self.y + self.radius self.move_x = 0 self.move_y = 3 elif self.currentdirection == 5: self.headx = self.x - self.radius / 2 self.heady = self.y + self.radius / 2 self.move_x = -1 self.move_y = 1 elif self.currentdirection == 6: self.headx = self.x - self.radius self.heady = self.y self.move_x = -3 self.move_y = 0 elif self.currentdirection == 7: self.headx = self.x - self.radius / 2 self.heady = self.y - self.radius / 2 self.move_x = -1 self.move_y = -1 else: self.move_x = 0 self.move_y = 0 self.x += self.move_x self.y += self.move_y def is_perceived(b1, b2): return np.linalg.norm(np.array([b1.x, b1.y]) - np.array([b2.x, b2.y])) < (b1.perceiveradius + b2.perceiveradius) def is_touching(b1, b2): return np.linalg.norm(np.array([b1.x, b1.y]) - np.array([b2.x, b2.y])) < (b1.radius + b2.radius) def handle_collision(fish, sharks): for fish_id, fish_animal, in fish.copy().items(): for other_animals in fish, sharks: for other_animals_id, other_animal in other_animals.copy().items(): if is_touching(fish_animal, other_animal): fish_animal + other_animal other_animal + fish_animal if fish_animal.radius <= 0: Fish.Respawn(fish[fish_id]) #del fish[fish_id] def draw_environment(fish, shark, animal_list): game_display.fill(COLOUR_OCEAN) handle_collision(fish, shark) for fish_id, fish_animal in fish.copy().items(): for other_animals in fish, shark: for other_animals_id, other_animal in other_animals.copy().items(): if is_perceived(fish_animal, other_animal): Fish.perceive(fish[fish_id], other_animal) Fish.QLearnAction(fish[fish_id]) Fish.QLearnUpdate(fish[fish_id]) Fish.move(fish[fish_id]) for shark_id, shark_animal in shark.copy().items(): Shark.hunger(shark[shark_id]) #if animalid.hungerscore < 0: del animalid Shark.move(shark[shark_id]) for animal_dict in animal_list: for animal_id in animal_dict: animal = animal_dict[animal_id] pygame.draw.circle(game_display, animal.color, (animal.x, animal.y), animal.radius) pygame.draw.line(game_display, COLOUR_FIN, [animal.x, animal.y], [animal.headx, animal.heady], 2) animal.check_bounds() pygame.display.update() return def main(): fish = dict(enumerate([Fish(WIDTH, HEIGHT) for i in range(STARTING_FISH)])) sharks = dict(enumerate([Shark(WIDTH, HEIGHT) for i in range(STARTING_SHARKS)])) animal_list = [fish, sharks] while True: try: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() draw_environment(fish, sharks, animal_list) clock.tick(60) except Exception as e: logging.critical(str(e)) pygame.quit() quit() break starttime = time.time() STARTING_FISH = 20 STARTING_SHARKS = 1 WIDTH = 300 HEIGHT = 200 COLOUR_FIN = (0, 0, 0) COLOUR_OCEAN = (24, 96, 228) COLOUR_FISH = (236, 241, 48) COLOUR_SHARK = (255, 0, 0) game_display = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Ocean World") clock = pygame.time.Clock() main()
158da877b7ff17292ec033c2e41728e356ce9a48
AdamZhouSE/pythonHomework
/Code/CodeRecords/2908/60752/246012.py
297
3.65625
4
num=int(input()) book=[] for n in range(num): word=input().split() word=list(''.join(word)) word.sort() word=''.join(word) has=False for w in book: if w==word: has=True if not has: book.append(word) print(len(book),end='')
d2752c75f1e4fa556766cb1c798d6d3d07bba6f1
Jason-leung123/Git_hub_Learning_Python
/user_input&while_loops.py
6,890
4.53125
5
#---------------Simple input() greetings = input("If you type something here, it will repeat the input again") print(greetings) #---------------Writing clear prompts name = input("Please enter your name") print(f"Hello, {name}!") #--------------Using int() to accept numerical input height = input("What is your height, in inches\n") height = int(height) #This line means that when a user inputs a number, it will be a string. This means that I have to convert it from a string to an integer, to do this we use int() if height >= 40: print("You are tall") else: print("You are small") #--------------Modulo Operator #The modulo operator(%) is an operator which divides a number by another number and returns the remainder: #Typing '4%3' into python on the terminal will result in providing the answer #Example number = int(input("Enter a number and this program will detect if its odd or even\n")) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd") #-------------While loops current_number = 1 while current_number <=5: #This means that if the current number is smaller than 5, it will continue to loop until the number is greater than 5 print(current_number) current_number +=1 #-------------Letting the User choose to quit the while statement prompt = "\nYou can write anything and this program will repeat it back to you:" prompt +="\nEnter 'quit' to end the program.\n" #This line defines the message which gives two options for the user. message = "" #By setting the user_input to have quotation marks means that it will be able to store information. while message != 'quit': #This line means that if the user input is not equal to 'quit', then it will continue to loop until the user types 'quit' message = input(prompt) if message != 'quit': # This line means that if the user inputs 'quit', it will not print it print(message) #-------------Using Flags prompt = "\nYou can write anything and this program will repeat it back to you:" prompt +="\nEnter 'quit' to end the program.\n" active = True #I set the variable active to 'True', This will make the while statement simpler as there will be no comparrison with the while statement. As long as the active variable remains True, it will continue to loop while active: #This means while True, which also means that it will continue to loop until we set the active variable to False message = input(prompt) if message == 'quit': #This line means that if the message is to equal the string 'quit', it will change the active state to False, meaning that it will no longer loop active = False else: #This means that if the message does not equal to 'quit', it will print the user inputs print(message) #-------------Using break to exit a loop prompt = "\nType in your favourite food:" prompt +="\nEnter 'quit' to end the program.\n" while True: # This line will continue to run unless it reaches a break statement message = input(prompt) if message == 'quit': print("You have stopped the loop") break #This means that if the user were to input 'quit', it will break the loop. else: print("I like to eat " + message + "!") #-----------Using continue in a loop current_number = 0 while current_number <10: #Here is using the while statement as a comparision. It means that if the current_number is smaller than 10, it will run the loop current_number += 1 if current_number % 2 == 0: continue #This line means that if the current_number is divisible by 2 and is even, it will ignore the rest of the loop go back to the beginning of the loop and make a check again. This program means that it will only print odd numbers print(current_number) #----------Making infinite loops x = 1 while x: #Since there is no comparision or no if statements to stop the loop, it will continue to run forever x += 1 print(x) #----------Preventing infinite loops x = 1 while x <= 5: #This line makes a comparision which means that if the variable x is smaller than 5, it will increment the current number by 1 and will continue to loop until x is greater than 5 print(x) x +=1 #---------Using a while loop with lists and dictionaries unconfirmed_users = ['jason', 'ricardo', 'ben'] #In this line, i created a list confirmed_users = [] #Another list is created but it is empty while unconfirmed_users: #The while loop here means that it will continue to loop until there is no items in the variable unconfirmed_users current_user = unconfirmed_users.pop() # Within the while loop, the pop function removes and returns the last item in the list at a time meaning that an item will be removed from the list and stored in the current_user variable print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) #This line will add the variable current_user into the confirmed user lists. Since the variable is being modified, it keeps changing and will not add a new item into the variable print("\nUsers that are confirmed:") for confirmed_user in confirmed_users: # This line checks for every item in confirmed_user, it will run a print statement print(confirmed_user.title()) #--------Removing All instances of specific values from a list Game_platforms = ['Playstation 4', 'Xbox', 'PC', 'Xbox', 'Xbox', 'Ninentdo Switch'] print() while 'Xbox' in Game_platforms: #This line means that as long as Xbox remains in the list, it will run a loop. Game_platforms.remove('Xbox') #This line will remove 1 item at a time. This means that the loop will break when the item 'Xbox' is no longer in the list print(Game_platforms) #-------Filling a Dictionary with User input responses = {} polling_active = True while polling_active:# This line means that it will continue to loop unless it is changed to false name = input("\nWhat is your name? \n") # When a user input their answer, it will store it into the 'name' variable response = input("What do you like to eat? \n") #Similiar to line 120, a user will input their answer and it will be stored in the variable 'response' responses[name] = response # This line stores the information into the dictionary. Meaning that the name is the key and the response is the value repeat = input("Would you like to let another person respond? (Yes/No) ") # if repeat == 'No' or 'no': #This line means that if the user were to input 'no', this will end the loop as it sets the active set to False and follow the next line of code polling_active = False print("\n--- Poll Results ---") for name, response in responses.items(): #What this line does is that for every item in the dictionary, it will continue to make a print statement print(name + " would like to eat " + response + ".")
343304c7c0948b42d56041af2220d1864330b6d9
idnbso/cs_study
/mathematics/series/series_ap.py
1,109
3.75
4
""" Given the first 2 terms A and B of an Arithmetic Series, tell the Nth term of the series. Input: The first line of input contains an integer, the number of test cases T. T testcases follow. Each testcase in its first line should contain two positive integer A and B(First 2 terms of AP). In the second line of every testcase it contains of an integer N. Output: For each testcase, in a new line, print the Nth term of the Arithmetic Progression. Constraints: 1 <= T <= 100 -103 <= A <= 103 -103 <= B <= 103 1 <= N <= 104 Example: Input: 2 2 3 4 1 2 10 Output: 5 10 """ def get_series_ap_term(n, a, b): """ O(1) """ diff = b - a return a + (n-1)*diff def get_series_ap_term_brute(n, a, b): """ O(n-1) = O(n) """ diff = b - a term = a for i in range(1, n): term += diff return term if __name__ == '__main__': total_inputs = int(input()) for inp in range(total_inputs): inp_num_a, inp_num_b = [int(x) for x in input().split()] inp_n = int(input()) print(get_series_ap_term_brute(inp_n, inp_num_a, inp_num_b))
1159485c36bf525ce0b683ddd198e318651b6261
zramos2/data-structures-and-algorithms
/two-pointer/LC167_two-sum-II-input-array-sorted.py
671
3.625
4
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # two pointer approach: # if sum is > target, right pointer moves # if sum is < target, left pointer moves # adds 0 to beginning of the list numbers.insert(0,0) left = 1 right = len(numbers) - 1 while left <= right: sumOfNumbers = numbers[left] + numbers[right] if sumOfNumbers > target: right -= 1 if sumOfNumbers < target: left += 1 if sumOfNumbers == target: return [left, right]
38c32aa33c5e35af70c9c83feed7fa49f7416e06
David-M-Dias/Exercicios-do-curso-de-Python
/Mundo2/Listas.py
556
4.15625
4
Lista = [1,2,3] # Criando lista e adicionando valores a mesma. print(len(Lista)) # Contando quantidade de itens na lista. print(Lista) # imprimindo a lista. Lista = Lista + [4,5,6] # Adicionando novos valores a uma lista já existente. print(Lista) # imprimindo lista atualizada. print(Lista[:3]) # imprimindo os valores desde a posição 0 até a posição 3(obs: a que a terceira posição não será impressa.) print(Lista[:4]) # imprimindo os valores desde a posição inicial (0) até a posição 4 (obs: Para aqui sim imprimir a posição 3.)
e3b382594066e8039b71bd6ac7b0fe723aa0ece0
zdravkog71/SoftUni
/OOP/ClassAndStaticMethodsExercise/project/gym.py
1,935
3.578125
4
class Gym: def __init__(self): self.customers = [] self.trainers = [] self.equipment = [] self.plans = [] self.subscriptions = [] @staticmethod def is_added(objects, object): if object in objects: return True return False def add_customer(self, customer): if not self.is_added(self.customers, customer): self.customers.append(customer) def add_trainer(self, trainer): if not self.is_added(self.trainers, trainer): self.trainers.append(trainer) def add_equipment(self, equipment): if not self.is_added(self.equipment, equipment): self.equipment.append(equipment) def add_plan(self, plan): if not self.is_added(self.plans, plan): self.plans.append(plan) def add_subscription(self, subscription): if not self.is_added(self.subscriptions, subscription): self.subscriptions.append(subscription) def subscription_info(self, subscription_id): result = "" for subscription in self.subscriptions: if subscription.id == subscription_id: result += f"{subscription.__repr__()}\n" for customer in self.customers: if customer.id == subscription.customer_id: result += f"{customer.__repr__()}\n" for trainer in self.trainers: if trainer.id == subscription.trainer_id: result += f"{trainer.__repr__()}\n" for exercise in self.plans: if exercise.id == subscription.exercise_id: for eq in self.equipment: if eq.id == exercise.equipment_id: result += f"{eq.__repr__()}\n" result += f"{exercise.__repr__()}" return result
faf4840b8226c54ecf73dd9b9b3653f997b6389a
vurise/PythonClasses
/classes-2.py
1,207
4.15625
4
#classes encapsulates 2 thngs- variables / attributes and functions/methods #recangle class- #length -var #width- var #area- funct/ method / var #perimeter - funct #diagnol- var #color- func #constructor/ init method #1. function #2. this function gets automatically invoked when i make an instance #3. to intialise variables in my class class rectangle(): #create class def __init__(self,l,w): # jo bhi instance iss function ko call karega vo uski values lega #self= rectangle1 self.length=l #length is an attribute of the class self.width=w #width is an attribute self.area1=0; def area(self): self.area1= self.length * self.width return self.area1 l=int(input("enter length")) w=int(input("enter width")) rectangle1 = rectangle(l,w) # i have made an instance rectangle1 of class rectangle #rectangle1.area() print(rectangle1.length ) print(rectangle1.width) print(rectangle1.area1) #print(str(rectangle1.length)+" "+ str(rectangle1.width)) # whenever i call a varibale or a method from an object/instance i will have to use the dot operator #print(rectangle1.length)
27f91101ef2e6ab5057c03503919eadf22420da7
distractedpen/datastructures
/BST.py
2,546
3.875
4
import random class Node(): def __init__(self, data): self.data = data self.left_child = None self.right_child = None class BinarySearchTree(): #Binary Tree algorithms def __init__(self): self.root = None def insert(self, data): new_node = Node(data) if self.root == None: self.root = new_node else: current = self.root while True: if new_node.data <= current.data: if current.left_child == None: current.left_child = new_node return else: current = current.left_child else: if current.right_child == None: current.right_child = new_node return else: current = current.right_child def printTree(self): def printSubTree(node): if node.left_child != None: temp = printSubTree(node.left_child) + " {0}".format(node.data) if node.right_child != None: return temp + " " + printSubTree(node.right_child) else: return temp elif node.right_child != None: return "{0} ".format(node.data) + printSubTree(node.right_child) else: return "{0}".format(node.data) return print(printSubTree(self.root)) def minValue(self): def traverseLeft(node): if node.left_child != None: return traverseLeft(node.left_child) else: return node.data v = traverseLeft(self.root) return v def maxValue(self): def traverseRight(node): if node.right_child != None: return traverseRight(node.right_child) else: return node.data v = traverseRight(self.root) return v #test code def main(): bst = BinarySearchTree() a = [7, 53, 17, 71, 63, 67, 41, 41, 34, 79, 83, 95, 21, 49, 53, 73, 84, 22, 7, 99] for n in a: bst.insert(n) ## for i in range(20): ## r = random.randint(0, 100) ## print(r, end=" ") ## bst.insert(r) ## print("\n") bst.printTree() if __name__ == "__main__": main()
591bf66bfac89e32091a618fd7ff84367c76b6b8
champagnepappi/python_kickstart
/reverse.py
155
4
4
def reverse(text): string = "" l = len(text) while l > 0: string += text[l-1] l -= 1 return string print reverse("KEvin")
11953a278ea44485e74d7629778de32c4dfa9191
Franklin-Wu/project-euler
/p042.py
1,544
3.90625
4
# Coded triangle numbers # # The nth term of the sequence of triangle numbers is given by, t_n = n(n+1)/2; so the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. # # Using p042_words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words? import csv; import sys; import time; start_time = time.time(); FILENAME = "p042_words.txt"; # FILENAME = "p042_words_toy.txt"; LETTER_VALUE_EXCESS = ord('A') - 1; MAX_TRIANGLE_N = 32; triangles = []; for n in range(1, MAX_TRIANGLE_N + 1): triangles.append(n * (n + 1) / 2); max_triangle = triangles[-1]; triangle_count = 0; with open(FILENAME, "rb") as csvfile: reader = csv.reader(csvfile); for words in reader: for word in words: value = 0; for letter in word: value += ord(letter) - LETTER_VALUE_EXCESS; if value > max_triangle: print "Failed due to insufficiently large triangles array."; sys.exit(-1); if value in triangles: print word, value; triangle_count += 1; print "triangle_count = %d." % triangle_count; print "Execution time = %f seconds." % (time.time() - start_time);
35cf802d36d245dc02a5ea7c2e5f7e1732b0d76d
TassioSales/Python-Solid
/exercicio-04.py
285
3.625
4
def maior_numero(objeto): return max(objeto) def menor_numero(objeto): return min(objeto) listaNumero = [x**2 for x in range(155, 255)] maior = maior_numero(listaNumero) menor = menor_numero(listaNumero) print(f"O maior numero e {maior}") print(f"O menor numero e {menor}")
d8361a949b9431ce05a71ee497d76d92f63c6354
ColdGrub1384/Pyto
/Pyto/Samples/Pandas/plotting.py
583
3.90625
4
""" An example of plotting with Pandas. Taken from http://queirozf.com/entries/pandas-dataframe-plot-examples-with-matplotlib-pyplot. """ import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ 'name':['john','mary','peter','jeff','bill','lisa','jose'], 'age':[23,78,22,19,45,33,20], 'gender':['M','F','M','M','M','F','M'], 'state':['california','dc','california','dc','california','texas','texas'], 'num_children':[2,0,0,3,2,1,4], 'num_pets':[5,1,0,5,2,2,3] }) df.plot(kind='scatter',x='num_children',y='num_pets',color='red') plt.show()
13f2a2ea674030d436e34d03f8829fb5f10e319c
paulorleal1991/prl1991
/ex008_prl1991.py
1,094
4.03125
4
'___Curso_de_Python___' '___Aluno_Paulo_R_Leal___' '___Exercicio_008____' print('') print('_' *40) print('Conversor de Medidas') m = float(input('Digite o Valor em Metros \n')) dm = m * 10 cm = m * 100 mm = m * 1000 print('') print('#' *40) print('{} Metros Equivale a:\n{:.0f} Centimetros ou {:.0f} milímetros'.format(m,cm,mm)) print('#' *40) dam = m / 10 hm = m / 100 km = m / 1000 print('') print('_' *40) print('Tabela de Medidas referente ao Valor') print('_' *40) print('') print('-----------------------------------------') print('|Medididas Equivalente | Valor') print('|Kilometros |{:.2f}'.format(km)) print('|Hectômetros |{:.2f}'.format(hm)) print('|Decâmetros |{:.2f}'.format(dam)) print('|Metros |{:.2f}'.format(m)) print('|Decímetros |{:.2f}'.format(dm)) print('|Centímetros |{:.2f}'.format(cm)) print('|Milímetros |{:.2f}'.format(mm)) print('-----------------------------------------') print('') print('-' *35) print('Paulo Roberto Leal 2020 01 31') print('paulorleal011291@hotmail.com') print('-' *35)
14328ac205eb0f3d73dac335c90e14dc9c9ef164
grishutenko/grishutenko.github.io
/python_labs/tests1.py
721
3.796875
4
def test(n): try: num = int(n) return 0 except: print('нельзя преобразовать в число') return 1 def tests(): test_result = 0 print('test 1') test_result = test_result + test([1]) print('test 2') test_result = test_result + test('-1') print('test 3') test_result = test_result + test([{1}]) print('test 4') test_result = test_result + test('l') print('test 5') test_result = test_result + test(-1) print('test 6') test_result = test_result + test(1.0) if test_result == 0: print("ошибок нет") else: print('количество ошибочных тестов',test_result)
057c3c0baf5c797e571f89e65d7b404d43e059b4
0xecho/KattisSubmissions
/digits.py
170
3.625
4
while 1: inp = input() if inp=="END": break # inp = int(inp) c=0 while inp!="1": inp = str(len(inp)) c+=1 print(c+1) # print(len(str(inp)))
349b3c9befeee7cded9e01e8ba9c769f8ee012f0
GiantSweetroll/Computational-Mathematics
/mid_exam/GardyanPrianggaAkbar_2301902296_COMP6572_L2AC.py
4,504
3.609375
4
from math import pi import matplotlib.pyplot as py import sympy as sp import numpy as np import time x = sp.Symbol('x') y = sp.Symbol('y') n = sp.Symbol('n') #No 1 #a #X for tools and equipment #Y for materials for EACH cloth revenueEq = (1.5*x + 2*x)*(n/2) totalCostEq = y + x*n profitEq = revenueEq - totalCostEq #I will be assuming Y has the value of 1000X and X has the value of 200000 xVal = 200000 yVal = 50*xVal print("a. Total cost:", totalCostEq) print(" Revenue:", revenueEq) temp = 1 while (revenueEq.evalf(subs={x : xVal, y: yVal, n : temp}) <= totalCostEq.evalf(subs={x : xVal, y: yVal, n: temp})): temp+=1 print("The solution means that once", temp, "clothes is sold, we will have broken even between cost and revenue. So any amount of clothes after this will produce a profit.") #b nVal = temp+1 print("b. For", nVal, "amount of clothes, he will get a profit of Rp", profitEq.evalf(subs={x: xVal, y: yVal, n:nVal})) #c nVals = [i for i in range(500, 500*10, 100)] profits = [] for nval in nVals: profits.append(profitEq.evalf(subs={x: xVal, y: yVal, n:nval})) py.plot(nVals, profits) py.xlabel("Number of clothes") py.ylabel("Profits") py.show() #d #LU Decomposition matrix = [[1, 2, 3, 10], [4, 7, 5, 4], [7, 1, 9, 11]] intervals = [] start = time.time() sp.solve_linear_system_LU(sp.Matrix(matrix), [x, y, n]) end = time.time() intervals.append(end - start) #Gauss Elimination #According to SymPy, Gauss Elimination is more efficient than Gauss-Jordan elimination start = time.time() sp.solve_linear_system(sp.Matrix(matrix), x, y, n) end = time.time() intervals.append(end - start) print("d.") print("LU Decomposition (time taken):", intervals[0]) print("Gauss Elimination (time taken):", intervals[1]) print() #No 2 #a functionOri = (x-1) function = functionOri def no_2_eq(function, n, xVal): answer = 0 for i in range(1, n+1): if (i == 1): answer = function.evalf(subs={x: xVal}) elif (i % 2 == 1): #Odd answer = answer + (functionOri**i/i).evalf(subs={x: xVal}) else: answer = answer - (functionOri**i/i).evalf(subs={x: xVal}) return answer print("No 2:") actualFunc = sp.ln(x) xVal = 2 trueError = actualFunc.evalf(subs={x: 2}) - no_2_eq(function, 5, xVal) print("a. True Error:", trueError) #b absError = abs(trueError) target = 0.0001 actualVal = actualFunc.evalf(subs={x: 2}) answer = -500 temp = 1 while (abs(actualVal - answer) >= target): if (temp == 1): answer = function.evalf(subs={x: xVal}) elif (temp % 2 == 1): #Odd answer = answer + (functionOri**temp/temp).evalf(subs={x: xVal}) else: answer = answer - (functionOri**temp/temp).evalf(subs={x: xVal}) temp += 1 print("b.", temp-1) #c target = 0.1/100 answer = -99999999999999999 temp = 1 while ((abs(actualVal - answer)/actualVal) >= target): if (temp == 1): answer = function.evalf(subs={x: xVal}) elif (temp % 2 == 1): #Odd answer = answer + (functionOri**temp/temp).evalf(subs={x: xVal}) else: answer = answer - (functionOri**temp/temp).evalf(subs={x: xVal}) temp += 1 print("c.", temp-1) #d answers = [] for n in range(1, 11): answers.append(abs(actualVal - no_2_eq(function, n, xVal))) xValues = [x for x in range(1, 11)] py.plot(np.array(xValues), np.array(answers)) py.xlabel("Terms number") py.ylabel("Approximate error") py.show() print() #No 3 def simpson_rule(equation, a, b, n): """ Method to get the integration approximation of a function using simpson rule Parameters: equation: The equation f(x) a: lower bound of the integral b: upper bound of the integral n: no of segments """ h = (b-a)/n x = sp.Symbol('x') xVal = a result = 0 #First segment result += equation.evalf(subs={x:xVal}) xVal += h #Other segments for i in range(1, n+1): if (i == n): #If last segment result += equation.evalf(subs={x:xVal}) else: if (i % 2 != 0): result += equation.evalf(subs={x:xVal}) * 4 else: result += equation.evalf(subs={x:xVal}) * 2 xVal += h result *= h/3 return result function = sp.sin(x) answers = [] for n in range(4, 11, 2): answers.append(simpson_rule(function, 0, pi, n)) print("No 3:") n = 4 for i in range(len(answers)): print("N is", n, ":", answers[i]) n+=2 #Simpson only accepts even segments
a74cfee77c8cf0ea166aac5d9d12be6d4b9a07e5
ZenVendor/Python
/CheckIO/Elementary/Elementary_19.py
525
3.8125
4
def most_frequent(data): most = '' count = 0 for word in data: if data.count(word) > count: most = word count = data.count(word) return most if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert most_frequent([ 'a', 'b', 'c', 'a', 'b', 'a' ]) == 'a' assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' assert most_frequent(["a","a","z"]) == 'a' print('Done')
8457b7e4b22ea3e752719969002f4c73972f2afb
chenxk/StudyDemo
/com/study/ai/np/NumpyDtype.py
2,133
3.515625
4
''' NumPy 数字类型是dtype(数据类型)对象的实例,每个对象具有唯一的特征。 这些类型可以是np.bool_,np.float32等。 https://www.yiibai.com/numpy/numpy_data_types.html numpy.dtype(object, align, copy) 参数为: Object:被转换为数据类型的对象。 Align:如果为true,则向字段添加间隔,使其类似 C 的结构体。 Copy? 生成dtype对象的新副本,如果为flase,结果是内建数据类型对象的引用 字节顺序取决于数据类型的前缀<或>。 <意味着编码是小端(最小有效字节存储在最小地址中)。 >意味着编码是大端(最大有效字节存储在最小地址中)。 ''' import numpy as np print(np.bool_) # int8,int16,int32,int64 可替换为等价的字符串 'i1','i2','i4',以及其他。 ''' 'b':布尔值 'i':符号整数 'u':无符号整数 'f':浮点 'c':复数浮点 'm':时间间隔 'M':日期时间 'O':Python 对象 'S', 'a':字节串 'U':Unicode 'V':原始数据(void) ''' dt = np.dtype(np.int32) print(dt) dt = np.dtype('i4') print(dt) dt = np.dtype('>i4') print(dt) dt = np.dtype([('age', np.int8)]) print(dt) dt = np.dtype([('age', np.int8)], align=True) a = np.array([(10,), (20,), (30,)], dtype=dt) print(a) print(a['age']) ''' 定义名为 student 的结构化数据类型,其中包含字符串字段name, 整数字段age和浮点字段marks。 此dtype应用于ndarray对象。 ''' student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')], align=False) print(student) a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student) ''' Python3的字符串的编码语言用的是unicode编码,由于Python的字符串类型是str, 在内存中以Unicode表示,一个字符对应若干字节,如果要在网络上传输,或保存在磁盘上就需要把str变成以字节为单位的bytes python对bytes类型的数据用带b前缀的单引号或双引号表示 'ABC' b'ABC' 要注意区分'ABC'和b'ABC',前者是str,后者虽然内容显得和前者一样,但bytes的每个字符都只占用一个字节 ''' print(a)
dcf610152c74efbaabe85f08f442ca810331779c
Maureen-max/Mad-Lib-Game-python
/Mad_lib Game.py
216
3.578125
4
color = input("Enter a color :") curtains = input("Enter the curtain type :") name = input("what is your name :") print("Roses are color", color) print("The curtain type is",curtains) print("My name is", name)
2178b61a092d0c0e769c2c8ec692ea402546304f
breezekiller789/LeetCode
/204_Count_Primes.py
1,887
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/count-primes/ # Sieve of Eratosthenes的核心概念是用消去的方法,一開始我們就準備size為n的陣列 # 陣列都是布林值,我們從頭把那些不可能是質數的位置改成false,最後再算出陣列中是 # true的個數就好,那他的想法是,一個數的平方不可能是質數,就像13^2 = 169,不可能是 # 質數,再者,一個數平方往後的倍數,一定也不是質數,以下舉例, # 3 * 3 = 9 # 3 * 4 = 12 # 3 * 5 = 15 # 3 * 6 = 18 # ... # ... # ... # 所以我們從2開始往後面刪,把是倍數的都改成false,最後做完就會只剩下質數。 n = 100 # =========Code Starts============ # Sieve of Eratosthenes if n < 2: print 0 is_Prime = [True for i in range(n)] # 先都假設全部是質數。 is_Prime[0] = False # 0不是質數,阿也不用去看,直接放False is_Prime[1] = False # 1也不是質數,直接False for i in range(2, n): # 從2開始一個一個往後,因為質數是從2開始。 if is_Prime[i]: # 如果flag是true,代表該數平方之後,以及比平方還要大 j = i # 的往後的倍數,一定也不是質數。 while i * j < n: is_Prime[i * j] = False # 往後的倍數一定不會是質數。 j += 1 print is_Prime.count(True) # # 我的暴力解法,很暴力。 # def Is_Prime(num): # flag = True # start = 2 # while start <= num/2 and flag: # if num % start == 0: # flag = False # break # start += 1 # return flag # Primes = [] # Index = 2 # if n < 2: # print Primes # if n == 2: # print [2] # while Index < n: # if Is_Prime(Index): # Primes.append(Index) # Index += 1 # print Primes
593dc5360fad48880763e6b5d6d30cd7660ece80
elena0624/leetcode_practice
/Challenge_Running_Sum_of_1d_Array1.py
167
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon May 3 15:32:32 2021 @author: ppj """ nums = [3,1,2,10,1] for i in range(1,len(nums)): nums[i]+=nums[i-1] print(nums)
578e730a33da41fc216864829e4a16d8b6852539
thoufiqzumma/tamim-shahriar-subeen-python-book-with-all-code
/all code/p.fstring application. formatted string.py
59
3.65625
4
num1 = 20 num2 = 50 print(f"{num1} + {num2} = {num1+num2}")
454d90555e21e50b6f9351fbf16bb13d938ca943
dataCalculus/fibonacci
/upgrade_1.py
1,632
4.125
4
class Fibonacci(): def __init__(self,start): self.start = start self.fibonacciList=[] def printSequence(self,count): """ instant generation count --> length of fibonacci sequence """ firstStep = self.start nextStep = self.start for i in range(count): print(nextStep) firstStep , nextStep = nextStep , firstStep+nextStep def storeSequence(self,count): """ belirtilen uzunlukta başlangıç değeri constructorda girilen fibonacci dizisini üretip kaydeder """ firstStep = self.start nextStep = self.start for i in range(count): self.fibonacciList.append(firstStep) firstStep, nextStep = nextStep, firstStep + nextStep def getSequence(self): """ fibonacci listesine kaydedilen veriyi döndürür :return: """ return self.fibonacciList def printStoredSequence(self): """ fibonacci listesine kaydedilen sayiları konsola basar :return: """ print(self.fibonacciList) def destructStoredSequence(self): """ fibonacci listesindeki değerleri siler :return: """ self.fibonacciList.clear() if __name__ == '__main__': fibonacci = Fibonacci(19) fibonacci.printStoredSequence() # None fibonacci.storeSequence(19) fibonacci.printStoredSequence() fibonacci.destructStoredSequence() fibonacci.printStoredSequence() #upgrade 2 gamified console version
4df514a30dc4f82b93d72baf9807f4d7caa83d1e
AmbyMbayi/CODE_py
/WebScraping/Question6.py
387
3.703125
4
"""write a python program to extract and display all the headers tags from en.wikipedia.org/wiki/Main_Page """ from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://en.wikipedia.org/wiki/Main_Page') bs = BeautifulSoup(html, "html.parser") titles = bs.find_all(['h1','h2','h3', 'h4', 'h5', 'h6']) print('List of all header tags: ', *titles, sep='\n\n')
a00c1c4a2319b4d9564eac7519a93d2fa866c0c4
gistable/gistable
/all-gists/5653532/snippet.py
975
4.125
4
# coding=UTF-8 """ Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo. Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo: 326 = 3 centenas, 2 dezenas e 6 unidades """ number = int(raw_input("Digite um numero: ")) if number > 0 and number < 1000: centenas = number / 100 dezenas = (number % 100) / 10 unidades = (number % 100) % 10 msg = list() msg.append("%s =" % number) if centenas == 1: msg.append("%s centena," % centenas) else: msg.append("%s centenas," % centenas) if dezenas == 1: msg.append("%s dezena e" % dezenas) else: msg.append("%s dezenas e" % dezenas) if unidades == 1: msg.append("%s unidade" % unidades) else: msg.append("%s unidades" % unidades) print ' '.join(msg) else: print "Insira um numero maior que zero (0) ou menor que (1000)"
262732c239ba84810a2334d2d51d336ac4b1001e
mohsenuss91/simple_neural_network
/neuralnet
3,865
3.640625
4
#!/usr/bin/python """Perform K-folds cross-validation on a simple neural network. Data is read from a ARFF file. Results are written to stdout. """ import optparse import math import random import utils from SimpleNeuralNetwork import SimpleNeuralNetwork def mean(list_of_numbers): """Returns the arithmetic mean of a list of numbers """ return 1. * sum(list_of_numbers) / len(list_of_numbers) if __name__ == "__main__": ######################### Parse arguments ################################# parser = optparse.OptionParser() options, args = parser.parse_args() assert len(args) == 4 # Positional argument 1: name of training set file # Positional argument 2: number of folds for cross-validation # Positional argument 3: learning rate of stochastic gradient descent # Positional argument 4: number of epochs for training filename, n_folds, learning_rate, n_epochs = args n_folds = int(n_folds) learning_rate = float(learning_rate) n_epochs = int(n_epochs) ######################### Declare inputs for learning ##################### # Load dataset X and labels y from ARFF file X, y, negative_label, positive_label = \ utils.load_binary_class_data(filename) # Size of data set n_instances = len(X) # Size of each feature vector n_feat = len(X[0]) ######################### Train neural network ############################ # Values to be written in output file predictions = n_instances * [None] # list of labels according to ARFF file outputs = n_instances * [None] # list of numbers according to ANN output fold_assignments = n_instances * [None] # numbers in interval [1, n_folds] # Fold of the test set. We start with n_folds and decrement to 1 test_fold_assignment = n_folds # Perform k folds cross validation # Each scheme is a 2-ple of indices for the training set and test set partition_scheme_generator = utils.generate_stratified_train_test_indices(y, n_folds, randomize=True) for training_inds, test_inds in partition_scheme_generator: # Initialize network ann = SimpleNeuralNetwork(n_feat) # Train network by stochastic gradient descent for training_ind in n_epochs * training_inds: instance, label = X[training_ind], y[training_ind] ann.train(instance, label, learning_rate=learning_rate) # Get non-binarized and binarized predictions of test set for ti in test_inds: instance = X[ti] predictions[ti] = positive_label \ if ann.predict(instance) == 1 \ else negative_label outputs[ti] = ann.output(instance) # Remember in which fold was each instance in the test set for ti in test_inds: fold_assignments[ti] = test_fold_assignment # Decrement fold value for next partition scheme test_fold_assignment = test_fold_assignment - 1 ######################### Write output to stdout ########################## # Our program should do stratified cross validation with the specified # number of folds. As output, it should print one line for each instance # (in the same order as the data file) indicating (i) the fold to which the # instance was assigned (1 to n), (ii) the predicted class, (iii) the # actual class, (iv) the confidence of the instance being positive (i.e. # the output of the sigmoid). for ii in range(n_instances): # index of instance true_label = positive_label \ if y[ii] == 1 \ else negative_label print "%i %s %s %f" % ( fold_assignments[ii], predictions[ii], true_label, outputs[ii] )
a2ed44022aee1ebf941aca86e5f3c08502ab3765
luca16s/INF1025
/Exercicios/ListaStrings/Exe3.py
887
4.1875
4
'''3. Crie as funções abaixo e teste-as no interpretador. a. Faça uma função que receba uma string e retorna uma string com os caracteres de índices pares b. Faça uma função que receba uma string e retorne uma cópia desta string invertida c. Faça uma função que recebe o nome de uma pessoa e a data de nascimento ('dd/mm/aaaa' ), crie e retorne sua senha de acordo com a seguintes regra: caracteres dos índices pares + dia do nascimento invertido + caracteres dos índices pares invertidos Exemplo: senha('Patinhas', '25/12/1900')  'Ptna52antP' Faça um programa que pergunte o nome de uma pessoa e a data de nascimento ('dd/mm/aaaa'), mostrando a senha de acordo com a regra acima.''' #--------------------------------------------------------------------------------- def RetornarCaracterIndicePar(texto): return texto[::2] print(RetornarCaracterIndicePar('ABCD'))
09e50bd2c35e73310492cb64e7cb50bf72b45a14
Jtaylorapps/Python-Algorithm-Practice
/remDups.py
687
3.75
4
# Remove duplicates from an array in O(n) time def remove_duplicates(input_array): # Create hash map / dictionary to add unique values of input_array to output_map = {} for element in input_array: # O(n) output_map.update({element: element}) # Create array that will contain sorted_output with the original array order output_array = [] i = 0 for element in input_array: # O(n) if element in output_map: # O(1) output_array.append(element) del output_map[element] # O(1) i += 1 return output_array print(remove_duplicates([4, 5, 5, 4, 6, 7, 8, 5, 5, 7, 12, 0])) # output: [4, 5, 6, 7, 8, 12, 0]
df672caed394e5baf248196ce8789ba0e213181b
robertvari/python_alapok_211106_1
/07_conditions.py
530
4.34375
4
number = 5 # True #if number != 10: # this runs if True # print("Number is not equal to 10") # True and True if number >= 5 and number <= 10: print("Number is between 5 and 10") # False or True if number < 5 or number > 10: print("Number is less than 5") print("Number is greater than 10") if number == 5: print("Number is 5") elif number == 8: print("Number is 8") elif number == 10: print("Number is 10") else: print("I couldn't find my favorite numbers :(((")
ecb08a634f1c3bfb84a39d762d41292b2bba43fc
nghoiwa/python
/reverse_linked_list.py
1,820
4.03125
4
class Node: def __init__(self, value=0, next=None) -> None: self.value = value self.next = next return def print_list_element(head): return head.value def print_full_list(head): if head != None: print(print_list_element(head)) print_full_list(head.next) else: return def reverse_link_list(head): # 1 -> 2 -> 3 prev = None #prev 1 -> 2 -> 3 while head: current = head # None 1 (head and current) -> 2 -> 3 head = head.next # None 1 (current) 2 (head) -> 3 current.next = prev # None <- 1 (current) 2 (head) -> 3 prev = current # None <- 1 prev -> 2 (head) -> 3 return prev def reverse_link_list_recur(head, prev=None): if not head: return prev next = head.next head.next = prev return reverse_link_list_recur(next, head) """if not head or not head.next: return head current = reverse_link_list_recur(head.next) print(current.value) print("head " + str(head.value)) head.next.next = head print("head.next.next " + str(head.next.next.value)) head.next = None return current""" def reverse(head, prev=None): while head: tmp = head head = head.next tmp.next = prev prev = tmp return prev def reversetest(head): dummy = Node(None, head) prev, current = dummy ,head while current: tmp = current current = current.next tmp.next = prev prev = tmp head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) print_full_list(head) print("---") """result = reverse_link_list(head) print_full_list(result)""" result3 = reverse(head) print_full_list(result3)
a417031d2f2d7a37e460f3d5ff48751459f28bf1
mengnan1994/Surrender-to-Reality
/py/0633_sum_of_square_nums.py
665
3.921875
4
""" Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a^2 + b^2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False """ import math class Solution: def judge_square_sum(self, c): square_set = set([]) for i in range(int(math.sqrt(c)) + 1): square_set.add(i ** 2) print(square_set) for a in square_set: if (c - a) in square_set: return True return False def test(self): c = 5 print(self.judge_square_sum(c)) soln = Solution() soln.test()
f22ac16019ccb69a5f853c3b85056a3559cd865b
jreiher2003/code_challenges
/project_euler/mult_3_5.py
159
3.765625
4
def multiple_3_5(n): x = 0 for i in range(n): if i % 5 == 0 or i % 3 == 0: x += i return x print multiple_3_5(10) print multiple_3_5(1000)
a23561d9d3e5da1c5a4fd48b2e6c40a8b8cf7d1b
scheidguy/Advent_of_Code
/2018/day1-1.py
145
3.578125
4
f = open('day1_input.txt') text = f.readlines() f.close() freq = 0 for line in text: line = line.strip() freq += int(line) print(freq)
e5176f31aac53425400899e4f3af439814cdecf1
kooshanfilm/Python
/basic_python/basics/decorator2.py
485
3.578125
4
def new_dectorator(func): def wrap_func(): print("start") func() print("end after func") return wrap_func @new_dectorator def func_need_dec(): print("this func needs decorator") func_need_dec() #another example: """ def my_decorator(func): def function_that_runs_func(): print("start") func() print("end") return function_that_runs_func @my_decorator def my_function(): print("inside") my_function() """
383aa00bfc4f6c81f3595a2f19132df7db52d25c
AleksandrFresh/training_dv
/py_clw/cl2.1.py
554
3.640625
4
#a=[] #a=map(int, input("Введите 10-ть чисел через пробел: ").split()) #m = max(a) #print(m) #iteres = int(input("введите колво итраций: ")) #myMax=0 #for i in range (iteres): # a = int(input("enter num: ")) # if a > myMax : # myMax = a #print(myMax) iteres = int(input("введите колво итраций: ")) myMax = 0 a = 0 while True: a = int(input("enter num: ")) if a == 13: break elif a > myMax : myMax = a print(myMax)
176bf8f6e0d50fcd71dfdde67287145e373229d6
emmaping/leetcode
/Python/Unique Binary Search Trees II.py
858
3.90625
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @return a list of tree node def generateTrees(self, n): return self.generate(1,n) def generate(self, left , right): if left == right: return[TreeNode(left)] if left > right: return [None] ret = [] for i in range(left, right+1): lefttree = self.generate(left,i-1) righttree = self.generate(i+1, right) for l in lefttree: for r in righttree: node = TreeNode(i) node.left = l node.right = r ret.append(node) return ret
8128be54ce84e3fb2bbef9945b2938aff170c053
ritishadhikari/Scikitlearn
/sklearn_training_model.py
1,285
3.65625
4
from sklearn.datasets import load_iris #Importing the Dataset from sklearn.neighbors import KNeighborsClassifier #Importing the Classifier from sklearn.linear_model import LogisticRegression iris = load_iris() #Instantiating the Dataset X = iris.data y= iris.target knn= KNeighborsClassifier(n_neighbors=1) #Instantiating the Classifier by tuning the model with appropriate Parameters print("Assigned Values of Knn Classifiers are :\n", knn, "\n") print("Directories of Knn Classifiers are :\n", dir(knn), "\n") knn.fit(X,y) #Fitting the model with the Data Prediction1 = knn.predict([[3,5,4,2]]) #Predicting with an unknown Data print("The Prediction for the new dataset is :\n", Prediction1) Prediction2 = knn.predict([[3,5,4,2],[5,4,3,2]]) #Predicting with an unknown Data print("The Prediction for the new datasets are :\n", Prediction2) #Predicting with another method lgg =LogisticRegression() lgg.fit(X,y) Prediction3 = lgg.predict([[3,5,4,2]]) #Predicting with an unknown Data print("The Prediction from Logistic Regression for the new dataset is :\n", Prediction3) Prediction4 = lgg.predict([[3,5,4,2],[5,4,3,2]]) #Predicting with an unknown Data print("The Prediction from Logistic Regression for the new datasets are :\n", Prediction4)
7b077c7c3c9774862a549b5ebff603fa6a2c173d
YikangGui/leetcode
/Tree.py
516
3.71875
4
def inOrder_Iterative(root, indexes): res = [] stack = [] node = 1 while stack or node != -1: while node != -1: stack.append(node) node = indexes[node-1][0] node = stack.pop() res.append(node) node = indexes[node-1][1] return res def inOrder_Recursive(root, indexes, ans): if root == -1: return inOrder_Recursive(indexes[root-1][0], indexes, ans) ans.append(root) inOrder_Recursive(indexes[root-1][1], indexes, ans)
d0397fa0157469ecd0c06a10449b0b2af54af35e
mohammedthasincmru/royalmech102018
/roc.py
494
4.15625
4
import random a={1:'r',2:'p',3:'s'} while True: p=input("your choice r/p/s: ") c=a[random.randint(1,3)] print("you chose:",p,"computer chose:",c) if(p==c): print("draw") elif(p=="r"): if(c=="p"): print("computer wins") elif(p=="p"): if(c=="s"): print("computer wins") elif(p=="s"): if(c=="r"): print("computer wins") elif(c=="r"): if(p=="p"): print("you win") elif(c=="p"): if(p=="s"): print("you win") elif(c=="s"): if(p=="r"): print("you win")
32658f13d542d0fa6dd1b546101457b9215f6773
jayw117/Light_Switch_Flow
/light_switch.py
4,658
3.734375
4
#Jason Wong # Problem: Have n lights and switches that are inside a floor plan. Ergonomic if each switch can be # seen by a light. One switch per light from graph import * from copy import deepcopy from collections import defaultdict Walls = [(1,2),(1,5),(8,5),(8,3),(11,3),(11,1),(5,1),(5,3),(4,3),(4,1),(1,1),(1,2)] lights = [(2,4),(2,2),(5,4)] #in red switches = [(4,4),(6,3),(6,2)] #in green graph = {} nodes = ['source','sink'] def ccw(A,B,C): return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0]) # Return true if line segments AB and CD intersect # Source: http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ def intersect(A,B,C,D): return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D) def visible(pt1,pt2,Walls): x1,y1 = pt1 x2,y2 = pt2 for i,wall in enumerate(Walls[:-1]): x3,y3 = wall x4,y4 = Walls[i+1] if intersect((x1,y1),(x2,y2),(x3,y3),(x4,y4)): return False return True # Code was from JuanGunner https://stackoverflow.com/questions/55486168/ # was able to understand how switches and lights are connected def edges(S,L): # S is switches, L is lights graph['sink'] = [] if len(switches) != len(lights): #check to see even amount of switches and lights print("Not even") return for i in range(0, len(S)): # will store switches as key in empty dictionary graph[S[i]] = [] for switch in range(0, len(S)): #checks to see what lights are visible to switches using visible function for light in range(0, len(S)): if visible(S[switch], L[light],Walls) == True: # if true will store lights for switches in dictionary graph[S[switch]].append(L[light]) graph['source'] = [] for switch in range(0, len(S)): graph['source'].append(S[switch]) #The source has three different options it can go out of for light in range(0, len(S)): graph[L[light]] = ['sink'] #each of the lights will connect to sink for i in lights: nodes.append(i) for x in switches: nodes.append(x) print(nodes) return flow(nodes, edges) == len(S) #https://pythoninwonderland.wordpress.com/2017/03/18/how-to-implement-breadth-first-search-in-python/ # finds shortest path between 2 nodes of a graph using BFS def bfs(graph, start, goal): # keep track of explored nodes explored = [] # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return "DONE" # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.append(node) # in case there's no path between the 2 nodes return False #print(bfs(graph, 'source','sink')) #print(graph['source']) def augment(f, p): b = 1 # bottleneck for i in range(len(p)-1): if f[(p[i],)+(p[i+1],)] != None: #If e is forward f[(p[i],)+(p[i+1],)]+=b else: #If e is backward f[(p[i+1],)+(p[i],)]-=b return f #f' def flow(nodes, edges): f = {(False):None} for n in nodes: for e in graph[n]: f[(n,) + (e,)] = 0 f[(e,)+(n,)] = None max_flow = 0 p = bfs(graph,'source','sink') #max_flow = 0 # Setting the flow at beginning 0 since there is no path while p: f = augment(f,p) for i in range(0,len(p)-1): #update edges graph[p[i]].remove(p[i+1]) #Always reverse the edge, since f(e) = 1 graph[p[i+1]].append(p[i]) #O(n) p = bfs(graph,'source','sink') #Find a path from source to sink if p == False: print("All paths done") max_flow += 1 if max_flow == len(lights): print("Ergonomic") else: print("Not Ergonomic") (edges(switches,lights))
266f16638743c35b42d2997b8df36cbfa6484038
shrutipai/CS-88
/lab02/lab02_extra.py
1,736
4.15625
4
# Optional lab02 questions. def square(x): return x * x def twice(f,x): """Apply f to the result of applying f to x" >>> twice(square,3) 81 """ "*** YOUR CODE HERE ***" def increment(x): return x + 1 def apply_n(f, x, n): """Apply function f to x n times. >>> apply_n(increment, 2, 10) 12 """ "*** YOUR CODE HERE ***" def zero(f): def _zero(x): return x return _zero def successor(n): def _succ(f): def t(x): return f(n(f)(x)) return t return _succ def one(f): """Church numeral 1: same as successor(zero)""" "*** YOUR CODE HERE ***" def two(f): """Church numeral 2: same as successor(successor(zero))""" "*** YOUR CODE HERE ***" three = successor(two) def church_to_int(n): """Convert the Church numeral n to a Python integer. >>> church_to_int(zero) 0 >>> church_to_int(one) 1 >>> church_to_int(two) 2 >>> church_to_int(three) 3 """ "*** YOUR CODE HERE ***" def add_church(m, n): """Return the Church numeral for m + n, for Church numerals m and n. >>> church_to_int(add_church(two, three)) 5 """ "*** YOUR CODE HERE ***" def mul_church(m, n): """Return the Church numeral for m * n, for Church numerals m and n. >>> four = successor(three) >>> church_to_int(mul_church(two, three)) 6 >>> church_to_int(mul_church(three, four)) 12 """ "*** YOUR CODE HERE ***" def pow_church(m, n): """Return the Church numeral m ** n, for Church numerals m and n. >>> church_to_int(pow_church(two, three)) 8 >>> church_to_int(pow_church(three, two)) 9 """ "*** YOUR CODE HERE ***"
adf1b78b321775b51437a06429af0e88109af0a6
Evacolone/Algorithm-Python
/Sort Algorithm/merge_sort.py
862
3.890625
4
# encoding=utf-8 # date: 2016-09-22 # gaooz.com # 归并排序 # 归并 def merge(list, left, mid, right): i = left j = mid + 1 temp = [] while i <= mid and j <= right: if list[i] < list[j]: temp.append(list[i]) i = i+1 else: temp.append(list[j]) j = j+1 while i <= mid: temp.append(list[i]) i = i+1 while j <= right: temp.append(list[j]) j = j+1 # 将临时表中数据复制到原理的表中 index = range(left, right+1) for i in range(len(temp)): list[index[i]] = temp[i] # 归并排序 def merge_sort(arr, left, right): if left < right: # 划分 mid = (left+right)/2 merge_sort(arr, left, mid) merge_sort(arr, mid+1, right) # 归并 merge(arr, left, mid, right)
62a2004fd02bde274ffe6284b6c74bc4b92f6126
Janragnak-X/14_S_calBMI.py
/R2a.py
369
3.546875
4
class BMI: def __init__(self,myWeight, myHeight,myName): self.myWeight = myWeight self.myHeight = myHeight self.myName = myName def calBMI(self): currentBMI = self.myWeight / (self.myHeight * self.myHeight) return currentBMI #testing person = BMI (60, 1.5,"John") print(person.myName,'BMI is',round(person.calBMI(),2))
2e1e07e3f9365c5fae2866b1f952727a63d8601a
basiledayanal/PROGRAM-LAB
/CO1.pg19.py
176
3.90625
4
a = int(input("Enter 1st number: ")) b = int(input("Enter 2nd number: ")) i = 1 while i<=a and i<=b: if a%i==0 and b%i==0: gcd = i i = i + 1 print("GCD is", gcd)
3bab800b54117c8d55102580480eb09ffff56f2d
lkoj/CSE
/notes/Adventure Game.py
5,150
3.625
4
class Room(object): def __init__(self, name, north=None, south=None, east=None, description=""): self.name = name self.north = north self.south = south self.east = east self.description = description class Player(object): def __init__(self, starting_location): self.health = 100 self.inventory = [] self.current_location = starting_location # There are the instances of the room (Instantiation) Master_Room = Room("This is the room you start in", None, None) Kitchen = Room("This is the kitchen here is where I eat", None, Master_Room) Exit_Door = Room("The exit door is here I can go outside", None) Living_Room = Room("I'm in the living room", None, Exit_Door) Garage = Room("Look at all these cars", None, Living_Room) Basement = Room("Look at all these stuff in the", None, Garage) Attic = Room("Look there are some many things in here!!!", None, Garage) Master_Room.east = Kitchen Kitchen.north = Exit_Door Exit_Door.west = Living_Room Living_Room.south = Exit_Door Garage.east = Living_Room directions = ['north', 'south', 'east', 'west', 'up', 'down'] short_direction = ['n', 's', 'e', 'w', 'u', 'd'] playing = True class Item(object): def __init__(self, name): self.name = name class Weapon(object): def __init__(self, name): super(Weapon, self).__init__(name) self.Weapon = True self.damage = 70 self.battery_life = 100 class Sword(Weapon): def __init__(self): super(Sword, self).__init__("Sword") self.damage = 50 class Gun(Weapon): def __init__(self): super(Gun, self).__init__("Gun") self.damage = 70 class Axe(Weapon): def __init__(self): super(Axe, self).__init__("Axe") self.damage = 40 class Knifes(Weapon): def __init__(self): super(Knifes, self).__init__("Knifes") self.damage = 25 class Shotgun(Weapon): def __init__(self): super(Shotgun, self).__init__("Shotgun") self.damage = 100 class Flashlight(Weapon): def __init__(self): super(Flashlight, self).__init__("Flashlight") self.Battery_life = 100 class Tourch(Weapon): def __init__(self): super(Tourch, self).__init__("Tourch") self.fuel = 100 class Vehicle(object): def __init__(self, name): self.name = name class Car(Vehicle): def __init__(self, name): super(Car, self).__init__(name) self.fuel = 100 class Jeep(Vehicle): def __init__(self): super(Jeep, self).__init__("Jeep") self.fuel = 100 class Ford(Vehicle): def __init__(self): super(Ford, self).__init__("Ford") self.fuel = 100 class Buffalo(Vehicle): def __init__(self): super(Buffalo, self).__init__("Buffalo") self.fuel = 100 class Humuee(Vehicle): def __init__(self): super(Humuee, self).__init__("Humuee") class Chevrolet(Vehicle): def __init__(self): super(Chevrolet, self).__init__("Chevrolet") class Armor(Item): def __init__(self, name, armor_amt): self.armor_amt = armor_amt class Character(object): def __init__(self, name, health, weapon, armor): self.name = name self.health = health self.weapon = weapon self.armor = armor def take_damage(self, damage): if damage < self.armor.armor_amt: print("No damage is done because of some FABULOUS armor!") else: self.health -= damage - self.armor.armor_amt if self.health < 0: self.health = 0 print("%s has fallen" % self.name) print("%s has %d health left" % (self.name, self.health)) def attack(self, target): print("%s attacks %s for %d damage" % (self.name, target.name, self.weapon.damage)) target.take_damage(self.weapon.damage) while playing: player = Player(Master_Room) print(player.current_location.name) command = input(">_") if command in short_direction: pos = short_direction.index(command) command = directions[pos] if command.lower() in ['q', 'quit', 'exit']: playing = False elif command in directions: pass elif "take" in command: Item_name = command[5:] try: next_room = player.find_room(command) if next_room is None: raise KeyError player.move(next_room) except AttributeError: print("THere is no path this way") except KeyError: print("I can't go that way.") else:player = Player(Master_Room) print("Command not recognized.") Found_item = None for item in player.current_location.item: if item.name == Item_name: Found_item = item if Found_item is not Item_name: player.inventory.append(Found_item) player.current_location.item.remove(Found_item) # Characters Joseph = Character("Joseph", 150, Gun, Armor("Metal", 50)) enemy = Character("enemy", 100, Sword, Armor("Wooden", 30)) enemy.attack(Joseph) Armor(enemy) Joseph(enemy)
9bd59b9bcfbe9e0c4b8aee1ed19c8b666160e197
akashjain15/hackerrankpythonpractice
/numpy-doTncross.py
439
3.8125
4
import numpy numpy.set_printoptions(sign=' ') n = int(input()) lis = [] for i in range(n): m = list(map(int,input().split())) lis.append(m) arr1 = numpy.matrix(lis,int) lis.clear() for i in range(n): m = list(map(int,input().split())) lis.append(m) arr2 = numpy.matrix(lis,int) print(arr1*arr2) # or we can do dot product of two arrays to get multiplication of two array # print(numpy.dot(arr1,arr2))
1f21521bfee9a81a7d241feed6a27d9ba40fd131
juansalomon/TIC
/menuoperacion.py
1,196
3.984375
4
def menu_operacion(): Seguir="Si" num1=input("Dime un numero: ") num2=input("Dime otro numero: ") while (seguir=="Si"): print "Que deseas hacer con los numeros: " print "1.Devolver la suma de las cifras pares" print "2.Devolver la suma de las cifras impares" print "3.Devolver la mayor de las cifras" print "4.Devolver un numero con las mismas cifras ordenadas de menor a mayor" respuesta=input() if(respuesta==1): suma=0 n_pares=0 n_impares=0 numero=input("Dime un numero") while numero>0: cifra=numero%10 if cifra%2==0: n_pares=n_pares+1 else: n_impares=n_impares+1 numero+numero/10 print "Tiene", n_pares, "cifras pares" if(respuesta==2): suma=0 n_pares=0 n_impares=0 numero=input("Dime un numero") while numero>0: cifra=numero%10 if cifra%2==0: n_pares=n_pares+1 else: n_impares=n_impares+1 numero+numero/10 print "Tiene", n_impares, "cifras impares" menu_operacion()
978aa8c1939a20a4cb6e59ddbdd585c2b62b57e2
JeanMarieN/CPH-Sentiment-Analysis
/preparation/from_json_to_words.py
4,266
3.5
4
''' This code is a json extractor, that takes a json file as input, targets a, then collects and cleans the data. In this case from json to ready-to-go words for NLP ''' ''' The code can be modified and adapted to fit different kind of json data and different targets''' import json # For reading in json files # For later regular expression processing through sentences # The whole natural language toolkit from nltk.tokenize import TweetTokenizer # For later natural language for the adaption of tweet feeds/insta posts ''' Load and transform json data into Python dictionary ''' def load_insta_text(target): with open str(target)+ ".json", "r") as f: # Loading the json file into python as read data = json.load(f) # Making the json file into a Python dict # Creating a string of words raw_characters = "" for line in data: try: text = line["edge_media_to_caption"]['edges'][0]['node']['text'] except IndexError: continue raw_characters+=(text) # Tokenizing the words, keeps hashtags and signs tknzr = TweetTokenizer(strip_handles=True, reduce_len=True) # Removes handles and shortens consective characters more info on: goo.gl/T7iMx4 tweet_token_words = tknzr.tokenize(raw_characters) # Save file as txt file with open(str(target) + 'filename.txt', 'w') as f: f.write('\n'.join(tweet_token_words)) ''' Next methods can be used to load in the txt file, and have the same output as tweet_token_words to apply to any method''' # Just copy paste it into the begining of the method #def load_ready_text_to_go() # data = [] # with open("filename.txt", "r") as file: # for line in file.readlines(): # data.append(line) #with open("whatever.json", "r") as f: # Opening the json file in 'r' mode as f # data = json.load(f) # Loading the json file into a Python dict ''' Creating a string of words ''' raw_characters = '' # Making an empty string for characters in data: # For each character in 'data'/python dict, apppend the following: try: # Try target following line text = characters["edge_media_to_caption"]['edges'][0]['node']['text'] # Targeting each character for 'text', inside 'node', inside 'edges', inside 'edge_media_to_caption'' except IndexError: # Except for when people didn't write anything about their uploaded picture continue raw_characters += text # Each character gets joined to the empty string '''Removing URL from the string of words''' no_URL_raw_characters = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', raw_characters) #making a string of raw characters without URL '''----------------- Introducing two methods for splitting by word ---------------------''' ''' Method 1 - Tweet_token (keeps words - keeps signs) ''' tknzr = TweetTokenizer(strip_handles=True, reduce_len=True) # Removes handles and shortens consective characters more info on: goo.gl/T7iMx4 tweet_token_words = tknzr.tokenize(raw_characters) # This nltk tokenizer splits every word in 'Twitter-recognizing' matter # OBS: KEEPS/recognize hashtags words, smileys, exclamation points, hypen and other signs #print(tweet_token_words[0:2]) # Testing the visual results #print(len(tweet_token_words)) # Checking the number of found words ''' Method 2 - Regular expression (keeps words - removes signs) ''' re_token_words = re.findall(r"[\w]+", raw_characters) # This regular expression module splits every word by whitespace # OBS: REMOVES hashtag words, smileys, exclamation --> ONLY KEEPS words and numbers, other unknown signs gets removed #print(re_token_words[0:2]) # Testing the visual results #print(len(re_token_words)) # Checking the number of found words # Inspiration for NLP: https://marcobonzanini.com/2015/03/17/mining-twitter-data-with-python-part-3-term-frequencies/
aba872040bd32bb67041143f7658337606adc213
hasson82/AI_ex2
/SearchAlgos.py
4,162
3.65625
4
"""Search Algos: MiniMax, AlphaBeta """ from utils import ALPHA_VALUE_INIT, BETA_VALUE_INIT #TODO: you can import more modules, if needed from state import get_move_between_states class SearchAlgos: def __init__(self, utility, succ, perform_move, goal=None): """The constructor for all the search algos. You can code these functions as you like to, and use them in MiniMax and AlphaBeta algos as learned in class :param utility: The utility function. :param succ: The succesor function. :param perform_move: The perform move function. :param goal: function that check if you are in a goal state. """ self.utility = utility self.succ = succ self.perform_move = perform_move self.goal = goal def search(self, state, depth, maximizing_player): pass class MiniMax(SearchAlgos): def search(self, state, depth, maximizing_player): """Start the MiniMax algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is a max node (True) or a min node (False). :return: A tuple: (The min max algorithm value, The direction in case of max node or None in min mode) """ if self.goal(state) or depth == 0: return state.heuristic_func(), None if maximizing_player: curr_max = float("-inf") for c, direction_to_son in self.succ(state, state.get_turn()): value, direction = self.search(c, (depth-1), not maximizing_player) if value > curr_max: curr_max = value returned_direction = direction_to_son # print("maximizing: heuristic value", curr_max, "depth", depth, "direction", returned_direction) return curr_max, returned_direction else: curr_min = float("inf") for c, direction_to_son in self.succ(state, state.get_turn()): value, direction = self.search(c, depth-1, not maximizing_player) if value < curr_min: curr_min = value # print("minimizing: heuristic value", curr_min, "direction None") return curr_min, None class AlphaBeta(SearchAlgos): def search(self, state, depth, maximizing_player, alpha=ALPHA_VALUE_INIT, beta=BETA_VALUE_INIT): """Start the AlphaBeta algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is a max node (True) or a min node (False). :param alpha: alpha value :param: beta: beta value :return: A tuple: (The min max algorithm value, The direction in case of max node or None in min mode) """ if self.goal(state) or depth == 0: return state.heuristic_func(), None if maximizing_player: curr_max = float("-inf") for c, direction_to_son in self.succ(state, state.get_turn()): value, direction = self.search(c, (depth-1), not maximizing_player, alpha, beta) if value >= curr_max: curr_max = value returned_direction = direction_to_son if curr_max > alpha: alpha = curr_max if curr_max >= beta: return float("inf"), None return curr_max, returned_direction else: curr_min = float("inf") for c, direction_to_son in self.succ(state, state.get_turn()): value, direction = self.search(c, depth-1, not maximizing_player, alpha, beta) # print("minimizer: depth", depth, "value", value, "curr min", curr_min, "alpha", alpha, "beta", beta) if value <= curr_min: curr_min = value if curr_min < beta: beta = curr_min if curr_min <= alpha: return float("-inf"), None return curr_min, None
0db67f1192996609e0487dd50fb00bd910446373
AP-MI-2021/lab-2-RuginaAlex
/main.py
2,270
3.859375
4
def get_base_2(n): ''' Algoritmul de schimbare a unui numar din baza 10 in baza 2 :param n: Numarul citit :return: Returnam numarul in baza 2 ''' r=0 p=1 nr=0 while n!=0: r=n%2 n=n//2 nr=nr+r*p p=p*10 print (nr) def test_get_base_2(): assert get_base_2(730)== 1011011010 assert get_base_2(251)== 11111011 def oglindit(n): ''' Functie pentru a afla oglinditul unui numar. :param n: Citim numarul caruia ii dorim oglinditul :return: Returnam oglinditul numarului ''' ogl=0 while n!=0: ogl=ogl*10+n%10 n=n//10 return ogl def is_antipalindrome(n): ''' Aflam daca numarul este antipalindrom :param n: Numarul citit :return: Returnam prin bool daca numarul este antipalindrom sau nu ''' c1=0 c2=0 invers=oglindit(n) while n!=0: c1=n%10 c2=invers%10 n=n//10 invers=invers//10 if c1==c2: return False return True def test_is_antipalindrome(): assert test_is_antipalindrome(2783) == True assert test_is_antipalindrome(2773) == False def is_palindrome(n): ''' Verificam in aceasta functie daca un numar este palindrom :param n: Citim n :return: Returnam prin bool daca numarul este palindrom sau nu ''' ogl=0 palindrom=n; while n!=0: ogl=ogl*10+n%10 n=n//10 if ogl==palindrom: return True else: return False def test_is_palindrome(): assert is_palindrome(121) == True assert is_palindrome(312) == False def main(): while True: print('1. Transformare numar in baza 2 .') print('2. Este antipalindrom?') print('3 Este Palindrom?') optiune=input('Alege optiunea:') if optiune == '1': n=int(input('Dati un numar')) get_base_2(n) elif optiune == '2': n =int(input('Dati un numar')) print(is_antipalindrome(n)) elif optiune== '3': n=int(input('Dati un numar')) print (is_palindrome(n)) elif optiune == 'x': break else: print('Optiune invalida.') if __name__ == '__main__': main()
a78dfcfbb6f7060870c2261d71c9c80329ffb357
Pirens/Projet3OC
/macgyver.py
2,673
3.90625
4
class Macgyver: ''' Init the coordinates and the objects variable ''' def __init__(self, ord, abs, nbr_objects): self.ord = ord self.abs = abs self.nbr_objects = nbr_objects ''' Move right ''' def right(self, display_map): if (display_map[self.ord][self.abs + 1] == 'N')\ or (display_map[self.ord][self.abs + 1] == 'T')\ or (display_map[self.ord][self.abs + 1] == 'E'): self.nbr_objects = self.nbr_objects + 1 if display_map[self.ord][self.abs + 1] == 'O': return display_map else: display_map[self.ord][self.abs] = 'X' self.abs = self.abs + 1 display_map[self.ord][self.abs] = 'P' position = display_map[self.ord][self.abs] return display_map ''' Move left ''' def left(self, display_map): if (display_map[self.ord][self.abs - 1] == 'N')\ or (display_map[self.ord][self.abs - 1] == 'T')\ or (display_map[self.ord][self.abs - 1] == 'E'): self.nbr_objects = self.nbr_objects + 1 if display_map[self.ord][self.abs - 1] == 'O': return display_map else: display_map[self.ord][self.abs] = 'X' self.abs = self.abs - 1 display_map[self.ord][self.abs] = 'P' position = display_map[self.ord][self.abs] return display_map ''' Move up ''' def up(self, display_map): if (display_map[self.ord - 1][self.abs] == 'N')\ or (display_map[self.ord - 1][self.abs] == 'T')\ or (display_map[self.ord - 1][self.abs] == 'E'): self.nbr_objects = self.nbr_objects + 1 if display_map[self.ord - 1][self.abs] == 'O': return display_map else: display_map[self.ord][self.abs] = 'X' self.ord = self.ord - 1 display_map[self.ord][self.abs] = 'P' position = display_map[self.ord][self.abs] return display_map ''' Move down ''' def down(self, display_map): if (display_map[self.ord + 1][self.abs] == 'N')\ or (display_map[self.ord + 1][self.abs] == 'T')\ or (display_map[self.ord + 1][self.abs] == 'E'): self.nbr_objects = self.nbr_objects + 1 if display_map[self.ord + 1][self.abs] == 'O': return display_map else: display_map[self.ord][self.abs] = 'X' self.ord = self.ord + 1 display_map[self.ord][self.abs] = 'P' position = display_map[self.ord][self.abs] return display_map
76fa3ea5c8d0b43b085ff0d6c17b38df7a730cd4
usmanchaudhri/azeeri
/hackerland/cut_a_tree_recursive.py
2,060
3.546875
4
from collections import defaultdict class Graph: # sum = [1500 1300 1100 ] value = [100, 200, 100, 500, 100, 600] def __init__(self, noOfNodes): self.totalSum = sum(self.value) self.noOfNodes = noOfNodes self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) # vertex is the index of the node def dfs(self, vertex): # what the max vertex's index is visited = [False] * (self.noOfNodes) self.dfsHelper(vertex, visited) res = list(map(lambda k: self.totalSum - k, self.value)) return min(res) # vertex is the index of the node, we can get the value of that index from the value array def dfsHelper(self, vertex, visited): visited[vertex-1] = True # for each vertex in the adjacency list for i in self.graph[vertex]: if visited[i-1] == False: # during the backtracking we are finished traversing all the child nodes # of this sub tree. self.dfsHelper(i, visited) # vertex is the parent node and i is the adjacent child node # we will store the sum of each subtree at the parent level. # this way we can just subtract the total sum from each value in the array # and hence we can determine what the max diff in the array self.value[vertex-1] += self.value[i-1] if __name__ == "__main__": tree = [1, 2, 3, 4, 5, 6] # the edges below are the indices of the vertex g = Graph(len(tree)) g.addEdge(1, 2) g.addEdge(2, 3) g.addEdge(2, 5) g.addEdge(4, 5) g.addEdge(5, 6) print(g.dfs(1)) # value = [100, 200, 100, 500, 100, 600] # value = list(map(lambda k: 1500 - k, value)) # print(value) # parsing 2d array # res = [[print(int(val)) for val in value] for value in array] # print(res) # array = [[1,2], [2,3]] # array = [2,3] # print(min(array)) # print(array.pop())
bcecb98449072cf8acbf7485ecadf4f7322a2d79
koltpython/python-exercises-spring2020
/section4/starter/hangman.py
1,045
4.1875
4
import random def pick_random_word(): """Returns a random word from a list of predefined options""" word_list = ['PYTHON', 'PUMPKIN', 'QUEEN', 'ISTANBUL', 'PENINSULA', 'ARCHIPELAGO', 'COFFEE', 'ADDICTION', 'CHARISMA', 'KUCU'] # Return random integer in range [a, b], including both end points. # random_index = random.randint(a, b) random_index = random.randint(0, len(word_list)-1) return word_list[random_index] def input_guess_letter(): """Takes and returns guess letter from user. Continues to ask for new letter if user enters invalid letter (length != 1).""" ## Your code starts here ## Your code ends here def update_display_string(correct_word, display_string, guess_letter): """ Do stuff """ ## Your code starts here ## Your code ends here lives = 6 random_word = pick_random_word() display_string = '_' * len(random_word) print(f'Welcome to Hangman! You have {lives} lives to correctly guess the word.') #Time to use functions and implement the game!
43e2a20a73a67d4798f4e5a150f581a59f3d5bc6
drhanfastolfe/python
/beginners_tutorial/strings.py
105
4.03125
4
s = "hello maam" print(s) print(s[1]) print(s.upper()) print(s.replace("maam", "leo")) print(s[0:5])
cabebde2d0c6709b3ecd0c1b605cbdc3b740e812
mfre1re/Diversas-atividades-em-Python
/Atividades - Python/Exerc.002 - Conversor de Bases (Bin, Octal, Hexa).py
438
4.1875
4
numero = int(input('Digite um número: ')) conversor = int(input('Escolha qual será a opção de conversão do seu número, sendo: \n1 - Binário \n2 - Octal \n3 - Hexadecimal \n')) if conversor == 1: print('O número em binário é {}.'.format(bin(numero)[2:])) elif conversor == 2: print('O número em Octal é {}.'.format(oct(numero)[2:])) else: print('O número em Hexadecimal é {}.'.format(str.upper(hex(numero)[2:])))
df4c913bad612d3024a03ab8756f572e50d4a280
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/stkthe002/boxes.py
928
3.984375
4
def print_square(): print('*'*5) for i in range(3): print('*' + ' '*(5-2) + '*') print('*'*5) def print_rectangle(width, height): print('*'*width) for i in range(height-2): print('*' + ' '*(width-2) + '*') print('*'*width) def get_rectangle(width, height): box = ('*'*width + "\n") for i in range(height-2): box +=('*' + ' '*(width-2) + '*' + "\n") box +=('*'*width) return box #choice = program.split(' ') #if choice[0] == 'a': # print_square() #elif choice[0] == 'b': # width,height = eval(choice[1]),eval(choice[2]) # print ("calling function") # print_rectangle(width,height) # print ("called function") #elif choice[0] == 'c': # width,height = eval(choice[1]),eval(choice[2]) # print ("calling function") # figure = get_rectangle(width,height) # print ("called function") # print(figure)
9f21cdc765f12172464ea89b5fb1e34af867c9c5
hcwhwang/ttbb
/t.py
178
3.65625
4
wList = ['c','d'] word = 'a_b_c' word.split("_") print word.split("_")[0] #word = word[len(word.split("_")[0])+1:] print word if not any( w in word for w in wList): print 'test'
6e77def2c55cb44cd90a398ffa45a63ff5b6f840
vinay-chowdary/python
/16_CSVfiles.py
1,751
3.875
4
import csv # reader() and writer() functions # For Writing: with open('myfile.csv', 'w', newline='') as fp: w_obj = csv.writer(fp) mylist = [['Ram', 'Manager', 75000], ['Lakshmi', 'Asst. Manager', 60000], ['Kumar', 'Clerk', 30000], ['Raja', 'Peon', 10000]] w_obj.writerows(mylist) # For Reading: with open('myfile.csv', 'r', newline='') as fp: r_obj = csv.reader(fp) for row in r_obj: print(row) with open('employee_file.csv', mode='w', newline='') as ef: ew = csv.writer(ef, delimiter=':', quotechar='"', quoting=csv.QUOTE_MINIMAL) ew.writerow(['Kumar', 'Marketing', 'January']) ew.writerow(['Raja', 'Finance', 'May']) with open('employee_file.csv') as ef: er = csv.reader(ef, delimiter=':', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in er: print(row) # Read / Write as Dictionary DictReader(),DictWriter() with open('employee_file2.csv', mode='w', newline='') as csv_file: fieldnames = ['emp_name', 'dept', 'birth_month'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'emp_name': 'Ram', 'dept': 'Accounting', 'birth_month': 'November'}) writer.writerow( {'emp_name': 'Lakshmi', 'dept': 'IT', 'birth_month': 'March'}) with open('employee_file2.csv') as employee_file: employee_reader = csv.DictReader(employee_file) for row in employee_reader: print(row) with open('employee_file2.csv') as employee_file: employee_reader = csv.DictReader(employee_file) for row in employee_reader: print('Name:', row['emp_name'], '\nDepartment:', row['dept'], '\nBirth Month:', row['birth_month'])
a2607a69c36a1a1896adaa23a4ce1f4f055708c3
whjwssy/Machine-Learning
/knn/knn.py
2,560
3.59375
4
import math import operator #读取文件,获取147个训练数据集 def getTrainingSet(filename,trainingSet=[]): fp = open(filename) dataset = [] for linea in fp.readlines(): #数据预处理 line = linea.replace('\n', '').replace('\t', ',') linetest = line.split(',') dataset.append(linetest) fp.close() print(dataset) print('len(dataset):' + str(len(dataset))) for x in range(len(dataset)): for y in range(4): dataset[x][y] = float(dataset[x][y])#将数据转换成float型 trainingSet.append(dataset[x]) # 计算参数的欧式距离 def euclideanDistance(instance1, instance2, lenth): distance = 0 for x in range(lenth): distance += pow((instance1[x] - instance2[x]), 2) return math.sqrt(distance) # 传递每一个测试实例,并将它同训练集每一个实例求取欧式距离,并且排序,获取k个近邻 def getNeighbors(trainingSet, testInstance, k): distances = [] lenth = len(testInstance) for x in range(len(trainingSet)): #计算测试的数据与每个训练数据的距离 dist = euclideanDistance(testInstance, trainingSet[x], lenth) #把距离写入训练实例以供排序 distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors # 根据k近邻少数服从多数的原则,将测试数据分类 def getResponse(neighbors): Votes = {} for x in range(len(neighbors)): response = neighbors[x][-1] if response in Votes: Votes[response] += 1 else: Votes[response] = 1 sort = sorted(Votes.items(), key=operator.itemgetter(1), reverse=True) return sort[0][0] def main(): trainingSet = [] testSet = [[5.4,3.4,1.5,0.4],[6.1,2.9,4.7,1.4],[7.9,3.8,6.4,2]]#测试数据三组 getTrainingSet(r'/Users/wanghongjin/Desktop/flower.txt', trainingSet) print('train set:' + repr(len(trainingSet))) print('test set:' + repr(len(testSet))) print(testSet) predictions = [] k = 6 #根据题设要求k值取6 for x in range(len(testSet)): # 循环并测试所有测试集,输出测试结果与真实标签。 neighbors = getNeighbors(trainingSet, testSet[x], k) result = getResponse(neighbors) predictions.append(result) print('测试集'+repr(testSet[x])+'的分类为'+repr(result)) if __name__ == '__main__': main()
f5070ae20fac032e457d1c30d2b501f7ec43382e
enzostefani507/python-info
/Test/test_empresa.py
929
3.609375
4
import unittest from empresa import Empleado class TestEmpleado(unittest.TestCase): @classmethod def setUpClass(cls): print("set up class") @classmethod def tearDownClass(cls): print("tear down class") def setUp(self): print("setup") self.emp1 = Empleado("axel", "perez", 5000) self.emp2 = Empleado("sandra", "rodriguez", 6000) def tearDown(self): print("teardown") def test_nombre_completo(self): print("test nombre") self.assertEqual(self.emp1.nombre_completo(), "axel perez") self.assertEqual(self.emp2.nombre_completo(), "sandra rodriguez") def test_aumentar_sueldo(self): print("test sueldo") self.emp1.aumentar_sueldo(500) self.emp2.aumentar_sueldo(500) self.assertEqual(self.emp1.sueldo, 5500) self.assertEqual(self.emp2.sueldo, 6500) if __name__ == "__main__": unittest.main()
2561e0b30a9f1b52c8b4686ce20702edc29d30b2
BranFerr/Rectangle_and_Temp_Converter
/Rectangle.py
258
4.125
4
h = input('What is the Height/Length of the Rectangle?\n') h = int (h) w = int (input('What is the Width of the Rectangle?\n')) x = int (h) * w x = str (x) h = str (h) print ('The area of a rectangle of Height/Length '+h+' and width ',w,' is '+x)
c2e472911f0ff5945eeeb2f4beb27f88600ee9ae
SergeiLSL/PYTHON-cribe
/Глава 10. Исключения Exceptions/5.4 Инструкция raise/5.4.3 Инструкция raise.py
1,549
4
4
""" 5.4 Инструкция raise https://stepik.org/lesson/427822/step/1?unit=417707 """ """ Где нам это понадобится? """ # # try: # [1, 2, 3][8] # except (KeyError, IndexError) as error: # можно добавить несколько исключений # print(f'fLogging error: {repr(error)}') # fLogging error: IndexError('list index out of range') # raise # except ZeroDivisionError as err: # print('error ZeroDivisionError') # print(f'fLogging error {err} {repr(err)}') """ В raise можно добавить """ print('*' * 30) # try: # [1, 2, 3][8] # except (KeyError, IndexError) as error: # можно добавить несколько исключений # print(f'fLogging error: {repr(error)}') # fLogging error: IndexError('list index out of range') # raise error # except ZeroDivisionError as err: # print('error ZeroDivisionError') # print(f'fLogging error {err} {repr(err)}') print('*' * 30) """ Что произойдет если будем делать исключения (KeyError, IndexError), а raise будем делать для TypeError """ try: [1, 2, 3][8] except (KeyError, IndexError) as error: # можно добавить несколько исключений print(f'fLogging error: {repr(error)}') # fLogging error: IndexError('list index out of range') raise TypeError('Ошибка типа') except ZeroDivisionError as err: print('error ZeroDivisionError') print(f'fLogging error {err} {repr(err)}')
05d95493cb4858b3dc7c36eb93ae29c723db59b6
LukeMowry/Projects
/Project20-UnitConverter.py
1,853
4.5625
5
""" Unit Converter (temp, currency, volume, mass and more) - Converts various units between one another. The user enters the type of unit being entered, the type of unit they want to convert to and then the value. The program will then make the conversion. """ init_unit = input("Please enter your current unit of temperature. >> ") fin_unit = input("Now enter the unit you want to convert to. >> ") amount = int(input("Finally, enter the amount that you are looking to convert. >> ")) def f_to_c(amount): print(round((amount - 32) * (5/9), 2)) def c_to_f(amount): print(round(amount * (9/5) + 32, 2)) def f_to_k(amount): print(round((amount + 459.67) * (5/9), 2)) def k_to_f(amount): print(round((amount * (9/5) - 459.67), 2)) def c_to_k(amount): print(round(amount + 273.15, 2)) def k_to_c(amount): print(round(amount - 273.15, 2)) if (init_unit.lower() == "f" or init_unit.lower() == "fahrenheit") and (fin_unit.lower() == "c" or fin_unit.lower() == "celsius"): f_to_c(amount) elif (init_unit.lower() == "c" or init_unit.lower() == "celsius") and (fin_unit.lower() == "f" or fin_unit.lower() == "fahrenheit"): c_to_f(amount) elif (init_unit.lower() == "f" or init_unit.lower() == "fahrenheit") and (fin_unit.lower() == "k" or fin_unit.lower() == "kelvin"): f_to_k(amount) elif (init_unit.lower() == "k" or init_unit.lower() == "kelvin") and (fin_unit.lower() == "f" or fin_unit.lower() == "fahrenheit"): k_to_f(amount) elif (init_unit.lower() == "c" or init_unit.lower() == "celsius") and (fin_unit.lower() == "k" or fin_unit.lower() == "kelvin"): c_to_k(amount) elif (init_unit.lower() == "k" or init_unit.lower() == "kelvin") and (fin_unit.lower() == "c" or fin_unit.lower() == "celsius"): k_to_c(amount) else: print("Those units are invalid.")
5d40e99c21e4d8d04570129651748bd1ecca103a
pehia/ze-camp-2019
/Programming Intro/sarath.py
287
4.15625
4
a=int(input("enter the first number :")) b=int(input("enter the second number :")) c=int(input("enter the third number :")) if((a>b) & (a>c)): print(str(a)+"is the biggest number : ") elif((b>c)): print(str(b)+"is the biggest number :") else: print(str(c)+ "is the biggest number ")
30149d0416e1784e95035347f87821997e4a7e44
SuHyeonJung/iot_python2019
/03_Bigdata/01_Collection/03_Web_crawling/02_Reguar_Expression/99_example/29_exam.py
429
3.703125
4
import re text = "The following example creates an ArrayList with a capacity of 50 elements. Four element are then added to the ArrayList and the ArrayList is trimmed accordingly." result = re.compile("\d+") m = result.finditer(text) print(m) for i in m: print(i.group()) print("Index position:", i.start()) # for element in m: # print(element) # result_1 = re.split("\d+", text) # for i in result_1: # print(i)
d72e66e97e12860cbc668f27d8e6f3354bf61bf7
Aasthaengg/IBMdataset
/Python_codes/p02880/s683315519.py
124
3.5625
4
n=int(input()) ans = "No" for i in range(1,10): if n%i==0 and n//i<10 : ans = "Yes" break print( ans )
0da7dbf45f722d5af8af47c09c6150d33a68469f
kevinchritian/UG10_E_71210797
/4_E_71210797.py
660
3.84375
4
def angka_terbesar (a, b, c): if a > b and a > c: return a elif b > a and b > c: return b return c def angka_terkecil (a, b, c): if a < b and a < c: return a elif b < a and b < c: return b return c def nilai_tengah (a, b, c): if (b > a > c) or (c > a > b): return a elif (a > b > c) or (c > b > a): return b return c a, b, c = ( int(input('masukan bilangan 1: ')), int(input('masukan bilangan 2: ')), int(input('masukan bilangan 3: ')) ) i1 = angka_terkecil(a, b, c) i2 = nilai_tengah(a, b, c) i3 = angka_terbesar(a, b, c) print(f'Urutan: {i1} {i2} {i3}')
d918beaca24f5c3590140d8ede001c872284a907
Valen0320/FuncionesBasicas
/prg_funciones_Basicas4.py
858
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 10:33:52 2021 @author: Valen """ # Leer dos numeros y calcular la combinatria de esos dos numeros # Declaracion variables fact_M=1 fact_N=1 fact_MN=1 # Entradas ve_M=int(input("Digite M: ")) ve_N=int(input("Digite N: ")) # Calcular el factorial de M for i in range(1,ve_M+1,1): fact_M=fact_M*i # Calcular el factorial de N vp_contReWhile=1 while(vp_contReWhile<=ve_N): fact_N=fact_N*vp_contReWhile vp_contReWhile=vp_contReWhile+1 # Calcular el factorial de M-N vp_difMN=ve_M-ve_N for i in range(1,vp_difMN+1,1): fact_MN=fact_MN*i # Calcular la combinatoria vps_comb_MN=fact_M/(fact_N*fact_MN) # Salidas print("Factorial M: ",fact_M) print("Factorial N: ",fact_N) print("Factorial M-N: ",fact_MN) print("La combinatoria de M,N: ",vps_comb_MN)
6ab01b8960e3d99ca63df71f72aea8d57ac106f6
hyeonhoshin/atom-editor-test
/Ch05/예외처리/filter.py
371
3.828125
4
# -*- coding: utf-8 -*- # positive.py ''' def positive(l): result = [] for i in l: if i > 0: result.append(i) return result print(positive([1,-3,2,0,-5,6])) ''' ''' def positive(x): return x > 0 print(list(filter(positive,[1,-3,2,0,-5,6]))) ''' #Using with lambda and filter func print(list(filter(lambda a:a>0,[1,-3,2,0,-5,6])))
2a678a53e17a27eba4ab19686dedb5771b078d5c
piotrnarecki/lista1Python
/l1z6.py
1,232
4.03125
4
def countParagraphs(filePath): file = open(filePath, "rt") paragraphsCount = 0 data = file.read() lines = data.split("\n") for i in lines: if i: paragraphsCount += 1 print("This is the number of lines in the file") file.close() return paragraphsCount def countWords(filePath): file = open(filePath, "rt") data = file.read() words = data.split() wordsCount = len(words) file.close() return wordsCount def countCharacters(filePath): file = open(filePath, "rt") data = file.read().replace(" ", "") charactersCount = len(data) file.close() return charactersCount def main(): import sys if len(sys.argv) is 2: try: filePath = (sys.argv[1]) # filePath = "/Users/piotrnarecki/Desktop/text1.txt" paragraphs = countParagraphs(filePath) words = countWords(filePath) characters = countCharacters(filePath) print "paragraphs:", paragraphs, " words:", words, " characters:", characters except IOError: print ('this file does not exist') else: print ('enter only filepath') if __name__ == "__main__": main()
6e7133150b24b2449429858972ab6ac03bfeebc8
ifat-tamir/python
/01_introduction/hot.py
101
3.84375
4
celsius = input("please enter degrees: ") fahrenheit = float(celsius) * 9 / 5 + 32 print(fahrenheit)
3da37548ff288a2d45d72235a45ada0b72f04069
shashank-indukuri/hackerrank
/StrongPassword.py
2,163
4.28125
4
# Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: # Its length is at least . # It contains at least one digit. # It contains at least one lowercase English character. # It contains at least one uppercase English character. # It contains at least one special character. The special characters are: !@#$%^&*()-+ # She typed a random string of length in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong? # Note: Here's the set of types of characters in a form you can paste in your solution: # numbers = "0123456789" # lower_case = "abcdefghijklmnopqrstuvwxyz" # upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # special_characters = "!@#$%^&*()-+" # Example # This password is 5 characters long and is missing an uppercase and a special character. The minimum number of characters to add is 2. # This password is 5 characters long and has at least one of each character type. The minimum number of characters to add is 1. #!/bin/python3 import math import os import random import re import sys # # Complete the 'minimumNumber' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. STRING password # def minimumNumber(n, password): # Return the minimum number of characters to make the password strong count = 0 if any(i.isdigit() for i in password)==False: count+=1 if any(i.islower() for i in password)==False: count+=1 if any(i.isupper() for i in password)==False: count+=1 if any(i in '!@#$%^&*()-+' for i in password)==False: count+=1 return max(count,6-n) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) password = input() answer = minimumNumber(n, password) fptr.write(str(answer) + '\n') fptr.close()
34aeb294d992035c5a8ccc8fa712c9568e033ce8
sarthak-chakraborty/Machine-Learning-Assgn
/Assignment2/Part 1/Part1.py
7,293
3.5
4
import numpy as np import pandas as pd # Reading data in DataFrame df1 = pd.read_csv("./dataset for part 1 - Training Data.csv") df2 = pd.read_csv("./dataset for part 1 - Test Data.csv") # Converting to integer encoding df1 = df1.replace(to_replace=['high','med','low','yes','no'],value=[2,1,0,1,0]) df2 = df2.replace(to_replace=['high','med','low','yes','no'],value=[2,1,0,1,0]) # Extracting the names of the features feature = [] for data in df1.iloc[:,:]: feature.append(str(data).strip()) # Extracting the attribute values and storing them in a list X_train = [list(df1.iloc[i,:-1]) for i in range(len(df1))] Y_train = list(df1[feature[-1]]) X_test = [list(df2.iloc[i,:-1]) for i in range(len(df2))] Y_test = list(df2[feature[-1]]) # class structure of the Decision Tree class DecisionTree: # Initialization of the class variables def __init__(self, criteria): self.criteria = criteria self.children = [] self.features = [] self.measure = [] self.labels = [] self.n_nodes = 1 self.children.append(-1) self.features.append(-1) self.labels.append(-1) self.measure.append(-1) # Computes gini index of a node def compute_gini(self, Y): length = len(Y) n = [0, 0] for i in Y: n[i] += 1 gini = 1 - sum((np.array(n)/float(length))**2) return gini # Aggregates the measure for the sibling nodes using weighted average def combine_measure(self, measure, ni, n): gini = np.array(measure) ni = np.array(ni) return np.sum((gini*ni)/n) # Computes entropy of a node def compute_entropy(self, Y): length = len(Y) n = [0, 0] for i in Y: n[i] += 1 prob = np.array(n)/float(length) entropy = 0 for i in prob: entropy += i*np.log2(i) if i else 0 # Probability of a result can be zero, hence precuations are taken return entropy*(-1) # Calls the fit_DT function with appropriate flags def fit(self, X, Y): if(self.criteria == 'gini'): flag = 1 elif(self.criteria == 'entropy'): flag = 0 self.fit_DT(X, Y, 0, flag, -1) # 0 represents that tree is to be build from root node. -1 represent no attribute has been chosen yet # Fits the Decision Tree def fit_DT(self, X, Y, node, flag, prev_attr): n_features = len(X[0]) # Compute the measure of the node node_measure = self.compute_gini(Y) if flag else self.compute_entropy(Y) self.measure[node] = node_measure # If the measure is 0, then set the label of the node and return if(node_measure == 0.0): self.labels[node] = max(Y, key=Y.count) return # Computes measure for each feature being selected for splitting. Such a feature will be chosen that has minimum impurity measure measure_feature = [] for i in range(n_features): feat = np.unique(zip(*X)[i]) measure = [] ni = [] for l in feat: Y_new = [] for k in range(len(X)): if(X[k][i]==l): Y_new.append(Y[k]) measure.append(self.compute_gini(Y_new) if flag else self.compute_entropy(Y_new)) ni.append(len(Y_new)) measure_feature.append(self.combine_measure(measure, ni, len(X))) # Feature having Minimum impurity measure is chosen measure_feature[prev_attr] = 1 if prev_attr!=-1 else measure_feature[prev_attr] # Mark 1 if some feautre has already veen used in splitting attribute = measure_feature.index(min(measure_feature)) self.features[node] = attribute self.measure[node] = node_measure-measure_feature[attribute] if (flag==0) else node_measure # Update the class variables dic = {} for l in np.unique(zip(*X)[attribute]): self.features.append(-1) self.children.append(-1) self.labels.append(-1) self.measure.append(-1) dic[l] = self.n_nodes self.n_nodes +=1 self.children[node] = dic self.labels[node] = max(Y, key=Y.count) # Divide the data and then recurse for the new nodes for l in np.unique(zip(*X)[attribute]): X_new = [] Y_new = [] for i in range(len(X)): if(X[i][attribute] == l): X_new.append(X[i]) Y_new.append(Y[i]) self.fit_DT(X_new, Y_new, self.children[node][l], flag, attribute) # Predicts the class of a given data def predict(self, X): label = [] for i in X: node = 0 # Reaches the leaf node using the attribute values and returns the label. while(1): output = self.labels[node] next_node = self.children[node][i[self.features[node]]] if(self.children[next_node] == -1): output = self.labels[next_node] break else: node = next_node label.append(output) return label # Gives the accuracy of the tree. predicts the labels and then compares with the actual results def accuracy(self, X, Y): pred = self.predict(X) correct = 0 for i in range(len(Y)): if(Y[i] == pred[i]): correct += 1 return float(correct)/len(Y) # Prints the decision tree recursively in the prescribed format def print_DT(children, split_attr, label, feature, node, level): if(children[node] != -1): print("") else: if(label[node]==0): print(": no") else: print(": yes") return for key in children[node]: for i in range(level): # add more tabs for higher levels print("\t"), print("|"+feature[split_attr[node]]+" ="), if(split_attr[node]==0 or split_attr[node]==1): # Convert the integer encoding to string if(key==0): print("low"), elif(key==1): print("med"), elif(key==2): print("high"), elif(split_attr[node]==2): print(key), elif(split_attr[node]==3): if(key==0): print("no"), else: print("yes"), a = children[node][key] print_DT(children, split_attr, label, feature, a, level+1) # Fits the decision tree taking gini index of a node as impurity measure clf1 = DecisionTree('gini') clf1.fit(X_train, Y_train) print("\n#################################") print("DECISION TREE trained using Gini Split") print("#################################") print("Structure: ") print_DT(clf1.children, clf1.features, clf1.labels, feature, 0, 0) print("_______________") print("\nGini Index of Root Node: " + "%.4f"%clf1.measure[0]) ans = clf1.predict(X_test) print("\nLabels generated on test data: ") for i in range(len(ans)): if(ans[i]==0): print(str(i+1)+ ". no") else: print(str(i+1)+ ". yes") print("Actual Labels: ") for i in range(len(Y_test)): if(Y_test[i]==0): print(str(i+1)+ ". no") else: print(str(i+1)+ ". yes") acc = clf1.accuracy(X_test, Y_test) print("\nAccuracy on Test Data: " + str(acc)) print("\n") print("\n----------------------------------\n") # Fits the decision tree with entropy of a node as the measure of impurity clf2 = DecisionTree('entropy') clf2.fit(X_train, Y_train) print("\n#################################") print("DECISION TREE trained using Information Gain") print("#################################") print("Structure: ") print_DT(clf2.children, clf2.features, clf2.labels, feature, 0, 0) print("_______________") print("\nInformation Gain of Root Node: " + "%.4f"%clf2.measure[0]) ans = clf2.predict(X_test) print("\nLabels generated on test data: ") for i in range(len(ans)): if(ans[i]==0): print(str(i+1)+ ". no") else: print(str(i+1)+ ". yes") print("Actual Labels: ") for i in range(len(Y_test)): if(Y_test[i]==0): print(str(i+1)+ ". no") else: print(str(i+1)+ ". yes") acc = clf1.accuracy(X_test, Y_test) print("\nAccuracy on Test Data: " + str(acc))
60edc42c4983fc568d2809a20a6a8c1f9af5c45e
rafaelperazzo/programacao-web
/moodledata/vpl_data/3/usersdata/130/564/submittedfiles/ex1.py
187
4.0625
4
# -*- coding: utf-8 -*- from __future__ import division a=input('digite um valor:') if a<0: a= a**2 print ('%.2f' % a) else: a= a**0.5 print('%.2f' % a)
84457f5c41fc632f079e55dd7010419bf3b7bf88
bnjbvr/ProjectEuler
/finished/problem20.py
473
3.90625
4
# -*- coding:utf-8 -*- # http://projecteuler.net/problem=20 # Find the sum of the digits in the number 100! # Returns the sum of digits of the integer n. def sumOfDigits(n): sum = 0 while n >= 10: sum += n % 10 # adds last number n /= 10 sum += n # adds the last number a last time (n == n%10 since n < 10) return sum # Computes n! def factorial(n): f = 1 while n > 1: f *= n n -= 1 return f print "Sum of digits is %s." % sumOfDigits(factorial(100))
0afb04d9e6d70bf6d96472ff1e4a86d946dede77
Wuzhibin05/python-course
/Course/Section-1/day2/code/test1.py
1,936
3.984375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Wu zhi bin" # Email: wuzhibin05@163.com # Date: 2021/4/13 # # 1、判断下列逻辑语句的True,False. # print(1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # T # print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # F # # # 2、求出下列逻辑语句的值。 # # print(8 or 3 and 4 or 2 and 0 or 9 and 7) # 8 # print(0 or 2 and 3 and 4 or 6 and 0 or 3) # 4 # 3、下列结果是什么? print(6 or 2 > 1) # 6 print(3 or 2 > 1) # 3 print(0 or 5 < 4) # False print(5 < 4 or 3) # 3 print(2 > 1 or 6) # True print(3 and 2 > 1) # True print(0 and 3 > 1) # 0 print(2 > 1 and 3) # 3 print(3 > 1 and 0) # 0 print(3 > 1 and 2 or 2 < 3 and 3 and 4 or 3 > 2) # 2 2 # 5、利用if语句写出猜大小的游戏: # 设定一个理想数字比如:66,让用户输入数字,如果比66大,则显示猜测的结果大了;如果比66小,则显示猜测的结果小了;只有等于66,显示猜测结果正确, # 然后退出循环。 number = 66 while True: guess_num = int(input("Please input number you guess:")) if guess_num > number: print("Too big") elif guess_num < number: print("Too small") else: print("You are so clever!") break # 6、在5题的基础上进行升级: # 给用户三次猜测机会,如果三次之内猜测对了,则显示猜测正确,退出循环,如果三次之内没有猜测正确, # 则自动退出循环,并显示‘太笨了你....’。 number = 66 guess_time = 0 while True: if guess_time < 3: guess_num = int(input("Please input number you guess:")) guess_time += 1 if guess_num > number: print("Too big") elif guess_num < number: print("Too small") else: print("You are so clever!") break else: print("You are so stupid!") break
ec66de38dac48ea5f6fe47e58a548247a0c3d786
danielmedinam03/Diplomado-Python2021
/EjerciciosVarios/SumarDosNumeros.py
126
3.8125
4
numero1=int(input("Numero 1: ")) numero2=int(input("Numero 2: ")) suma=numero1+numero2 print("Suma: ",suma,(type(suma)))
c69495f65f5d5e9cedb5c30a8cb3ae46781c2482
kasikritc/classic_snake_game
/Snake.py
2,939
3.90625
4
SQUARESIZE = 20 WIDTH = 35 # number of squares that can fit the width of the screen HEIGHT = 35 # number of squares that can fit the height of the screen class Snake: ''' @attributes: body = (list) storing the x and y coordinates according of each segment to box number (not according to the pixels) dir = (int) direction of head segment COLOR = (const) color of the snake ''' def __init__(self): self.body = [PVector(int(random(10, WIDTH-10)), int(random(0, HEIGHT-7)))] for i in range(1, 6): self.body.append(PVector(self.body[0].x, self.body[0].y+i)) self.dir = None self.COLOR = "#25FF25" self.add_segment = 0 def show(self): ''' @param: - @function: draw snake on screen @return: void ''' # print(self.body[0].x, self.body[0].y) for segment in self.body: fill(self.COLOR) rect(segment.x*SQUARESIZE, segment.y*SQUARESIZE, SQUARESIZE, SQUARESIZE) def change_dir(self, dir): ''' @param: (int) dir @function: change direction of snake @return: void ''' if (dir == UP or dir == 87) and dir != DOWN: self.dir = UP elif (dir == DOWN or dir == 83) and dir != UP: self.dir = DOWN elif (dir == LEFT or dir == 65) and dir != RIGHT: self.dir = LEFT elif (dir == RIGHT or dir == 68) and dir != LEFT: self.dir = RIGHT def update_loc(self): ''' @param: - @function: update the location of snake @return: void ''' head = self.body[0] # head.type = PVector(x, y) if self.dir == UP: self.body.insert(0, PVector(head.x, head.y - 1)) if self.add_segment > 0: self.add_segment -= 1 else: self.body.pop(-1) elif self.dir == DOWN: self.body.insert(0, PVector(head.x, head.y + 1)) if self.add_segment > 0: self.add_segment -= 1 else: self.body.pop(-1) elif self.dir == LEFT: self.body.insert(0, PVector(head.x - 1, head.y)) if self.add_segment > 0: self.add_segment -= 1 else: self.body.pop(-1) elif self.dir == RIGHT: self.body.insert(0, PVector(head.x + 1, head.y)) if self.add_segment > 0: self.add_segment -= 1 else: self.body.pop(-1) def check_out_of_bounds(self): pass def is_collide_with_self(self): head = self.body[0] for i in range(1, len(self.body)): if head == self.body[i]: return True return False
9fcd6637d89d2fcc65de3a494556853b409a9983
oxxostudio/python
/demo/a14.py
696
3.75
4
class human(): def __init__(self, name=None): if name: self.name = name else: self.name = '???' def talk(self, msg): print(f'{self.name}: {msg}') class Taiwan(human): def __init__(self, name, age=None): super().__init__(name) # 繼承 human 的 name if age: self.age = age else: self.age = '???' a = human('oxxo') b = human('tom') c = human() # 沒有輸入就採用預設值 print(a.name) # oxxo print(b.name) # tom a.talk('hello') # oxxo: hello b.talk('ya') # tom: ya c.talk('okok!!!!!') # ???: okok!!!!! c = Taiwan('qq', 18) print(c.name, c.age) # qq 18
ba61fc910765399ed6db13aa02c0d97ce15ac1a4
shloknangia/Machine-Learning-Algorithms
/examples/text_learning.py
884
3.859375
4
from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() string1 = "Hi this machine learning class is great great great class" string2 = "Hello the class will start late" string3 = "Hi this class will me most excellent" email_list = [string1, string2,string3] bag_of_words = vectorizer.fit(email_list) bag_of_words = vectorizer.transform(email_list) print bag_of_words print vectorizer.vocabulary_.get("great") # print vectorizer.vocabulary_.get_feature_names() # using nltk package # finding stop words from nltk.corpus import stopwords sw = stopwords.words("english") print sw, len(sw) # finding the root or stem of a word from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") print stemmer.stem("responsiveness") print stemmer.stem("looking") print stemmer.stem("unresponsive") print stemmer.stem("learning")
aad7ea9b1de87d4df0eff9783dd7d70d10c7d360
wangJmes/PycharmProjects
/pythonProject/pythonStudy/chap13/demo2.py
409
3.8125
4
# 练习 # 开发者:汪川 # 开发时间: 2021/8/23 16:24 class Student: def __init__(self, name, age): self.name = name self.__age = age def show(self): print(self.name, self.__age) stu = Student('张三', 20) stu.show() # 在类的外部使用name与age # print(stu.age) print(dir(stu)) print(stu._Student__age) # 在类的外部可以通过 _Student__age 进行访问
62e8d4d97f599f7563f1779409b1a3b5188f9cc1
emeshch/peer_code_review_2018
/8_вложенные_словари/4_tyhvop.py
2,660
3.765625
4
# Вам нужно написать программу, которая загадывает слова.В задании обязательно использовать словарь. # Программа должна уметь загадывать как минимум 5 разных слов (с разными подсказками). # Кроме того, желательно, чтобы слова и подсказки хранились в отдельном csv-файле, # который загружался бы при запуске программы. # 4. Многоточие должно содержать столько точек, сколько букв в подсказке; # ФАЙЛ со словами называется так же как и эта программа, только расширение другое from collections import defaultdict def dictionary_maker(): d = defaultdict(list) with open('words.csv', 'r', encoding='utf-8') as f: for line in f: sp = line.strip().split(';') if len(sp) != 2: continue d[sp[0]].append(sp[1]) return d def riddles(d): n = 0 w = 0 print('начало игры "угадайте существительное по словосочетанию"') for i in d: the_word = i for x in range(0, len(d[i])): clue = d[i][x] print(clue, '.' * len(clue)) print('ваша догадка?') guess = input() if guess == the_word: w += 1 if n + w == len(d) and w >= 1: print('Поздравляю, игра окончена и вы даже что-то угадали') else: print('круто! вы угадали; переходим к следующему слову') break else: if x < len(d[i]) - 1: print('НЕТ. попробуйте угадать это же слово еще раз') elif x == len(d[i]) - 1 and n + w != len(d) - 1: print('все еще нет, давайте попробуем другое слово') n += 1 elif n + w == len(d) - 1 and w >= 1: print('Поздравляю, игра окончена и вы даже что-то угадали') else: print('НЕТ. Игра окончена.') def main(): d = dictionary_maker() riddles(d) if __name__ == "__main__": main()
274120f76163e45d01aa3c8dd0e8a00249fcd3aa
Jimin2123/BaekJoon
/bronze/2750.py
203
3.515625
4
# 수 정렬하기 [ 티어 : 브론즈 1 ] # https://www.acmicpc.net/problem/2750 N = int(input()) values = [] for i in range(N): values.append(int(input())) values.sort() for i in values: print(i)
f94b8d4a92067d8d1877bcdde862f9a22daadd9c
hatmle/Python-code
/Exercises/11-hasPathWithGivenSum.py
1,164
3.71875
4
# Given a binary tree t and an integer s, determine whether there is a root to leaf path in t # such that the sum of vertex values equals s. # [input] tree.integer t # A binary tree of integers. # Guaranteed constraints: # 0 ≤ tree size ≤ 5 · 104, # -1000 ≤ node value ≤ 1000. # [input] integer s # An integer. # Guaranteed constraints: # -4000 ≤ s ≤ 4000. # [output] boolean # Return true if there is a path from root to leaf in t such that the sum of node values in it is equal to s, otherwise return false. # ## Definition for binary tree: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None def hasPathWithGivenSum(t, s): if t is None: if s == 0: return 1 else: return 0 else: ans = 0 subSum = s - t.value if subSum == 0 and t.left == None and t.right == None : return 1 if t.left is not None: ans = ans or hasPathWithGivenSum(t.left, subSum) if t.right is not None: ans = ans or hasPathWithGivenSum(t.right, subSum) return ans
50e218e10fb25b6cb3bee2b650d49c32af762083
Shaydaeva/Basic-Python
/home_work_05/5.1.py
712
4.375
4
""" Можно запрашивать название файла у пользователя, в моём случае с расширением, но можно и по умолчанию указать расширение, и у пользователя запрашивать только имя файла""" file_name = input("Enter file name with the extension") print("Enter your content") # Запись данных ввода, ограничение - пустая строка try: with open(file_name, "x", encoding='utf-8') as user_input: user_input.write("\n".join(iter(input, ""))) except IOError: print("File already exists") except EOFError: print("Input error")
2fb1ccb61f473b4ce18c02cf43a8898a88c815a6
juuhi/Python---DataStructure
/BubbleSort.py
809
4.40625
4
# Bubble sort using python # This code has the worst case complexity as O(n*n), that is when the list is in the reverse order #This code has the best case complexity as O(n) as it traverse the list once with the inner loop, #if nothing is swapped then it will exit the code and doesn't traverse the list once again. def bubbleSort(myList): for i in range(len(myList)-1): swapped = False for j in range(len(myList)-1-i): if myList[j]>myList[j+1]: myList[j],myList[j+1]=myList[j+1],myList[j] swapped=True if swapped == False: break return myList print bubbleSort([4,1,3]) print bubbleSort([2,3,1,4,5,3]) print bubbleSort([1,1,1,4,5,3]) # if you want the sorted unique list then apply the set() to the returned list.
ef49636610d94dbbcb88be0773140b6c5beb8622
balasekharnelli/Python-Basics
/Basics-1/loops-2.py
251
4.25
4
#Create a for loop that prompts the user for # a hobby 3 times, then appends each one to hobbies. hobbies = [] hobbies_count = 3 for hobby in range(0, hobbies_count): value = input("Enter your hobby: ") hobbies.append(value) print(hobbies)
4319a950a75d8e6409c1ecc8b5c65b735a772d11
Krishnaanurag01/PythonPRACTICE
/Stringsplit.py
107
3.5
4
import re from typing import Pattern Pattern=r"[ .,_'?!@]+" s=input().strip() print(re.split(Pattern,s))
85ff9390af3175f23e11e7d5f58019bb2ffeabfa
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__074.py
416
3.703125
4
# maior e menor valores em tupla from random import randint sorteio = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9)) print('Os valores sorteados foram: {}.'.format(sorteio)) print('O maior valor sorteado foi {}.'.format(max(sorteio))) print('O menor valor sorteado foi {}.'.format(min(sorteio)))
263b698c2d5ee6cd368b4ed10b89e303e6ea2674
sky-dream/LeetCodeProblemsStudy
/[0168][Easy][Excel_Sheet_Column_Title]/Excel_Sheet_Column_Title_3.py
296
3.59375
4
# leetcode time cost : 40 ms # leetcode memory cost : 13.6 MB # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def convertToTitle(self, n: int) -> str: # A ascii is 65 return "" if n == 0 else self.convertToTitle((n - 1) // 26) + chr((n - 1) % 26 + 65)
11b63f89786d216e81b20b30336f5fdd48b271e1
lhaislla/Introducao-a-programacao
/gerando_numeros_aleatorios.py
468
3.90625
4
# Programa que gera numeros aleatórios e coloca em uma tupla # Mostra a listagem dos números gerados # Indica o menor e o maior valor que estão na tupla import random sorteio = (random.randint(0, 10),random.randint(0, 10),random.randint(0, 10),random.randint(0, 10),random.randint(0, 10)) print(f'Valores sorteados:', end = ' ') for n in sorteio: print(f'{n}',end = ' ') print(' ') print(f'Menor valor: {min(sorteio)}') print(f'Maior valor: {max(sorteio)}')
c6f4902282e33b9141cfb8f97047d009d6f5a7d0
Oscarpingping/Python_code
/01-Python基础阶段代码/01-基本语法/Python分支-优化案例.py
2,197
3.5625
4
# Python版本的问题 # 思路, 语法 -> 工具 # Python3.x # 使用注释, 理清楚, 具体的实现步骤 # 代码填充 # 输入 # 身高 personHeight = input("请输入身高(m):") personHeight = float(personHeight) # 体重 personWeight = input("请输入体重(kg):") personWeight = float(personWeight) # 年龄 personAge = input("请输入年龄:") personAge = int(personAge) # 性别 personSex = input("请输入性别(男:1 女:0):") personSex = int(personSex) # 容错处理, 数据有效性的验证 # if 0 < personHeight < 3 and 0 < personWeight < 300 and 0 < personAge < 150 and (personSex == 1 or personSex == 0): if not (0 < personHeight < 3 and 0 < personWeight < 300 and 0 < personAge < 150 and (personSex == 1 or personSex == 0)): # 退出程序 print("数据不符合标准, 程序退出") exit() # 处理数据 # 计算体脂率 # BMI = 体重(kg) / (身高 * 身高)(米) # 体脂率 = 1.2 * BMI + 0.23 * 年龄 - 5.4 - 10.8*性别( BMI = personWeight / (personHeight * personHeight) TZL = 1.2 * BMI + 0.23 * personAge - 5.4 - 18.8 * personSex TZL /= 100 # 判定体脂率, 是否在正常的标准范围之内 # 正常成年人的体脂率分别是男性15%~18%和女性25%~28% # TZL MIN MAX # 0.10 1 0 # 区分男女 # personSex 1 0 if personSex == 1: # 判定男性标准的代码 result = 0.15 < TZL < 0.18 elif personSex == 0: # 判定女性标准的代码 result = 0.25 < TZL < 0.28 # minNum = 0.15 + 0.10 * (1 - personSex) # maxNum = 0.18 + 0.10 * (1 - personSex) # # result = minNum < TZL < maxNum # 输出 # 告诉用户, 是否正常 # print("你的体脂率, 是%f" % TZL) # print("你的体脂率, 是否符合标准", result) # 问好 if personSex == 1: wenhao = "先生你好:" minNum = 0.15 maxNum = 0.18 elif personSex == 0: wenhao = "女士你好:" minNum = 0.25 maxNum = 0.28 # 提示部分 if result: notice = "恭喜您, 身体非常健康, 请继续保持" else: if TZL > maxNum: notice = "请注意, 您的身体不正常, 偏胖" else: notice = "请注意, 您的身体不正常, 偏瘦" print(wenhao, notice)
fafba52c190eb20239fd2eee2b428bcf0789a867
axellbrendow/python3-basic-to-advanced
/aula013-indices-e-fatiamento-de-strings/aula13.py
638
3.96875
4
""" Manipulando strings * String índices * Fatiamento de strings [início:fim:passo] * Funções built-in len, abs, type, print, etc... Essas funções podem ser usadas diretamente em cada tipo. """ # positivos [012345678] texto = 'Python s2' # positivos -[987654321] print(texto[2:6]) print(texto[:6]) # Equivalente a [0:6] print(texto[7:]) # Equivalente a [7:9] print(texto[-1]) # Equivalente a [8] print(texto[-9:-3]) # Equivalente a [0:6] print(texto[:-1]) # Equivalente a [0:8] (exclui o último caractere) print(texto[0::2]) # Equivalente a [0] + [2] + [4] + [6] + [8] print(len(texto)) # Tamanho da string
d5febee17c663072625f70edc87e367abb8e67f4
ponvizhi19/Python-Internship
/Day5.py
1,034
4.34375
4
# 1)Create a function getting two integer inputs from user. & print the following: #Addition of two numbers is +value x=int(input("enter the first number:")) y=int(input("enter the second number:")) def add(a,b): print ("the sum is",+a+b) add(x,y) #Subtraction of two numbers is +value x=int(input("enter the first number:")) y=int(input("enter the second number:")) def diff(a,b): print ("the sum is",+a-b) diff(x,y) #Division of two numbers is +value x=int(input("enter the first number:")) y=int(input("enter the second number:")) def div(a,b): print ("the sum is",+a/b) div(x,y) #Multiplication of two numbers is +value a=int(input("enter the first number:")) b=int(input("enter the second number:")) def div(x,y): print ("the sum is",+x*y) div(a, b) #2. Create a function covid( ) & it should accept patient name, and body temperature, by default the body temperature should be 98 degree a=input() b='98°C' def covid(x,y): print ("Name of the patient =",x) print("the body temperature =",y) covid(a, b)
5502fa3455cd798fb7da1234b0b1dc261a4d049b
raunakpalit/myPythonLearning
/venv/map/map_intro.py
1,594
3.84375
4
# Wrap each of the 4 blocks of code in function definitions, then use the timeit module to # time each one. # # Remember to import timeit at the start of the file. # # My solution will use a slightly different approach, to save time in the video. The test of # whether your solution works is if successfully times all 4 approaches to capitalising the # characters and words in text import timeit text = "what have the romans ever done for us" def capital_str(): capitals = [char.upper() for char in text] return capitals # print(capitals) # use map def map_capital_str(): map_capitals = list(map(str.upper, text)) # print(map_capitals) return map_capitals def capital_word(): words = [word.upper() for word in text.split()] # print(words) return words # use map def map_capital_word(): map_words = list(map(str.upper, text.split())) # print(map_words) return map_words if __name__ == "__main__": # print(timeit.timeit("capital_str()", setup="from __main__ import capital_str", number=1000)) # print(timeit.timeit("map_capital_str()", setup="from __main__ import map_capital_str", number=1000)) # print(timeit.timeit("capital_word()", setup="from __main__ import capital_word", number=1000)) # print(timeit.timeit("map_capital_word()", setup="from __main__ import map_capital_word", number=1000)) print(timeit.timeit(capital_str, number=100000)) print(timeit.timeit(map_capital_str, number=100000)) print(timeit.timeit(capital_word, number=100000)) print(timeit.timeit(map_capital_word, number=100000))
24a581c97b6ddb4508464753de4d075e07720a60
tjbaesman/CSCI-Final-Projects
/PycharmBlackjack/Blackjack_Gameplay.py
4,790
3.578125
4
# TJ Baesman # CSCI 101 - Section D # Blackjack - Gameplay functions from Blackjack_Hand import Hand def deal_new_hands(player_hand, dealer_hand, deck): player_hand.rand_hand(deck) dealer_hand.rand_hand(deck) def make_bets(player_hand): bet_choice_unmade = True print("You have $%d" % player_hand.funds) while bet_choice_unmade: temp_bet = input("How much would you like to bet? (Whole numbers only) ") if temp_bet.isdigit(): temp_bet = int(temp_bet) else: print("Invalid input, try again") continue if temp_bet <= 0: print("Invalid input, try again") continue if temp_bet > player_hand.funds: print("Bet greater than available funds. Enter a bet that can be paid.") continue bet_choice_unmade = False player_hand.current_bet = temp_bet def choices(player_hand, dealer_hand, deck): choice_unmade = True print() print("Your hand is:") player_hand.display_hand() if player_hand.ace_present: print("Its values are %d and %d" % (player_hand.value, player_hand.value - 10)) else: print("Its value is: %d" % player_hand.value) print() if player_hand.is_blackjack(): print("Blackjack! Paying double bets") return elif dealer_hand.is_blackjack(): print("Dealer has Blackjack! Too bad.") return if player_hand.is_bust() and not player_hand.ace_present: print("You Bust! Better luck next time.") return print("The dealer has:") dealer_hand.display_hand() print() print("What would you like to do with your hand?") print("Your options: (What to Enter)\nHit(H)") if player_hand.can_split_hand(): print("Split(S)") if player_hand.can_double_down(): print("Double Down(D)") print("Stand(N)") while choice_unmade: choice = input() if choice == "H": player_hand.hit(deck) choices(player_hand, dealer_hand, deck) break elif choice == "S" and player_hand.can_split_hand(): player_hand.split_hand() split_choices(player_hand, dealer_hand, deck) break elif choice == "D" and player_hand.can_double_down(): player_hand.double_down(deck) return elif choice == "N": return else: print("Invalid choice, try again") def dealer_choices(dealer_hand, deck): while dealer_hand.value < 17: dealer_hand.hit(deck) def split_choices(player_hand, dealer_hand, deck): choice_unmade = True print() print("Your hand is:") player_hand.display_hand() if player_hand.ace_present_L: print("The left hand's values are %d and %d" % (player_hand.value_L, player_hand.value_L - 10)) else: print("The left hand's value is: %d" % player_hand.value_L) print() if player_hand.ace_present_R: print("The right hand's values are %d and %d" % (player_hand.value_R, player_hand.value_R - 10)) else: print("The right hand's value is: %d" % player_hand.value_R) print() if player_hand.is_bust(): if player_hand.hand_side == "L": print("Your left hand Busts! Better luck next time.") player_hand.hand_side = "R" split_choices(player_hand, dealer_hand, deck) else: print("Your right hand Busts! Better luck next time.") player_hand.hand_side = "L" return print("The dealer has:") dealer_hand.display_hand() print() if player_hand.hand_side == "L": print("What would you like to do with your left hand?") else: print("What would you like to do with your right hand?") print("Your options: (What to Enter)\nHit(H)\nStand(N)") while choice_unmade: choice = input() if choice == "H": player_hand.hit(deck) split_choices(player_hand, dealer_hand, deck) break elif choice == "N": if player_hand.hand_side == "L": player_hand.hand_side = "R" split_choices(player_hand, dealer_hand, deck) else: player_hand.hand_side = "L" return else: print("Invalid choice, try again") def end_game(player_hand): if player_hand.funds <= 0: print("You're out!") return False choice_unmade = True while choice_unmade: end_char = input("Would you like to play another hand? (Y/N)") if end_char == "Y": return True elif end_char == "N": return False else: print("Invalid input, try again")
4592ad56580e910d04cf621ce715b5ca78a79491
PauDuna/FeF_ej
/ej3/ej3.py
720
3.5625
4
import collatz import time start = time.time() secuencia2 = [] #sec de collatz mas larga hasta el momento numero = 1000000 b = list(range(2,numero+1)) for i in b: a = collatz.collatz (i) if len(a) > len(secuencia2): secuencia2.clear() secuencia2 = a c = set(secuencia2) #hace lo que le digo abajo mas rapido si estan ordenados b = [j for j in b if j not in c] #que no pruebe los que estan en la sec ya encontrada, porque la sec a la cual dan lugar va a ser menor que la actual print("El numero inicial menor a {} que produce la sucesion mas larga es: {}".format(numero,secuencia2[0])) end = time.time() print("El programa tardo {} segundos en ejecutarse." .format(end-start))
f4a909437ea389c3ba37b3d01a84a825047a0b0d
jiangjinju/Algorithms
/DP_Cuttingrod.py
1,040
3.671875
4
#Algorithms-Lab9-Dynamic Programing-cutting rod problem #c is unit cutting cost #n is rod total length import copy def OPT(price,n,c): profit=[0 for x in range(n+1)] cutlength=[] #the lenght of each piece profit[0]=0 profit[1] = price[0] cutlength.append([]) cutlength[0]=[] cutlength.append([]) cutlength[1]=[] for i in range(2,n+1): cutlength.append([]) m = price[i-1] cutindex=-1 for j in range(1,i): if price[j-1]+profit[i-j]-c>m: m=price[j-1]+profit[i-j]-c cutindex=j profit[i]=m if(cutindex!=-1): cutlength[i]=copy.copy(cutlength[i-cutindex]) cutlength[i].append(cutindex) return profit[n],cutlength[n] #testing script price_list=[3,4.5,8,9,10,17,17,20,22] n=8 #rod length c=1 #unit cutting cost m,k=OPT(price_list,n,c) print("max profit is: ",m) sum=n print("the cutting pieces are:") for x in k: sum-=x print(x) print(sum)