Dataset Viewer
Auto-converted to Parquet
blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d92e3e552a116e197b0b1e764ec0d58cb447267b
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/8a48ee8856204b46a1e4f8380a45d683.py
688
3.828125
4
# # Skeleton file for the Python "Bob" exercise. # def hey(what): #Testing for an empty string, or any lenthg of white space. #And return "Fine. Be that way!" if true if what.isspace() or what == '': return 'Fine. Be that way!' #Testing if the string has been written all in uppcase, ignoring the final character #and return 'Whoa, chillout!' if true. if what.isupper(): return 'Whoa, chill out!' #Testing final character of string if it is a question mark (?) #and return 'Sure.' if true. if what[-1] == '?': return 'Sure.' #Finally if not caught by any test before, return 'Whatever.' else: return 'Whatever.'
99c648d70caaddb758e854f62d0cfce5e9285a13
baewonje/iot_bigdata_-
/python_workspace/01_jump_to_python/4_input_output/1_function/3_164_3.py
371
3.671875
4
a=10 def vartest(a): print(a) # 전역 변수를 단순히 조회하는 것은 문제가 없다. # def vartest2(): # print(a) # a = a+1 # 지금과 같은 방식으로 전역 변수의 값을 수정 할 수 없다. # print(a) def vartest3(): global a print(a) a=a+1 print(a) vartest() vartest2()
52353e611a8d8c24b3e13f8916f8bf2ea82721d1
harrydadson/100daysofpython
/practice_python/Classes/07_concepts.py
1,282
3.671875
4
class Dog: def __init__(self, name, age, friendliness): self.name = name self.age = age self.friendliness = friendliness def likes_walks(self): return True def bark(self): return "arf arf!" class Samoyed(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def bark(self): return "arruff!" class Poodle(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def shedding_amt(self): return 0 class GoldenRetrieve(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def fetch_able(self): if self.age < 2: return 8 elif self.age < 10: return 10 else: return 7 class GoldenDoodle(Poodle, GoldenRetrieve): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def bark(self): return "aroooo!" sammy = Samoyed("Sammy", 2, 10) goldie = GoldenDoodle("Goldie", 1, 10) generic_dogo = Dog("Gene", 10, 10) print(goldie.shedding_amt()) print(goldie.fetch_able()) print(sammy.bark()) print(goldie.bark()) print(generic_dogo.bark())
bbda6b491a80b43dfff336de962c1d2188750f31
ivanamark/bdc
/controlflow/ifstat1.pyw
1,060
4.15625
4
points = 174 # use this input to make your submission wooden_rabbit="wooden rabbit" no_prize="Oh dear, no prize this time." wafer_thin_mint="wafer-thin mint" penguin="penguin" if 1<=points<=50: prize=wooden_rabbit elif 51<=points<=150: print(no_prize) elif 151<=points<=180: prize=wafer_thin_mint elif 181<=points<=200: prize=penguin else: print('You can\'t have more than 200 points' ) # write your if statement here result="Congratulations! You won a {}!".format(prize) print(result) points_1 = 174 # use this input when submitting your answer # set prize to default value of None prize_1 = None # use the value of points to assign prize to the correct prize name if points_1 <= 50: prize_1 = "wooden rabbit" elif 151 <= points_1 <= 180: prize_1 = "wafer-thin mint" elif points_1 >= 181: prize_1 = "penguin" # use the truth value of prize to assign result to the correct message if prize_1: result_1 = "Congratulations! You won a {}!".format(prize) else: result_1 = "Oh dear, no prize this time." print(result)
d08820c0088adf4d48241550a2e7047df9c3c86a
io-ma/Zed-Shaw-s-books
/lpthw/ex45/cave.py
8,330
3.921875
4
from textwrap import dedent import result as res class Cave(object): """ Main cave class """ def __init__(self, name): """Initialize cave class """ self.name = name # We need an entry scene self.entry_scene = """ """ # We need a description self.description = """ """ # We need a map of the cave # NOTE: implement a real map # in future versions # self.cave_map = """ """ # We might need the depth # in future versions self.depth = None # This is the problem the # diver needs to solve self.problem = """ """ # We need a winning choice self.won_choice = "won choice" # This is the unlucky choice self.death_choice = "death choice" # We need a different penalty # phrase for each cave self.death_phrase = "death phrase" # The divers gets rewarded with # this winning phrase self.won_phrase = "won phrase" # choose cave intro self.intro = """What is the cave you'd like to explore today? """ def enter(self): """ prints the cave entry scene """ print(dedent(self.entry_scene)) def get_description(self): """ prints description of cave """ print(dedent(self.description)) def get_map(self): """ prints cave map """ print(dedent(self.cave_map)) def get_depth(self, depth): """ defines cave depth""" self.depth = depth def get_problem(self): """ prints cave problem """ print(dedent(self.problem)) def get_won_phrase(self): """ prints winning phrase """ print(dedent(self.won_phrase)) def choose_cave(): izbandis = Cave("Izbandis") mina = Cave("Mina") bulz = Cave("Bulz") caves = [izbandis, mina, bulz] izbandis.entry_scene = "Izbandis is quite dangerous if you are not good at cave diving." izbandis.description = """ You see a beautiful tiny cristal clear lake. It is not very cold outside. The autumn leaves are the only reminders of this planet. The rest looks like in a dream. You put your drysuit on, carry your big tanks to the brink of the lake. Your heart is pounding with hope: this is starting well, it will be a promissing dive. The instructor is already in the water, waiting for you. """ izbandis.depth = 100 izbandis.cave_map = """ Hey, he says, we are going to descend directly to 28 m then find the entrance of the cave on the left. No guiding reel to that point. Once in the cave we are going to see the reel on the left. Following a narrow left corridor we'll reach a point where the reel goes under in a deep tunnel. 50 m deep. Then it opens up to a bigger cave. We explore that a little bit then ascend. Let's go! """ izbandis.problem = """ You found the reel on the left . There is a long, narrow corridor and two entrances: one up, one down. Where do you go? """ izbandis.won_choice = "up" izbandis.death_choice = "down" izbandis.death_phrase = "Wrong and bad. Your air finishes as you try to find the way back." izbandis.won_phrase = """ Perfect, your dive goes on as planned. You have enough air to explore the big beautiful cave. You ask the instructor to take a few pictures of you then you both ascend. Well done! """ mina.entry_scene = """ There's an old gold mine that was abandoned 20 years ago. After an earthquake some of its walls collapsed and the mine was filled with water. """ mina.description = """ You enter a dark tunnel. The water level is high enough. Once you reach the water, the instructor is helping you with handling the bottles. Just follow the reel, the instructor tells you. I will be in front of you at all times. If you stay behind and can't see me just check the reel. You go in and follow him. You turn on the light. Brilliant turquoise shafts of light plunge more than 30 m straight down. """ mina.depth = 35 mina.cave_map = """ There is a 500 m long, 4 m wide tunnel right in front of you. It then goes right and opens up downwards in a huge chamber. The descent is quite rocky and you have to be careful and follow the reel. """ mina.problem = """ while enjoying the view your lights go off. what do you do? change batteries or dive into the unknown? """ mina.won_choice = "change" mina.death_choice = "dive" mina.won_phrase = """ Good, you are going to enjoy a great dive. You know what to do in limit situations. The instructor takes pictures of you and you ascend happy. """ mina.death_phrase = "You should have listened to your mommy, this is a dangerous sport." bulz.entry_scene = """ Bulz doesn't have long galleries, but it's spectacular. The surrounding Valley is called The Valey of Hell. """ bulz.description = """ This one is a 4 km cave. It has lots of tunnels and obstacles. You really need to stay close to me, says the instructor. """ bulz.depth = 95 bulz.cave_map = """ The entrance is 6 m long and it's entirely submersed. The first gallery is 13 m long and it's only accessible by rib. There's a 2 m waterfall on the South wall. We can bypass it keeping right. In 5 m we face the second waterfall. On the left of it, the main tunnel. We enter this one then go down to 40 m. We play a bit there than come back. The reel is always on our right. You go in the water and swim to the rib. The instructor lights the waterfall. You follow the reel and reach 40 m in a 5 minutes descent. """ bulz.problem = """ You look back but the instructor is gone. What do you do next? Go back? Wait for him there? """ bulz.won_choice = "wait" bulz.death_choice = "go" bulz.won_phrase = """ You have lots of air to wait for him. Soon enough you see his light above you. The dive goes on. He takes pictures of you and you surface """ bulz.death_phrase = "You panick and get lost.You breathe like a running giraffe. At 30 bars you don't have enough air for safety stops" print(dedent(""" What is the cave you'd like to explore today? """)) print("Izbandis\nMina\nBulz") cave_choice = input('> ') for cave in caves: if cave_choice in cave.name: cave.enter() cave.get_description() cave.get_map() cave.get_problem() choice = input('> ') if cave.won_choice in choice: cave.get_won_phrase() elif cave.death_choice in choice: res.Death(cave.death_phrase) else: print("Not an option") res.Death(cave.death_phrase) else: continue
e431fb7ad66da3aeffa593ed688617b5a8f6770a
Hoon94/Algorithm
/Leetcode/20 Valid Parentheses.py
1,251
3.828125
4
class Solution: def isValid(self, s: str) -> bool: """[summary] Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Args: s (str): 1 <= s.length <= 104, s consists of parentheses only '()[]{}'. Returns: bool: Ture or False. Result: Runtime: 48 ms, faster than 10.17% of Python3 online submissions for Valid Parentheses. Memory Usage: 14.1 MB, less than 88.53% of Python3 online submissions for Valid Parentheses. """ open = {"(": ")", "[": "]", "{": "}"} stack = [] for s_ in s: if s_ in open: stack.append(s_) else: if len(stack) == 0: return False if s_ is open[stack[-1]]: del stack[-1] else: return False if len(stack) > 0: return False else: return True
4a339cbd56cfcff44ec4838791393ed66e5c1b97
wuchenxi118/lc
/rotate_image.py
1,030
3.984375
4
import copy class Solution: def rotate(self, matrix): """ Do not return anything, modify matrix in-place instead. """ if len(matrix)==0: return matrix temp = copy.deepcopy(matrix) size = len(matrix) for i in range(size): for j in range(size): matrix[i][j] = temp[size-j-1][i] print(matrix) def rotate_inplace(self,matrix): if len(matrix)==0: return matrix size = len(matrix) for i in range(size): for j in range(i,size): temp = matrix[j][i] matrix[j][i] = matrix[i][j] matrix[i][j] = temp for i in range(size): for j in range(size//2): temp = matrix[i][j] matrix[i][j] = matrix[i][size-j-1] matrix[i][size - j - 1] = temp print(matrix) if __name__ == '__main__': m = [[1,2,3],[4,5,6],[7,8,9]] S = Solution() S.rotate_inplace(m)
f5f2707a3e6408585157a2d289dd55aa082dc061
framoni/switches
/tree_search.py
2,980
3.609375
4
import copy import itertools def get_groups(size): """ starting from the board size, find all groups of decision variables v_i """ groups = {} for i in range(1, size ** 2 + 1): neig_i = [] neig_i.append(i) if not i % size == 1: neig_i.append(i - 1) if not i % size == 0: neig_i.append(i + 1) if i - size > 0: neig_i.append(i - size) if i + size <= size ** 2: neig_i.append(i + size) groups[i] = neig_i return groups def get_next_group(groups, values, board): """ get the next equation to solve """ unk = [] for group in groups.items(): group_values = [values[i - 1] for i in group[1]] unk.append(len([i for i, x in enumerate(group_values) if x == -1])) M = max(unk) if M == 0: return validate(groups, values, board) for it, u in enumerate(unk): if u == 0: unk[it] = M + 1 next_group = unk.index(min(unk)) + 1 return next_group def get_combinations(values, board, groups): """ recursively compute the combinations that satisfy the game equations """ next_group = get_next_group(groups, values, board) if next_group == -1: return True if next_group == -2: return False # print(next_group) # compute sum of known variables in group sum = 0 remaining = copy.copy(groups[next_group]) for it in groups[next_group]: if values[it - 1] > -1: sum += values[it - 1] remaining.remove(it) if board[next_group - 1] == 0: # odd combinations if sum % 2 == 1: r = range(0, len(remaining) + 1, 2) else: r = range(1, len(remaining) + 1, 2) else: # even combinations if sum % 2 == 1: r = range(1, len(remaining) + 1, 2) else: r = range(0, len(remaining) + 1, 2) for i in r: v_it = [0] * len(remaining) for j in range(i): v_it[j] = 1 for k in set(itertools.permutations(v_it)): for idx, m in enumerate(k): values[remaining[idx] - 1] = m # recursion here status = get_combinations(values, board, groups) if status: return True else: for idx, m in enumerate(k): values[remaining[idx] - 1] = -1 def validate(groups, values, board): for g in groups: group_values = [values[i - 1] for i in groups[g]] if board[g - 1] == 0 and sum(group_values) % 2 == 0: return -2 # error if board[g - 1] == 1 and sum(group_values) % 2 == 1: return -2 # error return -1 if __name__ == "__main__": size = 2 # board = [1, 0, 0, 0, 0, 1, 1, 0, 1] board = [1, 1, 1, 0] values = [-1] * size ** 2 groups = get_groups(size) print(groups) get_combinations(values, board, groups) print(values)
7e44e1cca9699b32e96df998c3583b235f0ad330
eujc21/AlgPy
/algpy/core/basic.py
1,514
3.734375
4
######### Basic - A class for basic mathematical calculations ######### class AlgPyBasic(object): #---------------------------------------------------------------------- """docstring for Basic.""" def __init__(self, arg): super(AlgPyBasic, self).__init__() self.arg = arg self.functions = { 'sum': self.sum, 'subtract': self.subtract, } #---------------------------------------------------------------------- def run(self): """ Distribute operation through registering a function """ operation = self.arg print self.functions[operation]() #---------------------------------------------------------------------- def sum(self): """ sums all arguments passed through the input """ inputOfTuple = input('Enter your arguments, seperated by commas: ') result = 0 if isinstance(inputOfTuple, tuple): for x in inputOfTuple: result += x return result #---------------------------------------------------------------------- def subtract(self): """ subtract all numbers passed through the input """ inputOfTuple = input('Enter argument in order of subtraction: ') if isinstance(inputOfTuple, tuple): result = inputOfTuple[0] for x in inputOfTuple: index = inputOfTuple.index(x) if(index != 0): result -= x return result
65fc639d6bf8f93c56a12bea87ec1337382c702d
ArifSanaullah/Python_codes
/74.print vs return - Python tutorial 71.py
304
3.890625
4
# 74.print vs return - Python tutorial 71 def add_three(a,b,c): return (a+b+c) add_three(5,5,5) print(add_three(6,6,6)) # both are same but in case of fuinctions return is better bcz # often we use such functions that dont have to print anything # we just use thier value in return in the code
7fcda50ff779e39172bdf5db47d7b6174effe223
liyu10000/leetcode
/linked-list/#24.py
1,066
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # recursive solution class Solution: def swapPairs(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head curr = head head = head.next curr.next = head.next head.next = curr head.next.next = self.swapPairs(head.next.next) return head # iterative solution class Solution: def swapPairs(self, head: ListNode) -> ListNode: dummy = next_head = ListNode(0) dummy.next = head cur = head while cur and cur.next: first = cur second = cur.next # swap next_head.next = second # update the head pointer first.next = second.next second.next = first # update next_head and cur node for next swap next_head = first cur = first.next return dummy.next
69a99983c318f8d332ca7577bef301ea20c7c2bc
Christopher-Cannon/python-docs
/Example code/16 - rectangle.py
432
4.1875
4
def rectangle_area(width, height): return width * height def rectangle_perimeter(width, height): return (width * 2) + (height * 2) width = int(input("Width of rectangle?: ")) height = int(input("Height of rectangle?: ")) area = rectangle_area(width, height) perimeter = rectangle_perimeter(width, height) print("Your rectangle is {} by {}".format(width, height)) print("Area: {}\nPerimeter: {}".format(area, perimeter))
a52891764e501c650c1e94d4dd69c00d5296d0ea
Gablooblue/CS11-PS2
/src/vector_sum.py
791
3.921875
4
def findQuadrant(x,y): if x > 0 and y > 0: return "I" elif x >0 and y < 0: return "IV" elif x < 0 and y > 0: return "II" else: return "III" def getNumber(s): num = "" for c in s: #for characters in string s if(c != '[' and c != ']'): num += c return int(num) def calc(a): b = [] for i in a: for j in i: b.append(j.split(",")) x = getNumber(b[0][0]) + getNumber(b[1][0]) # x1 + x2 y = getNumber(b[0][1]) + getNumber(b[1][1]) # y1 + y2 output = "[" + str(x) + "," + str(y) + "]" print(output, end = " ") print(findQuadrant(x,y)) n = int(input()) a = [] for i in range(n): line = input() a.append(line.split()) calc(a) a = []
de83847ea244027d4f35204093512451480e3642
cheezypuff/GameEngine
/World.py
1,264
3.609375
4
import pygame from Sprite import * class World: def __init__(self,size,rm): self.player = None self.rm=rm self.size=size self.s = size self.reset() def reset(self): self.sprites=[] #for x in range (20): # self.sprites.append(Sprite(self.rm.getAnimation("ahhh"),self.size)) #for x in range (20): # self.sprites.append(Sprite(self.rm.getImage("cronoflip"),self.size)) for x in range(1): self.player = Sprite(self.rm.getAnimation("left"), self.size) def update(self,dtime): self.player.update(dtime) for s in self.sprites: s.update(dtime) def draw(self,screen): for s in self.sprites: s.draw(screen) self.player.draw(screen) def jump(self): """Causes the player to start jumping""" pass def left(self): """starts the player from moving to the left""" self.player.velocity[0] = -30.0 def right(self): """starts moving the player to the right""" self.player.velocity[0] = 30.0 def stop(self): """stops the player sprite from moving horizontally""" self.player.velocity[0] = 0.0
98a96d8ce203446d038edeffc6b617ba0349114d
rodsom22/lwf_polyps
/retinanet/utils/colors.py
1,018
3.875
4
import warnings def label_color(label): """ Return a color from a set of predefined colors. Contains 80 colors in total. Args label: The label to get the color for. Returns A list of three values representing a RGB color. If no color is defined for a certain label, the color green is returned and a warning is printed. """ # specularity: pink, saturation: dark blue, artifact: light blue, blur: yellow, contrast: orange, bubbles: black, instrument: white colors = [ [236 , 20 , 236] , #pink [12 , 16 , 134] , #navyblue [23 , 191 , 242] , #lightblue [242 , 242 , 23] , #yellow [242 , 156 , 8] , #orange [10 , 10 , 10] , #black [255 , 255 , 255] , #white [255 , 51 , 51] , #red [255 , 51 , 255] , #purple ] if label < len(colors): return colors[label] else: warnings.warn('Label {} has no color, returning default.'.format(label)) return (0, 255, 0)
78e49f73474a97a0fd0a93d3a654c2a0ebf73ec8
Mi7ai/A
/E4/power.py
1,027
3.546875
4
import sys from algoritmia.schemes.divideandconquer import IDivideAndConquerProblem, DivideAndConquerSolver class PowerSolver(IDivideAndConquerProblem): def __init__(self, a, b): self.a = a self.b = b def is_simple(self) -> "bool": return self.b == 1 def trivial_solution(self) -> "Solution": return self.a def divide(self) -> "Iterable[IDivideAndConquerProblem]": yield PowerSolver(self.a, self.b // 2) yield PowerSolver(self.a, self.b // 2) def combine(self, solutions: "Iterable[Solution]") -> "Solution": a, b = tuple(solutions) pow = a * b return pow if __name__ == '__main__': print("POWER NUMBER CALCULUS") a = int(input("Enter base number: ")) b = int(input("Enter exponent number: ")) if b % 2 != 0: print("ONLY EVEN EXPONENT") sys.exit(-1) problem = PowerSolver(a, b) solution = DivideAndConquerSolver().solve(problem) print("{} powered {} = {}".format(a, b, solution))
fde20c4a8fb14d053f5d2fc2407ba3b9b1a6dd66
ndpark/PythonScripts
/RPS.py
2,147
4.28125
4
#! python3 import random """ Let's make a game of Rock, Paper, Scissors, where the user will play against the computer. """ # Ask the user their name and store it in a variable called name. name = input('Hello! What\'s your name?') print ('Okay ' + name + '! Let\'s play Rock, Paper, Scissors.') print('Rock breaks scissors, scissors beat paper, paper beats rock') #Making a list rps = ['r','p','s'] #Two variables for score player1 = 0 player2 = 0 print('\n\nR: Rock P:Paper S:Scissor') user = input() user.lower python = random.choice(rps) if user == python: print('It\'s a tie!') while player1 < 5 or player2 < 5: #Prompt the user to enter their choice and store it in 'user' print ('R: Rock, P: Paper, S: Scissor') user = input('Enter your choice: ') #Here is the computer's selection is stored in the python variable import random #Normally, we import modules at the begining of the script. python = random.choice(rps) #Compare the variables user and py in the if statement. if user == python: print ('It\'s a tie!') # First case elif user == 'p' and python == 'r': print ('You entered Paper. I had Rock. You win!') player1 = player1 + 1 # Second case elif user == 's' and python == 'r': print ('You entered Scissors. I had Rock. I win!') player2 = player2 + 1 # Third case elif user == 'r' and python == 'p': print ('You entered Rock. I had Paper. I win!') player2 = player2 + 1 #Fourth case elif user == 's' and python == 'p': print ('You entered Scissors. I had Paper. You win!') player1 = player1 + 1 #Fifth case elif user == 'r' and python == 's': print ('You entered Rock. I had Scissors. You win!') player1 = player1 + 1 # Sixth case elif user == 'p' and python == 's': print ('You entered Paper. I had Scissors. I win!') player2 = player2 + 1 # When someone has reached 5 points: if player2 == 5: print ('Python wins!') elif player1 == 5: print ('You win! Congrats!')
06fc84e3b4bb4e4ab114a95957fd1f0eb4b0a5b2
mrlaska/Students_List
/Students_List.py
1,936
4.21875
4
students = [] def get_student_titlecase(): for student in students: return student def print_students_titlecase(): for student in students: print(student) def add_student(name): student = name.title() students.append(student) def save_file(student): try: f = open("students_list.txt", "a") f.write(student + "\n") f.close() except Exception: print("Couldn't save the file.") def read_file(): try: f = open("students_list.txt", "r") for student in f.readlines(): add_student(student) f.close() except Exception: print("Couldn't read the file.") def select(): print("Welcome to Students list!","Please pick the option number","[1] Print the students list","[2] Add a new item","[3] Exit", sep="\n") adding_students = input("What is your choice?") if adding_students == "2": student_name = input("Enter student name: ") add_student(student_name) save_file(student_name) select2() elif adding_students == "1": print_students_titlecase() select2() elif adding_students == "3": print("Program will close then.") else: print("You didn't pick the proper action.") select2() def select2(): print("","","Please pick the option number","[1] Print the students list","[2] Add a new item","[3] Exit", sep="\n") adding_students = input("What is your choice?") if adding_students == "2": student_name = input("Enter student name: ") add_student(student_name) save_file(student_name) select2() elif adding_students == "1": print_students_titlecase() select2() elif adding_students == "3": print("Program will close then.") else: print("You didn't pick the proper action.") select2() read_file() select()
b8d7f20b5d3ff5d32238d27a886aa210c3cdc414
Ian100/Curso_em_Video-exercicios-
/desafio_20.py
471
3.953125
4
# O mesmo professor do desafio 019 quer sortear a # ordem de apresentação de trabalhos dos alunos. # Faça um programa que leia o nome dos quatro # alunos e mostre a ordem sorteada. from random import shuffle # shuffle significa embaralhar a = input('Primeiro aluno: ') b = input('Segundo aluno: ') c = input('Terceiro aluno: ') d = input('Quarto aluno: ') o = [a, b, c, d] shuffle(o) print('A ordem de apresentação dos trabalhos é \n{}'.format(o))
f60cffe6c45632e5a4c02596ac19a710ad8c1f75
milenacudak96/python_fundamentals
/labs/02_basic_datatypes/1_numbers/02_06_invest.py
500
4.15625
4
''' Take in the following three values from the user: - investment amount - interest rate in percentage - number of years to invest Print the future values to the console. ''' i_amount = float(input('Provide investment amount: ')) interest_rate = float(input('Provide interest rate in percentage: ')) years = float(input('Provide number of years to invest: ')) futureInvestmentValue = i_amount * (1 + interest_rate/100) ** years print('Feature value is: ' + str(futureInvestmentValue))
9b1e5f2ef83dbd9f65b85fc9b139012400b94ddc
tkaderr/python_fundamentals
/product.py
1,054
3.671875
4
class product(object): def __init__(self,price,item_name,weight,cost,brand): self.price=price self.item_name=item_name self.weight=weight self.cost=cost self.brand=brand self.status="For Sale" self.box="New" def sell(self): self.status="Sold" return self def add_tax(self): self.price=self.price+(self.price*0.12) return self def return_(self): if self.box=="Defective": self.status="Defective" self.price=0 elif self.box=="New": self.status="For Sale" elif self.box=="Opened": self.status="Used" self.price=self.price*0.8 return self def displayInfo(self): print "Price:",self.price print "ItemName:",self.item_name print "Weight:",self.weight print "Brand:",self.brand print "Status:",self.status print "Product Status:",self.box product1=product(6,"Cereal","5 lbs", "Kellogs",3) product1.displayInfo()
37bc2fa863d2fcc5b653482865aa9c10fba81dc8
michael-kaldawi/Prime-Number-Multiprocessing
/PipeTest.py
4,103
3.828125
4
__author__ = 'Michael Kaldawi' """ Programmer: Michael Kaldawi Class: CE 4348.501 Assignment: P01 (Program 1) Program Description: This program implements a prime number finder utilizing the sieve of Eratosthenes, multiprocessing, and communication via pipes. """ # Note: we are using numpy for our array processing to speed up # runtime. numpy needs to be installed/ imported for this # program to work. from multiprocessing import Process, Pipe import math import cProfile import numpy as np # This function finds primes between 'start' and 'end' indices. # The function returns a 1x(end-start) array of boolean values # indicating primes as 'True'. def find_primes(start, end, conn=None): # create an array of boolean True values, size: 1 x 'end' array = np.ones(shape=end, dtype=np.bool) # For each value 'i' in the True array, starting at 2, until the # square root of the end value, mark multiples of 'i' as False. # Hence, for i = 2, the values marked False would be {4, 6, 8, ...} for i in range(2, int(math.sqrt(end))): if array[i]: j = i**2 while j < end: array[j] = False j += i # If no connection is passed, return the array with a start value. if conn is None: return {'start': start, 'array': array[start:]} # If requested by the parent process, return the array with a start value. conn.send({'start': start, 'array': array[start:]}) conn.close() # This function prints the prime numbers marked by True in a # passed True/ False array. def print_primes(start, array): total = 0 pos = start for i in array: if i: print(pos, i) total += 1 pos += 1 # print(total) # a function to print the prime numbers marked by True in a # passed True/ False array into a file def write_primes(file_name, mode, start, array): f = open(file_name, mode) total = 0 pos = start for i in array: if i: f.write(pos.__str__() + "\n") total += 1 pos += 1 # f.write("total: " + total.__str__()) # Due to the nature of the profiling package cProfile, we require # an additional function to start the child process. def start_child(process): process.start() # This function calculates the prime numbers between # 2 and 1,000, then starts 10 child processes to complete # the calculation of prime numbers between 1,001 and 1,000,000. # The parent process requests for the calculated primes from # the child processes via Pipes. The child processes then # return the calculated primes via the pipes. def main(): # 'data' stores all boolean arrays. 'children' is an # array of child processes. data = [] children = [] # Find the primes between 2 and 1000. for i in find_primes(start=2, end=1000)['array']: data.append(i) # Make 10 pipes and 10 corresponding child processes. for process in range(0, 10): parent_conn, child_conn = Pipe() if process == 0: children.append(Process(target=find_primes, args=(1001, 100000, child_conn))) else: children.append(Process(target=find_primes, args=( process*100001, (process+1)*100000, child_conn))) # Start each child process. Profile the run time of each process. cProfile.runctx('start_child(children[process])', globals(), locals()) # Request each boolean array from the child processes, # and append the arrays to 'data'. for i in parent_conn.recv()['array']: data.append(i) children[process].join() # write the prime numbers to 'primes.txt' cProfile.runctx('write_primes(file_name="primes.txt", ' 'mode="w", start=2, array=data)', globals(), locals()) # This is our 'main' function. The first line of code # executed in this program is 'main()' # # This function executes main(). # Only the parent process can run this function. if __name__ == '__main__': main()
10571b55754d87c161a5d6a7859395d1a635250e
ADeeley/batch-file-updater
/file_updater.py
593
3.546875
4
from os import listdir from os.path import isfile, join mypath = "F:\\mystuff\\projects\\file_updater\\testfiles" files = [mypath + "\\" + f for f in listdir(mypath) if isfile(join(mypath, f))] # generates a list of file names def write_to_files(files): '''Pre: text must be string files must be list of strings ''' for file in files: with open(file, 'w') as f: with open("F:\\mystuff\\projects\\file_updater\\replacement_text.txt", "r") as text: for line in text.read(): f.write(line) write_to_files(files)
1f3fc3a27533c52ab0adc6e7b89fb13787c89bb7
hawkinsbl/04-TheAccumulatorPattern
/src/m4_more_summing_and_counting.py
15,176
4.28125
4
""" This module lets you practice the ACCUMULATOR pattern in several classic forms: SUMMING: total = total + number COUNTING: count = count + 1 AVERAGING: summing and counting combined and FACTORIAL: x = x * k Subsequent modules let you practice the ACCUMULATOR pattern in its "in graphics" form: IN GRAPHICS: x = x + pixels Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Aaron Wilkin, their colleagues, and Ben Hawkins. """ # Done: 1. PUT YOUR NAME IN THE ABOVE LINE. import math import builtins # Never necessary, but here for pedagogical reasons # ----------------------------------------------------------------------------- # Students: As you work each of these problems, ask yourself: # 1. Do I need a loop? # If so, HOW MANY LOOPS? # # 2. Where I need a loop, what needs to happen: # -- BEFORE the loop? # -- IN the loop? # -- AFTER the loop? # ----------------------------------------------------------------------------- def main(): """ Calls the TEST functions in this module. """ run_test_sum_from() run_test_factorial() run_test_count_cosines_from() run_test_sum_unit_fractions_from() # ----------------------------------------------------------------------------- # Students: READ the run_test_sum_from function that follows this comment. # ----------------------------------------------------------------------------- def run_test_sum_from(): """ Tests the sum_from function. """ print() print('--------------------------------------------------') print('Testing the sum_from function:') print('--------------------------------------------------') # ------------------------------------------------------------------------- # These first two tests use an ORACLE for testing, # that is, a way to get the answer by using some other approach # that is known to work correctly. # The oracle here is the builtins.sum function. # ------------------------------------------------------------------------- # Test 1: answer_from_oracle = builtins.sum(range(6, 10)) answer_from_my_code = sum_from(6, 9) print('Test 1 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # Test 2: answer_from_oracle = builtins.sum(range(100, 10001)) answer_from_my_code = sum_from(100, 10000) print('Test 2 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # ------------------------------------------------------------------------- # The next test uses a KNOWN answer (usually computed by hand). # (Everyone "knows" that the sum from 0 to 3 is 0+1+2+3, i.e. 6.) # ------------------------------------------------------------------------- # Test 3: answer_from_by_hand = 6 answer_from_my_code = sum_from(0, 3) print('Test 3 expected (from by-hand):', answer_from_by_hand) print(' actual (from my code): ', answer_from_my_code) # ------------------------------------------------------------------------- # The next test uses a FORMULA answer (which is one kind of ORACLE answer) # that uses the formula: # m + (m+1) + (m+2) + ... + n = (m + n) * (n - m + 1) / 2 # ------------------------------------------------------------------------- # Test 4: answer_from_formula = (53 + 4999) * (4999 - 53 + 1) // 2 answer_from_my_code = sum_from(53, 4999) print('Test 4 expected (from formula):', answer_from_formula) print(' actual (from my code): ', answer_from_my_code) # ----------------------------------------------------------------------------- # Done: 2. # When you have READ the above run_test_sum_from function, # asking questions as needed, and you feel that you (mostly, at least) # understand it, and you feel that you understand from the example: # -- what an ORACLE answer is # -- what a KNOWN (typically, BY-HAND) answer is # -- what a FORMULA answer is # -- how the above are used in testing # THEN: # CHANGE THE TO DO at the beginning of this comment to DONE. # There is no code to be written for this TO DO (just reading). # ----------------------------------------------------------------------------- def sum_from(m, n): """ What comes in: The arguments are two integers m and n, with m <= n. What goes out: Returns the sum of the integers from m to n, inclusive. Side effects: None. Example: sum_from(6, 9) returns 6 + 7 + 8 + 9, that is, 30. """ # ------------------------------------------------------------------------- # Done: 3. Implement and test this function. # Tests have been written for you (above). # # IMPORTANT: Your solution MUST # use an explicit for ... in range(...): statement # # IMPORTANT: As in previous problems in this session, # you must NOT use the 2 or 3-parameter versions # of the RANGE expression, if you happen to know them. # ------------------------------------------------------------------------- total = 0 for k in range(n-m+1): total = total + (k+m) return total def run_test_factorial(): """ Tests the factorial function. """ # ------------------------------------------------------------------------- # Done: 4. Implement this TEST function. # It TESTS the factorial function defined below. # Include at least ** 5 ** tests (we wrote two for you). # ########################################################################### # IMPORTANT: At least 2 of your tests MUST use the # math.factorial # function as an ORACLE for testing. See examples above. ########################################################################### # ------------------------------------------------------------------------- print() print('--------------------------------------------------') print('Testing the factorial function:') print('--------------------------------------------------') # Test 1: answer_from_oracle = math.factorial(0) answer_from_my_code = factorial(0) print('Test 1 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # Test 2: answer_from_oracle = math.factorial(21) answer_from_my_code = factorial(21) print('Test 2 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # ------------------------------------------------------------------------- # TO DO: 4 (continued). # Below this comment, add 3 more test cases, at least two of which # ** uses math.factorial as an ORACLE for testing. ** # ------------------------------------------------------------------------- # Test 3: answer_from_oracle = math.factorial(10) answer_from_my_code = factorial(10) print('Test 3 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # Test 4: answer_from_oracle = math.factorial(100) answer_from_my_code = factorial(100) print('Test 4 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) # Test 5: answer_from_oracle = math.factorial(3) answer_from_my_code = factorial(3) print('Test 5 expected (from oracle):', answer_from_oracle) print(' actual (from my code): ', answer_from_my_code) def factorial(n): """ What comes in: The sole argument is a non-negative integer n. What goes out: Returns n!, that is, n x (n-1) x (n-2) x ... x 1. Side effects: None. Examples: factorial(5) returns 5 x 4 x 3 x 2 x 1, that is, 120. factorial(0) returns 1 (by definition). """ # ------------------------------------------------------------------------- # Done: 5. Implement and test this function. # Note that you should write its TEST function first (above). # # IMPORTANT: Your solution MUST # use an explicit for ... in range(...): statement. # ------------------------------------------------------------------------- total = 1 for k in range(n): total = total*(k+1) return total def run_test_count_cosines_from(): """ Tests the count_cosines_from function. """ # ------------------------------------------------------------------------- # Done: 6. Implement this TEST function. # It TESTS the count_cosines_from function defined below. # Include at least ** 6 ** tests (we wrote one for you). # ** Yes, 6 (six) tests. ** # ** Counting problems are harder to test than summing. ** # # To implement this TEST function, use the same 4 steps as before: # # Step 1: Read the doc-string of count_cosines_from below. # Understand what that function SHOULD return. # # Step 2: Pick a test case: numbers that you could send as # actual arguments to the count_cosines_from function. # # Step 3: Figure out (by hand, or by using an oracle: a test case # that your instructor provided in the doc-string, or a # known formula or an alternative implementation that you trust) # the CORRECT (EXPECTED) answer for your test case. # # Step 4: Write code that prints both the EXPECTED answer # and the ACTUAL answer returned when you call the function. # Follow the same form as in the test case we provided below. # ------------------------------------------------------------------------- print() print('--------------------------------------------------') print('Testing the count_cosines_from function:') print('--------------------------------------------------') # Test 1: expected = 2 answer = count_cosines_from(3, 9, 0.29) print('Test 1 expected:', expected) print(' actual: ', answer) # ------------------------------------------------------------------------- # TO DO: 6 (continued). # Below this comment, add 5 more test cases of your own choosing. # ------------------------------------------------------------------------- # Test 2: expected = 10 answer = count_cosines_from(0, 9, -2) print('Test 2 expected:', expected) print(' actual: ', answer) # Test 3: expected = 0 answer = count_cosines_from(-5, 5, 1) print('Test 3 expected:', expected) print(' actual: ', answer) # Test 4: expected = 1 answer = count_cosines_from(1, 3, 0) print('Test 4 expected:', expected) print(' actual: ', answer) # Test 5: expected = 2 answer = count_cosines_from(3, 9, .5) print('Test 5 expected:', expected) print(' actual: ', answer) # Test 6: expected = 1 answer = count_cosines_from(10, 11, -.5) print('Test 6 expected:', expected) print(' actual: ', answer) def count_cosines_from(m, n, x): """ What comes in: The three arguments are non-negative integers m and n, with m <= n, and a number x. What goes out: Returns the number of integers from m to n, inclusive, whose cosine is greater than x. Side effects: None. Examples: Since: cosine(3) is about -0.99 cosine(4) is about -0.65 cosine(5) is about 0.28 cosine(6) is about 0.96 cosine(7) is about 0.75 cosine(8) is about -0.15 cosine(9) is about -0.91 -- count_cosines_from(3, 9, 0.29) returns 2 -- count_cosines_from(3, 9, 0.27) returns 3 -- count_cosines_from(4, 8, -0.5) returns 4 """ # ------------------------------------------------------------------------- # Done: 7. Implement and test this function. # Note that you should write its TEST function first (above). # # IMPORTANT: As in previous problems in this session, # you must NOT use the 2 or 3-parameter versions # of the RANGE expression, if you happen to know them. # ------------------------------------------------------------------------- total = 0 for k in range(n-m+1): if math.cos(k+m) > x: total = total+1 return total def run_test_sum_unit_fractions_from(): """ Tests the sum_unit_fractions_from function. """ # ------------------------------------------------------------------------- # Done: 8. Implement this TEST function. # It TESTS the sum_unit_fractions_from function defined below. # Include at least ** 3 ** tests (we wrote one for you). # Use the same 4-step process as for previous TEST functions. # ------------------------------------------------------------------------- print() print('--------------------------------------------------') print('Testing the sum_unit_fractions_from function:') print('--------------------------------------------------') # Test 1: expected = 0.545635 # This is APPROXIMATELY the correct answer. answer = sum_unit_fractions_from(6, 9) print('Test 1 expected:', expected, '(approximately)') print(' actual: ', answer) # ------------------------------------------------------------------------- # TO DO: 8 (continued). # Below this comment, add 2 more test cases of your own choosing. # ------------------------------------------------------------------------- # Test 2: expected = 1 answer = sum_unit_fractions_from(1, 1) print('Test 1 expected:', expected, '(approximately)') print(' actual: ', answer) # Test 3: expected = -1.283333 answer = sum_unit_fractions_from(-5, -2) print('Test 1 expected:', expected, '(approximately)') print(' actual: ', answer) def sum_unit_fractions_from(m, n): """ What comes in: Two positive integers m and n with m <= n. What goes out: Returns the sum: 1/m + 1/(m+1) + 1/(m+2) + ... + 1/n. Side effects: None. Examples: -- sum_unit_fractions_from(6, 9) returns 1/6 + 1/7 + 1/8 + 1/9 which is about 0.545635 -- sum_unit_fractions_from(10, 9000) returns about 6.853 """ # ------------------------------------------------------------------------- # Done: 9. Implement and test this function. # Note that you should write its TEST function first (above). # # IMPORTANT: As in previous problems in this session, # you must NOT use the 2 or 3-parameter versions # of the RANGE expression, if you happen to know them. # ------------------------------------------------------------------------- total = 0 for k in range(n-m+1): total = total + 1/(k+m) return total # ----------------------------------------------------------------------------- # Calls main to start the ball rolling. # ----------------------------------------------------------------------------- main()
3df67b34dd5e7677529c77330bae435e19f95b7d
persocom01/TestAnaconda
/pandas/12_pd_stat_functions_test.py
1,918
3.515625
4
import pandas as pd import seaborn as sb import matplotlib.pyplot as plt # Use this command if using Jupyter notebook to plot graphs inline. # %matplotlib inline import_path = r'.\datasets\drinks.csv' # Necessary in this case since 'NA'='North America' in this dataset. data = pd.read_csv(import_path, na_filter=False) df = pd.DataFrame(data[['beer_servings', 'spirit_servings', 'wine_servings']]) print(df.head()) print() # pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, **kwargs) # Doesn't actually return a percentage, but the number of times the previous # value had to be multiplied by to get the current value: (after - prev) / prev # Also why the first row is always nan. # I haven't figured out what periods actually does. Don't use it for now. print(df.head().pct_change()) print() # df.cov(self, min_periods=None) # The covariance is the non-normalized correlation between two variables. # It's probably not as useful as the correlation. print(df.cov()) print() # df.corr(self, method='pearson', min_periods=1) # Returns a correlation matrix, which is most useful as an input of # sb.heatmap() # method accepts 3 possible string arguments: # 'pearson': evaluates the linear relationship between two continuous variables. # 'kendall': evaluates if two variables are ordered in the same way. You will # probably seldom use this. # 'spearman': evaluates the monotonic relationship between two continuous or # ordinal variables. In other words, when evaluating things like a ranking # where the difference between ranks doesn't necessarily imply that they are # close together. fig, ax = plt.subplots(figsize=(12, 7.5)) plt.title('alcohol servings heatmap') # df.corr(self, method='pearson', min_periods=1) sb.heatmap(df.corr(), cmap='PiYG', annot=True) # Corrects the heatmap for later versions of matplotlib. bottom, top = ax.get_ylim() ax.set_ylim(bottom+0.5, top-0.5) plt.show()
d403e637e0eaeae86236f476a6a51ac70443fe82
IsaacDVM/main
/python/prueba.py
68
3.515625
4
pata = 0 pata += 1 print(pata) print("hello world","estúpido")
5eba8c2a989c0e8b4dbb40305b03bfd7f0cfa29f
filip-michalsky/Algorithms_and_Data_Structures
/Interview_problems_solutions/Tree_problems (BFS,DFS)/right_side_view_BST.py
1,140
3.625
4
class Solution: def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] O(n) time - each node visit only once O(n) space -dictionary stores the entire tree NOTE: it is possible to construct O(1) space if we keep track of the last elem visited in a level. If level changes, we know we are at the last element (the right most one) """ dict_list = self.get_list_depths(node=root,dict_levels = {},level = 0) result = [] for level in sorted(dict_list): result.append(max(dict_list[level])) return result def get_list_depths(self,node,dict_levels = {},level = 0): if node.val == None: return if level not in dict_levels: dict_levels[level] = [node.val] else: dict_levels[level].append(node.val) if node.left: self.get_list_depths(node=node.left,dict_levels=dict_levels,level = level+1) if node.right: self.get_list_depths(node=node.right,dict_levels=dict_levels,level=level+1) return get_list_depths
0be0ee08b0e356b25bd97a163eefae420de23902
calpa/Algorithm
/LeetCode/389_Find_the_Difference.py
376
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __author__ = 'calpa' __mtime__ = '2/11/2016' """ def find_the_difference(s, t): # Create an empty set first char_set = set() for char in set(t): if char in char_set: continue # Difference: if s.count(char) != t.count(char): return char char_set.add(char)
599876a7515625abb250cf60bdf8e108b854661c
adee-dev/Demo_Repo_1
/Datatypes.py
641
3.96875
4
#Datatypes By xyz '''var='Hello World' print(var) var='Hi Guys' print(var) name='John' print('hello', name, 'How are you?') print(name.upper()) print(name.lower()) print(name.title()) ''' #Famous_Quote='''Albert Einstein once said, “A person who never made a #mistake never tried anything new.”''' #print(Famous_Quote) ''' person1='\tJohan\nPaul\nMorphy\n' person2=' asakd ajfdk jhskskhs' print(person1) print(person1.lstrip()) print(person1.rstrip()) print(person1.strip()) print(person2.strip()) print(5+3) print(10-2) print(4*2) print((16/2)) print(2**3)''' import this 1 2 3 4 5 6 7 8 9 0
03592e4b2187ad637a552a2c747e4d7932fbdf64
JacobOrner/USAFA
/CS_210 (Introduction to Programming)/Labs/Lab32_Objects.py
11,903
4.15625
4
"""CS 210, Introduction to Programming, Fall 2015, _YOUR_NAME_HERE_. Instructor: Dr. Bower / Col Gibson / LtCol Harder / LtCol (Ret) Christman Documentation: None required; cooperation on labs is highly encouraged! ======================================================================= """ def main(): """Main program to test solutions for each exercise.""" # Print the docstring at the top of the file so your instructor can see your name. print( __doc__ ) one_half = Fraction( 1, 2 ) one_third = Fraction( 1, 3 ) one_fourth = Fraction( 1, 7 ) result = one_half == one_third print( "{} == {} = {}".format( one_half, one_third, result ) ) result = one_third == one_third print( "{} == {} = {}".format( one_third, one_third, result ) ) print() f = Fraction( 1, 2 ) g = Fraction( 1, 3 ) print( "{} += {} = ".format( f, g ), end="" ) f //= ( g ) print( "{} ... note {} did not change.".format( f, g ) ) class Fraction: """Class for representing a fraction with integer values for numerator and denominator.""" def __init__( self, n=0, d=1 ): """Create a new Fraction with the given values. :param int n: The numerator. :param int d: The denominator. """ self.n = n self.d = d def __str__( self ): """Build and return a string representation of the object. :return: A string representation of this Raindrop in the format "(x,y):r". :rtype: str """ return "{}/{}".format( self.n, self.d ) def __add__( self, other ): """Adds two Fraction objects, building and returning a new Fraction object. Note: This method does NOT modify the self or other Fraction objects. Note: This method ensures the result Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ n1 = self.n * other.d n2 = self.d * other.n d = self.d * other.d result = Fraction( n1 + n2, d ) result.simplify() return result def __iadd__( self, other ): """Adds two Fraction objects, modifying the self Fraction object. Note: This method does NOT modify the other Fraction object. Note: This method ensures the Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ self.n *= other.d self.n += self.d * other.n self.d *= other.d self.simplify() return self def __sub__( self, other ): """Subtracts two Fraction objects, building and returning a new Fraction object. Note: This method does NOT modify the self or other Fraction objects. Note: This method ensures the result Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ n1 = self.n * other.d n2 = self.d * other.n d = self.d * other.d result = Fraction( n1 - n2, d ) result.simplify() return result def __isub__( self, other ): """Subtracts two Fraction objects, modifying the self Fraction object. Note: This method does NOT modify the other Fraction object. Note: This method ensures the Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ self.n *= other.d self.n -= self.d * other.n self.d *= other.d self.simplify() return self def __mul__( self, other ): """Multiplies two Fraction objects, building and returning a new Fraction object. Note: This method does NOT modify the self or other Fraction objects. Note: This method ensures the result Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be multiplied by this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ n1 = self.n * other.n # n2 = self.d * other.n # d = self.d * other.d result = Fraction( n1, self.d * other.d ) result.simplify() return result def __imul__( self, other ): """Multiplies two Fraction objects, modifying the self Fraction object. Note: This method does NOT modify the other Fraction object. Note: This method ensures the Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ self.n *= other.n self.d *= other.d self.simplify() return self def __truediv__( self, other ): """Divides two Fraction objects, building and returning a new Fraction object. Note: This method does NOT modify the self or other Fraction objects. Note: This method ensures the result Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be multiplied by this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ n1 = self.n * other.d n2 = self.d * other.n # d = self.d * other.d result = Fraction( n1, n2 ) result.simplify() return result def __itruediv__(self, other): """Divides two Fraction objects, modifying the self Fraction object. Note: This method does NOT modify the other Fraction object. Note: This method ensures the Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ self.n *= other.d self.d *= other.n self.simplify() return self def __floordiv__( self, other ): """Divides two Fraction objects, building and returning a new Fraction object. Note: This method does NOT modify the self or other Fraction objects. Note: This method ensures the result Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be multiplied by this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ n1 = self.n * other.d n2 = self.d * other.n # d = self.d * other.d result = Fraction( n1 // n2, 1 ) result.simplify() return result def __ifloordiv__(self, other): """Divides two Fraction objects, modifying the self Fraction object. Note: This method does NOT modify the other Fraction object. Note: This method ensures the Fraction object is in lowest terms. :param Fraction other: The other Fraction object to be added to this Fraction object. :return: A new Fraction object equal to the sum of the self and other Fraction objects. :rtype: Fraction """ self.n *= other.d self.d *= other.n self.n //= self.d self.d = 1 self.simplify() return self def __eq__(self, other): """Test the equality of two fraction objects :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d == other.n * self.d: return True else: return False def __ne__(self, other): """Test the inequality of two fraction objects. :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d != other.n * self.d: return True else: return False def __lt__(self, other): """Test the less than operator of two fraction objects. :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d < other.n * self.d: return True else: return False def __le__(self, other): """Test the less than or equal operator of two fraction objects. :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d <= other.n * self.d: return True else: return False def __gt__(self, other): """Test the greater than operator of two fraction objects. :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d > other.n * self.d: return True else: return False def __ge__(self, other): """Test the greater than or equaloperator of two fraction objects. :param Fraction other: The other fraction object to be equality checked to this Fraction object. :return: A true or false statement of equality. :rtype: Boolean """ if self.n * other.d >= other.n * self.d: return True else: return False def __int__(self): """Return the int of the fraction object. :return: An integer of the fraction. :rtype: int """ return int(self.n / self.d) def __float__(self): """Return the float of the fraction object. :return: A float of the fraction. :rtype: float """ return float(self.n / self.d) def __neg__(self): return -Fraction(self.n, self.d) def simplify( self ): """Simplifies this Fraction object such that it is in lowest terms.""" # Find the greatest common divisor of this Fraction object's numerator and denominator. divisor = gcd( self.n, self.d ) # Simplify this Fraction object's numerator and denominator. self.n //= divisor self.d //= divisor def gcd( a, b ): """Uses division-based version of Euclid's algorithm to calculate the greatest common divisor of two integers. https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations :param int a: An integer. :param int b: An integer. :return: The greatest common divisor of a and b. :rtype: int """ while b != 0: temp = b b = a % b a = temp return a # The following two lines are always the last lines in a source file and they # start the execution of the program; everything above was just definitions. if __name__ == "__main__": main()
c5d7dd44f402c052625bd949c8ec6ad98af22f5c
roman-kachanovsky/checkio-python
/solutions/scientific_expedition/the_best_number_ever.py
1,262
4.34375
4
""" --- The best number ever --- Elementary It was Sheldon's version and his best number. But you have the coding skills to prove that there is a better number, or prove Sheldon sheldon right. You can return any number, but use the code to prove your number is the best! This mission is pretty simple to solve. You are given a function called "checkio" which will return any number (integer or float). Let's write an essay in python code which will explain why is your number is the best. Publishing the default solution will only earn you 0 points as the goal is to earn points through votes for your code essay. Input: Nothing. Output: A number as an integer or a float or a complex. How it is used: This mission revolves around code and math literacy. """ def my_solution(n): def pi(precision): """Get pi constant with the Bailey-Borwein-Plouffe formula""" from decimal import Decimal, getcontext getcontext().prec = precision return sum(1 / Decimal(16) ** k * ( Decimal(4) / (8 * k + 1) - Decimal(2) / (8 * k + 4) - Decimal(1) / (8 * k + 5) - Decimal(1) / (8 * k + 6)) for k in xrange(precision)) return pi(n)
bac2334a0bb43eedb8e35410b5758034965cd1af
victorsnms/reclip
/resizeclip.py
7,455
4.03125
4
#test commit #import tkinter as tk #import library of gui #window = tk.Tk() #creating window object #intro = tk.Label(text="Welcome!") #creating label #intro.pack() #incorporando os elementos #widgets: Label, Button, Entry, Text, Frame #entry widgets: get(), delete(), insert() ex:name = entry.get() #get() in texts need parameters: The line number of a character and The position of a character on that line. ex: text_box.get("1.0", "1.5") #insert()/delete() receives an intenteger character which will be inserted/deleted. ex: entry.insert(0, "Python") / entry.delete(0, tk.END) #parameters: text,foreground / fg,background / bg, width, height #colors HTML, hexdec RGB #width and height are measured in text unit (not pixels) #window.mainloop() This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until the window it’s called on is closed. #window.destroy() to destroy the window #border_effects: relief = {tk.FLAT, tk.SUNKEN, tk.RAISED, tk.GROOVE, tk.RIDGE} #frame.pack(side=tk.LEFT): da pack à esquerda #geometry managers: .pack(), .place(), .grid() #When no anchor point is specified when .pack() is called for each Frame, they’re all centered inside of their parcels. That’s why each Frame is centered in the window. #arguments of pack(): fill=tk.X / fill=tk.Y / fill=tk.BOTH (fills the parcel) #arguments of pack(): side=tk.LEFT / side=tk.BOTTOM / side=tk.RIGHT / side=tk.TOP #grid(): frame.grid(row=i, column=j, padx=5, pady=5) #setting minsize: window.columnconfigure(0, minsize=50) #setting minsize: window.rowconfigure([0, 1], minsize=50) #sticky parameter:sticky="n"/"s"/"e"/"w" (north,south, east, west)... ne/new/se/sw ... ns/ew(vertical/horizontal) ... nsew (fill) #.bind(a,b): a:"<event_name>"(Tkinter’s events), b:An event handler(function) #Events: "<Button-1>" = left mouse click on button / "<Button-2>" = middle click / "<Button-3>" = right click #get text from label: label = Tk.Label(text="Hello") / text = label["text"] / label["text"] = "Good bye" #function increase: def increase(): / value = int(lbl_value["text"]) / lbl_value["text"] = f"{value + 1}" import os import datetime import tkinter as tk from PIL import Image #image manip from PIL import ImageGrab #image manip from pynput import keyboard #hotkeys from pynput.keyboard import HotKey, Key, KeyCode, Listener from tkinter import * dir_path = "C:\\Users\\josivania\\Desktop\\Python\\Project Reclip" #Setting window and tk variables window = tk.Tk() window.title('Reclip v0.5') #Title saveOrOpen = tk.IntVar() #variable for radio button ddoption = tk.StringVar() #variable for drop down menu ddoption.set("BMP") #default value #Frame 1 w/ label and entry (create and load) frm1 = tk.Frame(height=2, width=100, bg="black") lbl1 = tk.Label(text="Width", master=frm1, width=12) #colocando a label dentro do master: frame ent1 = tk.Entry(fg="white", bg="grey", width=10, master=frm1) frm1.grid(row=1, column=1, padx=5, pady=5) lbl1.grid(row=0,column=0) ent1.grid(row=0,column=1) #Frame 2 w/ label and entry (create and load) frm2 = tk.Frame(height=2, width=100, bg="black") lbl2 = tk.Label(text="Height", master=frm2, width=12) ent2 = tk.Entry(fg="white", bg="grey", width=10, master=frm2) frm2.grid(row=2, column=1, padx=5, pady=5) lbl2.grid(row=0,column=0) ent2.grid(row=0,column=1) #Frame 3 w/ label and entry (create and load) frm3 = tk.Frame(height=2, width=100, bg="black") lbl3 = tk.Label(text="Directory", master=frm3, width=12) ent3 = tk.Entry(fg="white", bg="grey", width=10, master=frm3) frm3.grid(row=3, column=1, padx=5, pady=5) lbl3.grid(row=0,column=0) ent3.grid(row=0,column=1) #Frame 4 w/ label and entry (create and load) frm4 = tk.Frame(height=2, width=100, bg="black") lbl4 = tk.Label(text="Hotkey", master=frm4, width=12) ent4 = tk.Entry(fg="white", bg="grey", width=10, master=frm4) frm4.grid(row=4, column=1, padx=5, pady=5) lbl4.grid(row=0,column=0) ent4.grid(row=0,column=1) #Frame 5 w/ label (create and load) frm5 = tk.Frame(height=2, width=100) lbl5 = tk.Label(text="Save or open:", master=frm5, width=12) frm5.grid(row=1, column=2, padx=5, pady=5, sticky="W") lbl5.grid(row=0,column=0) #Radios to "save" or "open" btn_save = tk.Radiobutton( text="Save", variable=saveOrOpen, #important: saveOrOpen = tk.IntVar() after window = tk.Tk() value=1, master=frm5) btn_save.grid(row=1, column=0, padx=2, pady=2) btn_open = tk.Radiobutton( text="Open", variable=saveOrOpen, value=2, master=frm5) btn_open.grid(row=1, column=1, padx=2, pady=2) #Frame 6 w/ label (create and load) frm6 = tk.Frame(height=2, width=100) lbl6 = tk.Label(text="Image format:", master=frm6, width=12) frm6.grid(row=2, column=2, padx=0, pady=0, sticky="W") lbl6.grid(row=0,column=0) #Dropdown menu for frame 6 ddmenu = OptionMenu(frm6, ddoption, "BMP","PNG","JPEG") ddmenu.grid(row=1, column=1 , padx=2, pady=2) #button_go function def clip_it(): imgclip = ImageGrab.grabclipboard() model_width = int(ent1.get()) model_height = int(ent2.get()) output_coords = (imgclip.size[0]/2 - (model_width/2),imgclip.size[1]/2 - model_height/2,imgclip.size[0]/2 + model_width/2, imgclip.size[1]/2 + model_height/2) output = imgclip.crop(output_coords) choice = int(saveOrOpen.get()) image_format = str(ddoption.get()) if image_format == "JPEG": output = output.convert('RGB') if choice == 1: timenow = str(datetime.datetime.now()).replace(":","-")[0:19] image_name = ("%s" %timenow) + "." + ("%s" %image_format) file_path = os.path.join( dir_path, image_name) #join paths*** output.save(file_path, "%s" %image_format) print(output.size, image_name, " saved in ", file_path) print(image_format) print(choice) if choice == 2: output.show() print(output.size, " showed") print(image_format) print(choice) #Button to confirm parameters (create and load) btn_go = tk.Button( text="Go!", width=5, height=2, bg="grey", fg="white", command=clip_it ) btn_go.grid(row=5, column=1, padx=5, pady=5) #function to convert user hotkey input model_hotkey = "<ctrl>+o" def function_1(): print('Function 1 activated') def function_2(): print('Function 2 activated') def save_hotkey(): model_hotkey = str(ent4.get()).replace("^","<ctrl>+").replace("~","<shift>+").replace("!","<alt>+").replace("#","<win>+") print(model_hotkey+' setted as hotkey') with keyboard.GlobalHotKeys({ '%s' %model_hotkey: clip_it, '<alt>+<ctrl>+t': function_1, '<alt>+<ctrl>+y': function_2}) as h: h.join() #Button to confirm hotkey btn_sethotkey = tk.Button( text="Set", width=5, height=2, bg="grey", fg="white", command=save_hotkey ) btn_sethotkey.grid(row=5, column=2, padx=5, pady=5) #Text area for showing output (creat and load) txt1 = tk.Text(width=10, height=5) txt1.grid(row=5, column=3, padx=5, pady=5) """ #event def button_pressed(event): #Print the character associated to the key pressed print("button was pressed") # Bind keypress event to handle_keypress() window.bind("<Button-1>", button_pressed) """ #Creating variables to store user iputs #model_width = int(ent1.get()) #model_heigth = int(ent2.get()) #model_directory = ent3.get() #model_hotkey = ent4.get() window.mainloop()
0c1ee09363c998143d6bc8cba73dfe3b119a04af
Kaue-Romero/Python_Repository
/Exercícios/exerc_27.py
198
3.890625
4
nome = str(input('Qual é o seu nome? ')).strip() primeiro_nome = nome.split() print('Primeiro nome {}'.format(primeiro_nome[0])) print('Ultimo nome {}'.format(primeiro_nome[len(primeiro_nome)-1]))
a999fda705b946a95fc7afa0b2ba7ddd72fb0bea
masonwang96/LeetCode
/0167两数之和(2)输入有序数组/solution1.py
460
3.609375
4
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ dic = {} for index, num in enumerate(numbers): if num in dic: return [dic[num] + 1, index + 1] dic[target - num] = index if __name__ == "__main__": numbers = [2, 7, 11, 15] target = 9 print(Solution().twoSum(numbers, target))
b188e006d6738a1879271eff42bfbdc9a2331172
Rushi21-kesh/30DayOfPython
/Day-9/Day9-by-ShubbhRMewada.py
273
3.796875
4
def begineer(n): return n%10 def advance(n): if len(str(n))%2==0: return -1 return (int(n/(10**(len(str(n))//2))))%10 n=int(input("Enter a Number: ")) print(f'The last digit of {n} is',begineer(n)) print(f'The Middle digit of {n} is',advance(n))
b39ab9f30ca7dd5438155d7d564348525600a314
DrewDaddio/Automate-Python
/saveFiles.py
1,613
4.5
4
# Reading and Writing Plain Text Files print("""Steps to reading and writing text files in Python: Open 1. open() function: open's the file helloFile = open('<file name.txt>') helloFile.read() helloFile.close() Read 2. readlines() method: returns all of the lines as strings inside of a list. helloFile = open('<file name.txt>') helloFile.readlines() helloFile.close() Write mode 1. helloFile = open('<file name.txt>', 'w') # the w will turn the function into write mode. Write mode will overwrite items in the text file. helloFile.read() helloFile.close() Append mode 1. helloFile = open('<file name.txt>', 'a') # the w will turn the function into append mode. Append mode will add on to the file. helloFile.read() helloFile.close() For both the write & append mode then it will automatically create the file. helloFile.write(<text input>) helloFile.close() Relative filepath: If you don't put a directory in write mode then it will use the current working directory Shelve Module Used to save variables (list, dictionaries, complex data files) into the python program to binary shelf files using the shelve module. Then in the future you can call back to shelved data in order to use the it. They are stored as .bak, .dat, .dir file types. The files are binary files so they cannot be read in notepad. import shelve shelfFile = shelve.open('mydata') shelfFile['cats'] = ['zophie, 'Pooka', 'Simon', 'Fat-tail', 'Cleo] shelfFile.close() Keys Method shelfFile = shelve.open('mydata') shelfFile.keys .ist(shelfFile.keys()) list(shelfFile.values()) """)
b3d8d27086127b83b98f8a89f0c0ecb702681dae
n158/experimental-python3
/prime_fastest.py
1,223
3.796875
4
# -*- coding: UTF-8 -*- from itertools import compress import numpy as np def rwh_primes1v1(n): """ Returns a list of primes < n for n > 2 """ sieve = bytearray([True]) * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2::i] = bytearray((n - i * i - 1) // (2 * i) + 1) return [2, *compress(range(3, n, 2), sieve[1:])] def primesfrom2to(n): # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = np.ones(n // 3 + (n % 6 == 2), dtype=np.bool) sieve[0] = False for i in range(int(n ** 0.5) // 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) // 3)::2 * k] = False sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = False a = np.r_[2, 3, ((3 * np.nonzero(sieve)[0] + 1) | 1)] return a # Prime numbers from 0 to N N = 1000 N0 = 1000000 N1 = 1000000000 # n1 = rwh_primes1v1(N) n = primesfrom2to(N) n0 = primesfrom2to(N0) n0_ = str(len(n0)) n1 = primesfrom2to(N1) n1_ = str(len(n1)) # assert len(n1) == len(n2) n_ = str(len(n)) print(n1_, n0_, n_)
204de2c376ae0b8c1d2b0f943722d271a9290e50
TT0101/nyc-zcta-data-helpers
/ZipToZCTA/FileHelper.py
3,123
3.515625
4
# -*- coding: utf-8 -*- """ @author: Theresa Thomaier """ import csv import re import pandas as pd #file reader def readInCSVDicData(fileName, processFunction): fileReader = None data = [] try: with open(fileName) as fileReader: fileList = csv.DictReader(fileReader) data = processFunction(fileList) except IOError as e: print("Cound not read in the file at " + fileName + ". Error is: " + str(e)) except AttributeError as e2: print("There was an error: " + str(e2)) except TypeError as e3: print("There was an error: " + str(e3)) except: print("There is a unspecified error.") finally: if fileReader != None: fileReader.close() return data def readInCSVData(fileName, processFunction): fileReader = None data = [] try: with open(fileName) as fileReader: fileList = csv.reader(fileReader) data = processFunction(fileList) except IOError as e: print("Cound not read in the file at " + fileName + ". Error is: " + str(e)) except AttributeError as e2: print("There was an error: " + str(e2)) except TypeError as e3: print("There was an error: " + str(e3)) except: print("There is a unspecified error.") finally: if fileReader != None: fileReader.close() return data def readInCSVPandas(fileName, index):#, processFunction): try: if index > -1: pData = pd.read_csv(fileName, index_col=index) else: pData = pd.read_csv(fileName) #pDataClean = processFunction(pData) except IOError as e: print("Cound not read in the file at " + fileName + ". Error is: " + str(e)) except AttributeError as e2: print("There was an error: " + str(e2)) except TypeError as e3: print("There was an error: " + str(e3)) except: print("There is a unspecified error.") return pData def writeOutCSVPandas(fileName, data): try: data.to_csv(fileName) except IOError as e: print("Cound not read in the file at " + fileName + ". Error is: " + str(e)) except AttributeError as e2: print("There was an error: " + str(e2)) except TypeError as e3: print("There was an error: " + str(e3)) except: print("There is a unspecified error.") #user input parsing def parseToCSVFileName(userInput): fullreg = re.compile('^\w+.csv?$') csvReg = re.compile('.csv?$') cleanerInput = userInput.strip() #if it matches a valid .csv file already, return it if re.match(fullreg, cleanerInput): return cleanerInput #if there is a different extention on the file than .csv, kick it out if "." in cleanerInput and not re.match(csvReg): return "N" #if there's no extention on it, add the .csv extention and return return cleanerInput + ".csv"
12a69cff545d5a6029342300ebd772cc28ce745a
navyasree1011/CRT-BATCH
/#3.py
4,648
4.3125
4
#!/usr/bin/env python # coding: utf-8 # # every variable in python is acts like object and object has 3 characteristics # # identity # # type # #value # In[1]: a=10 print(id(a)) print(type(a)) print(a) # In[2]: b=10 b # In[3]: print(id(b)) # In[5]: a=10 b=24.5 c="gitam" d=2+4j print(a,b,c,d) print(type(a),type(b),type(c),type(d)) # # number types # ## integer # ## float # ## complex # ## blooean # ## all numbers are immutable,values are not # ## modified,if they modified new reference is # ## pointing to modified value # In[6]: a=10 print(id(a)) a=100 print(id(a)) # In[7]: a='t' print(id(a)) # In[10]: a=2+5j print(a) print(a.real) print(a.imag) print(a.conjugate()) c=complex(3,4) print(c) # In[12]: c=2+5j d=5+7j print(c+d) print(c-d) print(c*d) # In[14]: str="gitam" str1='gitam' print(str) print(str1) print(type(str),type(str1)) print(len(str)) # # type convertions # ## int() # ## float() # ## complex() # ## list() # ## tuple() # ## set() # ## dict() # ## bool() # # input() # ## it is used to give the input to the program # ## and its return type is string and by # ## using type convertions to convert it into # ## other types # In[15]: a=input("enter the number") print(type(a)) b=int(a) print(type(b)) # In[16]: # comments in the python ''' document srting ''' # In[17]: ''' print("its given the description about resource of python") ''' # In[19]: b="1947" print(type(b)) print(len(b)) c=int(b) print(type(c)) #print(len(c)) # In[22]: a=int(input("enter the first number")) b=int(input("enter the second number")) c=a+b print("the sum id",c) # # types of operators: # ## 1)arthmetic operators # ### +,-,*,/(decimal quetient),//(integer quetient),**,% # ### //(floor division) # ### %(remainder) # ### **(acts like pow),where arguments are integers # a=12 # b=5 # print(a+b) # print(a-b) # print(a*b) # print(a/b)# division with decimal # print(a//b)# floor dividion # print(a%b)#remainder # print(a**b)#pow(a,b) # ## relational operators: # ### <,<=,>,>=,==,!= # In[25]: x=10 y=34 print(x<34) print(x==y) print(x!=y) print(int(x>y)) print(int(y>x)) # # logical operators: # ## and or not # In[26]: x=20 print(x>20 and x<30) print(x>=30 or x<=20) print(not(x)) # # membership operators: # ## in,not in # In[28]: str1="gitam" print('i' in str1) print('z' not in str1) # # identity operators: # ## is,isnot # In[29]: a=45 b=89 print(a is b) print(a is not b) # # bitwise ops:(work with 0 and 1) # ## &,|,<<,>>,~ # ## <<leftshift # ## >>rightshift # ## ~(1's complement) # # special ops: # ## + and , are used for concatenation # ## * repetation operator # ## [start:stop:step] slice operator # ## range(start,stop,step) # ## indentation: # ## it represents block or{} in c # In[30]: a=100 print("the value of a is",a) c=[1,2,3] d=[4,5,6] print(c+d) d="gitam" print(d*3) print(d[1:3]) print(list(range(1,10,2))) # # control sattements # ## 1) simple if statement # ### if(condition): # statement1 # statement2 # # In[31]: a=int(input("enter the number")) if(a>0): print("it is +ve no") if(a<0): print("it is -ve no") if(a==0): print("it is zero") # ## control statements: # ## 1) if-else statement # ### if (condition): # statement1 # statement2 # ### else: # statement1 # statement2 # In[32]: n=int(input("enter the number")) if(n%2==0): print(n,"is even number") else: print(n,"is odd number") # In[39]: yr=int(input("enter the year")) if((yr%100!=0 and yr%4==0) or yr%400==0): print(yr,"is leap year") else: print(yr,"is not leap year") # ## control satements: # ## 3) elseif statement # ### if(condition): # satement1 # statement2 # ### elseif(condition): # statement3 # statement4 # ### else: # statement5 # statement6 # In[41]: a=10 b=200 c=100 if(a>b and a>c): print(a,"is big") elif(b>c): print(b,"is big") else: print(c,"big") # In[42]: a=10 b=20 print("before swapoing",a,b) a,b=b,a print("after swapping",a,b) # In[46]: a=100 b=25 ch=int(input("enter the choice")) if(ch==1): print("the addition is",a+b) elif(ch==2): print("the subtraction is",a+b) elif(ch==3): print("the multiplation is",a*b) elif(ch==4): print("the division is",a/b) else: print("choose the choice from[1-4] only") # In[48]: ch=input("enter the charactor") if(ch=='a' or ch=='e' or ch=='i'or ch=='o' or ch=='u'): print("it is vowel") elif(ch=='A' or ch=='E' or ch=="I" or ch=='O' or ch=='U'): print("it is vowel") else: print("it is consonant") # In[ ]:
ae4547023682a6f202bf1f01f1dea097c0cd7a1b
ishaansharma/blind-75-python
/tests/test_problem26.py
651
3.859375
4
import unittest from problems.problem26 import solution, TreeNode class Test(unittest.TestCase): def test(self): root1 = TreeNode(1) root1.left = TreeNode(2) root1.right = TreeNode(3) root2 = TreeNode(1) root2.left = TreeNode(2) root2.right = TreeNode(3) self.assertTrue(solution(root1, root2)) root1 = TreeNode(1) root1.left = TreeNode(2) root2 = TreeNode(1) root2.right = TreeNode(2) self.assertFalse(solution(root1, root2)) root1 = TreeNode(1) root1.left = TreeNode(2) root1.right = TreeNode(1) root2 = TreeNode(1) root2.left = TreeNode(1) root2.right = TreeNode(2) self.assertFalse(solution(root1, root2))
481b01a7035876cb2d86ef94149201ebaeb057a5
saviobobick/luminarsavio
/flowcontrols/import_modules/functions.py
153
3.625
4
#def add(num1,num2): # res=num1+num2 # print(res) #add(50,60) #add(50,65) #add(55,65) def cube(num): res=num*num*num print(res) cube(10)
d66a1a984d593e61a291a5ac090c3413d29662a2
Shoyee/learngit
/time_calendar_model01.py
1,294
3.515625
4
#!/usr/bin/env python3 #coding:utf-8 ''' import time local_time = time.localtime() print(local_time) print(type(local_time)) gm_time = time.gmtime() print(gm_time) print(type(gm_time)) asc_time = time.asctime() print(asc_time) print(type(asc_time)) c_time = time.ctime() print(c_time) print(type(c_time)) strf_time = time.strftime("%Y-%m-%d %H:%M:%S",local_time) print(strf_time) print(type(strf_time)) strp_time = time.strptime(strf_time,"%Y-%m-%d %H:%M:%S") print(strp_time) print(type(strp_time)) mk_time = time.mktime(local_time) print(mk_time) print(type(mk_time)) ''' ''' #time.sleep(秒)--->可以使程序暂停指定的秒数,然后继续执行下面的程序 print("倒计时10s开始计时:") sleep = time.sleep(1) print("10s") sleep = time.sleep(1) print("09s") sleep = time.sleep(1) print("08s") sleep = time.sleep(1) print("07s") sleep = time.sleep(1) print("06s") sleep = time.sleep(1) print("05s") sleep = time.sleep(1) print("04s") sleep = time.sleep(1) print("03s") sleep = time.sleep(1) print("02s") sleep = time.sleep(1) print("00s") sleep = time.sleep(1) print("发射!") ''' import time print("倒计时开始:") for i in range(10,-1,-1): time.sleep(1) print(i,"s") print("发射!")
9bccb8126f896060b32f6d569e9e61b9f60c5fd3
KonstantinosNakas/ProjectEuler-Python-Solutions
/27.py
467
3.5625
4
def isPrime(a): i = 2; if (a<2): return False; while (a%i != 0): i = i + 1; if (i == a): return True; else: return False; max_num_of_cons = 0; max_a = 0; max_b = 0; for a in range(-1000,1000): for b in range(-1000,1000): n = 0; num_of_cons = 0; while (isPrime(n*n+a*n+b)): num_of_cons = num_of_cons + 1; n = n + 1; if (num_of_cons > max_num_of_cons): max_num_of_cons = num_of_cons; max_a = a; max_b = b; print(max_a * max_b);
d636fe313bbd8b836447b5955f5c4f487ed94dd3
akhandsingh17/assignments
/boilerplates/Facebook/nlargestElement.py
409
4.28125
4
# Given a ´dictionary, print the key for nth highest value present in the dict. # If there are more than 1 record present for nth highest value then sort the key and # print the first one. input = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 3, 'f': 4, 'g': 5} def nHighestVal(input, k): input = sorted(input.items(), key=lambda x: x[1], reverse=True) return input[k - 1] print(nHighestVal(input, 3))
85b1400b0b1fed1291476a35529e569857049603
algorithmic-dynamics-lab/pybdm
/bdm/encoding.py
6,217
4
4
"""Encoding and decoding of arrays with fixed number of unique symbols. While computing BDM dataset parts have to be encoded into simple hashable objects such as strings or integers for efficient lookup of CTM values from reference datasets. In case of CTM dataset containing objects with several different dimensionalities string keys have to be used and this representation is used by :py:mod:`bdm.stages` functions at the moment. Integer encoding can be used for easy generation of objects of fixed dimensionality as each such object using a fixed, finite alphabet of symbols can be uniquely mapped to an integer code. """ from collections import deque import numpy as np def array_from_string(x, shape=None, cast_to=int, sep='-'): """Make array from string code. Parameters ---------- x : str String code. shape : tuple or None Desired shape of the output array. Determined automatically based on `x` is ``None``. cast_to : type or None Cast array to given type. No casting if ``None``. Defaults to integer type. sep : str Sequence separator. Returns ------- array_like Array encoded in the string code. Examples -------- >>> array_from_string('1010') array([1, 0, 1, 0]) >>> array_from_string('10-00') array([[1, 0], [0, 0]]) """ if sep in x: arr = [ list(s) for s in x.split(sep) ] else: arr = list(x) arr = np.array(arr) if arr.ndim == 0: arr = arr.reshape((1, )) if cast_to: arr = arr.astype(cast_to) if shape is not None: arr = arr.reshape(shape) return arr def string_from_array(arr): """Encode an array as a string code. Parameters ---------- arr : (N, k) array_like *Numpy* array. Returns ------- str String code of an array. Examples -------- >>> string_from_array(np.array([1, 0, 0])) '100' >>> string_from_array(np.array([[1,0], [3,4]])) '1034' """ x = np.apply_along_axis(''.join, arr.ndim - 1, arr.astype(str)) x = ''.join(np.ravel(x)) return x def encode_sequence(seq, base=2): """Encode sequence of integer-symbols. Parameters ---------- seq : (N, ) array_like Sequence of integer symbols represented as 1D *Numpy* array. base : int Encoding base. Should be equal to the number of unique symbols in the alphabet. Returns ------- int Integer code of a sequence. Raises ------ AttributeError If `seq` is not 1D. TypeError If `seq` is not of integer type. ValueError If `seq` contain values which are negative or beyond the size of the alphabet (encoding base). Examples -------- >>> encode_sequence(np.array([1, 0, 0])) 4 """ if seq.size == 0: return 0 if seq.ndim != 1: raise AttributeError("'seq' has to be a 1D array") if seq.dtype != np.int: raise TypeError("'seq' has to be of integer dtype") if not (seq >= 0).all(): raise ValueError("'seq' has to consist of non-negative integers") proper_values = np.arange(base) if not np.isin(seq, proper_values).all(): raise ValueError(f"There are symbol codes greater than {base-1}") code = 0 for i, x in enumerate(reversed(seq)): if x > 0: code += x * base**i return code def decode_sequence(code, base=2, min_length=None): """Decode sequence from a sequence code. Parameters ---------- code : int Non-negative integer. base : int Encoding base. Should be equal to the number of unique symbols in the alphabet. min_length : int or None Minimal number of represented bits. Use shortest representation if ``None``. Returns ------- array_like 1D *Numpy* array. Examples -------- >>> decode_sequence(4) array([1, 0, 0]) """ bits = deque() while code > 0: code, rest = divmod(code, base) bits.appendleft(rest) n = len(bits) if min_length and n < min_length: for _ in range(min_length - n): bits.appendleft(0) return np.array(bits) def encode_string(x, base=2): """Encode sequence-string to integer code. Parameters ---------- x : str Sequence string. Base : int Encoding base. Returns ------- int Integer code for a sequence-string. """ return encode_array(array_from_string(x), base=base) def decode_string(code, shape, base=2): """Decode sequence-string from an integer code. Parameters ---------- code : int Non-negative integer. base : int Encoding base. min_length : int or None Minimal number of represented bits. Use shortest representation if ``None``. Returns ------- str Sequence-string corresponding to an integer code. """ return string_from_array(decode_array(code, shape, base=base)) def encode_array(x, base=2, **kwds): """Encode array of integer-symbols. Parameters ---------- x : (N, k) array_like Array of integer symbols. base : int Encoding base. **kwds : Keyword arguments passed to :py:func:`numpy.ravel`. Returns ------- int Integer code of an array. """ seq = np.ravel(x, **kwds) return encode_sequence(seq, base=base) def decode_array(code, shape, base=2, **kwds): """Decode array of integer-symbols from a sequence code. Parameters ---------- code : int Non-negative integer. shape : tuple of ints Expected array shape. base : int Encoding base. **kwds : Keyword arguments passed to :py:func:`numpy.reshape`. Returns ------- array_like *Numpy* array. """ length = np.multiply.reduce(shape) seq = decode_sequence(code, base=base, min_length=length) if seq.size > length: raise ValueError(f"{code} does not encode array of shape {shape}") arr = seq.reshape(shape, **kwds) return arr
10e3028e017e09119ac98f2f1525ec31f3068d6f
presian/HackBulgaria
/Programming0-1/Week_2/1-Basic-List-Operations/problem2.py
557
3.625
4
languages = ['Python', 'Ruby'] languages.append('C++') languages.append('Java') languages.append('C#') languages.insert(0, 'Haskell') languages.append('Go') print(languages[0]) print(languages[1]) print(languages[4]) index = languages.index('C#') languages[index] = 'F#' print(languages) print(languages[len(languages)-1]) print('Is Haskell in the list: ' + str('Haskell' in languages)) print('Is Ruby in the list: ' + str('Ruby' in languages)) print('Is Go in the list: ' + str('Go' in languages)) print('Is Rust in the list: ' + str('Rust' in languages))
13bd11ca5c821abe9d675ca1a7c226da6cb231e7
rofernan42/Bootcamp_Python
/day04/ex00/FileLoader.py
441
3.609375
4
import pandas class FileLoader: def load(self, path): file = pandas.read_csv(path, sep=",") print(f"Loading dataset of dimensions {file.shape[0]} x {file.shape[1]}") return file def display(self, df, n): if n > 0: print(df.head(n)) elif n < 0: print(df.tail(-n)) fl = FileLoader() df = fl.load("../resources/athlete_events.csv") fl.display(df, 15) fl.display(df, -15)
e3cfe9b29e732d1d361c6d18fb4831ae557144d2
pflun/advancedAlgorithms
/Amazon-lunchRecommandation.py
1,308
3.53125
4
# -*- coding: utf-8 -*- class Solution(object): def lunchRecommandation(self, menu, person): dicm = {} dicp = {} tmp = set() res = [] # Italian => Pizza for item in menu: food = item[0] style = item[1] if style in dicm: dicm[style].append(food) else: dicm[style] = [food] # Peter => Italian for elem in person: name = elem[0] style = elem[1] if name in dicp: dicp[name].append(style) else: dicp[name] = [style] # [Peter, Pizza] for key, val in dicp.items(): for style in val: if style == "*": for item in menu: tmp.add((key, item[0])) continue if style in dicm: for food in dicm[style]: tmp.add((key, food)) # convert set tuple into list for t in tmp: res.append(list(t)) return res test1 = Solution() print test1.lunchRecommandation([["Pizza", "Italian"], ["Pasta", "Italian"], ["Burger", "American"]], [["Peter", "Italian"], ["Adam", "American"], ["Peter", "*"]])
8793bc0e33cf04f064b05bec3c0b7b5b4e576621
thec4iocesar/python3
/pythyon_old/modulos/modulo.py
274
3.734375
4
#!/usr/bin/python3.7 print('Usando Modulos') def contagem(): a = 0 while a <= 10: print (a) a = a + 1 contagem() def somar(x, y): print("somando") return x + y def boas_vindas(nome): return 'Seja bem vindo, {}!'\ .format(nome)
ebf018566fa8c7096abac7bfd99faa890cf50fc4
lostdatum/Python3-Tutorial
/c02_scope.py
5,339
4.28125
4
# ============================================================================= # SCOPE OF OBJECTS # ============================================================================= # This tutorial is about the scope of objects in Python. # Basicly, the scope of an object is the domain in which it can be referered to # by name (without having to do anything special). # Namespaces define the scope of the objects declared inside them. For example, # these create their own namespace: # - modules (i.e. files) # - classes # - functions/methods # For now, we will only cover the case of functions in the same module. # In Python, when a script is being executed, it is refered to by special # name '__main__', which is the top-level namespace. #%% ========================= SCOPE INSIDE FUNCTION =========================== # Here we try to read and overwrite an object defined in the module from inside # functions. # -------------------------------- DEFINITIONS -------------------------------- def myobj_print(): # try to read only try: print("myobj_print: 'myobj' =", myobj) except NameError as err: print("myobj_print:ERROR:", err) def myobj_set(value): # try to read and overwrite try: print("myobj_set(start): 'myobj' =", myobj) except NameError as err: print("myobj_set(start):ERROR:", err) myobj = value # direct assignment (overwrite) print("myobj_set(end): 'myobj' =", myobj) # -------------------------------- TEST SCRIPT -------------------------------- import misctest as mt # custom functions to make tests easier mt.headprint("SCOPE INSIDE FUNCTION") mt.stepprint("Set 'myobj' to 0") myobj = 0 print("main: 'myobj' =", myobj) mt.stepprint("Calling 'myobj_print()'") myobj_print() mt.stepprint("Calling myobj_set(42)") myobj_set(42) print("main: 'myobj' =", myobj) # CONCLUSIONS: # 1/ A function can read an object from caller namespace *IF & ONLY IF* # it does NOT attempt to OVERWRITE it (i.e. directly assign it a new value). # 2/ When a function tries to OVERWRITE an object 'myobj' from caller namespace: # a/ A new object also named 'myobj' is created locally within the function. # b/ The original 'myobj' object from caller namespace is masked within # the function and cannot be accessed. # c/ Any reference to 'myobj' inside the function redirects to the new # local object. This is called shadowing (or shading). # d/ The original 'myobj' object from caller namespace will be left # unchanged by the function. #%% ============================ GLOBAL KEYWORD =============================== # This time we declare 'myobj' as global object inside the function, using # keyword 'global'. # -------------------------------- DEFINITIONS -------------------------------- def myobj_glob_set(value): # try to read and overwrite global myobj # ADDED: declare 'myobj' as global object try: print("myobj_glob_set(start): 'myobj' =", myobj) except NameError as err: print("myobj_glob_set(start):ERROR:", err) myobj = value # direct assignment (overwrite) print("myobj_glob_set(end): 'myobj' =", myobj) # -------------------------------- TEST SCRIPT -------------------------------- mt.headprint("GLOBAL KEYWORD") mt.stepprint("Set 'myobj' to 0") myobj = 0 print("main: 'myobj' =", myobj) mt.stepprint("Calling 'myobj_glob_set(42)'") myobj_glob_set(42) print("main: 'myobj' =", myobj) # CONCLUSIONS: # 3/ A function can OVERWRITE an object from caller namespace *IF & ONLY IF* # this object is declared as global inside the function. #%% =================== MODIFYING MUTABLES INSIDE FUNCTION ==================== # Previously we used the functions with an immutable object (integer). # This time, we try with a mutable object (list), and check what happens when # we try to mutate the object inside the function instead of overwriting it. # -------------------------------- DEFINITIONS -------------------------------- def myobj_set_elt(idx, value): # try to read and modify try: print("myobj_set_elt(start): 'mylist' =", mylist) except NameError as err: print("myobj_set_elt(start):ERROR:", err) mylist[idx] = value # mutation with list.__setattr__() print("myobj_set_elt(end): 'mylist' =", mylist) def myobj_add_elt(value): # try to read and modify try: print("myobj_add_elt(start): 'mylist' =", mylist) except NameError as err: print("myobj_add_elt(start):ERROR:", err) mylist.append(value) # mutation with list.append() print("myobj_add_elt(end): 'mylist' =", mylist) # -------------------------------- TEST SCRIPT -------------------------------- mt.headprint("MODIFYING MUTABLES INSIDE FUNCTION") mt.stepprint("Set 'mylist' to [0]") mylist = [0] print("main: 'mylist' =", mylist) mt.stepprint("Calling 'myobj_set([42, 666])'") myobj_set([42, 666]) print("main: 'mylist' =", mylist) mt.stepprint("Calling 'myobj_set_elt(0, 42)'") myobj_set_elt(0, 42) print("main: 'mylist' =", mylist) mt.stepprint("Calling 'myobj_add_elt(666)'") myobj_add_elt(666) print("main: 'mylist' =", mylist) # CONCLUSIONS: # 4/ We can use methods inside a function to MODIFY a mutable object from # caller namespace (without having to do anything special).
deb235de612f63cf50cde3ee1ddf390e21743fe4
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/42_12.py
1,795
4.65625
5
Python – Split String on all punctuations Given a String, Split the String on all the punctuations. > **Input** : test_str = ‘geeksforgeeks! is-best’ > **Output** : [‘geeksforgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’] > **Explanation** : Splits on ‘!’ and ‘-‘. > > **Input** : test_str = ‘geek-sfo, rgeeks! is-best’ > **Output** : [‘geek’, ‘-‘, ‘sfo’, ‘, ‘, ‘rgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’] > **Explanation** : Splits on ‘!’, ‘, ‘ and ‘-‘. **Method : Using regex + findall()** This is one way in which this problem can be solved. In this, we construct appropriate regex and task of segregating and split is done by findall(). ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Split String on all punctuations # using regex + findall() import re # initializing string test_str = 'geeksforgeeks ! is-best, for @geeks' # printing original String print("The original string is : " + str(test_str)) # using findall() to get all regex matches. res = re.findall( r'\w+|[^\s\w]+', test_str) # printing result print("The converted string : " + str(res)) --- __ __ **Output** The original string is : geeksforgeeks! is-best, for @geeks The converted string : ['geeksforgeeks', '!', 'is', '-', 'best', ', ', 'for', '@', 'geeks'] Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
96e58815ee2ebc178532b77c4f24a3bdb8976a2e
AymanM92/PID_Python_Assignment_NanoDegree
/4_Implement_PID_controller.py
5,049
4.09375
4
# ----------- # User Instructions # # Implement a P controller by running 100 iterations # of robot motion. The desired trajectory for the # robot is the x-axis. The steering angle should be set # by the parameter tau so that: # # steering = -tau * crosstrack_error # # You'll only need to modify the `run` function at the bottom. # ------------ from random import * import numpy as np import matplotlib.pyplot as plt # ------------------------------------------------ # # this is the Robot class # class Robot(object): def __init__(self, length=20.0): """ Creates robot and initializes location/orientation to 0, 0, 0. """ self.x = 0.0 self.y = 0.0 self.orientation = 0.0 self.length = length self.steering_noise = 0.0 self.distance_noise = 0.0 self.steering_drift = 0.0 def set(self, x, y, orientation): """ Sets a robot coordinate. """ self.x = float(x) self.y = float(y) self.orientation = float(orientation) % (2.0 * np.pi) def set_noise(self, steering_noise, distance_noise): """ Sets the noise parameters. """ # makes it possible to change the noise parameters # this is often useful in particle filters self.steering_noise = float(steering_noise) self.distance_noise = float(distance_noise) def set_steering_drift(self, drift): """ Sets the systematical steering drift parameter """ self.steering_drift = float(drift) def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0): """ steering = front wheel steering angle, limited by max_steering_angle distance = total distance driven, most be non-negative """ if steering > max_steering_angle: steering = max_steering_angle if steering < -max_steering_angle: steering = -max_steering_angle if distance < 0.0: distance = 0.0 # apply noise steering2 = gauss(steering, self.steering_noise) distance2 = gauss(distance, self.distance_noise) # apply steering drift steering2 += self.steering_drift # Execute motion turn = np.tan(steering2) * distance2 / self.length if abs(turn) < tolerance: # approximate by straight line motion self.x += distance2 * np.cos(self.orientation) self.y += distance2 * np.sin(self.orientation) self.orientation = (self.orientation + turn) % (2.0 * np.pi) else: # approximate bicycle model for motion radius = distance2 / turn cx = self.x - (np.sin(self.orientation) * radius) cy = self.y + (np.cos(self.orientation) * radius) self.orientation = (self.orientation + turn) % (2.0 * np.pi) self.x = cx + (np.sin(self.orientation) * radius) self.y = cy - (np.cos(self.orientation) * radius) def __repr__(self): return '[x=%.5f y=%.5f orient=%.5f]' % (self.x, self.y, self.orientation) ############## ADD / MODIFY CODE BELOW #################### # ------------------------------------------------------------------------ # # run - does a single control run def make_robot(): """ Resets the robot back to the initial position and drift. You'll want to call this after you call `run`. """ robot = Robot() robot.set(0, 1, 0) robot.set_steering_drift(10 / 180 * np.pi) return robot robot = Robot() robot.set(0, 1, 0) def run(robot, tau_p,tau_d,tau_i, n=100, speed=1.0): x_trajectory = [] y_trajectory = [] old_y = [] sum_y = [] prev_cte = robot.y sum_cte = 0 #robot.set_steering_drift(10*np.pi/180) # TODO: your code here for i in range(n): cte = robot.y diff_cte= cte - prev_cte sum_cte += cte prev_cte = cte steering_wheel_angle = (-tau_p*cte) - (tau_d*diff_cte) - (tau_i*sum_cte) #print(cte,diff_cte,sum_cte) robot.move(steering_wheel_angle,speed) x_trajectory.append(robot.x) y_trajectory.append(robot.y) print(robot,steering_wheel_angle)#,'==> Y old and y now',old_y,robot.y) #end of my code return x_trajectory, y_trajectory x_trajectory, y_trajectory = run(robot, 0.2, 3, 0.004) n = len(x_trajectory) fig, (ax1, ax2) = plt.subplots(2, 1)#, figsize=(8, 8)) ax1.plot(x_trajectory, y_trajectory, 'g', label='PID controller Tuned without twiddle Algorithem') ax1.plot(x_trajectory, np.zeros(n), 'r', label='reference') ax1.legend() #plt.show() robot = make_robot() x_trajectory, y_trajectory = run(robot, 2.9229268964347743, 10.326767087320677, 0.4932708323372665) n = len(x_trajectory) #fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8)) ax2.plot(x_trajectory, y_trajectory, 'b', label='PID controller Tuned with twiddle Algorithem') ax2.plot(x_trajectory, np.zeros(n), 'r', label='reference') ax2.legend() plt.show()
cfa6ee5a4ff6161144261d9493dad84bcd94f02b
nn98/Python
/Python-19_2/lab7_4_T.py
1,206
3.609375
4
# -*- coding: ms949 -*- """ Էϴ ܾ Ͻÿ. ҹ ʰ ó϶. '.,!?()/ ܾ ƴϴ. Է¿) : While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions. ¿) ܾ : """ a=input(" : ") # Է a=a.replace(",","") a=a.replace(".","") a=a.replace("\'","") a=a.replace("\"","") a=a.replace("?","") a=a.replace("!","") a=a.replace("/","") a=a.replace("(","") a=a.replace(")","") # ܾ ƴ ͵ ü a=a=a.lower() # ҹڷ ٲ۴. word=[] # ܾ ϱ list Ѵ. for words in a.split(sep=' '): # ܾ ɰ. word.append(words) # ܾ word Ѵ. word=list(set(word)) # ߺ Ʈ print(word) print("ܾ :",len(word)) # ܾ
d5ae0defc00d608ac05694bd4811c33182710df0
macbeth-byui/MathShower_Arcade
/mathshower.py
5,411
3.5
4
from abc import abstractmethod import arcade import random from PIL import Image from PIL import ImageDraw from PIL import ImageFont WIN_WIDTH = 800 WIN_HEIGHT = 800 class Problem: def __init__(self): self.problem_text = "" self.points_right = 0 self.points_wrong = 0 @abstractmethod def solve(self, response): pass class Factors_Problem(Problem): def __init__(self): super().__init__() self.value = random.randint(2,100) self.problem_text = "Find Factors of {}".format(self.value) self.points_right = 5 self.points_wrong = -1 def solve(self, response): if self.value % response == 0: return self.points_right else: return self.points_wrong class Player(arcade.Sprite): def __init__(self): super().__init__() self.texture = arcade.load_texture("penguin.png") self.scale = 0.1 self.center_x = WIN_WIDTH//2 self.center_y = 50 def move_left(self): if self.center_x <= 10: self.center_x <= 10 else: self.center_x -= 5 def move_right(self): if self.center_x >= WIN_WIDTH - 10: self.center_x = WIN_WIDTH - 10 else: self.center_x += 5 class Precip(arcade.Sprite): def __init__(self): super().__init__() self.center_x = random.randint(10, WIN_WIDTH-10) self.center_y = WIN_HEIGHT - 10 self.change_x = random.uniform(-2, 2) self.change_y = random.uniform(-0.1, -2) def update(self): self.center_x += self.change_x self.center_y += self.change_y if self.center_x < 0 or self.center_x > WIN_WIDTH: self.change_x *= -1 if self.center_y < 0: self.remove_from_sprite_lists() @abstractmethod def hit(self, problem): pass class Number_Precip(Precip): def __init__(self): super().__init__() self.number = random.randint(2,9) self.texture = Number_Precip.convert_text_to_texture(str(self.number)) @staticmethod def convert_text_to_texture(text_value): img = Image.new('RGBA', (75,75), color = (255, 255, 255, 0)) d = ImageDraw.Draw(img) fnt = ImageFont.truetype('absender1.ttf', 100) d.text((15,5), text_value, font=fnt, fill=(255, 0, 0)) texture = arcade.Texture(str(text_value), img) return texture def hit(self, problem): self.remove_from_sprite_lists() return problem.solve(self.number) class Snow_Precip(Precip): def __init__(self): super().__init__() self.texture = arcade.load_texture("snowflake.png") self.scale = 0.1 def hit(self, problem): self.remove_from_sprite_lists() return 5 class Lightning_Precip(Precip): def __init__(self): super().__init__() self.texture = arcade.load_texture("lightning.png") self.scale = 0.05 def hit(self, problem): self.remove_from_sprite_lists() return -5 class Game(arcade.Window): def __init__(self): super().__init__(WIN_WIDTH,WIN_HEIGHT,"Math Showers") self.player = Player() self.precip = arcade.SpriteList() self.keys_pressed = set() self.score = 0 self.background = arcade.load_texture("background.jpg") self.problem = None self.problem_timer = 0 def on_draw(self): arcade.start_render() arcade.draw_texture_rectangle(WIN_WIDTH//2, WIN_HEIGHT//2, WIN_WIDTH, WIN_HEIGHT, self.background) self.player.draw() self.precip.draw() if self.problem is not None: arcade.draw_text(self.problem.problem_text, WIN_WIDTH//3, WIN_HEIGHT - 50, arcade.color.WHITE, 36) output = f"Score: {self.score}" arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) output = f"Timer: {self.problem_timer // 100}" arcade.draw_text(output, WIN_WIDTH - 100, 20, arcade.color.WHITE, 14) def on_update(self, delta_time): self.check_pressed_keys() self.create_precip() self.create_problem() self.precip.update() hit_list = arcade.check_for_collision_with_list(self.player, self.precip) for precip in hit_list: self.score += precip.hit(self.problem) def create_problem(self): if self.problem_timer == 0: self.problem = Factors_Problem() self.problem_timer = 2000 else: self.problem_timer -= 1 def create_precip(self): if random.randint(1,80) == 1: precip = Number_Precip() self.precip.append(precip) if random.randint(1,200) == 1: precip = Snow_Precip() self.precip.append(precip) if random.randint(1,200) == 1: precip = Lightning_Precip() self.precip.append(precip) def on_key_press(self, key, modifiers): self.keys_pressed.add(key) def on_key_release(self, key, modifiers): self.keys_pressed.remove(key) def check_pressed_keys(self): if arcade.key.LEFT in self.keys_pressed: self.player.move_left() if arcade.key.RIGHT in self.keys_pressed: self.player.move_right() window = Game() arcade.run()
a39293ee97c5d2c47ca63e991bfcfab945fb7fb8
NewtonFractal/Project-Euler-6
/Project Euler #6.py
177
3.65625
4
import time start = time.time() def squared(y): x = sum(x**2 for x in range(1,y+1)) print(abs((x-(((1+y)*y)/2)**2))) squared(100) end = time.time() print(end - start)
8e176c3f7830ceb14681aad8115873cb8b61e4b9
Deodatuss/DevOps_online_Kyiv_2021Q2
/m9/task9.1/py_files/fizzbuzz.py
235
3.53125
4
def get_reply(number): if (not number % 5) and (not number % 3): return 'FizzBuzz' elif not number % 3: return 'Fizz' elif not number % 5: return 'Buzz' else: return f'{number}'
39403ee450bdb0d3c0ad736213f504290aee45e5
Ceasar1978/NewCeasar
/d3_exercise_calculator.py
392
3.59375
4
a = int(input(""" 1:加法 2:减法 3:乘法 4:除法 请输入您要进行的计算:""")) i = int(input("请输入第一个数字:")) j = int(input("请输入第二个数字:")) if a == 1: print(i ,'+',j,'=',i+j) elif a == 2: print(i,"-",j,'=', i-j) elif a == 3: print(i,'*',j,'=',i*j) elif a== 4: print(i,'/',j,'=',i/j) else: print("输入错误!")
c946b407657c3aa3b1d14a83e7fdcc10c509bb8e
JustinDoghouse/LeetcodeAnswer
/twoSum.py
400
3.515625
4
__author__ = 'burger' class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): ht = {} for i in range(len(num)): if ht.__contains__(target - num[i]): return (ht[target - num[i]] + 1, i + 1) else: ht[num[i]] = i if __name__ == '__main__': s = Solution() print(s.twoSum([1, 2, 3], 4))
a0a5a772477096941c72c9a6c41082caea05a2a9
ryanbrown358/PythonStuff
/python list and loops/listAndLoops.py
443
4.125
4
Ryan = "Where is ryan at today?" for names in Ryan: print(names) list_of_list = ["String1", "String1", ["Second list of sting2", "Second2"], ["Third list of string3", "And so on!"]] for list in list_of_list: print(list) for i in range(1,101): if i % 3 == 0: print("zip") elif i % 5 == 0: print("zap") elif i % 15 == 0: print("zipzap") else: print(i)
b5d261bfdb148403ed9e72cbd1d275880aa5df4a
suniljarad/unity
/Assignment1_2.py
1,398
4.28125
4
# #Step 1 : Understand the problem statement #step 2 : Write the Algorithm #Step 3 : Decide the programming language #Step 4 : Write the Program #Step 5 : Test the Written Program #program statement: # Take one function named as ChkNum() which accept one parameter as number. # If number is even then it should display “Even number” otherwise display “Odd number” on console. ################################################################################################## #Algorithm #Start #Accept one parameter as no1 #Display no1 as Even number or Odd number #End #################################################################################################### #Function Name: ChkNum() #input :Integer #output:Integer #Description: It should display “Even number” otherwise display “Odd number” on console. #Author: Sunil Bhagwan Jarad #Date:19/2/2021 #################################################################################################### def ChkNum(no1): if no1%2==0: return True else: return False def main(): print("Enter number:") value=int(input()) ret=ChkNum(value) if ret==True: print("{} is Even number".format(value)) else: print("{} is Odd number".format(value)) if __name__ == "__main__": main()
0796081988a74f745fc0764ac554f723bf924a4a
lytl890/DailyQuestion
/jinhao/jinhao_q2.py
867
4.0625
4
''' 第2题:设计一个猜数字的游戏 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 ''' import random low = 1 high = 100 times = 5 #随机生成一个数字 goal = random.randrange(low, high) print('数字已选好,游戏开始。你只有{0}次机会!'.format(times)) while times > 0: number = int(input('请输入你猜的数字:')) times = times - 1 if number > goal: print('太大了,请重试。你还有{0}次机会!'.format(times)) elif number < goal: print('太小了,请重试。你还有{0}次机会!'.format(times)) elif number == goal: print('猜对了!我想的数字就是{0}!'.format(goal)) break
e1db0d5909ebf5a0139230d684948d04b435ea72
alishakundert/codewars-kata
/5kyu/[5kyu]Best_travel.py
595
3.65625
4
''' Best travel https://www.codewars.com/kata/55e7280b40e1c4a06d0000aa/python ''' import numpy as np from itertools import combinations def choose_best_sum(t, k, ls): # all possible combinations comb = combinations(ls, k) # compute sum of all combinations sum_comb = np.array(list(set([sum(p) for p in comb]))) # reduce sums to max cutoff sum_comb = sum_comb[sum_comb<=t] if len(sum_comb) == 0: # minimum sum of distances greater than cutoff return None else: # return maximum sum of combinations return max(sum_comb)
fac759b547e390011bc424472aa9b2d0cab60aa3
ahmed100553/Problem-List
/minimalMultiplet.py
407
4.25
4
''' Find the smallest multiple of the given number that's not less than a specified lower bound. ''' def minimalMultiple(divisor, lowerBound): if lowerBound%divisor == 0: return lowerBound return (lowerBound / divisor + 1) * divisor ''' Example For divisor = 5 and lowerBound = 12, the output should be:minimalMultiple(divisor, lowerBound) = 15. '''
909dc0a0da64c71de6371205b33a04c07ef43cb0
krixstin/python-enhance
/oop/visibility.py
400
3.578125
4
class Product(object): pass #__items : private type class Inventroy(object): def __init__(self): self.__items = [] def add_new_item(self, product): if type(product) == Product: self.__items.append(product) print("New item added") else: print("Invalid item") def get_number_of_items(self): return len(self.__itmes)
248d1776c7c38ce015b8e218c4cff839f899e655
mikoim/funstuff
/codecheck/codecheck-3538/app/calendar.py
2,225
3.875
4
import string class Calender: def __init__(self, days_year: int, days_month: int, days_week: int): if not (days_year > 0 and days_month > 0 and days_week > 0): raise ValueError('all arguments must be natural number') if days_week > 26: raise ValueError('days_week must be a integer from 1 to 26') if not (days_year >= days_month >= days_week): raise ValueError('invalid argument order') self._days_year = days_year self._days_month = days_month self._days_week = days_week self._month = int(days_year / days_month) self._leap_diff = days_year % days_month self._leap = 0 if self._leap_diff == 0 else int(days_month / self._leap_diff) def calc(self, date_string: str) -> str: year, month, day = map(int, date_string.split('-')) if not (year > 0 and month > 0 and day > 0): raise ValueError('all arguments must be natural number') if day > self._days_month: raise ValueError('invalid day: maximum day exceeded') if month > self._month + 1: raise ValueError('invalid month: maximum month exceeded') year -= 1 month -= 1 leap_years = [] if self._leap == 0: if self._month == month: raise ValueError('invalid month: there is no leap year') days = year * self._days_year + month * self._days_month + day else: days = 0 stock = 0 for _ in range(year): days += self._days_year - self._leap_diff stock += self._leap_diff if stock >= self._days_month: stock -= self._days_month days += self._days_month leap_years.append(_) stock += self._leap_diff if stock >= self._days_month: leap_years.append(year) if month + 1 > self._month and year not in leap_years: raise ValueError('invalid month: this year is not leap year') days += month * self._days_month + day return string.ascii_uppercase[(days - 1) % self._days_week]
04172f603871e3de71afebfe906e6ac8dfe621cd
Iron-Maiden-19/MapReduce
/reducerx.py
2,662
3.5625
4
#!/usr/bin/env python3.6 import sys #Variables that keep track of the keys. current_key_being_processed = None #Do not add anything above this line. The one #exception is that you can add import statements. #You can create any global variables you want here that you will use per key. #For example, we can create a dictionary variable called temp and/or set a variable to 0: #temp = {} #temp_num = 0 #However, we must reset these once a new key is found, see below. next_key_found = None cust_dictionary = {} cust_total = 0 for line in sys.stdin: line = line.strip() next_key_found, value = line.split('\t') if current_key_being_processed == next_key_found: #The next key read in is the same one we've been processing. #You'll likely want to add some code here. cust_total = float(cust_total) + float(value) cust_total = round(cust_total) else: #One of two things happened here: #1. The first key was found. #2. A new key was found. if current_key_being_processed: #2. happened, a new key was found. #Output something based on the (key,value) pairs that #we have just seen where all of them had the same key. cust_dictionary[current_key_being_processed] = float(cust_total) #end of the if statement for number 2. happening. #Since the next key found was a new key, we need to clear any global variables #we have created right now. If we do not clear them out, our code is not stateless. #Therefore, we clear the dictionary and reset the variable to 0. cust_total = 0 #Lastly, we set the current_key_being_processed to be the new key we just read in. current_key_being_processed = next_key_found cust_total = float(cust_total) + float(value) cust_total = round(cust_total,2) #for loop ends here if current_key_being_processed == next_key_found: cust_total = round(cust_total,2) cust_dictionary[next_key_found] = float(cust_total) #create new_dict with new key new_data = {} for key, val in cust_dictionary.items(): newkey, idnum = key.split(':') new_data.setdefault(newkey, []).append((val, idnum)) # Sort the values for each 'month,country' key, # and get the IDnums corresponding to the highest values for key, val in new_data.items(): val = sorted(val, reverse=True) highest = val[0][0] # Collect all IDnums that have the highest value ids = [] for v, idnum in val: if v != highest: break ids.append(idnum) print(key + ':' + ', '.join(ids))
3f87fcaeffe026d1366e9dcc784eb51e95067a13
alexmasucci/geocoding-helpers
/google-maps-api/init_pickle.py
1,079
3.59375
4
'''This program creates a dataframe from the address data, creates fields for the new variables we want, then saves the dataframe as a pickle. The address data is assumed to be saved as a CSV file called addresses.csv with the following variables: addressid - An integer uniquely identifying each address addressline1 - Address line 1 addressline2 - Address line 2 city - Address city state - Address state zipcode - Address ZIP code''' import pandas as pd import numpy as np import os import time if 'addresses.pkl' in os.listdir(): print('addresses.pkl already exists - delete manually before creating a new pickle') quit() conv = {'addressid': int, 'addressline1': str, 'addressline2': str, 'city': str, 'state': str, 'zipcode': str} loadstart = time.time() df = pd.read_csv('addresses.csv', header = 0, converters = conv) loadstop = time.time() print('Took', round(loadstop - loadstart, 2), 'seconds to read in', df.shape[0], 'addresses') df['jsonstring'] = np.nan df['matchstatus'] = np.nan df['numberofresults'] = np.nan df.to_pickle('addresses.pkl')
3bdbb73da108ab01e100d8fdff38cc5bbc2698ea
saurabhsarage/Python
/Task1_Assignment1.py
406
3.78125
4
""" Created on Mon Dec 23 22:20:42 2019 @author: saurabh """ """ Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. """ l = [] for i in range(2000,3201): if (i % 7 == 0) and (i % 5 !=0): l.insert(len(l),i) print(l)
1f83437583e03ed89d00374cddc0acb4579017ce
nsotiriou88/Machine_Learning
/10 - Model Selection & Boosting/XGBoost/xgboost.py
1,920
3.6875
4
# XGBoost - Gradient Boost Model with decision trees # High performance: speed, quality, results # Install xgboost following the instructions on this link: http://xgboost.readthedocs.io/en/latest/build.html# # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') #bank customers problem X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # NO FEATURE SCALING is required for XGBoost. High performant algorithm # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) #Specify the index of the categorical feature; creates more columns with 0 and 1 X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # need to remove one of the columns created(dummy variable trap) # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Fitting XGBoost to the Training set from xgboost import XGBClassifier classifier = XGBClassifier() #can change learning rate etc. classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Applying k-Fold Cross Validation from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10) print('Mean Accuracy', accuracies.mean()) print('Std Accuracy', accuracies.std())
15e590cd6035572aa042c5a03b18e60c0433ce62
shaon11579/Exploration-of-Learner-Data-with-VAEs
/Replication_main.py
5,359
3.5
4
# -*- coding: utf-8 -*- """ Replication __main__ This function creates a NN as described in Autoencoders for Education Assessment, and creates the graphs just like that paper. Specifically, we replicate table 1, figure 3, figure 4, table 2, and figure 5. @author: andre """ import pandas as pd import numpy as np import os os.chdir("C:/Users/andre/Documents/GitHub/Exploration-of-Learner-Data-with-VAEs") from Teaching_Vae_Class import Teaching_Vae from Data_Gen import Create_data from Graphical_Functions import Table_1, get_stats_over_time, get_theta_stats_v2 ############################################################################### #Replication_of_Paper_Figures: Function that trains a NN and replicates the data # for all figures and tables in the paper #INPUT: # Input_data = list of data if you have data you want to train the networks # on. If None, ignored. Format: [Q_mat, A, B, theta, data] # num_students: the number of simulated students. # num_questions: the number of questions in a test # num_tests: the number of tests given for each student # num_skills: the number of hidden skills being tested # dist: the distribution of the stochastic layer in the VAE # Input_Vae: a vae trained outside the function. If empty, the function will # train a vae. # Input_Ae = an ae trained outside the function. If empty, the function will # train an ae. #OUTPUT: # tab1_data: the data for the first table in the paper # fig3_data: '''' # fig4_data: ''' # tab2_data: ''' # fig5_data: # vae: the trained vae. # ae: the trained ae # data_list: [Qmat, A, B, theta, data] used in simulation ############################################################################### def Replication_of_Paper_Figures(Input_data = None, num_students = 10000, num_questions= 28, num_tests = 10, num_skills = 3, dist= 'norm', vae = None, ae = None): #Obtaining data for the Network if Input_data is not None: Q_mat, A, B, theta, data = Input_data else: Q_mat, A, B, theta, data = Create_data(num_students, num_questions, num_tests, num_skills) #Initializing the networks if vae is None: vae = Teaching_Vae(dist = 'norm', qmat = Q_mat, num_questions = A.shape[1]) H_vae = vae.train(data) else: H_vae = vae.train(data, epochs = 1) if ae is None: ae = Teaching_Vae(dist = 'None', qmat = Q_mat, num_questions = A.shape[1]) H_ae = ae.train(data) else: H_ae = ae.train(data, epochs = 1) #Extracting the statistics from the networks dfa1_vae , dfa2_vae, dfa3_vae, dfb_vae = get_stats_over_time(A_list=[], B_list=[], a_true = A, b_true= B, qmat = Q_mat, matrix = False, H = H_vae) dfa1_ae , dfa2_ae, dfa3_ae, dfb_ae = get_stats_over_time(A_list=[], B_list=[], a_true = A, b_true= B, qmat = Q_mat, matrix = False, H = H_ae) tab1_vae = Table_1(dfa1_vae, dfa2_vae, dfa3_vae, dfb_vae, dist) tab1_ae = Table_1(dfa1_ae, dfa2_ae, dfa3_ae, dfb_ae, 'AE') tab1 = pd.concat([tab1_vae,tab1_ae]) tab1 = tab1.groupby(['Statistic','Model']).agg('mean').reset_index() #Indicating which skill is used skill=[] for i in range(A.shape[0]): for j in range(A.shape[1]): skill.append(i) skill = np.array(skill)[np.where(np.reshape(Q_mat, [-1])==1)[0]] #Getting rid of a_i,j which were masked by the Q matrix A_qmat= np.reshape(A * Q_mat, [-1,]) A = np.delete(A_qmat, np.where(A_qmat == 0)) A_ae = np.reshape(Q_mat * np.exp(H_ae.history['log_A'][-1]), [-1]) A_ae = np.delete(A_ae, np.where(A_ae == 0)) A_vae= np.reshape(Q_mat * np.exp(H_vae.history['log_A'][-1]), [-1]) A_vae = np.delete(A_vae, np.where(A_vae==0)) fig3 = pd.DataFrame({'True_Values': A, 'Estimates_ae': A_ae, 'Estimates_vae': A_vae, 'skill_num': skill }) fig4 = pd.DataFrame({'True_Values': np.reshape(B,[-1]), 'Estimates_ae': H_ae.history['B'][-1], 'Estimates_vae': H_vae.history['B'][-1]}) #Vae stats tab2_vae, thetas_vae = get_theta_stats_v2(theta, H_vae.history['thetas'][-1] , data[:,0:2],Table2 = True, model = 'Vae') tab2_ae, thetas_ae = get_theta_stats_v2(theta, H_ae.history['thetas'][-1] , data[:,0:2],Table2 = True, model = 'ae') tab2 = pd.concat([tab2_vae, tab2_ae]) tab2 = tab2.groupby(['Statistic','Model']).agg('mean') #fig5 thetas_ae = pd.DataFrame(thetas_ae) thetas_ae.columns = ['Theta{}_ae'.format(i+1) for i in range(thetas_ae.shape[1])] thetas_vae = pd.DataFrame(thetas_vae) thetas_vae.columns = ['Theta{}_vae'.format(i+1) for i in range(thetas_vae.shape[1])] thetas_true = pd.DataFrame(theta) thetas_true.columns = ['Theta{}_true'.format(i+1) for i in range(thetas_vae.shape[1])] fig5 = pd.concat([thetas_true,thetas_ae, thetas_vae], axis= 1) return(tab1, fig3, fig4, tab2, fig5, vae, ae, [Q_mat, A, B, theta, data])
2e75b03dc287d1bc53754b508a84c9d4e049fa0d
zhangshv123/superjump
/interview/dp/hard/LC97. Interleaving String.py
2,275
3.625
4
""" Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. """ """ 首先,这道题的大前提是字符串s1和s2的长度和必须等于s3的长度,如果不等于,肯定返回false。那么当s1和s2是空串的时候,s3必然是空串,则返回true。 所以直接给dp[0][0]赋值true,然后若s1和s2其中的一个为空串的话,那么另一个肯定和s3的长度相等,则按位比较,若相同且上一个位置为True,赋True, 其余情况都赋False,这样的二维数组dp的边缘就初始化好了。下面只需要找出递推公式来更新整个数组即可,我们发现,在任意非边缘位置dp[i][j]时, 它的左边或上边有可能为True或是False,两边都可以更新过来,只要有一条路通着,那么这个点就可以为True。那么我们得分别来看,如果左边的为True, 那么我们去除当前对应的s2中的字符串s2[j - 1] 和 s3中对应的位置的字符相比(计算对应位置时还要考虑已匹配的s1中的字符),为s3[j - 1 + i], 如果相等,则赋True,反之赋False。 而上边为True的情况也类似,所以可以求出递推公式为: dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i - 1 + j]) || (dp[i][j - 1] && s2[j - 1] == s3[j - 1 + i]); """ class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ m, n = len(s1), len(s2) if m + n != len(s3): return False # dp[i][j]: s1[:i], s2[:j], s3[:i+j]子问题 dp = [False for _ in range(n + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 and j == 0: dp[j] = True elif i == 0 and j <= n: dp[j] = s2[j - 1] == s3[j - 1] and dp[j - 1] elif i <= m and j == 0: dp[j] = s1[i - 1] == s3[i - 1] and dp[j] else: dp[j] = (s1[i - 1] == s3[i + j - 1] and dp[j]) or (s2[j - 1] == s3[i + j - 1] and dp[j - 1]) return dp[n]
b944ed5368bac10834feb5d606c8055c8c830c56
StepanSZhuk/PythonCore377
/ClassWork/ClassWork1.py
329
4.125
4
a=int(input("Input the number a=")) b=int(input("Input the number b=")) if a <= b: min, max = a, b print("The number a={0} is minimal number,the number b={1} is maximum number".format(min, max)) else: min, max = b, a print("The number b={0} is minimal number,the number a={1} is maximum number".format(min, max))
9f93f4422a6d3eba4cf21199effd138e1d0df5b2
ChuhanXu/LeetCode
/Cisco/countBit.py
225
3.703125
4
# 统计一个整数的二进制式里有多少个1 def countBit(n): count = 0 while n: n &= (n-1) count += 1 return(count) print(countBit(10)) # 10 1010 2 # 10 &= 9 1010 &= 1001 = 1000
b9a21a5e45c4e11d928cace1619b8ead872fa1aa
radatelyukova/pfk
/pfk/07/01_functions.py
1,255
3.71875
4
#!/usr/bin/env python3 ################################################################################ # 01_functions.py # # <Executable Module Purpose> # # 18.07.2017 Created by: rada ################################################################################ def show_name(name): print("hello %s" % name) show_name('Renesma') show_name('Evgeny') def full_name(first_name, last_name): print("hello %s %s" % (first_name, last_name)) full_name('Rada', 'Telyukova') f_name = 'Evgeny' l_name = 'Telyukov' full_name(f_name, l_name ) def my_sum(x, y): return x + y result = my_sum(17, 50) print('\n') print(result) print(my_sum(17, 12)) if (result > 0): print('LOL') def new_sum(x, y): print(x + y) new_sum(4,39) def my_mult(a, b): print('my_mult: a = %i' % a) return a * b def my_sub(x, y): return x - y print('\n') print(my_sub(10, 30)) def my_div(w, q): if(q == 0): return "Ты Вася" return w / q print('\n') print(my_div(45, 3)) print(my_div(45, 33)) print(my_div(45, 33.0)) print(my_div(45, 0)) a = 100 print('\nScope') print('main: a = %i' % a) print(my_mult(10, 2)) print('main again: a = %i' % a) # Error #def my_mult(a, b): # return a * x #print(my_mult(10, 43))
48c3d7debc79400e5684a772b1b4273c17715f8d
Rshcaroline/FDU-Data-Visualization
/Final Project/reference/Python_FFD/NewtonSolver.py
3,140
3.890625
4
import numpy """ A method that will be used to solve a nonlinear system of equations using the Newton Raphson method. So, F(x) is a vector with the follwing components [f1(X), f2(X), ...] , where X is the vector of variables. Using Taylor's theorem, the following statement can be obtained: F(X) = F(X0) + DF(X0)*(delta X), where DF(X0) is the jacobian. In this module, we will take a variable n which will say how many equations and variables have to be sovled. It will then take the functions as a vector (which will lambda expressions or defined functions). It is on the user that the functions from the user take in the same number of arguments as the number n given. An iterative process using the numpy libraries then, the deltaX vector will be solved for until it becomes close to machine 0 which means that the solution has been found. """ #The dx variable used for calculating the jacobian CONST_dx = 0.001 CONST_Tolerance = 0.01 #args holds the functions def NewtonSolve(N, initialGuess , systemOfFunctions): counter = 0 X0 = initialGuess while(True): Jacobian = calculateJacobian(N,systemOfFunctions, X0) #create the system of equations to solve. DF(X0) * DeltaX = - F(X0). From this, #DeltaX can be solved for. DF(X0) is the Jacobian variable from the line before. #Now, create the vector F(X0) size = (N,1) MinusFX0 = numpy.zeros(size) for i in range(N): MinusFX0[i] = -systemOfFunctions[i](X0) deltaXVector = numpy.linalg.solve(Jacobian, MinusFX0) #deltaXVector = X1 - X0. Calculate X1 and use it for the next iteration #deltaXVector + X0 = X1 for i in range(N): X0[i] = deltaXVector[i][0] + X0[i] counter+=1 #to make sure an infinite loop isnt entered if(counter>100): break #if the delta x vector's norm is sufficiently small then quit the loop: norm = 0 for i in range(N): norm += deltaXVector[i]**2 norm = norm**(1./float(N)) if(norm < CONST_Tolerance): break #returning the solution vector return X0 #Each function has to take a vector as input. the vector is the vector of variables X #X0 is the vector about which the jacobian is calculated def calculateJacobian(N,systemOfFunctions, X0): #create an N*N matrix of zeros for the jacobian size = (N,N) Jacobian = numpy.zeros(size) for r in range(N): for c in range(N): #r is the row of interest and c is the column of interest. The loop will go through one row at a time #the column value will dictate which element in the X vector to perturb. Perturb this x position at the #beginning of the loop and then remove the perturbation after calculate an approximation of the partial delfrBydelXcAtX0 = -systemOfFunctions[r](X0)/CONST_dx X0[c] = X0[c] + CONST_dx delfrBydelXcAtX0 += systemOfFunctions[r](X0)/CONST_dx Jacobian[r][c] = delfrBydelXcAtX0 X0[c] = X0[c] - CONST_dx return Jacobian
0ded5e54231c63676059cdc0a117ce590f96febb
gwg118/Python-Play-Time
/for_loop.py
95
3.53125
4
foods = ["Tuna", "bacon", "peanut", "butter"] for f in foods: print(f) print(len(f))
8645a88f5594f292d9d8914453c01749b2d1fe09
samuelzq/Learn-Python-with-kids
/part1/check_prime.py
462
4.3125
4
''' Program to check whether a number is a prime ''' number = int(input('Please input an integer: ')) if number == 1: print('1 is neither a prime nor a composite number.\n') exit() remainder = 1 for factor in range(2, number): remainder = number % factor if remainder == 0: break; if remainder == 0: print('Number %s is a composite number.\n' %number) else: print('Number %s is a prime number.\n' %number)
964efdda8212de93a50e9c180fe1616691c3e9b5
tonyxiahua/CIS-40-Python
/Quizs/Quiz-9-Part-2.py
355
4.15625
4
inStr = input("Enter a sentence for pangram-checking:") inStr = inStr.strip() word = [] letters = [] for i in range(len(inStr)): if inStr[i].isalpha(): if inStr[i] not in letters: letters.append(inStr[i]) if len(letters) == 26: print("\"",inStr,"\" is a pangram") else: print("\"",inStr,"\" is a NOT pangram")
b2cc8b69dcb61dff6fcfcef042ffb73c4ab58d1a
programiranje3/2020
/main.py
2,630
4.28125
4
# # Hello world: the print() built-in function and the + operator # print("John Lennon") # print('John Lennon ' + 'was born in 1940.') # print('John Lennon', 'was born in 1940.') # print('John Lennon', 'was born in', 1940, '.') # print('John Lennon', 'was born in', str(1940) + '.') # print() # print('John Lennon', '\nwas born in', str(1940) + '.') # # The input() built-in function # # year = input('Read the year when John was born: ') # # print(year) # print('Read the year when John was born: ', end='') # year = input() # print(year) # # A simple function and function call # # def print_year(): # # print(1940) # # # # # # print_year() # # # # def print_year2(year): # # if year: # # print(year) # # else: # # print(None) # # # # # # print_year2('') # # # def f(a, b): # if a: # return a # elif b: # return b # else: # return None # # # print(f(0, '')) # # A simple loop and the range() built-in function # print(range(5)) # for i in range(5): # print(i) # print(', '.join(str(i) for i in range(5))) # # A simple list, accessing list elements, printing lists # theBeatles = ['John', 'Paul', 'George', 'Ringo'] # print(theBeatles) # print(theBeatles[0]) # print() # for i in range(4): # print(theBeatles[i]) # print(', '.join(theBeatles)) # print() # # # Looping through list elements - for and enumerate() # print(enumerate(theBeatles)) # print(list(enumerate(theBeatles))) # print() # for i, j in list(enumerate(theBeatles)): # print(str(i) + ': ', j) # # print(i, j) # # Global variables: __name__, __file__, __doc__,... # print(__name__) # print(__file__) # print(__doc__) from python import inception inception.print_year() # import python.inception # python.inception.print_year() print(__name__) # # Alternatively # import python.inception # python.inception.print_year() # # import python.inception # # python.inception.print_year() # print(__name__) # # Alternatively # from python.inception import * # print_year() # # import python.inception # # python.inception.print_year() # print(__name__) # # This is a sample Python script. # # # Press Shift+F10 to execute it or replace it with your code. # # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # # # def print_hi(name): # # Use a breakpoint in the code line below to debug your script. # print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. # # # # Press the green button in the gutter to run the script. # if __name__ == '__main__': # print_hi('PyCharm') # # # See PyCharm help at https://www.jetbrains.com/help/pycharm/
08be94dc59fb70dee4ec27e08eec3e7384139e27
Raffayet/CustomSearchEngine
/nonblocking_proccess.py
947
3.71875
4
import threading import time start_time = time.time() current_time = None stop = False class KeyboardThread(threading.Thread): def __init__(self, input_cbk=None, name='keyboard-input-thread'): self.input_cbk = input_cbk super(KeyboardThread, self).__init__(name=name) self.start() def run(self): while True: user_input = input() self.input_cbk(user_input) global stop stop = True break def my_callback(inp): #evaluate the keyboard input print('You Entered:', inp) #start the Keyboard thread kthread = KeyboardThread(my_callback) def count(): while True: global current_time current_time = time.time() #the normal program executes without blocking. here just counting up print('It has passed %.3f s' % (current_time-start_time)) time.sleep(2) if stop: return count()
bea704b6ebe787f26a7939f6dfdc6bf083b02e5f
chars32/edx_python
/Quizes/Quiz5/construct_dictionary_from_lists.py
1,540
4.375
4
#Write a function named construct_dictionary_from_lists that accepts 3 one dimensional lists and #constructs and returns a dictionary as specified below. # The first one dimensional list will have n strings which will be the names of some people. # The second one dimensional list will have n integers which will be the ages that correspond to those people. # The third one dimensional list will have n integers which will be the scores that correspond to those people. #Note that if a person has a score of 60 or higher (score >= 60) that means the person passed, if not the person failed. #Your function should return a dictionary where each key is the name of a person and the value corresponding #to that key should be a list containing age, score, 'pass' or 'fail' in the same order as shown in the sample output. names = ["paul", "saul", "steve", "chimpy"] ages = [28, 59, 22, 5] scores = [59, 85, 55, 60] def construct_dictionary_from_lists(names_list, ages_list, scores_list): dictionary = {} grades = [] #make a new list called grades where we evaluate if pass or fail for score in scores_list: if score >= 60: grades.append("pass") else: grades.append("fail") #correct keys and values en dictionary for x in range(len(names_list)): dictionary[names_list[x]]= [ages_list[x], scores_list[x], grades[x]] return dictionary print(construct_dictionary_from_lists(names, ages, scores)) #solution {'steve': [22, 55, 'fail'], 'saul': [59, 85, 'pass'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass']}
90be92859732d2a3f3fbfd207bc7f4ab8cdb7ede
PR850/LeetCode---Algorithms
/HowManyNumbersAreSmallerThantheCurrentNumber/test_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py
880
3.78125
4
import unittest import pytest from How_Many_Numbers_Are_Smaller_Than_the_Current_Number import smallerNumbersThanCurrent # python -m unittest test_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py class TestHowManySmaller(unittest.TestCase): def check_if_list_contain_only_integers(self): with self.assertRaises(TypeError): smallerNumbersThanCurrent(['3']) def check_if_list_is_not_empty(self): with self.assertRaises(IndexError): smallerNumbersThanCurrent([]) test_data = [ ([8, 1, 2, 2, 3], [4, 0, 1, 1, 3]), ([7, 7, 7, 7], [0, 0, 0, 0]), ([-1, 1, 4, 5], [0, 1, 2, 3]), ([-1, 5, 4, 2], [0, 3, 2, 1]), ([1], [0]) ] @pytest.mark.parametrize("test_input, expected_result", test_data) def testNumbers(test_input, expected_result): assert smallerNumbersThanCurrent(test_input) == expected_result
df877335e12653465f920c796b0539dfd640a015
ojenksdev/python_crash_course
/chapt_10/remember_me.py
1,052
3.96875
4
import json def get_stored_username(): """Retrieves the username from a file""" filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): """Gets a new username if one doesn't exist""" username = input("What is your name? - ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def greet_user(): """Greet the user by name""" username = get_stored_username() verify_user = input("Is " + username + " your username? (yes/no) ") if verify_user == "no": username = get_new_username() print("We'll remember you when you come back " + username + "!") elif username: print("Welcome back " + username + "!") else: username = get_new_username() print("We'll remember you when you come back " + username + "!") greet_user()
517f962e1117511ea4c41baf5e9af4f131bf191c
Frederik-N/projecteuler
/problem23.py
2,476
4.09375
4
# Problem 23 - Non-abundant sums # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. # For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. # As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. # By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. # However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number # that cannot be expressed as the sum of two abundant numbers is less than this limit. # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. import math def abundantNumbers(): abundantdivisors = [] for number in range(1, 28123): listofdivisors = [] i = 1 while i <= math.sqrt(number): if(number % i == 0): if(number / i == i): listofdivisors.append(i) else: listofdivisors.append(i) listofdivisors.append(number/i) i = i + 1 if number in listofdivisors: listofdivisors.remove(number) #print(int(sum(listofdivisors)), number) if(int(sum(listofdivisors))>number): abundantdivisors.append(number) # return the list up abundant divisors up to 28123 return abundantdivisors # traverses the abundantnumbers list and checks if there are two numbers in the list that gives n (bottleneck time complexity) def isSumOfTwoAbundant(n, abundantNumbers): l = 0 r = len(abundantNumbers)-1 while(l<=r): if(abundantNumbers[l] + abundantNumbers[r] == n): return 1 elif(abundantNumbers[l] + abundantNumbers[r] < n): l += 1 else: r -= 1 return 0 # Iterate through all numbers up to 28123 and check if it can be made from adding two abundant divisors from the list given by abundantNumber() abundantNumbers = abundantNumbers() result = [] for x in range(1,20162): if not(isSumOfTwoAbundant(x,abundantNumbers)): result.append(x) print(sum(result))
01c2161cbe02c4057c9d9ad7dc0702148d06122e
Pedropostigo/ml
/dataframe.py
3,555
3.625
4
""" functions to manipulate data frames """ import numpy as np import pandas as pd from tqdm import tqdm_notebook as tqdm def feature_inspection(data, unique_vals = 5): """ Function to inspect features of a data frame. Returns a data frame with feature names, type of feature and unique values Parameters: unique_vals -- number of unique values per feature to show in the results Return: """ features = data.columns.values types = [] num_unique_values = [] unique_values = [] num_missing = [] for feat in features: types.append(data[feat].dtype.name) # if feature is categorical, get categories, else get unique values if data[feat].dtype.name == 'category': unique_values.append(list(data[feat].cat.categories)[0:unique_vals]) else: unique_values.append(data[feat].unique()[0:unique_vals]) # if feature is categorical or object, get number of unique values if data[feat].dtype.name == 'category': num_unique_values.append(len(list(data[feat].cat.categories))) else: num_unique_values.append(len(data[feat].unique())) # number of missing values in feature num_missing.append(np.sum(data[feat].isna() * 1)) result = pd.DataFrame({'feature': features, 'type': types, 'num_unique_values': num_unique_values, 'unique_values': unique_values, 'num_missing': num_missing}) return result def reduce_mem_usage(df, progress_bar = True, verbose = True): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 # a progress bar is shown tracking how many features are left if progress_bar: columns = tqdm(df.columns) else: columns = df.columns for col in columns: col_type = df[col].dtype.name if col_type not in ['object', 'category']: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() / 1024**2 if verbose: print(f"Memory usage: start = {np.round(start_mem, 2)}, end = {np.round(end_mem, 2)}, " + \ f"decreased by = {np.round((100 * (start_mem - end_mem) / start_mem),1)} %") return df
79359f5e1a291b5c276f5520886b84fb78802e8e
JGeun/BOJ_Python
/Python_workspace/2900/2908.py
310
3.78125
4
import sys def get_bigger(nums): for i in range(2, -1, -1): if int(nums[0][i]) > int(nums[1][i]): return nums[0] elif int(nums[0][i]) < int(nums[1][i]): return nums[1] return nums[0] nums = sys.stdin.readline().rstrip().split() print(get_bigger(nums)[::-1])
004ba34d4f068c69c32d085326f15274d462ee29
Ponkiruthika112/codeset6
/str_word_rev.py
205
3.609375
4
s=input() j=0 for i in range(0,len(s)): if s[i]==" ": k=s[j:i] j=i+1 print(k[::-1],end=" ") elif i==len(s)-1: k=s[j:i+1] print(k[::-1]) #to print a string
9251527f2636ff1727596fa36d4016a86142facb
davray/lpthw-exercises
/ex11.py
850
4.3125
4
print "How old are you? ", age = raw_input() print "How tall are you? ", height = raw_input() print "How much do you weigh? ", weight = raw_input() print "So, you're %s old, %s tall and you weigh %s." % ( age, height, weight) # Study Drills # 1. Go online and find out what Python's raw_input does. # - raw_input is a built in function that reads a string from standard # input. # 2. Can you find other ways to use it? Try some of the samples you find. # - File: ex11_sd2.py # 3. Write another "form" like this to ask some other questions. # - File: ex11_sd3.py # 4. Related to escape sequences, try to find out why the last line has # '6\'2"' with that \' sequence. See how the single-quote needs to be # escaped because otherwise it would end the string? # - Changed the %r to %s to print the string instead of the raw value
9ef06c9ec5ffd97e669336bd761199436b2c3e7b
isakaaby/fys3150
/read_sol_plot.py
779
3.59375
4
import numpy as np import matplotlib.pyplot as plt infile = open("solution.txt", 'r') N = int(infile.readline()) #Filling the start boundaries x = [0] #grid points v = [0] #tridiagonal solutions u = [0] #analytic solutions for line in infile: numbers = line.split() x.append(float(numbers[0])) v.append(float(numbers[1])) u.append(float(numbers[2])) #Filling the end boundaries x[N] = 1 v[N] = 0 u[N] = 0 x = np.array(x) v = np.array(v) u = np.array(u) ##plotting tridiagonal solutions along with analytic solutions plt.plot(x,v,label = 'v (numerical)') plt.plot(x,u, label = 'u (analytical)') plt.title("Numerical and analytical solutions for N = %d" %(N)) plt.xlabel('x') plt.ylabel('Numerical and analytical solutions') plt.legend() plt.show()
1b35e0f18f0127e576a99c2cd524f715328b2256
MayuriTambe/Programs
/Programs/DataStructures/Tuples/RepeatedElements.py
188
3.65625
4
Data=(22,54,11,66,4,8,55,22,54,8,4) print("The tuple is:",Data) for i in range(0,len(Data)): for j in range(i+1,len(Data)): if Data[i]==Data[j]: print(Data[i])
b02332acc4534dbfc6d15b5d0d0ac796a32a8996
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/rna-transcription/91c3aec13b2e4f059be9b1bfc3b5da54.py
334
3.828125
4
class DNA(): def __init__(self, dna): self.dna = dna def to_rna(self): rna = '' for nucleotide in self.dna: if nucleotide == 'C': rna += 'C' elif nucleotide == 'G': rna += 'G' elif nucleotide == 'A': rna += 'A' elif nucleotide == 'T': rna += 'U' else: return 'Not a nucleotide' return rna
40d2beeb87e714f73d75fb67d998173538adc157
mmcelroy75/snippets
/class_objects/dice.py
406
3.65625
4
from random import randint class Die: def __init__(self, sides=6): self.sides = sides def roll_die(self): self.die_roll = randint(1, self.sides) print(self.die_roll) d4 = Die(4) d6 = Die() d8 = Die(8) d10 = Die(10) d12 = Die(12) d20 = Die(20) ''' for i in range(10): d6.roll_die() for i in range(10): d10.roll_die() for i in range(10): d20.roll_die() '''
ed6ffe0f8e7632854bf1e1af19a1dbcc8ecf7b0e
bpafoshizle/Small-Projects-and-Utils
/TRAGeocoder/TRAGeocoder/GoogleGeocoder.py
1,888
3.671875
4
""" http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet http://stackoverflow.com/questions/5035390/submit-without-the-use-of-a-submit-button-mechanize/6894179#6894179 """ from . import * import requests import json class GoogleGeocoder(object): """ Default init method takes an API key. If none is given Then it reads from an assumed file in an assumed folder. """ def __init__(self, APIKey=None): self.jsonResponse = None if(APIKey == None): self.getAPIKey() else: self.APIKey = APIKey """ Method to extract the Lat and Lon from the JSON """ def getLatLon(self): if(self.jsonResponse == None): raise GeocodeException("No JSON. Have you called geocode() with an address?") else: lat = self.jsonResponse["results"][0]["geometry"]["location"]["lat"] lon = self.jsonResponse["results"][0]["geometry"]["location"]["lng"] return "%s,%s" % (lat, lon) """ Geocode an address """ def geocode(self, address): geoUrl = "https://maps.googleapis.com/maps/api/geocode/json" self.getAPIKey() payload = {'address' : address, 'key' : self.APIKey} r = requests.get(geoUrl, params=payload) self.jsonResponse = r.json() return self.jsonResponse def writeLastResponse(self): with open("Output/lastResponse.json", 'wb') as lastResponse: lastResponse.write(self.jsonResponse) """ Method get the API key from a file and assign it to this object. """ def getAPIKey(self): keyList = self.readAPIKeyFromFile() self.APIKey = keyList[0]["APIKey"] def readAPIKeyFromFile(self): import csv userList = [] with open("Sensitive/apiKey.txt", 'rb') as csvfile: for row in csv.reader(csvfile, delimiter="|"): userDict = {} userDict["UserEmail"] = row[0] userDict["APIKey"] = row[1] userList.append(userDict) return userList if __name__ == '__main__': RLAutomationUnitTests.testAll()
81368d92d8fecb20780fe5a61e9878e12899b5dc
chipmonkey/adventofcode2020
/day1part2/runme.py
3,314
3.71875
4
DEBUG = False class filethingy: values = [] def __init__(self): self.values = [] f = open('input.txt', 'r') for line in f: self.values.append(int(line)) print("input: ", self.values) # class find2020s: # mydata = filethingy() # def getfirstresult(self): # for x in range(len(self.mydata.values)-1): # for y in range(x+1, len(self.mydata.values)): # if DEBUG: # print(x,y, self.mydata.values[x] + self.mydata.values[y]) # if (self.mydata.values[x] + self.mydata.values[y]) == 2020: # print(x, y, self.mydata.values[x], self.mydata.values[y], self.mydata.values[x]*self.mydata.values[y]) # exit() class findN2020s: mydata = filethingy() def __init__(self, n, s): """ find the first n entries in the values list which sum to s """ self.n = n self.s = s self.result = {} print(self.n, self.s) def solve(self): self.result = self.recurseN(self.n, self.s, 0) def multiplyResult(self): total = 1 for item in self.result['solutionValues']: total *= item print("Grand Total: ", total) def recurseN(self, n, s, i): """recursive function that finds n elements which sum to s from a SUBSET of self.mydata.values, namely in the range [i, len(values)] """ print(f"recursed with ({n}, {s}, {i})") # Could make this its own more useful class, but a dict of lists is OK for now solution = {'solutionIndexes': [], 'solutionValues': []} for candidateIndex in range(i, len(self.mydata.values) - n + 1): # Must test for off-by-one errors print(f"Depth: {n} at candidateIndex: {candidateIndex}, with len(values) = {len(self.mydata.values)}") candidate = self.mydata.values[candidateIndex] if n == 1: # Only terminate if we are here if candidate == s: solution['solutionIndexes'] = [candidateIndex] solution['solutionValues'] = [candidate] print(f"yay: {solution}") return(solution) else: continue else: if candidate > s: # Short circuit print ("Nope: {candidate} > {s}") continue else: rMore = self.recurseN(n-1, s-candidate, candidateIndex+1) if rMore: solution['solutionIndexes'].extend(rMore['solutionIndexes']) solution['solutionValues'].extend(rMore['solutionValues']) solution['solutionIndexes'].extend([candidateIndex]) solution['solutionValues'].extend([candidate]) print(f"Solved ({n}, {s}, {i}) with:") print(solution) return(solution) return None # mything = find2020s() # mything.getfirstresult() mything2 = findN2020s(2, 2020) mything2.solve() mything3 = findN2020s(3, 2020) mything3.solve() mything3.multiplyResult()
7c83675e9dfe82255ee9a469facc82a7d6864e3d
NJonas184/CS_portfolio
/CSC 356 Machine Learning/multiclassClassifier.py
2,531
3.78125
4
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import fetch_openml from sklearn.svm import SVC import pickle #Training a multiclass classifier to #recognize numbers from the mnist dataset. def main(): print("Hello World!") #fetching the information mnist = fetch_openml("mnist_784", version=1) #Fetching the data X, y = mnist["data"], mnist["target"] y = y.astype(np.uint8) X = X.to_numpy() #Premptive converting to numpy array #Splitting the data X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:] #The training will be a little different this time, #as a different classifier is being used. #The classifier below is a Support Vector Machine classifier, #which will be talked more about in Chapter 5. svm_clf = SVC() svm_clf.fit(X_train, y_train) #No need to distinguish any numbers like in the binary classifier #A quick demonstration of the classifier someDigit = X[0] someDigitImage = someDigit.reshape(28,28) print(f"The decision function was this: \n {svm_clf.decision_function([someDigit])}") print(f"The prediction is {svm_clf.predict([someDigit])}!") #The decision function will show how much the classifier believes the #image was each number 0 - 9 plt.imshow(someDigitImage, cmap = "binary") plt.axis("off") plt.show() #This example might have used a SVM classifier, but it's entirely #possible to replicate these results using Stochastic Gradient Descent #or RandomForest classifiers #TODO: Try making a mnist classifier using one of the classifiers mentioned above. #All that's left is to plot out the images rows = 5 # number of rows cols = 2 # number of columns axes = [] # list to be plotted fig = plt.figure() for i in range(rows*cols): img = X_test[i] #Grab the image imgReshape = img.reshape(28, 28) # reshape the image axes.append(fig.add_subplot(rows, cols, i+1)) #Place image on 2D array subplot_title= f"{svm_clf.predict([img])}" #Create prediction title axes[-1].set_title(subplot_title) #Add title plt.imshow(imgReshape, cmap = "binary") #plot the image plt.axis("off") fig.tight_layout() #Conform to a specific layout plt.show() #Plot the images #Saving the model using pickle pickle.dump(svm_clf, open("SVMCLF.p", "wb")) #End of main() if __name__ == "__main__": main()
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
35