blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
8ef8684758adf0c7047dd92dd1eaa34f9cb28ed5
yehongyu/acode
/2019/dynamic_programming/minimum_swaps_to_make_sequences_increasing_1016.py
895
3.546875
4
class Solution: """ @param A: an array @param B: an array @return: the minimum number of swaps to make both sequences strictly increasing """ def minSwap(self, A, B): # Write your code here if len(A) != len(B): return -1 n = len(A) swap = [n] * n swap[0] = 1 noswap = [n] * n noswap[0] = 0 for i in range(1, n): if A[i-1] < A[i] and B[i-1] < B[i]: swap[i] = swap[i-1] + 1 noswap[i] = noswap[i-1] if A[i-1] < B[i] and B[i-1] < A[i]: swap[i] = min(swap[i], noswap[i-1] + 1) noswap[i] = min(noswap[i], swap[i-1]) return min(swap[n-1], noswap[n-1]) s = Solution() A = [1,3,5,4] B = [1,2,3,7] A = [2,4,5,7,10] B = [1,3,4,5,9] A = [3,5,6,9,14,15,15,18,17,20] B = [3,4,5,8,10,14,17,16,19,19] print(s.minSwap(A, B))
c1867ca930794c75c86d0395e61e6329364e9d15
jeimynoriega/uip-prog3
/Laboratorios/quiz2.py
605
3.78125
4
#quiz2 descuento1 = 0.35 descuento2 = 0.20 descuento3 = 0.10 comprador = 0 while comprador < 5 ; monto = int(int(input("ingresar monto:")) comprador +=1 if (monto >= 500): subtotal1 = monto * descuento1 total = monto - subtotal1 print("el total es {0}:".format(total)) elif (monto < 500 and monto >= 200): subtotal1 = monto * descuento2 total = monto * subtotal print("el total es {0}:".format(total) elif monto < 200 and monto >= 100 : subtotal = monto * descuento3 total = monto * subtotal print("el total es {0}".format(total) else: print("no hay descuento \n gracias por su compra")
9ecc8f8e161737fac1fa37a78b2c374641999be8
mreishus/aoc
/2021/python2021/aoc/day22_failed2.py
8,945
4.03125
4
#!/usr/bin/env python """ Advent Of Code 2021 Day 22 https://adventofcode.com/2021/day/22 """ from typing import List import re import math from copy import deepcopy def ints(s: str) -> List[int]: return list(map(int, re.findall(r"(?:(?<!\d)-)?\d+", s))) def parse(filename: str): with open(filename) as file: return [parse_line(line.strip()) for line in file.readlines()] def parse_line(line): on = line.startswith("on") [x1, x2, y1, y2, z1, z2] = ints(line) return [on, x1, x2, y1, y2, z1, z2] class Range: def __init__(self, x1, x2, y1, y2, z1, z2, operation): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 self.z1 = z1 self.z2 = z2 self.operation = operation def is_overlap(self, other): # print(f"Isoverlap {self} {other}") x_over = False y_over = False z_over = False if self.x1 <= other.x1 and other.x1 <= self.x2: x_over = True if other.x1 <= self.x1 and self.x1 <= other.x2: x_over = True if not x_over: return False if self.y1 <= other.y1 and other.y1 <= self.y2: y_over = True if other.y1 <= self.y1 and self.y1 <= other.y2: y_over = True if not y_over: return False if self.z1 <= other.z1 and other.z1 <= self.z2: z_over = True if other.z1 <= self.z1 and self.z1 <= other.z2: z_over = True return x_over and y_over and z_over def has_subset(self, other): x_subset = False y_subset = False z_subset = False if self.x1 <= other.x1 and other.x2 <= self.x2: x_subset = True if self.y1 <= other.y1 and other.y2 <= self.y2: y_subset = True if self.z1 <= other.z1 and other.z2 <= self.z2: z_subset = True return x_subset and y_subset and z_subset def has_inverse(self, other): return ( self.x1 == other.x1 and self.x2 == other.x2 and self.y1 == other.y1 and self.y2 == other.y2 and self.z1 == other.z1 and self.z2 == other.z2 and self.operation != other.operation ) def overlap_area(self, other): x_overlap = max(0, min(self.x2 + 1, other.x2 + 1) - max(self.x1, other.x1)) y_overlap = max(0, min(self.y2 + 1, other.y2 + 1) - max(self.y1, other.y1)) z_overlap = max(0, min(self.z2 + 1, other.z2 + 1) - max(self.z1, other.z1)) return x_overlap * y_overlap * z_overlap def clamp(self, other): if not self.is_overlap(other): raise ValueError x1 = max(self.x1, other.x1) x2 = min(self.x2, other.x2) y1 = max(self.y1, other.y1) y2 = min(self.y2, other.y2) z1 = max(self.z1, other.z1) z2 = min(self.z2, other.z2) return Range(x1, x2, y1, y2, z1, z2, self.operation) def area(self): x_size = self.x2 - self.x1 + 1 y_size = self.y2 - self.y1 + 1 z_size = self.z2 - self.z1 + 1 return x_size * y_size * z_size def __repr__(self): return f"[{self.x1}..{self.x2}, {self.y1}..{self.y2}, {self.z1}..{self.z2}]={self.operation}" def __hash__(self): return hash( (self.x1, self.x2, self.y1, self.y2, self.z1, self.z2, self.operation) ) def __eq__(self, other): if not isinstance(other, type(self)): return False return ( self.x1 == other.x1 and self.x2 == other.x2 and self.y1 == other.y1 and self.y2 == other.y2 and self.z1 == other.z1 and self.z2 == other.z2 and self.operation == other.operation ) def compose(lefts, r): rights = [r] operation = r.operation lefts, rights = two_piece_split_x(lefts, rights, not operation) to_add = [] to_remove = set() # print(f"checking against {lefts}") for right in rights: if operation: # CASE: ADD overlap = any(right.is_overlap(l) for l in lefts) if overlap: # Don't count twice pass else: to_add.append(right) else: # CASE: SUBTRACT overlap = any(right.is_overlap(l) for l in lefts) if overlap: # Need to remove this region (right) from the lefts ## Make a copy of the subtract region with operation set to ADD ## So we can find it in a == comparison when removing new = deepcopy(right) new.operation = True to_remove.add(new) print(lefts, to_add, to_remove) return [x for x in lefts + to_add if not x in to_remove] def two_piece_split_x(ls, rs, is_sub): xs = [] for l in ls: if any(l.is_overlap(r) for r in rs): xs.append(l.x1) xs.append(l.x2) for r in rs: if any(r.is_overlap(l) for l in ls): xs.append(r.x1) xs.append(r.x2) ls = split_x(ls, xs, is_sub) rs = split_x(rs, xs, is_sub) ys = [] for l in ls: if any(l.is_overlap(r) for r in rs): ys.append(l.y1) ys.append(l.y2) for r in rs: if any(r.is_overlap(l) for l in ls): ys.append(r.y1) ys.append(r.y2) ls = split_y(ls, ys, is_sub) rs = split_y(rs, ys, is_sub) zs = [] for l in ls: if any(l.is_overlap(r) for r in rs): zs.append(l.z1) zs.append(l.z2) for r in rs: if any(r.is_overlap(l) for l in ls): zs.append(r.z1) zs.append(r.z2) ls = split_z(ls, zs, is_sub) rs = split_z(rs, zs, is_sub) return ls, rs def split_x(regions, xs, is_subtracting): xs = sorted(xs) for x in xs: new_regions = [] for r in regions: if r.x1 < x and x < r.x2: new1 = deepcopy(r) new2 = deepcopy(r) if is_subtracting: new1.x2 = x - 1 new2.x1 = x else: new1.x2 = x new2.x1 = x + 1 new_regions.append(new1) new_regions.append(new2) else: new_regions.append(r) regions = new_regions return regions def split_y(regions, ys, is_subtracting): ys = sorted(ys) for y in ys: new_regions = [] for r in regions: if r.y1 < y and y < r.y2: new1 = deepcopy(r) new2 = deepcopy(r) if is_subtracting: new1.y2 = y - 1 new2.y1 = y else: new1.y2 = y new2.y1 = y + 1 new_regions.append(new1) new_regions.append(new2) else: new_regions.append(r) regions = new_regions return regions def split_z(regions, zs, is_subtracting): zs = sorted(zs) for z in zs: new_regions = [] for r in regions: if r.z1 < z and z < r.z2: new1 = deepcopy(r) new2 = deepcopy(r) if is_subtracting: new1.z2 = z - 1 new2.z1 = z else: new1.z2 = z new2.z1 = z + 1 new_regions.append(new1) new_regions.append(new2) else: new_regions.append(r) regions = new_regions return regions def rangesum(regions): area = 0 for r in regions: area += r.area() return area class Day22: """ AoC 2021 Day 22 """ @staticmethod def part1(filename: str) -> int: """ Given a filename, solve 2021 day 22 part 1 """ print("") data = parse(filename) look = Range(-50, 50, -50, 50, -50, 50, False) ## Build ranges and clamp to 50 ranges = [] for operation, x1, x2, y1, y2, z1, z2 in data: r = Range(x1, x2, y1, y2, z1, z2, operation) if look.is_overlap(r): ranges.append(r) # print("total area dumb:") # print(rangesum(ranges)) processed = [ranges.pop(0)] print(rangesum(processed)) for r in ranges: processed = compose(processed, r) print(rangesum(processed)) # print("Done processing:") # print(processed) print("total area smart:") print(rangesum(processed)) return -1 @staticmethod def part2(filename: str) -> int: return -1 if __name__ == "__main__": print("2021 Day 22 Part 1:", end=" ") print(Day22.part1("../inputs/22/input_small2.txt"))
7f57b2e7530c7722fa63160d95b47ecbad160866
imaimon1/Learn-Python-the-Hard-Way
/ex42.py
763
3.71875
4
class Animal(object): pass ##is a class Dog(Animal): def __init__(self,name): ## has a self.name = name class Cat(Animal): def __init__(self, name): ##has a self.name = name class Person(object): def __init__(self,name): ##has a self.name = name self.pet= None ##isa class Employee(Person): def __init__(self,name,salary): super(Employee,self).__init__(name) self.salary=salary class Fish(object): pass class Salmon(Fish): pass class Salmon(Fish): pass class Halibut(Fish): pass Rover= Dog("rover") Satan = Cat("satan") mary= Person("Mary") mary.pet = Satan frank = Employee("Frank",1200000) frank.pet = Rover flipper = Fish() crouse = Salmon() harry = Halibut()
01e2a37f2f681d7892df5b7311704530b33a5a78
Basilio0505/CS_303E-Assignments
/SelectionSort.py
361
3.65625
4
def selectSort(alist): for x in range(0,len(alist)): temp = alist[x] for y in range(x,len(alist)): if temp > alist[y]: temp = alist[y] alist[y] = alist[x] alist[x] = temp def main(): mylist = [24,6,54,45,67,82,10] selectSort(mylist) print(mylist) main()
b8c09a24728d84ec2e2fbbfc19abbdc3f1284db9
ShreeyaVK/Python_scripts
/random_numbers.py
1,334
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 25 12:28:24 2017 @author: Sadhna Kathuria """ ## generate random numbers import numpy as np #random number between 1 and 100 print np.random.randint(1,100) #random number between 0 and 1 print np.random.random() #function for generating multiple random numbers def randint_range(n,a,b): x=[] for i in range(n): x.append(np.random.randint(a,b)) return x print randint_range(10,1,45) # generate random numbers in the range 0 to 100 that are multiples of 4 import random for i in range(3): print random.randrange(0,100,4) ## note that the first number will always be zero /10/100 #shuffle a list a=range(20) np.random.shuffle(a) print a #choose a random value from a list import pandas as pd path = 'C:/Users/Sadhna Kathuria/Documents/Shreeya_Programming/Predictive/Chapter 2' filename1 = 'Customer Churn Model.txt' fullpath = path + '/' + filename1 data = pd.read_csv(fullpath) column_names = data.columns.values.tolist() print np.random.choice(column_names) #generate the same random numbers using seed p=[] np.random.seed(1) for i in range(5): p.append(np.random.randint(1,10)) print p q=[] for i in range(5): q.append(np.random.randint(1,10)) print q r=[] np.random.seed(1) for i in range(5): r.append(np.random.randint(1,10)) print r
7c3b34189aebe769f5bfa6880d0326a7db5702b9
skoolofcode/SKoolOfCode
/TrailBlazers/Prisha/Practice/httyd.py
18,241
3.671875
4
twoOne = 10 TwoTwo = 11 TwoThree=12 TwoFour = 13 TwoFive = 14 TwoSix = 15 TwoSeven = 16 TwoOneOne =17 TwoOneTwo = 18 TwoTwoOne = 19 TwoTwoTwo = 20 TwoTwoThree = 21 TwoThreeOne = 22 TwoThreeTwo = 23 TwoThreeThree=24 TwoThreeFour=25 TwoFourOne = 26 TwoFourTwo = 27 TwoFiveOne=28 TwoFiveTwo=29 TwoSixOne=30 TwoSixTwo = 31 TwoSevenOne = 32 TwoSevenTwo = 33 TwoFourThree = 34 print ("Dragon discriptions and all reashearch was done on: howtotrainyourdragon.wikia.com/wiki/") def intro (): print ("------Start----") print ("in this quiz i will ask you some questions and in the end i will tell you the httyd that fits you based on your personality") name=input (print("what is your name")) def Questions(): print ( "-------Question One-------") print (" which dragon class do you most prefer???") print (" 1.Stoker:Stoker Class dragons are hot-headed fire breathers") print (" 2.Strike:Strike Class dragons are characterized by their blazing speed, vice-like jaw strength, and extreme intelligence. ") print (" 3.Mystery:Little is known about the Mystery Class dragons due to how stealthy and sneaky they are or how they work.") print (" 4.Tracker:Tracker Class dragons have a highly acute sense of smell or taste that enables them to track down and find things.") print (" 5.Boulder:Boulder Class dragons are tough and are associated with the earth") print (" 6.Sharp:Sharp Class dragons are vain and prideful, and they all possess sharp body parts.") print (" 7.Tidal:Tidal Class dragons live in or near the ocean") global answerOne answerOne = int (input ("enter a number 1-7")) def QuestionTwo (answerOne): global twoOne if answerOne == 1: print ("------Question Two-----") print (" which size dragon do you want, NOTE: small dragons are not rideable thus not in this quiz ") print ("1. Medium") print ("2. Large") twoOne = int (input ("enter a number 1-2")) if answerOne == 2: print ("------Question Two-----") print (" whih real life animal attracts you the most") print ("1.Scorpion") print ("2.Black Panthers") print ("3.Electric eels") global TwoTwo TwoTwo = int (input ("enter a number 1-3")) if answerOne == 3: print ("------Question Two----") print (" what so you want your dragons other special ability to be") print ("1. A Magnetic Body") print ("2. The ability to mimic fire") print ("3. Camaflouge") print ("4. a song that lures prey") global TwoThree TwoThree = int (input("enter a number 1-4")) if answerOne == 4: print ("------Question Two-----") print (" what fire type do you prefer") print (" 1.magnesium blast") print (" 2.Greenish fire") print (" 3.Flaming rock missles") global TwoFour TwoFour = int (input ("enter a number 1-3")) if answerOne == 5 : print ("------Question Two-----") print ("how commom do you want your dragon to be ") print ("1.commom") print ("2.very rare") global TwoFive TwoFive = int (input ("enter a number 1-3")) if answerOne == 6: print ("------Question Two-----") print ("what weakness do you want your dragon to have") print ("1.underbelly/belly is vunerable") print ("2.No Legs") global TwoSix TwoSix = int (input ("enter a number 1-2")) if answerOne == 7: print ("------Question Two-----") print ("what should yur dragon eat") print ("1.fish/crab") print ("2.Smaller tidal class dragons") global TwoSeven TwoSeven = int (input ("enter a number 1-2")) def QuestionThreeStoker (twoOne): if twoOne== 1: print ("------Question Three-----") print ("What do you want your dragons special ability to be") print ("1.ability to change color depending one his/hers mood") print ("2.lighting itself on fire") global TwoOneOne TwoOneOne = int (input ("enter a number 1-2")) if twoOne ==2: print ("------Question Three-----") print ("what should your dragon eat") print ("1. eels") print ("2. Ice Tail Pike, a type of fish") global TwoOneTwo TwoOneTwo = int (input ("enter a number 1-2")) def QuestionThreeStrike (TwoTwo): if TwoTwo == 1: print ("------Question Three-----") print ("what color do you prefer") print ("1.Orange") print ("2.Black") global TwoTwoOne TwoTwoOne = int (input("enter a number 1-2")) if TwoTwo == 2: print ("------Question Three-----") print ("which ability do you want your dragon to have") print ("1.Ecolocation") print ("2.Electrokenisis") global TwoTwoTwo TwoTwoTwo = int (input("enter a number 1-2")) if TwoTwo ==3: print ("------Question Three-----") print ("What do you want your dragons weakness to be") print ("1.water") print ("2.Dragon Root having a longer effect tahn usual") global TwoTwoThree TwoTwoThree = int (input ("enter a number 1-2")) def QuestionThreeMystery (TwoThree): if TwoThree == 1: print ("------Question Three-----") print ("what natural dragon habitat do you think is best") print ("1.Caves") print ("2.Caverns") global TwoThreeOne TwoThreeOne = int (input("enter a number 1-2")) if TwoThree == 2: print ("------Question Three-----") print ("Do you want your dragon to be a ") print ("1.Lone Survivor") print ("2. A memmber of a dragon pack ") global TwoThreeTwo TwoThreeTwo = int (input("enter a number 1-2")) if TwoThree == 3: print ("------Question Three-----") print ("what size") print("1.Large") print("2.Medium") global TwoThreeThree TwoThreeThree = int (input("enter a number 1-2")) if TwoThree == 4: print ("------Question Three-----") print ("which real life animal do you prefer") print ("1.Butterfly") print ("2.Bison") global TwoThreeFour TwoThreeFour = int (input("enter a number 1-2")) def QuestionThreeTracker (TwoFour): if TwoFour == 1 : print ("------Question Three-----") print ("Which animal do you prefer") print ("1.Jewel Beetle") print ("2.Birds") global TwoFourOne TwoFourOne = int (input ("enter a number 1-2")) if TwoFour == 2: print ("-------Question Three-----") print ("Do you want your dragon to be a expert at") print ("1.Stampeding") print ("2.Running (enhanced Speed)") global TwoFourTwo TwoFourTwo = int (input("enter a number 1-2")) if TwoFour ==3: print ("-------Question Three-----") print("Do you want your dragon to be abe to...") print ("1.lift a lot of weight") print ("2.be able to lift just one rider") global TwoFourThree TwoFourThree = int (input("enter a number 1-2")) def QuestionThreeBoulder (TwoFive): if TwoFive == 1: print ("-------Question Three-----") print("what do you want your dragons natural nature to be") print ("1.Reclusive at first but Loyal when they get to know you") print ("2.Friendly to anyone, unless they know you are a threat") global TwoFiveOne TwoFiveOne = int (input("enter a number 1-2")) if TwoFive == 2: print ("-------Question Three-----") print ("what color do you want your dragon to be") print ("1.Reddish Brown") print ("2.Grey and green") global TwoFiveTwo TwoFiveTwo = int (input ("enter a number 1-2")) def QuestionThreeSharp (TwoSix): if TwoSix == 1: print ("-------Question Three-----") print ("do you want your dragons design to be") print ("1.Inspired off multiple other dragon species") print ("2.or a dinosaur (baryonyx)") global TwoSixOne TwoSixOne = int(input("enter a number 1-2")) if TwoSix == 2: print ("-------Question Three-----") print ("what color do you want your dragon to be") print ("1.Woody brown with a lighter underbelly") print ("2.Silver") global TwoSixTwo TwoSixTwo = int (input ("enter a number 1-2")) def QuestionThreeTidal (TwoSix): if TwoSeven == 1: print ("------Question Three-------") print ("what color do you want your dragon to be") print ("1.Blue") print ("2.Purple") global TwoSevenOne TwoSevenOne = int (input("enter a number 1-2")) if TwoSeven ==2 : print ("-------Question Three-----") print ("what feature do you want your dragon to have") print ("1.Expandable Mouth") print ("2.Two Pairs of wings") global TwoSevenTwo TwoSevenTwo = int (input("enter a number 1-2")) def AnswerStoker (TwoOneOne,TwoOneTwo): if TwoOneOne == 1: print("------Answer-----") print ("YOU GOT A .....HobbleGrunt") print ("More sensitive than most other Stoker Class Dragons, it changes color depending on its mood: ") print ("Yellown means happy, purple means curious, and red means... RUN!The Hobblegrunt will take on anything its opponent dishes out in combat, and then will dish it right back! ") if TwoOneOne == 2: print("------Answer-----") print ("YOU GOT A.....Monstrous Nightmare") print("The Monstrous Nightmare is a Stoker Class dragon, considered to be one of the most aggressive, powerful, and stubborn species of dragons known to Vikings.") if TwoOneTwo == 1: print("------Answer-----") print ("YOU GOT A.....Typhoomerang") print ("Famously over-dramatic, this insecure Stoker Class Dragon is known for a spinning Flaming Cyclone maneuver in battle.... ") print("and courtship! The Typhoomerang whirls into action and defeats foes by breathing streams of fire. ") if TwoOneTwo == 2: print("------Answer-----") Print ("YOU GOT A.....Singetail") print ("Fiercely territorial, Singetails don't just breathe fire—they send it blasting out of their jaws, gills and tails.") def AnswerStrike (TwoTwoOne,TwoTwoTwo,TwoTwoThree): if TwoTwoOne == 1: print("------Answer-----") print ("YOU GOT A.... Triple Stryke") print ("This giant Strike Class Dragon's three tails can slash through its enemies or snake around its prey. When confronted by one, the best thing to do is turn tail and run!") if TwoTwoOne == 2: print("------Answer-----") print ("YOU GOT A.... Triple Stryke") print ("This giant Strike Class Dragon's three tails can slash through its enemies or snake around its prey. When confronted by one, the best thing to do is turn tail and run!") if TwoTwoTwo == 1: print("------Answer------") print ("YOU GOT A..... Night Fury") print ("Speed: Unknown. Size: Unknown. The unholy offspring of lightning and death itself. Never engage this Dragon. Your only chance, hide and pray it does not find you.") if TwoTwoTwo == 2: print ("------Answer-----") print ("YOU GOT A.... Skrill") print ("This elusive creature is highly secretive, it is known to ride lightning bolts. Found only during electrical storms that can shoot bursts of white fire.") if TwoTwoThree == 1: print ("------Answer-----") print ("YOU GOT A.... Skrill") print ("This elusive creature is highly secretive, it is known to ride lightning bolts. Found only during electrical storms that can shoot bursts of white fire.") if TwoTwoThree == 2: print("------Answer------") print ("YOU GOT A..... Night Fury") print ("Speed: Unknown. Size: Unknown. The unholy offspring of lightning and death itself. Never engage this Dragon. Your only chance, hide and pray it does not find you.") def AnswerMystery (TwoThreeOne,TwoThreeTwo,TwoThreeThree,TwoThreeFour): if TwoThreeOne == 1: print("-----Answer-----") print ("YOU GOT A..... ArmorWing") print ("With its welding torch-like flames and chain-whip tail the Armor Wing keeps enemies at bay long enough") print ("or it to attract new scraps of metal to its magnetic body and fuse them into an ever-expanding coat of armor.") if TwoThreeOne == 2: print ("------Answer-----") print ("YOU GOT A .....Hideous Zippleback") print ("Gas + Spark = BOOM! This tricky and evasive 2-headed Mystery Class Dragon is double trouble .") if TwoThreeTwo == 1: print ("-------Answer-----") print ("YOU GOT A.....Boneknapper") print ("Even the toughest of dragons need protecting every now and then. ") if TwoThreeTwo == 2: print ("-------Answer-----") print ("YOU GOT A.....Dramillion") print ("Although normally withdrawn and wary of humans, Dramillions mimic the fire blast of any dragon they encounter. ") if TwoThreeThree == 1: print ("------Answer-------") print ("YOU GOT A.....Snaptrapper") print ("While as beautiful and serene as an exotic flower upon first blush, ") print("the four-headed Snaptrapper is actually one of the most insidious and deadly dragons ever discovered.") if TwoThreeThree == 2: print ("-------Answer-------") print ("YOU GOT A...... Changewing") print ("This Mystery Class elusive expert in camouflage can shoot hot corrosive acid that can burn through wood and rock (and Vikings!).") if TwoThreeFour == 1: print ("-------Answer------") print ("YOU GOT A.....Death Song") print ("The Death Song is a Mystery Class dragon It is regarded as one of the deadliest and most beautiful species of dragon,") if TwoThreeFour == 2: print ("------Answer------") print ("YOU GOT A.....Buffalord") print ("Although it's been hunted to near extinction, the benevolent Buffalord holds the only cure to the lethal disease known as The Scourge of Odin.") def TrackerAnswer (TwoFourOne,TwoFourTwo,TwoFourThree): if TwoFourOne == 1: print("-----Answer-----") print ("YOU GOT A..... Runblehorn") print ("A Rumblehorn’s nose knows! From the Tracker Class, it can follow the faintest scent anywhere") if TwoFourOne == 2: print ("------Answer-----") print ("YOU GOT A .....Deadly Nadder") print ("The Deadly Nadder is a Tracker Class (formerly Sharp Class) dragon, which is said to be one of the most beautiful dragon ") print ("It is well known for its venomous and painful spines") if TwoFourTwo == 1: print ("-------Answer-----") print ("YOU GOT A.....Thunderclaw") print ("Members of this Tracker Class breed form running, rumbling herds very easily. ") if TwoFourTwo == 2: print ("-------Answer-----") print ("YOU GOT A.....Deadly Nadder") print ("The Deadly Nadder is a Tracker Class (formerly Sharp Class) dragon, which is said to be one of the most beautiful dragon ") print ("It is well known for its venomous and painful spines") if TwoFourThree == 1: print ("------Answer-------") print ("YOU GOT A..... Runblehorn") print ("A Rumblehorn’s nose knows! From the Tracker Class, it can follow the faintest scent anywhere") if TwoFourThree == 2: print ("-------Answer-------") print ("YOU GOT A.....Thunderclaw") print ("Members of this Tracker Class breed form running, rumbling herds very easily. ") def BoulderAnswers (TwoFiveOne,TwoFiveTwo): if TwoFiveOne == 1: print ("-------Answer------") print ("YOU GOT A....Catastrophic Quaken") print ("The Catastrophic Quaken can smash into the ground and create huge shockwaves that can knock dragons out air.") if TwoFiveOne == 2: print ("-------Answer------") print ("YOU GOT A....Gronckle") print ("With its bulbous shape, tiny wings and laid-back demeanor, the wart hoggish Gronckle is proving to be a fan favorite.") if TwoFiveTwo == 1: print ("------Answer-----") print ("YOU GOT A...HotBurple") print ("The Hotburple can be a hot mess. Literally! A louder, fussier and lazier Boulder Class cousin to the Gronckle. A nap is never too far away.") print ("The slow Hotburple is anything but lazy when it comes to battle. Opponents will have trouble getting out of its way! ") if TwoFiveTwo == 2: print ("------Answer-----") print ("YOU GOT A....Sentinel") print ("Although Sightless the Sentinels Keep a close watch over the isle of Vanahiem.Often mistaken for stone statues the sentinels stay still while allowing dragons enter Vanahiem") print ("But the second they sense an intruders presence they use their multiple abilites such as sonic screeches and the ability to counter most dragon") print ("attacks to save their home") def SharpAnswer (TwoSixOne,TwoSixTwo): if TwoSixOne == 1: print ("------Answer-----") print ("YOU GOT A....Timberjack ") print ("Timberjack. This gigantic creature has razor sharp wings that can slice through full grown trees. Extremely dangerous") if TwoSixOne == 2: print ("------Answer-----") print ("YOU GOT A....Razorwhip") print ("Razorwhip. Sharp Class dragon. Long, spiny, barbed tail. Very aggressive. Very dangerous. It can use its tail to wrap around a victim ") print ("and literally squeeze the life out of them. Unless it's in a hurry. Then it just slices you in half.") if TwoSixTwo == 1: print ("------Answer-----") print ("YOU GOT A....Timberjack ") print ("Timberjack. This gigantic creature has razor sharp wings that can slice through full grown trees. Extremely dangerous") if TwoSixTwo == 2: print ("------Answer-----") print ("YOU GOT A....Razorwhip") print ("Razorwhip.Sharp Class dragon. Long, spiny, barbed tail. Very aggressive. Very dangerous. It can use its tail to wrap around a victim ") print ("and literally squeeze the life out of them. Unless it's in a hurry. Then it just slices you in half.") def TidalAnswer (TwoSevenOne,TwoSevenTwo): if TwoSevenOne == 1: print ("------Answer------") print ("YOU GOT A....Thunderdrum") print ("When startled, the Thunderdrum will produce a concussive sound wave that can kill a man at close range. Extremely dangerous,") if TwoSevenOne == 2: print ("------Answer------") print ("YOU GOT A....Thunderdrum") print ("When startled, the Thunderdrum will produce a concussive sound wave that can kill a man at close range. Extremely dangerous,") if TwoSevenTwo == 1: print ("------Answer------") print ("YOU GOT A....Thunderdrum") print ("When startled, the Thunderdrum will produce a concussive sound wave that can kill a man at close range. Extremely dangerous,") if TwoSevenTwo == 2: print ("------Answer------") print ("YOU GOT A....Thunderdrum") print ("When startled, the Thunderdrum will produce a concussive sound wave that can kill a man at close range. Extremely dangerous,") intro () Questions() QuestionTwo(answerOne) QuestionThreeStoker(twoOne) QuestionThreeStrike (TwoTwo) QuestionThreeMystery (TwoThree) QuestionThreeTracker (TwoFour) QuestionThreeBoulder (TwoFive) QuestionThreeSharp (TwoSix) QuestionThreeTidal(TwoSeven) AnswerStoker (TwoOneOne,TwoOneTwo) AnswerStrike(TwoTwoOne,TwoTwoTwo,TwoTwoThree) AnswerMystery(TwoThreeOne,TwoThreeTwo,TwoThreeThree,TwoThreeFour) TrackerAnswer (TwoFourOne,TwoFourTwo,TwoFourThree) BoulderAnswers (TwoFiveOne,TwoFiveTwo) SharpAnswer (TwoSixOne,TwoSixTwo) TidalAnswer (TwoSevenOne,TwoSevenTwo)
d24d2024851e7c8e34cff86db00bbfec15851c18
doaa-altarawy/molssi_api_flask
/tests/pyMongo_test.py
1,759
3.8125
4
from pymongo import MongoClient client = MongoClient('localhost', 27017) # defaults # same as client = MongoClient('mongodb://localhost:27017') # By specifying this database name and saving data to it, # you create the database automatically. db = client.pymongo_test # or the dictionary-like access #db = client['pymongo_test'] # Collections and documents are akin to SQL tables and rows posts = db.posts def insert_one(): post_data = { 'title': 'Python and MongoDB', 'content': 'PyMongo is fun', 'author': 'Scott' } result = posts.insert_one(post_data) print('One post: {0}'.format(result.inserted_id)) def insert_multiple(): # Insert multiple post_1 = { 'title': 'Python and MongoDB', 'content': 'PyMongo is fun, you guys', 'author': 'Scott' } post_2 = { 'title': 'Virtual Environments', 'content': 'Use virtual environments, you guys', 'author': 'Scott' } post_3 = { 'title': 'zzzzzzzzLearning Python', 'content': 'Learn Python, it is easy', 'author': 'Bill' } new_result = posts.insert_many([post_1, post_2, post_3]) print('Multiple posts: {0}'.format(new_result.inserted_ids)) # Queries: # -------- def find_one(): bills_post = posts.find_one({'author': 'Bill'}) print('===== One Bill: ', bills_post) def find_many(): scotts_posts = posts.find({'author': 'Scott'}) print(scotts_posts) for post in scotts_posts: print(post) def print_all(): # All posts: all_posts = posts.find() print('-------- All Posts -----------: ', all_posts.count()) for post in all_posts: print(post) insert_one() insert_multiple() find_one() find_many() print_all()
7c8a5362d886ca893627d5b59a7075a0affb7e3c
piggymei/mycode
/nasa01/downloadimage.py
843
3.515625
4
import requests import wget datepic = input("what date do you like for the image? (YYYY-MM-DD) ") resolution = input("would you like the image in High definition or standard definition?(High or Standard) ").lower() API_KEY = "8EWWTP0IkiMrdVGucP6AOEMJsviwqjbPzHZ3zqLr" url = "https://api.nasa.gov/planetary/apod?date=" + datepic +"&api_key=" + API_KEY r = requests.get(url) resp = r.json() #print(resp) dateofpicture = resp["date"] titleofpicture = resp["title"] descriptionofpicture = ["explanation"] pic_url = resp["url"] pic_hurl = resp["hdurl"] if resolution == "high": wget.download(pic_hurl, 'dateofpicturehigh.jpg') wget.download("https://www.chanel.com/images/t_fashionzoom1/f_jpg/classic-handbag-black-velvet-gold-tone-metal-velvet-gold-tone-metal-packshot-default-as1939b0339894305-8826166935582.jpg") else: wget.download(pic_url, 'dateofpicture.jpg')
88307d6148e43e0bc82e8746409a55ad2e774061
JeevanMahesha/python_program
/Data_Structure/LinkedList/linked_list.py
662
3.796875
4
class Node: def __init__(self,val=None): self.DataValue = val self.NextValue = None class LinkedList(): def __init__(self): self.HeadValue = None def listprint(self): printval = self.HeadValue while printval is not None: print (printval.DataValue) printval = printval.NextValue if __name__ == "__main__": LinkedListObject = LinkedList() LinkedListObject.HeadValue = Node('Monday') obj1 = Node('Tuesday') obj2 = Node('Wednesday') LinkedListObject.HeadValue.NextValue = obj1 obj1.NextValue = obj2 LinkedListObject.listprint()
bc8321aa33f1be0a2ac129cb69816be66a1e8ee3
eden-r/iskills-python
/pig_latin_translator.py
994
4.125
4
def pigLatinTranslator(word): """ This function takes a word as its input and returns a version of the word translated into Pig Latin. It does not work on words that contain numbers or are only one character long. """ vowels = "aeiouAEIOU" word = str(word) if not word.isalpha(): return "Please submit a single word." elif len(word) < 2: return "Please submit a longer word." else: if word[0] in vowels: return word + "yay" for letter in word: word = word[1:] + word[0] if word[0] in vowels: return word + "ay" return word[1:] + word[0] + "ay" wordsToTranslate = ['example', 'school', 'question', 'fig', 'answer', 'computer', 'examine', 'shred', 'why', 'a word', 'the', 'I', 24601] for englishWord in wordsToTranslate: pigLatinWord = pigLatinTranslator(englishWord) print("Input Word: \"{}\" \t Returns: \"{}\"".format(englishWord, pigLatinWord))
46d13e41b151a2edbf2f49043caf11eacd1f28af
shubhamthorat07/Python-Dictionaries
/dict.py
526
4.03125
4
d = {"Movie" : "Titanic", "Genre" : "Romance", "Hours": "210mins", "Budget": "$200m"} print(d) d["Actor"] = "Leonardo Di Caprio" print(d) d["Actress"] = "Kate Winslet" print(d) print(d["Movie"]) print(d["Budget"]) print(d.get("Genre")) print(d.get("Movie")) for x in d: print(x) for key in d: print(key,d[key]) print(d.keys()) print(d.values()) print(d.items()) r = d.pop("Genre") print(d) print(d,r) r1 = d.popitem() print(d) d.clear() print(d)
67c5f72068ca3a2e0059298c95cf7e6c757d74df
roysegal11/Python
/While/Grades.py
218
3.8125
4
grade = int(input("Input grade: ")) sum = 0 count = 0 while grade >= 0 and grade <= 100: if grade >= 60: sum = sum + grade count += 1 grade = int(input("Input grade: ")) print(count) print (sum)
8ace3168e1d5c94791cc36202e67f522186fe4bd
atenudel/483hw
/mycode.py
1,491
3.71875
4
#Art Tenorio #CISC483 import csv import numpy as np import pandas as pd #simply edit the path to load the file at your convenience... df = pd.read_csv("/home/art/Downloads/data.csv", skiprows=0) #dataset attr names would mess up without this df.columns=df.columns.str.strip() #had to rename the class attribute, since class is a keyword somewhere in python df.rename(columns={'class' : 'classmoney'}, inplace=True) df.columns=df.columns.str.strip() #print(df.columns) #print(df.head(10)) print(df.dtypes) print("Not all columns are numerical, so they must be converted.\n") #convert sex to binary values. Makes sex to int64 type sex = {'Male' : 0, 'Female': 1} df.sex = [sex[item] for item in df.sex] #convert classmoney object to int64 in binary money = {'<=50K' : 0, '>50K' : 1} df.classmoney = [money[item] for item in df.classmoney] print(df.head(8)) #next, convert race to integer, based on classmoney attr value df.loc[df.classmoney == 0, ['race']] = 0 df.loc[df.classmoney == 1, ['race']] = 1 print(df.dtypes) print("finally all the columns for the matrices are numerical.\n") #finally, we want the covariance and correlation matrices #using: age, education-num,race,sex,capital-gain,capital-loss, #hours-per-week, class newdf = df[['age','education-num','race','sex','capital-gain', 'capital-loss','hours-per-week','classmoney']].copy() print('COVARIANCE MATRIX:') cov = newdf.cov() print(cov) print('\n') print('CORRELATION MATRIX:') corr = newdf.corr() print(corr) print('\n')
93d34f8297ab344863b05c40ada896259e8f1b13
sankhaMukherjee/mlPipes1
/kfpReusableComponents/readData/program.py
780
3.578125
4
import os def main(): pwd = os.path.dirname(os.path.realpath(__file__)) print(f'The current folder = {pwd}\n') print('+---------------------------------') print('| Folder Contents') print('+---------------------------------') files = os.listdir('.') for f in files: if os.path.isdir(f): print(f' [folder] {f}') else: print(f'[file] {f}') if os.path.exists( 'data/test.txt' ): print('+---------------------------------') print('| Contents of the file data/test.txt') print('+---------------------------------') with open('data/test.txt') as f: for l in f: print(l, end='') return if __name__ == '__main__': main()
f328ed3fdef0fc497d1fc148b6e6135ecd87e7c9
Offliners/Python_Practice
/code/216.py
346
4.03125
4
# is the number an armstrong number? # example: 153 is. # 153 = 1^3 + 5^3 + 3^3 # 3 is the length of the number def is_armstrong(n): pwr = len(str(n)) s = sum([int(x) ** pwr for x in str(n)]) return s == n print(is_armstrong(153)) # Yes print(is_armstrong(154)) # No print(is_armstrong(1634)) # Yes # Output: # True # False # True
54adc6a99bb40da64d2c93f4b3587a25c6e49c3d
Jiangyiyi1028/Project
/Animal.py
1,370
4.09375
4
# _*_ coding: utf-8 _*_ # @Time : 2021/1/23 0023 下午 16:55 # @Author : jiangyiyi # 比如创建一个类(Animal)【动物类】,类里有属性(名称,颜色,年龄,性别),类方法(会叫,会跑) # 创建子类【猫】,继承【动物类】, # 重写父类的__init__方法,继承父类的属性, # 添加一个新的属性,毛发 = 短毛, # 添加一个新的方法, 会捉老鼠, # 重写父类的【会叫】的方法,改成【喵喵叫】 class Animal: # 属性 name = 'Alice' colour = 'orange' age = 3 gender = 'female' def __init__(self): self.leg = '小短腿' # 方法 def call(self): print('我会叫') def run(self): print('我会跑') class Cat(Animal): def __init__(self): self.hair = '短毛' def catch(self): print('会捉老鼠') def call(self): # Animal().call() # 调用父类 super(Cat, self).call() print('喵喵叫') if __name__ == '__main__': cat_animal = Animal() # Cat_Animal = Cat() # cat_animal.call() # cat_animal.run() print('我的名字:',cat_animal.name) print('我的年龄:',cat_animal.age) print('我喜欢的颜色:',cat_animal.colour) print('我的性别:',cat_animal.gender) # Cat_Animal.catch() # Cat_Animal.call()
388cc665bc3470825ba2d5621b3161e084a28667
othaderek/DnA
/matrixElementSum.py
796
3.703125
4
def matrixElementsSum(matrix): # loop over each array simlutaneously # add numbers not underneath a zero # as soon as I see a zero i rule out the rest everything underneath it matrixSum = 0 l_to_r = 0 t_to_b = 0 while l_to_r < len(matrix[0]): while t_to_b < len(matrix): print(f"top to bottom: {t_to_b} " , f"left to right: {l_to_r}" , f"element: {matrix[t_to_b][l_to_r]}") if matrix[t_to_b][l_to_r] == 0: t_to_b = 0 break matrixSum += matrix[t_to_b][l_to_r] t_to_b += 1 if l_to_r < len(matrix[0]): t_to_b = 0 l_to_r += 1 return matrixSum matrix=[[1,1,1,0], [0,5,0,1], [2,1,3,10]] print(matrixElementsSum(matrix)) # => 9
5a2c9c0d1985366856532d660db67b50f4a478e0
nisholics/Practical-Python
/p2_1.py
1,596
3.984375
4
''' 2.1. Create Regular Expressions that a) Recognize following strings bit, but, bat, hit, hat or hut b) Match any pair of words separated by a single space, that is, first and last names. c) Match any word and single letter separated by a comma and single space, as in last name, first initial. d) Match simple Web domain names that begin with www and end with a ".com" suffix; for example, www.yahoo.com. Extra Credit: If your regex also supports other high-level domain names, such as .edu, .net, etc. (for example: www.foothill.edu). e) Match a street address according to your local format (keep your regex general enough to match any number of street words, including the type designation). For example, American street addresses use the format: 1180 Bordeaux Drive. Make your regex flexible enough to support multi-word street names such as: 3120 De la Cruz Boulevard. ''' import re pattern = '[bh][aiu]t' text = 'rushit' m = re.search(pattern, text) if m is not None: print("Data = ",m.group()) pattern = '[a-zA-Z]+ [a-zA-Z]+' text = 'Nishu Bhardwaj' m = re.match(pattern, text) if m is not None: print("Data = ",m.group()) pattern = '([A-Z]\. )+[A-Za-z]+' text = 'n. s' m = re.match(pattern, text) if m is not None: print(m.group()) pattern = 'w{3}(\.[\w_]+)+((\.com)|(.edu)|(.net))' text = 'www.foothill.edu' m = re.search(pattern, text) if m is not None: print("Website = ",m.group()) pattern = r'\d{4} ([a-zA-Z]+ )+[a-zA-Z]+' text = '3120 De la Cruz Boulevard' m = re.search(pattern, text) if m is not None: print("String = ",m.group())
50d2f0d83d8165dd5fc49235e2b07f5e47550245
horkheimer8/PGE_projects_CVUT
/1_Robot_Mining_Simulation/PGE_first_assignment.py
870
3.734375
4
# [7 1 3 2 5 2 4 6 1] # Given: # s: start position:6 # d: direction of movement 0... left 1...right # n: num of visited positions in the move. # Goal: total sum of all visited values in one move. # More commands of the same format def moveValueGetSum(s, d, n): arr = [7, 1, 3, 2, 5, 2, 4, 6, 1] sum = 0 # move left, extract index values and add it to the sum for i in range(s, s-n): sum = sum + arr[i] # move right, extract index values and add it to the sum for i in range(s, s+n): sum = sum + arr[i] # make if for exception that is out of range of index if ((s<0) || (s>=9)): print("wrong index. try it again:) # what if the move required exceed the index? # in case of the array values that I put in doens't fit into the array size # in case of
eab1bba365d6375e93c055fd88d1a2879de7085f
ruchi2ch/Python-Programming-Assignment
/week 2/2.4.py
571
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 4 19:20:57 2020 @author: HP FOLIO 9480M """ '''Problem 2_4: random.random() generates pseudo-random real numbers between 0 and 1. Write a program to use only random.random() to generate a list of random reals between 30 and 35.''' import random def problem2_4(): listt=[] # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(70) for i in range(0,10): listt.append(30+5*random.random()) print(listt)
e6ec18b3cc01e05179775495cb94863bc09be4be
crazcalm/problem_solving_with_algorithms_and_data_structures_using_python
/Chapter_1/Fraction.py
4,301
3.78125
4
class Fraction: """ A module to deal with basic fractions. """ def __init__(self, top, bottom = 1): common = gcd(top, bottom) self.num = top //common self.den = bottom //common def __str__(self): return str(self.num) + "/" + str(self.den) def __repr__(self): return self.__str__() def show(self): print (self.num, "/", self.den) def __add__(self, otherfraction): if isinstance(otherfraction, int) or \ isinstance(otherfraction, float): otherfraction = Fraction(otherfraction, 1) newnum = self.num * otherfraction.den + \ self.den * otherfraction.num newden = self.den * otherfraction.den return Fraction(newnum, newden) def __radd__(self, other): return self.__add__(other) def __eq__(self, other): firstnum = self.num * other.den secondnum = other.num * self.den return firstnum == secondnum def __ne__(self, other): if not self.__eq__(other): return True else: return False def __gt__(self, other): a = self.num * float(self.den) b = other.num * float(other.den) if a > b: return True else: return False def __ge__(self, other): if self.__eq__(other) or self.__gt__(other): return True else: return False def __lt__(self, other): if not self.__ge__(other): return True else: return False def __le__(self, other): if not self.__gt__(other) or self.__eq__(other): return True else: return False def __sub__(self, other): newnum = self.num * other.den - \ self.den * other.num newden = self.den * other.den return Fraction(newnum, newden) def __mul__(self, other): newnum = self.num * other.num newden = self.den * other.den return Fraction(newnum, newden) def __truediv__(self, other): new_other = Fraction(other.den, other.num) return self.__mul__(new_other) def getNum(self): return self.num def getDen(self): return self.den def squareroot(n): """ Newton's Method for square roots """ root = n/2 #initial guess will be 1/2 of n for k in range(20): root = (1/2)*(root + (n/root)) return root def gcd(m,n): """ Greatest common denominator """ while m%n !=0: oldm = m oldn = n m = oldn n = oldm %oldn return n if __name__ == "__main__": test = Fraction(1,2) test2 = Fraction(6,8) test3 = Fraction(4,8) test4 = Fraction(-1,2) test5 = Fraction(0,1) print("Testing BASIC Functionality: \n") print("Fraction A = %s" % (test)) print("Fraction B = %s \n" % (test2)) print("%s + %s = %s\n" % (test, test2, test+test2)) print("The gcd(100,40) = %d" % gcd(100,40)) print("The sqrt(10) = %f\n" % squareroot(10)) print("Testing equality: %s == %s --> %s" % (test, test, test==test)) print("Testing equality: %s == %s --> %s" % (test, test2, test==test2)) print("Testing equality: %s == %s --> %s\n" % (test, test3, test==test3)) print("Testing getNum for Fraction A: %s" % (test.getNum())) print("Testing getDen for Fraction A: %s\n" % (test.getDen())) print("Testing Subtraction: %s - %s = %s" % (test, test2, test - test2)) print("Testing Subtraction: %s - %s = %s" % (test2, test, test2 - test)) print("Testing Subtraction: %s - %s = %s\n" % (test, test, test - test)) print("Testing __mul__: %s * %s = %s" % (test, test, test * test)) print("Testing __mul__: %s * %s = %s" % (test, test4, test * test4)) print("Testing __mul__: %s * %s = %s\n" % (test, test5, test * test5)) print("Testing __truediv__: %s / %s = %s\n" % (test, test, test/test)) print("Testing __gt__: %s > %s = %s" % (test2, test, test2 > test)) print("Testing __gt__: %s > %s = %s" % (test, test2, test > test2)) print("Testing __gt__: %s > %s = %s" % (test, test, test > test)) print("Testing __ge__: %s >= %s = %s" % (test, test, test >= test)) print("Testing __lt__: %s < %s = %s" % (test, test2, test < test2)) print("Testing __lt__: %s < %s = %s" % (test2, test, test2 < test)) print("Testing __le__: %s <= %s = %s" % (test, test2, test <= test2)) print("Testing __ne__: %s != %s = %s" % (test, test2, test != test2)) print("Testing __ne__: %s != %s = %s\n" % (test, test, test != test)) print("Modified the __add__: %s + %s = %s" % (test, 2, test + 2)) print("Modified the __add__: %s + %s = %s\n" % (2, test, 2 + test))
4d3c6fb718eec67017d5782f7562a4a16be69695
hyunjun/practice
/python/problem-string/shortest_distance_to_a_character.py
1,771
3.53125
4
# https://leetcode.com/problems/shortest-distance-to-a-character # https://leetcode.com/problems/shortest-distance-to-a-character/solution from typing import List class Solution: # 78.70% def shortestToChar(self, S, C): cIdx, res = -1, [] for i, c in enumerate(S): if C == c: res.append(0) cIdx = i else: if -1 == cIdx: res.append(len(S)) else: res.append(abs(cIdx - i)) for i in range(len(S) - 1, -1, -1): if C == S[i]: cIdx = i else: res[i] = min(res[i], abs(cIdx - i)) return res # https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3631 # runtime; 40ms, 82.09% # memory; 14.4MB, 61.15% def shortestToChar(self, s: str, c: str) -> List[int]: ret = [float('inf')] * len(s) for i, ch in enumerate(s): if ch == c: l, lDistance, r, rDistance = i - 1, 1, i + 1, 1 ret[i] = 0 while 0 <= l and s[l] != c: ret[l] = min(ret[l], lDistance) l -= 1 lDistance += 1 while r <= len(s) - 1 and s[r] != c: ret[r] = min(ret[r], rDistance) r += 1 rDistance += 1 return ret s = Solution() data = [('loveleetcode', 'e', [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]), ('aaab', 'b', [3, 2, 1, 0]), ] for S, C, expect in data: real = s.shortestToChar(S, C) print(f'{S}, {C}, expect {expect}, real {real}, result {expect == real}')
d7e7c7d249b22fd0bdb29139bb768b48ef933d99
des-learning/struktur-data
/src/09/binary.py
2,039
3.5625
4
class Node: def __init__(self, value, parent=None): self.parent = parent self.value = value self.left = None self.right = None def addLeft(self, value): if self.left is None: node = Node(value, self) self.left = node else: self.left.addLeft(value) def addRight(self, value): if self.right is None: node = Node(value, self) self.right = node else: self.right.addRight(value) def inorder(self): left = [] if self.left is not None: left.extend([x for x in self.left.inorder()]) right = [] if self.right is not None: right.extend([x for x in self.right.inorder()]) l = [] l.extend(left) l.append(self.value) l.extend(right) return l def preorder(self): left = [] if self.left is not None: left.extend([x for x in self.left.preorder()]) right = [] if self.right is not None: right.extend([x for x in self.right.preorder()]) l = [] l.append(self.value) l.extend(left) l.extend(right) return l def postorder(self): left = [] if self.left is not None: left.extend([x for x in self.left.postorder()]) right = [] if self.right is not None: right.extend([x for x in self.right.postorder()]) l = [] l.extend(left) l.extend(right) l.append(self.value) return l class Tree: def __init__(self): self.root = None def add(self, value): if self.root is None: self.root = Node(value) def inorder(self): return self.root.inorder() if self.root is not None else [] def preorder(self): return self.root.preorder() if self.root is not None else [] def postorder(self): return self.root.postorder() if self.root is not None else []
09330f672f835b2b7e17232529d59caee1aa60ae
szhmery/algorithms
/sorting/ShellSort.py
474
3.6875
4
# https://www.cnblogs.com/chengxiao/p/6104371.html def shellSort(arr): n = len(arr) gap = int(n / 2) while gap > 0: for i in range(gap, n): temp = arr[i] j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp gap = int(gap / 2) if __name__ == '__main__': array = [12, 11, 13, 5, 6, 7] shellSort(array) print(array)
4868efae039403027acc5b814ed76480a7cedfb7
ranvsin2/PythonBasics
/for.py
424
4.0625
4
#range(start,stop,step) #step:print every no after step. for i in range(1,6,2): print(i) fish=['rohu','katla','shark','mangur'] for f in fish: print(f) for item in range(len(fish)): fish.append('jhinga') print(fish) sammy='Mangur' for letter in sammy: print (letter) fish_dict={'name':'rohu','color':'brown','taste':'excellent','animal':'aqua'} for key in fish_dict: print(key+"====="+fish_dict[key])
a78666a57c4e34b35e76b64ef19f884ce6a5a6db
vukovicofficial/Programsko-inzenjerstvo-
/vjezba_1/Razlomak.py
3,924
3.6875
4
''' Može se lakše uraditi preko ugrađene biblioteke 'fractions' ''' ''' Stvori datoteku razlomak.py Napravi klasu Razlomak koja će imati dva atributa brojnik i nazivnik. Brojnik i nazivnik se šalju kao argumenti tijekom inicijalizacije klase Napravi svojstva za čitanje i pisanje brojnika i nazivnika. Napravi metodu skrati() koja će skratiti razlomak, na primjer. razlomak 3/12 se može skratiti na 1/4. ''' class Razlomak(object): def __init__(self, brojnik, nazivnik): self._brojnik = int(brojnik) self._nazivnik = int(nazivnik) # Getters @property def brojnik(self): return self._brojnik @property def nazivnik(self): return self._nazivnik #--------------------------- # Setters @brojnik.setter def brojnik(self, brojnikVrijednost): self._brojnik = brojnikVrijednost @nazivnik.setter def nazivnik(self, nazivnikVrijednost): self._nazivnik = nazivnikVrijednost # --------------------------- #Metoda za skraćivanje razomaka ako je to moguće @property def skrati(self): najmanjiDjeljitelj = None if(self.brojnik <= self.nazivnik): manjiBroj = self.brojnik else: manjiBroj = self.nazivnik for djeljitelj in range(2, int(manjiBroj + 1)): if(self.brojnik % djeljitelj == 0 and self.nazivnik % djeljitelj == 0): najmanjiDjeljitelj = djeljitelj if(najmanjiDjeljitelj == None): print("Razlomak se ne može skratiti.") else: self.nazivnik //= najmanjiDjeljitelj self.brojnik //= najmanjiDjeljitelj print("Razlomak se može skratiti sa brojem", najmanjiDjeljitelj, "te razlomak sada izgleda:", repr(self)) def __repr__(self): return "Razlomak(" + repr(self.brojnik) + ", " + repr(self.nazivnik) + ")" #------------------------------------------------------------------------------------------------------------------- #Vježba 1.1 ''' U klasi razlomak napravi specijalnu metodu __str__() koja će služiti za ispis razlomka u oblikubrojnik|nazivnik i specijalnu metodu __repr__() za reprezentaciju razlomka. Napravi specijalne metode za operacije usporedbe razlomaka. ''' def __str__(self): return str(self.brojnik) + "|" + str(self.nazivnik) #__repr__ metoda je definirana ranije def __eq__(self, other): return (self.brojnik / self.nazivnik) == (other.brojnik / other.nazivnik) def __ge__(self, other): return (self.brojnik / self.nazivnik) >= (other.brojnik / other.nazivnik) def __lt__(self, other): return (self.brojnik / self.nazivnik) < (other.brojnik / other.nazivnik) # ------------------------------------------------------------------------------------------------------------------- # Vježba 1.2 ''' klasi razlomak napravi specijalnu metode za zbrajanje, oduzimanje, množenje i dijeljenje razlomaka. ''' def __add__(self, other): brojnik = (self.brojnik * other.nazivnik) + (other.brojnik * self.nazivnik) nazivnik = self.nazivnik * other.nazivnik return repr(Razlomak(brojnik, nazivnik)) def __sub__(self, other): brojnik = (self.brojnik * other.nazivnik) - (other.brojnik * self.nazivnik) nazivnik = self.nazivnik * other.nazivnik return repr(Razlomak(brojnik, nazivnik)) def __mul__(self, other): brojnik = self.brojnik * other.brojnik nazivnik = self.nazivnik * other.nazivnik return repr(Razlomak(brojnik, nazivnik)) def __truediv__(self, other): brojnik = self.brojnik / other.brojnik nazivnik = self.nazivnik / other.nazivnik return repr(Razlomak(brojnik, nazivnik)) # -------------------------------------------------------------------------------------------------------------------
1c41e1a104f733e8d0a8667fe02963be3618458e
MED-B/DiabitesDetectorPY
/main.py
2,712
3.671875
4
#Description : this is a program that detect whether someone has diabites with ML and Python #Import libraries import pandas as pd from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from PIL import Image import streamlit as st #Create Title and Subtitle st.write(""" #Diabites Detector detect whetheer someone has diabites with ML and Python """) #Open and display an image image = Image.open('pic.png') st.image(image, caption="Caption : ML", use_column_width=True) #Get the Data df = pd.read_csv('diabetes.csv') #Set A SubHeader st.subheader('Data Informations : ') #show the data as a table st.dataframe(df) #show statistics about the data st.write(df.describe()) #show the data as a chart chart = st.bar_chart(df) #Split the data into independet 'X' and dependent 'Y' variables X = df.iloc[:, 0:8].values Y = df.iloc[:, -1].values #Split the data set into 75% trainig data and 25% testing data X_train, X_test,Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0) #Get the feature input from the user def get_user_input(): Pregnancies = st.sidebar.slider('Pregrancies', 0, 17, 3) Glucose = st.sidebar.slider('Glucose', 0, 199, 117) Blood_Pressure = st.sidebar.slider('Blood_Pressure', 0, 122, 72) Skin_Thickness = st.sidebar.slider('Skin_Thickness', 0, 99, 23) Insulin = st.sidebar.slider('Insulin', 0.0, 846.0, 30.0) BMI = st.sidebar.slider('BMI', 0.0, 67.1, 32.0) DPF = st.sidebar.slider('DPF', 0.078, 2.42, 0.3725) Age = st.sidebar.slider('Age', 18, 81, 29) #Store a dictionarry into a variable user_data = { 'Pregnancies' : Pregnancies, 'Glucose' : Glucose, 'Blood_Pressure' : Blood_Pressure, 'Skin_Thickness' : Skin_Thickness, 'Insulin' : Insulin, 'BMI' : BMI, 'DPF' : DPF, 'Age' : Age } #Transform the data into a DataFrame features = pd.DataFrame(user_data, index=[0]) return features #Store the user input into a variable user_input = get_user_input() # Set a subheader and diplaying the user inputs st.subheader('User Input : ') st.write(user_input) #create and train the model RandomForestClassifier = RandomForestClassifier() RandomForestClassifier.fit(X_train, Y_train) #Show th e model metrics st.subheader('Model Test Accuracy Score : ') st.write(str(accuracy_score(Y_test,RandomForestClassifier.predict(X_test))*100)+'%') #Store the model predictions in a variable prediction = RandomForestClassifier.predict(user_input) #Set a subheader displaying the predictio for the user data st.subheader('Classification') st.write(prediction)
1ec0c74519b72a68da6a807720040a6cdca893d3
AnishHota/Coding-Problems
/Palindrome Permutation.py
346
3.9375
4
string = input() count=0 for i in string: if string.count(i.lower())%2!=0 and i!=' ': count+=1 length = len([1 for i in string if i!=' ']) if length%2!=0 and count==1: print('Permutation of a Palindrome') elif length%2==0 and count==0: print('Permutation of a Palindrome') else: print('Not a Permutation of a Palindrome')
93843b8294ba36836e6e0f0330941ddc068e0efb
lucasbbs/APC-2020.2
/dicionario/questao4/main.py
292
3.78125
4
string = input() def histogram(s): d = dict() for c in s: d[c] = d.get(c,0)+1 return d print(histogram(string)) def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d a = input() print(histogram(a))
a2473012b612bcc8accb855637d8f3662d158b24
tony-andreev94/Python-Fundamentals
/02. Lists/03. Smallest number v2.py
538
4.28125
4
# Write a program to read a list of integers, finds the smallest item and prints it. # This is another solution, instead to search for the smallest number the list is sorted and the first item is printed def list_sort_func(input_list): sorted_list = sorted(input_list) return sorted_list[0] if __name__ == "__main__": my_list = [int(x) for x in input().split()] print(list_sort_func(my_list)) # Alternative solution without additional functions or sorting is using the min(list) method: # print(min(my_list))
8644f104a40f2b5f748836f58442eb9d47a514f4
cesarfois/Estudo_Livro_python
/#Livro_Introd-Prog-Python/cap-6/Listagem 6.7 - Apresentação de numeros.py
537
3.65625
4
print('=' * 72) print('{:=^72}'.format(' Listagem 6.7 ')) print('{:=^72}'.format(' By César J. Fois ')) print('=' * 72) print('{0:=^72}'.format(' Listagem 6.7 - Apresentação de Numeros')) print('=' * 72) print('') numeros = [0, 0, 0, 0, 0] x = 0 while x < 5: numeros[x] = float(input('Numero %d: ' % (x+1))) x += 1 while True: escolhido = int(input('Que posição você quer imprimir (0 para sair):')) if escolhido == 0: break print('Você escolheu o numero: %d' % (numeros[escolhido-1]))
6c15e5be19d0549994d1ae7e060553f83b40792c
kiran-kotresh/Python-code
/test_python_dummy.py
173
3.6875
4
# # result = [x ** y for x in [10, 20, 30] for y in [2, 3, 4]] # print(result) from functools import reduce result = reduce((lambda x, y: x * y), [1, 2, 3]) print(result)
fb8339c7c5d619e79d090c53a6d7e3eb63e27ce3
Dmitry892/Py111-Arefev
/Tasks/b2_Taylor.py
1,028
3.828125
4
""" Taylor series """ from typing import Union def factorial(fac: int) -> int: factorial_ = 1 for f in range(fac, 0, -1): factorial_ *= f return factorial_ def ex(x: Union[int, float]) -> float: """ Calculate value of e^x with Taylor series :param x: x value :return: e^x value """ delta = 0.0001 exp = 0 for n in range(10000000): value = x ** n / factorial(n) if value <= delta: return exp else: exp += value def sinx(x: Union[int, float]) -> float: """ Calculate sin(x) with Taylor series :param x: x value :return: sin(x) value """ delta = 0.0001 current_value = 0 for n in range(10000000): current_value += (-1) ** n * (x ** (2 * n + 1)) / factorial(2 * n + 1) next_value = (-1) ** (n + 1) * (x ** (2 * (n + 1) + 1)) / factorial(2 * (n + 1) + 1) next_value += current_value if abs(current_value - next_value) <= delta: return current_value
596d94f42e2a47f2c2bd70afb1c6da243b4b3a61
invintrar/CS50WP
/Python/name.py
51
3.5
4
name = input("Name: ") print("His name is: ", name)
73179cbe10f4a6c658238bb249c41d6efcff2ab9
wongyee11/PythonLearning
/Projectexception/exceptMsg.py
487
3.6875
4
#!/usr/bin/env.python # coding=utf-8 print("只要有一行出现了异常就会'print()'异常信息,但是当打印异常时,我们并不能准确地知道到底是哪一行代码引起了异常") print("我们在'BaseException'后面定义了'msg'变量用于接受异常信息,并通过'print'将其打印出来") print("此处的写法在'Python2'里用逗号','代替'as'") try: open("abc.txt", 'r') print(hello) except BaseException as msg: print(msg)
578ffac6c8072432b1098cee56344a11525a4dd9
tayloradam1999/AirBnB_clone
/tests/test_models/test_place.py
2,607
3.703125
4
#!/usr/bin/python3 """ Unit test module for Place class """ import unittest import os from models.engine.file_storage import FileStorage from datetime import datetime from models.place import Place place1 = Place() class TestPlace(unittest.TestCase): """ Class for Place tests """ def test_id(self): """ Unittesting test_id instance """ self.assertTrue(isinstance(place1.id, str)) def test_city_id(self): """ Make sure city_id is string """ self.assertTrue(isinstance(Place.city_id, str)) self.assertTrue(isinstance(place1.city_id, str)) def test_user_id(self): """ Make sure user_id is string """ self.assertTrue(isinstance(Place.user_id, str)) self.assertTrue(isinstance(place1.user_id, str)) def test_name(self): """ Make sure name is a string """ self.assertTrue(isinstance(Place.name, str)) self.assertTrue(isinstance(place1.name, str)) def test_description(self): """ Make sure description is a string """ self.assertTrue(isinstance(Place.description, str)) self.assertTrue(isinstance(place1.description, str)) def test_number_rooms(self): """ Make sure number of rooms is an int """ self.assertTrue(isinstance(Place.number_rooms, int)) self.assertTrue(isinstance(place1.number_rooms, int)) def test_number_bathrooms(self): """ Make sure number_bathrooms is an int """ self.assertTrue(isinstance(Place.number_bathrooms, int)) self.assertTrue(isinstance(place1.number_bathrooms, int)) def test_max_guest(self): """ Make sure max_guest is an int """ self.assertTrue(isinstance(Place.max_guest, int)) self.assertTrue(isinstance(place1.max_guest, int)) def test_price_by_night(self): """ Make sure price_by_night is a integer """ self.assertTrue(isinstance(Place.price_by_night, int)) self.assertTrue(isinstance(place1.price_by_night, int)) def test_latitude(self): """ Make sure latitude is a float """ self.assertTrue(isinstance(Place.latitude, float)) self.assertTrue(isinstance(place1.latitude, float)) def test_longitude(self): """ Make sure longitude is a float """ self.assertTrue(isinstance(Place.longitude, float)) self.assertTrue(isinstance(place1.longitude, float)) def test_amenity_ids(self): """ Make sure amenity_ids is a list """ self.assertTrue(isinstance(Place.amenity_ids, list)) self.assertTrue(isinstance(place1.amenity_ids, list))
f787cfa52ecb32d1fd508a63c34c0bb64ccf4e33
asomodi/PYTHON_single_tasks
/hangman_game.py
820
4
4
#!/usr/bin/env python # coding: utf-8 # In[2]: word="GUESS" guessed=0 current_guess=["_"]*len(word) count=0 print("HANGMAN Experience :-)\nThe word has " + str(len(word)) + "letters.\nGOOD LUCK\n\n") print(("_"+" ")*len(word)) while count <6: guess=input("\nGuess your letter: ").upper() for letter in range(0,len(word)): if word[letter]==guess: current_guess[letter]=guess if "_" not in current_guess: guessed=1 break else: for i in range(0,len(word)): print ( current_guess[i] + " ", end="") print("\n") count+=1 if guessed==1: print("Yeah, you managed to find the word: ", word) else: print("Sorry, you'r dad, man!\nThe right word would have been: ", word) # In[ ]:
863055d42f0ab5eeba5d3c2bde9ea14277f436d0
Aigerimmsadir/BFDjango
/week1/CodeingBat/max_end3.py
146
3.796875
4
def max_end3(nums): maxx = max(nums) nums[0]=maxx nums[1]=maxx nums[2]=maxx return nums print(max_end3(input().split()))
96140dfc5b32b5e251fa9c17e62b61552b111728
shatuji/python
/zipAndLambdaAndMap.py
324
3.953125
4
#zip lambda map a = [1,324,32] b = [12,34,2] obj = zip(a,b) #print(list(obj)) #for u in list(obj): #s print(u) #for i , j in obj: # print(i*2,j*3) def function1(x , y): return x+y #this is just liking invoked function that get it return data result_map = map(function1,[2,32],[3,23]) print(list(result_map))
6aadbce268cc472e41b8ee0a2a562a9071778a42
leeejihyun/Grade-Management
/main.py
5,401
3.8125
4
def getaverage(student): average = (student['Midterm'] + student['Final'])/2 average = round(average,1) return average def getgrade(student): average = student['Average'] if average >= 90: grade = 'A' elif average >= 80: grade = 'B' elif average >= 70: grade = 'C' elif average >= 60: grade = 'D' else: grade = 'F' return grade def showhead(): print("{:>10}\t{:^15}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\n".format("Student", "Name", "Midterm", "Final", "Average", "Grade")) print("-" * 100) def showrecord(student): print("{:>10}\t{:^15}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\n".format(student['Student'], student['Name'], student['Midterm'], student['Final'], student['Average'], student['Grade'])) def find(stu_list, column, key): for student in stu_list: if student[column] == key: return student return False def show(stu_list): stu_list.sort(key=lambda student : student['Average'], reverse=True) # 평균 점수를 기준으로 내림차순 정렬 showhead() for student in stu_list: showrecord(student) def search(stu_list): studentID = input("Student ID: ") if find(stu_list, 'Student', studentID): student = find(stu_list, 'Student', studentID) showhead() showrecord(student) else: print("NO SUCH PERSON.\n") def changescore(stu_list): studentID = input("Student ID: ") if find(stu_list, 'Student', studentID): student = find(stu_list, 'Student', studentID) choice = input("Mid/Final? ") if (choice == "mid") | (choice == "final"): score = int(input("Input new score: ")) if (0 <= score <= 100): showhead() showrecord(student) if choice == "mid": student['Midterm'] = score else: student['Final'] = score student['Average'] = getaverage(student) student['Grade'] = getgrade(student) print("Score changed.") showrecord(student) else: print() else: print() else: print("NO SUCH PERSON.\n") def add(stu_list): student = {} studentID = input("Student ID: ") if not find(stu_list, 'Student', studentID): student['Student'] = studentID name = input("Name: ") student['Name'] = name mid = int(input("Midterm Score: ")) student['Midterm'] = mid final = int(input("Final Score: ")) student['Final'] = final student['Average'] = getaverage(student) student['Grade'] = getgrade(student) stu_list.append(student) print("Student added.\n") else: print("ALREADY EXISTS.\n") def searchgrade(stu_list): grade = input("Grade to search: ") if grade in "ABCDF": if find(stu_list, 'Grade', grade): showhead() for student in stu_list: if student['Grade'] == grade: showrecord(student) else: print("NO RESULTS.\n") else: print() def remove(stu_list): if stu_list: studentID = input("Student ID: ") if find(stu_list, 'Student', studentID): student = find(stu_list, 'Student', studentID) stu_list.remove(student) print("Student removed.\n") else: print("NO SUCH PERSON.\n") else: print("List is empty.\n") def quit(stu_list): save = input("Save data?[yes/no] ") if save == "yes": filename = input("File name: ") with open(filename, 'w') as f: for student in stu_list: line = '\t'.join(list(map(str, student.values()))) f.write(line + '\n') def menu(): import sys try: file_name = sys.argv[1] except: file_name = 'students.txt' with open(file_name, 'r') as f: stu_list = [] while True: line = f.readline() if not line: break line = line.strip().split('\t') student = {} student['Student'] = line[0] student['Name'] = line[1] student['Midterm'] = int(line[2]) student['Final'] = int(line[3]) student['Average'] = getaverage(student) student['Grade'] = getgrade(student) stu_list.append(student) show(stu_list) print(''' show: 전체 학생 정보 출력 search: 특정 학생 검색 changescore: 점수 수정 add: 학생 추가 searchgrade: 학점으로 검색 remove: 특정 학생 삭제 quit: 종료 ''') while True: cmd = input("# ") if cmd.upper() == "SHOW": show(stu_list) elif cmd.upper() == "SEARCH": search(stu_list) elif cmd.upper() == "CHANGESCORE": changescore(stu_list) elif cmd.upper() == "ADD": add(stu_list) elif cmd.upper() == "SEARCHGRADE": searchgrade(stu_list) elif cmd.upper() == "REMOVE": remove(stu_list) elif cmd.upper() == "QUIT": quit(stu_list) return False menu()
32a3b85370beee49dd86b481fa66e33909f70fe7
adikabintang/kolor-di-dinding
/programming/basics/crackingthecodinginterview/recursion_and_memoization/2_robot_in_a_grid.py
1,342
3.515625
4
# class Point: # def __init__(self, x, y): # self.x = x # self.y = y class Solution: def __init__(self): self.paths = [] self.__forbidden_points = set([(2, 2)]) def is_offlimit(self, row, column) -> bool: return (row, column) in self.__forbidden_points def find_path(self, start_row, start_column, end_row, end_column) -> ([(int, int)], bool): if start_row == end_row and start_column == end_column: return [(start_row, start_column)], True res = False path = [] p = None if start_row + 1 <= end_row: if self.is_offlimit(start_row + 1, start_column) == False: p, res = self.find_path(start_row + 1, start_column, end_row, end_column) if res == False and (start_column + 1 <= end_column): if self.is_offlimit(start_row, start_column + 1) == False: p, res = self.find_path(start_row, start_column + 1, end_row, end_column) if res: path.append((start_row, start_column)) path.extend(p) return path, res s = Solution() print(s.find_path(0, 0, 2, 3)) # print(find_path(0, 0, 1, 1)) # print(find_path(0, 0, 1, 2)) # print(s.find_path(0, 0, 100, 5))
cc9118229ede1bd0379c4a074bc4e7f941d6c379
liulizhou/leetcode
/utils/sort.py
2,297
3.671875
4
import random # sort class Solution: def heap_sort_pos(self, nums): def max_heap(nums, root, size): p = root while(p * 2 + 1 < size): l, r = p * 2 + 1, p * 2 + 2 if r < size and nums[l] < nums[r]: nex = r else: nex = l if nums[nex] > nums[p]: nums[nex], nums[p] = nums[p], nums[nex] p = nex else: break size = len(nums) for i in range(size - 1, -1, -1): max_heap(nums, i, size) for i in range(size - 1, -1, -1): nums[0], nums[i] = nums[i], nums[0] max_heap(nums, 0, i) def heap_sort_rev(self, nums): def min_heap(nums, root, size): p = root while(2 * p + 1 < size): l, r = 2 * p + 1, 2 * p + 2 if r < size and nums[l] > nums[r]: nex = r else: nex = l if nums[nex] < nums[p]: nums[nex], nums[p] = nums[p], nums[nex] p = nex else: break size = len(nums) for i in range(size - 1, -1, -1): min_heap(nums, i, size) for i in range(size - 1, -1, -1): nums[0], nums[i] = nums[i], nums[0] min_heap(nums, 0, i) def quick_sort(self, nums): def part(nums, l, r): pivot = random.randint(l, r) nums[pivot], nums[r] = nums[r], nums[pivot] i = l - 1 for j in range(l, r): if nums[j] < nums[r]: i = i + 1 nums[i], nums[j] = nums[j], nums[i] i = i + 1 nums[i], nums[r] = nums[r], nums[i] return i def sort(nums, l, r): if l >= r: return mid = part(nums, l, r) sort(nums, l, mid - 1) sort(nums, mid + 1, r) l, r = 0, len(nums) - 1 sort(nums, l, r) if __name__ == '__main__': nums = [3, 4, 5, 1, 7, 9] s = Solution() # s.heap_sort_pos(nums) # s.heap_sort_rev(nums) s.quick_sort(nums) print(nums)
5109ceb6663fa1be9edd06ad5604eac8b5d9dbc4
leomcp/Algorithms
/Python/Data Structure/Trees/tree_identical.py
1,425
3.9375
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BSTree: def __init__(self): self.root = None def get_root(self): if self.root: return self.root def insert(self, node_data): if self.root is None: self.root = Node(node_data) else: self._insert(self.root, self.data) def _insert(self, curr_node, node_data): if curr_node.data > node_data: if curr_node.left is None: curr_node.left = Node(node_data) else: self._insert(curr_node.left, node_data) elif curr_node.data < node_data: if curr_node.right is None: curr_node.right = Node(node_data) else: self._insert(curr_node.right, node_data) else: print("ALready inserted Node") def inorder(self): if self.root: self._inorder(self.root) print() def _inorder(curr_node): if curr_node: self._inorder(curr_node.left) print(curr_node.data, end=" ") self._inorder(curr_node.right) def find_identical(self, root1, root2): if root1 is None and root2 is None: return 1 if root1 is not None and root2 is not None: if root1.data == root2.data and find_identical(root1.left, root2.left) and find_identical(root1.right, root2.right) return False if __name__ == "__main__": bst = BSTree() in_put = [10, 8, 15, 2, 9, 13, 18] for elem in in_put: bst.inorder() print() bst.inorder() is_identical(bst.get_root, bst.get_root)
a73815c6b1000d77172a3cbb8f3820a36e44a70a
wzwhit/leetcode
/剑指offer/面20表示数值的字符串.py
396
3.875
4
# -*- coding:utf-8 -*- import sys class Solution: # s字符串 def isNumeric(self, s): # write code here try: p = float(s) return True except: return False while True: try: line = sys.stdin.readline().strip() if not line: break print(Solution().isNumeric(line)) except: pass
b2a6d14a03925db180cf96cb3c870657b074cf84
nindalf/euler
/25-fibonacci.py
788
4.0625
4
#!/usr/bin/env python3 """ Searched online for a better way of knowing the index of the current iteration. Found that the enumerate() function does just that. Updated a previous program to use this. An excellent pen and paper solution to this problem. http://www.mathblog.dk/project-euler-25-fibonacci-sequence-1000-digits/ The old way to check if the element had 1000 digits. divisor = 10**999 for index, element in enumerate(fibonacci()): if element >= divisor: """ def fibonacci(): current = 0 previous = 1 while True: temp = current current = current + previous previous = temp yield current def main(): for index, element in enumerate(fibonacci()): if len(str(element)) >= 1000: answer = index + 1 break print(answer) if __name__ == "__main__": main()
db84f97977120139c1f2d5caf434056c0e74a3b5
elainy-liandro/mundo1e2-python-cursoemvideo
/Desafio42.py
504
3.953125
4
print('-='*20) print('Desafio 42 - Triângulos') r1 = float(input('Primeiro segmento: ')) r2 = float(input('Segundo segmento: ')) r3 = float(input('Terceiro segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os seguimentos acima PODEM FORMAR Triângulo',end='') if r1 == r2 == r3: print(' EQUILATERO!') elif r1 != r2 != r3 != r1: print(' ESCALENO') else: print(' ESÓSCELES') else: print('Os segmentos acima NÃO PODEM FORMAR Triângulo')
b9b350d763ccf61b56af719ef0e674d24937ca9a
HAKSOAT/Timely
/calendar_picker/CalendarDialog.py
1,618
3.609375
4
import tkinter from calendar_picker import ttkcalendar from calendar_picker import tkSimpleDialog class CalendarDialog(tkSimpleDialog.Dialog): """Dialog box that displays a calendar and returns the selected date""" def body(self, master): self.calendar = ttkcalendar.Calendar(master) self.calendar.pack() def apply(self): self.result = self.calendar.selection # Demo code: class CalendarFrame(tkinter.LabelFrame): def __init__(self, master, date = None): tkinter.LabelFrame.__init__(self, master) self.transient = master def getdate(): cd = CalendarDialog(self) result = cd.result try: self.date_box["state"] = tkinter.NORMAL self.selected_date.set(result.strftime("%d/%m/%Y")) self.date_box["state"] = tkinter.DISABLED except AttributeError: self.date_box["state"] = tkinter.DISABLED except tkinter._tkinter.TclError: pass self.selected_date = tkinter.StringVar() if date == None: pass else: self.selected_date.set(date) self.date_box = tkinter.Entry(self, textvariable=self.selected_date, state = tkinter.DISABLED) self.date_box.pack(side=tkinter.TOP) tkinter.Button(self, text="Choose a date", command=getdate).pack(side=tkinter.TOP) # def main(master): # calendar_frame = CalendarFrame(master) # calendar_frame.grid(row = 3, column = 0, columnspan = 2, pady = [50,10]) # if __name__ == "__main__": # main(master)
3349b20b387f4434cfefbbcc22655af873a06913
maridigiolo/python-exercises
/pyexe/madlib.py
255
4.0625
4
print (" Please fill in the blanks below: ") print (" 's favorite subject in school is .") name = input("What is your name? ") subj = input ("What is you favorite subject in school? ") print (name + "'s favorite subject in school is " + subj)
762c14fad9a80b66c672c65180b704fc20e3c2d6
milenaS92/HW070172
/L03/exercise5.py
670
4.21875
4
# A program to compare Celsius and Farenheit temperatures def main(): print("********************************************************") print("This program compares Celsius and Farenheit temperatures") print("********************************************************") for i in range(0, 110, 10): celsius = float(i) farenheit = 9/5 * celsius + 32 if celsius<10: print("Celsius: ", celsius, " Farenheit: ", farenheit) elif celsius>=10 and celsius<100: print("Celsius: ", celsius, " Farenheit: ", farenheit) else: print("Celsius: ", celsius, " Farenheit: ", farenheit) main()
53d15e4b5757fb0581933a87c9c9bfef85743594
cielavenir/procon
/aizu/tyama_aizuALDS1~2D.py
550
3.8125
4
#!/usr/bin/python import sys if sys.version_info[0]>=3: raw_input=input def insertionSort(a,g): global cnt for i in range(g,len(a)): v = a[i] j = i - g while j >= 0 and a[j] > v: a[j+g] = a[j] j = j - g cnt+=1 a[j+g] = v def shellSort(a): global cnt cnt = 0 g = [] h = 1 while h <= len(a): g.append(h) h = 3*h+1 g.reverse() m = len(g) print(m) print(' '.join(map(str,g))) for i in range(m): insertionSort(a,g[i]) a=[int(raw_input()) for i in range(int(raw_input()))] shellSort(a) print(cnt) for e in a: print(e)
77ee09399ade81f8873ef47fe94a9475602bfd07
andiegoode12/Intro-to-Computer-Programming
/Assignments/Assignment45.py
502
3.703125
4
""" Andie Goode 10/26/15 File I/O: Line Numbers """ #prompt user for filename name = input("Enter a filename: ") print("") #open file file = open(name,'r') #ouput statement print("Contents of",name) #set lines equal to reading file lines = file.read() #set line equal to a list of each seperate line line = lines.split('\n') #loop through the len of list line for i in range(len(line)): #output line number, tab, and line at location i in list print(str(i+1)+':\t'+line[i]) #close file file.close()
c4ad54304524270f2c244b47c30ffb7b54987f62
Shalini2801/S.Shalini-csc
/Task14(2).py
978
4.375
4
#2.Design a simple calculator app with try and except for all use cases def calculate(): try: print('+') print('-') print('*') print('/') print('%') print('**') operation = input("Select an operator:") print("Enter two numbers") number_1 = int(input()) number_2 = int(input()) if operation == '+': print(number_1 + number_2) elif operation == '-': print(number_1 - number_2) elif operation == '*': print(number_1 * number_2) elif operation == '/': print(number_1 / number_2) elif operation == '%': print(number_1 % number_2) elif operation == '**': print(number_1 ** number_2) else: print('Invalid Input') except Exception as e: print(e) calculate() #Output + - * / % ** Select an operator : + Enter two numbers 10 10 20
eba99a49ea7f77606186b5747a71c6bb2c073820
kilik42/tkinter_appPython
/grid.py
642
4.625
5
from tkinter import * root = Tk() #creating label widget #myLabel1 = Label(root, text="hello world!") ##myLabel2 = Label(root, text="my name is jake dawn!") #myLabel3 = Label(root, text="dumas is the name!") #shoving it on the screen #myLabel.pack() #myLabel1.grid(row=0, column=0) #myLabel2.grid(row=1, column=0) #myLabel3.grid(row=1, column=1) e = Entry(root, width=50,borderwidth= 5) e.pack() e.insert(0,"enter your name") def myClick(): hello = " hello " + e.get() myLabel1 = Label(root, text=hello) myLabel1.pack() myButton = Button(root, text="enter your name", command = myClick) myButton.pack() root.mainloop()
6fc69be211b1159860d14f4caceb83ea9375fe1f
retuam/pyadvanced
/homework_06/homework_06_02.py
2,649
3.96875
4
# 2) Создать свою структуру данных Словарь, которая поддерживает методы, # get, items, keys, values. Так же перегрузить операцию сложения для # словарей, которая возвращает новый расширенный объект. class MyDict: def __init__(self, **kwargs): self._current = 0 self._structure = {} for key in kwargs: self[key] = kwargs[key] self._len = len(kwargs) def __iter__(self): self._current = 0 return self def __next__(self): if self._current == self._len: raise StopIteration current = self._current self._current += 1 return self.keys()[current] def items(self): _items = [0] * self._len i = 0 for key in self._structure: _items[i] = (key, self._structure[key]) i += 1 return _items def keys(self): _keys = [0] * self._len i = 0 for key in self._structure: _keys[i] = key i += 1 return _keys def values(self): _values = [0] * self._len i = 0 for key in self._structure: _values[i] = self._structure[key] i += 1 return _values def get_structure(self): return self._structure def __str__(self): return f'MyDict = {self._structure}' def __add__(self, other): new_obj = MyDict() for key, value in self.items(): new_obj[key] = value for key, value in other.items(): new_obj[key] = value return new_obj def __getitem__(self, item): return item, self._structure[item] def __setitem__(self, key, value): self._structure[key] = value def get(self, key): try: return self._structure[key] except KeyError: return None def pop(self, key): del self._structure[key] self._len -= 1 def clear(self): self._structure = {} self._len = 0 if __name__ == '__main__': obj = MyDict(v1=10, v3=20, v5=30, v7=40) print(obj['v1']) print(obj['v5']) print(obj) for row in obj: print(row) print(obj.values()) print(obj.keys()) print(obj.items()) print(obj.get('v')) print(obj.get('v1')) obj.pop('v5') print(obj) obj.clear() print(obj) obj1 = MyDict(v1=10, v3=20, v5=30, v7=40) obj2 = MyDict(v1=11, v2=10, v4=20, v6=30, v9=40) obj3 = obj1 + obj2 print(obj3)
47759affc32dc878ecc6ea164e893b236c98a551
Marist-CMPT120-FA19/STUREBORG-VERONICA-Project3
/tree.py
339
4.21875
4
#CMPT 120L 200 #Veronica Stureborg #Program to display a tree on screen using text characters #i is equal to the row #h is the height of the tree def main(): h=int(input("How high would you like the tree to be?")) for i in range (h): print(((h-i-1))* ' '+(i*2+1)* '#') print((h-1)* ' '+'#') main()
3a984e01afccce5e87875486738da27f719e9b11
kevinnaguirre9/python-from-zero
/CalculadoraPython.py
2,864
4
4
import numpy as np from math import * def menu(): while True: print("1.- Sumar") print("2.- Restar") print("3.- Multiplicar") print("4.- Dividir") print("5.- Potencia") print("6.- Raíz") print("0.- Exit") try: op = int(input("Elija una opcion ")) if op==1: sumar() elif op==2: restar() elif op==3: multiplicar() elif op==4: dividir() elif op==5: potencia() elif op==6: raiz() elif op==0: break except ValueError: print("Input inválido") def sumar(): try: n1 = float(input("Enter first number: ")) n2 = float(input("Enter second number: ")) suma = n1+n2 print("El resultado de {} + {} es: {} ".format(n1,n2,suma)) except ValueError: print("Input inválido") def restar(): try: n1 = float(input("Ingrese el primer número: ")) n2 = float(input("Ingrese el segundo número: ")) resta = n1-n2 print("El resultado de {} - {} es: {} ".format(n1,n2,resta)) except ValueError: print("Input inválido") def multiplicar(): try: n1 = float(input("Ingrese el primer número: ")) n2 = float(input("Ingrese el segundo número: ")) mult = n1*n2 print("El resultado de {} * {} es: {} ".format(n1,n2,mult)) except ValueError: print("Input inválido") def dividir(): try: n1 = float(input("Ingrese el primer número: ")) n2 = float(input("Ingrese el segundo número: ")) div = n1/n2 print("El resultado de {} / {} es: {} ".format(n1,n2,div)) except ValueError: print("Input inválido") except ZeroDivisionError as zero_err: print("ERROR:", zero_err) def potencia(): try: n1 = int(input("Ingrese la base: ")) n2 = int(input("Ingrese el exponente: ")) power = pow(n1, n2) print("El resultado de {} ^ {} es: {} ".format(n1,n2,power)) except ValueError: print("Input inválido") def raiz(): try: n1 = int(input("Ingrese el radicando:")) n2 = int(input('Ingrese el índice:')) if n1 < 0 | n2 < 0: print('El número debería ser positivo') else: raiz = pow(n1, 1/n2) print("El resultado es: {} ".format(raiz)) except ValueError: print("Input inválido") # Lo probamos menu() print("Thank you for using the system")
30ec9be80209d5a43efa1276186f8f7625745869
777preethi/PythonSample
/syntax.py
307
3.796875
4
print("Python Basic Syntax") print("Python Indentations:") if 5 > 2: print("Five is greater than two!") print("Python Comments:") #This is a comment. print("There is a comment above.") print("Python Docstrings:") """This is a multiline docstring.""" print("There is a multiline docstring above.")
b7b191993866d8d10c92cc9e299bdb294d5d819e
rcsbiotech/learnerboi
/03_rosalind/old_stronghold_scripts/19_SharedMotif.py
1,431
4.125
4
#!/usr/bin/env python3 """ ----------------------------------------------------------------------------- A common substring of a collection of strings is a substring of every member of the collection. We say that a common substring is a longest common substring if there does not exist a longer common substring. For example, "CG" is a common substring of "ACGTACGT" and "AACCGTATA", but it is not as long as possible; in this case, "CGTA" is a longest common substring of "ACGTACGT" and "AACCGTATA". Note that the longest common substring is not necessarily unique; for a simple example, "AA" and "CC" are both longest common substrings of "AACC" and "CCAA". Given: A collection of k (k≤100) DNA strings of length at most 1 kbp each in FASTA format. Return: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.) http://rosalind.info/problems/lcsm/ ----------------------------------------------------------- rcs.biotec@gmail.com """ ## Bibliotecas comuns de FASTA import sys ## Para leitura de arquivos from Bio import SeqIO ## Para captura de arquivos FASTA from Bio.Seq import Seq ## Processamento de sequências ## Abre o arquivo # fasta_fh = open(sys.argv[1], 'r') fasta_fh = open("19_SharedMotif.py", 'r') print(fasta_fh) ## Captura a sequência única sequence = SeqIO.read(fasta_fh, "fasta") strseq = str(sequence.seq)
5f7a69e20d383e4a64c2a21a09d0455454adecaa
bloverton/MiningSomeData
/scripts/preprocessing/test.py
1,012
3.515625
4
import time import json import pandas as pd import matplotlib.pyplot as plt def main(): print('Starting review_count normalization') df = pd.read_csv("optimized_yelp_academic_dataset_user1.csv") print("Finished Reading .csv file") #print(df.info(memory_usage='deep')) print("Processing min-max algorithm") df['review_count'] = get_max_min(df['review_count']) print("Finished min-max algorithm") print('Starting df -> csv conversion') df.to_csv('yelp_user_dataset_normalized.csv', index=False) print('\nFinished Data Transformation') print(df.head()) def get_max_min(df): max = df.max() min = df.min() df = df.map(lambda x: (x - min / (max - min))) return df def json_to_csv(): df = pd.read_json("optimized_yelp_academic_dataset_user.json", orient="columns", lines=True) df.to_csv('optimized_yelp_academic_dataset_user1.csv', index=False) if __name__ == "__main__": start = time.time() main() print(time.time() - start)
91827ba07dc8123c9639b27f049b860aa5b9a127
albertojr/estudospython
/ex024.py
270
4.03125
4
nome = input('Digite o nome de uma cidade: ').strip().upper()#removo os espaço e deixo tudo maisculo print('Se o retorno for true, tem a palavra SANTO.\nCaso for False, não tem a palavra') print('\n\nRetorno:{}'.format(nome[:5] == 'SANTO'))#leio as 5 primeiras letras
9c4b1dc3fc9f48e7fd400dc10fd441de2e3074bc
Asurada2015/Python-Data-Analysis-Learning-Notes
/Matplotlib/demo_00Mofandemo/00_ceshi_demo.py
223
3.671875
4
"""测试linspace,meshgrid函数""" import matplotlib.pyplot as plt import numpy as np nx, ny = (3, 2) x = np.linspace(0, 1, nx) y = np.linspace(0, 1, ny) xv, yv = np.meshgrid(x, y) # print(x) # print(y) print(xv) print(yv)
81c5006758e185cbb5127558096946ac2360422b
praneethaa83/The-Sparks-Foundation---Task-1
/task1.py
1,414
3.59375
4
#TASK 1 #M.PRANEETHAA #importing the required libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics # importing the dataset as a CSV file data=pd.read_csv("C:/Users/praneethaa m/Desktop/task1dataset.csv") data data.head(10) data.corr() #plotting the given dataset df=data[['Hours','Scores']] sns.pairplot(df,kind="scatter") plt.show() #SPLITTING THE DATASET X = data.iloc[:, :-1].values y = data.iloc[:, 1].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) #training dataset regressor = LinearRegression() regressor.fit(X_train, y_train) line = regressor.predict(X) # Plotting for the test data plt.scatter(X, y) plt.plot(X, line,color='red'); plt.show() #predicted values vs actual values y_pred = regressor.predict(X_test) df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) df df.plot.bar() #The predicted value hours=9.25 pred_score=regressor.predict([[hours]]) print("HOURS={}".format(hours)) print("PREDICTED SCORES={}".format(pred_score[0])) #EVALUATING THE ACCURACY OF THE MODEL print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
82a5880a96f86590c01e5bf99f41c9c36df722f5
arumnenden/pdpbo3-Nenden-Bucin
/main.py
7,139
3.625
4
from tkinter import * import sqlite3 root = Tk() root.title("Halaman Reservasi") root.geometry("600x410") #Databases #Create a database or connect to one conn = sqlite3.connect('data.db') #Create cursor c = conn.cursor() #create table # c.execute(""" CREATE TABLE couple( # nama_cowo text, # nama_cewe text, # no_telepon integer # #view text, # #Extra text, # #Paket text # )""") #Create submit function def submit(): #Create a database or connect to one conn = sqlite3.connect('data.db') #Create cursor c = conn.cursor() #Insert Into Table c.execute("INSERT INTO couple VALUES (:nama_cowo, :nama_cewe, :no_telepon)", { 'nama_cowo': nama_cowo.get(), 'nama_cewe': nama_cewe.get(), 'no_telepon': no_telepon.get() # 'view': view(), # 'Extra': Extra(), # 'Paket': Paket() }) #commit Changes conn.commit() #close Connection conn.close() #Clear The Text boxes nama_cowo.delete(0, END) nama_cewe.delete(0, END) no_telepon.delete(0, END) # view.delete(0, END) # Extra.delete(0, END) # Paket.delete(0, END) #Create Show data function def query(): top_q = Toplevel() top_q.title('Halaman Data') top_q.geometry("450x150") #Create a database or connect to one conn = sqlite3.connect('data.db') #Create cursor c = conn.cursor() #query the database c.execute("SELECT * FROM couple") records = c.fetchall() print(records) #Loop thru Results print_records = '' for record in records[0]: print_records += str(record) + "\n" query_label = Label(top_q, text=print_records) query_label.grid(row=0, column=0, columnspan=2) #commit Changes conn.commit() #close Connection conn.close() #Create clear data function def clear(): top_q = Toplevel() top_q.title('Halaman Data') top_q.geometry("450x150") #Create a database or connect to one conn = sqlite3.connect('data.db') #Create cursor c = conn.cursor() #delete a record lbl1 = Label(top_q, text="SEMUA DATA TELAH TERHAPUS ").pack()#isi Windows Baru c.execute("DELETE from couple WHERE oid=PLACEHOLDER") #commit Changes conn.commit() #close Connection conn.close() #===================================== Label Judul =======================================. Label_reser = Label(root, text="RESERVASI HERE!") #Mendorongnya ke layar Label_reser.grid(row=0, column=1, padx=10, pady=10) #=================================Create Text Box Label==================================== nama_cowo_label = Label(root, text="Nama Cowo") nama_cowo_label.grid(row=2, column=0) nama_cewe_label = Label(root, text="Nama Cewe") nama_cewe_label.grid(row=3, column=0) no_telepon_label = Label(root, text="No Telepon") no_telepon_label.grid(row=4, column=0) view_label = Label(root, text="View") view_label.grid(row=5, column=0) Extra_label = Label(root, text="Extra") Extra_label.grid(row=6, column=0) Paket_label = Label(root, text="Paket") Paket_label.grid(row=8, column=0) #==================================Create text Boxes========================================= nama_cowo = Entry(root, width=30) nama_cowo.grid(row=2, column=1, padx=30) nama_cewe = Entry(root, width=30) nama_cewe.grid(row=3, column=1,) no_telepon= Entry(root, width=30) no_telepon.grid(row=4, column=1) #=================================Create Dropdown(view)============================================= clicked = StringVar() clicked.set("City view")#untuk tampilan nya drop = OptionMenu(root, clicked, "City view", "Nature View", "Pool View", "Beach View") #pilihan chckbox drop.grid(row=5, column=1, ipadx=40, padx=1) #===============================Create Chackbox (Extra)=============================================== c1 = IntVar()#var nya c2 = IntVar()#var nya c3 = IntVar()#var nya c4 = IntVar()#var nya c1 = Checkbutton(root, text="Flower", variable=c1)#chackbox nya c1.grid(row=6, column=1)#munculin c2 = Checkbutton(root, text="Coklate", variable=c2)#chackbox nya c2.grid(row=6, column=2)#munculin c3 = Checkbutton(root, text="Candle", variable=c3)#chackbox nya c3.grid(row=7, column=1)#munculin c4 = Checkbutton(root, text="Instrumen", variable=c4, padx=20)#chackbox nya c4.grid(row=7, column=2)#munculin #===============================Create Radio (Paket)===================================================== r = IntVar() Radiobutton(root, text="Anniversary", variable=r, value=1).grid(row=8, column=1)#untuk buat pilihnan radio 1 Radiobutton(root, text="Brithday", variable=r, value=2).grid(row=8, column=2)#untuk buat pilihan radio 2 Radiobutton(root, text="Date", variable=r, value=3).grid(row=9, column=1)#untuk buat pilihnan radio 1 Radiobutton(root, text="Dinner", variable=r, value=4).grid(row=9, column=2)#untuk buat pilihan radio 2 #===============================Create Per-Bottunan============================================ #Create Submit Button * submit_btn = Button(root, text="Submit", command=submit) submit_btn.grid(row=10, column=0, columnspan=3, pady=10, padx=10, ipadx=95) #Create Exit Button * button_quit = Button(root, text="Exit", command=root.quit) button_quit.grid(row=11, column=0, columnspan=3, pady=10, padx=10, ipadx=102) #Create a Query Button / ngeliat seluruh data query_btn = Button(root, text = "See All Submissons", command=query) query_btn.grid(row=2, column=10, columnspan=3, pady=10, ipadx=20) #Create Clear Button clear_btn = Button(root, text="Clear Submissons", command=clear) clear_btn.grid(row=3, column=10, columnspan=3, pady=10, ipadx=20) #Create About Button def window_about():#fungsi untuk munculin window about top_a = Toplevel() top_a.title('Halaman About') top_a.geometry("950x150") lbl1 = Label(top_a, text="JUDUL: Bucin (Budak Cinta) ").grid(row=1, column=0, sticky= "w")#isi Windows Baru lbl2 = Label(top_a, text="DESKRIPSI: App Bucin ini merukapan Aplikasi reservasi khusus yang kami buat untuk para couple yang akan mengadakan acara di restoran kami").grid(row=2, column=0, sticky= "w")#isi Windows Baru lbl3 = Label(top_a, text="Acara seperti anniversary, birthday, Dinner , dll yang sudah kami sediakan di bagian ‘paket’. ").grid(row=3, column=0, sticky= "w")#isi Windows Baru lbl4 = Label(top_a, text="Mereka juga dapat memilih view yang diinginkan, serta dapat memilih tambahan extra fasilitas apa saja yang ada, seperti buket bunga, sampai iringan instrumen biola pribadi.").grid(row=4, column=0,sticky= "w")#isi Windows Baru lbl5 = Label(top_a, text="Dengan ada nya App nya ini di harapkan dapat membatu mereka para couple untuk menciptakan pengalaman yang terencana , nyaman dan romantis. ").grid(row=5, column=0,sticky= "w")#isi Windows Baru lbl6 = Label(top_a, text="PEMBUAT: Nenden Citra S.N / 1908589 ").grid(row=6, column=0, sticky= "w")#isi Windows Baru about_btn = Button(root, text="About", command = window_about) about_btn.grid(row=4, column=10, columnspan=3, pady=10, ipadx=20) #commit Changes conn.commit() #close Connection conn.close() root.mainloop()
99548b09f52a00a531433a1414024d5519898b4f
codeAligned/Programming-Interviews-Problems
/The Algorithm Design Manual/fibo.py
438
3.5
4
def fibo_rec(n): if n==0: return 0 if n == 1: return 1 else: return fibo_rec(n-1)+fibo_rec(n-2) def fibo_it(n): result=0 prv=1 prvprv=0 if n<2: return n for i in range(1,n): result= prv + prvprv prvprv=prv prv=result i+=1 return result fibTable = {1:1, 2:1} def fib_rec_hash(n): if n in fibTable: return fibTable[n] else: fibTable[n]=fib_rec_hash(n-1)+fib_rec_hash(n-2) return fibTable[n]
0e6b0712f81f93e857905496e43064971d45e78e
CodingClubGECB/practice-questions
/Python/Week-1/01_multiplication_table.py
146
4.34375
4
#1.Write a program to print the multiplication table of a number upto 10. n = int(input()) for i in range(11): print(n, " x ", i, " = ", n*i)
5989c6094c599ba9d3cc0ab2dc974f81123a7b91
gabriellaec/desoft-analise-exercicios
/backup/user_058/ch21_2019_08_26_20_34_56_596427.py
105
3.71875
4
X=(float(input("Qual o valor da conta? ") y=(1.1)*x print("Valor da conta com 10%: R$ {0:.2f}".format(y))
42eb7fcda7769533db5f422ffc69734ef15081e7
bodii/test-code
/python/python-cookbook-test-code/5 section/13.py
2,479
3.734375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Topic: 第五章:文件与 IO Desc: 所有程序都要处理输入和输出。这一章将涵盖处理不同类型的文件,包括文本和二 进制文件,文件编码和其他相关的内容。对文件名和目录的操作也会涉及到。 Title; 获取文件夹中的文件列表 Issue:你想获取文件系统中某个目录下的所有文件列表 Answer: 使用 os.listdir() 函数来获取某个目录中的文件列表 """ import os names = os.listdir('../test file/') ''' 结果会返回目录中所有文件列表,包括所有文件,子目录,符号链接等等。如果你 需要通过某种方式过滤数据,可以考虑结合 os.path 库中的一些函数来使用列表推导。 ''' import os names = [name for name in os.listdir('../test file/') if os.path.isfile(os.path.join('somedir', name))] dirnames = [name for name in os.listdir('../test file/') if os.path.isdir(os.path.join('somedir', name))] ''' 字符串的 startswith() 和 endswith() 方法对于过滤一个目录的内容也是很有用 的。 ''' pyfiles = [name for name in os.listdir('./') if name.endswith('.py')] ''' 对于文件名的匹配,你可能会考虑使用 glob 或 fnmatch 模块。 ''' import glob pyfiles = glob.glob('./*.py') from fnmatch import fnmatch pyfiles = [name for name in os.listdir('./') if fnmatch(name, '*.py')] ''' 获取目录中的列表是很容易的,但是其返回结果只是目录中实体名列表而已。如 果你还想获取其他的元信息,比如文件大小,修改时间等等,你或许还需要使用到 os.path 模块中的函数或着 os.stat() 函数来收集数据。 ''' import os import glob import datetime pyfiles = glob.glob('*.py') name_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name)) for name in pyfiles] for name, size, mtime in name_sz_date: print('filename:%s filesize:%i filemtime:%f' % (name, size, mtime)) ''' 最后还有一点要注意的就是,有时候在处理文件名编码问题时候可能会出现一些问 题。通常来讲,函数 os.listdir() 返回的实体列表会根据系统默认的文件名编码来 解码。但是有时候也会碰到一些不能正常解码的文件名。关于文件名的处理问题,在 5.14 和 5.15 小节有更详细的讲解。 '''
45c8452783f848095d41f37c9d5737ce6e5cc7da
Harishkumar18/data_structures
/450_qn_ds_lb/move_neg_no_one_side.py
367
4.03125
4
""" Move all the negative elements to one side of the array """ def move_negative_nos(arr): neg = 0 pos = len(arr)-1 while neg <= pos: if arr[neg] < 0 : neg += 1 else: arr[neg], arr[pos] = arr[pos], arr[neg] pos -= 1 return arr arr = [9, -8, 5, 0, -4, -6] res = move_negative_nos(arr) print(res)
ec846a3040ebb614f27740762657c8709145598b
InjiChoi/algorithm_study
/정렬 알고리즘/quicksort.py
440
3.796875
4
# 퀵 정렬 구현 def quicksort(data): if len(data)<1: return data left = list() right = list() pivot = data[0] for i in range(1, len(data)): if pivot > data[i]: left.append(data[i]) else: right.append(data[i]) return quicksort(left) + [pivot] + quicksort(right) # time complexity = n*logn # test # a = [26, 27, 42, 10, 14, 19, 35, 20] # print(quicksort(a))
649600fdd1eb2bea61ac49c67384e5dcc85808df
AdamZhouSE/pythonHomework
/Code/CodeRecords/2711/58547/272200.py
1,171
3.5
4
def is_avail(word0, word1): if len(word0) != len(word1): return False diff_index = [] i = 0 while i < len(word0): if word0[i] != word1[i]: diff_index.append(i) if len(diff_index) > 2: return False i += 1 if len(diff_index) != 2: return False if word0[diff_index[0]] == word1[diff_index[1]] and \ word0[diff_index[1]] == word1[diff_index[0]]: return True return False def func(): words = input()[2:-2].split("\",\"") groups = [[words[0]]] words.pop(0) for word in words: i = 0 flag = False break_flag = False while i < len(groups): j = 0 while j < len(groups[i]): if is_avail(word, groups[i][j]): groups[i].append(word) break_flag = True flag = True if break_flag: break j += 1 if break_flag: break i += 1 if not flag: groups.append([word]) # print(groups) print(len(groups)) func()
d0163eed15aa96bb9b2f01c56eee36a340b952a2
MayKeziah/CSC110
/assn6_funcs.py
2,229
4.28125
4
#Keziah May #05/16/18 #CSC110 #Assn6 def main(): print("This program calculates fuel efficiency on a multi-leg journey.\n" "It returns the MPG per leg and the MPG overall.\n") #get the starting odometer reading StartMiles = float(input("\nPlease enter your starting odometer reading:\n")) BuildLists(StartMiles) #A function that uses a sentinel loop to build 2 lists from a users input #A list of how much gas has been used #A list of odometer readings def BuildLists(StartMiles): #set variables GasList = [0] MileList = [StartMiles] Leg = 1 prompt = input("Please enter your current odometer reading\n" "and the amount of gas used separated by a space.\n" "When finished, press enter to calculate.\n" "Leg 1: ") #Start the sentinel loop for legs while prompt != "": try: #Separate miles traveled and Gas used, Convert to float Mi, Gas = prompt.split() Mi = float(Mi) Gas = float(Gas) #Form lists of miles traveled and gas used MileList.append(Mi) GasList.append(Gas) #track legs for user Leg = Leg+1 #Prompt for new leg newprompt = "Leg " + str(Leg) + ": " prompt = input(newprompt) except ValueError: print("Oops! Try again!") newprompt = "Leg " + str(Leg) + ": " prompt = input(newprompt) # return #Loop through Mile and Gas lists for each leg. #Count totals and calc MPG per leg GasTotal = 0 MileTotal = 0 for i in range(len(GasList)): GasTotal = GasTotal + GasList[i] MileTotal = MileTotal + MileList[i] if i == 0: print("\nFuel Efficiency for each leg:") #Calculate the MPG for each leg and print it else: MPG = (MileList[i]-MileList[i-1])/(GasList[i]-GasList[i-1]) print("For leg "+str(i)+",", MPG, "MPG.") #Print total MPG TotalMPG = (MileTotal-MileList[0])/GasTotal print("\nYour overall fuel efficiency for this trip was", round(TotalMPG, 2), "MPG.") main()
c636d9e00ff9cf0fff8218de3c3c6a1e90b70278
MaximeWbr/Expedia_Project
/Pokemon_Game/Package_Object/Object.py
134
3.75
4
from abc, import ABC, abstractmethod class Object(ABC): def __init__(self): self.name = "" self.price = 0 super().__init__()
0826e76a4f39803c8b2c0bb9c6c9487b8e748500
VladiGH/FP_Python
/Labo6_ejercicio9.py
709
3.84375
4
"""Hacer un programa que dado un rango de números (por ejemplo de 10 hasta 100) y muestre todos los números que son múltiplo de x número en ese rango (por ejemplo los múltiplos de 3)""" flag = 0 while(flag == 0): try: limInferior = int(input("Ingresa el lim inferior del rango: ")) limSuperior = int(input("Ingresa el lim superior del rango: ")) multiplo = int(input("Ingresa el múltiplo a evaluar: ")) for i in range (limInferior, limSuperior+1): if(i % multiplo == 0): print("Es múltiplo de "+ str(multiplo) +": "+ str(i) ) flag = 1 except ValueError: print("Tienes que meter un número, intentalo de nuevo")
bd9a610d76da05f2bf63bc11a74ac228a8c1177f
Nooder/Cracking-Codes-With-Python
/Chapter 15 - HACKING THE AFFINE CIPHER/AffineHacker.py
1,832
4.0625
4
#!python3 # Chapter 15 Project - Hacking the Affine Cipher import AffineCipher, CryptoMath, DetectEnglish SILENT_MODE = False def main(): message = """5QG9ol3La6QI93!xQxaia6faQL9QdaQG1!!axQARLa!!AuaRLQADQALQG93!xQxaGaAfaQ1QX3o1RQARL9Qda!AafARuQLX1LQALQI1iQX3o1RN"Q-5!1RQP36ARu""" hackedMessage = hackAffine(message) if hackedMessage != None: # Display the plaintext that was decrypted print(hackedMessage) else: print("Failed to hack encryption.") def hackAffine(message): print("Hacking...") # Allow program to stop on Windows or Linux respectively print("(Press Ctrl-C (Windows) or Ctrl-D (Mac/Linux) to stop at any time.)") # Brute force by looping through every possible key for key in range(len(AffineCipher.SYMBOLS) ** 2): keyA = AffineCipher.getKeyParts(key)[0] if CryptoMath.gcd(keyA, len(AffineCipher.SYMBOLS)) != 1: continue decryptedText = AffineCipher.decryptMessage(key, message) if not SILENT_MODE: print("Tried Key %s... (%s)" % (key, decryptedText)) if DetectEnglish.isEnglish(decryptedText): # Check with the user if the decrypted text has been found print() print("Possible encryption hack:") print("Key: %s" % key) print("Decrypted message: %s" % decryptedText[:200]) print() print("Enter 'D' for done, or just press Enter to continue hacking:") response = input("> ") # Success if response.upper().strip().startswith("D"): return decryptedText # Failed to find plaintext return None # If AffineHacker.py was run (instead of imported as a module), call # the main() function if __name__ == '__main__': main()
57a3213207726e011f38bcd944bdc1b91ababb79
jacktnp/PSIT60
/Week 11/4-RunLengthDecoding.py
499
3.609375
4
""" PSIT Week 11 Wiput Pootong (60070090) Run Length Decoding """ def main(): """ Convert encoded string into decoded """ strings = input() counts = [] chars = [] temp = "" for char in strings: if char.isdigit(): temp += char else: counts.append(int(temp)) temp = "" chars.append(char) result = "" for count in range(len(chars)): result += (counts[count] * chars[count]) print(result) main()
646b571b771c1a79b88bf78728ac29727eb25aaf
greshem/develop_python
/check_chinese.py
1,098
3.6875
4
#!/usr/bin/python #coding:utf-8 def is_chinese(uchar): """ #判断一个unicode是否是汉字 """ if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True else: return False def contains_chinese(input): chinese = unicode(input, "utf-8") for each in chinese: if is_chinese(each): return True; return False; #ascii 的 遍历的方式 会出现错误, utf8 本质是ascii def ascii_error_check_chinese(): a="文字"; #for each utf8 for each in a: if is_chinese(each): print "%s is chinest "%each; else: print "is not chinest "; # for each unicode unicode 的遍历. def check_ok_(): a="文字"; #b=a.encode(); s2 = unicode(a, "utf-8") #s3= unicode(s2, "utf-8") errrr for each in s2: if is_chinese(each): print "%s is chinest "%each; else: print "is not chinest "; print contains_chinese("我的中国") print contains_chinese("bbbbbba中") print contains_chinese("bbbbbba")
d59910760266b28aa8dc2ed468a4de275b33873f
tainenko/Leetcode2019
/leetcode/editor/en/[1716]Calculate Money in Leetcode Bank.py
1,390
3.59375
4
# Hercy wants to save money for his first car. He puts money in the Leetcode # bank every day. # # He starts by putting in $1 on Monday, the first day. Every day from Tuesday # to Sunday, he will put in $1 more than the day before. On every subsequent # Monday, he will put in $1 more than the previous Monday. # # Given n, return the total amount of money he will have in the Leetcode bank # at the end of the nᵗʰ day. # # # Example 1: # # # Input: n = 4 # Output: 10 # Explanation: After the 4ᵗʰ day, the total is 1 + 2 + 3 + 4 = 10. # # # Example 2: # # # Input: n = 10 # Output: 37 # Explanation: After the 10ᵗʰ day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 # + 3 + 4) = 37. Notice that on the 2ⁿᵈ Monday, Hercy only puts in $2. # # # Example 3: # # # Input: n = 20 # Output: 96 # Explanation: After the 20ᵗʰ day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 # + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. # # # # Constraints: # # # 1 <= n <= 1000 # # # Related Topics Math 👍 477 👎 14 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def totalMoney(self, n: int) -> int: return sum(range(1, 8)) * (n // 7) + sum(range(n // 7 + 1, n % 7 + n // 7 + 1)) + 7 * sum(range(n // 7)) # leetcode submit region end(Prohibit modification and deletion)
79f8d1b6d92fe6e5c5bda0b9b30a557ec432281c
kautilya/billing
/Identity.py
1,388
3.5
4
import logging; class Entity: def __init(self): pass; def __init__(self, name, email, spouse, semail): self._name = name; self._email = email; self._spouse = spouse; self._semail = semail; def printData(self) : logging.info("Entity: %s <%s>\n", self._name, self._email); def name(self) : return self._name; def memNames(self) : return self._name; def getEmail(self) : return self._email; def getSpouse(self) : return self._spouse; def getSpouseEmail(self) : return self._semail; class EntityGroup: def __init__(self): pass; def __init__(self, name): self._name = name; self._entities = set(); self._memNames = ""; pass; def name(self) : return self._name; def memNames(self) : return self._memNames; def addEntity(self, entity): self._entities.add(entity); if (len(self._memNames) > 0) : self._memNames = self._memNames + " " + entity.name(); else : self._memNames = self._memNames + entity.name(); def add(self, entity): if isinstance(entity, Entity) : self.addEntity(entity); elif isinstance(entity, EntityGroup) : for e in entity._entities : self.addEntity(e); def getEntities(self) : return self._entities; def printData(self) : logging.info("EngityGroup: %s : %s\n", self._name, str(self._entities));
1922f14e27907d4b02f0e55c64e007fe8b7eebf3
ash/python-tut
/course/tasks/count-words-in-file.py
197
3.9375
4
filename = input('File name: ') content = '' for line in open(filename): content += line #print(content.split()) words_count = len(content.split()) print('%d words in the file' % words_count)
7bbc94e35ba64c9288f5dc2c398d2c865b2dc125
fwparkercode/IntroProgrammingNotes
/Notes/Spring2020/Ch7LabStarterCode.py
1,263
3.734375
4
''' Chapter 7 Lights Out ''' import random done = False # print numbers 0 to 9 using a for loop # override "\n" by using keyword argument end = " " print("Francis", end=" ") print("Parker") # create a random X O list lights = [] for i in range(10): flip = random.randrange(2) if flip == 0: lights.append("O") else: lights.append("X") while not done: for i in range(10): print(i, end=" ") print() for light in lights: print(light, end=" ") print() choice = int(input("Flip a switch 0 to 9: ")) print() if lights[choice] == "X": lights[choice] = "O" else: lights[choice] = "X" if choice > 0: if lights[choice - 1] == "X": lights[choice - 1] = "O" else: lights[choice - 1] = "X" if choice < 9: if lights[choice + 1] == "X": lights[choice + 1] = "O" else: lights[choice + 1] = "X" # check for win if lights == ["X", "X", "X", "X", "X", "X", "X", "X", "X", "X"]: print("You win!") done = True for i in range(10): print(i, end=" ") print() for light in lights: print(light, end=" ") print()
ce9915bca1ad0951f097d777cb752091269336c1
rajadavidh/learning-opencv-python
/source/_11_template_matching.py
1,251
3.703125
4
# Run command: python _11_template_matching.py # We are going to implement basic object recognition by finding identical # regions of an image that match a template we provide. # Further reading: # https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html # Importing libraries as shortcut import numpy as np import cv2 # import matplotlib.pyplot as plt # Converting image to greyscale img_rgb = cv2.imread('../data/fisher-anyer-beach-2016-raja-david.jpg') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # template = cv2.imread('../data/palm-tree-pattern.png', 0) template = cv2.imread('../data/palm-tree-pattern.jpg', 0) width, height = template.shape[::-1] # Load the template result = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) # Search the template pattern with 80% match threshold = 0.8 loc = np.where(result >= threshold) # Mark all the matches with yellow box # Read more about zip function: https://realpython.com/python-zip-function/ for point in zip(*loc[::-1]): cv2.rectangle(img_rgb, point, (point[0] + width, point[1] + height), (0, 255, 255), 2) # Show the image cv2.imshow('Detected', img_rgb) # Wait until any key is pressed cv2.waitKey(0) # Close everything cv2.destroyAllWindows()
87e7ea2ba8d88dca72ee07940707872a8dd68816
nickfang/classes
/projectEuler/webScraping/problemTemplates/348.py
587
3.859375
4
# Sum of a square and a cube # #Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way. #Consider the palindromic numbers that can be expressed as the sum of a square and a cube, both greater than 1, in exactly 4 different ways. #For example, 5229225 is a palindromic number and it can be expressed in exactly 4 different ways: #2285^2 + 203 #2223^2 + 663 #1810^2 + 1253 #1197^2 + 1563 #Find the sum of the five smallest such palindromic numbers. # import time startTime = time.time() print('Elapsed time: ' + str(time.time()-startTime))
982922076fd3ebac94e081475675e18922d1e1cf
TeonD/Python_Beginnings
/SuSu/DICE.py
1,759
3.921875
4
import random print("Lets play dice") print("Hit enter to roll") input() leaveprogram = 0 while leaveprogram != "q": number=random.randint(1,6) if number == 1: print("[-------------]") print("[ ]") print("[ O ]") print("[ ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input() if number == 2: print("[-------------]") print("[ ]") print("[ O O ]") print("[ ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input() if number == 3: print("[-------------]") print("[ O ]") print("[ O ]") print("[ O ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input() if number == 4: print("[-------------]") print("[ O O ]") print("[ ]") print("[ O O ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input() if number == 5: print("[-------------]") print("[ O O ]") print("[ O ]") print("[ O O ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input() if number == 6: print("[-------------]") print("[ O O ]") print("[ O O ]") print("[ O O ]") print("[-------------]") print("To leave program type 'q'") leaveprogram = input()
dc0599621a01b12f83c3276d18cee00b71a80f33
LeoHung/myleetcode
/Roman_to_Integer/solution.py
1,334
3.53125
4
class Solution: # @return an integer def romanToInt(self, s): n1_num = ["", "I", "II","III", "IV", "V", "VI", "VII", "VIII", "IX"] n2_num = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] n3_num = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] n4_num = ["", "M", "MM", "MMM"] ret = 0 i = 0 for k in range(len(n4_num)-1, 0, -1): e = n4_num[k] if s[i:].startswith(e): ret += k * 1000 i += len(e) for k in range(len(n3_num)-1, 0, -1): e = n3_num[k] if s[i:].startswith(e): ret += k * 100 i += len(e) for k in range(len(n2_num)-1, 0, -1): e = n2_num[k] if s[i:].startswith(e): ret += k * 10 i += len(e) for k in range(len(n1_num)-1, 0, -1): e = n1_num[k] if s[i:].startswith(e): ret += k i += len(e) return ret if __name__ == "__main__": s = Solution() print s.romanToInt("MCMLIV") print s.romanToInt("MCMLIV") == 1954 print s.romanToInt("MCMXC") print s.romanToInt("MCMXC") == 1990 print s.romanToInt("MMXIV") print s.romanToInt("MMXIV") == 2014
49ba3435b679a809ee1310529ccecb55c54d107f
xlocux/Scripts
/favhash.py
724
3.546875
4
# favhash is a script to obtain a favicon hash. # then search in shodan https://www.shodan.io/search?query=http.favicon.hash%3A-538460259&page=3 # or use qshodanscript to obtains IP addresses import sys import mmh3 import requests import argparse import base64 parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', help='Input a: URL', action='store') args = parser.parse_args() def parser_error(errmsg): print('Usage: python %s [Options] use -h for help' % sys.argv[0]) print('Error: %s' % errmsg) sys.exit() url = args.url if url[len(url)-1] != "/": url = url + "/" resp = requests.get(url + "favicon.ico") ico = base64.encodebytes(resp.content) hash = mmh3.hash(ico) print (hash)
abf3842405c2a21881a257124fb54b70c3643fe3
decodingjourney/BeginnerToExpertInPython
/Functions/functions.py
664
3.671875
4
def python_food(): width = 80 text = "Spam and Eggs" left_margin = (width - len(text)) // 2 print(" " * left_margin, text) def center_text(*args): text = "" for arg in args: text += str(arg) + " " left_margin = (80 - len(text)) // 2 return " " * left_margin + text # with open("centered", mode='w') as center_file: with open("menu", mode='w') as menu: s1 = center_text("Spam and Eggs") print(s1, file=menu) s2 = center_text("Spam Spam and Eggs Eggs") print(s2, file=menu) s3 = center_text("Anand Kumar Jha Sonam Kumari Ananya Jha") print(s3, file=menu) s4 = center_text("First", "Second", 3, 4, "Five") print(s4, file=menu)
5ef599e74ed4cc0d9000434228e1696a0ecda224
TinaCloud/leanleet
/380.py
975
3.515625
4
class RandomizedSet: def __init__(self): self.top_key = 0 self.value_dict = {} self.key_dict = {} def insert(self, val: int) -> bool: if val not in self.value_dict: self.value_dict[val] = self.top_key self.key_dict[self.top_key] = val self.top_key += 1 return True return False def remove(self, val: int) -> bool: if val in self.value_dict: used_key = self.value_dict[val] self.top_key -= 1 if used_key != self.top_key: replaced_value = self.key_dict[self.top_key] self.key_dict[used_key] = replaced_value self.value_dict[replaced_value] = used_key del self.value_dict[val] del self.key_dict[self.top_key] return True return False def getRandom(self) -> int: return self.key_dict[random.randint(0,self.top_key-1)]
b45c47597afd831d1c0d7f665c451d397db3032c
lamoureux-sylvain/BlackJack
/hand.py
2,355
3.59375
4
from cards import Card class Hand: def __init__(self, dealer=False): self.dealer = dealer self.cards = [] self.value = 0 self.check_ace = False def add_card(self, card): self.cards.append(card) def calculate_value(self): self.value = 0 if self.dealer: for card in self.cards: if card.value.isnumeric(): self.value += int(card.value) elif card.value == "A": self.aces() else: self.value += 10 else: for card in self.cards: if card.value.isnumeric(): self.value += int(card.value) elif card.value == "A" and not self.check_ace: if self.value <= 10: self.aces() else: self.value += 1 else: self.value += 10 def get_value(self): self.calculate_value() return self.value def display(self, nb_card): self.nb_card = nb_card if self.nb_card <= 2: if self.dealer: print(self.cards[0]) print("Carte cachée") print() else: print(self.cards[0]) print(self.cards[1]) print("Valeur:", self.get_value()) print() else: if self.dealer: for card in self.cards: print(card) print("Valeur:", self.get_value()) print() else: for card in self.cards: print(card) print("Valeur:", self.get_value()) print() def aces(self): if self.dealer: self.value += 11 if self.value > 21: self.value -= 10 else: if self.value == 10: self.value += 11 else: self.ace_value = 0 while self.ace_value != "1" and self.ace_value != "11": self.ace_value = input("Valeur de l'As: 1 ou 11 : ") print() self.check_ace = True self.value += int(self.ace_value)
23cabdc141d14347accb29a4a33abc5fc3821e3b
deborabr21/mycode
/fact/looping_challenge2.py
499
4.25
4
#!/usr/bin/env python3 farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] for dict in farms: #looping across every dictionary in the list (farms) # add something to check if the value of "name" is equal to "NE Farm" if dict["name"] == "NE Farm": print (dict["agriculture"])
57a81e9a846cf95a344554fb7f3cd1c053641de9
fergmack/efficient-python-code
/faster_loops.py
1,934
3.890625
4
# A list of integers that represents each Pokémon's generation has been loaded into your session called generations. You'd like to gather the counts of each generation and determine what percentage each generation accounts for out of the total count of integers. from collections import Counter generations = [4, 1, 3, 5, 1, 3, 2, 1, 5, 3] # counts number of elements in the list gen_counts = Counter(generations) # inefficent loop for gen, count in gen_counts.items(): # print(gen, count) total_count = len(generations) gen_percent = round(count / total_count * 100, 2) print( 'Generation {}: count = {:3} percentage = {}'.format(gen, count, gen_percent) ) # Write a better for loop that places a one-time calculation outside (above) the loop. Use the exact same syntax as the original for loop (simply copy and paste the one-time calculation above the loop). # Faster loops total_count = len(generations) for gen, count in gen_counts.items(): # print(gen, count) gen_percent = round(count / total_count * 100, 2) print( 'Generation {}: count = {:3} percentage = {}'.format(gen, count, gen_percent) ) # ----------- Holistic Conversion Loop ----------------- from itertools import combinations pokemon_types = ['Bug', 'Dark', 'Dragon', 'Electric', 'Fairy', 'Fighting', 'Fire', 'Flying', 'Ghost', 'Grass', 'Ground', 'Ice', 'Normal', 'Poison', 'Psychic', 'Rock', 'Steel', 'Water'] # # Collect all possible pairs using combinations() possible_pairs = [*combinations(pokemon_types, 2 )] # Gather all the possible pairs of Pokémon types. enumerated_tuples = [] # # Append each enumerated_pair_tuple to the empty list above for i, pair in enumerate(possible_pairs, 1): enumerated_pair_tuple = (i, ) + pair enumerated_tuples.append(enumerated_pair_tuple) # # Convert all tuples in enumerated_tuples to a list enumerated_pairs = [*map(list, enumerated_tuples)] print(enumerated_pairs)
8b9a38bf26dd9800a3a9f54ffb0e0614e2780f42
ConnerSick/Python-Challenge
/PyBank/main.py
1,690
3.734375
4
import os import csv csvpath = os.path.join(".." , "budget_data.csv") # define all variables profit_sum = 0 months = 0 profit_change = 0 total_change = 0 largest_increase = 0 largest_decrease = 0 row_count = 0 profit = [] month_list = [] greatest_increase_month = 0 greatest_decrease_month = 0 with open(csvpath,newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) # split csv values into 2 lists and count rows to determine number of months for row in csvreader: profit.append(int(row[1])) month_list.append(row[0]) profit_sum = profit_sum + (int(row[1])) row_count = row_count + 1 final_profit = row[1] print(f"Total months: {row_count}") print(f"Total: ${profit_sum}") # loop through lists to calculate changes between each month for x in range (0,row_count - 1): profit_change = int(profit[x+1]) - int(profit[x]) total_change = total_change + profit_change # largest increase if (profit[x+1] - profit[x]) > largest_increase: largest_increase = (profit[x+1] - profit[x]) greatest_increase_month = month_list[x+1] # Largest decrease if (profit[x+1] - profit[x]) < largest_decrease: largest_decrease = (profit[x+1] - profit[x]) greatest_decrease_month = month_list[x+1] print(f"Average Change: ${round(total_change/(row_count - 1),2)}") print(f"Greatest Increase in Profits: {greatest_increase_month} (${largest_increase})") print(f"Greatest Decrease in Profits: {greatest_decrease_month} (${largest_decrease})")
836363ddcef982ad8acded5f168057bb7cce16ca
alpiges/emukit
/emukit/core/loop/user_function.py
1,706
4.0625
4
""" This file contains the "OuterFunction" base class and implementations The outer function is the objective function in optimization, the integrand in quadrature or the function to be learnt in experimental design. """ import abc from typing import Callable, List import numpy as np from .user_function_result import UserFunctionResult class UserFunction(abc.ABC): """ The user supplied function is interrogated as part of the outer loop """ @abc.abstractmethod def evaluate(self, X: np.ndarray) -> List[UserFunctionResult]: pass class UserFunctionWrapper(UserFunction): """ Wraps a user-provided python function. """ def __init__(self, f: Callable): """ :param f: A python function that takes in a 2d numpy ndarray of inputs and returns a 2d numpy ndarray of outputs. """ self.f = f def evaluate(self, inputs: np.ndarray) -> List[UserFunctionResult]: """ Evaluates python function by providing it with numpy types and converts the output to a List of OuterFunctionResults :param inputs: List of function inputs at which to evaluate function :return: List of function results """ if inputs.ndim != 2: raise ValueError("User function should receive 2d array as an input, actual input dimensionality is {}".format(inputs.ndim)) outputs = self.f(inputs) if outputs.ndim != 2: raise ValueError("User function should return 2d array as an output, actual output dimensionality is {}".format(outputs.ndim)) results = [] for x, y in zip(inputs, outputs): results.append(UserFunctionResult(x, y)) return results
d522bb5401656e47183258c925bb7edc02ff31a1
Nine-Songs/Fundamentals_of_Python
/03/搜索最小值.py
284
3.796875
4
''' Returns the index of the minimun item O(n) ''' def indexOfMin(lyst): minIndex = 0 #the index of the minimum item is 0 currentIndex = 1 while currentIndex < len(lyst): if lyst[minIndex] > lyst[currentIndex]: minIndex = currentIndex currentIndex += 1 return minIndex
5eecf3913d57b27075f8b3b6c4b673968de28361
joaovicentesouto/INE5452
/lists/seven/p10.py
227
3.59375
4
# -*- coding: utf-8 -*- while True: a, b, c, d = input().split() a = int(a) b = int(b) c = int(c) d = int(d) if (a + b + c + d) == 0: break x = c * (a/2 + b) / d print("%.5f" % x)
910726d6542069c0891db12a29b8b9f0a6112b92
OCCOHOCOREX/HuangXinren-Portfolio
/Weekly Tasks/Week1/HuangXinren-Week1-Task1.py
525
4.125
4
number_list=[1,2,3,4,5,6.5] print("number list:" , number_list) def the_numbers(number_list): even_list=[] for number in number_list: if number % 2 == 0: even_list.append(number) return even_list even_number = the_numbers(number_list) print("even", even_number) def the_numbers(number_list): odd_list=[] for number in number_list: if number % 2 == 1: odd_list.append(number) return odd_list odd_number = the_numbers(number_list) print("odd", odd_number)
08693ca174d12eff737cc6a467d1159652787a31
astralblack/Calculator
/calc.py
1,262
4.5
4
# Astral's Calcultor # Date: 9.27.18 # Menu print("Hello welcome to my calculator!\n") print("1: Addition") print("2: Subtraction") print("3: Multiplication") print("4: Division\n") # Functions def addition(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 + num2 print("The total is : " + str(sum)) def subtraction(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 - num2 print("The total is : " + str(sum)) def multiplication(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 * num2 print("The total is : " + str(sum)) def division(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 / num2 print("The total is : " + str(sum)) # Used for selecting the operation the user wants to use choice = input("What operation would you like?") if choice == "1": addition() elif choice == "2": subtraction() elif choice == "3": multiplication() elif choice == "4": division()
22b6b83b25fc6b96208d93e0e5ec4c8eb54b6bd4
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/linkedlist/reverse.py
746
4.09375
4
""" Reverse a singly linked list. For example: 1 --> 2 --> 3 --> 4 After reverse: 4 --> 3 --> 2 --> 1 """ # # Iterative solution # T(n)- O(n) # def reverse_list(head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return prev # # Recursive solution # T(n)- O(n) # def reverse_list_recursive(head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head p = head.next head.next = None revrest = reverse_list_recursive(p) p.next = head return revrest
92225469265c939c4bbbd1529346809d7aada2ae
samuelyusunwang/quant-econ
/myExercise/05_numPy/ex01_polyval.py
311
3.59375
4
# Use numPy to calculate polynomial value import numpy as np def p(x, coeff): x_power = np.ones(len(coeff)) x_power[1:] = x x_power = np.cumprod(x_power) return np.sum((x_power) * np.array(coeff)) # Test code coeff = [1, 2, 3, 4, 5] x = [0, 1, 2, 3] for xx in x: print(p(xx,coeff))
f6806a16502a870fee8d794d8ccebe919c7483dd
VladKli/Lasoft
/9.py
1,482
4.15625
4
# З клавіатури вводиться ціле число в діапазоні від 0 до 1000000. Необхідно вивести його прописний стрічковий еквівалент # The first option # _____________________________________________________ # from num2words import num2words # number = input('Print any number, please: ') # print(num2words(0)) # _____________________________________________________ # The second option # number_1 = input('Print a number from 0 to 1000000, please: ') def convert(num): units = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '] tens = ('', '', 'twenty ', 'thirty ', 'forty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety ') if (num >= 0) and (num < 20): return units[num] elif (num >= 20) and (num < 100): return tens[num // 10] + units[int(num % 10)] elif (num >= 100) and (num < 1000): return units[num // 100] + 'hundred ' + convert(int(num % 100)) elif (num >= 1000) and (num < 10000): return units[num // 1000] + "thousand " + convert(int(num % 1000)) elif (num >= 10000) and (num < 1000000): return convert(num // 1000) + "thousand " + convert(int(num % 1000)) elif num == 1000000: return 'a million' print(convert(444777))