blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
76c14c8ca786ac0f40738da70f939b975403f197
p-singh/CTCI
/1-Arrays-Strings/1_1_isUnique.py
227
3.8125
4
def is_unique(s: str): char_set= set() for c in s: if c in char_set: return False else: char_set.add(c) return True if __name__ == "__main__": print(is_unique("ab22s"))
ce01964b645a71b25c2b332b742abbc725b6a579
LuciaIng/TIC_20_21
/ejercicio19.py
414
3.59375
4
'''Escriba una funcin que reciba una cadena de caracteres que represente una fecha (formato 04 de Febrero de 2009) y devuelva un nmero que represente el mes (en el ejemplo anterior devolvera un 2).''' def ejercicio_19(): from datetime import datetime str = '9 de 15 de 18' date_object = datetime.strptime(str, '%m de %d de %y') print(date_object) ejercicio_19()
064f091b537c6f49d3a7951497a2c995fb71287e
ashwini91098/Space-Invaders
/game4.py
4,496
3.609375
4
import math import turtle import os import random #setup screen wn=turtle.Screen() wn.bgcolor("black") wn.title("space invaders") wn.bgpic("bg.png") wn.setup(width=650,height=650) #register shapes turtle.register_shape("invader.gif") turtle.register_shape("player.gif") #draw border border_pen=turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pen.setposition(-300,-300) border_pen.pendown() border_pen.pensize(3) for side in range(4): border_pen.fd(590) border_pen.lt(90) #angle border_pen.hideturtle() #scoring score=0 score_pen=turtle.Turtle() score_pen.speed(0) score_pen.color("white") score_pen.penup() score_pen.setposition(-290,260) scorestring="score:%s" %score score_pen.write(scorestring,False,align="left",font=("Arial",14,"normal")) score_pen.hideturtle() #create player turtle player=turtle.Turtle() player.color("blue") player.shape("player.gif") player.penup() player.speed(0) player.setposition(0,-250) player.setheading(90) playerspeed=15 #choose no.of enemies number_of_enemies=5 #create an empty list of enemies enemies=[] #add enemies to list for i in range(number_of_enemies): enemies.append(turtle.Turtle()) for enemy in enemies: enemy.color("red") enemy.shape("invader.gif") enemy.penup() enemy.speed(0) x=random.randint(-200,200) y=random.randint(100,250) enemy.setposition(x,y) enemyspeed=2 #create player's bullet bullet=turtle.Turtle() bullet.color("yellow") bullet.shape("triangle") bullet.penup() bullet.speed(0) bullet.setheading(90) bullet.shapesize(0.5,0.5) bullet.hideturtle() bulletspeed=20 #bullet states #ready & fire bulletstate="ready" #move player left & right def move_left(): x=player.xcor() x-=playerspeed #move 15pixels each tym key pressed if x<-280: x=-280 #movement within border player.setx(x) def move_right(): x=player.xcor() x+=playerspeed #move 15pixels each tym key pressed if x>270: x=270 player.setx(x) def fire_bullet(): #any changes to bulletstate inside this func vl be reflected everywhere else global bulletstate if bulletstate=="ready": os.system("afplay laser.wav&") #if & not used...game pauses vn sound plays bulletstate="fire" #move bullet just above the player x=player.xcor() y=player.ycor() + 10 bullet.setposition(x,y) bullet.showturtle() #use pythogaurus thrm to calc the dist(a^2 + b^2 = c^2) def isCollision(t1,t2): distance =math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2)) if distance<15: return True else: return False #keyboard bindings turtle.listen() turtle.onkey(move_left,"Left") turtle.onkey(move_right,"Right") turtle.onkey(fire_bullet,"space") #main loop while True: for enemy in enemies: #move enemy x=enemy.xcor() x+=enemyspeed enemy.setx(x) #move enemy in reverse direction & jump down vn hit border if enemy.xcor()>280: for e in enemies: y=e.ycor() y-=40 e.sety(y) enemyspeed*=-1 if enemy.xcor()<-280: for e in enemies: y=e.ycor() y-=40 e.sety(y) enemyspeed*=-1 #collision bet bullet & enemy if isCollision(bullet,enemy): os.system("afplay explosion.wav&") #reset the bullet bullet.hideturtle() bulletstate="ready" bullet.setposition(0,-400) #reset the enemy x=random.randint(-200,200) y=random.randint(100,250) enemy.setposition(x,y) #update score score+=10 scorestring="score:%s" %score score_pen.clear() score_pen.write(scorestring,False,align="left",font=("Arial",14,"normal")) #collision between player & enemy if isCollision(player,enemy): os.system("afplay explosion.wav&") player.hideturtle() enemy.hideturtle() print("game over") break #move bullet if bulletstate=="fire": y=bullet.ycor() y+=bulletspeed bullet.sety(y) #check if bullet has gone to the top if bullet.ycor()>275: bullet.hideturtle() bulletstate="ready"
0fb39e0fef3b1769dfe6f353f4b0aa8709522210
lwd19861127/LeetCde-TopInterviewQuestions-Easy
/IntroToAlgorithms/Wenda_bonus.py
1,054
4.21875
4
""" Bonus Question """ def gcd(n1, n2): while n2 != 0: n1, n2 = n2, n1 % n2 return n1 def gcd_of_strings(str1: str, str2: str): """ For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) return the largest string that divides both str1 and str2. e.g. gcd_of_strings("ABCABC", "ABC") -> "ABC" gcd_of_strings("ABABAB", "ABAB") -> "AB" gcd_of_strings("LAMP", "CODE") -> "" :param str1: string. :param str2: string. :return: the largest string that divides str1 and str2. """ if len(str1) == 0 or len(str2) == 0: return "" while len(str2) != 0: if len(str2) > len(str1): mid = str1 str1 = str2 str2 = mid mid = str1 str1 = str2 if mid.find(str2) != -1: str2 = mid[0:mid.find(str2)] + mid[mid.find(str2)+len(str2):] else: str1 = "" str2 = "" return str1 print(gcd_of_strings("ABABC", "ABC"))
4b1b58af6260b22b444df310c5462a9ffe0eecb7
idan1ezer/LeetCode
/26 - Remove Duplicates from Sorted Array.py
344
3.71875
4
def removeDuplicates(nums): if (not nums): return 0 curIndex = 0 for i in range(1, len(nums)): if (nums[i] != nums[curIndex]): curIndex += 1 nums[curIndex] = nums[i] return curIndex + 1,nums print(removeDuplicates(nums = [1,1,2])) print(removeDuplicates(nums = [0,0,1,1,1,2,2,3,3,4]))
7137a4ca710acb1e42f1df61d19807f9620dc80c
vadimsavenkov/Miscelaneous
/untitled7.py
933
3.765625
4
class BankAccount: def __init__(self): self.name = name self.no = 0 self.balance = initial_amount def withdraw(self, amount): self.balance -= amount return self._balance def deposit(self, amount): self.balance += amount return self._balance def currentBalance(self, amount): self.balance = amount return self.b_alance class MinimumBalanceAccount(BankAccount): def withdraw(self, amount): self._balance = amount def main(): account1 = MinimumBalanceAccount(5000) print(account1.currentBalance()) account2 = BankAccount() account1.deposit(10000) account2.deposit(5000) print(account1.currentBalance()) account2.withdraw(2000) print(account2.currentBalance()) account1.withdraw(3000) account1.withdraw(6000) main()
59b5945f6e638b8d8ecd48db8486d3d85f5a8e51
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/5d80afb6ecc04de294ea702d65bb54b7.py
205
3.625
4
def difference(i): return square_of_sum(i) - sum_of_squares(i) def square_of_sum(i): return sum(xrange(1, i + 1))**2 def sum_of_squares(i): return sum(i**2 for i in xrange(1, i + 1))
ed994b7f564c63c6ad75e88bcdf5dd07e23a3542
Aftabkhan2055/Python
/fsum.py
163
3.578125
4
def test(n,m): c=n+m print(c) #------------------------------------------------- p=int(input("enter the no")) q=int(input("entr the no")) test(p,q)
8849e4a0e1616c76fb3b2d66eca5493edabba4dd
Jacquesvdberg92/SoloLearn-Python-3-Tutorial
/09. Pythonicness and Packaging/01. The Zen of Python/The Zen of Python/The Zen of Python/The_Zen_of_Python.py
2,321
3.734375
4
# The Zen of Python # Writing programs that actually do what they are supposed to do is just one component of being a good Python programmer. # It's also important to write clean code that is easily understood, even weeks after you've written it. # One way of doing this is to follow the Zen of Python, a somewhat tongue-in-cheek set of principles that serves as a guide to programming the Pythoneer way. Use the following code to access the Zen of Python. import this # The Zen of Python, by Tim Peters # Beautiful is better than ugly. # Explicit is better than implicit. # Simple is better than complex. # Complex is better than complicated. # Flat is better than nested. # Sparse is better than dense. # Readability counts. # Special cases aren't special enough to break the rules. # Although practicality beats purity. # Errors should never pass silently. # Unless explicitly silenced. # In the face of ambiguity, refuse the temptation to guess. # There should be one-- and preferably only one --obvious way to do it. # Although that way may not be obvious at first unless you're Dutch. # Now is better than never. # Although never is often better than *right* now. # If the implementation is hard to explain, it's a bad idea. # If the implementation is easy to explain, it may be a good idea. # Namespaces are one honking great idea -- let's do more of those! # Some lines in the Zen of Python may need more explanation. # Explicit is better than implicit: It is best to spell out exactly what your code is doing. # This is why adding a numeric string to an integer requires explicit conversion, rather than having it happen behind the scenes, as it does in other languages. # Flat is better than nested: Heavily nested structures (lists of lists, of lists, and on and on…) should be avoided. # Errors should never pass silently: In general, when an error occurs, you should output some sort of error message, rather than ignoring it. # There are 20 principles in the Zen of Python, but only 19 lines of text. # The 20th principle is a matter of opinion, but our interpretation is that the blank line means "Use whitespace". # The line "There should be one - and preferably only one - obvious way to do it" references and contradicts the Perl language philosophy that there should be more than one way to do it.
99b92f0ca990ebfab634c7eb863ad94df067a8c9
PedroPK/PythonAlura
/AluraInvest/date.py
345
3.984375
4
class Date : def __init__( self, day, month, year ) : self.day = day self.month = month self.year = year def format(self) : date = "{:02}/{:02}/{:04}".format(self.day, self.month, self.year) return date d = Date(13, 6, 2020) print(d.format())
0c78953d452de1b922a7fe5fb41c8891efc0faf1
johndurde14/Python_Learn
/10.4.1.py
885
3.609375
4
#coding = utf-8 import json class ReadAndWrite(): def __init__(self, numbers): self.numbers = numbers self.fileName = "D:\\1etrip系统\\tmp.txt" self.msg = "Successfully!" def number_write(self): try: with open(self.fileName, 'w') as file: json.dump(self.numbers, file) except FileNotFoundError: print("File Not Found,Please Check In Again!") else: print(self.msg) def number_read(self): try: with open(self.fileName) as file: json.load(file) except FileNotFoundError: print("File Not Found,Please Check In Again!") else: print(self.msg) number = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 0] rnw = ReadAndWrite(number) rnw.number_write() rnw.number_read()
cba28bdd66b754c0935d5b6ea3ab3c6e124081b9
wafindotca/pythonToys
/leetcode/ugly_number.py
1,170
4.1875
4
# https://leetcode.com/problems/ugly-number/ # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # # Note that 1 is typically treated as an ugly number. # Easiest way to do this: factorize the number. If at any point in time you come across a factor that isn't 2/3/5, ret import math class Solution: def isUgly(self, num): uglyFactors = {2: True, 3: True, 5: True} def factorize(number): if number == 1: return True for i in range(2, int(math.floor(number / 2)+1)): remainder = number % i if remainder == 0: if i not in uglyFactors: return False return factorize(int(number / i)) if number not in uglyFactors: return False return True return factorize(num) sol = Solution() print(sol.isUgly(214797179)) print(sol.isUgly(14)) print(sol.isUgly(6)) print(sol.isUgly(8))
7289db0d72680d8238ca1d1f9207e3327cb3d0b4
SparshJohri/Kepler_Data_Analysis
/Put_final_data_in_csv.py
3,034
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 8 22:37:18 2019 @author: bhata """ import pandas campaign_2_targets = pandas.read_csv("Campaign_2_EPICS.csv") #gets all of the Campaign 2 targets campaign_2_targets.set_index(campaign_2_targets .columns[0], inplace=True, drop = True) #sets up the EPIC ID as the index of the dataframe pre_main_sequence_stars = pandas.read_csv("Campaign_2_PMS.csv" ) #gets of the Campaign 2 PMS stars pre_main_sequence_stars.set_index(pre_main_sequence_stars.columns[0], inplace=True, drop = True) #sets up the EPIC ID as the index of the dataframe final_table = pandas.DataFrame(columns = ["Epic ID", "Right Ascension", "Declination", "Magnitude", "Investigation IDs", "Type"]) #sets up the final table that will contain the complete information about the PMS stars #------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------- for i in range(len(pre_main_sequence_stars.index)): #iterates through the PMS stars epic_id = pre_main_sequence_stars.index[i] #gets the EPIC ID table1 = campaign_2_targets.loc[epic_id] #gets the data pertaining to the EPIC ID from the campaign 2 targets dataframe #------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------- RA = table1[table1.index[0]] Dec= table1[table1.index[1]] mag= table1[table1.index[2]] inv= table1[table1.index[3]] typ= pre_main_sequence_stars.iloc[i]["Type"] #------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------- final_table = final_table.append(pandas.Series([epic_id, RA, Dec, mag, inv, typ], index = final_table.columns),\ ignore_index=True) #puts the data about the EPIC ID, right ascension, declination, magnitude, investigation IDs, and type into the final table dataframe #------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------- print(campaign_2_targets.loc[epic_id]) print("-----------------------------------------------------") #------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------- final_table.set_index('Epic ID', inplace=True, drop = True) #sets up the EPIC ID as the index of the final table export_csv = final_table.to_csv (r'Data_on_PMS_Stars.csv') #exports the final table into a csv file
d83663b762c21f9e232d886eac460cc8163b52cf
benlands/isat252
/lec6.py
613
3.90625
4
""" lec 6 """ demo_str = "this is my string" #for str_item in demo_str: # print(str_item) #for word_item in demo_str.split(): # print(word_item) #print(word_item.title()) #for str_item in word_item: # print(str_item) #if word_item != "my": #print(word_item) for each_num in range(5): print(each_num) #for each_num in range(1,5): #print(each_num) #for each_num in range(1,5,2): # print(each_num) num_list = [213,321,123,312] max_item = num_list[0] for num in num_list: if max_item <= num: max_item = num print(max_item)
9d39514fd61d814b54efad20b4ba89512d9b5d35
mowangdk/worthtowrite
/two_sum.py
903
3.5
4
import bisect class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ # if numbers is not None or target is not None: # return -1 total_size = len(numbers) for i in range(total_size): if numbers[i] <= target: start = i + 1 value = target - numbers[i] # list.index 的效率是O(n), 不能用在较大的数组中 ano_index = bisect.bisect_left(numbers, value, lo=start) if ano_index != total_size and numbers[ano_index] == value: return i + 1, ano_index + 1 continue else: return -1 if __name__ == '__main__': result = Solution().twoSum([0, 0, 0, 0, 0, 0, 0, 0, 3, 4], 7) print result
23e026a4f1183e127d0760f69fd24c0d204355c4
masmedia/mips
/rearrange.py
663
3.859375
4
#!/usr/bin/env python def rearranger(): #a_string = raw_input("Enter a string:") #for indices in range(1,2): file1 = open("mips.src","r") file2 = open("mips2.src", "w") newLine = '\n' for filerange in file1: a_string = filerange arran = a_string.strip() file2.writelines(arran) file2.writelines(newLine) #This module just deletes the empty spaces just in case #It iterates the line by line and copies the same instructions #from "mips.src" file to "mips2.src" file. Normally this option #i.e: swap: addi $t0, $t1, -4 becomes #swap: addi $t0, $t1, -4
528d45afc72300c10950e39c987891f041089fe2
alexfaley/pythonhardway
/exercise6/step1.py
452
3.609375
4
x = "There are %d types of people ."%10 binary = "binary" do_not = "don't" y = "These who know %s and those %s" % (binary, do_not) print x print y print "I said : %r" % x print "I also said : '%r'" % y hilarious = False joke_evalution = "Isn't that joke so funny?! %s" print joke_evalution % hilarious w = "This is the left %s side of..." e = "a string with a right side." print w % 'alex'+e print "one %" + "s %s three" % "two"
6b5c9ec6f8ac072e3486db1b84f4ad3c213b4010
MEng-Alejandro-Nieto/Python-3-Udemy-Course
/16. list comprehensions in python.py
253
4.34375
4
name="alejandro" mylist=[] for letter in name: mylist.append(letter) print(mylist) print("") # we can rewrite the same above as below mylist2= [letter for letter in name] print(mylist2) print("") mylist3=[num for num in range(5)] print(mylist3)
fd48c75d58487692ab73a05511e5cc1cd402e72c
xuyonghui6512/My_notes
/Python简单练习/条件判断.py
278
3.953125
4
a=[1,3,5,7,9,11,13] if(2 in a): print("DAGE") if(3 in a): print("dage") if(2 not in a): a.insert(1,2) print(a) age1=[1,15,18,19,25,13,5,7] for age in age1: if(age>18): print("you are too old") elif(10<age<19): print("you are so young") else: print("you are a baby")
ca39abc56f8000b4ac85564db9f60b8a37b6c93b
QuentinDuval/PythonExperiments
/dp/EditDistance_Hard.py
1,107
3.890625
4
""" https://leetcode.com/problems/edit-distance Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: * Insert a character * Delete a character * Replace a character """ from functools import lru_cache class Solution: def minDistance(self, word1: str, word2: str) -> int: """ It is enough to try to match from left to right: the right to left will be managed by deletion / replacement at the end. """ @lru_cache(maxsize=None) def distance(start1, start2): if start1 == len(word1): return len(word2) - start2 if start2 == len(word2): return len(word1) - start1 if word1[start1] == word2[start2]: return distance(start1 + 1, start2 + 1) return 1 + min([ distance(start1 + 1, start2), distance(start1, start2 + 1), distance(start1 + 1, start2 + 1) ]) return distance(0, 0)
43fe197667c87c7d1a9a6d166196c8e748e876c8
neal-o-r/questions
/only_unique.py
602
4
4
# find the only unique element in an array # in a sorted array def unique_sorted(arr): x = arr[0] for i, a in enumerate(arr[1:]): if x != a and a != arr[i + 1]: return a x = a return x # given that everything else appears twice def find_double(arr): x = arr[0] for a in arr[1:]: x ^= a return x # given that everything else appears three times def find_triple(arr): one = 0 two = 0 for a in arr: two |= one & a one ^= a both = ~(one & two) one &= both two &= both return one
a85f464f6f75e0e824e6385a7c69ca6831b90cff
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/335.py
631
3.609375
4
def all_happy(pancakes): return all(pancake == '+' for pancake in pancakes) n = int(raw_input()) for i in range(n): tmp = raw_input().split() pancakes = list(tmp[0]) k = int(tmp[1]) nflip = 0 for j in range(0, len(pancakes) - k + 1): if pancakes[j] == '+': continue for p in range(k): if pancakes[j + p] == '-': pancakes[j + p] = '+' else: pancakes[j + p] = '-' nflip += 1 if all_happy(pancakes): print "Case #{}: {}".format(i + 1, nflip) else: print "Case #{}: IMPOSSIBLE".format(i + 1)
6cc8b07138b418809e923d0820f98111ed3ea1f2
rAndrewNichol/oldrepo
/Python/monty_hall/monty_hall.py
619
3.640625
4
#monty_hall.py import random def gen_doors(): doors = [0,1,2] car = random.randrange(3) doors[car] = "Car" goats = list(range(3)) del goats[car] for i in goats: doors[i] = "Goat" return doors def random_play(doors = ["Goat","Car","Goat"], switch = True): goats = [] [goats.append(i) for i in range(3) if doors[i] == "Goat"] pick = random.randrange(3) if switch == True: if pick in goats: return "Car" else: return "Goat" else: if pick in goats: return "Goat" else: return "Car"
a9eeb2522af895dee72f78b10a8539b502799dba
SalvatoreRaia/Salvorra
/scratch_3.py
2,004
3.65625
4
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation import pandas as pd ''' # First set up the figure, the axis, and the plot element we want to animate fig, ax = plt.subplots(ncols=1, nrows=1) ax = plt.axes(projection='3d') line, = ax.plot([], [], lw=2) x = np.linspace(0, 2, 1000) y = np.linspace(0, 2, 1000) z = np.sin(x*y) ax.plot(x,y,z) def animate(i): line.set_data(x, y) line.set_3d_properties(np.sin(x[i]*y[i])) return line, # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, frames=50, interval=20, blit=True) plt.show() ''' filename = r"C:\Users\Salvo\Desktop\IFISC\data\no_words_per_county.csv" df = pd.read_csv(filename, index_col=[0]) print(df) df.iloc[1:,1] = df.iloc[1:,1] -1 pd.to_numeric(df.iloc[:,1]) df = df.sort_values(by=['counting'], ascending=False) df = df.reset_index() fig = plt.figure() ax = fig.add_subplot(1,1,1) a = len(df.iloc[:, 1]) x = np.arange(1, a) #ax.grid(color='xkcd:ocean blue', linestyle=':') ax.set_yticks(np.arange(0, 71000, 5000), minor=False) ax.set_xlabel('County ranking') ax.set_ylabel('No. of nonzero occurrency words') ax.scatter(x, df.iloc[:-1, 2], s=1) print(df) #ax.set_yscale('log') ax.set_xscale('log') fig.tight_layout() plt.show() #filename = r"C:\Users\Salvo\Desktop\IFISC\data\no_words_per_county(sorted).csv" #df.to_csv(filename) ''' fig = plt.figure() ax = fig.add_subplot(111, projection='3d') line, = ax.plot([], [], [], "o", markersize=2) X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) i = int def update(i, x, y, z): line.set_data(X[i], Y[i]) line.set_3d_properties(Z[i]) ani = animation.FuncAnimation(fig, update(i,X,Y,Z), 100, blit = False,) plt.show() '''
c4b7e00e39aa92fbe99bfe5d2d620b24999f9e88
Dearyyyyy/TCG
/data/3922/AC_py/508734.py
147
3.609375
4
# coding=utf-8 while True: a,b=input().split() a=int(a) b=int(b) if b==0: print("error") else: m=a/b+0.5 m=int(m) print(m)
4a191e882e1216ddf78667e322289a103dd5ca49
huangchen1996/Python_Base
/PythonBase/IfAndOr/If_Nest_03.py
291
3.703125
4
ticket = 1 knife = 9 if ticket == 1: print("你可以进入车栈") if knife > 8: print("不好意思,您携带的工具太过于危险,不能上车") else: print("祝您旅途愉快") else: print("不好意思,您缺少相关物件不能进入车站")
ee423771b495161e5671e232ae8dccc9f743ee72
wilcokuyper/cs50
/pset6/credit.py
1,752
4.21875
4
def sumOfDigits(number): sum = 0 length = len(number) val = int(number) # creditcard is only valid if it contains 13, 15 or 16 digits if length == 13 or length == 15 or length == 16: # calculate the sum of the digits by adding the individual numbers to each other, every other number should also be doubled for i in range(1,length+1): # find the current digits currentDigit = int(val % 10); # nth mod 2 digits should be doubled if i % 2 == 0: currentDigit *= 2; if currentDigit > 9: sum += int(currentDigit % 10) + 1 else: sum += currentDigit else: sum += currentDigit val = int(val / 10) return sum; def typeOfCard(number): lastTwoDigits = int(int(number) / (pow(10.0, len(number)-2) )) if lastTwoDigits == 34 or lastTwoDigits == 37: return "AMEX" elif (lastTwoDigits == 51 or lastTwoDigits == 52 or lastTwoDigits == 53 or lastTwoDigits == 54 or lastTwoDigits == 55): return "MASTERCARD" elif int(lastTwoDigits / 10) == 4: return "VISA" else: return "INVALID" def printCardType(number): # calculatie the sum of the creditcard digits, if it is positive and divisible by 10 it is valid sum = sumOfDigits(number) if sum > 0 and sum % 10 == 0: print(typeOfCard(number)) else: print("INVALID") def main(): try: number = input("Number: ") printCardType(number) exit(0) except ValueError: print("INVALID") exit(1) if __name__ == "__main__": main()
8eeb5596b794f70153512fb051f34c72a97fae53
chinacharlie/demo
/f.py
168
3.71875
4
import functools @functools.lru_cache(maxsize=100) def fibonacci(n): if n < 2: return n return fibonacci(n-2) + fibonacci(n-1) print(fibonacci(40))
6c994564ba68112d97d5b3f81be3e256947f4d79
pknipp/permutations
/tennis.py
2,164
3.5625
4
import math from itertools import permutations dx1 = 27 dx2 = 36 dy1 = 36 dy2 = 78 ## Python code for finding the least-distance travel-path when sweeping the lines on one side of a Hartru court. ## This is a modified traveling-salesman problem. Below are descriptions of the lines. All positions are ## expressed in half-feet, relative to an origin at the middle of the baseline. All lines point in positive ## direction (either x or y). ## 0: left-outside alley ## 1: left-inside alley ## 2: back of service line ## 3: bisector of service boxes ## 4: baseline ## 5: right-inside alley ## 6: right-outside alley xy = (((-dx2, 0),(-dx2,dy2)), \ ((-dx1, 0),(-dx1,dy1)), \ ((-dx1,dy1),(-dx1,dy2)), \ ((-dx1,dy1),( 0,dy1)), \ (( 0,dy1),( dx1,dy1)), \ (( 0,dy1),( 0,dy2)), \ ((-dx2, 0),( dx2, 0)), \ (( dx1, 0),( dx1,dy1)), \ (( dx1,dy1),( dx1,dy2)), \ (( dx2, 0),( dx2,dy2))) lenmin = 999999 imin = [] nmin = [] for iline in range(0,len(xy)): imin.append(2) nmin.append(iline) print('\n All distances/positions below are expressed in half-feet.') print('Below are the successive minima of the "wasted distance" function, followed by the values of each of its ',len(xy)-1,' terms. \n') perm = permutations(xy) for lines in perm: for ntot in range(0,2**(len(xy)-1)): i = [0] n = ntot length = 0 d = [] for iline in range(1,len(xy)): i.append(int(n % 2)) n -= i[iline] n /= 2 xi = lines[iline-1][1-i[iline-1]][0] yi = lines[iline-1][1-i[iline-1]][1] xf = lines[iline][i[iline]][0] yf = lines[iline][i[iline]][1] d.append(math.sqrt((xi - xf)**2 + (yi - yf)**2)) length += d[iline-1] if length<lenmin: lenmin=length for iline in range(len(xy)): imin[iline] = i[iline] nmin[iline] = lines[iline] print(length,d) print('\n The smallest possible "wasted distance" is ',lenmin,',') print('which is obtained by traversing the following sequence of coordinates.:\n') for iline in range(len(xy)): print(nmin[iline][imin[iline]]) print(nmin[iline][1 - imin[iline]])
97888b17bc6aad0e4344567aaa4188827ebe795e
newtonsart/wordlistgenerator
/wordlistgenerator
1,426
4.21875
4
#!/usr/bin/env python3 from itertools import product import string, sys def generate_characters(): characters = [char for char in string.printable.replace("\t\n\r\x0b\x0c","")] return characters if __name__ == '__main__': try: min_characters = int(sys.argv[1]) max_characters = int(sys.argv[2]) + 1 output_file = sys.argv[3] except: print("Usage: python3 {} <MIN_CHARACTERS> <MAX_CHARACTERS> <OUTPUT FILE>".format(sys.argv[0])) exit() x=0 f = open(output_file, "w+") characters = "".join(generate_characters()) print("Characters going to be used: "+characters) if max_characters < min_characters: print("The max number of characters is smaller than the min number of characters\nUsage: python3 {} <MIN_CHARACTERS> <MAX_CHARACTERS> <OUTPUT FILE>".format(sys.argv[0])) try: for lenght in range(min_characters, max_characters): for item in product(characters, repeat=lenght): f.write("".join(item)+"\n") x+=1 print("\rPaswords generated: {}, current password: {}".format(x, "".join(item)), end="\r") print("Wordlist finished, passwords created: "+str(x)) except KeyboardInterrupt: print("\nLol") f.close() f.close()
19fd7e1061cf3119f8b921d59ab172b9b113119e
PetosPy/hackbulgaria_python
/week06/game_of_frogs_tree.py
2,929
3.71875
4
FROG_DIRECTION = {'>': 1, '<': -1} class TreeNode: def __init__(self, value: tuple, parent: 'TreeNode'=None): self.value = value self.parent = parent # self.children = children def number_of_frogs(count: int): root_value = tuple(['>'] * count + ['_'] + ['<'] * count) expected_value = tuple(['<'] * count + ['_'] + ['>'] * count) tree = TreeNode(value=root_value) right_node = create_children(tree, expected_value) print(build_path(right_node)) # get the done path def build_path(start_node): path = [] while True: path.append(''.join(start_node.value)) if not start_node.parent: break start_node = start_node.parent return list(reversed(path)) def create_children(node, expected_frogs) -> TreeNode: should_stop, right_node, wrong_solutions = False, None, set() expected_frogs = expected_frogs max_range = len(node.value) - 1 def __create_children(node): nonlocal should_stop, right_node, wrong_solutions, expected_frogs can_move = False if node.value in wrong_solutions: return for frog_idx, frog in enumerate(node.value): if should_stop: return target_index = frog_can_move(frogs=node.value, frog_index=frog_idx, max_range=max_range) if target_index is None: continue can_move = True # we can move the frog moved_frogs = move_frog(frogs=node.value, source_index=frog_idx, target_index=target_index) new_node = TreeNode(value=moved_frogs, parent=node) if moved_frogs == expected_frogs: # we've found the solution should_stop = True right_node = new_node return # node.children.append(new_node) __create_children(new_node) # recursively call the function using the new node if not can_move: wrong_solutions.add(node.value) __create_children(node) return right_node def move_frog(frogs: tuple, source_index, target_index): """ Swaps the frogs """ temp_list = list(frogs) # swap the values temp_list[source_index], temp_list[target_index] = temp_list[target_index], temp_list[source_index] return tuple(temp_list) def frog_can_move(frogs, frog_index, max_range): frog = frogs[frog_index] if frog != '_': next_index = frog_index + FROG_DIRECTION[frog] if 0 <= next_index <= max_range: # in bounds if frogs[next_index] == '_': return next_index nexter_index = next_index + FROG_DIRECTION[frog] if 0 <= nexter_index <= max_range: # in bounds if frogs[nexter_index] == '_': return nexter_index import time start = time.time() number_of_frogs(3) end = time.time() print(end-start) ">><<_"
f9b275c8403497898992c8bcdde4c71199a5b929
mollinaca/ac
/code/practice/abc/abc056/c.py
151
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- x = int(input()) i = 0 while True: if i*(i+1)//2 >= x: print (i) exit () i += 1
6a6356af7e9e47f48a161594c6a8dcada8219577
kathirvelgounder/SharkSpotting
/metadata/extract_metadata.py
2,635
3.546875
4
#we are going to be provided a .srt file, as well an interval #range that sharks are found in the video. Extract the other #pertinent information that is present at that time class DroneInfo(): """ Stores information logged into a given entry of the SRT file created in the drones flight. Contains useful information such as drone altitude, drone GPS location, etc. """ def __init__(self, gps_loc: tuple, barometer: float=None): self.gps_loc = gps_loc self.barometer = barometer def __repr__(self): return 'DroneInfo(%s, %s)' % (self.gps_loc, self.barometer) def get_metadata_from_srt(file: str, interval: tuple) -> dict: metadata: dict = {} start = interval[0] end = interval[1] cnt = 0 with open(file) as fp: line = fp.readline() while line: line = line.strip() if (line.isdigit()): cnt += 1 if cnt > end: break if cnt >= start: drone_info = get_single_entry(fp) metadata[cnt] = drone_info line = fp.readline() return metadata def get_single_entry(fp) -> DroneInfo: cnt = 0 gps_loc: tuple = None barometer: float = None while cnt < 4: line = fp.readline() if cnt == 0: pass elif cnt == 1: pass elif cnt == 2: readings = line.split() gps_loc = get_gps_from_entry(readings[0]) barometer = get_floats_from_str(readings[1])[0] elif cnt == 3: pass cnt += 1 drone_info = DroneInfo(gps_loc, barometer) return drone_info # extract a tuple of gps coordinates from a string gps # entry of the form GPS(-117.6868,33.4609,18) def get_gps_from_entry(gps_entry: str) -> tuple: nums = get_floats_from_str(gps_entry) coords = (nums[0], nums[1]) return coords # filters out all non numeric symbols, and returns # list of floats def get_floats_from_str(s: str): num_strs = list() nums = list() i = 0 temp = '' while i < len(s): if s[i].isnumeric() or s[i] == '-' or s[i] == '.': temp += s[i] if (i == len(s) - 1): nums.append(temp) elif len(temp) > 0: nums.append(temp) temp = '' i += 1 for num in num_strs: nums.append(float(num)) return nums if __name__ == '__main__': interval = (22, 23) metadata = get_metadata_from_srt("example_data/DJI_0001.SRT", interval) for m in metadata: print(metadata[m])
f02999e1fcb8a6a37d3151929eee0ef350334b71
bielevan/a_sintatico
/table.py
2,950
3.890625
4
# Representa a tabela de simbolos ja definidos pela linguagem inicialmente # Possui uma estrutura de dados em tabela hash, onde as colisões são resolvidas # Implementando uma lista para cada posição. Assim, se houver dois elementos # para a mesma posição, então eles estaram inseridos em formato de lista na # mesma posição # Para buscar a posição, foi implementado uma função de hash, na qual calcula-se # a posição devida do token através da soma dos valores inteiros de cada caracter # e aplicando a função de resto, com um valor já pré-definido no inicio da compilação (LEN = 37). class Table: len = 0 table_token = list() # Método construtor def __init__(self, len): self.len = len i = 0 while i < len: self.table_token.append(list()) i += 1 self.add("var", "simb_var") self.add("integer", "simb_integer") self.add("real", "simb_real") self.add("char", "simb_char") self.add("begin", "simb_begin") self.add("end", "simb_end") self.add("while", "simb_while") self.add("do", "simb_do") self.add("if", "simb_if") self.add("then", "simb_then") self.add("else", "simb_else") self.add("for", "simb_for") self.add("to", "simb_to") self.add("read", "simb_read") self.add("write", "simb_write") self.add("program", "simb_program") self.add("const", "simb_const") self.add("procedure", "simb_procedure") self.add(";", "simb_pv") self.add(":", "simb_dp") self.add(":=", "simb_atrib") self.add("=", "simb_igual") self.add("(", "simb_apar") self.add(")", "simb_fpar") self.add("<", "simb_menor") self.add(">", "simb_maior") self.add("+", "simb_mais") self.add("*", "simb_multi") self.add("-", "simb_menos") self.add("+", "simb_mais") self.add("/", "simb_div") self.add(".", "simb_p") self.add("<>", "simb_dif") self.add(">=", "simb_maior_igual") self.add("<=", "simb_menor_igual") self.add(".", "simb_pf") self.add(",", "simb_virgula") self.add("'", "simb_aspas") # Printa toda a tabela def show(self): for pos, value in enumerate(self.table_token): if (len(self.table_token[pos]) is not 0): print(value) # Retorna a posição de um elemento def pos(self, cad): tam = 0 aux = list(cad) for i in aux: tam += ord(i) return tam % self.len # Insere elemento na tabela hash def add(self, cad, token): self.table_token[self.pos(cad)].append((cad, token)) # Obter um token def getToken(self, cad): aux = self.pos(cad) for i in self.table_token[aux]: if i[0] == cad: return i[1] return None
577797a27b6cda56a60ee5f9cce039bdb94d25c6
beboptank/the-self-taught-programmer-challenges
/ch6.py
2,459
4.375
4
# print every character in the string "Camus" lets_print = "Camus" print ( lets_print[0], lets_print[1], lets_print[2], lets_print[3], lets_print[4] ) # write a program that collects two strings from a user, inserts them into the string "Yesterday I wrote a [response_one]. # I sent it to [response_two]!" and prints a new string writing = input("Enter a type of literature (book, pamphlet, etc):") person = input("Enter a person's name:") new_sentence = "Yesterday I wrote a {}. I sent it to {}.".format(writing, person) print (new_sentence) # use a method to make the string "aldous Huxley was born in 1894." grammatically correct by capitalizing the first letter in the sentence huxley = "aldous Huxley was born in 1894." huxley = huxley.capitalize() print (huxley) # take the string "Where now? Who now? When now?" and call a method that returns a list that looks like: # ["Where now?", "Who now?", "When now?"] "Where now? Who now? When now?".split(" ") # take the list ["The", "fox", "jumped", "over", "the", "fence", "."] and turn it into a grammactically correct string. # There should be a space between the word fence and the period that follows it. words = ["The", "fox", "jumped", "over", "the", "fence", "."] fox_sentence = " ".join(words) fox_sentence = fox_sentence[:29] + fox_sentence[-1] # replace every instance of "s" in "A screaming comes across the sky." with a dollar sign scream_sentence = "A screaming comes across the sky." scream_sentence = scream_sentence.replace("s", "$") print (scream_sentence) # use a method to find the first index of the character "m" in the string "Hemingway" "Hemingway".index("m") # find dialogue in your favorite book (containing quotes) and turn it into a string norwegian_wood = '''"How did you like my song?" she asked. I answered cautiously, "It was unique and original and very expressive of your personality." "Thanks," she said. "The theme is that I have nothing." "Yeah, I kinda thought so."''' # create the string "three three three" using concatenation, and then again using multiplication three_concat = "three " + "three " + "three" three_mult = "three " * 3 three_mult = three_mult.strip() # slice the string "It was a bright cold day in April, and the clocks were striking thirteen." to only include the # characters before the comma quote = "It was a bright cold day in April, and the clocks were striking thirteen." quote = quote[0:33] print (quote)
815b522a7834747c8186b8e419e0722fc8612777
minseunghwang/algorithm
/TEST/TOSS/Server delveloper - 2.py
303
3.609375
4
user_input = input() def solution(user_input): lotto = user_input.split() if len(set(lotto)) != 6: return False if int(lotto[0]) < 1 or int(lotto[-1]) > 45: return False if sorted(lotto) != lotto: return False return True print(solution(user_input))
131f45f30ce56f3b34f458292af1b2e97e8827f2
HeywoodKing/mytest
/MyPractice/class_domain.py
889
3.859375
4
# Filename:class_domain.py class Person: population = 0 def __init__(self,name): self.name = name print("(Initializing %s)" % self.name) Person.population += 1 def __del__(self): print("%s says bye." % self.name) Person.population -= 1 if Person.population == 0: print("I am the last one.") else: print("There are still %d people left." % Person.population) def sayHi(self): print("Hi,my name is %s." % self.name) def howMany(self): if Person.population == 1: print("I am the only person here.") else: print("We are %d person here." % Person.population) ching = Person("Ching") ching.sayHi() ching.howMany() admin = Person("Admin") admin.sayHi() admin.howMany() del admin del ching
f55816c447fd808580c896ab68e564487fa33c53
twymer/project-euler
/python/p17.py
969
3.515625
4
onesPlaceDict = { 0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" } teensDict = { 0: "ten", 1: "eleven", 2: "twelve", 3: "thirteen", 4: "fourteen", 5: "fifteen", 6: "sixteen", 7: "seventeen", 8: "eighteen", 9: "nineteen" } tensPlaceDict = { 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety" } result=0 for i in range(1000): currentNum ="" currentNum += onesPlaceDict[int(i/100)] if int(i>=100): if(i%100==0): currentNum += " hundred " else: currentNum += " hundred and " if i%100 in range(10): currentNum += onesPlaceDict[i%100] elif i%100 in range(10,20): currentNum += teensDict[i%100-10] else: currentNum += tensPlaceDict[int(i/10)%10] + " " + onesPlaceDict[i%10] result+=len(currentNum.replace(" ","")) print(currentNum) print(len(currentNum.replace(" ",""))) result+=len("onethousand") print(result)
e48f030e8dde581675b9bcde6e98e9074a922047
infixsrf/Trash
/programmer.py
3,565
3.890625
4
import people class Programmer(People): # кол-во языков программирования _i_language_prog = 0 # опыт работы _i_experience = 0 # скил прокраммировани в % _i_progr = 0 # пропишим getter's и setter's def set_langauge_prog(self, n): # запрос на кол-во языков которые вы знаете x = 0 n = int(n) while(x == 0): if n <= 15: self._i_language_prog = n x += 1 else: print("Инициальзиция не удалась") print("Вы не можите выучить 15 языков на уровне профи, за всю свою жизнь") print("Повторите попытку...\n") n = input("\nВведите кол-во языков программирования: ") n = int(n) def langauge_prog(self): # возыращаем кол-во языков return self._i_language_prog def set_experience(self, e): # запрашиваем опыт работы x = 0 x = int(x) while(x == 0): if e <= 60: self._i_experience = e x += 1 else: print("Инициальзиция не удалась") print("Ваш опыт работы, не может быть больше 60 лет") print("Повторите попытку...\n") def experience(self): # возвращаем опыт работы return self._i_experience def set_progr(self, pr) # процентное соотношение скилла программирования x = 0 x = int(x) while(x == 0): if pr <= 100: self._i_progr = pr x += 1 else: print("Инициальзиция не удалась") print("Максимальное значение == 100%") print("Повторите попытку...\n") def progr(self): # возвращаем процентное соотношение скилла программирования return self._i_progr # сколько языков программирования вы знаете def languages_prog(self): if self._i_language_prog == 1 and _i_progr >= 70: pritn("Вы знаете 1 язык программирования") elif self._i_language_prog == 2 and _i_progr >= 70: pritn("Вы знаете 2 языка программирования") elif self._i_language_prog == 3 and _i_progr >= 70: pritn("Вы знаете 3 языка программирования") elif self._i_language_prog == 4 and _i_progr >= 70: pritn("Вы знаете 4 языка программирования") elif self._i_language_prog >= 5 and _i_progr >= 70: print("Да вы профи, вы знаете больше 5 языков программирования, браво!") # качество вашего кода def programming(self): if self._i_progr >= 85 and _i_experience >= 7: print("Я выполнил работ отлично!") elif self._i_progr >= 65 and _i_experience >= 4: print("Я выполнил свою работу хорошо!") elif self._i_progr >= 40 and _i_experience >= 1: ("У меня получился тёмный - мутный код...") else: print("Мой код можно только выкинуть") # вывод основной инфомации def printf(self): print("Кол-во языков программирования = ", _i_language_prog) print("Опыт работы = ", _i_experience, " лет") print("Скил прокраммировани в % = ", _i_progr)
551b2ac66bf7ef1986e311353af32bb1b5c88fab
rhkaz/Udacity_IntroComputerScience
/Lesson_3_Problems/greatest2.py
502
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 20 10:06:58 2016 @author: RashidKazmi """ # Define a procedure, greatest, # that takes as input a list # of positive numbers, and # returns the greatest number # in that list. If the input # list is empty, the output # should be 0. def greatest(list_of_numbers): big = 0 for e in list_of_numbers: if (e > big): big = e return big print (greatest([4,23,1])) #>>> 23 #print (greatest([])) #>>> 0
d89b92a5c3b300c2d5e9168484d0242ee097b21f
gloomyline/ML
/python/demos/2048/screen.py
1,216
3.609375
4
# -*- coding: utf-8 -*- # @Author: Administrator # @Date: 2018-05-18 13:37:45 # @Last Modified by: Administrator # @Last Modified time: 2018-05-18 16:26:00 class Screen(object): help_string1 = '(W)up (S)down (A)left (D)right' help_string2 = ' (R)Restart (Q)Exit' over_string = ' GAME OVER' win_string = ' YOU WIN!' def __init__(self, screen=None, grid=None, score=0, best_score=0, over=False, win=False): self.grid = grid self.score = score self.over = over self.win = win self.screen = screen self.counter = 0 def cast(self, string): self.screen.addstr(string + '\n') def draw_row(self, row): self.cast(''.join('|{: ^5}'.format(num) if num > 0 else '| ' for num in row) + '|') def draw(self): self.screen.clear() self.cast('SCORE: ' + str(self.score)) for row in self.grid.cells: self.cast('+-----' * self.grid.size + '+') self.draw_row(row) self.cast('+-----' * self.grid.size + '+') if self.win: self.cast(self.win_string) else: if self.over: self.cast(self.over_string) else: self.cast(self.help_string1) self.cast(self.help_string2)
cc7db316caafe3cf5e2d0d7d66ba41dc7e5e24d4
rhian-bottura/ExCursoGuanabara
/ex052.py
306
3.59375
4
s = 0 n = int(input('Digte um numero:')) for c in range(1,n+1): if n % c == 0: print('\033[34m', end='') s += 1 else: print('\033[m', end='') print('{}'.format(c), end='') if s == 2: print(' \n \033[mPrimo') else: print(' \n \033[mNão é primo')
fbc79e8174fc13a75c696c899d52735dd6b68d6e
enmyj/cryptopals
/set1/uno.py
549
3.609375
4
import codecs from binascii import unhexlify from base64 import b64encode def hex_to_b64(h: str) -> str: return codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode() # https://www.reddit.com/r/learnpython/comments/2vj4o5/cryptography_bytes_vs_encoded_strings/ def hb64(h: str) -> str: return b64encode(unhexlify(h)) if __name__ == "__main__": hex = ( '49276d206b696c6c696e6720796f757220627261696e20' '6c696b65206120706f69736f6e6f7573206d757368726f6f6d' ) # print(hex_to_b64(hex)) print(hb64(hex))
940c9cd56b5d3b04a404149b13391dab785920fc
xumaxie/pycharm_file-1
/Algorithma and Data Structures/python数据结构与算法分析/第二章/demo01(前n数之和).py
207
3.8125
4
#@Time : 2021/10/3110:48 #@Author : xujian #计算前前n个数的和 def sum(n): sum_num=n*(n+1)/2 return sum_num if __name__=="__main__": n=int(input("请输入数字")) print(sum(n))
ef9cd811318072f8235c8a5c58f0867d5f520133
arnet95/Project-Euler
/Python/euler125.py
1,051
4.0625
4
#Project Euler 125: Palindromic sums def sum_of_squares(n, m): """Returns the sum of i**2 for n <= i < m""" return ((2*(m-1)**3 + 3*(m-1)**2 + (m-1)) - (2*(n-1)**3+3*(n-1)**2+(n-1))) // 6 def is_palindrome(n): return str(n) == str(n)[::-1] def max_num(N): """Returns the n such that any sum of > n consecutive squares is greater than N""" n = 1 while sum_of_squares(1, n) < N: n += 1 return n def all_sums(i, N): """Returns a list of all numbers < N which can be written as the sum of i consecutive squares.""" result = [] n = 1 while True: s = sum_of_squares(n, n+i) if s >= N: return result result.append(s) n += 1 def main(N): max_n = max_num(N) sums = [] for k in xrange(2, max_n+1): sums += all_sums(k, N) #Creates a list of all possible sums of consecutive squares, and #returns the sum of all those sums which are also palindromes. return sum(s for s in set(sums) if is_palindrome(s)) print main(10**8)
7c782ec40a308029eea80944492a68717a8a53ba
younkyounghwan/python_class
/lab3_1.py
2,301
4.28125
4
""" 쳅터: day3 데이터형 연습 주제: 데이터형 연습 작성자: 윤경환 작성일: 18.09 04 """ f = 3.4 #f의 데이터타입은 float 왜냐하면, 3.4가 실수이기 떄문이다 print(f) i = 3 #i의 데이터타입은 int. 왜냐하면, i에 정수인 3이 저장되었으므로 print(i) b = True #b는 boolean type. 왜냐하면, b에 true가 저장되었으므로.(boolean type은 true 또는 false를 저장한다 print(b) s="안녕하세요" #s는 문자열 str 문자열은 " "로 묶는다. 또는 ''로 묶는다. print(s) s='1' #s의 데이터 타입은 str print(s) #f와 i를 더해서 출력, i가 float로 자동 변환되어 계산됨 print(f+i) #s+i 더해서 출력 #오류발생 왜냐하면, 문자열이 int로 자동변환되지는 않는다. #print(s+i) #s를 int로 형 변환하여 i와 더하기 print(int(s)+i) #i를 str로 형변환하여 s와 더하기. 문자열 이어주기 연산이 실행됨 print(s+str(i)) #정수 계산 print("정수 나누기") i=57 j=28 #i를 j로 나눈 값 출력 print(i/j) #i를 j로 나눈 몫 출력 print(i//j) #i를 j로 나누었을 때 나머지 출력 print(i%j) #j의 제곱 출력 print(j**2) #j의 세제곱 출력 print(j**3) #실수 계산 print("실수 나누기") i=57.0 j=28.0 #i를 j로 나눈 값 출력 print(i/j) #i를 j로 나눈 몫 출력 print(i//j) #i를 j로 나누었을 때 나머지 출력 print(i%j) #j의 제곱 출력 print(j**2) #j의 세제곱 출력 print(j**3) print(100000000000000000000000) # or 연산자(boolean type 연산자) print(b or False) # and 연산자(boolean type 연산자) print(b and False) print(True and b) print(False and False) #복소수(실수부와 허수부ㅜ로 구성된 숫자)타입 변수 k k = 5 + 7j print(k) print(k.real) #복소수의 실수부를 출력 print(k.imag) #복소수의 허수부를 출력 print(k.conjugate()) #켤레 복소수를 가져오는 함수 호출 # 8진수 표현 o = 0o16 #십진수로는 14를 의미, 실제 테이터 타입은 int print(o) #기본 십진수 print("%o" %o) #8진수로 출력됨 print("%x" %o)#16진수로 출력됨. %x는 소문자로 출력, %X는 대문자로 출력 #16진수 표현 x=0xA5 #십진수 출력 print(x) #8진수 출력 print("%o" %x) #16진수 출력 print("%x" %x)
9862a682811ff5eef3b19e4723b6607d9adc6727
kashikakhatri08/Python_Poc
/python_poc/python_strings_program/string_execute_code.py
260
3.6875
4
def exec_method(): string_container = """ def sum(a,b): print("first number: {} , second number: {}".format(a,b)) c= a +b print("sum of first and second number : {}".format(c)) sum(1,2) """ exec(string_container) exec_method()
791570978e8bcf8b2e36bd64aaaeaab0e6fabd54
Kalpavrikshika/python_modules
/list1.py
233
3.5
4
#list squared = [x**2 for x in range(10)] print(squared) #dict mcase = {'a': 10, 'b': 34, 'A':7, 'Z':3} mcase_frequency = { k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() } print(mcase)
0ec3fb8af7eb622ee322169e99c201faf770a4fd
Mr-alan9693/cursoemvideopython
/venv/Qual é o maior e o menor.py
277
3.984375
4
A = int(input('Digite o primeiro numero: ')) B = int(input('Digite o segundo numero: ')) C = int(input('Digite o terceiro numero: ')) if A>B and A>C: maior = A if B>C and B>A: maior = B if C>A and C>B: maior = C print('O maior valor digitado foi {}'.format(maior))
a9e5df68ae94c64c2aafa0aa21a1751d70786798
ksarthak4ever/Competitive-Programming
/Algorithms/Search/Find First Duplicate Entry/find.py
841
3.921875
4
""" Write a function that takes an array of sorted integers and a key and returns the index of the first occurrence of that key from the array. Example: idx 0 1 2 3 4 5 6 7 8 9 A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] target = 108 Returns index 3 since 108 appears for the first time at index 3. """ A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] target = 108 def find(A, target): low = 0 high = len(A) - 1 while low <= high: mid = (low + high) // 2 if A[mid] < target: low = mid + 1 elif A[mid] > target: high = mid - 1 else: if mid - 1 < 0: return mid if A[mid - 1] != target: return mid high = mid - 1 x = find(A, target) print(x)
38278c93d68206abb5d4c5356593504de29044e0
RishabhGoswami/Algo.py
/Delete n node from end list.py
1,070
3.703125
4
class Node: def __init__(self,data): self.data=data self.next=None class Linke: def __init__(self): self.head=None def push(self,data): newp=Node(data) newp.next=self.head self.head=newp def printl(self): temp=self.head while(temp): print(temp.data) temp=temp.next def countl(self): temp=self.head c=0 while(temp): c=c+1 temp=temp.next return c def dele(self,x): first=self.head second=self.head for i in range(x): if(second.next==None): if(i==(x-1)): self.head=self.head.next return self.head second=second.next while(second.next): first=first.next second=second.next first.next=first.next.next if __name__=='__main__': l=Linke() l.push(4) l.push(5) l.push(2) l.push(1) l.dele(1) l.printl()
cc3fbf43ccd352586452f2dac5dffac8c3f9cd2b
anand-prashar/python-code-practice
/005_Longest_Palindrome.py
1,253
4.03125
4
''' Given a string s, find the longest palindromic substring in s. Input: "babad" Output: "bab" Note: "aba" is also a valid answer. ''' def longestPalindrome(s): """ :type s: str :rtype: str """ lowLimit = 0 highLimit = len(s) palindrome = '' for index in range(0,highLimit): dist = 1 if (index!=highLimit-1) and (s[index] == s[index+1]): searchEvenString = True tempPalindrome = '' else: searchEvenString = False tempPalindrome = s[index] if searchEvenString: while ( index-dist+1>=lowLimit and index+dist <highLimit) and (s[index-dist+1] == s[index+dist]): tempPalindrome = s[index-dist+1] + tempPalindrome + s[index+dist] dist+=1 else: while ( index-dist>=lowLimit and index+dist <highLimit) and (s[index-dist] == s[index+dist]): tempPalindrome = s[index-dist] + tempPalindrome + s[index+dist] dist+=1 if len(tempPalindrome) > len(palindrome): palindrome = tempPalindrome return palindrome print longestPalindrome('ccc')
03ead92cbf2457d60b0d6a7cefc2f51c58f091c9
Yennutiebat/Noeties_repo
/TICT-VIPROG-15/Les07/Practice files/7.1.py
180
3.53125
4
invoer=1 totaal=0 som=0 while invoer !=0: invoer=eval(input('geef een getal: ')) totaal+=1 som=som+invoer print('er zijn',totaal,'getallen ingevoerd, de som is: ',som)
c26992815978d34b56390776266e11d80a172d45
wangluolin/Algorithm-Everyday
/tree/98-Validate_Binary_Search_Tree.py
1,456
3.84375
4
""" https://leetcode-cn.com/problems/validate-binary-search-tree/ 98. 验证合法的二叉搜索树 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ 方法一:中序遍历的方式 1. 注意题目,节点间严格大于小于,所以在排序时要转换为set进行判断 2. 列表之间可用+来连接 """ class Solution: def isValidBST(self, root: TreeNode) -> bool: arr = self.inOrderTra(root) return arr == sorted(set(arr)) # set的作用是避免重复值出现 def inOrderTra(self, root: TreeNode): if not root: return [] return self.inOrderTra(root.left)+[root.val]+self.inOrderTra(root.right) # 列表之间可用+号来连接 """ 方法二:边界法 1. 每个节点都具有边界值,递归即可 2. python3中获取最大值的方法是sys.maxsize """ import sys class Solution2: def isValidBST(self, root: TreeNode) -> bool: return self.isValidBoundary(root) def isValidBoundary(self, root: TreeNode, b_min=-sys.maxsize, b_max=sys.maxsize) -> bool: if not root: return True if b_min < root.val < b_max: return self.isValidBoundary(root.left, b_min, root.val) and \ self.isValidBoundary(root.right, root.val, b_max) else: return False if __name__ == "__main__": pass
e3985929a8e53c42fc524dafb21635987aacfd0a
HanYouyang/GameSoftware
/project/Algorithm/t1/8+9链表/9.3.py
529
3.890625
4
def mergeTwoLists(l1, l2): dum = cur = Node(0) while l1 and l2: if l1.value < l2.value: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dum.next def mergeTwoLists2(l1, l2): if not l1 or not l2: return l1 or l2 if l1.value < l2.value: l1.next = mergeTwoLists2(l1.next, l2) return l1 else: l2.next = mergeTwoLists2(l1, l2.next) return l2
7882a508587a172706a1dbfa55dffd225d0a1206
beidou9313/deeptest
/第一期/深圳--NLJY/生成器.py
306
3.5625
4
l = [x * x for x in range(10)] # 这是一个列表 g = (x * x for x in range(10)) # 这是一个生成器 # g.next() 通过g.next() 来调用生成器 for n in g: print(n) def fib(max): n = 0 a = 0 b = 1 while n<max: print(b) a,b = b,a+b n= n+1 print(fib(6))
ad4e7ee49c517608e23d73e126cb8a04e777fd9b
yuhao600/project-euler
/src/012. Highly divisible triangular number/012.py
401
3.609375
4
def num_of_factors(num): n = 0 factor = 1 while factor * factor < num: if num % factor == 0: n += 1 factor += 1 if factor * factor > num: return n * 2 else: # perfect square return n * 2 + 1 triangle = 0 i = 1 while True: triangle += i if num_of_factors(triangle) > 500: print(triangle) break i += 1
eb4b2ca5d2bfc4f491fb9a17f30c74ff75ce41c7
jkpr/advent-of-code-2020
/advent/day2/__init__.py
906
3.65625
4
from collections import Counter import re from typing import List def part1(lines: List[str]): count = 0 for line in lines: found = re.search(r"(\d+)-(\d+) (\w): (\w+)", line) if found: start, stop, letter, password = found.groups() counter = Counter(password) hits = counter.get(letter, 0) if int(start) <= hits <= int(stop): count += 1 print(count) def part2(lines: List[str]): count = 0 for line in lines: found = re.search(r"(\d+)-(\d+) (\w): (\w+)", line) if found: start, stop, letter, password = found.groups() password += " " * int(stop) start_match = password[int(start) - 1] == letter stop_match = password[int(stop) - 1] == letter if sum((start_match, stop_match)) == 1: count += 1 print(count)
c4d96ec8677f2d7960c7d968dfe35a5661780e3a
hoyeongkwak/workspace
/python/pythonProject/day2_2/pythonPart/pEx15.py
236
3.6875
4
for i in range(10): try: result = 10/i except ZeroDivisionError: print('숫자는 0으로 나눌 수 없습니다') else: print('result:',result) finally: print('한 번 연산 종료')
56bff1e63496eb77623feae2dd1ab46dd6ea5a86
AkshayManchanda/Machine_Learning_with_Python_Training
/day1/123.py
946
4.46875
4
"""tuple = ('rahul',100,60.4,'deepak') tuple1 = ('sanjay',10) print(tuple) #print tuple print(tuple[2:]) #0,1,2 wale se end tak (slice operator) print(tuple1[0]) #0th index wala print(tuple+tuple1) #concatenate tuples a=10; b=10; print(type(a)) print(id(a)) #address of a particular variable print(id(b)) #same as above.. it is same as value is same why waste memory name=('Utkarsh') #if one then type is string name=('Utkarsh',) #as seperated by comma and paranthesis type is tuple #name=('Utkarsh','sharma') #type is tuple print(type(name)) print(id(name)) dic = {'name':'charlie','id':100,'dept':'it'} #dict ni lia kyuki wo keyword tha print(type(dic)) print(dic) print(dic.keys()) print(dic.values()) print(dic['name']) text1 = 'hello\ user' #multiline string print(text1) str2 = '''welcome to india''' print(str2) """
69adf4ce95be93ac97cd7b6ba5f32d4be533455b
tumugip/chibi
/parser.py
1,009
3.734375
4
from exp import Val,Add,Mul,Sub,Div ''' def parse(s: str): num = int(s) return Val(num) #e = parse("123") #print(e) #s = "123+234" #pos = s.find('+')  #記号を探す #print('pos',pos) #s1=s[0:pos] #s2=s[pos+1:] #print(s,s1,s2) #+記号で分割 ''' def parse(s:str): if s.find('+') >0: pos = s.rfind('+') s1 = s[0:pos] s2 = s[pos+1:] return Add(parse(s1),parse(s2)) if s.find('-') > 0: pos = s.rfind('-') s1 = s[0:pos] s2 = s[pos+1:] return Sub(parse(s1),parse(s2)) if s.find('*') > 0: pos = s.rfind('*') s1 = s[0:pos] s2 = s[pos+1:] return Mul(parse(s1),parse(s2)) if s.find('/') > 0: pos = s.rfind('/') s1 = s[0:pos] s2 = s[pos+1:] return Div(parse(s1),parse(s2)) if s.find('(') >0: pos = s.rfind('(') return Val(int(s)) e = parse("1+6/3") print(e,e.eval())
b69978209334f59c2823c45f4a787a952f1de06f
dblarons/Choose-Your-Own-Python
/spaceadventure.py
8,334
3.9375
4
from sys import exit def chapter_three(): print "\nCHAPTER THREE: FRENEMIES\n" print "You ask the group what is going on." print "Shocked, they ask you if you remember anything." name = raw_input("They say that your name is ") print "The ship you are on is called the ENDEAVOR and you were recently raided by the menaces of the galaxy..." print "The DURG Dominion (Cue intense sound effects here)" print "Duh Duh Dummmm" print "1. What is the Durg Dominion?" print "2. Let's find other survivors and take this ship to safety!" the_durgs = raw_input("> ") # if the_durgs == "1": # NEXT ROOM HERE # elif the_durgs == "2": # FIND SURVIVORS ROOM HERE # else: # "I don't speak %r" % the_durgs # chapter_three() def chapter_three_alt(): print "\nCHAPTER THREE: ALONE AGAIN\n" print "You shoot all three soldiers--one woman and two men-- and search their bodies." print "To your dismay, you find nothing but a few rations and a rifle." print "1. Take rifle" print "2. Leave rifle" rifle = raw_input("> ") #if rifle == "1": # print "You pick up the rifle and strap it around your shoulder." # rifle = True # NEED THE NEXT ROOM HERE # else: # print "You leave the rifle and leave through the next door." # NEED THE NEXT ROOM HERE def door_three(): print "You enter the third door to find three wounded soldiers." print "You draw your blaster." print "1. Shoot them all" print "2. Ask them what is going on." three_hostages = raw_input("> ") if three_hostages == "1": chapter_three_alt() elif three_hostages == "2": chapter_three() else: print "Seriously? All you had to choose between was 1 and 2, but there you go again, choosing %r" % three_hostages three_hostages() def door_two(): print "You enter the second door, but find nothing but a few canteens and a broken galactic rifle." print "You leave the room." door_two = True chapter_two() def door_one(): print "You enter the first door hoping, or not hoping, to find the source of the mysterious scream." print "To your right you see a dead soldier." print "1. Scream like a little girl" print "2. Approach the dead man" dead_soldier = raw_input("> ") if dead_soldier == "1" or "2": door_one = True print "You are frightened, but you approach the man and hope for the best." print "As you draw near him, he suddenly opens his eyes." print "1. Shoot him" print "2. Talk to him" shoot_soldier = raw_input("> ") if shoot_soldier == "1": print "You shoot the man and leave the room." global kill_count kill_count = kill_count + 1 chapter_two() elif shoot_soldier == "2": print "You approach the man, hoping to ask about the ship and your past." dead("Suddenly, the soldier draws his gun and kills you!") else: print "I don't know what that means." dead("You are dead because you hesitated. The soldier killed you.") def chapter_two(): global begin_chapter_two while begin_chapter_two == True: print "CHAPTER TWO: CURIOSITY KILLED THE CAT" print "You search the abandoned bridge for a few minutes." print "You find a few dead soldiers and some ripped up papers, but you do not remember what happened here." global begin_chapter_two begin_chapter_two = False print "You stand in front of 3 closed doors." print "1. Door 1" print "2. Door 2" print "3. Door 3" three_doors = raw_input("> ") if three_doors == "1": door_one() elif three_doors == "2": door_two() elif three_doors == "3": door_three() else: print "%r is not a number between 1 and 3." % three_doors chapter_two() def long_hallway(): print "You walk down the long hallway and through the broken door into the main deck of the ship." print "Suddenly you hear a scream." print "1. Investigate the scream" print "2. Barricade yourself in a corner and hide" the_scream = raw_input("> ") if the_scream == "1": global begin_chapter_two begin_chapter_two = True chapter_two() elif the_scream == "2": print lightsaber print "You barricade yourself in a corner of the bridge like the coward that you are." print "After an hour of waiting, you must make a decision" print "1. Continue hiding" print "2. Investigate the ship" barricade = raw_input("> ") if barricade == "1": dead("The designer eliminates you for being a weeny.") elif barricade == "2": global begin_chapter_two begin_chapter_two = True chapter_two() else: print "What is %r supposed to mean??" % barricade long_hallway() else: print "Does your mother let you eat %r? Yeah, I didn't think so. So don't type it." % the_scream long_hallway() def stay_and_look(): print "You stay in the room and find a chest with the same emblem on it as your pack." print "1. Open the chest" print "2. Leave the room" chest_room = raw_input("> ") if chest_room == "1": print "You open the chest and find a lightsaber." print "Astounded at this discovery, you clearly take the lightsaber." print "Don't you...?" lightsaber = raw_input("> ") if lightsaber == "yes": global lightsaber lightsaber = True print "You take the lightsaber and leave the room." open_door() else: global lightsaber lightsaber = False print "You leave the lightsaber and exit the room." open_door() else: print "You leave the room." open_door() def open_door(): print "You exit the room and find yourself in a long hallway with a broken door on the other side." print "1. Walk through the door." hallway_door = raw_input("> ") if hallway_door == "1": long_hallway() else: print "This is not the time for %r " % hallway_door print "Please choose a number." open_door() def chapter_one(): print "You take the items and get dressed." print "There is a closed door in front of you." print "1. Open door" print "2. Stay in the room and take a look around" first_room = raw_input("> ") if first_room == "1": open_door() elif first_room == "2": stay_and_look() else: print "I don't know what that means. Please choose a number." chapter_one() def leave_items(): print "You are going to need these items." print "1. Take the items." items = raw_input("> ") if items == "1": global blaster blaster = True chapter_one() else: print "I don't know what that means. Please choose a number." leave_items() def start(): print "CHAPTER ONE: THE FORGOTTEN VESSEL" print "You wake up on an abandoned space ship." print "There is a pair of clothes, a blaster, and a pack with a strange emblem on it." print "1. Take the items" print "2. Leave the items" global lightsaber lightsaber = False global kill_count kill_count = 0 global blaster blaster = False items = raw_input("> ") if items == "2": leave_items() elif items == "1": global blaster blaster = True chapter_one() else: print "I don't know what that means. Please choose a number." start() def dead(why): print "\n" print why, "Good job!" global kill_count print "Your kill count is %d" % kill_count #Add if else statement here that grades you on your kill count. Lower being better. print "\nWould you like to play again?" replay = raw_input("> ") if replay == "yes": start() else: exit() print "\nThank you for playing The Durg Dominion!\n" start()
e04e3566aa851acaa56ef5a5e29eac4b603af493
rahuladream/LeetCode
/April_LeetCode/Week_1/Queue/sorting_queue.py
391
3.578125
4
import queue q = queue.Queue() q.put(14) q.put(27) q.put(11) q.put(4) q.put(1) # using bubble sort algorithm n = q.qsize() for i in range(n): x = q.get() for j in range(n-1): y = q.get() if x > y: q.put(y) else: q.put(x) x = y q.put(x) while(q.empty() == False): print(q.queue[0], end=" ") q.get()
50b2ed2fe7e3218c4e23b5f6b9a388a9c0788826
nahaza/pythonTraining
/ua/univer/HW02/ch04AlgTrain08.py
287
4.59375
5
# 8. Write code that prompts the user to enter a positive nonzero number and validates # the input. num = int(input("Enter a positive nonzero number: ")) while num <= 0: print("Warning: it is not a positive nonzero number") num = int(input("Enter a positive nonzero number: "))
88697500560cc5bf479e7a4801f6f19e4adf3f08
UMComp4140ATeam/Raymond
/src/simple_error_distribution.py
983
3.859375
4
#!/bin/python import math import random MIN_ODD_MODULUS = 0 ''' A simple error distribution class. That returns a small error relative to the odd modulus. This is a temporary class that will be used until we have time to look into making a better error distribution. ''' class SimpleErrorDistribution(object): def __init__(self, odd_modulus, seed=1): if odd_modulus < MIN_ODD_MODULUS: raise ValueError("Odd modulus {0} is too small for error distribution.".format(odd_modulus)) # If q is sufficiently large, log(q) should be small enough for our max error self.__max_rand = int(math.log(odd_modulus, 64)) +1 # Uses os.urandom function which, according to the documentation, is cryptographically secure self.__random_generator = random.SystemRandom(seed) def sample_distribution(self): return self.__random_generator.randint(0, self.__max_rand) if __name__=="__main__": print "SimpleErrorDistribution class"
123b4d63062b675e4615d7d70184f9a4e05e9e4c
TiagoRodriguesskt/Aprendendo-Python
/adivinhação.py
435
3.890625
4
from random import randint from time import sleep computer = randint(0, 10) print('=' * 50) print('\tLet s play guessing? ') print('\tTry to hit the number I am thinking! ') print('=' * 50) player = int(input('Enter an integer from 0 to 10! ')) print('YOU...') sleep(3) if player == computer: print('CONGRATULATIONS! You are right!' ) else: print('LOST! I thought of the number {} and not the {}!'.format(computer, player))
a8cf52b6682772397c1e46736b301f30ce01d5d2
T1h0can/2d-platformer-pygame
/lib/vector.py
3,325
3.609375
4
class Vector2d: # @type_check(tuple, 2) def __init__(self, coords): """ input a tuple of (x,y) """ # Type check # if not ((isinstance(coords, tuple)) and (len(coords) == 2)): # raise TypeError("{} isn't a tuple of length 2".format(coords)) self.coords = list(coords) self.x = coords[0] self.y = coords[1] def __eq__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) return self.coords == vec.coords def __add__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) return Vector2d((self.x+vec.x, self.y+vec.y)) def __mul__(self, num): # Type check if not isinstance(num, float): raise TypeError("Argument is a {} object, not a float object".format(type(num))) return Vector2d((self.x*num, self.y*num)) def __sub__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) return Vector2d((self.x-vec.x, self.y-vec.y)) def __matmul__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) return [a*b for a,b in zip(self.coords, vec.coords)] # reflected operators def __rmul__(self, num): # Type check if not isinstance(num, float): raise TypeError("Argument is a {} object, not a float object".format(type(num))) return self*num # in place operators def __iadd__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) self.x += vec.x self.y += vec.y self.coords = [self.x, self.y] return self def __imul__(self, num): # Type check if not isinstance(num, float): raise TypeError("Argument is a {} object, not a float object".format(type(num))) self.x *= num self.y *= num self.coords = [self.x, self.y] return self def __isub__(self, vec): # Type check if not isinstance(vec, Vector2d): raise TypeError("Argument is a {} object, not a Vector2d object".format(type(vec))) self.x -= vec.x self.y -= vec.y self.coords = [self.x, self.y] return self # operators def __neg__(self): return Vector2d((self.x*(-1), self.y*(-1))) def __abs__(self): return Vector2d((abs(self.x), abs(self.y))) # print def __str__(self): return str(self.coords) def set(self, xy): x = xy[0] y = xy[1] self.x = x self.y = y if __name__ == "__main__": vector2 = Vector2d((-4.0, 5.0)) vector1 = Vector2d((3.0, 1.0)) print(vector1) vector1 -= vector2 vector1 *= 2.0 print(-vector1) print(abs(vector2)) vector1 = Vector2d('wrong' )
b92fa06d7d91f75370ae601cff9cc768cb1f215c
Weiguo-Jiang/alien_invasion_project
/alien_invasion.py
1,572
3.5
4
import pygame from settings import Settings from game_stats import GameStats from scoreboard import Scoreboard from button import Button from ship import Ship from alien import Alien import game_functions as gf from pygame.sprite import Group def run_game(): # initialize game and create a screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # create a Play button play_button = Button(ai_settings, screen, "Play") # create an example for storing statistcial information stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # create an alien alien = Alien(ai_settings, screen) # create a ship ship = Ship(ai_settings, screen) # create a class used to store bullets bullets = Group() aliens = Group() # create alien group gf.create_fleet(ai_settings, screen, ship, aliens) # begin the main loop of the game while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) # delete bullets that have disappeared for bullet in bullets.copy(): if bullet.rect.bottom <= 0 : bullets.remove(bullet) print(len(bullets)) run_game()
7f0dbbfce00c1d8239771665b61a682730abf8e1
y56/leetcode
/694. Number of Distinct Islands.py
4,703
3.53125
4
""" 694. Number of Distinct Islands Medium Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Example 1: 11000 11000 00011 00011 Given the above grid map, return 1. Example 2: 11011 10000 00001 11011 Given the above grid map, return 3. Notice that: 11 1 and 1 11 are considered different island shapes, because we do not consider reflection / rotation. Note: The length of each dimension in the given grid does not exceed 50. """ """ Approach #1: Hash By Local Coordinates [Accepted] Intuition and Algorithm At the beginning, we need to find every island, which we can do using a straightforward depth-first search. The hard part is deciding whether two islands are the same. Since two islands are the same if one can be translated to match another, let's translate every island so the top-left corner is (0, 0) For example, if an island is made from squares [(2, 3), (2, 4), (3, 4)], we can think of this shape as [(0, 0), (0, 1), (1, 1)] when anchored at the top-left corner. From there, we only need to check how many unique shapes there ignoring permutations (so [(0, 0), (0, 1)] is the same as [(0, 1), (1, 0)]). We use sets directly as we have showcased below, but we could have also sorted each list and put those sorted lists in our set structure shapes. In the Java solution, we converted our tuples (r - r0, c - c0) to integers. We multiplied the number of rows by 2 * grid[0].length instead of grid[0].length because our local row-coordinate could be negative. """ """ Complexity Analysis Time Complexity: O(R∗C)O(R*C)O(R∗C), where RRR is the number of rows in the given grid, and CCC is the number of columns. We visit every square once. Space complexity: O(R∗C)O(R*C)O(R∗C), the space used by seen to keep track of visited squares, and shapes. """ class Solution: def numDistinctIslands(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 M,N=len(grid),len(grid[0]) seen=set() def dfs_explore(r,c,li): # li to collect if 0<=r<M and 0<=c<N and (r,c) not in seen and grid[r][c]==1: li.append((r,c)) seen.add((r,c)) dfs_explore(r+1,c,li) dfs_explore(r-1,c,li) dfs_explore(r,c-1,li) dfs_explore(r,c+1,li) def translated(li,r0,c0): # 平移 return frozenset((r-r0,c-r0) for r,c in li) # or # return tuple(sorted((r-r0,c-r0) for r,c in li)) island_pattern_pool=set() li=[] ans=0 for r,row in enumerate(grid): for c,ele in enumerate(row): li.clear() dfs_explore(r,c,li) if not li: continue pattern=translated(li,r,c) if pattern not in island_pattern_pool: ans+=1 island_pattern_pool.add(pattern) return ans """ Float precision issue!!! Using float as hash-key is such a bad idea """ """ Approach #2: Hash By Path Signature [Accepted] Intuition and Algorithm When we start a depth-first search on the top-left square of some island, the path taken by our depth-first search will be the same if and only if the shape is the same. We can exploit this by recording the path we take as our shape - keeping in mind to record both when we enter and when we exit the function. The rest of the code remains as in Approach #1. """ """ Complexity Analysis Time and Space Complexity: O(R∗C)O(R*C)O(R∗C). The analysis is the same as in Approach #1. """ class Solution(object): def numDistinctIslands(self, grid): seen = set() def explore(r, c, di = 0): if (0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] and (r, c) not in seen): seen.add((r, c)) shape.append(di) explore(r+1, c, 1) explore(r-1, c, 2) explore(r, c+1, 3) explore(r, c-1, 4) shape.append(0) shapes = set() for r in range(len(grid)): for c in range(len(grid[0])): shape = [] explore(r, c) if shape: shapes.add(tuple(shape)) return len(shapes)
9ca9191cf6729688724725f225cfea55a09cc4f6
rctorr/desarrollo-web-python-cdmx-20-01
/Sesion-01/pares_nones.py
346
3.6875
4
# 1. Leer el valor de N cad = input("Dame un número entero mayor que cero:") n = int(cad) # 2. Generar una lista de N números lista = range(n) # 3. Determinar cuales son pares y nones y asignar la palabra correcta # 4. Imprimir el resultado for i in lista: if i % 2 == 0: # par print(i, "par") else: print(i, "impar")
a70fd09a71c18c65319b4c4739bc8151bc3ce82a
bruce-szalwinski/lpthw
/ex3.py
640
4.1875
4
# prints print "i will now count my chickens:" # division before addition print "Hens", 25+30 / 6.0 # modulo first, then multiplication, then subtraction print "Roosters", 100-25 * 3 % 4 # 4%2 = 0, integer division (1/4 = 0) print "Now i will count the eggs" print 3+2+1-5+4%2-1/4+6 # addition and subtraction before comparisoin print "is it true that 3+2<5-7" print 3+2 < 5-7 # addition print "what is 3+2", 3+2 # subtraction print "what is 5-7", 5-7 print "oh, that's why it is false" print "how about some more" # comparison print "is it greater", 5 > -2 print "is it greater or equal", 5>= -2 print "is it less or equal", 5 <= -2
a02d068b153208c49aa6881685eb550acd2320f1
zhengjiani/pyAlgorithm
/leetcodeDay/April/prac23.py
2,802
4.03125
4
# -*- encoding: utf-8 -*- """ @File : prac23.py @Time : 2020/4/26 9:37 上午 @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm """ # Definition for singly-linked list. from queue import PriorityQueue from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: """ 暴力求解-时间复杂度O(NlogN),N是结点总数目 遍历所有的值需话费O(N)的时间 一个稳定的排序算法花费O(NlogN)时间 遍历同时创建新的有序链表花费O(N)的时间 空间复杂度:O(N) """ def mergeKLists(self, lists: List[ListNode]) -> ListNode: # 声明用于排序的数组 self.nodes = [] # 声明头结点和构建链表结点 head = point = ListNode(0) # 将输入的结点放入数组 for l in lists: while l: self.nodes.append(l.val) l = l.next # 将数组排序并放入链表 for x in sorted(self.nodes): point.next = ListNode(x) point = point.next return head.next class Solution1: """优先队列优化逐一比较方法 时间复杂度O(Nlogk),k是链表数目 """ def mergeKLists(self, lists: List[ListNode]) -> ListNode: # 声明头结点和构建链表结点 head = point = ListNode(0) q = PriorityQueue() # 将输入节点放入优先队列中 for l in lists: if l: q.put((l.val,l)) # 循环迭代队列 while not q.empty(): val, node = q.get() point.next = ListNode(val) point = point.next node = node.next if node: q.put((node.val,node)) return head.next class Solution2: """逐一两两合并链表,分治 将合并k个链表的问题转化为合并2个链表k-1次 时间复杂度O(kN),空间复杂度O(1) """ def mergeKLists(self, lists: List[ListNode]) -> ListNode: amount = len(lists) intervel = 1 while intervel < amount: for i in range(0,amount-intervel,intervel*2): lists[i] = self.merge2Lists(lists[i],lists[i+intervel]) intervel *=2 return lists[0] if amount > 0 else None def merge2Lists(self,l1,l2): head = point = ListNode(0) while l1 and l2: if l1.val <= l2.val: point.next = l1 l1 = l1.next else: point.next = l2 l2 = l1 l1 = point.next.next point = point.next if not l1: point.next = l2 else: point.next = l1 return head.next
196eadac08ba78e9a5cd446b363e429aee2958b4
yeboahd24/Python201
/default program/class2.py
1,856
4.09375
4
#!usr/bin/env/python3 """use plain attribute instead of setter and getter methods""" class OldResistor(object): """using these setters and getters is simple but not pythonic""" def __init__(self, ohms): self._ohms = ohms def get_ohms(self): return self._ohms def set_ohms(self, ohms): self._ohms = ohms # r = OldResistor(50e3) # print('Before: ', r.get_ohms()) # r.set_ohms(10e3) # print('After: ', r.get_ohms()) class Resistor(object): def __init__(self, ohms): self.ohms = ohms self.voltage = 0 self.current = 0 r1 = Resistor(50e3) r1.ohms = 10e3 # simple implementation # print(r1.ohms) # Pythonic Implementation class VoltageResistor(Resistor): def __init__(self, ohms): super().__init__(ohms) self._voltage = 0 @property def voltage(self): return self._voltage @voltage.setter def voltage(self, voltage): self._voltage = voltage self.current = self._voltage / self.ohms # r2 = VoltageResistor(1e3) # print(f'Before: {r2.current:.2f} amps') # r2.voltage = 10e3 # print(f'After: {r2.current:.2f} amps') class BoundedResistance(Resistor): """using setter and getter to validate""" def __init__(self, ohms): super().__init__(ohms) @property def ohms(self): return self._ohms @ohms.setter def ohms(self, ohms): if ohms <= 0: raise ValueError(f'ohms must be > 0; got {ohms}') self._ohms = ohms # using property method to make attribute from parent class immutable class FixedResistance(Resistor): def __init__(self, ohms): super().__init__(ohms) @property def ohms(self): return self._ohms @ohms.setter def ohms(self, ohms): if hasattr(self, '_ohms'): raise AttributeError("Ohms is immutable") self._ohms = ohms r4 = FixedResistance(10e3) r4.ohms = 11e4 print(r4.ohms)
87ddb62ebf1a0e29466247b4874f0733b86927f0
davidjmstewart/DependencyInversion-DependencyInjection
/IoC/python/python_ioc_tkinter.py
1,189
3.625
4
# Run with python ./python_ioc_tkinter.py from tkinter import * window = Tk() window.title("IoC example") window.geometry('600x300') first_name_label = Label(window, text="First name") first_name_label.grid(column=0, row=0) first_name_txt = Entry(window,width=10) first_name_txt.grid(column=1, row=0) # Lambda callback allows the framework to call our code when a click event happens # This is the Hollywood principle in action! btn = Button(window, text="Submit first name", command=lambda: first_name_label.configure(text = first_name_txt.get())) btn.grid(column=2, row=0) last_name_label = Label(window, text="Last name") last_name_label.grid(column=0, row=1) last_name_txt = Entry(window,width=10) last_name_txt.grid(column=1, row=1) btn = Button(window, text="Submit last name", command=lambda: last_name_label.configure(text = last_name_txt.get())) btn.grid(column=2, row=1) email_label = Label(window, text="Email address") email_label.grid(column=0, row=2) email_txt = Entry(window,width=10) email_txt.grid(column=1, row=2) btn = Button(window, text="Submit email address", command=lambda: email_label.configure(text = email_txt.get())) btn.grid(column=2, row=2) window.mainloop()
22612544a898bdf9ee3bdf45ab6ded5ba9e32d13
vzhng/python_practice
/python_learn1/factor.py
210
3.78125
4
a=input("Please input a number:") #a=30 # m=int(a) def factorize(n): b=[] for i in range(1,n+1): if n % i ==0: b.append(i) return b x=factorize(int(a)) print(x)
b7fd40f7cf3b28676618e12c34734fb563f62fef
laithadi/School-Work---Data-Structures-Python-
/Adix5190_a03/src/t05.py
719
3.9375
4
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-02-01 ................................................... ''' from functions import has_balanced_brackets BALANCED = 0 MORE_LEFT = 1 MORE_RIGHT = 2 MISMATCHED = 3 string = input("Enter a string: ") balanced = has_balanced_brackets(string) if balanced == MORE_LEFT: print("'{}' has more left brackets.".format(string)) elif balanced == BALANCED: print("'{}' has balanced brackets.".format(string)) elif balanced == MORE_RIGHT: print("'{}' has more right brackets.".format(string)) else: print("'{}' has mismatched brackets.".format(string))
c49d72cef8ea6b16beae7c1ec695c32ee8e59c40
GloriaWing/wncg
/打印乘法表(不同排列方式).py
913
3.796875
4
''' #完整格式输出九九乘法表 for i in range(1,10): for j in range(1,10): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #左上三角格式输出九九乘法表 for i in range(1,10): for j in range(i,10): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #右上三角格式输出九九乘法表 for i in range(1,10): for k in range(1,i): print(end=' ') for j in range(i,10): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #左下三角格式输出九九乘法表 for i in range(1,10): for j in range(1,i+1): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #右下三角格式输出九九乘法表 for i in range(1,10): for k in range(1,10-i): print(end=' ') for j in range(1,i+1): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') '''
80e181f8b75ffcb822b0f1aaa61d26632c190007
SketchwithTejOfficial/TexttoSpeechSoftware
/TexttoSpeech.py
469
3.671875
4
import pyttsx3 #To install module enter pip install pyttsx3 in terminal engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) #For female voice enter 1. engine.setProperty('rate', 150) #To make the voice slow and fast decrease and increase the values here. def speak(text): engine.say(text) speak("ENTER YOUR TEXT HERE TO SPEAK") #Here you can enter any text, it will speak the entered text.
d610a795b627460112c49e9b328de7c1973f1753
hattoryha/Python
/find_question.py
975
3.53125
4
import requests import bs4 import argparse def get_questions(N, tag): # tag = 'python' url = 'https://api.stackexchange.com/2.2/questions?order=desc&sort=votes&tagged={}&site=stackoverflow'.format(tag) r = requests.get(url) api_data = r.json() api_item = api_data['items'] # N = 1000 questions = [] for question_index in range(N): try: questions.append(api_item[question_index]['title']) print(api_item[question_index]['title']) except IndexError: print('there are only {} questions related to the tag'.format(len(api_item)).upper()) break def main(): parser = argparse.ArgumentParser(description='Enter N and tag to find N the highest voted questions with this tag') parser.add_argument("N", type=int) parser.add_argument("tag", type=str) N = parser.parse_args().N tag = parser.parse_args().tag get_questions(N, tag) if __name__ == "__main__": main()
53f74cafb1e31ae278a4b33b91984d1791cb2f6c
EmlynQuan/Programming-Python
/JZOffer/JZOffer36.py
2,021
3.90625
4
# coding=utf-8 # Definition for a Node. class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ # head head, tail = root, root self.travTree(root.left, root, True) self.travTree(root.right, root, False) while head.left: head = head.left while tail.right: tail = tail.right head.left = tail tail.right = head return head def travTree(self, curNode, father, tempNode, leftFlag): if curNode == None: return else: # 如果当前已经是叶子了, 可以修改指针了 if curNode.left == None and curNode.right == None: # 当前节点的右节点是父节点 if leftFlag: curNode.right = father if curNode.val > tempNode.val: tempNode = curNode # 当前节点的左节点是父节点 else: curNode.left = father if curNode.val < tempNode.val: tempNode = curNode else: # 如果还有左子节点 if curNode.left: self.travTree(curNode.left, curNode, tempNode, True) curNode.left = tempNode tempNode.right = curNode # 如果还有右子节点 if curNode.right: self.travTree(curNode.right, curNode, tempNode, False) curNode.right = tempNode tempNode.left = curNode if __name__ == '__main__': root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) Solution().treeToDoublyList(root)
8aa4e6c66c6b6e1bbed93846899fa796a3b7b2ce
cligs/toolbox
/analyse/make_freqslist.py
7,007
3.671875
4
#!/usr/bin/env python3 # Filename: make_freqslist.py # Author: #cf # Date: 2016 """ Creates an overall relative frequency list for items in a text collection. Items can be raw word tokens, lowercase word tokens, or lemmata (using TreeTagger). Data can be relative frequency per 1000 words or proportion of texts containing item at least once. TODOs: Solution for frequent apostrophe'd / hyphenated words; Complete punctuation. """ ##################### # Parameters ##################### WorkDir = "/" # ends on slash TextPath = WorkDir + "txt/*.txt" Modes = ["raw-words", "lower-words", "lemmata"] # raw-words|lower-words|lemmata Types = ["props", "freqs"] #props|freqs Tokenizer = "[\W]" Punctuation = "[.,:;!?«»\(\)—\"]" FreqFilePrefix = "./freqlists/fr-20th-novel" ##################### # Import statements ##################### import os import re import glob import pandas as pd from collections import Counter import treetaggerwrapper as ttw ##################### # Functions ##################### def read_file(File): """ Read a text file and return as string. """ with open(File, "r") as InFile: Text = InFile.read() Filename, Ext = os.path.basename(File).split(".") #print(Filename) return Text def get_words(Text, Tokenizer, Punctuation): """ Turn a string into a list of word tokens (excluding punctuation). """ # Merge elided tokens into full token where possible (no ambiguity) # Note: Does not work for: l, s, which remain as such. Text = re.sub("\Wd\W", " de ", Text) Text = re.sub("\WD\W", " De ", Text) Text = re.sub("\Wj\W", " je ", Text) Text = re.sub("\WJ\W", " Je ", Text) Text = re.sub("\Wn\W", " ne ", Text) Text = re.sub("\WN\W", " Ne ", Text) Text = re.sub("\Wc\W", " ce ", Text) Text = re.sub("\WC\W", " Ce ", Text) Text = re.sub("\Wqu\W", " que ", Text) Text = re.sub("\WQu\W", " Que ", Text) Text = re.sub("\Wt\W", " te ", Text) Text = re.sub("\WT\W", " Te ", Text) Text = re.sub("\Wm\W", " me ", Text) Text = re.sub("\WM\W", " Me ", Text) Text = re.sub("\Wjusqu\W", " jusque ", Text) Text = re.sub("\WJusqu\W", " Jusque ", Text) Text = re.sub("\Wquelqu\W", " quelque ", Text) Text = re.sub("\WQuelqu\W", " Quelque ", Text) Text = re.sub("\Wquoiqu\W", " quoique ", Text) Text = re.sub("\WQuoiqu\W", " Quoique ", Text) # Protect some composed tokens from being split Text = re.sub("peut-être", "peut_être", Text) Text = re.sub("après-midi", "après_midi", Text) Text = re.sub("au-dessus", "au_dessus", Text) Text = re.sub("Peut-être", "Peut_être", Text) Text = re.sub("Après-midi", "Après_midi", Text) Text = re.sub("Aujourd'hui", "Aujourd_hui", Text) Text = re.sub("au-dessous", "au_dessous", Text) Text = re.sub("au-delà", "au_delà", Text) Text = re.sub("en-deça", "en_deça", Text) Text = re.sub("aujourd'hui", "aujourd_hui", Text) # Tokenize the text Tokens = re.split(Tokenizer, Text) Tokens = [Token for Token in Tokens if len(Token) != 0] Words = [Token for Token in Tokens if Token not in Punctuation] return Words def get_lower(Text, Tokenizer, Punctuation): """ Same as words, but also makes all items lowercase. """ Words = get_words(Text, Tokenizer, Punctuation) Lower = [Word.lower() for Word in Words] return Lower def get_lemmata(Text, Punctuation): """ Lemmatize the text using TreeTagger. Correct language model needs to be set! """ tagger = ttw.TreeTagger(TAGLANG='fr') Tagged = tagger.tag_text(Text) Lemmata = [] for Item in Tagged: Item = re.split("\t", Item) if len(Item) == 3: Lemma = Item[2] if Item[1] != "NAM": if "|" in Lemma: Lemma = re.split("\|", Lemma)[1] Lemmata.append(Lemma) Lemmata = [Lemma for Lemma in Lemmata if Lemma not in Punctuation] Lemmata = [Lemma for Lemma in Lemmata if Lemma not in ["--", "---", "...", "@card@", "@ord@", "\"\"\"\""]] return Lemmata def get_itemfreqs(AllItems, Type, Mode, TextCounter): """ Get the overall frequency of each item in the text collection. Calculate relative frequency or proportion of texts containing the item. Sort by descending frequency / proportion, transform to DataFrame. """ ItemFreqs = Counter(AllItems) ItemFreqs = pd.DataFrame.from_dict(ItemFreqs, orient="index").reset_index() ItemFreqs.columns = [Mode, "freqs"] ItemFreqs.sort_values(["freqs", Mode], ascending=[False, True], inplace=True) ItemFreqs = ItemFreqs.reset_index(drop=True) if Type == "freqs": ItemFreqsRel = pd.DataFrame(ItemFreqs.loc[:,"freqs"].div(len(AllItems))*1000) ItemFreqsRel.columns = ["per1000"] ItemFreqs = pd.concat([ItemFreqs, ItemFreqsRel], axis=1, join="outer") #ItemFreqs = ItemFreqs.drop("freqs", axis=1) elif Type == "props": ItemFreqsRel = pd.DataFrame(ItemFreqs.loc[:,"freqs"].div(TextCounter)*100) ItemFreqsRel.columns = ["in%texts"] ItemFreqs = pd.concat([ItemFreqs, ItemFreqsRel], axis=1, join="outer") #ItemFreqs = ItemFreqs.drop("freqs", axis=1) return ItemFreqs def save_csv(ItemFreqs, FreqFilePrefix, Type, Mode): """ Save to file. """ ItemFreqsFile = WorkDir + FreqFilePrefix +"_"+ Type +"-"+ Mode+".csv" print("Saving", os.path.basename(ItemFreqsFile)) with open(ItemFreqsFile, "w") as OutFile: ItemFreqs.to_csv(OutFile) #################### # Main #################### def main(TextPath, Modes, Types, Tokenizer, Punctuation, FreqFilePrefix): print("Launched.") for Type in Types: for Mode in Modes: AllItems = [] TextCounter = 0 for File in glob.glob(TextPath): TextCounter +=1 print(".", end="\r") Text = read_file(File) if Mode == "raw-words": Words = get_words(Text, Tokenizer, Punctuation) if Type == "props": Words = list(set(Words)) AllItems = AllItems + Words if Mode == "lower-words": Lower = get_lower(Text, Tokenizer, Punctuation) if Type == "props": Lower = list(set(Lower)) AllItems = AllItems + Lower if Mode == "lemmata": Lemmata = get_lemmata(Text, Punctuation) if Type == "props": Lemmata = list(set(Lemmata)) AllItems = AllItems + Lemmata ItemFreqs = get_itemfreqs(AllItems, Type, Mode, TextCounter) save_csv(ItemFreqs, FreqFilePrefix, Type, Mode) print("Done.") main(TextPath, Modes, Types, Tokenizer, Punctuation, FreqFilePrefix)
f80d47fdecbd93953dba21d9194e5a695d7259e5
MarioPezzan/ExerciciosGuanabaraECurseraPyCharm
/Exercícios curso em video/Exercicios/ex002.py
424
3.796875
4
nome = input('qual seu nome? ') print(f'Muito bem vindo {nome} prazer em te conhecer!') sexo = input('qual seu sexo? ') nacionalidade = input('qual sua nacionalidade? ') dia = input('Dia do Nascimento: ') mes = input('Mês do Nascimento (Ex:Janeiro): ') ano = input('Ano do Nascimento: ') print(f'Nome:{nome}. Sexo:{sexo}. Nacionalidade:{nacionalidade}.Você nasceu no dia {dia} do mês de {mes} do ano de {ano}. Correto?')
3f6ed96b7b580570ab4bf4af5fbe925ac0048833
GuilhermeUtech/Python
/intro/ex15.py
194
3.875
4
a = str(input("Digite uma frase\n")) b = a.count('A') print(b) c = a.find('A') print("O primeiro A começa em: {}".format(c)) d = a.rfind('A') print("A última ocorrência é em: {}".format(d))
6579f3df53d81400e77a1b14654130a55d235ff4
DeviantBadge/spheremail.ru
/1sem/intoToDataAnalisys/practice/hw2/taskH.py
2,615
3.734375
4
class Node: left = None right = None parent = None value: int = None def __init__(self, val, parent): self.value = val self.parent = parent def next(self, val: int): if val > self.value: return self.right else: if val != self.value: return self.left else: return self def append_child(self, val: int): if val > self.value: self.right = Node(val, self) else: if val != self.value: self.left = Node(val, self) def __contains__(self, value: int): if value == self.value: return True else: if self.right is not None and self.right.__contains__(value): return True if self.left is not None and self.left.__contains__(value): return True return False class TreeIterator: cur_node: Node = None left: bool = False right: bool = False def __init__(self, node: Node): self.cur_node = node class BinarySearchTree: root: Node = None def __init__(self, root_value=None): if root_value is not None: self.append(root_value) def __contains__(self, value: int): if self.root is None: return False return self.root.__contains__(value) def __iter__(self): if self.root is None: self.__iterators__ = [] else: self.__iterators__ = [self.root] return self def __next__(self): if len(self.__iterators__) == 0: raise StopIteration node = self.__iterators__[0] if node.left is not None: self.__iterators__.append(node.left) if node.right is not None: self.__iterators__.append(node.right) del self.__iterators__[0] return node.value def append(self, value: int): if self.root is None: self.root = Node(value, None) else: cur = self.root while True: next_el = cur.next(value) if next_el is None or next_el == cur: break cur = next_el if cur != next_el: cur.append_child(value) return self if __name__ == '__main__': tree = BinarySearchTree() for v in [8]: tree.append(v) for v in [8, 12, 13]: print(v in tree) print(*tree)
03efc485c1336e1786c44190c301aba5c423df33
Bl4ky113/clasesHaiko2021
/check_vocales.py
990
3.75
4
VOCALES = ('a', 'e', 'i', 'o', 'u') class word (): def __init__(self) -> None: self.word = input("Ingresa una palabra: ") self.info = self.getInfo(self.word) def getInfo (self, word): info_dict = {} has_vocals = False num_vocals = 0 vocals = [] for char in word: if char.lower() in VOCALES: has_vocals = True num_vocals += 1 if char.lower() not in vocals: vocals += char info_dict.update({ "has_vocals": has_vocals, "num_vocals": num_vocals, "vocals": vocals }) return info_dict arr_words = [] input_word = word() while input_word.word != "fin": arr_words.append(input_word) input_word = word() for index_word in arr_words: if (index_word.info["has_vocals"] == True): print(f"La Palabra {index_word.word} Sí tiene Vocales") print(f"Tiene {index_word.info['num_vocals']} vocales y son {index_word.info['vocals']}") else: print(f"La Palabra {index_word.word} No tiene Vocales")
db72261115a1ebe40b8ebf78e11fb39f45fb31cf
YasinEhsan/developer-drills
/twoPointers/pairWithTargetSum.py
420
3.640625
4
# may 29 20 def pair_with_targetsum(arr, target_sum): # init pointers left = 0 right = len(arr) -1 # loop until pair found while left < right: # get sum currSum = arr[left] + arr[right] if currSum == target_sum: return [left, right] elif currSum < target_sum: # need bigger number left+=1 else: # sum too big right -=1 return [-1, -1] # n time | 1 space
00f3091b6a05c7ede5800e9468385189e3236734
cuimin07/LeetCode-test
/133.最长和谐子序列.py
613
3.75
4
''' 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。 现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。 示例 1: 输入: [1,3,2,2,5,2,3,7] 输出: 5 原因: 最长的和谐数组是:[3,2,2,2,3]. 说明: 输入的数组长度最大不超过20,000. ''' #答: class Solution: def findLHS(self, nums: List[int]) -> int: ans = 0 d = collections.Counter(nums) for num in nums: if num + 1 in d: ans = max(ans, d[num]+d[num+1]) return ans
360b9485c6627e37c7a94d97fab41bd5a2ba7520
benfatehi/cs114
/Volume_in_gallons.py
154
3.953125
4
print("Please give me a volume in gallons. I will then convert it into liters.") gallons=int(input()) liters=(gallons * 3.78541) print("liters: ",liters)
fc0b92d7fef715eb235a38397556eae2051741dd
qwert19981228/P4
/课件/0228/9问题.py
925
3.609375
4
import threading g_num = 0 def task1(): global g_num for i in range(1000000): # 上锁 mutexFlag = mutex.acquire(True) # 检测是否获得资源 如果得到 mutexFlag True if mutexFlag: g_num += 1 # 释放锁 mutex.release() print('task1',g_num) def task2(): global g_num for i in range(1000000): # True 如果资源已经被其他线程上锁,就会一直等(阻塞)到对方释放锁 # False 不等待 直接继续执行下面的代码 mutexFlag = mutex.acquire(True) if mutexFlag: g_num += 1 mutex.release() print('task2',g_num) if __name__ == '__main__': # 实例化锁 mutex = threading.Lock() t1 = threading.Thread(target=task1) t2 = threading.Thread(target=task2) t1.start() t2.start() t1.join() t2.join() print(g_num)
8c449ae9a3ef50d9e09acc515a55ab68f1b20664
Anindyadeep/CNN-from-scratch
/conv_test.py
3,220
3.578125
4
from keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt from conv3x3 import Conv3x3 from maxpool import MaxPool2D from softmax import Softmax (X_train, Y_train), (X_test, Y_test) = mnist.load_data() X_train_now = X_train[0:1000] Y_train_now = Y_train[0:1000] X_test_now = X_test[0:1000] Y_test_now = Y_test[0:1000] conv3x3_1 = Conv3x3(16) maxpool2d_1 = MaxPool2D() conv3x3_2 = Conv3x3(16) maxpool2d_2 = MaxPool2D() softmax = Softmax(5*5*16, 10) # single feed forward CNN impleamnetation def single_full_forward(image, label): image = image/255 out_image_1 = conv3x3_1.single_conv_forward(image) out_image_1 = maxpool2d_1.maxpool_forward(out_image_1) ''' IT CAN ACTUALY CANT GO THRIUGH MULTIPLE CONVOLUTION COZ, THE CONVOLUTION IS MEANT FOR 2x2 BUT AFTER ONE CONVOLUTION THE IMAGE WILL BE TREATED AS 3x3 AND SO ITS GIVING THAT ERROR, NOW WHAT I CAN DO IS THAT, IN THE CONV PART JUST CAN MAKE ONE MORE LOOP FOR THE F NO OF THE CHANNELS WHERE F = 3 (IF RGB) ''' out_image_2 = conv3x3_2.single_conv_forward(out_image_1) out_image_2 = maxpool2d_2.maxpool_forward(out_image_2) probabilities = softmax.softmax_forward(out_image_2) loss = -np.log(probabilities[label]) acc = 1 if np.argmax(probabilities) == label else 0 return probabilities, loss, acc # single training impleamentation def train(image, label, learning_rate = 0.003): probabilities, loss, acc = single_full_forward(image, label) gradients = np.zeros(10) gradients[label] = -1/probabilities[label] # backprop gradient_dx2 = softmax.soft_backward(gradients, learning_rate) gradient_dx2 = maxpool2d_2.maxpool_backward(gradient_dx2) gradient_dx2 = conv3x3_2.single_conv_backward(gradient_dx2, learning_rate) gradient_dx1 = maxpool2d_1.maxpool_backward(gradient_dx2) gradient_dx1 = conv3x3_1.single_conv_backward(gradient_dx1, learning_rate) return loss, acc print(".... USING KERAS DATASET ONLY, NO OTHER FUNCTIONALITIES ARE BEING ADDED HERE ....") print("\nCONVOLUTON INITIALIZED ...") print("TRAINING FOR ", len(X_train_now), " IMAGES \n") print("USING ONE CONV LAYER WITH 64 FILTERS") print("NO DENSE LAYER\n") for epoch in range(3): permutation = np.random.permutation(len(X_train_now)) train_images = X_train_now[permutation] train_labels = Y_train_now[permutation] val_images = X_test_now[permutation] val_labels = Y_test_now[permutation] # TRAIN total_train_loss = 0 train_accuracy = 0 total_val_loss = 0 val_accuracy = 0 for i, (image_train, label_train) in enumerate(zip(train_images, train_labels)): if i> 0 and i%100 == 99: print( "AT EPOCH ", epoch, " AFTER COMPUTING ", i+1, " IMAGES TRAIN LOSS IS ", total_train_loss/100, " TRAIN ACC ", train_accuracy, "%" ) total_train_loss = 0 train_accuracy = 0 loss_train, acc_train = train(image_train, label_train) total_train_loss += loss_train train_accuracy += acc_train print("\n")
8eb8d03953e7ed71598715af93170224e7cfa274
eboladev/Study
/ProgrammingLanguage/Python/Source/LeapYear.py
174
3.640625
4
def leap_year(n): return (n%4==0) and n%100 or n%400==0 def main(): for n in range(1990, 2001): if leap_year(n): print n if __name__ == "__main__": main()
3a848c420e0aea16fdd18572c418127c9233044e
xulleon/algorithm
/leetcode/Chapter6_DFS_on_Combination/Word_Ladder_II.py
2,924
3.71875
4
# https://leetcode.com/problems/word-ladder-ii/submissions/ from pprint import pprint class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if not beginWord or not endWord or not wordList or endWord not in wordList: return [] ladder = [] if beginWord not in wordList: # THIS IS VERY IMPORTANT!!! wordList.append(beginWord) indegree = self.build_graph(wordList) distance = self.bfs(beginWord, indegree) self.dfs(ladder, [endWord], endWord, beginWord, indegree, distance) return ladder def dfs(self, ladder, subsets, end, start, indegree, distance): if end == start: # This is an exit condition ladder.append(subsets[::-1]) return for i in range(len(end)): # it is important to track from end to start new_end = end[:i] + '*' + end[i+1:] for word in indegree[new_end]: if word in subsets: # ensure that nbr is never used. continue # this condition ensure that the path is going to the direction # to the endWord, not going back or stay in the same level!!!!! # this is another reasaon why we need bfs to create the distance dict if distance[word] + 1 == distance[end]: subsets.append(word) self.dfs(ladder, subsets[:], word, start, indegree, distance) subsets.pop() # different from word ladder. this problem requires to list possible pathes # bfs is needed to create the instance dictionary. This dict will record # the cost of each node from beginWord to endWord def bfs(self, beginWord, indegree): from collections import deque queue = deque([(beginWord, 1)]) instance = {beginWord: 1} visited = {beginWord: True} while queue: size = len(queue) for _ in range(size): word, level = queue.popleft() for i in range(len(word)): new_word = word[:i] + '*' + word[i+1:] for nbr in indegree[new_word]: if nbr not in instance: # append a tuple (nbr, level+1) on queue!!!!! queue.append((nbr, level + 1)) instance[nbr] = level + 1 return instance # Template to build a tree with strings # Need to memorize it. def build_graph(self, wordList): from collections import defaultdict indegree = defaultdict(list) for word in wordList: for i in range(len(word)): new_word = word[:i] + '*' + word[i+1:] indegree[new_word].append(word) return indegree
becc6a966f455b1d32d7633c9f7cfb53e110b033
kelvinng2017/chat1
/test2.py
225
3.890625
4
while True: print("請輸入密碼:", end='') password = input() if int(password) == 1234567: print("歡迎光臨!敬請指教") break else: print("密碼錯誤!請在重新輸入")
fcb3cfcc1d4cc6d40a3bf55b42324c8b25d44071
armspkt/Hacktoberfest2021-2
/Python/simple_calculator.py
2,711
4.125
4
####### A Simple Python Calculator ####### ####### Made by: Anish Shilpakar (github: juju2181) ####### """ A Simple Python Calculator that will do addition, subtraction, multiplication, division and modulo operations on two entered numbers. """ #function to add two numbers def addTwoNumbers(x,y): return f"Sum of {x} and {y} is {x + y}" #function to subtract two numbers def subtractTwoNumbers(x,y): return f"When you subtract {y} from {x} you will get {x - y}" #function to multiply two numbers def multiplyTwoNumbers(x, y): return f"Product of {x} and {y} is {x * y}" #function to divide two numbers def divideTwoNumbers(x, y): if(y == 0): print('Error: Cannot divide by zero\nPlease re-enter inputs') return return f"{x} divided by {y} yields {x / y}" #function to perform a modulo operation def moduloTwoNumbers(x, y): if(y == 0): print('Error: Cannot perform modulus operation by zero\nPlease re-enter inputs') return return f"{x} modulus {y} is {x % y}" #main function def main(): isCalculating = True print('--------- Simple Calculator Made in Python ---------') while(isCalculating == True): firstNumber = int(input('Enter first number: ')) secondNumber = int(input('Enter second number: ')) operation = input('Enter operation (+, -, *, /, %): ') if operation == '+': print(addTwoNumbers(firstNumber, secondNumber)) elif operation == '-': print(subtractTwoNumbers(firstNumber, secondNumber)) elif operation == '*': print(multiplyTwoNumbers(firstNumber, secondNumber)) elif operation == '/': print(divideTwoNumbers(firstNumber, secondNumber)) elif operation == '%': print(moduloTwoNumbers(firstNumber, secondNumber)) else: print('Sorry, the operation you are trying to perform is an invalid operation') continueChoice = input('Do you want to continue? (y/n): ') if continueChoice == 'n': isCalculating = False print('Thank you for using this calculator :)') print("--------------------------------------------------------") if __name__ == '__main__': main() print("select operation") print("1.add") print("2.subtract") print("3.multiply") print("4.division") choice=input("enter choice 1/2/3/4/: ") number1=int(input("enter number 1: ")) number2=int(input("enter number 2: ")) if choice == "1": print(number1 + number2) elif choice == "2": print(number1 - number2) elif choice =="3": print(number1 * number2) elif choice == "4": print(number1 / number2) else: print("invalid")
119aea0c6ea10902a592343390116095ca9c6919
darkcode357/rfclist
/rfc-list.py
1,310
3.5
4
from os import system import sys, urllib.request criador = "by darkcode 14/7/2017\nsite:https://www.darkcode0x00.com" versao = "1" def rfclist(): try: numero_rfc = int(sys.argv[1]) except (IndexError, ValueError): print("Deve fornecer um numero de RFC para a busca...") sys.exit(2) site = 'http://www.ietf.org/rfc/rfc{}.txt' url = site.format(numero_rfc) rfc_raw = urllib.request.urlopen(url).read() rfc = rfc_raw.decode() save = str(input("quer salar o arquivo s/n :")) if save == 's': print("salvando.....") print("um momento.....") try: nome_arquivo = str(input("nome do protocolo > ")) arquivo = open(nome_arquivo, 'r+') arquivo.writelines(rfc) system('nano' + ' ' + ' ' + '' +nome_arquivo) dsa = str(input("quer ler outro protocolo s/n :")) if dsa == 's': rfclist() else: print("saida....") print(criador) except FileNotFoundError: arquivo = open(nome_arquivo, 'w+') arquivo.writelines(rfc) system('nano' + ' ' + ' ' + '' + nome_arquivo) else: system("clear") print(rfc) print("saida") print(criador) rfclist()
4a8e8942d9e1ad9beabefb8ca6a3cba6b13f9070
yibei8811/algorithm
/codingInterview/006/solution.py
655
3.640625
4
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def __str__(self, data=None, next=None): return self.data class Solution: @staticmethod def solve(var_node): if var_node.next is None: print(var_node) else: Solution.solve(var_node.next) print(var_node) @staticmethod def solve2(var_node): if var_node is None: return Solution.solve2(var_node.next) print(var_node) node3 = Node('3') node2 = Node('2',node3) node1 = Node('1',node2) Solution.solve(node1) Solution.solve2(node1)
af5c712e4e55878f4034b70735235a60656b4b78
kurazu/pycon_quiz
/solutions/poss1.py
299
3.84375
4
import itertools digits = '2', '4', '6', '8' s = 0 for perm in itertools.permutations(digits): num = int(''.join(perm)) print num s += num print 'SUM', s digits = '1', '2', '3', '4' s = 0 for perm in itertools.permutations(digits): num = int(''.join(perm)) print num s += num print 'SUM', s
eba10d3b1d250b11d0d27c55a23739783b92f44b
idkosilov/RSA_encrypting
/pictogramcoding.py
2,510
3.5
4
def rle_algorithm(string_code): rle_string = '' count = 1 for i in range(1, len(string_code)): if i <= len(string_code): if string_code[i - 1] == string_code[i]: count += 1 else: rle_string += str(count) count = 1 rle_string += str(count) return rle_string def line_by_line(code): return ''.join([''.join(map(str, row)) for row in code]) def line_by_line_reversed(code): sequence = [code[i] if i % 2 == 0 else list(reversed(code[i])) for i in range(len(code))] return ''.join([''.join(map(str, row)) for row in sequence]) def by_stripes_2(code): sequence = [] for i in range(0, len(code), 2): for j in range(len(code[i])): sequence.append(code[i][j]) try: sequence.append(code[i + 1][j]) except IndexError: pass return sequence def by_stripes_4_reversed(code): sequence = [] for i in range(0, len(code), 4): for j in range(len(code[i])): if j % 2 == 0: sequence.append(code[i][j]) sequence.append(code[i + 1][j]) sequence.append(code[i + 2][j]) sequence.append(code[i + 3][j]) else: sequence.append(code[i + 3][j]) sequence.append(code[i + 2][j]) sequence.append(code[i + 1][j]) sequence.append(code[i][j]) return sequence def get_picture_code(picture=None): if picture is None: return [list(map(lambda el: 1 if el == '*' else 0, input())) for _ in range(int(input('Число строк в изображении: ')))] else: return [list(map(lambda el: 1 if el == '*' else 0, row)) for row in picture.split('\n')] def main(): picture = ' ** ** \n' \ ' *** ** \n' \ ' ** *** \n' \ ' *** ** \n' \ ' ** *** \n' \ ' *** ** \n' \ ' ** *** \n' \ ' *** ** \n' print(f"line by line:\n{rle_algorithm(line_by_line(get_picture_code(picture)))}") print(f"line by line with reverse:\n{rle_algorithm(line_by_line_reversed(get_picture_code(picture)))}") print(f"by stripes-2:\n{rle_algorithm(by_stripes_2(get_picture_code(picture)))}") print(f"by stripes-4 with reverse:\n{rle_algorithm(by_stripes_4_reversed(get_picture_code(picture)))}") if __name__ == "__main__": main()
36363799a699f6fd976cbae2541a43c88376a352
alukinykh/python
/lesson2/4.py
566
4.03125
4
# 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. my_str = input('Введите строку из нескольких слов: ') str_list = my_str.split(' ') for key, item in enumerate(str_list): print(f'{key + 1} {item[:10]}')
cc9d8dbd76e1b3d00a9f6fc7fa795bcfe3652263
vmk0102/PIAIC-AIC
/stringmethods.py
551
4.03125
4
#**************ASSIGNMENT 1*************** a = "my name is Wali" b = "PYTHON IS GREAT!" c = "Hello World" num = "6789325" print(a.capitalize()) print(c.lower()) print(b.casefold()) print(a.find("is")) print(a.count("")) print(b.istitle()) print(a.isalnum()) print(a.endswith("li")) print(b.replace("GREAT", "BAD")) print(b.encode()) print(c.join("XYZ")) print(c.swapcase()) print(a.partition("is")) print(b.rpartition("E")) print(c.startswith("Hell")) print(int(num)) print(float(num)) print(len(a)) print(max(a)) print(min(num)) print(sorted(b))