blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5464a614b6b02186a9139bf6aab72f279ea78099
lucioeduardo/cc-ufal
/APC/Listas/04 - Funções/q6.py
609
4.25
4
""" 6. Percebendo que o método anterior de cálculo de notas foi muito severo, o professor decidiu mudar o formato do cálculo. A nova fórmula foi: – Nota = (nota/max)*10 – Faça um programa para calcular as notas dos alunos segundo essa nova regra, utilizando funções """ def maior(lista): res = lista[0] for i in lista: if i > res: res = i return res def calc_nota(nota, nota_max): return 10*(nota/nota_max) notas = [1,4,3,5,7,8,9,8,8,5,2] resultado = [] nota_max = maior(notas) for i in notas: resultado.append(calc_nota(i, nota_max)) print(resultado)
false
a9a1e6045d4a0ba4ff26f662bfc670c4ae007693
alvintangz/pi-python-curriculum
/adventuregame.py
745
4.34375
4
# Simple adventure game for day 3. hero = input("Name your hero. ") print("\n" + hero + " has to save their friend from the shark infested waters.") print("What do they do?") print("A. Throw a bag of salt and pepper in the water?") print("B. Drink up the whole ocean?") print("C. Do nothing.\n") option = input("What do they do? Type in an option. "); if(option == "A"): print("Great! Theyjust seasoned their friend so the sharks will have a " + "delicious lunch!") elif(option == "B"): print("Their body can't handle that? Where does their pee go?") elif(option == "C"): print("Correct. Sharks are actually not that dangerous! " + "Just tell their friend to relax.") else: print("That option is not valid.")
true
8ca0ed2176a8dac59fd50ae330c278b1cf649ac1
jzaunegger/PSU-Courses
/Spring-2021/CSE-597/MarkovChains.py
1,804
4.3125
4
''' This application is about using Markov Chains to generate text using N grams. A markov chain is essentially, a series of states, where each state relates to one another in a logical fashion. In the case of text generation, a noun phrase is always followed by a verb phrase. Lets say we have two states: A and B A -> B with a 25% chance of occuring A -> B with a 25% chance of occuring B -> A with a 25% chance of occuring B -> B with a 25% chance of occuring This idea can be applied in a ton of different ways, from text generation to weather predictions or financial analysis. ''' import os, random # Set parameters input_path = os.path.join(os.getcwd(), 'Corpus', 'Lovecraft', 'Azathoth.txt') ngram_size = 5 markov_count = 1000 n_grams = {} input_text = '' # Read the file with open(input_path, 'r') as txt_file: input_text = txt_file.read() # Determine the N-Grams for i in range(len(input_text)-ngram_size): gram = input_text[i:i+ngram_size] # Check that we have enough characters to get a next char if i == len(input_text) - ngram_size: break else: next_char = input_text[i+ngram_size] # Check if ngram is already in the dictionary if gram in n_grams.keys(): pass else: n_grams[gram] = [] # Append next character n_grams[gram].append(next_char) # Generate new text from the ngram analysis current_gram = input_text[0:ngram_size] result = current_gram for k in range(markov_count): possibilities = n_grams[current_gram] if len(possibilities) == 0: break next_char = random.choice(possibilities) result += next_char current_gram = result[len(result)-ngram_size:len(result)] print(result)
true
28bf44989f72a0a9c14d5a34bb1068437800c72a
mustail/Election_analysis
/practice/python_practice2.py
1,711
4.46875
4
# python practice continued print("Hello world.") print("Arapahoe and Denver are not in the list of counties.") # printing with f string my_votes = int(input("How many votes did you get in the election?")) total_votes = int(input("What is the total number of votes in the election?")) percentage_votes = (my_votes/total_votes) * 100 #print("I received " + str(percentage_votes)+ "% of total votes.") message_to_candidate = ( f"You received {my_votes:,} number of votes. " f"The total number of votes cast was {total_votes:,}. " f"You received {my_votes/total_votes*100:.2f}% of the total votes." ) print(message_to_candidate) print(f"I received {my_votes/total_votes*100}% of the total votes.") print(f"I received {percentage_votes}% of the total election.") counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222} for county, voters in counties_dict.items(): #print(county + " county has " + str(voters) + " registered voters.") print(f"{county} county has {voters:,} number of registered voters.") # skill drill voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438} ] for county_dict in voting_data: print(f"{county_dict['county']} county has {county_dict['registered_voters']:,} number of registered voters.") # very important here: If you use double quotation marks for the f-strings containing the keys, # then be sure to use single quotation marks for the keys and values of the dictionary. # I tried the above (for ex. county, registered_voters) with double quotes, but it did not work.
true
60dc024310defe5fb2ea8d12ecd91965d9151681
mayelespino/code
/LEARN/python/functional-programming-tools/functional-programming.py
538
4.15625
4
#!/usr/bin/python #https://docs.python.org/2/tutorial/datastructures.html #---- filter ---- print "---- filter ----" def isEven(x): return x % 2 == 0 myList = (filter(isEven, range(1,20))) for N in myList: print N #---- map ---- print "---- map ----" seq1 = range(1,10) seq2 = range(101,110) def addThem(x, y): return x+y myList = (map(addThem, seq1, seq2)) for N in myList: print N #---- reduce ---- print "---- reduce ----" def addThem(x, y): return x+y seq = range(1,10) print seq print (reduce(addThem, seq ))
false
08693ca174d12eff737cc6a467d1159652787a31
astralblack/Calculator
/calc.py
1,262
4.5
4
# Astral's Calcultor # Date: 9.27.18 # Menu print("Hello welcome to my calculator!\n") print("1: Addition") print("2: Subtraction") print("3: Multiplication") print("4: Division\n") # Functions def addition(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 + num2 print("The total is : " + str(sum)) def subtraction(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 - num2 print("The total is : " + str(sum)) def multiplication(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 * num2 print("The total is : " + str(sum)) def division(): num1 = int(input ("What is the first number?")) num2 = int(input ("What is the second number?")) sum = num1 / num2 print("The total is : " + str(sum)) # Used for selecting the operation the user wants to use choice = input("What operation would you like?") if choice == "1": addition() elif choice == "2": subtraction() elif choice == "3": multiplication() elif choice == "4": division()
false
6873b522169569c7e04a6e39c065fdab343f6405
Sabdix/Python-Tutorials
/Dictionaries.py
465
4.25
4
# A dictionary is a collection which is unordered, changeable and indexed. thisDict = { "apple": "green", "bannana": "yellow", "cherry": "red" } print(thisDict) #Changing elements thisDict["apple"] = "red" print(thisDict) #Create dictionary with method thisdict = dict(apple="green", bannana="yellow", cherry="red") print(thisdict) #adding items thisdict["damson"] = "purple" print(thisdict) #deleting items del(thisdict["bannana"]) print(thisdict)
true
abbc2b40c22b26f2c2305a5b69b91cb8ccb63b9a
Sabdix/Python-Tutorials
/Json.py
1,302
4.4375
4
# importing JSON import json # If you have a JSON string, you can parse it to convert it in to a dictionary # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"]) #If you have a Python object, you can convert it into a JSON string # a Python object (dict): x = { "name": "John", "age": 30, "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y) #Convert Python objects into JSON strings, and print the values: print(json.dumps({"name": "John", "age": 30})) print(json.dumps(["apple", "bananas"])) print(json.dumps(("apple", "bananas"))) print(json.dumps("hello")) print(json.dumps(42)) print(json.dumps(31.76)) print(json.dumps(True)) print(json.dumps(False)) print(json.dumps(None)) #Another example x = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } print(json.dumps(x)) #Formating the Result print(json.dumps(x, indent=4)) #Change the separator print(json.dumps(x, indent=4, separators=(". ", " = "))) #Order the Result print(json.dumps(x, indent=4, sort_keys=True))
true
5e44a8c1f6fe05525aacd26f0f03e5d37114476c
JuanSch/ejemplo_python
/Ejercicio 7 PRACTICA 2.py
244
4.125
4
cadena = input('Ingrese un string ') cadenaInvertida = cadena[::-1] #invertimos la cadena if (cadena == cadenaInvertida): print('la palabra ingresada es palindrome') else: print('La palabra ingrtesada no es palindrome')
false
bbfa000ad67f734df09ed03e70d85119123cfef0
sangeetjena/datascience-python
/Dtastructure&Algo/algo/water_supply.py
826
4.1875
4
"""Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1. The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through that particular city. Determine the maximum number of cities to which water can be supplied. """ path={1:[2,3],2:[4,6],3:[],4:[5],5:[],6:[7],7:[]} supply=[] block=[2] cnt=0 def line_draw(source): global cnt for v in path[source]: if(v in block): continue else: line_draw(v) if v not in supply: cnt=cnt+1 supply.append(v) return line_draw(1) print(supply) line_draw(1)
true
6e363f232d0f0345d446bcfbf7a7b9a649ec6470
COSJIE/meachine-learning
/04_函数/hm_09_函数嵌套调--打印分隔线.py
426
4.25
4
# 定义一个print_line函数打印 * 组成的一条分隔线 # def print_line(): # print("*" * 50) # print_line() # 定义一个print_line函数打印 任意字符 组成的一条分隔线 # def print_line(char): # print(char * 50) # print_line("-") # 定义一个print_line函数打印 任意字符 任意次数的组成的一条分隔线 def print_line(char,times): print(char * times) print_line("-", 10)
false
00503cb30615d01facc609ef894f0ee570717a96
kajaltingare/Python
/Basics/verbing_op.py
328
4.4375
4
# Write a program to accept a string from user & perform verbing operation. inp_stmt=input("Enter the statement: ") if(len(inp_stmt)>=3): if(inp_stmt.endswith("ing")): print(inp_stmt[:-3]+'ly') else:print(inp_stmt+'ing') else: print('Please enter verb atleast 3 or more number of characters in it.')
true
58b6f4caa8b080662653399a75cff2afc9ff6691
kajaltingare/Python
/Basics/Patterns/pattern6_LL.py
334
4.125
4
# Write a program to print LowerLeft side pattern of stars. def Pattern6(n): for i in range(1,n+1): for _ in range(0,n-i+1): print('*',end='') print() def main(): n = eval(input('Enter the no of rows want to print pattern: ')) Pattern6(n) if __name__ == '__main__': main()
true
c0af2569858fa4b0d2e8d8c2246d7948a8d97841
kajaltingare/Python
/Basics/UsingFunc/fibboSeriesWithUpperLimit.py
433
4.21875
4
# Write a program to print fibonacci series with given upper limit, starting from 1. def fiboSeries(upperLmt): a,b=1,1 print(a,b,end='') #for i in range(1,upperLmt): while((a+b)<=upperLmt): c=a+b print(' %d'%c,end='') a=b b=c def main(): upperLmt = eval(input('Enter upper limit of fibo to print: ')) fiboSeries(upperLmt) if __name__=='__main__': main()
true
9b4de2ccf3539b1f714c3855bff8989f19f433fa
kajaltingare/Python
/Basics/min_of_3.py
260
4.21875
4
# Write a program to accept three numbers from user & find minimum of them. n1,n2,n3=eval(input("Enter the 3 no.s: ")) if(n1<n2 and n1<n3):print("{0} is minimum".format(n1)) elif(n2<n1 and n2<n3):print('%d is minimum.'%n2) else:print('%d is minimum.'%n3)
true
831023701ff1b841124a34e1eebb20f05489cc6a
kajaltingare/Python
/Basics/UsingFunc/isDivisibleByEight.py
481
4.34375
4
# Write a program to accept a no from user & check if it is divisible by 8 without using arithmatic operators. def isDivisibleByEight(num): if(num&7==0): return True else: return False def main(): num = eval(input('Enter the number: ')) result = isDivisibleByEight(num) if(result): print('%d is divisible by 8.'%num) else: print('%d is not divisible by 8.'%num) if __name__ == '__main__': main()
true
a8c06bb0934f021d06a854bba1861b83d31bd4e1
kajaltingare/Python
/Basics/basic_str_indexing.py
676
4.65625
5
#String-Immutable container=>some basics about string. name="kajal tingre" print("you entered name as: ",name) #'kajal tingre' print("Accessing 3rd char in the string(name[2]): ",name[2]) print("2nd including to 5th excluding sub-string(name[2:5]): ",name[2:5]) print("Printing alternate char from 1st position(name[::2]): ",name[::2]) print("Printing string from 2nd char to end(name[2::]): ",name[2::]) print("Print last char of string(name[-1::]): ",name[-1::]) print("Printing in between string(name[1:-5]): ",name[1:-5]) print("When starting index>end index, prints nothing(name[5:2]): ",name[5:2]) print("if we give step value in above as(name[5:2:-1]): ",name[5:2:-1])
true
094559f9145b0d98920ed6960f275c0de68f0d48
Ahed-bahri/Python
/squares.py
250
4.25
4
#print out the squares of the numbers 1-10. numbers=[1,2,3,4,5,6,7,8,9,10] for i in numbers: print("the square of each number is : ", i**2) #mattan strategy for i in range(1,11): print("the square of each number is : ", i**2)
true
da3e46522a54ff4971dda36cb3a0ad19de85e874
donchanee/python_trick
/Chaining_Comparison.py
502
4.25
4
# Chaining comparison operators: >>> x = 5 >>> 1 < x < 10 True >>> 10 < x < 20 False >>> x < 10 < x*10 < 100 True >>> 10 > x <= 9 True >>> 5 == x > 4 True ''' In case you're thinking it's doing 1 < x, which comes out as True, and then comparing True < 10, which is also True, then no, that's really not what happens (see the last example.) It's really translating into 1 < x and x < 10, and x < 10 and 10 < x * 10 and x*10 < 100, but with less typing and each term is only evaluated once. '''
true
ed37d9243eda6d10b8f2cb0e8c3c55791ed99e38
KlimDos/exercism_traning
/python/yacht/yacht.py
2,457
4.1875
4
""" This exercise stub and the test suite contain several enumerated constants. Since Python 2 does not have the enum module, the idiomatic way to write enumerated constants has traditionally been a NAME assigned to an arbitrary, but unique value. An integer is traditionally used because it’s memory efficient. It is a common practice to export both constants and functions that work with those constants (ex. the constants in the os, subprocess and re modules). You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type """ # Score categories. # Change the values as you see fit. YACHT = "YACHT" ONES = "ONES" TWOS = "TWOS" THREES = "THREES" FOURS = "FOURS" FIVES = "FIVES" SIXES = "SIXES" FULL_HOUSE = "FULL_HOUSE" FOUR_OF_A_KIND = "FOUR_OF_A_KIND" LITTLE_STRAIGHT = "LITTLE_STRAIGHT" BIG_STRAIGHT = "BIG_STRAIGHT" CHOICE = "CHOICE" def findSame(dice: list): s = sorted(dice.copy()) count_left = s.count(s[0]) count_right = s.count(s[-1]) return s, count_left, count_right def score(dice, category): result = 0 sorted_dice, r1, r2 = findSame(dice) for i in dice: if category == "ONES": if i == 1: result += 1 elif category == "TWOS": if i == 2: result += 2 elif category == "THREES": if i == 3: result += 3 elif category == "FOURS": if i == 4: result += 4 elif category == "FIVES": if i == 5: result += 5 elif category == "SIXES": if i == 6: result += 6 if category == "FULL_HOUSE": if r1 == 3 and r2 == 2 or r1 == 2 and r2 == 3: result = sum(dice) else: result = 0 elif category == "FOUR_OF_A_KIND": if r1 >= 4: result = 4 * sorted_dice[0] elif r2 >= 4: result = 4 * sorted_dice[-1] else: result = 0 elif category == "LITTLE_STRAIGHT": if sorted_dice == [1, 2, 3, 4, 5]: result = 30 else: result = 0 elif category == "BIG_STRAIGHT": if sorted_dice == [2, 3, 4, 5, 6]: result = 30 else: result = 0 elif category == "CHOICE": result = sum(dice) elif category == "YACHT": if r1 == 5: result = 50 else: result = 0 return result
true
336152ac95245e4b7b59387b1ec96501cecd2940
Shalima2209/Programming-Python
/rectangle.py
882
4.125
4
class rectangle: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return self.length*self.breadth def perimeter(self): return 2*(self.length + self.breadth) a=int(input("length of rectangle1 : ")) b=int(input("breadth of rectangle1 : ")) c=int(input("length of rectangle2 : ")) d=int(input("breadth of rectangle2 : ")) rec1=rectangle(a,b) rec2=rectangle(c,d) print("area of rectangle1 : ",rec1.area()) print("perimeter of rectangle1 : ",rec1.perimeter()) print("area of rectangle2 : ",rec2.area()) print("perimeter of rectangle2 : ",rec2.perimeter()) if rec1.area()==rec2.area(): print("the 2 given rectangle have same area") elif rec1.area() > rec2.area(): print("rectangle1 is greater than rectangle2") else: print("rectangle2 is greater than rectangle1")
false
c2bccd3dc5edb3734482d4540c954292ae6bc85f
shun-lin/Shun-LeetCode-OJ-solutions
/Algorithm/ImplmentingQueueUsingStacks.py
1,718
4.40625
4
class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ # stack is first in last out so in python we can use append to add and # pop front # we want to implement a queue which is first in first out self.stacks = [[], []] self.activeStackIndex = 0 def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ otherStateIndex = 1 - self.activeStackIndex while len(self.stacks[self.activeStackIndex]) > 0: lastElement = self.stacks[self.activeStackIndex].pop() self.stacks[otherStateIndex].append(lastElement) self.stacks[otherStateIndex].append(x) while len(self.stacks[otherStateIndex]) > 0: lastElement = self.stacks[otherStateIndex].pop() self.stacks[self.activeStackIndex].append(lastElement) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ return self.stacks[self.activeStackIndex].pop() def peek(self): """ Get the front element. :rtype: int """ lastElementInex = len(self.stacks[self.activeStackIndex]) - 1 return self.stacks[self.activeStackIndex][lastElementInex] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return len(self.stacks[self.activeStackIndex]) == 0 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
true
09a4bf54f13dee45f673fcb7b8770c88ab7dc584
Vishnu8649/task3
/2/defaultdic.py
316
4.25
4
import collections as c def default(): ''' demonstrating working of default dict ''' d={1:'a', 2:'a', 3:'b', 4:'c',5:'d', 6:'c'} print 'Before reversal', d new=c.defaultdict(list) for k,v in d.items(): new[v].append(k) print 'Reversed dictionary is', dict(new) default()
false
e064c21b78829ef1a99ce2e205c7298cca798afc
gmaher/flask-react-be
/src/crypto/password.py
938
4.3125
4
import bcrypt def hash_password(pw, rounds=10): """ Uses the bcrypt algorithm to generate a salt and hash a password NOTE: ONLY PASSWORDS < 72 CHARACTERS LONG!!!! :param pw: (required) password to hash :param rounds: number of rounds the bcrypt algorithm will run for """ if not type(pw) == str: raise RuntimeError('password {} is not a string!'.format(pw)) if len(pw) >= 72: raise RuntimeError('password {} has length {} > 72!'.format(pw,len(pw))) return bcrypt.hashpw(pw,bcrypt.gensalt(rounds)) def pw_is_valid(pw,hashed_pw): """ compare the entered password to the hashed one and see if they match up :param pw: (required) password entered by user :param hashed_pw: (required) the hashed password we stored in the database """ if not type(pw) == str: return False if len(hashed_pw) != 60: return False return bcrypt.checkpw(pw,hashed_pw)
true
3207b1deeb5506e7d1346291901a759cc2549fca
TianfangLan/LetsGoProgram
/Python/week_notes/week2_QueueADT_v1.py
1,718
4.34375
4
class EmptyQueueException(Exception): pass class Queue(): ''' this class defines a Queueu ADT and raises an exception in case the queue is empty and dequeue() or front() is requested''' def __init__(self): '''(Queue) -> Nonetype creates an empty queue''' # representation invariant #_queue is a list #if _queue is not empty then # _queue[0] referes to the front/head of the queue # _queue[-1] referes to the back/tail of the queue # _queue[:] referes to the elements of the queue in the order of insertion self._queue = [] def enqueue(self, element): ''' (Queue, obj) -> NoneType add element to the back of the queue''' # The element goes to the back of queue self._queue.append(element) def dequeue(self): '''(Queue) -> obj remove and returns the element at the front of the queue raise an exception if _queue is empty''' if self.is_empty(): raise EmptyQueueException ("This queue is empty") #remove and return the item at the front return self._queue.pop(0) def is_empty(self): ''' (Queue) -> bool returns true if _queue is empty''' return (len(self._queue) == 0) def size(self): '''(Queue) -> int returns the number of elements, which are in _queue''' return len(self._queue) def front(self): '''(Queue) -> obj returns the first element, which is in _queue It raises an exception if this queue is empty''' if (self.is_empty()): raise EmptyQueueException("This Queue is Empty") return self._queue[0]
true
f7068520fbd7e15129b46ca5995c0a305ec9e07c
ArthurHGSilva/Atividades-Python
/Exercícios_parte3/exercício8.py
552
4.125
4
num1 = float(input('Coloque o valor do primeiro número: ')) num2 = float(input('Coloque o valor do segundo número: ')) operacao = input('Coloque a operação desejada: ') if operacao == '+': resultado = num1 + num2 print('Adição\t', resultado) elif operacao == '-': resultado1 = num1 - num2 print('Subtração\t', resultado1) elif operacao == '*': resultado2 = num1 * num2 print('Multiplicação\t', resultado2) elif operacao == '/': resultado3 = num1 / num2 print('Divisão\t', resultado3)
false
54492efbf4c23f590bef414dcfc611dc28dde4a0
mrklyndndcst/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022
/Beginner/D004_Randomisation_and_Python_Lists/ProjectD4_Rock_Paper_Scissors.py
1,551
4.15625
4
import random rock = "👊" paper = "✋" scissors = "✌️" choices = [rock, paper, scissors] player = int(input(f"What do you choose? type 1 for {rock}, 2 for {paper} or 3 for {scissors}\n")) print("You choose") if player < 1 or player > 3: print("Invalid") ai = random.randint(1 , 3) print("Artificial Intelligence choose") print(choices[ai - 1]) print("You loose!, please follow simple instructions..") elif player >= 1 or player <= 3: print(choices[player - 1]) ai = random.randint(1 , 3) print("Artificial Intelligence choose") print(choices[ai - 1]) if player == ai: print("Draw!, Try again..") elif player == 1 and ai == 2 or player == 2 and ai == 3 or player == 3 and ai == 1: print("You loose!, Pay your debt..") else: print("You Win!, get your rewards..") # user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n")) # if user_choice >= 3 or user_choice < 0: # print("You typed an invalid number, you lose! ") # else: # print(game_images[user_choice]) # computer_choice = random.randint(0, 2) # print("Computer chose:") # print(game_images[computer_choice]) # if user_choice == 0 and computer_choice == 2: # print("You win!") # elif computer_choice == 0 and user_choice == 2: # print("You lose") # elif computer_choice > user_choice: # print("You lose") # elif user_choice > computer_choice: # print("You win!") # elif computer_choice == user_choice: # print("It's a draw")
true
e999d005eff83eca21ec9e1f4acb28cc96ba4d0b
zhanglulu15/python-learning
/python学习基础及简单实列/basic learing 6.py
246
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 26 10:41:55 2018 @author: lulu """ count = 3 while count <= 5: print("the count less than 5",count) count = count + 1 else: print("the count greater than 5",count)
true
52c689ac08f7020700ec0ede437162eb1c0e7f81
Valuoch/pythonClass
/pythonoperators.py
1,375
4.53125
5
#OPERATORS #special symbols in python to carry out arithmetic and logical computations #They include; #1.arithmetic- simple math operations eg addition, sustraction, multiplication(*), division(/), modulas(%), floor(//),exponent(**)etc #x=10 #y=23 #print(x+y) #print(x-y) #print(x/y) #print(x*y) #print(x%y) #print(x//y) #print(x**y) # x = input("Enter a number:") # print(type(x)) # x = input("Enter a number:"), # y = input("Enter a number:") # sum= int(x) + int(y) # print(sum) # 2.Comparison Operators eg greater than(>),less than(<), ==,|=, # >=, <= # a) greater than > # a=12 # b=13 # a= int(input("Enter a value:")) # b= int(input("Enter a value:")) # print("a > is", a>b) # print("a < is", a<b) # print("a == is", a==b) # print("a ! b is", a!=b) # print("is a >=b is", a>=b) # print("is a <=b is", a<=b) # 3.Logical Operators # eg and, or , not # 1. and- returns true ONLY if both operands are true #2.or- returns true if any of the operands is true #3.not-inverts the true value # m = True # n = False # print("m and n is", m and n) # print("m or n", m or n) # print("not n is", not n) # 4. Assignment Operators - used to assign values to a variable eg =, +=, -= # c = 10 # print(c) # c += 10 # print(c) # (c = c +1 0) # c -= 5 # print(c) # (c = c -5) # c *= 4 # print(c) # (c = c * 4) #5. Membership Operators #6. Identity Operators #7. Bitwise Operators
true
ccb56373dde67a27e4c4bfabd234b6d0a310cf86
alexthomas2020/Banking
/test_Account.py
2,028
4.3125
4
# Banking Application # Author: Alex Thomas # Updated: 11/10/2020 import unittest from Account import get_account, get_accounts, Account """ Banking Application - Unit tests for Account class. Run this program to view results of the tests. """ class TestAccount(unittest.TestCase): def test_get_account(self): # check if the function returns account details. ac_num = 'A1469' ac_dict = get_account(ac_num) self.assertGreater(len(ac_dict), 0) def test_get_accounts(self): # check if the function returns 1 or more account records. accounts = get_accounts() self.assertGreater(len(accounts.shape), 0) def test_add_account_record(self): # check if the function inserts account record into database. ac_num = 'A_TEST1' ac_type = 'C' open_date = '12/12/2020' close_date = "" balance = int(10.00) status = 'A' customer_id = "C_TEST123" account = Account(ac_num, ac_type, open_date, close_date, balance, status) account.add_account_record(customer_id) ac_dict = get_account(ac_num) self.assertGreater(len(ac_dict), 0) def test_deposit(self): # check if the function deposit adds money to the account. ac_num = 'A1469' acc_dict = get_account(ac_num) balance = acc_dict['balance'] account = Account(ac_num, "", "", "", balance, "") deposit_amount = 99.00 new_balance = account.deposit(deposit_amount) self.assertGreater(new_balance, deposit_amount) def test_withdrawal(self): # check if the function withdraws amount from the account. ac_num = 'A1469' acc_dict = get_account(ac_num) balance = acc_dict['balance'] account = Account(ac_num, "", "", "", balance, "") withdraw_amount = 99.00 new_balance = account.withdraw(withdraw_amount) self.assertGreater(new_balance, withdraw_amount) if __name__ == '__main__': unittest.main()
true
6966ec8f669922fa1a78661630eb6732ba5b549a
matthew02/project-euler
/p005.py
820
4.1875
4
#!/usr/bin/env python3 """Project Euler Problem 5: Smallest multiple Find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. https://projecteuler.net/problem=5 Usage: python3 p0005.py [number] """ import sys from math import gcd from typing import List def smallest_multiple(numbers: List[int]) -> int: """Finds the smallest integer multiple of a list of numbers. Calculates the smallest number that is evenly divisible by all numbers in given list, also known as the least common multiple. """ result = 1 for num in numbers: result *= num // gcd(num, result) return result def main(stop: int): """Prints the result.""" print(smallest_multiple(range(1, int(stop) + 1))) if __name__ == '__main__': main(int(sys.argv[1]))
true
5e8d00838e9a82b03de35bf595a3b140bfe5baa1
yaHaart/hometasks
/Module21/03_fibonacci/main.py
275
4.125
4
index_number = 7 # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) print(index_number, '-ый элемент ряда ', fibonacci(index_number)) # зачёт! 🚀
false
3d8813c43d8f57d133fb2f487cd15f65b9a59106
gabrielbessler/ProgrammingCompetition
/AI18/AI18_1.py
1,422
4.65625
5
#!/bin/python3 import sys ''' Problem Statement You have been given an integer which represents the length of one of cathetus of a right-angle triangle. You need to find the lengths of the remaining sides. There may be multiple possible answers; any one will be accepted. ''' def pythagorean_triple(side_length): ''' Given one cathetus of a right-angle triangle, this function computes and returns a 3-tuple containing 3 sides of integer values for the triangle. ''' if side_length % 2 == 1: #a is odd k = (side_length - 1) // 2 b = 2*(k+1)*k c = (k+1)**2 + k**2 return int(side_length), int(b), int(c) else: #a is even num_div = 0 while side_length % 2 != 1: side_length //= 2 num_div += 1 if side_length == 1: # this means a was a power of 2 side_length *= (2 ** num_div) multiple = side_length // 4 return int(side_length), int(3 * multiple), int(5 * multiple) else: k = (side_length - 1) // 2 b = 2*(k+1)*k c = (k+1)**2 + k**2 mul = 2 ** num_div return int(side_length * mul), int(b*mul), int(c*mul) # Integer division is required (floating point math is annoying) a = int(input().strip()) triple = pythagorean_triple(a) print(" ".join(map(str, triple)))
true
85f848d0e6e073ec282e96cb98481eda112c43e4
dstamp1/FF-BoA-2020
/day01/day01c-ForLoops.py
2,787
4.6875
5
### For Loops ### # Computers are really good at repeating the same task over and over again without making any mistakes/typos # Let's imagine we were having a competition to see who could type out "print('hello')" as many times as we could without using copy and paste. # We might type out print('hello') print('hello') print('hello') print('hello') print('hello') print('hello') print('hello') # and quickly get bored or maybe a typo! ## What kind of tasks do you often have to repeat or maybe a company might need to repeat? Let's chatstorm. annticipated responses: marketing emails, order emails, happy birthday emails, etc. ## the most basic way to complete a task multiple times is too use a for loop like so: for i in range(10): print("Hello") ## Let's do a chat waterfall, so type but don't send yet, how many times "Hello" will print on the screen? ## let's examine what that i is doing by modifying our code for i in range(10): print(f"i is currently {i}") print("Hello") ## The letter i is used as this placeholder (this placeholder frustratingly doesn't have a name, but is most commonly called the "iterator", "loop counter", "iteration variable" or "constant of iteration"), but the term i isn't special or reserved, it's just the most common. You might have seen it before in a math class during summations ## since it's a variable, we can call it anything we want so we can referennce it later. ### There are soooo many things you can do with loops. Let's talk about finding sums and you can think about other uses of the superpower. ## Lets say we want to find the sum of the numbers 5,6,7 and 8 ## We could use this code: sum = 0 for i in range(5,9): sum += i print(f"The sum is currently {sum}.") print(f"The loop is over, and the total is {sum}!") # What is the value of sum before the loop starts? # What is the value of sum after the loop has gone one round? # What is the value of sum after the loop has gone two rounds? #### Let's skip over 'looping with a condition' in the teacherhub for time purposes ###### ## I will mention it's something we can do ## Looping over strings ### ## So we've looked at looping over a range(), but we can loop over any 'iterable' like a string. your_word = input("Give me a word and I'll spell it.") print(f"Okay! I'll try to spell {your_word}.") for letter in your_word: print(letter) ## Lab Time: we'll be working on the loopy math lab # git clone https://github.com/upperlinecode/loopy-math-python-iteration.git ## You might want to explore the documentation for the range() function https://www.w3schools.com/python/ref_func_range.asp ## and if you might want to know more about the modulo function to find even numbers https://www.pythoncentral.io/using-python-to-check-for-odd-or-even-numbers/
true
43e6b014cd9e53fd21794668a77fde252063dd5c
anajulianunes/aprendendo-python
/Curso-python-iniciante/Projetos do Curso em Vídeo/aula9/9c - separa digitos de um numero.py
280
4.21875
4
numero = int(input('Insert a number: ')) u = numero // 1 % 10 #pega um número divide por 1 e depois por 10 e pega o resto da divisao d = numero // 10 % 10 c = numero // 100 % 10 m = numero // 1000 % 10 print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u,d, c, m))
false
8c997e49168c94f312993b43f08b26c857579ba6
vijaysharma1996/Python-LIst-Basic-Programmes
/list find the sum of element in list.py
232
4.25
4
# Python program to find sum of elements in list # creating a list list1 = [11, 5, 17, 18, 23] # using sum() function total = sum(list1) # printing total value print("Sum of all elements in given list: ", total)
true
b489616b270128b30f5f06ad34c2e4f613cdf575
imnikkiz/Conditionals-and-Variables
/guessinggame.py
2,344
4.15625
4
import random def check_guess(guess, correct): """ Compare guess to correct answer. Return False once guess is correct. """ if guess == correct: return False elif guess < 1 or guess > 100: print "Your guess is out of the range 1-100, try again." elif guess > correct: print "Your guess is too high, try again." else: print "Your guess is too low, try again." return True def generate_guess(): """ Check raw_input for valid guess format. Return guess and number of guesses as a tuple. """ count = 0 while True: try: guess = float(raw_input("What is your guess? > ")) count += 1 break except ValueError: print "Oops! That wasn't a number! Try again." count +=1 return guess, count # Return a tuple def play_game(player): """ Choose number randomly. Track guess and number of guesses until player guesses the correct number. Return number of guesses. """ print ("%s, I'm thinking of a number between 1 and 100. " "Try to guess my number.") % player number = random.randrange(1,101) total_number_of_tries = 0 guessing = True while guessing: guess, guess_count = generate_guess() # Unpack the returned tuple total_number_of_tries += guess_count guessing = check_guess(guess, number) # False = guess is correct print ("Well done, %s! You found my number " "in %d tries!") % (player, total_number_of_tries) return total_number_of_tries def main(): """ Greet player and track high score. Each round is instigated by play_game, and the round score is assigned to game_score. The highest score is tracked in main. Player may choose to continue playing. """ your_name = raw_input("Welcome to the guessing game! What is your name? > ") high_score = 1000 playing = True while playing: game_score = play_game(your_name) high_score = min(high_score, game_score) print "Your score is: ", game_score print "Best score is: ", high_score answer = raw_input("Would you like to play again? > ") if answer[0].upper() == "N": playing = False if __name__ == "__main__": main()
true
6166a4a86a3a486745dee02399b400820ba446d9
raresrosca/CtCI
/Chapter 1 Arrays and Strings/9_stringRotation.py
847
4.125
4
import unittest def is_rotation(s1, s2): """Return True if s2 is a rotation of s1, False otherwise""" for i, c in enumerate(s2): if c == s1[0]: if s2[i:]+s2[:i] == s1: return True return False def is_rotation_2(s1, s2): """Return True if s2 is a rotation of s1, False otherwise. Uses the 'in' operator.""" if len(s1) == len(s2) != 0 and s2 in s1+s1: return True return False class Test(unittest.TestCase): '''Test Cases''' data = [ ('waterbottle', 'erbottlewat', True), ('foo', 'bar', False), ('foo', 'foofoo', False) ] def test_string_rotation(self): for [s1, s2, expected] in self.data: actual = is_rotation_2(s1, s2) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()
true
55885f48b318943495a44ff4454b5c21ca1f3f45
sirajmuneer123/anand_python_problems
/3_chapter/extcount.py
533
4.125
4
#Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension. import os import sys cwd=os.getcwd() def count(cwd): list1=os.listdir(cwd) newlist=[] frequency ={} for i in list1: if os.path.isfile(i): newlist.append(i.split(".")[1]) for j in newlist: frequency[j]=frequency.get(j,0)+1 for key,value in frequency.items(): print key ,value count(cwd)
true
a360a18d93371e46214a28eb71275171a5a3a93c
sirajmuneer123/anand_python_problems
/3_chapter/regular_ex.py
409
4.21875
4
''' Problem 9: Write a regular expression to validate a phone number. ''' import re def reg_exp(str1): match=re.search(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1) if match: print 'found' s= re.findall(r'phone:\d\d\d\d\d\d\d|mobile:\d\d\d\d\d\d\d\d\d\d',str1) for i in s: print i else: print 'not found' reg_exp("mobile:3949499456 kjnbb nuphone:2 b[njk k[[nnkjuuphone:1234567")
false
9fdf38d1a2c8bf2460625ff16b4ebc6692936cfc
sirajmuneer123/anand_python_problems
/2_chapter/factorial.py
412
4.1875
4
#Problem 5: Write a function factorial to compute factorial of a number. Can you use the product function defined in the previous example to compute factorial? array=[] def factorial(number): while number!=0: array.append(number) number=number-1 return array def product(num): mul=1 a=len(num) while a!=0: mul=mul*num[a-1] a=a-1 return mul s=product(factorial(4)) print "factorial is =%s" % s
true
38171858be0fc89461f6e38bb85d7585c18525c1
LTTTDH/dataScienceHelpers
/NaNer.py
477
4.125
4
# This function was created to deal with numerical columns that contain some unexpected string values. # NaNer converts all string values into np.nans def NaNer(x): """Takes a value and converts it into a float. If ValueError: returns np.nan Originally designed to use with pandas DataFrames. Example: your_df['YourColumn'].transform(NaNer) """ try: x = float(x) except ValueError: x = np.nan return x
true
051c485cf68844613d64f75d57de227f614be24e
SetOffAtDawn/python
/day1/var.py
571
4.3125
4
"""" 变量 目的:用来存储数据 定义变量: name = "huchao" 变量定义的规则: 字母、数字、下划线 第一个字符不能是数字 关键字不能作为变量名 不合适的变量名: a1 a 不知道变量代表的意思 姓名 = 'huchao' xingming = "huchao" 推荐写法: girl_of_friend = "huchao" """"" print("hello world") name = "huchao" print("my name is ",name) name = "huchao" name2 = name print("my name is ",name,name2) name = "huchao" name2 = name print("my name is ",name,name2) name = "alex" print(name,name2)
false
ee9d018f5a7fd7e23e66f972c0ab3aa8f8d19e27
PingryPython-2017/black_team_palindrome
/palindrome.py
823
4.28125
4
def is_palindrome(word): ''' Takes in an str, checks to see if palindrome, returns bool ''' # Makes sure that the word/phrase is only lowercase word = word.lower() # Terminating cases are if there is no characters or one character in the word if len(word) == 0: return True if len(word) == 1: return True # Checks if the first character in the word is different than the last character is the world. If not, then that means the word is not a palindrome. if word[0] != word[len(word) - 1]: return False # This means that the first character is equal to the last character. else: # Slices the word so that the first character and the last character is cut off. word2 = word[1:-1] # Recurses with this new word. if is_palindrome(word2) == True: return True else: return False
true
be832202e22425289126c594a6c5649cff49d533
dan76296/stopwatch
/stopwatch.py
1,495
4.25
4
import time class StopWatch: def __init__(self): ''' Initialises a StopWatch object''' self.start_time = None self.end_time = None def __repr__(self): '''Represents the object in a readable format''' return 'Time Elapsed: %r' % ':'.join((self.convertSeconds(self.result))) def start(self): ''' Start the StopWatch ''' self.start_time = time.time() def stop(self): ''' Stop the StopWatch''' self.end_time = time.time() pass def split(self): '''Starts a split timer''' self.split_start_time = time.time() pass def unsplit(self): '''Stops the split timer, returns time elapsed since split''' self.result = time.time() - self.split_start_time return self.__repr__() def time_elapsed(self): '''Time elapsed since last start''' self.result = time.time() - self.start_time return self.__repr__() def total_runtime(self): '''Time elapsed between Start and Stop''' self.result = self.end_time - self.start_time return self.__repr__() def convertSeconds(self, seconds): '''Converts seconds into hours and minutes''' h = int(seconds//(60*60)) m = int((seconds-h*60*60)//60) s = round(seconds-(h*60*60)-(m*60), 2) h = str(h) + 'h' m = str(m) + 'm' s = str(s) + 's' return h.strip('.'), m.strip('.'), s
true
aa08a6475f125520389646b0551301a54dafcf89
GitFiras/CodingNomads-Python
/03_more_datatypes/3_tuples/03_16_pairing_tuples.py
992
4.4375
4
''' Write a script that takes in a list of numbers and: - sorts the numbers - stores the numbers in tuples of two in a list - prints each tuple Notes: If the user enters an odd numbered list, add the last item to a tuple with the number 0. ''' # sort numbers numbers_ = [ 1, 5, 4, 67, 88, 99, 3, 2, 12] numbers_.sort() print(numbers_) # check for odd numbers use % to check: 0 = even, 1 is odd x = len(numbers_) if x % 2 == 1: numbers_.append(0) # add '0' to the list, because list is odd # sort numbers in tuples of two in a list list_numbers = [] # print(numbers_[::2]) steps of 2, starting at the start of the list for i in range(0,len(numbers_),2): # range start at start of list, till end of list, by steps of 2 j = tuple(numbers_[i:i+2]) # turn the 2 numbers into tuples list_numbers.append(j) # append new numbers to new list print(list_numbers)
true
be616a73c1e05410a1461277824f37d45e8a3d24
GitFiras/CodingNomads-Python
/13_aggregate_functions/13_03_my_enumerate.py
693
4.3125
4
''' Reproduce the functionality of python's .enumerate() Define a function my_enumerate() that takes an iterable as input and yields the element and its index ''' def my_enumerate(): index = 0 value_list = ['apple', 'banana', 'pineapple', 'orange', 'grape'] # list for value in value_list: # loop for values in list index += 1 # increase index by 1 with each value yield index -1, value # yield output: index, value print(list(my_enumerate())) # call function and print in list
true
64c9d551092b05a7d1fc1b4919403731cb2aa07d
GitFiras/CodingNomads-Python
/04_conditionals_loops/04_01_divisible.py
473
4.40625
4
''' Write a program that takes a number between 1 and 1,000,000,000 from the user and determines whether it is divisible by 3 using an if statement. Print the result. ''' num = int(input('Please provide a number between 1 and 1,000,000,000: ')) if num % 3 == 0: # if output is 0, the number can be divided by 3 without residual value. print(int(num/3)) else: print("Your number cannot be divided by 3, please insert another number")
true
48550e1cb00bf023ec1394a0d0c8116fa0c8c456
GitFiras/CodingNomads-Python
/06_functions/06_01_tasks.py
2,146
4.25
4
''' Write a script that completes the following tasks. ''' # define a function that determines whether the number is divisible by 4 or 7 and returns a boolean print("Assignment 1 - Method 1:") def div_by_4_or_7(x): if x % 4 == 0: print(f"{x} is divisible by 4: ",True) # boolean True if function returns True return True elif x % 7 == 0: print(f"{x} is divisible by 7: ",True) # boolean True if function returns True return True else: print(f"{x} is divisible by 4 or 7: ",False) # boolean False if function returns False return False var = div_by_4_or_7(7) # calling the function with variable input = 7 print(var) # define a function that determines whether a number is divisible by both 4 and 7 and returns a boolean print("Assignment 2") def div_by_4_and_7(z): if z % 4 == 0 and z % 7 == 0: print(f'{z} is divisible by 4 and 7: {True}') return True else: print(f"{z} is not divisible by 4 and 7: ",False) return False var2 = div_by_4_and_7(28) # calling the function with variable input = 28 print("divisible by 4 and 7: ",var2) # take in a number from the user between 1 and 1,000,000,000 # call your functions, passing in the user input as the arguments, and set their output equal to new variables num = 0 # while num != 100: # optional while loop num = int(input("Please insert a number between 1 and 1,000,000,000: ")) # user input INT div_by_4_or_7(num) # calling function with input = num div_by_4_and_7(num) # calling function with input = num # print your new variables to display the results xx = div_by_4_or_7(num) # new variable based on function yy = div_by_4_and_7(num) # new variable based on function print("div_by_4_or_7",xx) print("div_by_4_and_7",yy)
true
3ad789eadbc061a3dafa8af235e28282e659ad63
GitFiras/CodingNomads-Python
/09_exceptions/09_05_check_for_ints.py
669
4.625
5
''' Create a script that asks a user to input an integer, checks for the validity of the input type, and displays a message depending on whether the input was an integer or not. The script should keep prompting the user until they enter an integer. ''' while True: try: user_input = input("Please provide a number value: ") int_input = (int(user_input)) if user_input == int: print(f'Your input {user_input} was correct.') break # break if correct except ValueError as val_err: print(f'Your input {user_input} was not a number value. Please try again.')
true
c43746c218b0df727e187614f7859b0146575356
GitFiras/CodingNomads-Python
/03_more_datatypes/4_dictionaries/03_20_dict_tuples.py
506
4.3125
4
''' Write a script that sorts a dictionary into a list of tuples based on values. For example: input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [("item3", 1), ("item1", 5), ("item2", 6)] ''' input_dict = {"item1": 5, "item2": 6, "item3": 1} list_ = [] # Iteration from dict to list with tuples for i in input_dict: j = (i, input_dict[i]) list_.append(j) print(list_) print(sorted(list_, key = lambda sorted_number : sorted_number[1])) # sort by the number of index 1 [1].
true
20acb5c9c5b63cfb04b70a82a815027e856fb517
GitFiras/CodingNomads-Python
/Inheritance - Course Example Code.py
1,361
4.46875
4
class Ingredient: """Models an Ingredient.""" def __init__(self, name, amount): self.name = name self.amount = amount def expire(self): """Expires the ingredient item.""" print(f"whoops, these {self.name} went bad...") self.name = "expired " + self.name def __str__(self): return f"You have {self.amount} {self.name}." # we can define new classes that take over all their superclasses' variables and methods: class Spice(Ingredient): # means it inherits from the Ingredient class # test of Class # p = Ingredient('peas', 12) # print(p) # s = Spice('salt', 200) # print(s) # no need to define __str__() again - it works! # let's give Spice a method that its superclass doesn't have! def grind(self): print(f"You have now {self.amount} of ground {self.name}.") c = Ingredient('carrots', 3) p = Spice('pepper', 20) print(c, p) p.grind() # c.grind() # produces an error class Spice(Ingredient): # we override this inherited method def expire(self): if self.name == 'salt': print(f"{self.name} never expires! ask the sea!") else: print(f"eh... sorry but that {self.name} actually got bad!") self.name = "expired " + self.name c = Ingredient('carrots', 3) p = Spice('pepper', 20) s = Spice('salt', 200) print(c, p, s) p.expire() print(p) # try calling expire() with the c and s objects!
true
f39fadba2f9d57dd9c9f59c827619f891d579fa4
SnehaMercyS/python-30-days-internship-tasks
/Day 7 task.py
1,734
4.125
4
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #1) create a python module with list and import the module in anoother .py file and change the value in list >>> list=[1,2,3,4,5,6] >>> import mymodule >>> mymodule.list.append(7) >>> print(mymodule.list) [1, 2, 3, 4, 5, 6, 7] >>> #2) install pandas package (try to import the package in a python file >>> import pandas as pd >>> import numpy as np >>> import sys >>> sys._stdout_=sys.stdout >>> fruit = np.array(['apple','orange','mango','pear']) >>> series = pd.Series(fruits) >>> print(series) 0 apple 1 orange 2 mango 3 pear dtype: object >>> #3) import a module that picks random number and write a program to fetch a random number from 1 to 100 on every run >>> import random >>> print("random integer is :",random.randint(1,100)) random integer is : 93 >>> #4) import sys package and find the python path >>> import sys >>> sys.path ['C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pandas', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\idlelib', 'C:\\Users\\ELCOT\\Downloads\\python-3.9.0-amd64.exe', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\ELCOT\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] >>> #5)try to install a package and uninstall a package using pip >>>
true
81af9ef448d9228b34e6c8017b034ccd6405d9ea
clopez5313/Python
/1. Become a Python Developer/4. Programming Foundations - Data Structures/Arrays/2dArrays.py
1,025
4.125
4
import os # Create a 2D array and print some of their elements. studentGrades = [[72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60]] print(studentGrades[1]) print(studentGrades[0]) print(studentGrades[2]) print(studentGrades[3][4]) # Traverse the array. for student in studentGrades: for grade in student: print(grade, end=" ") print() # Insert an element into the 2D array. os.system("cls") studentGrades.insert(1, [84, 93, 72, 60, 75]) for student in studentGrades: for grade in student: print(grade, end=" ") print() # Update elements of the array. studentGrades[0] = [77, 90, 92, 95, 74] studentGrades[1][2] = 77 os.system("cls") for student in studentGrades: for grade in student: print(grade, end=" ") print() # Delete elements of the array. del(studentGrades[0][2]) del(studentGrades[1]) os.system("cls") for student in studentGrades: for grade in student: print(grade, end=" ") print()
true
ba5b7564b61ea7d0bacdfcb2ac19024a39f163ae
clopez5313/Python
/1. Become a Python Developer/4. Programming Foundations - Data Structures/Stacks and Queues/sortingQueues.py
730
4.15625
4
import queue # Create the object and add some elements to it. myQueue = queue.Queue() myQueue.put(14) myQueue.put(27) myQueue.put(11) myQueue.put(4) myQueue.put(1) # Sort with Bubble Sort algorithm. size = myQueue.qsize() for i in range(size): # Remove the element. item = myQueue.get() #Remove the next element. for j in range(size-1): nextItem = myQueue.get() # Check which item is greater and put the smaller one at the beginning of the Queue. if item > nextItem: myQueue.put(nextItem) else: myQueue.put(item) item = nextItem myQueue.put(item) while(myQueue.empty() == False): print(myQueue.queue[0], end=" ") myQueue.get()
true
ec94e882ff4f039bad9c0785c6d615c445cb706b
shyboynccu/checkio
/old_library/prime_palindrome.py
1,877
4.28125
4
#!/usr/local/bin/python3 # An integer is said to be a palindrome if it is equal to its reverse in a string form. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N. You must find the smallest integer M >= N such that M is a prime number and M is a palindrome. # Input: An integer. # Output: A prime palindrome. An integer. from math import sqrt, floor def is_prime(number): for n in range(2, floor(sqrt(number)) + 1): if number % n == 0: return False return True def find_smallest_prime_palindrome(lower_bound, palindrome_list): for m in palindrome_list: if m >= lower_bound and is_prime(m): return m return None def checkio(data): palindrome = [[], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99]] digit = 1 while True: if digit < 3: m = find_smallest_prime_palindrome(data, palindrome[digit]) if m: return m else: mid_palindrome_list = palindrome[digit-2] this_palindrome_list = [] for n in range(1, 10): if mid_palindrome_list: temp_list = [n*10**(digit-1) + x*10 + n for x in mid_palindrome_list] if data < pow(10, digit): m = find_smallest_prime_palindrome(data, temp_list) if m: return m this_palindrome_list += temp_list palindrome.append(this_palindrome_list) digit += 1 #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio(31) == 101, 'First example' assert checkio(130) == 131, 'Second example' assert checkio(131) == 131, 'Third example'
true
48798e1b51baefc7c23b92cf86b34eef35313cee
emilnorman/euler
/problem007.py
493
4.15625
4
# !/usr/bin/python # -*- coding: utf-8 -*- # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, # we can see that the 6th prime is 13. # # What is the 10 001st prime number? def next_prime(p): temp = p + 2 for i in xrange(3, temp, 2): if ((temp % i) == 0): return next_prime(temp) return temp n = 2 prime = 3 while(n < 10001): prime = next_prime(prime) n += 1 print(n, prime) print("n:"), print(n) print("prime:"), print(prime)
true
05bd5cba24b50221d83ae84bee8958dff9b2c7ae
rsoemardja/Python
/PythonAndPygameArcade/Chapter 3 Quiz Games and If Statements/3.2/PythonOrder/PythonOrder/test.py
996
4.3125
4
# we are going to be taking a look at logic with if Statements # Their is actually a hidden error # The error is that computer looks at each statement # and is 120 > 90. It is indeed and the else would execute but the else DID not excute hence the logic error temperature=input("What is the temperature in Fahrenheit? ") temperature=int(temperature) if temperature > 90: print("It is hot outside.") elif temperature > 110: print ["Oh man, you could fry egg on the pavement"] elif temperature < 30: print ("It is cold outside.") else: print("It is not hot outside") print ("Done") # This is now correct and now the statement should be okay temperature=input("What is the temperature in Fahrenheit? ") temperature=int(temperature) if temperature > 110: print("It is hot outside.") elif temperature > 90: print ["Oh man, you could fry egg on the pavement"] elif temperature < 30: print ("It is cold outside.") else: print("It is not hot outside") print ("Done")
true
313c45fa97a1c12eee440966216c3904f549cd07
KDRGibby/learning
/nthprime.py
781
4.46875
4
def optimusPrime(): my_list = [1,2] my_primes = [] prime_count = 0 # this is supposed to add numbers to my_list until the prime count reaches x numbers. while prime_count < 10: last_num = my_list[-1] my_list.append(last_num + 1) #here we check to see if a number in my_list is a prime for i in my_list: #divisibles counts how many numbers can be evenly divided into x. Primes are only divisible by 2 numbers, itself and 1. divisibles = 0 if last_num % i == 0: divisibles += 1 if divisibles < 3: #at this point we should have found a prime and thus we are adding to the prime count and appending the number to my_primes list. prime_count = prime_count + 1 my_primes.append(last_num) print my_list print my_primes optimusPrime()
true
6c0fcf97e0aa94637e2582269a0984bb41003c52
LeiZhang0724/leetcode_practice
/python/practice/easy/reverse_int.py
2,743
4.15625
4
# Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside # the signed 32-bit integer range [-231, 231 - 1], then return 0. # Assume the environment does not allow you to store 64-bit integers (signed or unsigned). def reverse(x: int) -> int: INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1 rev = 0 while x != 0: # INT_MIN 也是一个负数,不能写成 rev < INT_MIN // 10 if rev < INT_MIN // 10 + 1 or rev > INT_MAX // 10: return 0 digit = x % 10 # Python3 的取模运算在 x 为负数时也会返回 [0, 9) 以内的结果,因此这里需要进行特殊判断 if x < 0 and digit > 0: digit -= 10 # 同理,Python3 的整数除法在 x 为负数时会向下(更小的负数)取整,因此不能写成 x //= 10 x = (x - digit) // 10 rev = rev * 10 + digit return rev # Slice notation "[a:b:c]" means "count in increments of c starting at a inclusive, up to b exclusive". If c is # negative you count backwards, if omitted it is 1. If a is omitted then you start as far as possible in the # direction you're counting from (so that's the start if c is positive and the end if negative). If b is omitted then # you end as far as possible in the direction you're counting to (so that's the end if c is positive and the start if # negative). If a or b is negative it's an offset from the end (-1 being the last character) instead of the start. # # OK, so string[0::-1] is one character, it says "count backwards from index 0 as far as you can". As far as it can # is the start of the string. # # string[0:len(string):-1] or for that matter string[0:anything:-1] is subtly different. It's empty for the same # reason that string[1:0] is empty. The designated end of the slice cannot be reached from the start. You can think # of this as the slice having ended "before" it began (hence is empty), or you can think of the end point being # automatically adjusted to be equal to the start point (hence the slice is empty). # # string[:len(string):-1] means "count backwards from the end up to but not including index len(string)". That index # can't be reached, so the slice is empty. # # You didn't try string[:0:-1], but that means "count backwards from the end up to but not including index 0". So # that's all except the first character, reversed. [:0:-1] is to [::-1] as [0:len(string)-1] is to [:]. In both cases # the excluded end of the slice is the index that would have been the included last character of the slice with the # end omitted. # # You also didn't try string[-1::-1], which is the same as string[::-1] because -1 means the last character of the # string.
false
e170befde825656d17d5b17b81cd51d3c0f09c55
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.36.py
294
4.125
4
#-*-coding: utf-8 -*- """ Write a Python program that inputs a list of words, separated by whitespace, and outputs how many times each word appears in the list. You need not worry about efficiency at this point, however, as this topic is something that will be addressed later in this book """
true
fbef3fb244b0ecb1c97a293c1f9e029fe3273f6f
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 2/R/R-2.4.py
426
4.3125
4
#-*-coding: utf-8 -*- """ Write a Python class, Flower, that has three instance variables of type str, int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method that initializes each variable to an appropriate value, and your class should include methods for setting the value of each type, and retrieving the value of each type. """
true
3d1efee5bd503d5503ecafc36e40b60ef833fb7c
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/R/R-1.1.py
590
4.40625
4
#-*-coding: utf-8 -*- """ Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise """ def is_multiple(n, m): n = int(n) m = int(m) if n % m == 0 and n != 0: return True else: return False if __name__ == '__main__': e = is_multiple(4, 2) print e # e1 = is_multiple(4, 4) # print e1 # e2 = is_multiple(0, 4) # print e2 # e3 = is_multiple(4, 0) # print e3 # e4 = is_multiple(4, 5) # print e4
true
092eca02e6e2d164b20444d05b2c328e0b548cb6
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.32.py
395
4.21875
4
#-*-coding: utf-8 -*- """ Write a Python program that can simulate a simple calculator, using the console as the exclusive input and output device. That is, each input to the calculator, be it a number, like 12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input, you should output to the Python console what would be displayed on your calculator. """
true
2124b62809bc75f650e3ed62908a4fb2aaf74ac9
avanti-bhandarkar/ML
/2.py
1,812
4.125
4
#1 - linear regression with sklearn import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt #predictor variable x = np.array([5, 15 , 25 , 35 , 45 ,55]) xm = x x = x.reshape((-1,1)) x.shape #response variable y = np.array([4,7,23,5,39,23]) ym = y #y = y.reshape((-1,1)) y.shape plt.scatter(x,y) model = LinearRegression() model.fit(x,y) r_sq = model.score(x,y) print('The coefficient of determination is : ', r_sq) # the model has the formula of b0 + b1 x print('Intercept :',model.intercept_) #b0 is the intercept print('Slope :',model.coef_) #b1 is the slope x_predict = x y_predict = model.predict(x_predict) print('Predicted response : ', y_predict) print('Actual value of y : ',y) plt.scatter(x,y) plt.plot(x_predict,y_predict,'y') plt.xlabel('Independent variable, x') plt.ylabel('Dependent variable, y') plt.title('Simple Linear Regression plot') ymean = np.average(y) ybar = np.array([ymean,ymean,ymean,ymean,ymean,ymean]) plt.plot(x,ybar,'c') plt.show() #2 - linear regression without sklearn xmean = np.average(xm) ymean = np.average(ym) xymean = np.average(np.multiply(xm,ym)) xmeansq = xmean*xmean xsqbar = np.average(np.multiply(xm,xm)) b1 = ((xmean*ymean) - xymean)/(xmeansq-xsqbar) b0 = ymean - (b1*xmean) print('intercept ',b0) print('slope ',b1) y_pred = b0 + b1*xm print('predicted values for y ',y_pred) ssr = np.sum(np.square(y_pred - ymean)) print('SSR ', ssr) sse = np.sum(np.square(ym - y_pred)) print('SSE ', sse) ssto = np.sum(np.square(ym - ymean)) print('SSTO ', ssto) rs = ssr/ssto print('R squared ',rs) x = 2*np.random.rand(100,1) y = 4+3*x+(2*np.random.rand(100,1)) plt.scatter(x,y) x = 2*np.random.rand(100,1) y = 4-3*x+(2*np.random.rand(100,1)) # << adding some noise or distribution to the line plt.scatter(x,y)
false
d22cd7865db4233da780c7346c2df1a21d7ef71c
jeasonliang/Learning-notes
/Python/3-8-9-10address.py
2,702
4.28125
4
#想出至少 5 个你渴望去旅游的地方。将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。 world_address = ['LosAngeles','Beijing','Xiamen','Amsterdam','Caribbean Sea'] print('按照原始排列顺序打印该列表:\n\t',world_address)#按原始排列顺序打印该列表。 print('按照临时排列字母的顺序打印该列表:\n\t',sorted(world_address))#使用 sorted()按字母顺序打印这个列表,同时不要修改它。临时排序 print('按照原始排列顺序打印该列表:\n\t',world_address)#再次打印该列表,核实排列顺序未变。 print('按照临时排列字母相反顺序打印该列表:\n\t',sorted(world_address,reverse=True))#使用 sorted()按与字母顺序相反的顺序打印这个列表,同时不要修改它。 print('按照原始排列顺序打印该列表:\n\t',world_address)#再次打印该列表,核实排列顺序未变。 world_address.reverse()#使用.reverse()修改列表元素的排列顺序。 print('修改后的列表:\n\t',world_address)#打印该列表,核实排列顺序确实变了。 world_address.reverse()#使用 reverse()再次修改列表元素的排列顺序。 print('修改回来的列表:\n\t',world_address)#打印该列表,核实排列顺序确实恢复了。 world_address.sort()#使用 reverse()再次修改列表元素的排列顺序。 print('按字母排序打印列表:\n\t',world_address)#打印该列表,核实排列顺序确实变了。 #在完成练习 3-4~练习 3-7 时编写的程序之一中,使用 len()打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。 vip_name = ['jeason','angle','lance','chaer'] print('\n\t欢迎VIP:',vip_name[0],vip_name[1],vip_name[2],vip_name[3],'\n\t') can_not_attend = 'chaer' vip_name.remove(can_not_attend) print('因为VIP'+can_not_attend+'无法来!所以我们邀请另外一位嘉宾!') vip_name.insert(3,'winter') print('欢迎VIP:','\n\t',vip_name[0],'\n\t',vip_name[1],'\n\t',vip_name[2],'\n\t',vip_name[3]) print('我们刚找到了个更大的桌子,所以更多的VIP将加入') vip_name.insert(0,'ben')#使用 insert()将一位新嘉宾添加到名单开头。 vip_name.insert(2,'dior')#使用 insert()将另一位新嘉宾添加到名单中间。 vip_name.append('sliaer')#使用 append()将最后一位新嘉宾添加到名单末尾。 #print(vip_name) #向所邀请的人发出欢迎 print('欢迎VIP:','\n\t',vip_name[0],'\n\t',vip_name[1],'\n\t',vip_name[2],'\n\t',vip_name[3],'\n\t',vip_name[4],'\n\t',vip_name[5],'\n\t',vip_name[6]) print('VIP总人数:',len(vip_name))#使用 len()打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。
false
88f2f7683025b2fcbcc0006b279bce698743d10b
himanshu2801/leetcode_codes
/sort colors.py
912
4.15625
4
""" Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Follow up: Could you solve this problem without using the library's sort function? Could you come up with a one-pass algorithm using only O(1) constant space? """ class Solution: def sortColors(self, nums: List[int]) -> None: p0 = 0 p2 = len(nums)-1 p1 = 0 while p1<=p2: if nums[p1] == 2: nums[p2],nums[p1] = nums[p1],nums[p2] p2 -= 1 elif nums[p1] == 0: nums[p0],nums[p1] = nums[p1],nums[p0] p0 += 1 p1 += 1 else: p1 += 1 return nums
true
96ffd6f2d96e810840f4e8aab3bd3d5968f600ba
bitomann/classes
/pizza_joint.py
1,322
4.625
5
# 1. Create a Pizza type for representing pizzas in Python. Think about some basic # properties that would define a pizza's values; things like size, crust type, and # toppings would help. Define those in the __init__ method so each instance can # have its own specific values for those properties. class Pizza: def __init__(self): self.size = "" self.crust_type = "" self.toppings = [] # 2. Add a method for interacting with a pizza's toppings, called add_topping. def add_topping(self, topping): self.toppings.append(topping) # 3. Add a method for outputting a description of the pizza (sample output below). def print_order(self): print(f"The pizza is {self.size} inches with a {self.crust_type} crust with " + " and ".join(self.toppings) + ".") # 4. Make two different instances of a pizza. If you have properly defined the class, # you should be able to do something like the following code with your Pizza type. meat_lovers = Pizza() meat_lovers.size = 16 meat_lovers.crust_type = "deep dish" meat_lovers.add_topping("Pepperoni") meat_lovers.add_topping("Olives") meat_lovers.print_order() # You should produce output in the terminal similar to the following string: # "I would like a 16-inch, deep-dish pizza with Pepperoni and Olives."
true
c05f369e874662f1f383cd25148e99c980f37d49
Vohsty/password-locker
/user.py
1,472
4.21875
4
class User: """ Class to generate new instances of users """ user_list= [] # Empty user list def __init__(self, f_name, l_name, username, password): ''' To take user input to create a new user ''' self.f_name = f_name self.l_name = l_name self.username = username self.password = password def save_user(self): ''' save_user method saves user objects into user_list ''' User.user_list.append(self) def delete_user(self): ''' delete_user method deletes a saved user from the user_list ''' User.user_list.remove(self) @classmethod def find_by_username(cls, username): ''' Method that takes in a username and returns a user that matches that username. Args: username: username to search for Returns : User of person that matches the username. ''' for user in cls.user_list: if user.username == username: return user @classmethod def user_exist(cls, username): ''' Method that checks if a user exists from the user array. Args: username: username to search if it exists Returns : Boolean: True or false depending if the user exists ''' for user in cls.user_list: if user.username == username: return True
true
72d89fa9093ed5d9629c86480309380b87d871a2
DiegoDeJotaWeb/uninove
/5 - LÓGICA DE PROGRAMAÇÃO/aula_05-06-2020/exer8.py
394
4.125
4
'''Para doar sangue é necessário ter entre 18 e 67 anos. Faça um programa que pergunte a idade de uma pessoa e diga se ela pode doar sangue ou não.''' idade=int(input("Digite sua idade")) if(idade >= 18 and idade <=67): print("Sua idade é {}. Você pode doar sangue!".format(idade)) else: print("Sua idade é {}. Você não pode doar sangue!".format(idade))
false
3f6e66a5e45651ee7fe6dd0454f771b6343edc29
davidjbrossard/python
/hello.py
669
4.3125
4
import math as m """ This method takes in a string and returns another string. It encrypts the content of the string by using the Caesar cipher. """ def encrypt(message, offset): encryptedString = ""; for a in message: encryptedString+=chr(ord(a)+offset); return encryptedString; """ This method takes in a string and returns another string. It decrypts the content of the string by using the inverse of the Caesar cipher """ def decrypt(message,offset): decryptedString = ""; for a in message: decryptedString+=chr(ord(a)-offset); return decryptedString; print(encrypt("Zebulon", 1)); print(decrypt(encrypt("Zebulon", 1),1));
true
9473f6456519749d1b687bc83cf290e9d31316cf
KoushikRaghav/commandLineArguments
/stringop.py
1,399
4.125
4
import argparse def fileData(fileName,stringListReplace): with open(fileName,'w') as f: f.write(str(stringListReplace)) print stringListReplace def replaceString(replace,stringList,fileName,word): rep = replace.upper() stringListReplace = ' ' for w in stringList: stringListReplace = w.replace(word, rep) fileData(fileName,stringListReplace) def findString(word, stringList): for s in stringList: if word in s: print ('{} is found\n'.format(word.upper())) #print stringList else: print 'String is not found\n' exit() def fileOpen(fileName): with open(fileName,'r') as f: stringList = f.read().split(',') return stringList def argParser(): parser = argparse.ArgumentParser(description = 'String Operation') parser.add_argument('filename', help = 'name of the file') parser.add_argument('s',help = 'word for searching strings in the file') parser.add_argument('-r', help = 'word for replacing strings in the file') args = parser.parse_args() return args def main(): args = argParser() fileName = args.filename word = args.s replace = args.r if args.s is not None: stringList = fileOpen(fileName) findString(word, stringList) else: exit() #print args.word if replace is None: print stringList exit() else: replaceString(replace,stringList,fileName,word) if __name__ == '__main__': main()
true
5ce58dda0c9928a43e3463e7447ce63f404c5e51
brickfaced/data-structures-and-algorithms
/challenges/multi-bracket-validation/multi_bracket_validation.py
2,197
4.34375
4
class Node: """ Create a Node to be inserted into our linked list """ def __init__(self, val, next=None): """ Initializes our node """ self.val = val self.next = next def __repr__(self, val): """ Displays the value of the node """ return '{val}'.format(val=self.val) class Stack: def __init__(self, iter=[]): self.top = None self._height = 0 for item in iter: self.push(item) def __repr__(self): """ Returns a string that contains the value of the top of the stack """ if self._height == 0: return 'Stack is empty' return 'Top of stack is {}'.format(self.top.val) def __str__(self): """ Returns the value of the top of the stack """ if self._height == 0: return 'Stack is empty' return self.top.val def __len__(self): return self._height def peek(self): """ Returns the value of the top of the stack """ return self.top.val def push(self, val): """ Pushes a new value at the top of the stack """ self.top = Node(val, self.top) self._height += 1 def pop(self): """ Removes the value at the top of the stack and sets the next value as the new top """ if len(self) == 0: raise IndexError('Stack is empty') temp = self.top self.top = temp.next self._height -= 1 return temp.val def multi_bracket_validation(string): """ Validates if each bracket has a pair """ if isinstance(string, str) is False: raise TypeError('Input is not a string') brackets = {'(': ')', '{': '}', '[': ']'} balance = Stack() for i in string: if i in brackets.keys(): balance.push(i) if i in brackets.values(): if balance.top is None: return False elif brackets[balance.top.val] == i: balance.pop() if len(balance) == 0: return True return False
true
d1f9324a011cbbe33a65a2005115e06ab86f74d1
brickfaced/data-structures-and-algorithms
/data-structures/binary_search_tree/fizzbuzztree.py
602
4.5625
5
def fizzbuzztree(node): """ Goes through each node in a binary search tree and sets node values to either Fizz, Buzz, FizzBuzz or skips through them depending if they're divisible by 3, 5 or both. The best way to use this function is to apply it to a traversal method. For example: BST.in_order(fizzbuzztree) """ if node.val % 3 == 0 and node.val % 5 == 0: node.val = 'FizzBuzz' return if node.val % 5 == 0: node.val = 'Buzz' return if node.val % 3 == 0: node.val = 'Fizz' return else: pass return
true
0a748373a51802c7500f8b6bd72cbd44d3f467d9
brickfaced/data-structures-and-algorithms
/data-structures/hash_table/repeated_word.py
857
4.125
4
"""Whiteboard Challenge 31: Repeated Word""" from hash_table import HashTable def repeated_word(text): """ Function returns the first repeated word. First thing it does is splits the inputted string into a list and for each word in that list it checks if that word is already in the hash table, if it isn't it adds word to the hash table. If it is it'll return that word and complete the problem domain. If it goes through the entire word list and there is no repeat words it'll return a informative output """ if type(text) is not str: raise TypeError('Please Enter A String') words = text.split(' ') word_hasher = HashTable() for word in words: if word_hasher.get(word) == [word]: return word word_hasher.set(word, word) return 'There are no repeated words'
true
b26893e0db5a57db2eed7de038eedc67337aecbf
abhaysingh00/PYTHON
/even odd sum of 3 digit num.py
307
4.21875
4
n= int(input("enter a three digit number: ")) i=n sm=0 count=0 while(i>0): count=count+1 sm=i%10+sm i=i//10 if(count==3): print(sm) if(sm%2==0): print("the sum is even") else: print("the sum is odd") else: print("the number entered is not of 3 digits")
true
ee3f8590f6a7be22bdf100b98b772aa9c09cc024
o0brunolopes0o/Curso-em-video-exercicios
/ex044.py
898
4.15625
4
""" Exercício Python 44: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: – à vista dinheiro/cheque: 10% de desconto – à vista no cartão: 5% de desconto – em até 2x no cartão: preço formal – 3x ou mais no cartão: 20% de juros (no valor total do produto) """ produto = float(input('Digite o valor do produto R$: ')) avistad = produto - (produto * (10/100)) avistac = produto - (produto * (5/100)) parcela = produto / 2 parcelaj = (produto * (20/100)) + produto parcelajp = parcelaj / 3 print('A vista com 10% de desconto R$: {}' .format(avistad)) print('A vista com 5% de desconto R$: {}' .format(avistac)) print('Parcelado sem juros fica em 2x de R$: {}' .format(parcela)) print('Parcelado com 20% de juros fica em 3x de R$: {} \n Juros ficou em R$: {}' .format(parcelajp, parcelaj))
false
7bd2f2e61e7a2728c265e2606e06fc8e95e6d7e3
aman1698/Semester-5
/SEE/1/1a.py
728
4.125
4
def insert(): l=[] while(True): print("1-insert an element\n2-exit") n=int(input()) if(n==1): print("Enter the element") n1=int(input()) l.append(n1) else: return l l1=insert() #l1=input().split() print("Original List: ",l1) l1.sort() l2=len(l1) print("Maximum Element ",l1[l2-1]) print("Minimum Element ",l1[0]) l3=int(input("Enter the number to be inserted\n")) l1.append(l3) print("List after insertion : ",l1) l4=int(input("Enter the element to be deleted\n")) if l4 in l1: l1.remove(l4) print("List after Deletion : ",l1) else: print("Element not present to be Deleted") l5=int(input("Enter the element to be searched\n")) if l5 in l1: print("Element Found") else: print("Element not found")
true
352066b731853c536a0c3d88bdb837092cdfc657
aman1698/Semester-5
/assignment4.py
530
4.125
4
dict={'O':'OXYGEN', 'N':'NITROGEN', 'C':'CARBON'} print("Original Dictionary :", dict) sym=input("Enter Unique Symbol : ").upper() dict[sym]=input("Enter Name : ").upper() print(dict,"\n") print("Number of terms in Dictionary :",len(dict)) print("\n") sym=input("Enter Symbol for element retrieval : ") if sym in dict: print (dict[sym]) else: print("element not present") #elname=input("Enter element for symbol retrieval : ").upper() #if elname in list(dict.values()): # for i in dict: # if dict[i]==elname: # print (i)
false
a7f8be5252fe91554221a80ee00489284ddc87ab
wbsartori/ExerciciosPython
/2 - estrutura-de-decisao/1-Exercicio.py
663
4.5
4
""" Faça um Programa que peça dois números e imprima o maior deles. """ print('##############################################################') print('####################### QUAL É MAIOR #########################') print('##############################################################') print('') numero_um = int(input('Digite um numero: ')) numero_dois = int(input('Digite mais um numero: ')) if(numero_um > numero_dois): print('O numero {} é maior que o numero {}. '.format(numero_um, numero_dois)) elif(numero_dois > numero_um): print('O numero {} é maior que o numero {}. '.format(numero_dois, numero_um)) else: print('São iguais.')
false
e52e23f51a52d5c8fb1a242c19846028d0723126
wbsartori/ExerciciosPython
/3 - estrutura-de-repeticao/6-Exercicio.py
336
4.1875
4
""" Faça um programa que imprima na tela os números de 1 a 20, um abaixo do outro. Depois modifique o programa para que ele mostre os números um ao lado do outro. """ numero = 20 i = 0 while(i < numero): i+= 1 print( '{}'.format(i)) j = 0 for j in range(numero): j += 1 print( '{}'.format(j), end="")
false
ae9f409b6b7823bbc285a4f7e15812165c1de721
PeriCode/PythWinter2018
/py_kids2018/l06/quest.py
1,884
4.34375
4
print("""Вы - бабушка А. Очнулись вы в темном помещении. Ваши действия: 1. Выглянуть в окно 2. Позвать на помощь 3. Попытаться позвонить""") action = int(input("Выбор: ")) if action == 1: print("""Вы выглянули в окно и узнали, что находитесь на Пустошах. Перед домом пробегает двухметровый Радскорпион. Просто так на улицу не высунешься. Вы можете: 1. Посмотреть в шкафчике с оружием. 2. Выпить стелл-стимулятор и стать невидимым 3. Просто рвануть на улицу и броситься на скорпиона """) action = int(input("Вы выбрали: ")) if action == 1: print("""Там вы обнаружили ракетницу 'Толстяк'. Взвалив ее на плечо, вы пошли в бой.""") elif action == 2: print("""Вы невидимы и поэтому решили, что скорпион вас не заметит, и пошли на улицу.""") elif action == 3: print("""Непонятно, на что вы рассчитывали. Сегодня скорпион поужинает бабушкой. Ваша жизнь окончена.""") elif action == 2: print("""На помощь отозвались рейдеры и отобрали все деньги-крышки""") elif action == 3: print("""Вы попытались позвонить, но единственное, что напоминает телефон это ваш башмак. Но это вас не остановило,и вы-таки с него дозвонились до базы супермутантов.""")
false
3c089a72e04559e257a8972d563a5d6c0a21acb7
PeriCode/PythWinter2018
/py_kids2018/l02/digits.py
567
4.21875
4
number = 22 #print(number) number = number + 10 #print(number) number = number - 30 #print(number) number = number * 10 #print(number) number = number / 5 #print(number) number += 5 # тоже самое, что и number = number + 5 number -= 5 # тоже самое, что и number = number - 5 number *= 5 # тоже самое, что и number = number * 5 number /= 3 # тоже самое, что и number = number / 3 number2 = 7 # новая переменная number2 = number2 ** 2 # возводим number2 в квадрат print(number2)
false
9d20d1a57f32db564e29e662cefa6b2304d103c4
PeriCode/PythWinter2018
/PyNoFantasy2k18/l01/first.py
738
4.34375
4
print("Здравствуй, Амин" + ". Как твои дела?") print(5) # целый тип - int print(5.6) # дробный тип - float print(int(7.6)) # преобразование float к int print("I am a string") # строковый тип - str print("5") # также строковый тип - str print('3') # также строковый тип - str print(True) # логический(булевый) тип - bool print(None) # пустой тип a = 5 b = 10 # a и b - ссылки на целочисленные объекты 5 и 10 print("Значение переменной:", a + 10) a = a + b print("Новое значение переменной:", a) c = '1' d = '2' print(c + d)
false
8b83fbcfd31ba3cc1676ee16906a6bbd2935af98
sanketsoni/6.00.1x
/longest_substring.py
796
4.375
4
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc """ s = 'abcabc' maxlength = 0 string1 = s[0] string2 = s[0] for i in range(len(s)-1): if s[i+1] >= s[i]: string1 += s[i+1] if len(string1) > maxlength: string2 = string1 maxlength = len(string1) else: string1 = s[i+1] i += 1 print("Longest substring in alphabetical order is:{}".format(string2))
true
72f2fa7a7980edb279f23269173545890ebd360b
mohor23/code_everyday
/binary_search(recursive).py
701
4.125
4
//binary search using recursion in python def binary_search(arr,l,h,number): if l<=h: mid=(l+h)//2 if(arr[mid]==number): return mid elif(number<arr[mid]): binary_search(arr,l,mid-1,number) else: binary_search(arr,mid+1,h,number) else: return -1 arr=[] n=int(input("enter the number of elements of array")) for i in range(0,n): ele=int(input("enter the elements of the array in sorted order")) arr.append(ele) print(arr) number=int(input("enter the element to be searched")) result=binary_search(arr,0,n-1,number) if(result==-1): print("element not found") else: print("element found at index",result)
true
8b6df693a8931d87148817973e68ef401f524d73
xuefengCrown/Learning-Python
/Beginning Python/database.py
2,953
4.15625
4
# Listing 10-8. A Simple Database Application # database.py import sys, shelve def store_person(db): """ Query user for data and store it in the shelf object """ pid = raw_input('Enter unique ID number: ') person = {} person['name'] = raw_input('Enter name: ') person['age'] = raw_input('Enter age: ') person['phone'] = raw_input('Enter phone number: ') db[pid] = person def lookup_person(db): """ Query user for ID and desired field, and fetch the corresponding data from the shelf object """ pid = raw_input('Enter ID number: ') field = raw_input('What would you like to know? (name, age, phone) ') field = field.strip().lower() print field.capitalize() + ':', \ db[pid][field] def print_help(): print 'The available commands are:' print 'store : Stores information about a person' print 'lookup : Looks up a person from ID number' print 'quit : Save changes and exit' print '? : Prints this message' def enter_command(): cmd = raw_input('Enter command (? for help): ') cmd = cmd.strip().lower() return cmd def main(): database = shelve.open('C:\\database.dat') # You may want to change this name try: while True: cmd = enter_command() if cmd == 'store': store_person(database) elif cmd == 'lookup': lookup_person(database) elif cmd == '?': print_help() elif cmd == 'quit': return finally: database.close() if __name__ == '__main__': main() The program shown in Listing 10-8 has several interesting features: • Everything is wrapped in functions to make the program more structured. (A possible improvement is to group those functions as the methods of a class.) • The main program is in the main function, which is called only if __name__ == '__main__'. That means you can import this as a module and then call the main function from another program. • I open a database (shelf) in the main function, and then pass it as a parameter to the other functions that need it. I could have used a global variable, too, because this program is so small, but it’s better to avoid global variables in most cases, unless you have a reason to use them. • After reading in some values, I make a modified version by calling strip and lower on them because if a supplied key is to match one stored in the database, the two must be exactly alike. If you always use strip and lower on what the users enter, you can allow them to be sloppy about using uppercase or lowercase letters and additional white- space. Also, note that I’ve used capitalize when printing the field name. • I have used try and finally to ensure that the database is closed properly. You never know when something might go wrong (and you get an exception), and if the program terminates without closing the database properly, you may end up with a corrupt data- base file that is essentially useless. By using try and finally, you avoid that.
true
fafaffc7c97297e40be44fb5b0bd2b77b6bfb4e2
InfinityTeq/Introduction-to-Python3
/module05/m5-practice/data-comparison.py
902
4.15625
4
# for this module's practice: # we will use sets to compare data # created by : C0SM0 # sets of animals that can live on land and sea [respectively] can_live_on_land = {"Wolves", "Alligator", "Deer"} can_live_in_sea = {"Fish", "Dolphin", "Alligator"} # create terrestial specific sets for the creature types land_creatures = can_live_on_land - can_live_in_sea sea_creatures = can_live_in_sea - can_live_on_land amphibious_creatures = can_live_on_land & can_live_in_sea # output, creatures that can live on land print(f"Creatures that live on land:\n{land_creatures}\n") print(f"Creatures that live in water:\n{sea_creatures}\n") print(f"Creatures that live in both:\n{amphibious_creatures}\n") # feel free to keep practicing, here are some more ideas """ - compare food at home to food on your grocery list - prevent duplicate entries when creating an account or submitting quiz/survey answers """
true
534f12658f7dffa0efca11c00226adb79df46c76
InfinityTeq/Introduction-to-Python3
/module03/m3-practice/multiplication-tables.py
682
4.4375
4
# for this module's practice: # we will make a program that will generate multiplication tables # created by : C0SM0 # variables range_limit = range(1, 13) # iterate through each table for table_number in range_limit: # banner print(f"\nMultiplication Table for {table_number}:") # iterate through each multiple for multiple in range_limit: answer = table_number * multiple print(f"{table_number} x {multiple} = {answer}") # feel free to keep practicing, here are some more ideas """ - multiplication table with user input - users can ask for certain tables or to list the first 12 - a quiz that can end if a question is answered wrong """
true
8219a19e2e78f610f4acdff4d3139c5b65d36642
mhamzawey/DataStructuresAlgorithms
/InsertionSort.py
665
4.28125
4
from BinarySearch import binarySearch def insertionSort(arr): """ Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. :param arr: :return: arr Complexity O(n^2 """ for i in range(len(arr)): current = arr[i] j = i - 1 while j >= 0 and arr[j] > current: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = current return arr x_array = [54, 26, 93, 17, 77, 31, 44, 55, 20, 89, 0] print("Insertion Sort Algorithm: " + str(insertionSort(x_array))) y = binarySearch(55, x_array, 0, len(x_array) - 1) print(y)
true
af531dfc2e22c0b2ef6500bb74b484331f2c6ac7
chokkalingamk/python
/Bitwise_operators.py
588
4.28125
4
#This is the Bitwise program to check print ("Welcome to Addition Calculator") print ("Enter the value A") a = int(input()) print ("Enter the value B") b = int(input()) and_val = (a & b) or_val = (a | b) xor_val = (a ^ b) #not_val = (a ~ b) left_val = (a << b) right_val = (a >> b) print ("The value of A is ", a ) print ("The value of B is ", b ) print ("The value of AND is", and_val) print ("The value of OR is", or_val) print ("The value of XOR is", xor_val) #print ("The value of not is", not_val) print ("The value of left is", left_val) print ("The value of right is", right_val)
true
955ba7fa1d1b396827c775318180d15ccf0b0ffe
ambateman/TechAcademy
/Python/PyDrill_Datetime_27_idle.py
732
4.125
4
#Python 2.7 #Branches open test #Drill for Item 62 of Python Course # #The only quantity that should matter here is the hour. If the hour is between 9 and 21 #for that office, then that office is open. import datetime portlandTime = datetime.datetime.now().hour nyTime = (portlandTime + 3)%24 #NYC is three hours ahead of portland londonTime = (portlandTime + 8)%24 #London is 8 hours ahead of portland #Which of the non-Portland branch offices are open? if nyTime>=9 and nyTime<21: print "NYC Branch Office is Open" else: print "NYC Branch Office is Closed" if londonTime>=9 and londonTime<21: print "London Branch Office is Open" else: print "London Branch Office is Closed"
true
dc46be41cfc4becb94a1eeaec36fc098942b9fd7
devyanshi-t/Contibution
/Codes/case.py
493
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 13 10:25:35 2020 @author: devyanshitiwari You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. """ def swap_case(s): x="" for i in s: if i.islower(): x=x+i.upper() else: x=x+i.lower() return x if __name__ == '__main__': s = raw_input() result = swap_case(s) print (result)
true
37a1e9841cff3ceca38a39f3351a294f0efb1e0f
devyanshi-t/Contibution
/Codes/leapyear.py
363
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 23 17:52:40 2020 @author: devyanshitiwari """ def is_leap(year): leap = False # Write your logic here if(year%4==0 and year%100 !=0): leap=True elif(year%100==0 and year%400==0): leap=True return leap year = 2100 print (is_leap(year))
false
71e368e81fee53211cfecaed497d06a3b385f703
eventuallyrises/CS61A
/hw1_q4.py
624
4.125
4
"""Hailstone Sequence problem""" def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1 10 5 16 8 4 2 1 >>> a 7 """ assert n > 0, 'Seed number %d is not greater than 0' % n assert type(n) == int, 'Seed number is not an Integer' count = 1 while n != 1: print(n) if(n % 2 == 0): # N is even n = n // 2 else: # N is odd n = (n * 3) + 1 count += 1 print(n) return count
true
b457618da678f79c59ceb9b6e191e5c6a18df933
Vivekyadv/InterviewBit
/Tree Data Structure/2 trees/1. merge two binary tree.py
2,064
4.15625
4
# Given two binary tree A and B. merge them in single binary tree # The merge rule is that if two nodes overlap, then sum of node values is the new value # of the merged node. Otherwise, the non-null node will be used as the node of new tree. # Tree 1 Tree 2 Merged Tree # 2 3 5 # / \ / \ / \ # 1 4 + 6 1 --> 7 5 # / \ \ / \ \ # 5 2 7 5 2 7 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # Method 1: merge tree b in tree a and return a def merge(self, a, b): a.val = a.val + b.val if a.left and b.left: self.merge(a.left, b.left) if a.right and b.right: self.merge(a.right, b.right) if not a.left and b.left: a.left = b.left if not a.right and b.right: a.right = b.right def mergeTree1(self, a, b): if not a: return b elif b: self.merge(a, b) return a # Method 2: create new tree and merge a and b def mergeTree2(self, a, b): if not a and not b: return None if a and not b: return a if b and not a: return b root = TreeNode(a.val + b.val) root.left = self.mergeTree2(a.left, b.left) root.right = self.mergeTree2(a.right, b.right) return root def inorder(self, node): if not node: return self.inorder(node.left) print(node.val, end=' ') self.inorder(node.right) node1 = TreeNode(2) l = TreeNode(1) ll = TreeNode(5) r = TreeNode(4) node1.left = l node1.right = r l.left = ll # Tree 2 node2 = TreeNode(3) l_ = TreeNode(6) lr_ = TreeNode(2) r_ = TreeNode(1) rr_ = TreeNode(7) node2.left = l_ node2.right = r_ l_.right = lr_ r_.right = rr_ sol = Solution() newTree = sol.mergeTree2(node1, node2) sol.inorder(newTree)
true
a79248bc4e2ee6c8146f7a292f336ccf6462b721
Vivekyadv/InterviewBit
/Array/Arrangement/2. rotate matrix.py
303
4.15625
4
# rotate matrix by 90 ° clockwise def rotate(A): for i in range(len(A)): for j in range(i,len(A)): A[i][j], A[j][i] = A[j][i], A[i][j] for i in range(len(A)): A[i].reverse() return A arr = [ [1,2,3], [4,5,6], [7,8,9] ] print(rotate(arr))
false
edcd7c026b3fd1a6122be4e78f13a77516a9c9e2
Vivekyadv/InterviewBit
/String/String math/4. power of 2.py
1,531
4.25
4
# Find if Given number is power of 2 or not. # More specifically, find if given num can be expressed as 2^k where k >= 1. # Method 1: using log func # 2 ^ k = num # k*log(2) = log(num) # k = log(num,2) # if ceil value of k is equal to k then it can be expressed num1 = "1024" num2 = "1023" from math import log, ceil def power(num): num = int(num) if num < 2: return 0 k = log(num,2) return 1 if ceil(k) == k else 0 print(power(num1), end= ' ') print(power(num2)) # Method 2: divide num in loop and check if its completely divisible by 2 def power(num): num = int(num) if num < 2: return 0 while num != 1: if num % 2 == 0: num = num//2 else: return 0 return 1 print(power(num1), end= ' ') print(power(num2)) # Method 3: using bitwise & operator # Logic: If we subtract a power of 2 numbers by 1 then all unset bits # after the only set bit become set; and the set bit becomes unset. # Example: 16 (10000) and 15 (01111) --> bitwise and of 16 and 15 # is 00000 i.e 0 # Time Complexity: O(1) def power(num): num = int(num) if num == 1 : return 0 if num & (num-1) == 0: return 1 else: return 0 print(power(num1), end= ' ') print(power(num2)) # Method 4: if num is power of 2, then no_of bit 1 is equal = 1 def power(num): num = int(num) bin_num = bin(num) if bin_num.count('1') == 1: return 1 else: return 0 print(power(num1), end= ' ') print(power(num2))
true
cb1225395f4f4787d998a299bfa40e077da4421c
hualili/opencv
/deep-learning-2020S/20-2021S-0-2slicing-2021-2-24.py
2,631
4.21875
4
""" Program: 2slicing.py Coded by: HL Date: Feb. 2019 Status: Debug Version: 1.0 Note: NP slicing Slicing arrays, e.g., taking elements from one given index to another given index. (1) pass slice instead of index as: [start:end]. (2) define the step like: [start:end:step]. (3) if we don't pass start its considered 0, and If we don't pass end its considered length of array in that dimension, and If we don't pass step its considered 1 ref: https://www.w3schools.com/python/numpy_array_slicing.asp """ import sys import numpy as np #================ # Slicing 1D tensor, float 32 or float 64 for np x = np.array([5,6,13,-2.1,100]) print ('x') print (x) print ('slicing: [start:end] = [1:3]') print (x[1:3]) print ('Negative slicing: [-start:-end] start counting from the end = [-3:-1]') print (x[-3:-1]) print ('step: [start:end:step] = [1:5:2]') print (x[1:5:2]) print ('step: [start:end:step] = [::2]') print (x[::2]) y = x.ndim print ('vector x dimension') print (y) print ('---------------------\n') #================ # Slicing 2D tensor, float 32 or float 64 for np x = np.array([[5,6,13,-2.1], [0,1,-1.1,0.1], [2,1,-1, 0.15]]) print ('2D tensor x') print (x) print ('slicing: [row, start:end] = [0, 1:3]') print (x[0,1:3]) print ('step: [row, start:end:step] = [0, ::2]') print (x[0,::2]) y = x.ndim print ('vector x dimension') print (y) print ('---------------------\n') #================ # 3D tensor, float 32 or float 64 for np x = np.array([[[0,1,2,3], [4,5,6,7], [8,9,10,11]], [[12,13,14,15], [16,17,18,19], [20,21,22,23]], [[24,25,26,27], [28,29,30,31], [32,33,34,35]]]) print ('3D tensor x') print (x) print ('slicing: [index2D, index1D(row), start:end] = [0,1, 1:3]') print (x[0,1,1:3]) ''' now, [::1] to select all matrices, and all rows, and col 1 ''' print ('slicing: [index2D, index1D(row), start:end] = [::2]') print (x[::2]) print ('slicing: [index2D, index1D(row), start:end] = [::,2]') print (x[::,2]) ''' now, [::1] to select all matrices, and all rows, and col ''' #print ('step: [index2D, index1D(row), start:end:step] = [0,1, ::2]') #print (x[0,::2]) y = x.ndim print ('vector x dimension') print (y) ''' Note: NumPy arrays iterate over the left-most axis first. https://stackoverflow.com/questions/28010860/slicing-3d-numpy-arrays/28010900 ''' #if src is None: # print ('Error opening image!') # print ('Usage: pdisplay.py image_name\n') #while True: # c = cv2.waitKey(500) # if c == 27: # break
true
894e677b208321a842d980a623f9a00bdee2ecea
gan3i/CTCI-Python
/Revision/LinkedList/remove_duplicates_2.1_.py
2,738
4.15625
4
#ask questions # 1. is it a doubly linked list or singly linked list # 2. what type of data are we storing, integer? float? string? can there be negatives, class Node(): def __init__(self,data): self.data = data self.next = None # in interview do not write the linked list class assume that it's given class LinkedList(): def __init__(self): self.head = None # linear space and time complexity def remove_duplicates(self): if self.head == None: return # hash set the keeps track of values that we have already seen hash_set =set() current = self.head prev = None while current: if current.data in hash_set: # found the duplicate node temp = current current = current.next self.remove_node(temp, prev) else: hash_set.add(current.data) prev = current current = current.next # quadratic time and constant space def remove_duplicates1(self): current = self.head while current: prev_node = current next_node = current.next while next_node: if prev_node.data == next_node.data: temp = next_node next_node = next_node.next self.remove_node(temp,prev_node) else: prev_node = next_node next_node = next_node.next current = current.next def remove_node(self,node, prev): prev.next = node.next node = None # algorithm ends here rest is just are just helper methods for linked list @staticmethod # to add a new Node to the sigly linked list def add_node(head,data): # if the head is None return new node if head == None: return Node(data) # else travel to the end of the Node recursively and insert the new node at the end head.next = LinkedList.add_node(head.next,data) return head def add(self,data): # self.head = LinkedList.add_node(self.head, data) if self.head == None: self.head = Node(data) end = self.head while end.next: end = end.next end.next = Node(data) def print(self): current = self.head while current: print(current.data) current = current.next linked_list = LinkedList() linked_list.add(1) # linked_list.add(1) # linked_list.add(3) # linked_list.add(3) # linked_list.add(4) linked_list.remove_duplicates1() linked_list.print()
true