blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a3d204581bd24365e6ebb3ce7fb1d750e795237f
tieje/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
240
4.1875
4
#!/usr/bin/python3 """This module reads a text file""" def read_file(filename=""): """This method reads a file.""" with open(filename, mode="r", encoding="utf_8") as file: for line in file: print(line, end='')
true
32040098ac2f626214124dab1cc919b8aebd8eb9
GaryGonzenbach/python-exercises
/control_structures_examples.py
1,991
4.3125
4
print('Good Morning Ada!') i_like_coffee = True # switch to False to test else if i_like_coffee: print('I like coffee!') else: print('Ok - lets have some tea') # --- pizza_reference = input('What kind of pizza do you like?') if pizza_reference == 'pineapple and hot sauce': print('Wow - what a coincidence!') # spicy_level = int(input('How spicy would you like it? (1-5)')) elif pizza_reference == 'pepperoni and chocolate': print('hmmm... ok') elif pizza_reference == 'cheese': print('Plain cheese, ok!') else: print('Not my favorite, but lets order some!') # - print('Ok - Done ordering pizza') # ----------------------------------- # 1. prompt the user for a day of the week, print out whether the day is Monday or not day_of_the_week = input('What day of the week is it?') if day_of_the_week.lower() == 'monday' or day_of_the_week == 'mon': print('Happy Monday!') else: print('At least its not Monday') # 2. prompt the user for a day of the week, print out whether the day is a weekday or a weekend weekend_list = ['saturday', 'sat', 'sunday', 'sun'] if day_of_the_week.lower() in weekend_list: print('Great, its the weekend! ') else: print('another workday') # 3. create variables for # - the number of hour worked in one week # - the hourly rate number_of_hours_per_week = -1 hourly_rate = -1 while number_of_hours_per_week < 1 or number_of_hours_per_week > 150: number_of_hours_per_week = int(input('How many hours did you work this week (1-150)?')) while hourly_rate < 1 or hourly_rate > 2000: hourly_rate = int(input('How much do you make an hour?')) # - how much the week's paycheck will be # write the python code that calculates the weekly paycheck. You get paid time # and a half if you work more than 40 hours if number_of_hours_per_week > 40: paycheck = ((number_of_hours_per_week - 40) * (1.5 * hourly_rate)) + (40 * hourly_rate) else: paycheck = (40 * hourly_rate) print('You paycheck will be ', paycheck)
true
b27acfbc54aeae4b5741ed27fa849e09d9c8a46a
skyrydberg/LPTHW
/ex3/ex3.py
1,251
4.25
4
# Exercise 3: Numbers and Math # I addressed Exercises 1 & 2 in the same post because they # are trivial. This one gets its own post. print "I will now count my chickens:" # Note the order of operations holds here, a kind programmer # would type this 25 + (30 / 6) for clarity, we divide 30 by 6 # and then add the result to 25 print "Hens", 25 + 30 / 6 # Similarly 100 - ((25 * 3) % 4), we multiply 25 by 3 and then # divide by 4 and take the remainder, which we then subtract # from 100 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" # And again 3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6 or more # realistically you'd split this across a couple lines... # Regardless, we divide 1 by 4 and divide 4 by 2 and keep the # remainder then we sum across. Note per Study Drill 3 I've # replaced 1 with 1.0 to force python to evaluate the values # as floating point numbers instead of integers print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
618535ad2c3d769521c1a60f73b2e37f26ee5cc3
GaddamMS/PythonMoshYT
/own_program_weather_notify_0.py
1,481
4.4375
4
'''Feature: Intimate user with precautions based on weather when going outside Problem Statement: We should identify the weather and tell the user of necessary precautions Solution: 1. We will ask the user for temperature 2. Based on the given temperature, we will intimate user with self - defined precautions ''' temperature = int(input('What is the temperature (in centigrade) outside now?')) # if type(temperature) is int or type(temperature) is float: # else : # print('I am expecting the temperature and nothing else') if temperature < 0: print('It is freezing outside. Prefer staying indoor unless it is an emergency.') elif temperature in range (1,14): print('Use a thick, furry coat and shoes to go outside. Carry an umbrella if possible') elif temperature in range (15,24): print('Use a furry coat and shoes to go outside. You should be loving the weather today.') elif temperature in range (24,30): print('Damn! Your lucky day') elif temperature in range (30,45): print('Cotton clothes are the best for this weather. Avoid black colour. ' 'Wear as lite as possible. Carry an umbrella') elif temperature in range (45,60): print('You must stay indoors. Possibilities of heat stroke and going to an ER') elif temperature in range (60,75): print('rush! Switch ON your air conditioner right away') elif temperature > 75: print('You are Kentucky Fried Chicken!') else: print('Nasty You! Enter the temperature correctly')
true
7b28907cfd5737677e3d0380f631272847cfe936
monsybr11/FirstCodingAttempts
/textrealiser.py
535
4.21875
4
abc = input("Type any text in.\n") abc = str(abc) # converting the input to a string in case of text and digits being used. if abc.islower() is True: print("the text is lowercase!") if abc.isupper() is True: print("the text is Uppercase!") if abc.isupper() is False and abc.islower() is False and abc.isnumeric() is False and abc.isdigit() is False: print("The text is mixed!!!") # so many "and" uses to make sure that one output is chosen. if abc.isnumeric() is True: print("these are numbers!")
true
095c16d2e25fe3e5d076ea09bad8b18c0e0e140a
SastreSergio/Datacademy
/paper_scissors.py
2,815
4.1875
4
#A game of Scissors, paper and stone against the machine import random def choice_player2(): #Function with random for the other player, in this case: the machine options = ['Scissors', 'Paper', 'Stone'] random_choice = random.choice(options) return random_choice def play(choice_player1, choice_player2): print('One two three scissors, paper and stone!') if choice_player1 == 'Scissors' and choice_player2 == 'Paper': print(f'{choice_player1} against {choice_player2}') print('Player 1 wins') elif choice_player1 == 'Scissors' and choice_player2 == 'Stone': print(f'{choice_player1} against {choice_player2}') print('The machine wins') elif choice_player1 == 'Scissors' and choice_player2 == 'Scissors': print(f'{choice_player1} against {choice_player2}') print('It is a draw!') elif choice_player1 == 'Paper' and choice_player2 == 'Stone': print(f'{choice_player1} against {choice_player2}') print('Player 1 wins') elif choice_player1 == 'Paper' and choice_player2 == 'Scissors': print(f'{choice_player1} against {choice_player2}') print('The machine wins') elif choice_player1 == 'Paper' and choice_player2 == 'Paper': print(f'{choice_player1} against {choice_player2}') print('It is a draw!') elif choice_player1 == 'Stone' and choice_player2 == 'Scissors': print(f'{choice_player1} against {choice_player2}') print('Player 1 wins') elif choice_player1 == 'Stone' and choice_player2 == 'Paper': print(f'{choice_player1} against {choice_player2}') print('The machine wins') elif choice_player1 == 'Stone' and choice_player2 == 'Stone': print(f'{choice_player1} against {choice_player2}') print('It is a draw!') def run(): ## Initialization print('Welcome to Scissors, Paper and Stone!') choice_player1 = input('What do you choose? Scissors, Paper or Stone? -> ') ##Verification process if choice_player1 == "Scissors" or choice_player1 == "scissors": choice_player1 = choice_player1.capitalize() print(f'You have chosen {choice_player1}') elif choice_player1 == "Paper" or choice_player1 == "paper": choice_player1 = choice_player1.capitalize() print(f'You have chosen {choice_player1}') elif choice_player1 == "Stone" or choice_player1 == "stone": choice_player1 = choice_player1.capitalize() #Capitalize first letter print(f'You have chosen {choice_player1}') else: print('Please, write a valid option') run() ## Player 2 choice ( The machine chooses randomly) player2 = choice_player2() ## Playing the game play(choice_player1, player2) if __name__ == '__main__': run()
true
f1217d5ddd3b8c780f5d08eda75bd31481cd6b38
kissann/Lab1
/five.py
966
4.4375
4
#Задача 5 Задано чотири точки паралелограма за допомогою координат його вершин. # Визначити площу паралелограма та довжину його діагоналей. Результат округлити до тисячних. print("Введите координаты первой точки:") x1= input("x1 = ") y1= input("y1 = ") print("Введите координаты второй точки:") x2= input("x2 = ") y2= input("y2 = ") x3=float(x1)+float(x2) y3=float(y1) x4=float(x3)-float(x1)-float(x2) y4=float(y2) print("(x1 = %.2f y1 = %.2f)\n(x2 = %.2f y2 = %.2f)\n(x3 = %.2f y3 = %.2f)\n(x4 = %.2f y4 = %.2f)\n" % (float(x1), float(y1),float(x2),float(y2),float(x3),y3,x4,y4)) a=float(x3)-float(x1) h=float(y2)-float(y3) print("Высота h = %.2f \nОснование а = %.2f" % (h,a)) S=a*h print("Площа параллелограмма S = %.2f" % (S))
false
a141c79f05ee4dfe9eb04f36e7ce0e2ca59e8fc2
tdounnyy/SampleCodes
/python/helloPython.py
961
4.15625
4
#!/usr/bin/python print 'hello python' print '' print '#\/*\'?:"' # fuck the golden lian print "what do you mean?" print '''hey, son. what`s your name? do \ i\ know # Hail the winterfell you? ''' i = 5 print i print i+1 i=i+1 print i string= '''Which family do you serve? Long live the king!''' print string if True : print 'hello' complain = False; #complain = True; while complain : answer = raw_input('say you love me\n') if 'i love you' == answer: complain = False; print 'i know' else : print 'cross my heart' def functiona(): print 'i`m functiona' functiona() def autoCounter(msg = '123', times = 1): print msg * times autoCounter() autoCounter('hallo') autoCounter('hello',4) def assignParam(x): '''This is ___doc___ fo assignParam. Which is a Python way to self-explain''' x = 5 print x return x y = 6 print y y = assignParam(y) print y print assignParam.__doc__
false
27804af36166140fc6655be1c6fd1f60096f34ef
vickiedge/cp1404practicals
/prac_04/quick_picks.py
584
4.125
4
#relied heavily on solution for this exercise. Still not printing all quick picks import random MIN_NUMBER = 1 MAX_NUMBER = 45 NUMBER_PER_LINE = 6 number_of_quick_picks = int(input("How many quick picks? ")) for i in range(number_of_quick_picks): quick_pick = [] for j in range(NUMBER_PER_LINE): number = random.randint(MIN_NUMBER, MAX_NUMBER) while number in quick_pick: number = random.randint(MIN_NUMBER, MAX_NUMBER) quick_pick.append(number) quick_pick.sort() print("".join("{:3}".format(number) for number in quick_pick))
true
11ed3a0ab634d3fc1568dbfb38c9d9aff5aced21
introprogramming/exercises
/exercises/fibonacci/fibonacci-iterative.py
735
4.25
4
'''An iterative version, perhaps more intuitive for beginners.''' input = int(input("Enter a number: ")) def fibonacci_n(stop_after): """Iteratively searches for the N-th fibonacci number""" if stop_after <= 0: return 0 if stop_after <= 2: return 1 prev = 1 curr = 1 count = 2 while count <= stop_after: curr = curr + prev prev = curr - prev count = count + 1 return prev def next_fibonacci(stop_after): """Iteratively searches for the fibonacci number that comes after the stop_after value""" prev = 0 curr = 1 while prev <= stop_after: curr += prev prev = curr - prev return prev print(next_fibonacci(input))
true
e6ca6a8207216df4ce34d79187e9e41e147ba4b8
introprogramming/exercises
/exercises/talbas/convert.py
657
4.1875
4
# # Decimal to binary (and back) converter # # Usage: # python convert.py bin|dec 100 # import sys def dectobin(dec_string): """Convert a decimal string to binary string""" bin_string = bin(int(dec_string)) return bin_string[2:] def bintodec(bin_str): """Convert a binary string to decimal string""" num = 0 index = 1 for c in reversed(bin_str): num = num + index * int(c) index = index * 2 return num if len(sys.argv) > 2: if sys.argv[1] == 'bin': print(bintodec(sys.argv[2])) elif sys.argv[1] == 'dec': print(dectobin(sys.argv[2])) else: print("Usage: convert.py bin|dec number") else: print("Usage: convert.py bin|dec number")
false
e435dd76259d6ad09b57f30f5b8b3647f565b086
shea7073/Algorithm_Practice
/phone_number.py
495
4.28125
4
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string # of those numbers in the form of a phone number. def create_phone_number(arr): if len(arr) != 10: return ValueError('Array Must be 10 digits long!') for i in arr: if i > 9 or i < 0: return ValueError('Phone numbers only except 0-9') return '({}{}{}) {}{}{}-{}{}{}{}'.format(*arr) print(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
true
f6a6fe07b1678d57b8b3d600b2dfe9b84458313b
frclasso/CodeGurus_Python_mod1-turma1_2019
/atividades/imc_cris.py
1,218
4.15625
4
#imc = peso / altura * altura #input #criar um menu com osparametros print('Vamos calcular seu Indice de massa corporal!') input('Digite Enter para comecar!') altura = 0 peso = 0 while peso<=0: peso = float(input('Por favor digite seu peso: ')) if peso<=0: print('Digite um valor maior que 0!') while altura<=0 or altura>=3: altura = float(input('Por favor digite sua altura: ')) if altura <=0: print('Digite um valor maior que 0!') elif altura >=3: print('Você é uma girafa, seu IMC deve ser calculado diferente!') IMC = peso/altura**2 if IMC <18.5: print('Você esta abaixo do peso!') print() elif IMC >18.5 and IMC <24.9: print('Parabéns seu peso esta normal!') print() elif IMC <=25: print('Cuidado você esta em sobrepeso') print() elif IMC >25 and IMC <29.9: print('Cuidado você esta em pré-obesidade!') print() elif IMC >30 and IMC <34.9: print('Cuidado você esta em grau de obesidade I!') print() elif IMC >35 and IMC <39.9: print('Cuidado você esta em grau de obesidade II!') print() elif IMC >40: print('Cuidado você esta em grau de obesidade III!') print() print('O seu IMC e', round(IMC,2))
false
dd7aa50d126ddab75b24da79f3b0ac1b0d61bcf3
gy09/python-learning-repo
/PythonLearning/FunctionLearning/forLoop.py
290
4.15625
4
def upperConversion(): sentence = input("Enter the sentence to loop on:") for word in sentence: print(word.upper()) def listLoop(): friends = ["test1","test2","test3","test4"] for friend in friends: print(friend.upper()) upperConversion() listLoop()
true
758b8bec6328bfb4e403b1ea4bd3e12ca235d0b8
yxh13620601835/store
/day10/car.py
2,671
4.4375
4
''' 车类: 属性:车型号,车轮数,车身颜色,车重量,油箱存储大小 。 功能:跑(要求参数传入车的具体功能,比如越野,赛车) 创建:法拉利,宝马,铃木,五菱,拖拉机对象 ''' class Car: __type="" __wheelnum=0 __color="" __weight=0.0 __fuelstorge=0.0 def setType(self,type): self.__type=type def getType(self): return self.__type def setWheelNum(self,wheelnum): if wheelnum<0 or wheelnum>20: print("输入非法!") else: self.__wheelnum=wheelnum def getWheelNum(self): return self.__wheelnum def setColor(self,color): self.__color=color def getColor(self): return self.__color def setWeight(self,weight): if weight<0: print("输入非法!") else: self.__weight=weight def getWeight(self): return self.__weight def setFuelStorge(self,fuelstorge): if fuelstorge<0: print("输入非法!") else: self.__fuelstorge=fuelstorge def getFuelStorge(self): return self.__fuelstorge def introduce(self): print("%s的车有%d个车轮,车身颜色是%s,%.2f公斤,%.2fL油箱。"% (self.__type,self.__wheelnum,self.__color,self.__weight,self.__fuelstorge)) def run(self,function): print("%s的功能是%s"%(self.__type,function)) if __name__=="__main__": falali=Car() falali.setType("法拉利") falali.setWheelNum(4) falali.setColor("黄色") falali.setWeight(5000.5) falali.setFuelStorge(30.5) falali.introduce() falali.run("赛车") baoma=Car() baoma.setType("宝马") baoma.setWheelNum(4) baoma.setColor("宝石蓝") baoma.setWeight(2300) baoma.setFuelStorge(40) baoma.introduce() baoma.run("赛车") lingmu=Car() lingmu.setType("铃木") lingmu.setWheelNum(4) lingmu.setColor("炫彩紫") lingmu.setWeight(5600) lingmu.setFuelStorge(60) lingmu.introduce() lingmu.run("越野") wuling=Car() wuling.setType("五菱") wuling.setWheelNum(4) wuling.setColor("粉色") wuling.setWeight(3200) wuling.setFuelStorge(28.3) wuling.introduce() wuling.run("越野") tuolaji=Car() tuolaji.setType("拖拉机") tuolaji.setWheelNum(3) tuolaji.setColor("绿色") tuolaji.setWeight(4800) tuolaji.setFuelStorge(48.3) tuolaji.introduce() tuolaji.run("拉货")
false
c2853f4bd7682ed91b22dd8040e727299bff2b52
vharmers/Kn0ckKn0ck
/Parsing/Readers/Reader.py
1,416
4.1875
4
import abc class Reader: """ Abstract class which defines the minimal functionality of Readers. You will need to extend from tis class if you want to create your own reader. """ def __init__(self): pass @abc.abstractmethod def get_count(self): """ Gets the amount of items in this Reader. :return: amount of items (int) """ return @abc.abstractmethod def get_value(self, value_name, index): """ Get a value from the reader. :param value_name: The name of the value :param index: The index of the value :return: The value with the given value name at the given index. Example get_value('Age', 0) -> 25 """ return @abc.abstractmethod def value_exists(self, value_name): """ Checks if the given value name exists. :param value_name: The value name to check :return: True if the given value name exists in the Reader and False otherwise """ return @abc.abstractmethod def get_item(self, index): """ Get a dictionary with values and their names at a given index. :param index: Index of the values you want :return: A list with values. Example: ['Name': 'John', 'Surname': 'Doe', 'Age': 25] """ return
true
0bb76f227b04593d109b4abf127f95aa5348c09f
jraulcr/curso-python
/practica_listas.py
1,229
4.25
4
miLista=["María", "Pepe", "Marta", "Antonio"] #Accede a todos los elementos print(miLista[:]) #Acceso por indice (Desde el primer lugar) print(miLista[2]) #Acceso por subindice (Desde el último lugar) print(miLista[-1]) #Acesso por porciones print(miLista[1:3]) print(miLista[2:]) print(miLista[:2]) #Agrega nuevo elemento al final de la lista miLista.append("Sandra") print(miLista[:]) #Agrega nuevo elemento desde N posicion de la lista miLista.insert(2,"Curro") print(miLista[:]) #Concatena una lista a la lista principal miLista.extend(["Ana","Juan","Rebeca"]) print(miLista[:]) #Devuelve en que numero de indice está situado print(miLista.index("Antonio")) #Imprime True o False si un elemento está en la lista print("Pepe" in miLista ) #Elimina un elemento a la lista miLista.remove("Ana") print(miLista[:]) #Elimina el último elemento de la lista miLista.pop() print(miLista[:]) #Concatena una lista con otra lista y lo devuelve unida a otra lista vacia miLista1=["María", "Pepe", "Marta", "Antonio"] miLista2=["Ana","Juan","Rebeca"] miLista3=miLista1+miLista2 print(miLista3[:]) #Repite una lista N veces miLista1=["Ana","Juan","Rebeca"]*3 print(miLista1[:]) numeros_lista = list((1,2,3,4)) print(numeros_lista)
false
f2e3ddcbfedf9b3860590b28dbfd032e106e9390
aayush2906/learning_curve
/for.py
559
4.34375
4
''' You are given a number N, you need to print its multiplication table. ''' { #Initial Template for Python 3 //Position this line where user code will be pasted. def main(): testcases=int(input()) #testcases while(testcases>0): numbah=int(input()) multiplicationTable(numbah) print() testcases-=1 if __name__=='__main__': main() } def multiplicationTable(N): for i in range(1,11): ## i in range(x,y,z) means i goes from x to y-1 and increments z steps in each iteration print(i*N, end=" ")
true
a4e7ded1eac764352cb65888ba36ef4289bd6c4b
nathanesau/data_structures_and_algorithms
/_courses/cmpt225/lecture09/python/stack.py
1,661
4.15625
4
class Node: def __init__(self, data): self.data = data self.prev = None class StackLinkedList: """ linked list implementation of stack - similar to singly linked list """ def __init__(self): self.top = None def push(self, data): """ add element to top of stack, O(1) """ if not self.top: self.top = Node(data) else: node = Node(data) node.prev = self.top self.top = node def pop(self): """ pop element from top of stack, O(1) """ if not self.top: raise Exception("Cannot pop from empty stack") data = self.top.data self.top = self.top.prev return data def __str__(self): """ string representation of stack """ s = "" node = self.top while node is not None: s += str(node.data) + " " node = node.prev return s class StackArrayList: """ array list implementation of stack """ def __init__(self): self.arr = [] def push(self, data): self.arr.insert(0, data) def pop(self): return self.arr.pop(0) def __str__(self): return str(self.arr) if __name__ == "__main__": stack = StackLinkedList() stack.push(5) stack.push(3) stack.push(7) print(str(stack)) # 7, 3, 5 stack.pop() print(str(stack)) # 3, 5 stack = StackArrayList() stack.push(5) stack.push(3) stack.push(7) print(str(stack)) # 7, 3, 5 stack.pop() print(str(stack)) # 3, 5
true
9a044231cb1d922651e6b3463e5f3696cf7b18af
nathanesau/data_structures_and_algorithms
/_courses/cmpt225/practice4-solution/question6.py
892
4.1875
4
""" write an algorithm that gets a tree and computes its depth using iterative implementation. """ """ write an algorithm that gets a tree and computes its size using iterative implementation. """ from binary_tree import build_tree1, build_tree2, build_tree3 def get_depth(bt): """ use level-order iterative algorithm """ max_depth = 0 q = [(bt.root, 1)] while q: node, depth = q.pop(0) max_depth = max(depth, max_depth) if node.left is not None: q.append((node.left, depth + 1)) if node.right is not None: q.append((node.right, depth + 1)) return max_depth if __name__ == "__main__": # test tree1 tree1 = build_tree1() print(get_depth(tree1)) # test tree2 tree2 = build_tree2() print(get_depth(tree2)) # test tree3 tree3 = build_tree3() print(get_depth(tree3))
true
3875d9590a0a90962b5680329c571b9e300d4540
Pranav2507/My-caption-project
/project 2.py
398
4.125
4
filename=input('Enter a filename: ') index=0 for i in range(len(filename)): if filename[i]=='.': index=i print(filename[index+1: ]) filename = input("Input the Filename: ") f_extns = filename.split(".") print ("The extension of the file is : " + repr(f_extns[-1])) fn= input("Enter Filename: ") f = fn.split(".") print ("Extension of the file is : " + f[-1])
true
aba6611d825897b03b9d9c4a7adca8f2e6b66c69
uniite/anagram_finder
/modules/util.py
449
4.125
4
import string def remove_punctuation(word): """ Return the given word without any punctuation: >>> remove_punctuation("that's cool") 'thatscool' """ return "".join([c for c in word if c in string.ascii_letters]) def save_anagram_sets(sets, output_file): """ Save the given list of anagram_sets to the specified file or file-like object. """ for s in sets: output_file.write(",".join(s) + "\n")
true
5d8b5f6d8436b68596e79fd29672031d4e0fbd03
kwstu/Algorithms-and-Data-Structures
/BubbleSort.py
443
4.15625
4
def bubble_sort(arr): # Go over every element (arranged backwards) for n in range(len(arr)-1,0,-1): # For -1 each time beacuse each loop an elemnt will be set in position. for k in range(n): # Check with the rest of the unset elements if they are greater than one another if so, switch if arr[k]>arr[k+1]: temp = arr[k] arr[k] = arr[k+1] arr[k+1] = temp
true
c608d17aeb079332cf51be22647352ce2abc5085
titanlien/workshop
/task04/convert.py
1,167
4.15625
4
#!/usr/bin/env python3 import argparse """https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html""" ROMAN_NUMERALS = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def int_to_roman_num(_int: int) -> str: """Convert a integer to a Roman numerals :param _int: the digital number """ if (not isinstance(_int, int)): raise TypeError("input int must be of type int") return_list = [] keeper = _int for integer, numeral in ROMAN_NUMERALS: quotient, keeper = divmod(keeper, integer) return_list.append(quotient * numeral) return ''.join(return_list) if __name__ == "__main__": parser = argparse.ArgumentParser(description="converts integer numbers into Roman numbers") parser.add_argument( "integer", metavar="N", type=int, choices=range(1, 999999), help="an natural number for webapp size, [1-9999]", ) args = parser.parse_args() print (int_to_roman_num(args.integer))
true
06b8339073dff3c0e3207154c9a1277f63202956
davidygp/Project_Euler
/python/prob4.py
893
4.34375
4
""" Problem 4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def find_max_palin_product() -> int: """ Find the largest palindrome made from the product of two 3-digit numbers """ max_palin_product = 0 for _, val1 in enumerate(range(100, 1000), 1): for _, val2 in enumerate(range(100, 1000), 1): if val1 > val2: product = str(val1 * val2) reverse_product = "".join(list(product)[::-1]) if product == reverse_product and int(product) > max_palin_product: max_palin_product = int(product) return max_palin_product if __name__ == "__main__": print("Ans is %s" % ( find_max_palin_product() ) ) # 9066909
true
dd37b3f9e28b6c26000a9c94f1883c647708b3ae
razvitesting/Automation-Testing
/mylist.py
206
4.125
4
mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) print(mylist[0]) # prints 1 print(mylist[1]) # prints 2 print(mylist[2]) # prints 3 # prints out 1,2,3 for x in mylist: print(x)
true
044be8776e8a959acbac43836290556e632b3e99
milindukey/Python
/Beginners/control loop.py
1,022
4.375
4
largestNumber = -99999999 counter = 0 number = int(input("Enter a number or type -1 to end program: ")) while number != -1: if number == -1: continue counter += 1 if number > largestNumber: largestNumber = number number = int(input("Enter a number or type -1 to end program: ")) if counter: print("The largest number is", largestNumber) else: print("You haven't entered any number.") #Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters "chupacabra" as the secret exit word, #in which case the message "You've successfully left the loop." should be printed to the screen, and the loop should terminate. #Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement. while True : word = input("You're stuck in an infinite loop. Enter secret word to exit the loop ") if word == "chupacabra" : break print("You've successfully left the loop.")
true
4b41f7f1a744e6820d77049da3443faadacaa9a6
Abinaya3198/shivanya
/f4.py
211
4.34375
4
al = input("enter the character : ") if((al >= 'a' and al <= 'z') or (al >= 'A' and al <= 'Z')): print("The Given Character ", ch, "is an Alphabet") elif(al == '?'): print("no") else: print("not an alphabet")
true
5f12ff4b364897d99f9a9ac78243f1ad19907479
jewellwk/sample-code
/Python/Cartesian Distance/Methods.py
1,132
4.25
4
#Compute the Cartesian distance between 2 points with coordinates (x1,y1) and (x2,y2) = sqrt((x2-x1)^2+(y2-y1)^2)) import math def solveCart(): x1 = int(input("Enter a value for x1: ")) y1 = int(input("Enter a value for y1: ")) x2 = int(input("Enter a vlaue for x2: ")) y2 = int(input("Enter a value for y2: ")) cart = math.sqrt((x2-x1)**2 + (y2-y1)**2) print(cart) def findCart(x1,y1,x2,y2): cart = math.sqrt((x2-x1)**2 + (y2-y1)**2) return(cart) def distance (x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) print(result) #python methods can return multiple values (tuple) def getInput(): x1 = int(input("Enter a value for x1: ")) y1 = int(input("Enter a value for y1: ")) x2 = int(input("Enter a vlaue for x2: ")) y2 = int(input("Enter a value for y2: ")) return x1, y1, x2, y2 def main(): # solveCart() x1 = int(input("Enter a value for x1: ")) y1 = int(input("Enter a value for y1: ")) x2 = int(input("Enter a vlaue for x2: ")) y2 = int(input("Enter a value for y2: ")) print(findCart(x1,y1,x2,y2)) if __name__ == "__main__": main()
false
41801fad4b3a2693ff4dbf696e7e5fa6e86c9dfc
ignaciomgy/python
/Tests/LambdaYmapYfilter.py
774
4.21875
4
#MAP mapea una funcion definida sobre un conjunto de objetos #FILTER aplica en una funcion sobre un conjunto y los filtra por la funcion aplicada #ej defino las funciones a mapear y filtrar def cuadrado(a): return a**2 def pares(a): return a%2==0 numeros = [1,2,3,4,5,6] #pongo dentro de una lista el resultado para visualizarlo #mapeo el cuadrado de cada elemento list(map(cuadrado, numeros)) #filtro por numeros pares list(filter(pares, numeros)) #LAMBDA es una expresion para definir una sola vez una funcion sin nombres #EJ list(map(lambda num:num**2, [1,2,3,4,5])) list(filter(lambda a:a%2==0, [1,2,3,4,5,6])) list(map(lambda a:a[0], ['Juan', 'Paco', 'Pedro'])) #Reverse de cada string en la lista list(map(lambda a:a[::-1], ['Juan', 'Paco', 'Pedro']))
false
5fbc21600fc9ea53a5e16fa3a00389efecc8be91
nitin-cherian/LifeLongLearning
/Web_Development_Python/RealPython/flask-blog/sql.py
684
4.125
4
# sql.py - Create a sqlite3 table and populate it with data # import sqlite3 library import sqlite3 # create a new database if the database already does not exist with sqlite3.connect("blog.db") as connection: # get a cursor object to execute sql commands c = connection.cursor() # create the table c.execute("CREATE TABLE posts(title TEXT, post TEXT)") # insert dummy data into the table c.execute('INSERT INTO posts VALUES("Good", "I\'am good")') c.execute('INSERT INTO posts VALUES("Well", "I\'am well")') c.execute('INSERT INTO posts VALUES("Excellent", "I\'am excellent")') c.execute('INSERT INTO posts VALUES("Okay", "I\'am good")')
true
b70018a393d272324b542a0d6bc40ce0e1a5a23e
nitin-cherian/LifeLongLearning
/Python/Experiments/ITERATORS/Polyglot.Ninja/why_iterables.py
494
4.75
5
# why_iterables.py print(""" Iterator behaves like an iterable in that it implements the __iter__ method. Then why do we need iterables? When StopIteration is raised from an iterator, there is no way to iterator over the iterator again, because iterator maintains the state and return self when iter is invoked on it. If we iterate over iterables, a fresh instance of iterator is returned which can be used to iterate again. This is what happens in the case of iterables like 'list' """)
true
83b8306a533237034ce55d980ee49b44d9ba0f78
nitin-cherian/LifeLongLearning
/Python/Experiments/ITERATORS/Polyglot.Ninja/iterators_should_be_iterable.py
2,400
4.40625
4
# iterators_should_be_iterable print(''' According to the official doc: ********* Iterators should implement the __iter__ method that returns the iterator object itself, so every iterator is also iterable and may be used in most places where other iterables are accepted. ********* {code} class HundredIterator: def __init__(self): self.__int = 0 def __next__(self): self.__int += 1 if self.__int > 100: raise StopIteration return self.__int class HundredIterable: def __iter__(self): return HundredIterator() hundred = HundredIterable() for i in hundred: print(i) hundredIter = HundredIterator() print() for i in hundredIter: print(i) {code} ''') class HundredIterator: def __init__(self): self.__int = 0 def __next__(self): self.__int += 1 if self.__int > 100: raise StopIteration return self.__int class HundredIterable: def __iter__(self): return HundredIterator() hundred = HundredIterable() for i in hundred: print(i) hundredIter = HundredIterator() print() # for i in hundredIter: # print(i) print("""Since the iterator has not implemented an __iter__ method, the iterator above is not iterable and a for loop cannot be used on the iterator. To fix this issue, implement a __iter__ method on the iterator object, returning itself like so:. {code} class HundredIterator: def __init__(self): self.__int = 0 def __iter__(self): return self def __next__(self): self.__int += 1 if self.__int > 100: raise StopIteration return self.__int class HundredIterable: def __iter__(self): return HundredIterator() hundred = HundredIterable() for i in hundred: print(i) print() hundredIter = HundredIterator() for i in hundredIter: print(i) {code} """) class HundredIterator: def __init__(self): self.__int = 0 def __iter__(self): return self def __next__(self): self.__int += 1 if self.__int > 100: raise StopIteration return self.__int class HundredIterable: def __iter__(self): return HundredIterator() hundred = HundredIterable() for i in hundred: print(i) print() hundredIter = HundredIterator() for i in hundredIter: print(i)
true
d0c3eee3504d0e0fb919e97c9396080bb70719b9
indra-singh/Python
/prime_number.py
350
4.125
4
#Write a program to print if a number is a prime number * n=int(input("Enter lower number :")) m=int(input("Enter upper number :")) print("Prime numbers between",n,"and",m,"are:") for num in range(n,m+1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)
true
d71afbf08a4088e3770dc46957e7b9e45a6d3e03
aniGevorgyan/python
/math_util.py
1,194
4.1875
4
#!/usr/bin/python # 1. Math simple actions """ :input a, b :output: a+b, a-b, a*b, a/b """ def mathActions(a, b): add = a + b minus = a - b mult = a * b div = a / b return ('Addition is ' + str(add), 'Subtraction is ' + str(minus), 'Multiplication ' + str(mult), 'Division is ' + str(div)) # 2. Summary """ :input numbers list :output: summary of numbers """ def sum(*a): s = 0 for i in a: s += int(i) return s # 3. Power of number """ :input a, b :output: pow(a, b) """ def myPower(a, b): p=1 for i in range(b): p*=a return p # 4. Factorial of number """ :input a :output: a! """ def myFactorial(a): b=1 for i in range(1,a+1): b=b*i return b # 5. Fibonacci sequence """ :input number of Fibonacci sequence :output: list of numbers from Fibonacci sequence """ def myFibonacci(a): list = [] for i in range(a): if (i == 0 or i == 1): list.append(i) else: list.append(list[i - 1] + list[i - 2]) return list def main(): print('\n'.join(mathActions(10, 5))) print(sum(1, 3, '5', 6)) print(myPower(2,5)) print(myFactorial(5)) print(myFibonacci(20)) if __name__ == "__main__": main()
false
4c7173d644078932261cf2f33aa568baf85671f1
imaaduddin/TreeHouse-Data-Structures-And-Algorithms
/recursion.py
297
4.125
4
# def sum(numbers): # total = 0 # for number in numbers: # total+= number # return total # print(sum([1, 2, 3, 4, 5])) # Recursive Function def sum(numbers): if not numbers: return 0 remaining_sum = sum(numbers[1:]) return numbers[0] + remaining_sum print(sum([1, 2, 7, 9]))
true
88891cba26521787b2d7eeecd1f2e558baf8f0fd
orhanyagizer/Python-Code-Challange
/count_of_wovels_constants.py
549
4.3125
4
#Write a Python code that counts how many vowels and constants a string has that a user entered. vowel_list = [] constant_list = [] word = input("Please enter a word: ").lower() for i in word: if i in set("aeiou"): vowel_list.append(i) count_vowel = len(vowel_list) else: constant_list.append(i) count_constant = len(constant_list) print(f"'{word}'\nVowels: {vowel_list}. The number of vowels is {count_vowel}.\nConstants: {constant_list}. The number of constants is {count_constant}.")
true
541d39fe2f6ef9cc7f86284554fc10a7fe0d7678
JamesMcPeek/Python-100-Days
/Day 2.py
342
4.125
4
print("Welcome to the tip calculator!") billTotal = float(input("What is the total bill? ")) percTip = int(input("What percentage tip would you like to give? ")) people = int(input("How many people will split the bill? ")) results = round((billTotal * (1 + (percTip / 100))) / people,2) print("Each person should pay: " + "$" + str(results))
true
caf58ea2197a68273d5e5a8a7c2b85925ed42bb4
Lucas-JS/Python_GeekUni
/loop_for.py
1,107
4.21875
4
""" Loop for Utilizamos loops para iterar sobre sequencias ou sobre valores iteráveis Exemplos de iteráveis: - String nome = 'John Wayne' - Lista lista = [1, 3, 5, 7, 9] - Range numeros = range(1, 10) """ nome = 'John Wayne' lista = [1, 3, 5, 7, 9] numeros = range(1, 10) # Exemplo de for 1 (Iterando em uma string) for letra in nome: print(letra) # Exemplo de for 2 (Iterando sobre uma lista) for numero in lista: print(numero) # Exemplo de for 3 (Iterando sobre um range) """ range = (valor_inicial, valor_final) Obs: o valor final não é incluso """ for numero in range(1, 10): print(numero) # ========================= OUTROS EXEMPLOS ========================= for tupla in enumerate(nome): print(tupla) for _, valor in enumerate(nome): print(valor, end=' ') qtd = int(input('Quantas vezes esse loop deve rodar? ')) soma = 0 for n in range(1, qtd+1): num = int(input(f'Informe o valor {n}/{qtd}: ')) soma += num print(f'A soma é de: {soma}') for _ in range(3): for num in range(1, 11): print('\U0001F480' * num)
false
7419e55dcfacf0eab400524d1fd3cc1cbe5f48c6
srajamohan1989/aquaman
/StringSlicer.py
392
4.59375
5
#Given a string of odd length greater 7, return a string made of the # middle three chars of a given String def strslicer(str): if(len(str)<=7): print("Enter string with length greater than 7") else: middleindex= int(len(str)/2) print(text[middleindex-1:middleindex+2]) text=input("Enter a string of lenght odd and greater than 7: ") strslicer(text)
true
2d2c2f7ea670a516a2716d73a92d986b8498325e
joshl26/tstcs_challenge_solutions
/chapter14_ex1.py
1,456
4.34375
4
# This question actually does not make much sense # because it is impossible to make a binary tree with no # leaf nodes! My mistake! class BinaryTree(): def __init__(self, value): self.key = value self.left_child = None self.right_child = None def insert_left(self, value): if self.left_child == None: self.left_child = BinaryTree(value) else: bin_tree = BinaryTree(value) bin_tree.left_child = self.left_child self.left_child = bin_tree def insert_right(self, value): if self.right_child == None: self.right_child = BinaryTree(value) else: bin_tree = BinaryTree(value) bin_tree.lef_child = self.right_child self.right_child = bin_tree def has_leaf_nodes(self, root): current = [root] next = [] while current: leaf = True for node in current: if node.left_child: next.append(node.left_child) leaf = True if node.right_child: next.append(node.right_child) leaf = True if leaf: return True current = next next = [] return False tree = BinaryTree(0) tree.insert_left(10) tree.insert_right(4) tree.insert_left(3) tree.insert_right(5) print(tree.has_leaf_nodes(tree))
true
8053fdd5fed3a656f5e52ae6e66af9a62976500d
jnyryan/rsa-encryption
/p8_is_prime.py
965
4.375
4
#!/usr/bin/env python """ Implement the following routine: Boolean fermat(Integer, Integer) such that fermat(x,t) will use Fermat's algorithm to determine if x is prime. REMEMBER Fermat's theorm asserts that if n is prime and 1<=a<=n, then a**n-1 is congruent to 1(mod n) """ import p5_expm import random def is_prime(n, t): for i in xrange(1, t): a = random.randint(2, n-1) #r = (a**n-1) % n r = p5_expm.expm(a, n-1, n) #print a , r if r != 1: return False return True ##################################################################### # Tests if __name__ == "__main__": print "Practical 8 - Verify a number is prime using Fermats Theorem" t = 30 print is_prime(3, t) print is_prime(4, t) print is_prime(5, t) print is_prime(6, t) print is_prime(7, t) print is_prime(11, t) print is_prime(13, t) print is_prime(101, t) print is_prime(294000, t) print is_prime(294001, t) print "Done."
true
efa2dcde8d6fddbcbea0ce5b0defa790986396ef
martinpeck/broken-python
/mathsquiz/mathsquiz-step3.py
1,822
4.15625
4
import random # this function will print a welcome message to the user def welcome_message(): print("Hello! I'm going to ask you 10 maths questions.") print("Let's see how many you can get right!") # this function will ask a maths question and return the points awarded (1 or 0) def ask_question(first_number, second_number): print("What is", first_number, "x", second_number) answer = input("Answer: ") correct_answer = first_number * second_number if int(answer) == correct_answer: print("Correct!") points_awarded = 1 else: print("Wrong! The correct answer was", correct_answer) points_awarded = 0 print("") return points_awarded # this function will look at the final scores and print the results def print_final_scores(final_score, max_possible_score): print("That's all the questions done. So...what was your score...?") print("You scored", score, "points out of a possible", max_possible_score) percentage = (score/max_possible_score)*100 if percentage < 50: print("You need to practice your maths!") elif percentage < 80: print("That's pretty good!") elif percentage < 100: print("You did really well! Try and get 10 out of 10 next time!") elif percentage == 100: print("Wow! What a maths star you are!! I'm impressed!") # display welcome message welcome_message() # set the score to zero and the number of questions to 10 score = 0 number_of_questions = 10 # ask questions for x in range(1,number_of_questions + 1): print("Question", x) first_number = random.randint(2,12) second_number = random.randint(2,12) score = score + ask_question(first_number,second_number) # print the final scores print_final_scores(score, number_of_questions)
true
b66bf8a200e19fe87eb82eaf0667bca53f7fc8c3
sumitsrv121/parctice2
/Excercise3.py
227
4.1875
4
def reverse_string(arr): new_list = [] for x in arr: new_list.append(x[::-1]) return new_list fruits = ['apple','mango','orange','pears','guava','pomegranate','raspberry pie'] print(reverse_string(fruits))
true
3d9abc8e44dccf5964b610e95be724b8964d2185
helaluddin92/Python-Challanges
/how to find average N number in python.py
283
4.25
4
# How to find average N number in python def avg_n(num): total_sum = 0 for n in range(num): number = int(input("Enter any number ")) total_sum += number avg = total_sum / num return avg result = avg_n(int(input("How many number?"))) print(result)
false
f8adcc2bdd040963560c5fa96ae48e219b9afe0f
aditmulyatama/pertemuan-6
/tuple.py
868
4.46875
4
# Tuple # Tuple adalah struktur data kolektif sekuensial yang tidak dapat diubah bawaan python # Tuple juga bisa menyimpan banyak tipe data yang berbeda dan mengizinkan duplikasi data this_is_tuple = ("oke", 100, 9.0, "oke") # print(this_is_tuple, " is type of ", type(this_is_tuple)) # Akses data di Tuple # print("First index is ", this_is_tuple[0]) # print("Last index is ", this_is_tuple[-1]) # print("Data after index 0 is ", this_is_tuple[1:]) # print("Data from index 3 is ", this_is_tuple[:3]) # print("Data between index 0 and 3 is ", this_is_tuple[1:3]) # Mengubah data di dalam tuple # this_is_tuple[2] = 10 # this_is_listed_tuple = list(this_is_tuple) # this_is_listed_tuple[2] = 10 # this_is_tuple = tuple(this_is_listed_tuple) # this_is_new_tuple = ("owo", "owi", "uwu") # print(this_is_tuple + this_is_new_tuple) a, b, c, d = this_is_tuple print(a)
false
12dda19350218d4ad3b9a4bbae13a72101bd44a5
Chithra-Lekha/pythonprogramming
/co5/co5-1.py
346
4.40625
4
# Write a python program to read a file line by line and store it into a list. l = list() f = open("program1.txt", "w") n = int(input("Enter the number of lines:")) for i in range(n): f.write(input("Enter some text:")+"\n") f.close() f = open("program1.txt", "r") for i in f: print(i) l.append(i[:-1]) f.close() print(l)
true
04aea542b7903d07b756e8a7287b720f8938a414
Chithra-Lekha/pythonprogramming
/co2-8.py
335
4.28125
4
list=[] n=int(input("enter the number of words in the list:")) for i in range(n): x=input("enter the word:") list.append(x) print(list) length=len(list[0]) temp=list[0] for i in list: if len(i) > length: length=len(i) temp=i print("the longest word is of length",length)
true
29a2c2a520dfad83d106dddf1ce3d7039ac437c6
dannymulligan/Project_Euler.net
/Prob_622/primes.py
1,962
4.125
4
#!/usr/bin/python import time ############################################################ def calculate_primes(limit, prime_table, prime_list): start_time = time.clock() if (limit>len(prime_table)): raise Exception("prime_table is too small ({} entries, need at least {})".format(len(prime_table), limit)) # Optimization to allow us to increment i by 2 for the rest of the algoritm i = 2 prime_list.append(i) j = i**2 while (j < limit): prime_table[j] = i j += i i = 3 while (i < (limit/2)): if (prime_table[i] == 1): prime_list.append(i) j = i**2 while (j < limit): prime_table[j] = i j += i i += 2 while (i < limit): if (prime_table[i] == 1): prime_list.append(i) i += 2 print("There are {:,} primes less than {:,}, calculated in {:.2f} seconds".format(len(prime_list), limit, (time.clock() - start_time))) ############################################################ def find_factors(n, prime_list): factors = [] for prime in prime_list: while (n % prime) == 0: factors.append(prime) n = n // prime if n == 1: return factors return factors ############################################################ def exp_by_sq(x,y,z): # return (x**y % z) if (y == 1): # y is 1 ans = x elif ((y % 2) == 0): # y is even ans = exp_by_sq(x,y/2,z) ans = (ans * ans) % z else: # l is odd ans = exp_by_sq(x,(y-1)/2,z) ans = (ans * ans) % z ans = (x * ans) % z return ans ############################################################ def factors(n): answer = [] while (prime_table[n] != 1): answer.append(prime_table[n]) n //= prime_table[n] answer.append(n) answer.sort() return answer
true
771c6cc674e6299c842a3e388bca7cc0f2252bf1
srinijadharani/DataStructuresLab
/02/02_c_delete_duplicate.py
594
4.3125
4
# 2c. Program to delete duplicate elements from an array # import the array module import array as arr array1 = arr.array("i", [1, 3, 6, 6, 8, 1, 9, 4, 3, 0, 4]) # initial array print("Initial array is:") for a in array1: print(a, end = ", ") # function to delete duplicate elements def delete_duplicate(array1): array2 = arr.array("i", []) for num in array1: if num not in array2: array2.append(num) print("\nArray after deleting the duplicate elements is:") for i in array2: print(i, end = ", ") delete_duplicate(array1)
true
1f81e477ec81fde2f1edcbf9a33c2a1580f8d8d6
srinijadharani/DataStructuresLab
/10/10_queue_implementation.py
746
4.15625
4
class Queue(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def display(self): print(self.items) qu = Queue() print("Is the queue empty?", qu.isEmpty()) qu.enqueue(3) qu.enqueue("Hey") qu.enqueue(9) qu.enqueue(10) qu.enqueue("DSP") qu.enqueue(87) print("The queue is after Enqueue: ") qu.display() print("Is the queue empty?", qu.isEmpty()) print("Dequeue element:", qu.dequeue()) print("The queue is after Dequeue: ") qu.display() print("Size of the queue is:", qu.size())
false
5a18eac0d8a069a3a7b38ce9281616e0027fc02c
srinijadharani/DataStructuresLab
/08/08_stack_implementation.py
1,029
4.28125
4
''' 08. Program to create a stack and perform various operations on it. ''' class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, items): self.items.append(items) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def display(self): print(self.items) st = Stack() print("Is the stack empty?", st.isEmpty()) print("Elements pushed into the stack are:") st.push(4) st.push("Hey") st.push(6) st.push(False) st.push(90) st.push("This is a stack element") st.push(87) st.push("LAST") st.display() print("Peek element is {}." .format(st.peek())) print("Is the stack empty?", st.isEmpty()) print("Popped element is {}." .format(st.pop())) print("Final stack elements are:") st.display() print("Size of the queue is:", st.size())
true
f1c8c835ca5b6efbb1e31eafc5ee2a5dc77fde26
mouayadd/TurtleArtDesign
/mydesignfunctions.py
584
4.34375
4
import turtle #brings in turtle bob = turtle.Turtle() #gives turtle the name bob def draw_star(size,color): #creates a function bob.penup #pulls the pen up to make sure no lines are drawn when moving bob.goto(10,15) bob.pendown #drops the pen in order to start drawing again angle=120 bob.fillcolor(color) bob.begin_fill() for side in range(5): #loop used as a part of the function to draw a star bob.forward(size) bob.right(angle) bob.forward(size) bob.right(72-angle) bob.end_fill() return
true
a36f69ae0e11a20138a5232983d13af4660476dc
BabyNaNaWang/myPythonProgram
/列表排序.py
722
4.25
4
import random #列表排序 nums = [1,34,5,90,80] '''nums.sort(reverse = True) print(nums)''' nums.reverse() print(nums) newNums = [100,20,18,39,90] #newNums.reverse() #倒置 #newNums.sort() #从小到大排序 newNums.sort(reverse = True) #从大到小排序 print(newNums) #列表的常见操作 #1、添加 insert names = ['he','she','his'] names.insert(0,'him') print(names) #2、添加append names1 = ['he', 'she', 'his'] names.append('hah') print(names1) # 3、extend names1.extend(names) print(names1) print(names) ss = random.sample(range(1,35),6) ss.sort() print(ss) ss.sort(reverse = True) print(ss) ss.reverse() print(ss) xiaBiao = 'hello' print(xiaBiao[::-1]) a = 10 b = 20 a,b = b,a print(a) print(b)
false
cafd46886bf1713a537458db19daa24dabd93bc5
BabyNaNaWang/myPythonProgram
/列表循环.py
343
4.125
4
names = ['gaga','didi','gana'] '''print(names[0]) print(names[1]) print(names[2]) for x in names: print(x)''' #查询是否数字在列表内 findFlag = 0 insertName = input('请输入名字:') for temp in names: if temp == insertName: findFlag = 1 break if findFlag ==1 : print('yes') else: print('no')
false
4b400c91a2d5c8c918c7af9c216fbd687c357751
andreylrr/PythonDeveloperHW5
/borndayforewer.py
1,053
4.5
4
""" МОДУЛЬ 2 Программа из 2-го дз Сначала пользователь вводит год рождения Пушкина, когда отвечает верно вводит день рождения Можно использовать свой вариант программы из предыдущего дз, мой вариант реализован ниже Задание: переписать код используя как минимум 1 функцию """ def birth_year(): year = input('Ввведите год рождения А.С.Пушкина:') while year != '1799': print("Не верно") year = input('Ввведите год рождения А.С.Пушкина:') return def birth_day(): day = input('Ввведите день рождения Пушкин?') while day != '6': print("Не верно") day = input('В какой день июня родился Пушкин?') print('Верно') return birth_year() birth_day()
false
5edebd8cdbebcb9ae782c6d8571b7e15f41a8da1
fm3ssias/python-exercices
/02_oddOrEven.py
529
4.15625
4
''' Objetivo: Mostrar pro usuário se o numero inserido é par ou impar Entrada: Um numero Saida: Se é impar ou par ''' numero = 1 while numero != 0 : numero = int(input("Digite um numero (0 para sair): ")) if numero == 0: break divPorQuatro = str(numero) if int(divPorQuatro[-2:])%4 == 0 or int(divPorQuatro[-2:]) == 00: print(f"O numero {numero} é divisivel por 4!") elif numero%2 == 0: print(f"O numero {numero} é par!") else: print(f"O numero {numero} é impar!")
false
a1b9bf680534dbbfbc310a822deb14f1bb4e2dad
prataprc/gist
/py/loop.py
657
4.65625
5
#! /usr/bin/python # Some examples using the looping constructs in python a = ['cat', 'dog', 'elephant'] x = 10 print type(x) for x in a : print x, type(x), len(x) b = 'hello \n world' for x in b : print x, type(x), len(x) # Dangerous iteration on a mutable sequence (list) # for x in a : # a.insert(1, x) # Dont do this ! # print a # To acheive the above mentioned purpose do the following for x in a[:] : # Now we taking a copy of the sequence a.insert(0, x) # you can safely do this ! print a # Using the range() function for x in range(10,100,30) : print x, else print "the loop normally exited"
true
a73736d32143141ee7a794e8dbee169441c640d1
TungstenRain/Python-conditionals_and_recursion
/koch_curve.py
1,357
4.4375
4
""" This module contains code from Think Python, 2nd Edition by Allen Downey http://thinkpython2.com This is to complete the exercises in Chapter 5: Conditionals and Recursion in Think Python 2 Note: Although this is saved in a .py file, code was run on an interpreter to get results Note: Using Python 3.8.5 """ import turtle def draw_koch_curve(t, order, x): """ Draw a Koch curve. t: Turtle order: the order of magnitude of the Koch curve x: integer length """ if order == 0: t.forward(x) else: for angle in [60, -120, 60, 0]: draw_koch_curve(t, order-1, x/3) t.left(angle) def draw_snowflake(t, order, x): """ Draw a snowflake using three Koch curves t: Turtle x: integer length """ for i in range(3): draw_koch_curve(t, order, x) t.rt(120) def user_input(): """ Prompt user to input the length for the Koch curve """ print("Welcome to drawing a Koch curve.\n") order = int(input("Please enter the order of magnitude for the Koch curve: ")) x = int(input("Please enter a length x: ")) # Instantiate the Turtle bob = turtle.Turtle() bob.hideturtle() draw_snowflake(bob, order, x) # Call the user prompt user_input() turtle.mainloop()
true
553dac4289f659e451c03900b34c0ea558605567
xxxxgrace/COMP1531-19T3
/Labs/lab03/19T3-cs1531-lab03/timetable.py
733
4.25
4
# Author: @abara15 (GitHub) from datetime import date, time, datetime def timetable(dates, times): ''' Generates a list of datetimes given a list of dates and a list of times. All possible combinations of date and time are contained within the result. The result is sorted in chronological order. For example, >>> timetable([date(2019,9,27), date(2019,9,30)], [time(14,10), time(10,30)]) [datetime(2019,9,27,10,30), datetime(2019,9,27,14,10), datetime(2019,9,30,10,30), datetime(2019,9,30,14,10)] ''' newList = [] for i in dates: for j in times: newList.append(datetime.combine(i, j)) sorted_dates = sorted(newList) return sorted_dates pass
true
a1b96498860d27c397fb2713cda40c85ada6b51a
sabu0912/reto3
/reto.py
1,965
4.21875
4
#CADA UNA DE LAS NOTAS while True: try: nota1 = int(input("Ingresa la primera nota : ")) print(f"La primera nota es :", (nota1)) nota2 = int(input("Ingresa la segunda nota : ")) print(f"La segunda nota es :", (nota2)) nota3 = int(input("Ingresa la tercera nota : ")) print(f"La tercera nota es :", (nota3)) nota4 = int(input("Ingresa la cuarta nota : ")) print(f"La cuarta nota es :", (nota4)) nota5 = int(input("Ingresa la quinta nota : ")) print(f"La quinta nota es :", (nota5)) break except Exception: print("El valor de la nota NO es numerico") lista_notas = [] lista_notas.append(nota1) lista_notas.append(nota2) lista_notas.append(nota3) lista_notas.append(nota4) lista_notas.append(nota5) lista_notas: [nota1,nota2,nota3,nota4,nota5] print(f"La lista de nota es : {lista_notas}") #NOTA DE MENOR A MAYOR lista_desordenada = lista_notas lista_desordenada.sort() print(f"La nota de menor a mayor es : {lista_desordenada}") #NOTA DE MAYOR A MENOR lista_al_reves = lista_desordenada[::-1] print(f"La nota de mayor a menor es : {lista_al_reves}") #NOTA PROMEDIO nota_promedio = nota1+nota2+nota3+nota4+nota5 // 5 print(f"La nota promedio es : {nota_promedio}") '''#NOTA MAYOR print(lista_notas) nota_mayor = lista_notas[0] for i in range(0,len(lista_notas)): if lista_notas[i]>nota_mayor: nota_mayor = lista_notas[i] print("La nota mayor es : ",nota_mayor) print("La posición que ocupa la nota es: ",lista_notas.index(nota_mayor)) #NOTA MENOR print(lista_notas) nota_menor = lista_notas[0] for i in range(0,len(lista_notas)): if lista_notas[i]<nota_menor: nota_menor = lista_notas[i] print("La nota menor es : ",nota_menor) print("La posición que ocupa la nota es: ",lista_notas.index(nota_menor)) #NOTA PROMEDIO print(lista_notas) suma = 0 for i in lista_notas: sum = i promedio = suma / i print("La nota promedio es :",nota_promedio)'''
false
2323b6570606fb1b7ad155680f0d77cbeaf5dac2
M01eg/algo_and_structures_python
/Lesson_1/3.py
596
4.125
4
''' Урок 1 Задание 3 По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки. ''' X1 = float(input("Введите X1: ")) X2 = float(input("Введите X2: ")) Y1 = float(input("Введите Y1: ")) Y2 = float(input("Введите Y2: ")) K = (Y2 - Y1) / (X2 - X1) B = Y2 - K * X2 K = round(K, 4) B = round(B, 4) print(f"Уравнение прямой по вашим точкам будет таким: y = {K}x + {B}")
false
30e901c77786c1803fa054cc36961361a43b68ca
Jenoe-Balote/ICS3U-Unit6-04-Python
/list_average.py
1,558
4.28125
4
#!/usr/bin/env python3 # Created by: Jenoe Balote # Created on June 2021 # This program determines the average of a 2D list # with limitations inputted by the user import random def calculate_average(number_list, rows, columns): # This function calculates the average # sum of numbers in list total = 0 for row_counter in number_list: for column_counter in row_counter: total += column_counter average = total / (rows * columns) return average def main(): # this function generates the random numbers in the list list_of_numbers = [] # input print("Let's average out some lists!") rows_string = str(input("How many rows would you like?: ")) columns_string = str(input("How many columns would you like?: ")) print("\nGenerating numbers...") print("") # process and output try: rows = int(rows_string) columns = int(columns_string) for loop_counter in range(0, rows): temp = [] for loop_counter in range(0, columns): random_number = random.randint(1, 50) temp.append(random_number) print("{0} ".format(random_number), end="") list_of_numbers.append(temp) print("") # call function(s) average = calculate_average(list_of_numbers, rows, columns) print("\nThe average is {}.".format(average)) except Exception: print("Invalid.") print("\nThanks for participating!") if __name__ == "__main__": main()
true
cfa3db9cd7599d1a15291c5d6c2f954ebc3080c6
arpitdixit445/Leetcode-30-day-challenge
/Day_11__Diameter_of_Binary_Tree.py
1,135
4.1875
4
''' Problem Statement -> Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example->Input: 1 / \ 2 3 / \ 4 5 Output : Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. ''' #Solution - Using DFS : Time O(n), Space O(log(n))[Recursion Stack] # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: arr = [] self.helper(root,arr) if not len(arr): return 0 return max(arr) def helper(self,root,arr): if root is None: return 0 left = self.helper(root.left,arr) right = self.helper(root.right,arr) arr.append(left+right) return max(left,right)+1
true
b95a6c6882907504cfa7442d906117bed63a04f8
hkkmalinda/python_simple_calculator
/simple_python_calculator.py
641
4.15625
4
# define functions def add(a,b): result = a + b print(f'{a} + {b} = {result}') def sub(a,b): result = a - b print(f'{a} - {b} = {result}') def mul(a,b): result = a * b print(f'{a} * {b} = {result}') def div(a,b): result = a / b print(f'{a} / {b} = {result}') #getting inputs a = int(input('Enter the first number : ')) b = int(input('Enter the second number : ')) op = input('Enter the operator number : ') # selecting which function to run via operator if op == '+': add(a,b) elif op == '-': sub(a,b) elif op == '*': mul(a,b) elif op == '/': div(a,b) else: print('Invalid Operator')
true
c43ebbe77c89e0e72019436179ee8fd22bdc2a50
CeciFerrari16/Esercizi-Python-1
/es31.py
1,924
4.21875
4
# Esercizio 31 ''' Fornisci la rappresentazione in binario di un numero decimale. Dopo aver acquisito il valore del Numero da trasformare, si esegue la divisione del numero per 2 e si calcola quoziente e resto. Il resto è la prima cifra della rappresentazione binaria. Si ripete il procedimento assegnando il quoziente ottenuto a Numero e ricalcolando la divisione per 2; la ripetizione prosegue mentre il quoziente ottenuto si mantiene diverso da zero. La rappresentazione binaria del numero decimale è costituita da cifre binarie ottenute come resti, lette in ordine inverso. Confronta poi il risultato con il valore ottenuto dalla funzione predefinita del linguaggio per convertire un numero decimale in binario. ''' import math num = int(input("Qual è il numero decimale da trasformare? ")) n = num binario = [] #lista con tutti i resti delle divisioni quoziente = 1 while True: if num < 1 or quoziente < 1: break elif quoziente <= num: math.trunc(num)/ math.trunc(quoziente) quoziente = num / 2 resto = math.trunc(num)%2 binario.append(resto) num = quoziente else: math.trunc(num)/ math.trunc(quoziente) num = quoziente / 2 resto = math.trunc(quoziente)%2 binario.append(resto) quoziente = num binario.reverse() print(binario) # controllo bin = int(input("Puoi riscivere il numero binario che è risultato? ")) controllo = int(str(bin), base=2) #numero decimale if n == controllo: print("Il programma funzionaaa!!") print("Il numero è", bin) else: print("I numeri non coincidono, qualcosa è andato storto!") # Ho cambiato la funzione round() con trunc() # Funziona perchè la funzione trunc() tronca tutta la parte decimale del numero e non lo approssima mai per eccesso # Invece la funzione round() approssimava i numeri come "37.5" a "38" e questo genera un errore nel calcolo del resto
false
df40f13d105229bd08bb69536e0a1c05a606acfa
Sudani-Coder/python
/Rock Paper Scissor Game/index.py
2,249
4.5
4
## project11 # Rock - Paper - Scissor "Game" import random print( """ Winning Rules: \n "Rock vs paper => paper wins" \n "Rock vs scissor => Rock wins" \n "paper vs scissor => scissor wins \n """ ) # Step 1: Conditions for the User while True: print("\nEnter Choice 1.Rock 2.Paper 3.Scissor", end = "\n\n") user_choice = int(input("User Turn --> ")) while user_choice > 3 or user_choice < 1: user_choice = int(input("\nEnter valid input --> ")) if user_choice == 1: user_choice_name = "Rock" elif user_choice == 2: user_choice_name = "Paper" else: user_choice_name = "Scissor" print("\nUser choice is : {}".format(user_choice_name), end = "\n\n") print("It's computer turn --> ", end = "\n\n") # Step 2: Conditions for the Computer computer_choice = random.randint(1, 3) while computer_choice == user_choice: computer_choice = random.randint(1, 3) if computer_choice == 1: computer_choice_name = "Rock" elif computer_choice == 2: computer_choice_name = "Paper" else: computer_choice_name = "Scissor" print("Computer choice is : {}".format(computer_choice_name), end = "\n\n") print(user_choice_name + " VS " + computer_choice_name, end = "\n\n") # Step 3: Condition of Winning !!! if ((user_choice == 1 and computer_choice == 2) or (user_choice == 2 and computer_choice == 1)): print("paper wins => ", end = "") result = "Paper" elif ((user_choice == 2 and computer_choice == 3) or (user_choice == 3 and computer_choice == 2)): print("scissor wins => ", end = "") result = "Scissor" else: print("rock wins => ", end = "") result = "Rock" # Step 4: Printing the Winner if result == user_choice_name: print("<** User wins **>") else: print("<** Computer wins **>") print("\nDo you want to play again? (Y/N):", end=" ") answer = input() print("\n\n========================================================================================\n") # if user input n or N then Break if answer == "n" or answer == "N": break print("\nThanks for playing", end = "\n\n")
false
72080afb57f4c2e02c0a15b7a5ba49fe378cb50b
Sudani-Coder/python
/Silly sentences/silly.py
1,050
4.15625
4
import random import words def silly_string(nouns, verbs, templates): # Choose a random template. template = random.choice(templates) # We'll append strings into this list for output. output = [] # Keep track of where in the template string we are. index = 0 # Add a while loop here. while index < len(template): if template[index:index+8] == '{{noun}}': # Add a random noun to the output. output.append(random.choice(nouns)) index += 8 elif template[index:index+8] == '{{verb}}': # Add a random verb to the output. output.append(random.choice(verbs)) index += 8 else: # Copy a character to the output. output.append(template[index]) index += 1 # After the loop has finished, join the output and return it. # Join the output into a single string. output = ''.join(output) if __name__ == '__main__': print(silly_string(words.nouns, words.verbs, words.templates))
true
65cf2845d8c237a4b53f0d3091269a33557a57f2
Sudani-Coder/python
/User Input/index.py
286
4.125
4
fName = input("\nwhat is your first name? ").strip().capitalize() mName = input("\nwhat is your middle name? ").strip().capitalize() lName = input("\nwhat is your last name? ").strip().capitalize() print(f"\nHello World, My name is {fName:s} {mName:.1s} {lName:s}, Happy to see you.")
true
8a4892bb57e06dc99f908e82e6ea9adc470c0bb8
Sudani-Coder/python
/Removing Vowels/index.py
279
4.375
4
## Project: 2 # Removing Vowels vowels = ("a", "e", "i", "o", "u") message = input("Enter the message: ").lower() new_message = "" for letters in message: if letters not in vowels: new_message += letters print("Message without vowels is : {} ".format(new_message))
true
77089197928b24182560f982d74cf2b2262987a9
natp75/homework_4
/homework_4/homework_4_3.py
360
4.125
4
#Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. # Необходимо решить задание в одну строку. #Подсказка: использовать функцию range() и генератор. result = [x for x in range(20,240) if ((x % 20==0) or (x % 21==0))] print(result)
false
c0327f753e1cbd8d3bba93aa38b75a1d976e9056
jcrock7723/Most-Common-Character---Python
/Pg368_#10_mod.py
1,216
4.40625
4
# Unit 8, pg368, #10 # This function displays the character that appears the most # frequently in the sring. If several characters have the same # highest frequency, it displays the first character with that frequency def main(): count=[0]*26 letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' index = 0 frequent = 0 # Recieve user input user_string = input('Enter a string statement: ') for ch in user_string: ch = ch.upper() # Determing which letter this character is # in your substring index = letters.find(ch) if index >= 0: print(index) print(count) dummy=input('press any key...') # increase the counting array for this letter count[index] += 1 # Find out where it lives for i in range(len(count)): if count[i] > count[frequent]: frequent = i print('The character that appears most frequently' \ ' in the string is ', letters[frequent], '.', \ sep='') print('It appears', count[frequent], 'times within your statement.') # Call the main function main()
true
7d19936ea344f55344b7e4a8e18e4efbf5e84938
ceadoor/HacktoberFest-2020
/Python/tints-GuessGame.py
447
4.28125
4
# PROGRAM-NAME : Guess Game # By Tintu # PROGRAM-CODE : import random def guess(val,x): while ((val-x)!=0): dif=val-x if(dif>0): print("Number is greater than guessed") else: print("Number is less than guessed") x=int(input("Gues another number: ")) print("You guessed right!!!") val=int(random.randrange(1,1000)) x=int(input("Guess a number between 1 & 1000: ")) if (val==x): print("You guessed right!!!") else: guess(val,x)
true
64b7feefea06bb59afba2ebdb4598276479eb0cc
saravananprakash1997/Ranking-and-Rewarding-Project-using-Python-intermediate-
/Intermediate_Project.py
1,878
4.21875
4
#intermediate Python Project #get the total marks of the students #Rank them and highlight the top three #Reward the top three with 1000$, 500$ and 250$ respectively import operator def student_details(): print() number_of_students=int(input("Enter the number of students :")) students_records={} for x in range(1,number_of_students+1): name=input('Enter the name of the Student '+str(x)+" :") marks=int(input("enter the marks of the students:")) students_records[name]=marks print() return students_records def rank_the_students(students_records): print() sorted_students_records=sorted(student_records.items(),key=operator.itemgetter(1),reverse=True) print(sorted_students_records) print("{} has been ranked first scoring {} marks".format(sorted_students_records[0][0],sorted_students_records[0][1])) print("{} has been ranked first scoring {} marks".format(sorted_students_records[1][0],sorted_students_records[1][1])) print("{} has been ranked first scoring {} marks".format(sorted_students_records[2][0],sorted_students_records[2][1])) print() return sorted_students_records def reward_students(sorted_student_records,rewards): print() print("Congrats {} for scoring {} marks.You have been rewarded {}$ ".format(sorted_students_records[0][0],sorted_students_records[0][1],rewards[0])) print("Congrats {} for scoring {} marks.You have been rewarded {}$ ".format(sorted_students_records[1][0],sorted_students_records[1][1],rewards[1])) print("Congrats {} for scoring {} marks.You have been rewarded {}$ ".format(sorted_students_records[2][0],sorted_students_records[2][1],rewards[2])) print() print() rewards=(1000,500,250) students_records=student_details() sorted_students_records=rank_the_students(students_records) reward_students(sorted_students_records,rewards)
true
820621fd61547622d1e3208d595eeae3b2edd989
eugurlubaylar/Python_Kod_Ornekleri
/Noktalama İşaretlerini kaldırma.py
392
4.40625
4
# Program to all punctuation from the string provided by the user # define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # take input from the user my_str = input("Enter a string: ") # remove punctuation from the string no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # display the unpunctuated string print(no_punct)
true
78ac7f08733f7501d3f4bdf3dfbe98c732cc25db
PatrickArthur/Python_Calculator
/python_calc.py
954
4.125
4
#Calculator in Python# import math print(" Weclome to Patrick Arthur's Calculator: V1") print(" A) Add") print(" B) Sub") print(" C) Mul") print(" D) Div") choice = raw_input("Pick your choice: ") if choice == "A": print("add numbers!") x= input("First Number: ") y= input("Second Number: ") print("Your answer is: "+str(x+y)) raw_input("Press <ENTER> to exit") if choice == "B": print("subtract numbers!") x= input("First Number: ") y= input("Second Number: ") print("Your answer is: "+str(x-y)) raw_input("Press <ENTER> to exit") if choice == "C": print("multiply numbers!") x= input("First Number: ") y= input("Second Number: ") print("Your answer is: "+str(x*y)) raw_input("Press <ENTER> to exit") if choice == "D": print("divide numbers!") x= input("First Number: ") y= input("Second Number: ") print("Your answer is: "+str(x/y)) raw_input("Press <ENTER> to exit")
false
9a173033eab1402ceb4ee544aa9d5b55f683d3f6
freeglader/python_repo
/automate_the_boring_stuff/ch3_functions/ch3_number_guessing_game.py
2,274
4.3125
4
#TODO: The number guessing game will look something like the following: #TODO: I am thinking of a number between 1 and 20. Take a guess. (Guess is too low, guess is too high) #? My implementation, done before checking solution in the book: import random print('Let\'s play a game. I will pick a number between 1 and 20, and you will get 5 guesses. Ready?') response = input() def newGame(): if response.lower() == 'yes': answer = random.randint(1,20) count = 1 while count <= 5: guess = int(input('Guess number ' + str(count) + ': ')) count += 1 if guess == answer: print('Wow, you won! Great job! The answer was ' + str(answer)) break elif guess < answer: print('Too low! Try again.') continue elif guess > answer: print('Too high! Try again.') continue if count >= 5: print('Sorry, out of guesses! The answer was ' + str(answer)) else: print('Thanks for playing!') elif response.lower() == 'no': print('Okay :( bye!') else: print('Please answer either yes or no.') #? Couldn't figure out how to make this loop back to the start of the if statement correctly newGame() #* The book's implementation: import random secretNumber = random.randint(1,20) print('I\'m thinking of a number between 1 and 20.') #* Allow 6 guesses for guessesTaken in range(1,7): #* This makes the program loop through 6 times, and stops the loop when guessesTaken reaches 6. print('Take a guess!\n') guess = int(input()) if guess < secretNumber: print('Sorry, your guess was too low.') elif guess > secretNumber: print('Sorry, your guess was too high.') else: break #* If the guess ends up being the correct answer, it breaks out of the loop & sends execution to the next line if guess == secretNumber: #! You have to put this in an if loop, because there is also another way the loop could stop: running out of tries. print('You got it! You got it in ' + str(guessesTaken) + ' tries!') else: print('Sorry, you ran out of tries. The number was ' + str(secretNumber))
true
7d215d4ebde45fd672ee4c55e86a6e8f6fba0648
Vivek-Muruganantham/Project-Euler
/Python Project Euler/Python Project Euler/Functions/PrimeNumber.py
697
4.3125
4
#Returns true if the number is prime else false import math def IsPrime(number): # If number is 2, 3, 5 or 7, return IsPrime as true if(number == 2 or number == 3 or number == 5 or number == 7): return True # If number is divisible by 2,3,5 or 7, return IsPrime as False elif(number % 2 == 0 or number % 3 == 0 or number % 5 == 0 or number % 7 == 0): return False else: # It is enough to check till square root of number N = int(math.sqrt(number)) # Since we have verified above till 7 and we are checking only odd numbers for i in range(11,N,2): if (number % i == 0): return False return True
true
0d31376a8bd4c7fbec9c225637fdfaded0f0f490
pipo411/AT06_API_Testing
/ArielGonzales/python/session2/DaysInMonth.py
699
4.15625
4
def days_in_month(month): months = { "January": 31, "February": 28, "March": 31, "April": 30, "May": 31, "June": 30, "July": 31, "August": 30, "September": 31, "October": 30, "November": 31, "December": 30 } if (month not in months): return None else: return months.get(month) print("May has", days_in_month("May"), "days") print("September has", days_in_month("September"), "days") print("December has", days_in_month("December")) print("February has", days_in_month("February"), "days") print("April has", days_in_month("April"), "days") print(days_in_month("Duck"))
false
c86e88ee54016d83cd5b25a0f1a58758d6c5e2ab
ezmiller/algorithms
/mergesort/python/mergesort.py
988
4.21875
4
# Merge sort # # How it works: # 1. Divide the unsorted list into n sublists, each containing 1 element # 2. Repeatedly merge sublists to produce new sorted sublists until there # is only 1 sublist remaining. This will be the sorted list. def merge(l, r): # print('merge():: l => {} r => {}'.format(l,r)) l_idx = 0 r_idx = 0 merged = [] while l_idx < len(l) and r_idx < len(r): if l[l_idx] > r[r_idx]: merged.append(r[r_idx]) r_idx += 1 else: merged.append(l[l_idx]) l_idx += 1 while l_idx < len(l): merged.append(l[l_idx]) l_idx += 1 while r_idx < len(r): merged.append(r[r_idx]) r_idx += 1 return merged def merge_sort(list): # print('merge_sort()::list {}'.format(list)) if len(list) == 1: return list mid = int(len(list) / 2) left = list[:mid] right = list[mid:] return merge(merge_sort(left), merge_sort(right))
true
def7dc7dc7df68acab39702c78cba860f8f1970e
adeelnasimsyed/Interview-Prep
/countTriplets.py
743
4.28125
4
''' In an array check how many triplets exist of a common ration R example: ratio: 4 [1,4,16,64] triplets: [1,4,16] and [4,16,64] returns 2 method: read array in reverse order have two dicts, one for each number and one for each pair that meet criteria if a num*ratio exists in dic that means we have a pair if num*ratio exists in dicPair that means we have num, and the pair in dicPair ''' def countTriplets(arr, ratio): dic = {} dicPairs = {} count = 0 for num in reversed(arr): if num*ratio in dicPairs: count += dicPairs[num*ratio] if num*ratio in dic: dicPairs[num] = dicPairs.get(num, 0) + dic[num*ratio] dic[num] = dic.get(num, 0) + 1 print(count) arr = [1, 5, 5, 25, 125] countTriplets(arr, 5)
true
79ff9476ded6d3eb48bb8a98389a16c84b163510
1131057908/-1
/函数.py
2,624
4.125
4
""" 座右铭:将来的你一定会感激现在拼命的自己 @project:7-23 @author:Mr.Zhang @file:函数.PY @ide:PyCharm @time:2018-07-23 09:05:17 """ #函数:为什么使用函数?因为没有函数的编程只是在单纯的写代码逻辑,如果想重用代码逻辑,只能够copy一份代码。但是一旦使用函数,就可以将一些相同的代码逻辑封装起来,这样可以提高代码的重复使用率,提升开发效率。 #第一步:声明一个函数,在函数里面写逻辑代码 #第二步:调用函数,执行编写的逻辑代码 # print('今天是周一') # print('明天是周二') # print('后天是周三') # # print('今天是周一') # print('明天是周二') # print('后天是周三') # # print('今天是周一') # print('明天是周二') # print('后天是周三') #怎么声明一个函数? #def 声明函数的关键字,shuchu,函数名(可以自定义的),():用于定义函数的参数,如果没有内容就表示该函数没有参数。:下面的东西,要封装的代码逻辑。 #1.声明一个无返回值,无参数的函数 def shuchu(): print('今天是周一') print('明天是周二') print('后天是周三') #调用函数,函数名+括号 shuchu() shuchu() shuchu() #2.声明一个有返回值,无参数的函数 #一个函数为什么要有返回值:因为一个函数想要最终的执行结果,后面的程序才能根据这个执行结果进行其他的操作。 def cheng(): c = 10 d = 20 e = c*d return e res=cheng() print(res) f = res * 10 print(f) #3.声明一个无返回值,有参数的函数 #a,b叫做形式参数,简称形参 def chufa(a,b): c = a/b print(c) #10,2.5称之为实际参数,简称实参。、实参想当于给a,b这两个形参赋值,a=10,b=2.5。 chufa(10,2.5) chufa(10,4) #4.有返回值,有参数的函数 def jian(a,b): c = a-b return c res=jian(8,5) print(res) res1=res+10 print(res1) #return关键字的作用。 #1.用于返回函数的执行结果。 #2.用于结束当前代码的执行。使用return关键结束代码执行的时候,return必须位于函数内部。区别于break。 def test(): for x in range(1,11): if x==4: return else: print('======',x) test() def func2(): for i in range(1,11): if i % 2 == 0: break #到第一个符合条件的情况下就停止。不输出符合条件的语句,并停止。 print(i) func2()
false
2d1e425c878658733f1d32f2e5edcdbcc39e47fd
ericgreveson/projecteuler
/p_020_029/problem23.py
888
4.1875
4
from factor_tools import compute_factors def main(): """ Entry point """ # Compute set of all abundant numbers up to the limit we know all integers above can be # expressed as a sum of two abundant numbers sum_abundant_limit = 28123 abundant = {i for i in range(1, sum_abundant_limit) if sum(compute_factors(i)) > i} print(f"Found {len(abundant)} abundant numbers") # Now compute set of numbers which are a sum of two of the above sum_two_abundant = {i + j for i in abundant for j in abundant} print(f"Found {len(sum_two_abundant)} sum-two-abundant") # And compute the sum of all non-sum-two abundant numbers sum_non_sum_two_abundant = sum(i for i in range(1, sum_abundant_limit) if i not in sum_two_abundant) print(f"Total sum of non-sum-two-abundant numbers: {sum_non_sum_two_abundant}") if __name__ == "__main__": main()
true
de1c37645d58898828ec4d4b1ec85588065cf75e
The-Kernel-Panic/HackerRank-Solutions
/Algorithms/Day of the Programmer.py
1,241
4.375
4
#Practice > Algorithms > Implementation > Day of the Programmer #Julian -> after 1918 (leap year is divisible by 4) #Gregorian -> from 1919 #During 1918 feb starts from 14. #Jan + Mar + April + May + June + July + Aug = 215 def dayOfProgrammer(year): if year < 1917: if year % 4 == 0: #Leap Year day = 256 - (215 + 29) #Day Of Programmer always lies on the 256 day of the year. if day < 10: day = "0" + str(day) #To get the proper output format else: #Not a leap year day = 256 - (215 + 28) if day < 10: day = "0" + str(day) elif year >= 1919: if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): #Leap Year day = 256 - (215 + 29) if day < 10: day = "0" + str(day) else: #Not a leap year day = 256 - (215 + 28) if day < 10: day = "0" + str(day) elif year == 1918: day = 256 - (215 + 15) #1918 is not a leap year and feb has only 15 days. if day < 10: day = "0" + str(day) date = str(day) + ".09." + str(year) return date ''' For testing: year = 1918 print(dayOfProgrammer(year)) '''
false
159cdae23d6e3e19c73eb74eb39bdc8e42554574
gavinmcguigan/gav_euler_challenge_100
/Problem_59/XOR_Decryption.py
2,417
4.1875
4
from globs import * """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. """ def all_perms(n: list): a = None for x, y, z in permutations('abcdefghijklmnopqrstuvwxyz', 3): new_str = '' for b, i in enumerate(n): if b % 3 == 0: new_str += chr(i ^ ord(x)) if b % 3 == 1: new_str += chr(i ^ ord(y)) if b % 3 == 2: new_str += chr(i ^ ord(z)) if ' the ' in new_str: EULER_LOGGER.debug(f"Key: '{x}{y}{z}' - {new_str}") a = sum([ord(c) for c in new_str]) break return a def main(): with open("p059_cipher.txt", "r") as f: encrypted_ints = [int(y) for y in f.readline().split(',')] a = all_perms(encrypted_ints) return a if __name__ == '__main__': answer = main() show_answer(answer)
true
769836cb18a5f7bd6851f28792daebd0f561d5fb
aldzor/School-python-projects
/calculator.py
1,397
4.15625
4
# An even better calculator import math def asking(): loop = True while loop == True: givenNum = input("Give a number:") try: givenNum = int(givenNum) return givenNum loop = False except Exception: print("This input is invalid.") def operation(): loop = True while loop == True: operation = input("Please select something (1-8):") try: operation = int(operation) return operation loop = False except Exception: print("This input is invalid") print("Calculator") num1 = asking() num2 = asking() decider = False while decider == False: print("""\n(1) + (2) - (3) * (4) / (5) sin(number1/number2) (6) cos(number1/number2) (7) Change numbers (8) Quit""") print("Current numbers:",num1," ",num2) operator = operation() if operator == 1: result = num1 + num2 print("The result is:",result) elif operator == 2: result = num1 - num2 print("The result is:",result) elif operator == 3: result = num1 * num2 print("The result is:",result) elif operator == 4: result = num1 / num2 print("The result is:",result) elif operator == 5: result = num1 / num2 result = math.sin(result) print("The result is:",result) elif operator == 6: result = num1 / num2 result = math.cos(result) print("The result is:",result) elif operator == 7: num1 = asking() num2 = asking() elif operator == 8: print("Thank you!") decider = True
true
c4d2f88ede5a3b373ce8e6912c70c71d9de7d863
Jeffreyo3/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,277
4.15625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) # create a list with lenght # equal to total incoming elemnts merged_arr = [0] * elements a_idx = 0 # keep track of current arrA index b_idx = 0 # keep track of current arrB index # iterate over merged_arr for i in range(len(merged_arr)): # check if b_idx is out of range if b_idx > len(arrB)-1: # all b elements have been sorted and we can now # assign the rest of the a elemtns since they're sorted merged_arr[i] = arrA[a_idx] a_idx += 1 # check if a_idx is out of range elif a_idx > len(arrA)-1: # all a elements have been sorted and we can now # assign the rest of the b elemtns since they're sorted merged_arr[i] = arrB[b_idx] b_idx += 1 # if current indexes are in range else: # check if a is less than b if arrA[a_idx] < arrB[b_idx]: # assign current merge_arr idx to a element merged_arr[i] = arrA[a_idx] a_idx += 1 else: # assign current merge_arr idx to b element merged_arr[i] = arrB[b_idx] b_idx += 1 # when all merge_arr elements are set, return final result return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): if len(arr) < 2: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): # Your code here pass def merge_sort_in_place(arr, l, r): # Your code here pass arr1 = [1, 8, 20] arr2 = [3, 6, 7] array = [1, 24, 22, 7, 3, 6, 9, 21, 0, 14] print("\nTEST MERGE") print(merge(arr1, arr2)) print("\nTEST MERGE_SORT") print(merge_sort(array))
true
9136d269ad920365c747a0fefcf3ad8e238e20c6
nx6110a5100/Internshala-Python-Training
/while.py
235
4.125
4
day=0 sq=0 total=0 print('Enter number of quats each day') while day<=6: day=day+1 sq=int(input('Enter the number of quats on {} day '.format(day))) total+=sq avg=total/day print('Average sqats is {} per day'.format(avg))
true
bfd58a191c030136732f08e61ab49a124178fdbd
roblivesinottawa/problem_solving
/weektwo/format_name.py
754
4.5
4
"""Question 6 Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string""" def format_name(first_name, last_name): # code goes here string = '' if first_name!= '' and last_name != '': return f"Name: {last_name}, {first_name}" elif first_name != '' or last_name != '': return f"Name: {last_name}{first_name}" else: return string print(format_name("Ernest", "Hemingway")) # Should return the string "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should return the string "Name: Madonna" print(format_name("Voltaire", "")) # Should return the string "Name: Voltaire" print(format_name("", "")) # Should return an empty string
true
519141822d77e1cc19c19e2261c942a6fc95c94b
roblivesinottawa/problem_solving
/weektwo/fractional_part.py
938
4.375
4
""" Question 10 The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division. """ def fractional_part(numerator, denominator): # Operate with numerator and denominator to # keep just the fractional part of the quotient if numerator == 0: return 0 elif denominator == 0: return 0 else: v = numerator / denominator v = v - int(v) if v == 0.0: return 0 return v print(fractional_part(5, 5)) # Should be 0 print(fractional_part(5, 4)) # Should be 0.25 print(fractional_part(5, 3)) # Should be 0.66... print(fractional_part(5, 2)) # Should be 0.5 print(fractional_part(5, 0)) # Should be 0 print(fractional_part(0, 5)) # Should be 0
true
78279ce8c48f746121c66a5297a044dee410ef9c
NicholasBreazeale/NB-springboard-projects
/python-syntax/words.py
288
4.1875
4
def print_upper_words(wordList, must_start_with): """Print out a list of words if they start with a specific letter, each on separate lines, and all uppercase""" for word in wordList: for letter in must_start_with: if word[0] == letter[0]: print(word.upper()) break
true
74b92ec02440aa5980ea1dff14115ce3603d60fc
mimikrija/ProjectEuler.py
/01.py
616
4.34375
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def is_multiple_of_any(num, divisors): "returns if `num` is divisible by any of the `divisors`" return any(num % divisor == 0 for divisor in divisors) solution = sum(candidate for candidate in range(1, 1000) if is_multiple_of_any(candidate, (3, 5))) print(f'the sum of all the multiples of 3 or 5 below 1000 is: {solution}') # the sum of all the multiples of 3 or 5 below 1000 is: 233168
true
31e121e4facd9b159492a8195ea4316317aa766d
brunnacroches/python-calculadora
/3.0CalculoDaApp.py
1,422
4.375
4
#CALCULADORA DE PINTURA# #Bem, agora pegando todos os dados do usario # vamos fazer todos os calculos que faltam definir # a litragem de tinta necessaria para fazer a nossa calculadora de pintura #CALCULADORA DE PINTURA# #1- REMOVER A EXPRESSAO DO PRINT E COLOCA-LA DENTRO DE UMA VARIAVEL # VARIAVEL CHAMADA DE AREA PAREDE: #ANTES #print("A area das paredes é: ", #(2 * (largura + profundidade) * altura)) #DEPOIS #area_paredes: float = 2 * (largura + profundidade) * altura #print("A area das paredes é ") largura:float = float(input('Qual a largura do cômodo?')) profundidade:float = float(input('Qual a profundidade do comodo?')) altura:float = 2.9 area_paredes: float = 2 * (largura + profundidade) * altura print("A area das paredes é: ", area_paredes ) area_teto: float = largura * profundidade print( 'A area do teto e:', area_teto ) print( 'A litragem de tinta necessaria é', (area_paredes + area_teto) / 10 ) # (area_paredes + area_teto) / 10 > 10 E O RENDIMENTO DA TINTA #DIVIDO pelo RENDIMENTO estimado da tinta. #Nesse caso vamos calcular que o rendimento da tinta e de 1 litro para cada 10m2 #ESTILO SKANE_CASE #NOTE QUE, no PYTHON a convencao e voce nomear a variavel pelo #estilo SKAKE_CASE #que e separar as palavras por um UNDERSCORE #BOAS PRATICAS DE PROGRAMACAO # uma linha nao deveria passar de 80 caracteres # mantem seu codigo mais legivel e mais bonito
false
acfa9d5fd8f1c22e0a15d8e26ef8882c8de07907
jackparra253/pythonya
/ejercicio19.py
515
4.15625
4
#Confeccionar un programa que lea por teclado tres números enteros distintos y nos muestre el mayor mensaje = "Ingrese un número " numero_uno = int(input(mensaje)) numero_dos = int(input(mensaje)) numero_tres = int(input(mensaje)) if numero_uno > numero_dos and numero_uno > numero_tres: print(numero_uno) else: if numero_dos > numero_uno and numero_dos > numero_tres: print(numero_dos) else: if numero_tres > numero_dos and numero_tres > numero_uno: print(numero_tres)
false
1bf86108fe73ed2004793ad957e6c0c631a3aa51
keithsm/python-specialization
/Seventh_Assignment/input_read_upper.py
409
4.625
5
#Assignment 7.1 #Program that prompts for a file name, then opens that file and #reads through the file, and print the contents of the file in upper case. #Input and open the the file fname = input ('Enter the name of the file: ') file_contents = open (fname) #Read the file contents text = file_contents.read() text = text.rstrip() #Convert to uppercase and display uc_text = text.upper() print (uc_text)
true
af73c1e95044953a0fcf88f0bce2f3622a2dd110
alandaleote/Algoritmos-II
/Aula01/atividade_aula01.py
2,055
4.25
4
''' Construir um algoritmo que contenha 3 listas: • Nomes de produtos • Preços de cada produto • Quantidades de cada produto • Construir uma função para imprimir um dos produtos da lista e uma função para retirar um dos produtos das listas ''' nome_produto = [] preco_produto = [] quantidade_produto = [] def inserir_produto(): try: nome = input('Nome do produto: ') preco = float(input('Preço unitário: ')) quantidade = int(input('Quantidade: ')) nome_produto.append(nome) preco_produto.append(preco) quantidade_produto.append(quantidade) except: print("valores inválidos") def deletar_produto(nome): for i,e in enumerate(nome_produto): if e == nome: ind = i nome_produto.pop(ind) preco_produto.pop(ind) quantidade_produto.pop(ind) def imprimir_tudo(): if len(nome_produto) > 0: print('Produto ----------------------- --- Preço --- Quantidade') for i,nome in enumerate(nome_produto): print( str(nome).ljust(33,' '), str(preco_produto[i]).center(10, ' '), str(quantidade_produto[i]).center(14, ' ') ) else: print('Não existem produtos na lista.') menu = ''' +---------------MENU----------+ | | | 0 - Sair | | 1 - Adicionar produto | | 2 - Deletar produto | | 3 - Visualizar produtos | | | +-----------------------------+ Escolha: ''' while (True): escolha = int(input(menu)) if escolha == 0: break elif escolha == 1: inserir_produto() elif escolha == 2: prod = input('Digite o nome do produto: ') if prod in nome_produto: deletar_produto(prod) print('{} deletado com sucesso!'.format(prod)) else: print('Produto não encontrado.') elif escolha == 3: imprimir_tudo() else: print('valor inválido')
false
1708ba01af55f49a00f835d4872ce553a8a01cd1
Goldenresolver/Functions-and-pizza
/happy 3 using write to a file.py
876
4.125
4
def happy(): return "Happy Birthday to you!|n" # the magic of value returning functions is we have streamlined the #program so that an entire verse is built in a single string expression. # this line really illustrates the power and beauty of value returning functions. # in this line we are calling happy() function twice def verseFor(person): lyrics = happy()*2 + "Happy birthday, dear "+person+".\n"+happy() return lyrics # in main() we are calling verseFor function within it it contains happy() # using a loop and a list to invoke the function. def main(): outfile= open("Happy_Birthday.txt","w") for person in ["Fred","Lucy","Elmer"]: print(verseFor(person)) # or we can use print(verseFor(person),file=outfile) outfile.write(verseFor(person)) # or we can use outfile.close() main()
true
e47f4fbd7866bd272fae080bc44af55004c66ceb
leilalu/algorithm
/剑指offer/第一遍/stack&queue/59-2.队列的最大值.py
943
4.125
4
""" 题目二:队列的最大值 请定义一个队列并实现函数max得到队列里的最大值,要求函数max、push_back和pop_front的时间复杂度都是O(1) """ class MaxQueue: def __init__(self): # python内置的deque的popleft 时间复杂度才是O(1),python数组的pop(0)的时间复杂度是O(n) from collections import deque self.data = deque() # 原始队列 self.max_data = deque() # 辅助队列 def max_value(self): return self.max_data[0] if self.max_data else -1 def push_back(self, value): self.data.append(value) while self.max_data and value > self.max_data[-1]: self.max_data.pop() self.max_data.append(value) def pop_front(self): if not self.data: return -1 res = self.data.popleft() if res == self.max_data[0]: self.max_data.popleft() return res
false
8ab7440e90e5d9527d973428e86a20cccf336aca
leilalu/algorithm
/剑指offer/第一遍/search/30-3.数组中数值和下标相等的元素.py
1,522
4.125
4
""" 题目三:数组中数值和下标相等的元素 假设一个单调递增的数组里的每个元素都是整数并且是唯一的。请编程实现一个函数,找出数组中任意一个数值等于其下标的元素。 例如,在数组[-3,-1,1,3,5]中,数字3和它下标相等。 """ class Solution1: def GetNumberSameAsIndex(self, numbers): """ 暴力法,顺序遍历数组 """ # 检查无效输入 if not numbers: return for i in range(len(numbers)): if numbers[i] == i: return i return None class Solution2: def GetNumberSameAsIndex(self, numbers): """ 看到【排序数组】想【二分查找】 二分过程: 1、如果mid的【值小于下标】,那么它左边的值都会小于他们的下标,下一轮在右半边搜索 2、如果mid的【值大于下标】,那么它右边的值都会大于他们的下标,下一轮在左半边搜索 3、如果mid的值等于下标,那么返回这个数 """ # 检查无效输入 if not numbers: return left = 0 right = len(numbers) - 1 while left <= right: mid = left + ((right - left) >> 1) if numbers[mid] > mid: right = mid - 1 elif numbers[mid] < mid: left = mid + 1 else: return mid return -1
false
03bdbf7857ae16c8d9d3a0112336abdd284aba82
leilalu/algorithm
/剑指offer/第二遍/16.数值的整数次方.py
1,485
4.21875
4
""" 题目描述 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 保证base和exponent不同时为0 """ class Solution1: def Power(self, base, exponent): """" base = 0 exp = 0 0 base = 0 exp > 0 0 base = 0 exp < 0 倒数无意义 base > 0 exp > 0 累乘 base > 0 exp < 0 累乘 取倒数 base > 0 exp = 0 1 base < 0 exp > 0 累乘 base < 0 exp < 0 累乘 取倒数 base < 0 exp = 0 1 """ if base == 0.0 and exponent >= 0: return 0 if base == 0.0 and exponent < 0: return -1 power = 1.0 for i in range(1, abs(exponent)+1): power *= base if exponent < 0: power = 1.0 / power return power class Solution2: def Power(self, base, exponent): if base == 0.0 and exponent < 0: return -1 if base == 0.0 and exponent >= 0: return 0 power = 1.0 power = self.PowerCore(base, abs(exponent)) if exponent < 0: power = 1.0 / power return power def PowerCore(self, base, exponent): if exponent == 0: return 1 if exponent == 1: return base power = 1 power = self.PowerCore(base, exponent >> 1) power *= power if exponent & 1 == 1: power *= base return power
false