blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2ff4e164e15623a045036ad189bfab2280086e68
kpatel1293/CodingDojo
/DojoAssignments/Python/PythonFundamentals/Assignments/12_ScoresAndGrades.py
907
4.375
4
# Assignment: Scores and Grades # Write a function that generates ten scores between 60 and 100. # Each time a score is generated, your function should display what the grade # is for a particular score. # Here is the grade table: # Score: 60 - 69; Grade - D # Score: 70 - 79; Grade - C # Score: 80 - 89; Grade - B # Score: 90 - 100; Grade - A import random def scoreAndGrade(): grade = '' print 'Scores and Grades' for num in range(0,10): score = random.randint(60,101) if score <= 69 and score >= 60: grade = 'D' elif score <= 79 and score >= 70: grade = 'C' elif score <= 89 and score >= 80: grade = 'B' elif score <= 100 and score >= 90: grade = 'A' print 'Score: {}; Your grade is {}'.format(score,grade) print 'End of the program. Bye!' scoreAndGrade()
true
fac7cceb04d13dc68e238e969a306522b51c73e9
kpatel1293/CodingDojo
/DojoAssignments/Python/PythonFundamentals/Assignments/9_FooBar.py
1,623
4.1875
4
# Optional Assignment: Foo and Bar # Write a program that prints all the prime numbers and all the perfect # squares for all numbers between 100 and 100000. # For all numbers between 100 and 100000 test that number for whether # it is prime or a perfect square. If it is a prime number, print "Foo". # If it is a perfect square, print "Bar". If it is neither, print "FooBar". # Do not use the python math library for this exercise. For example, if the # number you are evaluating is 25, you will have to figure out if it is a # perfect square. It is, so print "Bar". # prime numbers : 1 2 3 5 7 11 13 17 19 23 29... # def primeNum(num): # count = 0 # for i in range(1,12): # if(num % i == 0 and num != i): # count += 1 # if count == 1: # return 'Foo' def FooAndBar(): count = 0 num = 1 # for e in range(100,100000): while(num <= 100): for i in range(1,12): if(num % i == 0 and num != i): count += 1 print num num += 1 # num += 1 FooAndBar() FooAndBar() # def primeNum(num): # count = 0 # #check if prime # for e in range(1,100): # if(num % e == 0 and num != e): # count += 1 # if count == 1: # print 'Foo' # # check if square # for e in range(1,100): # if(e * e == num): # print 'Bar' # break # if(count > 1 and e * e != num): # print 'FooBar' # # primeNum(2) # primeNum(3) # primeNum(4) # # primeNum(25) # primeNum(6) # # primeNum(7) # primeNum(8)
true
a3b664d4fa3abcccc3cd93690ffe40b053ccf044
prkhrv/mean-day-problem
/meanday.py
1,050
4.53125
5
""" Mean days Problem: You are given a list with dates find thee mean day of the given list Explanation: Given that the range of day values are 1-7 while Monday = 1 and Sunday = 7 Find the "Meanest Day" of the list . "Meanest Day" is the sum of values of all the days divided by total number of days For Example:- Consider a list with dates ['04041996','09091999','26091996'] Meanest Day == Thursday Explanation:- Day on '04041996 is Thursday(4), Day on '09091999' is Thursday(4), Day on '26091996' is Thursday(4), hence Meanest day = 4+4+4 // 3 ---> 4 (Thursday) Input:- A list with dates in string format. ie. '01011997' Output:- Name of the Mean Day """ import calendar import datetime date_list = ['04041996','09091999','26091996'] def mean_day(date_list): value_sum = 0 for date in date_list: day_value = datetime.datetime.strptime(date, '%d%m%Y').weekday()+1 value_sum = value_sum + day_value mean_day = value_sum // len(date_list) return calendar.day_name[mean_day-1] print(mean_day(date_list))
true
61895160c36dbfbaafb426cfdbdecc280d6475c9
lisu1222/towards_datascience
/jumpingOnClouds.py
1,833
4.28125
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game. For each game, Emma will get an array of clouds numbered if they are safe or if they must be avoided. For example, indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes and . She could follow the following two paths: or . The first path takes jumps while the second takes . Function Description Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer. jumpingOnClouds has the following parameter(s): c: an array of binary integers Input Format The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds where . Constraints Output Format Print the minimum number of jumps needed to win the game. Sample Input 0 7 0 0 1 0 0 1 0 Sample Output 0 4 """ def jumpingOnClouds(c): step = 0 i = 0 while i < len(c)-2: if c[i+2] == 0: i += 1 step += 1 i += 1 #if i hasn't reached the last cloud: if i != len(c)-1: step += 1 return step #improved solution: def jumpingOnClouds(c): step = -1 i = 0 while i < len(c): if i < len(c)-2, and c[i+2]==0: i+=1 i += 1 step += 1 return step if __name__ =='__main__': n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c)
true
01c591c32142f0cb206fbee55375e77ee798121e
momentum-cohort-2019-02/w2d3-word-frequency-rob-taylor543
/word_frequency.py
1,769
4.125
4
STOP_WORDS = [ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he', 'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were', 'will', 'with' ] import string def clean(file): """Read in a string and remove special characters and stop words (keep spaces). Return the result as a string.""" file = file.casefold() valid_chars = string.ascii_letters + string.whitespace + string.digits new_file = "" for char in file: if char in valid_chars: new_file += char file = new_file file = file.replace("\n", " ") return file def print_word_freq(file): """Read in `file` and print out the frequency of words in that file.""" with open(file, "r") as open_file: file_string = open_file.read() clean_file = clean(file_string) word_freq = {} words = [] for word in clean_file.split(" "): if word and word not in STOP_WORDS: words.append(word) for word in words: if word in word_freq: word_freq[word] += 1 else: word_freq[word] = 1 sorted_keys = sorted(word_freq, key = word_freq.__getitem__, reverse = True) for word in sorted_keys: freq = word_freq[word] asterisk = "*" * freq print (f"{word:>20} | {freq:<3} {asterisk}") if __name__ == "__main__": import argparse from pathlib import Path parser = argparse.ArgumentParser( description='Get the word frequency in a text file.') parser.add_argument('file', help='file to read') args = parser.parse_args() file = Path(args.file) if file.is_file(): print_word_freq(file) else: print(f"{file} does not exist!") exit(1)
true
cec4b8438e743ddce8a680a2d4791b3e75dcbb93
Nas-Islam/qa-python-exercises
/programs/gradecalc.py
687
4.21875
4
def gradeCalc(): print("Welcome to the Grade Calculator!") mathsmark = int(input("Please enter your maths mark: ")) chemmark = int(input("Please enter your chemistry mark: ")) physicsmark = int(input("Please enter your physics mark: ")) percentage = (mathsmark + chemmark + physicsmark) / 3 if percentage >= 70: grade = 'You scored a grade of: A' elif percentage >= 60: grade = 'You scored a grade of: B' elif percentage >= 50: grade = 'You scored a grade of: C' elif percentage >= 40: grade = 'You scored a grade of: D' else: grade = 'You failed.' print(percentage,"%") print(grade) gradeCalc()
true
d0402a757ccb537d9916f827f061d2e55ea696e1
Dex4n/avaliacao-linguagem-II-n1
/ex_02.py
1,568
4.40625
4
#2 - Crie um classe Funcionário com os atributos nome, idade e salário. Deve ter um método aumenta_salario. # Crie duas subclasses da classe funcionário, programador e analista, implementando o método nas duas subclasses. # Para o programador some ao atributo salário mais 20 e ao analista some ao salário mais 30, mostrando na tela o valor. # Depois disso, crie uma classe de testes instanciando os objetos programador e analista e # chame o método aumenta_salario de cada um.(2,0) class Funcionario: def __init__(self, nome, cpf, salario): self._nome = nome self._idade = cpf self._salario = salario def aumentarSalario(self, aumento): self._salario += aumento return self._salario class Programador(Funcionario): def aumentarSalario(self): return super().aumentarSalario(20) class Analista(Funcionario): def aumentarSalario(self): return super().aumentarSalario(30) class Teste: programador = Programador('Alexandre Marino Casagrande', 22, 500.00) print("Salário do programador aumentado: ", programador.aumentarSalario()) analista = Analista('Fulano de Tal', 22, 250.00) print("Salário do analista aumentado: ", analista.aumentarSalario()) main = Teste() print("Dados do programador - Nome: {0}, idade: {1} e salário com aumento: {2}.".format(main.programador._nome, main.programador._idade, main.programador._salario)) print("Dados do analista - Nome: {0}, idade: {1} e salário com aumento: {2}.".format(main.analista._nome, main.analista._idade, main.analista._salario))
false
b79293531edb30b52ab3e3d4cb83abece2e2b7a9
BeepBoopYeetYourScoot/GeneralPython
/basic_python/1_variables/numberTypes.py
781
4.1875
4
x = 2 y = 3 print(x/y) # В python 2 получился бы ответ 0, т.к. там было бы целочисленное деление print(type(y % x)) # Модульное деление всегда даёт целое число (остаток от деления числа на число) print(y // x) # Целочисленное деление реализовано отдельным оператором x = 4 y = 2 print(x/y) # В любом случае получаю float y += x print(y) print(abs(-228)) # Функция для вычисления модуля числа print(round(3.55)) # Функция округления (работает по-человечески) num = '100' num_1 = '200' print(int(num) + int(num_1))
false
fff87a0aa35c151e1e4c94b3a43e44ace36287f2
BeepBoopYeetYourScoot/GeneralPython
/intermediate_python/2_algorithms/bubble_sort.py
929
4.28125
4
import random def generate_random_array(length: int): """Функция генерирует список длины *length*, который состоит из случайных целых чисел""" temp = [] for i in range(length): temp.append(random.randint(0, 101)) return temp array = generate_random_array(10) print(array) def bubble_sort(array_to_sort: list): """Функция реализует алгоритм сортировки пузырьком. Принимает на вход только существующие в Python типы массивов""" for n in range(1, len(array_to_sort)): for m in range(len(array_to_sort) - n): if array_to_sort[m] > array_to_sort[m+1]: array_to_sort[m], array_to_sort[m+1] = array_to_sort[m+1], array_to_sort[m] return array_to_sort print(bubble_sort(array))
false
da785fbd6a17fa38518bdc5e42e30bf28cd0c302
Leonardo612/Entra21_Leonardo
/01-Exercicios/Aula001/Ex1.py
633
4.15625
4
#--- Exercício 1 - Variáveis #--- Crie 5 variáveis para armazenar os dados de um funcionário #--- Funcionario: Nome, Sobrenome, Cpf, Rg, Salário #--- Deve ser usado apenas uma vez a função print() #--- Cada dado deve ser impresso em uma linha diferente #--- O salário deve ser de tipo flutuante nome = input('Digite o Nome: ') sobrenome = input('Digite o Sobrenome: ') cpf = (input('Digite o cpf: ')) rg = (input('Digite o rg: ')) salario = float(input('Digite o Salario: ')) print(f''' nome: {nome} Sobrenome: {sobrenome} cpf: {cpf} rg: {rg} Salario: {'{:.3f}'.format(salario)}'''.format(nome,sobrenome,cpf,rg,salario))
false
f68a1c9afe8a230e2b9e5ef79982be601a9b97bb
meahow/adventofcode
/2017/06/solution1_test.py
1,348
4.28125
4
import solution1 """ For example, imagine a scenario with only four memory banks: The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2. Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3. Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4. The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1. The third bank is chosen, and the same thing happens: 2 4 1 2. At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5. """ def test_solve(): data = [0, 2, 7, 0] assert solution1.solve(data) == 5
true
24cab64adff4d0da92ad5b941b501e355dacfd98
Iliyakarimi020304/darkT-Tshadow
/term 2/dark shadow51.py
320
4.125
4
number = input("Enter Number: ") counter = 0 numbers = [] sums = 0 while number != '0': if number.isdigit(): numbers.append(number) counter += 1 number = input("Enter Number: ") for n in numbers: sums += int(n) print(f"Your numbers{numbers}") print(f"Average of your numbers {sums/counter}")
true
5c64470d7d305603eb43654528cb7fd6ea78c1cb
MerchenCB2232/backup
/todolist.py
814
4.125
4
import pickle print ("Welcome to the To Do List :))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))") todoList = [] while True: print("Enter a to add an item") print("Enter r to remove an item") print("Enter l to load list") print("Enter p to print the list") print("Enter q to quit") choice = input("Make your choice: ") if choice == "q": pickle.dump(todoList,open("save.p", "wb")) break elif choice == "a": addition = input("What would you like to add to the list? ") todoList.append(addition) elif choice == "r": subtraction = input("What would you like to remove? ") todoList.remove(subtraction) elif choice == "p": print(todoList) elif choice == "l": todoList = pickle.load(open("save.p", "rb")) else: print("That is not an option. :(")
true
64b8718c992320ddc1650100417cd4dcc5689b3e
davideduardo001github/tarea1python
/p4.py
1,416
4.625
5
""" 4.- Elabora un programa que me permita realizar la suma de dos matrices de 3x3. Cada uno de los elementos de la matriz deberá ser ingresado por el usuario. Una matriz en Python puede implementarse con listas dentro de listas. """ ## DECLARACIÓN DE MÉTODOS # Impresión de matrices nxn def printmatrix(mat): for i in range(len(mat)): for j in range(len(mat[i])): print(mat[i][j], end = " ") print("\n") # Generación de matrices por usuario def genmatrix(rows, columns): mat = [[0] * rows for i in range(columns)] for i in range(len(mat)): for j in range(len(mat[i])): mat[i][j] = int(input("Ingresa el valor {0}x{1}: ".format(i+1,j+1))) return mat # Suma de matrices def summatrix(a,b): if ( len(a)==len(b) and len(a[0])==len(b[0]) ): rows = len(a) columns= len(a[0]) matout = [[0] * rows for i in range(columns)] for i in range(rows): for j in range(columns): matout[i][j] = a[i][j] + b[i][j] return matout else: print("Las mátrices no son compatibles en suma") # PRUEBA DEL MÉTODO if __name__ == '__main__': print("Ingresa la matriz A") mat1 = genmatrix(3,3) printmatrix(mat1) print("Ingresa la matriz B") mat2 = genmatrix(3,3) printmatrix(mat2) print("La suma de las matrices A+B es: ") printmatrix(summatrix(mat1,mat2))
false
737263f3bdd1c1d0a6c64a021c9c125fe944a557
ldd257/python_ai
/com/learn/python/十、类/2. self.py
2,989
4.25
4
""" Python 的 self 相当于 C++ 的 this 指针。 类的方法与普通的函数只有一个特别的区别 —— 它们必须有一个额外的第一个参数名称(对应于该实例,即该对象本 身),按照惯例它的名称是 self 。在调用方法时,我们无需明确提供与参数 self 相对应的参数。 """ class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt() # <__main__.Test object at 0x000000BC5A351208> # <class '__main__.Test'> class Ball: def setName(self, name): self.name = name def kick(self): print("我叫%s,该死的,谁踢我..." % self.name) a = Ball() a.setName("球A") b = Ball() b.setName("球B") c = Ball() c.setName("球C") a.kick() # 我叫球A,该死的,谁踢我... b.kick() # 我叫球B,该死的,谁踢我... """ Python的魔法方法 据说,Python 的对象天生拥有一些神奇的方法,它们是面向对象的 Python 的一切... 它们是可以给你的类增加魔力的特殊方法... 如果你的对象实现了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,而这一切都是自动发生 的... 类有一个名为 __init__(self[, param1, param2...]) 的魔法方法,该方法在类实例化时会自动调用。 """ class Ball: def __init__(self, name): self.name = name def kick(self): print("我叫%s,该死的,谁踢我..." % self.name) a = Ball("球A") b = Ball("球B") c = Ball("球C") a.kick() # 我叫球A,该死的,谁踢我... b.kick() # 我叫球B,该死的,谁踢我... """ 公有和私有 在 Python 中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。 """ class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount) counter = JustCounter() counter.count() # 1 counter.count() # 2 print(counter.publicCount) # 2 print(counter._JustCounter__secretCount) # 2 Python的私有为伪私有 print(counter.__secretCount) # AttributeError: 'JustCounter' object has no attribute '__secretCount' # 类的私有方法实例 class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() x = Site('老马的程序人生', 'https://blog.csdn.net/LSGO_MYP') x.who() # name : 老马的程序人生 # url : https://blog.csdn.net/LSGO_MYP x.foo() # 这是公共方法 # 这是私有方法 x.__foo() # AttributeError: 'Site' object has no attribute '__foo'
false
df1a5647ba6cd504cf5e6dba183ca4aed1f276d5
jimbuho/hiring-test
/tests/test_stack.py
1,250
4.1875
4
""" Un Stack o Pila: el primer elemento en entrar es el primero en salir. Nota: En el siguiente codigo hay cuatro lineas que deben corregirse para que las tres pruebas sean superadas """ class Stack: def __init__(self, initial_items=[]): self.items = initial_items def shift(self): self.items = self.items[1:] return self.items[0] def push(self, item): self.items.append(item) def printit(self): return str(self.items) class TestStack: def test_stack(self): """ Stack Test of numbers from 1 to 5 """ expected = str([i+1 for i in range(5)]) queue = Stack([1,2,3]) for i in range(3,5): queue.push(i) assert queue.printit() == expected, "Should be {}".format(expected) def test_destack(self): """ Stack of numbers from 1000 and de-Stack of a set of numbers """ expected = str([1000+(i*10) for i in range(4)]) queue = Stack() for i in range(4): queue.push(1000+(i*10)) item = queue.shift() assert queue.printit() == expected, "Should be {}".format(expected) assert item == 1000, "Should be 1000"
false
c0d1f2201c3dc6a715ba9994214db7c1d535b453
cpvp20/bubblesort
/del.py
378
4.21875
4
def sortit(numbers): for i in range(len(numbers)): if i[1]>i[2]: i[1],i[2]=i[2],i[1] return(numbers) #ACTIAL CODE x=list(input("type some integers randomly, separating them with spaces ")) #creates a list with the numbers the user gives y=[int(i) for i in range(len(x))]#turns list of str into list of int sortit(y) #sort the list of int
true
622f93ea01a437ead0616c01901d593092a26927
rwaidaAlmehanni/python_course
/get_started/Comprehensions/problem28.py
218
4.21875
4
#Write a function enumerate that takes a list and returns a list of tuples containing (index,item) for each item in the list. def enumerate(array): print [(array.index(y),y) for y in array] enumerate(["a", "b", "c"])
true
28a6f77cddab8da561601b8f743f57d2e1da03bf
Nzembi123/function.py
/functions.py
2,647
4.3125
4
#Function is a block of code that runs only when called def adding(num1, num2): x = num1+num2 print(x) adding(2,4) #Multiplication def multiplication(): num1 =15 num2 =30 sum = num2*num1 print(sum) multiplication() ##arguments def courses(*args): for subject in args: print(subject) courses('IT', 'Nutririon', 'Math') def courses(*args): for subject in args: return subject print(courses('IT', 'Nutririon', 'Math')) #keyword arguments def cars(**kwargs): for key, value in kwargs.items(): print("{}:{} ". format(key,value)) cars( car1='Subaru\n', car2='Bentley\n', car3='jeep') #Default parameter value - used when we call the fn without an argument def shoes(shoe_type = 'Airmax'): ##Airmax is set to be the default argument print('\nMy shoe type is ' + shoe_type ) shoes() ##this will print 'My shoetype is Airmax since it is the default parameter' shoes('fila') shoes('puma') #passing a list as arguments def muFunction (devices): for x in devices: print(x) input_devices = ['Keyboard', 'touchscreen', 'mouse'] muFunction(input_devices) #passing a dictionary as arguments def muFunction (student): for x in student: print(x) student = { 'Fname' : 'James', #string 'Sname' : 'Bond', #string 'Tel' : 8508447, #integer 'Shoes' : ['Fila', 'Airmax' , 'Dior'], #list 'Male' : True } muFunction(student) #The pass statement #area of a circle def area_of_circle(): print('\nAREA OF A CIRCLE') pi = 3.142 r = float(input('\nEnter the radius: ')) area = (pi*r*r) print('\nThe area is ' + str(area)) area_of_circle() #volume of a cylinder def volume_of_cylinder(): print('\nVOLUME OF A CYLINDER') pi = 3.142 r = float(input('\nEnter the radius: ')) h = float(input('\nEnter the height: ')) v = (pi*r*h) print('\nThe volume is ' + str(v)) volume_of_cylinder() #GRADING SYSTEM def grading(): mat = float(input('Enter marks for Math: ')) sci = float(input('Enter marks for Science: ')) eng = float(input('Enter marks for English: ')) sum = mat+sci+eng avr = sum/3 if avr >=0 and avr<=49: print('Average = ' + str(avr) + 'GRADE : E') elif avr >=50 and avr<=59: print('Average = ' + str(avr) + 'GRADE : D') elif avr >=60 and avr<=69: print('Average = ' + str(avr) + 'GRADE : C') elif avr >=70 and avr<=79: print('Average = ' + str(avr) + 'GRADE : B') elif avr >=80 and avr<=100: print('Average = ' + str(avr) + 'GRADE : A') else: print('Marks out of range! ') grading()
true
e214ac661d060b1ce887b15ad66ff44caac1947c
jubic/RP-Misc
/System Scripting/Problem15/6P/t50_xml1.py
1,763
4.21875
4
""" h2. XML from List of Dictionary Create a function @xmlFromList@ that takes a list of dictionaries. The XML must have the root tag @<storage>@. Each item in the dictionary should be put inside the @<container>@ tag. The dictionary can contain any keys (just make sure the keys are the same for all of the dictionaries in the list). and different values. See the example below. bc. {- python -} print xmlFromList([ {'title':'Introduction to Algoritms', 'author':'Ronald Rivest'}, {'title':'Learning Python', 'author':'Mark Lutz'}, {'title':'The Ruby Programming Language', 'author':'David Flanagan'} ]) bc. {- xml -} <?xml version='1.0' encoding='UTF-8'?> <storage> <container> <author>Ronald Rivest</author> <title>Introduction to Algoritms</title> </container> <container> <author>Mark Lutz</author> <title>Learning Python</title> </container> <container> <author>David Flanagan</author> <title>The Ruby Programming Language</title> </container> </library> *{color:red;}Notes:* Don't hardcode @<author>@ and @<title>@ as they can change according to keys and values in the dictionary. Only @<storage>@ and @<container>@ are fix. """ def xmlFromList(l): # your code here s = "<?xml version='1.0' encoding='UTF-8'?>\r\n" s += "<storage>\r\n" for dict in l: s += "\t<container>\r\n" for (k,v) in dict.items(): s += "\t\t<%s>%s</%s>\r\n" % (k, v, k) s += "\t</container>\r\n" s += "</storage>\r\n" return s if __name__ == "__main__": print xmlFromList([ {'title':'Introduction to Algoritms', 'author':'Ronald Rivest'}, {'title':'Learning Python', 'author':'Mark Lutz'}, {'title':'The Ruby Programming Language', 'author':'David Flanagan'}])
true
4a2ce6635442bfaf8555a1958b6dd06b1389d52d
jubic/RP-Misc
/System Scripting/Problem15/t40_db1.py
1,533
4.53125
5
""" h2. Putting Data into SQLite Database Write a function @putData@ that takes 4 arguments as specified below: # @dbname@ - a string that specifies the location of the database name # @fnames@ - the list of first names # @lnames@ - the list of last names corresponding to the first names list # @ages@ - the list of the age corresponding to each name in the first name and last name lists Insert those lists into a table named @people@ in a database with name that is in the first argument. The function needs not return anything. See the example below: bc. {- python -} putData("tmp/test.db", ["Bob", "John"], ["Lim", "Tan"], [45, 32]) @testall.pyc@ will check the database that's created by @putData@ directly. """ import sqlite3 # Complete the function below def putData(dbname, fnames, lnames, ages): conn = sqlite3.connect(dbname) #conn.execute("drop table people") conn.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, fnames TEXT, lnames TEXT, ages INTEGER)") for x in range(len(fnames)): #age = ", "+ str(ages[x]) conn.execute("INSERT INTO people (fnames, lnames, ages) VALUES ('"+fnames[x]+"', '"+lnames[x]+"', "+str(ages[x])+")") #print "INSERT INTO people (firstname, lastname, age) VALUES ('"+fnames[x]+"', '"+lnames[x]+"', "+str(ages[x])+")" conn.commit() if __name__ == '__main__': putData("tmp/names.db", ["John", "Paul", "George", "Ringo"], ["Lennon", "McCartney", "Harrison", "Star"], [25, 26, 27, 28])
true
8ac8ef9b63495ec2678dbad87faa668c9d4d9924
jubic/RP-Misc
/System Scripting/Problem15/t02_list3.py
665
4.21875
4
""" h2. Zip Two Lists into One Write a function @zipper@ that takes 2 arguments. Both arguments are lists of integers. The function must then create a new list to put the first item of the first list, followed by the first item of the second list. Then second item of the first list, followed by the second item in the second list. Check the example below: bc. {- python -} """ a = [1,2,3] b = [4,5,6] # After running zipper(a, b), you'll get [1,4,2,5,3,6] def zipper(l1, l2): result = [] i=0 for item in l1: result.append(item) result.append(l2[i]) i = i+1 return result if __name__ == "__main__": print zipper(a, b)
true
4c4bb3ad3c2b0a45b1b044891d10805fccabb614
Montanaz0r/Skychallenge-Chapter_II
/I_write_my_programs_in_JSON/I_write_my_programs_in_JSON.py
629
4.25
4
import re def sum_the_numbers(filename): """ A function that sum up all the numbers encountered in the file :param filename: name of the file (str) :return: sum of all numbers (int) """ with open(f'{filename}.txt', 'r') as file: data = file.read() results = re.findall(r'(-?\d+)', data) # using REGEX pattern to detect numbers sum_of_all_numbers = sum([int(number) for number in results]) print(f'Sum of all numbers in the document is equal to: {sum_of_all_numbers}') return sum_of_all_numbers if __name__ == '__main__': sum_the_numbers('json_data')
true
beaaff1569c17464bb006805d7f2f20ae0b7457a
SpikyClip/rosalind-solutions
/bioinformatics_stronghold/FIB_rabbits_and_recurrence_relations.py
2,483
4.40625
4
# url: http://rosalind.info/problems/fib/ # Problem # A sequence is an ordered collection of objects (usually numbers), which # are allowed to repeat. Sequences can be finite or infinite. Two examples # are the finite sequence (π,−2–√,0,π) and the infinite sequence of odd # numbers (1,3,5,7,9,…). We use the notation an to represent the n-th # term of a sequence. # A recurrence relation is a way of defining the terms of a sequence with # respect to the values of previous terms. In the case of Fibonacci's # rabbits from the introduction, any given month will contain the rabbits # that were alive the previous month, plus any new offspring. A key # observation is that the number of offspring in any month is equal to # the number of rabbits that were alive two months prior. As a result, # if Fn represents the number of rabbit pairs alive after the n-th month, # then we obtain the Fibonacci sequence having terms Fn that are defined # by the recurrence relation Fn=Fn−1+Fn−2 (with F1=F2=1 to initiate the # sequence). Although the sequence bears Fibonacci's name, it was known # to Indian mathematicians over two millennia ago. # When finding the n-th term of a sequence defined by a recurrence # relation, we can simply use the recurrence relation to generate terms # for progressively larger values of n. This problem introduces us to the # computational technique of dynamic programming, which successively # builds up solutions by using the answers to smaller cases. # Given: Positive integers n≤40 and k≤5. # Return: The total number of rabbit pairs that will be present after n # months, if we begin with 1 pair and in each generation, every pair of # reproduction-age rabbits produces a litter of k rabbit pairs # (instead of only 1 pair). def rabbit_recursive(months, litter_size): """ return no. of adult pairs after n months given adult pairs produce a litter of size k each month """ adults, newborns = 0, 1 for _ in range(months): adults, newborns = adults + newborns, adults * litter_size return adults if __name__ == "__main__": file1, file2 = "inputs/FIB_input.txt", "outputs/FIB_output.txt" with open(file1, "r") as f1, open(file2, "w") as f2: # splits string into list, converts to int, then tuple months, litter_size = tuple(map(int, f1.read().split())) # convert int result to str before writing f2.write(str(rabbit_recursive(months, litter_size)))
true
e8bcb65bd9bb11fd4a11c030c0885dda1669c43b
SpikyClip/rosalind-solutions
/bioinformatics_stronghold/MRNA_inferring_mRNA_from_protein.py
2,808
4.28125
4
# url: http://rosalind.info/problems/mrna/ # Problem # For positive integers a and n, a modulo n (written amodn in shorthand) # is the remainder when a is divided by n. For example, 29mod11=7 # because 29=11×2+7. # Modular arithmetic is the study of addition, subtraction, multiplication, # and division with respect to the modulo operation. We say that a and b # are congruent modulo n if amodn=bmodn; in this case, we use the # notation a≡bmodn. # Two useful facts in modular arithmetic are that if a≡bmodn and c≡dmodn, # then a+c≡b+dmodn and a×c≡b×dmodn. To check your understanding of these # rules, you may wish to verify these relationships for a=29, b=73, c=10, # d=32, and n=11. # As you will see in this exercise, some Rosalind problems will ask for # a (very large) integer solution modulo a smaller number to avoid the # computational pitfalls that arise with storing such large numbers. # Given: A protein string of length at most 1000 aa. # Return: The total number of different RNA strings from which the # protein could have been translated, modulo 1,000,000. (Don't neglect # the importance of the stop codon in protein translation.) import numpy as np def prot_to_mrna_no(protein): """ Counts the number of each type of amino acid in protein, appending the number of permutations possible for each amino acid type to the power of the count to a list. The product of this list is returned as a modulo of 1_000_000. """ # dict containing the number of possible codons for each amino acid aa_permutations = { "F": 2, "L": 6, "I": 3, "V": 4, "M": 1, "S": 6, "P": 4, "T": 4, "A": 4, "Y": 2, "H": 2, "N": 2, "D": 2, "Q": 2, "K": 2, "E": 2, "C": 2, "R": 6, "G": 4, "W": 1, } # 3 ** 1 is the initial value in the list, as proteins must have 1 # stop codon and there are only 3 permutations to a stop codon total_no = [3] # Loops through all amino acids and counts its frequency in # protein. The possible mRNA combinations for that amino acid are # appended as permutations to the power of its count, modulus # 1_000_000 which saves some computational power for amino_acid, permute in aa_permutations.items(): aa_count = protein.count(amino_acid) total_no.append(pow(permute, aa_count, 1_000_000)) result = np.prod(total_no) % 1_000_000 return result if __name__ == "__main__": file1, file2 = "inputs/MRNA_input.txt", "outputs/MRNA_output.txt" with open(file1, "r") as f1, open(file2, "w") as f2: protein = f1.read().strip() total_no = prot_to_mrna_no(protein) f2.write(str(total_no))
true
1e0382442c4c5c2c87899e2084d88182bf589c11
VIncentTetteh/Python-programming-basics
/my_math.py
868
4.125
4
import math def calculate(enter, number1, number2): print("choose from the list.") print(" 1. ADD \n 2. SUBTRACT \n 3. MULTIPLY") if enter == "add" or enter == "ADD": #number1 = input("enter first number ") #number2 = int(input(" enter second number ")) answer = number1 + number2 return answer elif enter == "subtract" or enter == "SUBTRACT": #number1 = int(input("enter first number ")) #number2 = int(input(" enter second number ")) answer = number1 - number2 return answer elif enter == "multiply" or enter == "MULTIPLY": #number1 = int(input("enter first number ")) #number2 = int(input(" enter second number ")) answer = number1 * number2 return answer else: print("wrong input !!") print("your answer is ", calculate("ADD",10,2))
true
9e3dbf46dc181a269216335c10726a82d1ad659f
to-yuki/pythonLab-v3
/ans/4/Calculation.py
324
4.375
4
#-- Calc Function --# def calc(val1,operator,val2): if operator == '+': return val1 + val2 elif operator == '-': return val1 - val2 elif operator == '*': return val1 * val2 elif operator == '/': return val1 / val2 else: raise ArithmeticError("Operator Error")
false
95a29801463084c4374fa418b437e2b79719c702
Aparna9876/cptask
/task9.py
201
4.28125
4
odd = 0 even = 0 for i in (5,6,8,9,2,3,7,1): if i % 2 == 0: even = even+1 else: odd = odd+1 print("Number of even numbers: ",even) print("Number of odd numbers: ",odd)
true
661875f584581198453a3ba706a8dd24f2c71430
erchiragkhurana/Automation1
/Python_Practice/Loops/WhileLoop.py
362
4.15625
4
#Initialization, condition then increment #while loop with increment, while loop is also called indefinte loop number = input("Write your number") i=1 while(i<=10): print(int(number)*i) i = i + 1 #while loop with decrement number = input ("your num") i=10 while(i>=1): print(int(number)*i) i=i-2 #another i=10 while(i>=1): print(i) i=i-3
true
61d72a38fbeda9f07c9e3847e50dd85737c94f53
erchiragkhurana/Automation1
/Python_Practice/Handling/Condition_Handling.py
1,511
4.46875
4
# take a number from user to check condition handling using if and else x = input("Hey User type your number") if(int(x)==100): print("Number is Greater") else: print("Number is smaller") if(int(x)>100): print("Number is Greater") else: print("Number is smaller") #check multiple condition handling elif statements inputnum = input("type your number") inputnum = int(inputnum) # typecasting to change the string to integer if(inputnum<0): print("Number is less than zero") elif(inputnum==0): print("Number is equal to zero") elif(inputnum%2==0): #if number remainder is 0 print("This is even number") else: print("This is odd number") #check nested condition handling examples inputnum = input("Give your num input") inputnum = int(inputnum) if (inputnum>=0): if(inputnum%2==0): print("This is even number") else: print("This is odd number") else: print("This is negative number") #check condition handling with logical or operator and this should be in lower case as it is case sensitive inputnum = input("Give your num input") inputnum = int(inputnum) if (inputnum> 100 or inputnum <0): print(" This is invalid number") else: print("This is valid number") #check condition handling with logical and operator and same goes with not operator which is ! inputnum = input("Give your num input") inputnum = int(inputnum) if (inputnum> 0 and inputnum >10): print(" This is valid number") else: print("This is invalid number")
true
4aba95f8d59bec6b7be786522f62bcc98b8ca04f
tranhd95/euler
/1.py
367
4.28125
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. """ multiplies_of_three = set(range(0, 1000, 3)) multiplies_of_five = set(range(0, 1000, 5)) multiplies = multiplies_of_three.union(multiplies_of_five) print(sum(multiplies))
true
e4a0c67027e213cf03f165c2ccd6b1ccc6c05ba6
snirsh/intro2cs
/ex2/largest_and_smallest.py
1,261
4.4375
4
###################################################################### # FILE : largest_and_smallest.py # # WRITER : Snir Sharristh , snirsh , 305500001 # # EXERCISE : intro2cs ex2 2015-2016 # # DESCRIPTION: The code below calculates the maximum number and the # # minimum number using three numbers given to it # ###################################################################### # function receives three numbers and returns the biggest and the smallest one def largest_and_smallest(n1, n2, n3): n1 = int(n1) n2 = int(n2) n3 = int(n3) # defines which one is the biggest considering that it may be equal to the # rest and mx is the biggest number if n1 >= n2 and n1 >= n3: mx = n1 elif n2 >= n1 and n2 >= n3: mx = n2 elif n3 >= n1 and n3 >= n2: mx = n3 # defines which one is the smallest considering that it may be equal to the # rest and mn is the smallest number if n1 <= n2 and n1 <= n3: mn = n1 elif n2 <= n1 and n2 <= n3: mn = n2 elif n3 <= n1 and n3 <= n2: mn = n3 # returns the biggest number, and the smallest number return mx, mn
true
4078dfbb0fa06a2375d323e747edf7bd4aae9d4a
danschae/Python-Tutorial
/introduction/basics.py
757
4.1875
4
""" This section is more just about very basic programming, i'm not putting too much effort into it. This type of information is universal to most programming languages. """ print("hello world") # simple console log print (5 * 7) print("hello" + " world") # can concatante strings just like in javascript # greetings = "Hello" # name = input("please enter your name?") # print(greetings + " " + name) print("1\n2\n3\n4\n5") # escaping """ the good thing with python is that variables can have multiple types implied. It's more that the value has a data type. Python is a strongly typed languaged meaning the data types should match with each other, so you can't concatante a string with a number. Javascript for example is a weakly typed language. """
true
b3299f6e5d300404892111647477ef82d30dfb1b
Rohit102497/Command_Line_Utility
/web_crawler/links_from_html.py
1,657
4.15625
4
''' This script prompts a user to pass website url and the html code in string format and output all the links present in the html in a set. ''' import re HREF_REGEX = r""" href # Matches href command \s* # Matches 0 or more white spaces = \s* # Matches 0 or more white spaces [\'\"](?P<link_url>.+?)[\"\'] # Matches the url """ SRC_REGEX = r""" src \s* = \s* [\'\"](?P<src_url>.+?)[\'\"] """ href_pattern = re.compile(HREF_REGEX, re.VERBOSE) src_pattern = re.compile(SRC_REGEX, re.VERBOSE) def links_from_html(html_crawled: str, url: str) -> set: ''' Returns a set of links extracted from the html passed. It contains internal links by removing the url (from the starting of the string) passed to it. All internal links begins with '/'. Example Usage: -------------- >>> url = "https://python.org/" >>> links_from_html('src = "https://python.org/sitemap/"', url) {'/sitemap/'} >>> links_from_html("""src = '#sitemap/'""", url) {'/#sitemap/'} >>> links_from_html('href = "https://git.corp.adobe.com/"', url) {'https://git.corp.adobe.com/'} ''' links = href_pattern.findall(html_crawled) links.extend(src_pattern.findall(html_crawled)) links = set(links) links = {link.replace(url, "/") if link.startswith(url) else link for link in links} links = {f"/{link}" if link.startswith('#') else link for link in links} if "/" in links: links.remove("/") return links if __name__ == '__main__': import doctest doctest.testmod()
true
4b44a37b5d556ce1f5d4e00969f0554858064091
juann2563/curso_python
/main.py
1,316
4.125
4
# tipos de datos y condiciones anidadas """ x =float(input("Ingrese dato: ")) #print(x) y= float(input("Ingrese dato: ")) print(10%2) a = True b = False print(a) """ """ a = 5 if a<4: print("hola") print("mundo") elif a<5: print("es menor que 5") else: print("No es menor") """ # condiciones multiples """ a = 3 b = 4 if a ==3 or b == 4: print("es correcto") """ # cilo while """ a = 7 while a==7: print("estoy en el while") a = int(input("ingrese el nuevo valor de a: ")) if a != 7: break """ # ciclo for """ for i in range(0,5): print(i) """ #ejercicio algoritmo num1 = int(input("Ingrese dato 1: ")) num2 = int(input("Ingrese dato 2: ")) while True: opcion = input('Ingrese S - suma, R - resta, M - multiplicacion, D - Division: ') if opcion == 'S': print("suma = " + str(num1 + num2)) break elif opcion == 'R': print("resta = " + str(num1 - num2)) break elif opcion == 'M': print("multiplicacion = " + str(num1 * num2)) break elif opcion == 'D': if num2 == 0: print("No se puede realizar division por 0, intente de nuevo") else: print("division = " + str(num1 / num2)) break else: print("opcion no valida, ingrese una opcion valida")
false
491fefbcbebbbe83f59f94b792b123bd2d0a5e0a
Madhu13d/GITDemo
/PythonBasics1/List.py
1,217
4.5
4
values = [1, 2, "Sai", 4, 5] print(values[0]) # prints 1 print(values[3]) # prints 4 print(values[-1]) # -1 refers to the last element in the list, prints 5 print(values[1:3])#[1:3] is used to get substring.it will fetch 2 values leaving the 3rd index, prints 2, Sai values.insert(3, "Ramana") # will insert Ramana at 3rd index print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5] values.append("End") # append will insert value at last print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5, 'End'] values[2] ="SAI" # will Update the old value with new one print(values) # prints [1, 2, 'Sai', 'Ramana', 4, 5, 'End'] del values[0] # will delete the 0th index value print(values) # prints [2, 'SAI', 'Ramana', 4, 5, 'End'] #Tuple val= (1, 2, "Sai") print(val) # prints (1, 2, 'Sai') #val[2] ="SAI" #TypeError: 'tuple' object does not support item assignment # Dictionary dic = {"a":2, 4:"bcd","c":"Hello World"} print(dic[4]) # prints bcd print(dic["c"]) # prints Hello World print(dic["a"]) # prints 2 # dict = {} dict["firstname"] = "Madhavi" dict["lastname"] = "Latha" dict["gender"] = "Male" print(dict)# prints {'firstname': 'Madhavi', 'lastname': 'Latha', 'gender': 'Male'} print(dict["lastname"]) # prints Latha
true
1bdc93f3380c0678b115f7c7ee4d0a556a46e0e8
dsplaymaxxis/4linux-teste
/aula2/aula2 ex1.py
673
4.21875
4
#!/usr/bin/python3 #alterar vogais por asterisco #jeito 1 palavra = input('Digite Palavra: ') vogais = 'aeiou' troca = '' for k in palavra: if k in vogais: troca += '*' else: troca += k print(troca) exit() #jeito 2 vogais = 'aeiouAEIOUáéíóúÂÊÎÔÛ' palavra = input('Digite Palavra: ') for k in palavra: if k in vogais: palavra = palavra.replace(k,'*') print(palavra) exit() #como detectar se uma palavra é palindromo palavra = input('Digite uma Palavra: ') if palavra == palavra[:: -1]: #[:: -1] este é o comando para a variavel ao contrario print (palavra + ' é palíndromo') else: print (palavra + ' não é palíndromo') exit()
false
f88a428b294348655fba37c81c51cce6976e75aa
RumorsHackerSchool/PythonChallengesSolutions
/Guy/hackerrank.com/Python_Division.py
596
4.15625
4
''' Task Read two integers and print two lines. The first line should contain integer division, // . The second line should contain float division, / . You don't need to perform any rounding or formatting operations. Input Format The first line contains the first integer, . The second line contains the second integer, . Output Format Print the two lines as described above. ''' from __future__ import division if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) if a > b: print int(a/b) print float(a/b) else: print int(b/a) print float(b/a)
true
edcc1681efd32fb99d9c6e3ad28109cc9073e54e
tahniyat-nisar/if_else
/comparing ages.py
606
4.125
4
aryan=int(input("enter the age of aryan:")) arjun=int(input("enter the age of arjun:")) arav=int(input("enter the age of arav:")) if (aryan<(arjun and arav)) and ((arjun and arav)>aryan) : print("aryan is younger brother of arjun and arav\narjun and arav are elder brothers of aryan") elif (arjun<aryan and arav) and (aryan and arav>arjun): print("arjun is younger brother of aryan and arav\naryan and arav are elder brothers of arjun") elif (arav<arjun and aryan) and (arjun and aryan >arav): print("arav is younger brother of aryan and arjun\narjun and aryan are elder brothers of arav")
false
88178fe718a377817fbc9100a5d790ba5ca2798a
tahniyat-nisar/if_else
/based on age and gender wages.py
356
4.15625
4
age=int(input("enter age upto 40 only:")) gender=(input("enter as M for male and F for female:")) if age>=18 and age<30: if gender=="M": print("wage/day=700") elif gender=="F": print("wage/day=750") elif age>=30 and age<=40: if gender=="M": print("wage/day=800") elif gender=="F": print("wage/day=850")
false
995a1bbf95d98be9fd0ad66d4ffdbef299e9b78d
sudharkj/ml_scripts
/regression/regression_template.py
1,426
4.125
4
# From the course: Machine Learning A-Z™: Hands-On Python & R In Data Science # https://www.udemy.com/machinelearning/ # dataset: https://www.superdatascience.com/machine-learning/ # Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import the dataset dataset = pd.read_csv('data/Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values # Split the dataset # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # Scale the dataset # from sklearn.preprocessing import StandardScaler # sc_X = StandardScaler() # X_train = sc_X.fit_transform(X_train) # X_test = sc_X.transform(X_test) # Fit the regression model # Predict with regression model # y_pred = regressor.predict(6.5) # Visualize regression model plt.scatter(X, y, color='red') # plt.plot(X, regressor.predict(X), color='blue') plt.title("Truth or bluff (Regressor Model)") plt.xlabel("Position Level") plt.ylabel("Salary") plt.show() # Visualize regression model (for higher resolution and smoother curve) X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape(len(X_grid), 1) plt.scatter(X, y, color='red') # plt.plot(X_grid, regressor.predict(X_grid), color='blue') plt.title("Truth or bluff (Smoother Regressor Model)") plt.xlabel("Position Level") plt.ylabel("Salary") plt.show()
true
d73be7748c66e2a6d3a50c8d884b4e713dc1b92d
sudharkj/ml_scripts
/regression/simple_linear_regression.py
1,252
4.34375
4
# From the course: Machine Learning A-Z™: Hands-On Python & R In Data Science # https://www.udemy.com/machinelearning/ # dataset: https://www.superdatascience.com/machine-learning/ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('data/Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values # Split the dataset from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0) # fit the data from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the test set y_pred = regressor.predict(X_test) # Visualising the Train set plt.scatter(X_train, y_train, color='red') plt.plot(X_train, regressor.predict(X_train), color='blue') plt.title("Salary vs Experience (Train Set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show() # Visualising the Test set plt.scatter(X_test, y_test, color='red') plt.plot(X_train, regressor.predict(X_train), color='blue') plt.title("Salary vs Experience (Test Set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show()
true
3e8b56b106e9a5172de1592b9669bb35303af4a6
Vaild/python-learn
/teacher_cade/day19/9.next和iter的迭代器.py
1,004
4.21875
4
#!/usr/bin/python3 # coding=utf-8 from collections.abc import Iterator class MyIterator(): """自定义的供上面可迭代对象使用的一个迭代器""" def __init__(self): self.mylist = [] # current用来记录当前访问到的位置 self.current = 0 def add(self, val): self.mylist.append(val) # 调用next方法时,其实就是执行__next__ def __next__(self): if self.current < len(self.mylist): item = self.mylist[self.current] self.current += 1 return item else: raise StopIteration def __iter__(self): return self if __name__ == '__main__': myIterator = MyIterator() myIterator.add(1) myIterator.add(2) myIterator.add(3) myIterator.add(4) myIterator.add(5) print(isinstance(myIterator, Iterator)) # print(next(myIterator)) # 打印结果是多少 # for num in myIterator: # print(num) next(myIterator)
false
c5cc75fe885f14f205e2b0db8255ef3c580f0684
Vaild/python-learn
/teacher_cade/day19/7.对象可迭代的.py
533
4.3125
4
#!/usr/bin/python3 # coding=utf-8 class MyList(object): def __init__(self): self.container = [] def add(self, item): self.container.append(item) # 对象就是可迭代的 def __iter__(self): return iter(self.container) mylist = MyList() mylist.add(1) mylist.add(2) mylist.add(3) for num in mylist: print(num) from collections import Iterable print(isinstance(mylist, Iterable)) from collections import Iterator print(isinstance(mylist, Iterator)) print(isinstance([], Iterator))
true
307cd2f8ccdcf9abd2e077ed313a81e7cd574989
Yuanchao07/100day
/which_days.py
561
4.34375
4
def is_leap_year(year): return year % 4 == 0 and year != 100 or year % 400 == 0 def which_day(year, month, day): days_of_month = [ [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ] days = days_of_month[is_leap_year(year)] total = 0 for index in range(month-1): total += days[index] return total + day print(which_day(1980, 11, 28)) # 333 print(which_day(1981, 12, 31)) # 365 print(which_day(2018, 1, 1)) # 1 print(which_day(2016, 3, 1)) # 61
false
1e252b0287dd1146885882d9443fa506a41cdfc6
chris-miklas/Python
/Lab01/reverse.py
269
4.1875
4
#!/usr/bin/env python3 """ Print out arguments in reverse order. """ import sys def reverse(): """ Printing arguments in reverse order. """ for i in range(len(sys.argv)-1, 0, -1): print(sys.argv[i]) if __name__ == "__main__": reverse()
true
86ffb3138d8eb92b4fb9d7834b8411a9e77e1b57
leoswaldo/acm.tju
/2968_Find-the-Diagonal/find_the_diagonal.py
1,969
4.4375
4
#!/python3/bin/python3 # A square matrix contains equal number of rows and columns. If the order of # the matrix is known it can be calculated as in the following format: # Order: 3 # 1 2 3 # 4 5 6 # 7 8 9 # Order: 5 # 1 2 3 4 5 # 6 7 8 9 10 # 11 12 13 14 15 # 16 17 18 19 20 # 21 22 23 24 25 # # and so on.. # # Now look at the diagonals of the matrices. In the second matrix - the # elements of a diagonal are marked with circles but this is not the only one # in this matrix but there are some other minor diagonals like <6, 12, 18, 24> # as well as <2, 8, 14, 20> and many others. # Input # # Each input line consists of two values. The first value is the order of the # matrix and the later is an arbitrary element of that matrix. The maximum # element of the matrix will fit as a 32-bit integer. # Output # # Each output line will display the diagonal elements of the matrix containing # the given input element. # Sample Input # # 4 5 # 5 11 # 10 81 # # Sample Output # # 5 10 15 # 11 17 23 # 81 92 def find_diagonals(diagonal_questions): # Need to know how many questions are, to iterate for each one and get its # answer questions = len(diagonal_questions) # Iterate for each question for current_question in range(0, questions): # Get order and number to look for order = diagonal_questions[current_question][0] number = diagonal_questions[current_question][1] numbers = '' # Iterate throug the virtual matrix to find all the diagonal members, # avoid breaking the limits using the order * order while(number < (order * order)): numbers += str(number) + " " # Add order to break line in diagonal, add 1 to make it diagonal # to the right number += order + 1 print(numbers) # Test scenarios find_diagonals([[4, 5], [5, 11], [10, 81]])
true
24d17e612bfc874dc12d9e3c03d8eb020bf9158a
RanjaniMK/Python-DataScience_Essentials
/creating_a_set_from_a_list.py
250
4.34375
4
# Trying to create a set from a list # 1. create a list # 2. create a set my_list = [1,2,3,4,5] my_set = set(my_list) print(my_set) #Note: The list has square brackets # The output of a set has curly braces. Like below: # {1, 2, 3, 4, 5}
true
5c05985b4974bd8282c20678ff326cf61407b99e
VictorTruong93/dictionary_exercises_python
/dictionary_recap.py
839
4.40625
4
# Dictionaries aka # Hashes, HashMap, HashTables, Object, Map # places = { # 'farm burger': '1234 piedmont, atlanta', # 'naan stop': '12345 piedmont, atlanta', # } # what is the address of farm burger? # print(places['farm burger']) friends = { 'Europe':{ 'Paris': ['Frankie','Grace'], 'Berlin': ['Bobbie'] }, 'Asia': ['my cousin', 'my other cousin', 'their friend'], 'US': { 'Angela':{ 'pets':{ 'Oakley': { 'toys':['everything' ] } } } } } #directs to berlin friends['Europe']['Berlin'] friends['Europe']['Paris'][0] #directs to Grace friends['US']['Angela']['pets']['Oakley']['toys'] for item in friends['toys'][0]: print('%s is one of Oakley\'s fav toys' %( item))
false
0d55e9a32e80e3bf70ef0534f9f8bda1cec61684
gjwlsdnr0115/Computer_Programming_Homework
/lab5_2015198005/lab5_p1.py
431
4.28125
4
# initialize largest number variable largest_num = 0 # variable to stop while loop more = True while(more): num = float(input('Enter a number: ')) if(num > largest_num) : largest_num = num if(num == 0): more = False if(largest_num > 0): # if there was a positive number input print('The largest number entered was', format(largest_num, '.2f') ) else: print('No positive number was entered')
true
cca53fa2eae57d9c6a933cb4130a475c8cf3187c
gjwlsdnr0115/Computer_Programming_Homework
/lab2_2015198005/lab2_p5.py
246
4.375
4
print('This program will convert degrees Celsius to degrees Fahrenheit') celsius = float(input('Enter degrees Celsius: ')) fahren = celsius * 9/5 + 32 print(celsius, 'degrees Celsius equals', format(fahren, '.1f'), 'degrees Fahrenheit')
false
069739315c2e7c0c2a2f8e62fb2f4338cb767650
grahamh21/Python-Crash-Course
/Chapter 4/Try_it_yourself_chapter_4_2.py
1,560
4.34375
4
#Try_it_yourself 4-7 print('Try it yourself 4-7') threes = list(range(3,31,3)) for three in threes: print(three) #Try_it_yourself 4-8 print('Try it yourself 4-8\n') cubes = [] for cube in range(1,11): cubes.append(cube**3) print(cubes) #Try_it_yourself 4-9 print('Try it yourself 4-9') #list comprehension cubed = [quark**3 for quark in range(1,11)] print(cubed) #range() function generates a series of numbers #from there, you can manipulate it in a list comprehension or other ways #Try_it_yourself 4-10 print('Try it yourself 4-10: Slices') colors = ['red', 'blue', 'orange', 'green', 'yellow', 'black', 'white'] print('The first three items in the list are:') print(colors[0:3]) print('The middle three items in the list are:') print(colors[2:5]) print('The last three items in the list are:') print(colors[-3:]) #Try_it_yourself 4-11 print('Try it yourself 4-11: pizzas') my_pizzas = ['cheese', 'pepperoni', 'mushroom', 'meat', 'veggie', 'cream'] friend_pizza = my_pizzas[:] print(my_pizzas) print(friend_pizza) my_pizzas.append('frank') friend_pizza.append('charlie') print('My favorite pizzas are:') for pizzas in my_pizzas: print(pizzas) print('\n') for pizzas2 in friend_pizza: print(pizzas2) #Try_it_yourself 4-12 print('Try it yourself 4-12: tuples') buffet = ( 'chicken', 'beef', 'cheese', 'meat', 'pork' ) for food in buffet: print(food) #buffet[1] = 'cow' print('\n') buffet = ( 'beer', 'water', 'cheese', 'meat', 'pork' ) for food in buffet: print(food)
true
e21813eeb1869e5f1776dc82d68f08b17a02c9af
grahamh21/Python-Crash-Course
/Chapter 9/dog.py
821
4.1875
4
class Dog(): '''Simple dog class''' def __init__(self, name, age): '''Initialize name and age attributes''' self.name = name self.age = age def sit(self): '''simulate a dog sitting in response to a command''' print(self.name.title() + ' is now sitting.') def roll_over(self): '''simulate a dog rolling over in response to a command''' print(self.name.title() + ' rolled over!') my_dog = Dog('lily', 6) print('My dogs name is ' + my_dog.name.title() + '.') print('My dog is ' + str(my_dog.age) + ' years old!') print('\n') old_dog = Dog('murphy', 11) print('My dogs name is ' + old_dog.name.title() + '.') print('My dog is ' + str(old_dog.age) + ' years old!') old_dog.sit() old_dog.roll_over()
false
e22b71585457b49b0e2a9c4525ce003b9c84ed76
grahamh21/Python-Crash-Course
/Chapter 9/Try_it_yourself_Chapter_9_Part_6.py
2,010
4.34375
4
#Try it yourself 9-8: Privileges class User(): '''A way to model a user''' def __init__(self, first_name, last_name, job, birth_month, birth_year): self.first_name = first_name self.last_name = last_name self.job = job self.birth_month = birth_month self.birth_year = birth_year self.login_attempts = 0 def describe_user(self): print('First Name: ' + self.first_name.title()) print('Last Name: ' + self.last_name.title()) print('Job: ' + self.job) print('Birth Month: ' + self.birth_month.title()) print('Birth Year: ' + str(self.birth_year)) def greet_user(self): print('Hello ' + self.first_name.title() + ' ' + self.last_name.title() + '.') def increment_login_attempts(self): '''increment login attempts by 1''' self.login_attempts += 1 def reset_login_attempts(self): '''resets login attempts''' self.login_attempts = 0 #notice not 2 equal signs, only 1 class Privileges(): '''Defining class to be used as an attribute.''' def __init__(self, privileges=[]): '''Initializing the privileges class.''' self.privileges = privileges self.privileges = ['can add post', 'can delete post', 'can ban user'] def show_privileges(self): '''shows a list of the Admin privileges.''' for privilege in self.privileges: print('-' + privilege) class Admin(User): '''child class for Admins.''' def __init__(self, first_name, last_name, job, birth_month, birth_year): '''Initializing the Admin Child class.''' super().__init__(first_name, last_name, job, birth_month, birth_year) self.privileges = Privileges() kmoney = Admin('karson', 'lattamore', 'nurse', 'december', 1989) kmoney.privileges.show_privileges()
false
2ecb0b4693bdf1151e12e928a88c8daed10cb93e
IagoFrancisco22/listaDeExerciciosPython
/Quarta lista de exercicios Python/exercicio4.py
1,395
4.34375
4
import os print(''' Seja o statement sobre diversidade: “The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you.”. Gere uma lista de palavras deste texto com split(), a seguir crie uma lista com as palavras que começam ou terminam com uma das letras “python”. Imprima a lista resultante. Não se esqueça de remover antes os caracteres especiais e cuidado com maiúsculas e minúsculas. ''') palavras= '''The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you.''' palavras=palavras.lower() palavras=palavras.replace(',',' ') palavras=palavras.split() palavraspython=[] for i in range(0,len(palavras)): if palavras[i].startswith(tuple("python"))or palavras[i].endswith(tuple("python")): palavraspython.append(palavras[i]) print(palavraspython)
false
38c726a507f57fe39460d94ae50a9fb214de35b8
IagoFrancisco22/listaDeExerciciosPython
/Primeira lista de exercicios Python/exercicio8.py
277
4.15625
4
#enunciado print('''Converta uma temperatura digitada em Fahrenheit para Celsius.''') f=int(input("Digite o valor da temperatura em Fahrenheit:")) #temperatura em celsius C = ((f-32)/9)*5#conversao para celsius (F = 9*C/5 + 32) print("A temperatura e de",C,"Celsius")
false
4cfe68342c6d0ce20d2a7657ca106b29259b3345
Akshat111999/Python
/problem03.py
476
4.15625
4
#take a list say adhoc=[1,2,3,1,4,5,66,22,2,6,0,9] #write the program that will do #i) print only those numbers greater than 5 #ii) also print those numbers those are less than or equals to 2 ( <= 2 ) #iii) store these answers in in two different list also adhoc = [1,2,3,1,4,5,66,22,2,6,0,9] for i in adhoc: if i>5: print(i) for i in adhoc: if i<=2: print(i) a = [ i for i in adhoc if i<=2] print(a) b = [i for i in adhoc if i>5] print(b)
false
d755294e211e66c44e04c990d383650b061d087c
ly21st/my-algorithm
/python-vsc/geekbangtrain/week01/1c/1c_python.py
2,222
4.21875
4
# 1 Python是一门简洁的语言 int temp = var1 ; var1 = var2 ; var2 = temp ; var2, var1 = var1, var2 # 2 所有语言的开头 Hello world print('Hello, World') # 3 Python可交互可字节码 >>> x = 1 >>> help(x) >>> dir() >>> exit() # 4 内置数据类型 数值 布尔 字符串 列表、元组、字典、集合 # 4.1 数值常见有 整数、浮点数、复数、布尔值 整数 1 -5 100 8888 整数没有大小限制,受限于内存 浮点数 2.5 4.8 复数 1+2j 5.6+7.8j 布尔 True 、 False 数值支持算数运算 + - * / //整数除法 %求模 **求幂 支持数学函数 import math math.pow(2, 3) # 4.2 字符串 string 'a' "a" '''a''' """a""" # 4.3 列表 list [] x = [1, 'a', 'A'] 列表可以通过下标访问 x[0] x[-1] Python支持对列表的内置函数 len max min 也支持列表本身的方法 append count extend index insert pop remove reverse sort len(x) x.reverse() 还支持操作符 in + * 参考: 官方文档-教程 # 4.4 元组 tuple 元组和列表类似,但是一旦被创建就不可修改, 支持操作符 、内置函数 本身的方法只能支持两个 count index 可以显式转换 y = tuple(x) z = list(y) type(z) # 4.5 字典 dict 字典本质是哈希表,key只能是数值、字符串、元组 dict1 = {'a':1, 'b':2} 本身的方法支持copy、get、items、keys、values、update # 4.6 集合 set 由基本对象组成的无序集,特点:唯一性 set1 = set([1, 2, 3, 4, 5, 3, 2, 1]) print(set1) # 5 流程控制 False 0 零值None 空(列表、字典、字符串等) 表示假值 True 其他值 表示真值 # 5.1 if x = 1 if x < 10: y = 1 elif x > 10: y = 2 else: y = 3 z = 4 代码块与缩进 # 5.2 while (支持break continue) x = 2 y = 1 while x > y : pass # 5.3 for (支持break continue) for i in z: print(i) # 6 函数 def func1(x, y): return x + y print(func1(10, 20)) # 7 面向对象 class DemoClassName: def __init__(self, x, y): self.x = x self.y = y def add(self): return self.x + self.y demo = DemoClassName(10, 20) print(demo.add()) # 8 标准库的引入 import datetime datetime.date.today() from datetime import date date.today()
false
d758a3f7db1391f62de60fafdb8396d8977f1e70
sudheer-sanagala/edx-python-course
/WEEK-01/square_of_numbers.py
522
4.125
4
""" Square of a given number ex: 3^2 = 3*3 = 9; 5^2 = 5*5 = 25 """ # using while-loop x = 4 ans = 0 itersLeft = x # no of iterations remaining while(itersLeft != 0): # while no of iterations not equal to 0 ans = ans + x # add the same number by itself for thje total no of loops itersLeft = itersLeft - 1 # reduce the iteration loop by 1 print(str(x) + '*' + str(x) + ' = ' + str(ans)) # using for-loop x = 4 ans = 0 for i in range(x): ans = ans + x print(str(x) + '*' + str(x) + ' = ' + str(ans))
true
1c6a01ffad2fabee405191e2e4d6e5a6f094d55f
meltedfork/Python-1
/Python Assignments/Bike_Assignment/bike.py
890
4.21875
4
class bike(object): def __init__(self,price, max_speed,miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print self.price,self.max_speed,self.miles return self def ride(self): print "Riding..." self.miles+=10 print "Total miles on bike is",self.miles return self def reverse(self): if self.miles < 5: print "Cannot reverse below zero, you moron." return self print "Reversing..." self.miles-=5 print "Total miles on bike is",self.miles return self Blue = bike(450,"25mph") Red = bike(300, "15mph") Yellow = bike(375, "22mph") Blue.ride().ride().ride().reverse().displayInfo() Red.ride().ride().reverse().reverse().displayInfo() Yellow.reverse().reverse().reverse().displayInfo()
true
aa894da9a10e60a2de42056c4c9be3733f1631fb
meltedfork/Python-1
/Python Assignments/dictionary_basics/dictionary_basics.py
287
4.15625
4
def my_dict(): about = { "Name": "Nick", "Age": "31", "Country of birth": "United States", "Favorite Language": "Italian" } # print about.items() for key,data in about.iteritems(): print "My", key, "is", data my_dict()
true
3bed285f835cc5e500ae14e0daaa9d738a53efcf
TamizhselvanR/TCS
/alternative_series.py
967
4.25
4
''' For Example, consider the given series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Now write a program to find the Nth term in this series. ''' def primefn(n): new_term = n // 2 count = 0 for i in range(1, 1000): flag = 1 if (i > 1): for j in range(2, i): if (i % j == 0): flag = 0 break if (flag == 1): prime = i count += 1 if (count == new_term): print(prime) break def fibbo(n): new_term = (n+1) // 2 t1 = 0 t2 = 1 for i in range(1, new_term + 1): next = t1 + t2 t1 = t2 t2 = next print(t1) n = int(input()) if(n % 2 == 0): primefn(n) else: fibbo(n)
true
7d6a397767236554fe50d29a043682d9ac471a6c
ddilarakarakas/Introduction-to-Algorithms-and-Design
/HW3/q4.py
1,373
4.21875
4
import random swap_quicksort=0 swap_insertion=0 def quick_sort(array, low, high): if low<high: pivot = rearrange(array, low, high) quick_sort(array, low, pivot - 1) quick_sort(array, pivot + 1, high) def rearrange(array,low,high): global swap_quicksort p = array[high] left = low-1 for i in range(low,high): if array[i]<p: left+=1 array[i], array[left] = array[left], array[i] swap_quicksort += 1 array[left+1], array[high] = array[high], array[left+1] swap_quicksort += 1 return left+1 def insertionSort(arr): global swap_insertion for i in range(2,len(arr)): current=arr[i] position=i-1 while position>=1 and current < arr[position]: swap_insertion+=1 arr[position+1] = arr[position] position=position-1 arr[position+1]=current if __name__ == "__main__": arr1=[] for i in range(0,1000): arr1=[] for i in range(0,1000): arr1.append(random.randint(0,10000)) arr2=arr1[:] quick_sort(arr1,0,len(arr1)-1) insertionSort(arr2) print("Average count for quicksort = " + str(swap_quicksort/1000)) print("Average count for insertionsort = " + str(swap_insertion/1000)) #It is a bit slow because it works with 1000 sizes.
true
42d6ade9eec3f1abb794bf4f544026fb83451bfe
JuanDiazUPB/LogicaProgramacionUPB
/Laboratorios/Lab1604/Ejercicio 1.py
470
4.1875
4
def validacion(email): for x in email: if direccion.endswith("@gmail.com") or direccion.endswith("@hotmail.com") or direccion.endswith("@outlook.com"): # endswith valida la ultima parte de la cadena return True return False direccion = input("Ingresa tu email: ") if validacion(direccion): print("Dirección válida:", direccion) else: print("Dirección inválida (debe tener @gmail, @hotmail o @outlook)")
false
fa6192cee5ee11b819b8037ad641333ded8f9422
Bpara001/Python_Assgn
/03 Functions/varargs_start.py
445
4.1875
4
# Demonstrate the use of variable argument lists # TODO: define a function that takes variable arguments def addition(*args): result = 0 for arg in args: result +=arg return result def main(): # TODO: pass different arguments print(addition(5,10,20,30)) print(addition(1,2,3)) # TODO: pass an existing list Mynums = [4 , 8 ,10 ,12] print (addition(*Mynums)) if __name__ == "__main__": main()
true
504e64c3d0be1d03c044c54594c9af6785539da2
samsnarrl22/Beginner-Projects
/Song Variables.py
1,116
4.28125
4
# Storing attributes about a song in Variables # First create variables for each of the characteristics that make up a song title = "Ring of Fire" artist = "Jonny Cash" # These variables are strings which can be seen due to the "" album = "The Best of Johnny Cash" genre = "Country" time_in_seconds = 163 # time_in_seconds is an integer beats_per_minute = 103.5 # beats_per_minute is a float track_number = "1" # These variables will appear like integers but are strings year_released = "1967" # Now its time to print these variables so we can see them in the console print(title) print(artist) print(album) print(genre) print(time_in_seconds) print(beats_per_minute) print(track_number) print(year_released) """This shows us the information stored in the variable. However it is just a random list at this point so it would like better if they were defined""" print("Title: ", title) print("Artist: ", artist) print("Album: ", album) print("Genre: ", genre) print("Track length (s): ", time_in_seconds) print("BPM", beats_per_minute) print("Track Number: ", track_number) print("Year Released: ", year_released)
true
984863b3ccb43eb11025cd1aae499deee7d6acec
sicp/ikoma-sicp
/oza/2/2-17,23.py
1,132
4.125
4
# last_pair #class mytuple: # # def __init__(self, t): # self.tpl = t # # def car(self): # return self.tpl[0] # # def cdr(self): # return self.tpl[1:] # # def last_pair(self): # # return (self.tpl(-1),) # l = len(self.tpl) # return (self.tpl[l-1],) # # def __str__(self): # return str(self.tpl) # #t = mytuple((1,2)) #print(t) #print(t.last_pair()) def make_rlist(first, rest): return (first, rest) def first(s): return s[0] def rest(s): return s[1] empty_rlist = None counts = make_rlist(1, make_rlist(2, make_rlist(3, make_rlist(4, empty_rlist)))) print(counts) # (1, (2, (3, (4, None)))) def len_rlist(s): """Return the length of recursive list s.""" length = 0 while s != empty_rlist: s, length = rest(s), length + 1 return length def getitem_rlist(s, i): """Return the element at index i of recursive list s.""" while i > 0: s, i = rest(s), i - 1 return first(s) print(len_rlist(counts)) print(getitem_rlist(counts, 1)) def last_pair(tpl): if tpl[0] == empty_rlist: return tpl while tpl[1] != None: tpl = rest(tpl) return (tpl[0],) print(last_pair(counts)) print(last_pair((None,)))
false
5656d54460e0742abd2340bbcd6e61024858e0d7
Zaliann/practice
/практика 2/lab2-2.py
1,023
4.4375
4
# Целые числа и числа с плавающей точкой являются одними из самых распространенных в языке Python number = 9 print(type(number)) # Вывод типа переменной number float_number = 9.0 # Создайте ещё несколько переменных разных типов и осуществите вывод их типов lenn = 2.4 snake = 4 stroch = "Площадь - произведение длины и ширины прямоугольника" print(type(lenn)) print(type(snake)) print(type(stroch)) # Существует множество функций, позволяющих изменять тип переменных. # Изучите такие функции как int(), float(), str() и последовательно примените их к переменным, созданным ранее. print(type(float(snake))) print(type(int(lenn))) print(type(str(lenn))) print(int(float_number))
false
fe7e22bfd1dac7b4c1bf88c09e7cf02eed311563
Andresdamelio/master-python
/08 - Funcionalidades avanzadas/funcion-map.py
1,707
4.15625
4
# encoding: utf-8 """ ============================================================================================== FUNCION MAP ============================================================================================== """ # Trabaja de forma similar a filter, a diferencia de que en lugar de aplicar una condicion a un elemento de una lista o secuencia, aplica una funcion sobre todo los elementos y como resultado se devuelve un iterable de tipo map # Ejemplo numeros = [2,5,10,23,50,33] # Funcion para doblar todos los elementos de la lista def doblar(numero): return numero*2 m = map(doblar, numeros) print(m) # El mismo ejemplo se puede crear usando la funcion anonima lambda m = map(lambda numero: numero*2, numeros) print(m) # Se puede utilizar para operar sobre listas de misma longitud a = [1,2,3,4,5] b = [6,7,8,9,10] c = [11,12,13,14,15] print(map( lambda a,b,c: a*b*c, a,b,c )) # utilizando map con objetos class Persona(): def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def __str__(self): return "Nombre: {} de {} annos".format(self.nombre, self.edad) personas = [ Persona("Andres",22), Persona("Juan",35), Persona("Manuel",16), Persona("Eduardo",12), Persona("Jose",78), ] # funcion normal def incrementar(persona): persona.edad +=1 return persona personas = map(incrementar, personas) for persona in personas: print(persona) # Tambien es posible hacer el ejemplo anterior utilizando la funcion lambda personas = map( lambda persona: Persona(persona.nombre, persona.edad+1), personas ) for persona in personas: print(persona)
false
f66969d71e58004f000e966988c4ec81dd9679ad
Andresdamelio/master-python
/08 - Funcionalidades avanzadas/funcion-filter.py
1,828
4.5
4
# encoding: utf-8 """ ============================================================================================== FUNCION FILTER ============================================================================================== """ # Tal como su nombre lo indica su funcion es filtrar, a partir de una lista o iterador y una funcion condicional es capaz de devolver una nueva coleccion con los elementos filtrados que cumplan la condicion numeros = [2,5,10,23,50,33] # Obtener numeros multiples de 5 # Esta funcion devuelve los elementos que son multiples de 5 def multiple(numero): if(numero % 5 == 0): return True # la funcion filter de usa de la siguiente manera, el primer argumento debe ser la funcion que hara la logica, es decir, la funcion que devulve los elementos a filtrar, y el segundo argumento son los elementos que sera filtrados, en este caso se utiliza el cash list() para que el filtrado sea devuelto en una lista, por defecto la funcion filter devuelve un objeto iterable print(list(filter(multiple, numeros))) # Transformar el ejemplo anterior a una funcion anonima lambda, para reducir la cantidad de lineas de codigo print( filter( lambda numero: numero%5 == 0, numeros )) # Ejemplo con una lista de personas, para filtrar las personas menores de edad class Persona(): def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def __str__(self): return "Nombre: {} de {} años".format(self.nombre, self.edad) personas = [ Persona("Andres",22), Persona("Juan",35), Persona("Manuel",16), Persona("Eduardo",12), Persona("Jose",78), ] # Comprabar las personas menores de edad menores = filter( lambda persona: persona.edad < 18, personas) for menor in menores: print(menor)
false
80ff22bf321c958b2b71b97a0c2eada9d23a9bf3
Andresdamelio/master-python
/02 - Entrada y salida/salida.py
2,950
4.125
4
""" ====================================================================== Salida de datos ====================================================================== """ v = "otro texto" n = 10 print("un texto", v, "y un numero", n) # Para evitar escribir muchos print, e ir colocando variables separadas por una coma ("."), podemos usar el .format, veamos c = "un texto {} y un numero {}".format(v,n) # Con esto estamos indicando que la cadena va a recibir dos valores, uno en cada {}, con esto especificamos que vamos a introducir cualquier valor, estos valores son pasados como argumentos en el .format, y se iran colocando de acuerdo al orden en que aparecen en la cadena de texto """ ====================================================================== Colocando los valores por posicion ====================================================================== """ c = "un texto {0} y un numero {1}".format(v,n) print(c) #Al colocar un indice entre las llaves, estamos diciendo la posicion del elemento dentro del .format que mostraremos """ ====================================================================== Colocando letras para los valores ====================================================================== """ c = "un texto {texto} y un numero {numero}".format(texto=v,numero=n) print(c) """ ====================================================================== Alinear a la derecha ====================================================================== """ print("{:>40}".format("Alineamiento derecha")) #En este caso nos permite alinear a la derecha un string con 40 espacios a la derecha, incluyendo el texto """ ====================================================================== Alinear a la izquierda ====================================================================== """ print("{:40}".format("Alineamiento izquierda")) """ ====================================================================== Alinear al centro ====================================================================== """ print("{:^40}".format("Alineamiento central")) """ ====================================================================== Truncar ====================================================================== """ #Como truncar una palabra de izquierda a derecha print("{:.4}".format("Truncamiento")) """ ====================================================================== Formateo de numeros enteros ====================================================================== """ print("{:04d}".format(10)) print("{:04d}".format(100)) print("{:04d}".format(1000)) #salida por consola """ 0010 0100 1000 """ """ ====================================================================== Formateo de numeros flotantes ====================================================================== """ print("{:07.3f}".format(3.1415926)) print("{:07.3f}".format(153.21))
false
b6a30271fa2adfcb89ae1b1fb658fdeae0dce67c
Andresdamelio/master-python
/08 - Funcionalidades avanzadas/compresion-listas.py
2,669
4.5625
5
# COMPRESION DE LISTAS # Es una forma de optimizar las lineas de codigo al crear una lista de elementos ''' ====================================================================================================== CREANDO UNA LISTA CON LAS LETRAS DE UNA PALABRA ====================================================================================================== ''' # METODO TRADICIONAL lista = [] for letra in "palabra": lista.append(letra) print(lista) # COMPRESION DE LISTAS # Es una forma muy optima de crear una linea, ademas es sencillo, aqui estamos indicando que letra sera el elemento que se ira agregando, y despues se realiza el for iterando letra, implicitamente realiza los mismos pasos que el ejemplo tradicional lista = [letra for letra in "palabra"] print(lista) ''' ====================================================================================================== CREANDO UNA LISTA CON LOS NUMEROS DEL 1 AL 10 ELEVADOS A 2 ====================================================================================================== ''' # METODO TRADICIONAL numeros = [] for numero in range(0,11): numeros.append(numero**2) print(numeros) # COMPRESION DE LISTAS numeros = [numero**2 for numero in range(0,11)] print(numeros) ''' ====================================================================================================== CREANDO UNA LISTA CON LOS NUMEROS PARES DEL 1 AL 10 ====================================================================================================== ''' # METODO TRADICIONAL numeros = [] for numero in range(0,11): if( numero % 2 == 0): numeros.append(numero) print(numeros) # COMPRESION DE LISTAS numeros = [numero for numero in range(0,11) if numero%2==0] print(numeros) ''' ====================================================================================================== CREANDO UNA LISTA CON LOS NUMEROS PARES DEL 1 AL 10 CON POTENCIA 2 SACADOS DE OTRA LISTA ====================================================================================================== ''' # METODO TRADICIONAL # Creadndo una lista con los numeros del 1 al 10 elevados a 2 numeros = [] for numero in range(0,11): numeros.append(numero**2) print(numeros) # Creando una lista con numeros pares a partir de la creada pares = [] for numero in numeros: if(numero % 2 == 0): pares.append(numero) print(pares) # COMPRESION DE LISTAS pares = [ numero for numero in [potencia**2 for potencia in range(0,11)] if numero%2 == 0 ] print(pares)
false
88812cfba755cc4b06a8724ea3def8d51f18dd68
JinHoChoi0104/Python_Study
/Inflearn/chapter05_02.py
850
4.21875
4
# Chapter05-02 # 파이썬 사용자 입력 # Input 사용법 # 기본 타입(str) # ex1 # name = input("Enter Your Name: ") # grade = input("Enter Your Grade: ") # company = input("Enter Your Company name: ") # print(name, grade, company) # ex2 # number = input("Enter number: ") # name = input("Enter name: ") # print("type of number", type(number) * 3) # print("type of name", type(name)) # ex3 # first_number = int(input("Enter number1: ")) # second_number = int(input("Enter number2: ")) # # total = first_number + second_number # print("first_number + second_number: ", total) # ex4 # float_number = float(input("Enter a float number: ")) # print("input float: ", float_number*3) # print("input type: ",type(float_number)) # ex5 print("FirstName - {0}, LastName - {1}".format(input("Enter first name: "), input("Enter second name: ")))
true
df3b1b911ee16292a1cf94b1c9523c4b0ee2698a
Himanshuhub/Python
/python_fundamentals/Assignment-MultiplesSumAverage.py
299
4.15625
4
# Assignment: Multiples, Sum, Average # Multiples # Part 1 # for count in range(1,1000,2): # print count # Part 2 # for count in range(5,1000005, 5): # print count # Sum List list = [1, 2, 5, 10, 255, 3] print sum(list) # Average List a = [1, 2, 5, 10, 255, 3] print sum(a)/len(a)
false
9eb1e8456b09fc34a2d11c5c41c63d85704cc70c
JoyP7/BasicPythonProjects
/rock_paper_scissors.py
1,408
4.28125
4
from random import randint #create a list of play options t = ["Rock", "Paper", "Scissors"] #assign a random play to the computer computer = t[randint(0,2)] #set player to False player = False p_score = 0 c_score = 0 #here is the game while player == False: #case of Tie player = input("Rock, Paper, or Scissors?") if player == computer: print("That's a Tie!") elif player == "Rock": if computer == "Paper": print("You lose! You got covered by", computer) c_score += 1 else: print("You won! Your", player, "smashes", computer) p_score += 1 elif player == "Paper": if computer == "Scissors": print("You lose! You got cut by", computer) c_score += 1 else: print("You won! Your ", player, "covered", computer) p_score += 1 elif player == "Scissors": if computer == "Rock": print("You lose! You got smashed by", computer) c_score += 1 else: print("You won! Your",player, "cut", computer) p_score += 1 else: print("That's not a valid option! Please choose one three available options.") print("You:", p_score, "Computer:", c_score) #start the game over #set the player to False since it's True after a run player = False computer = t[randint(0,2)]
true
5ee2bde50b9cf56e40ca8bc146dd6085eba343d5
YunfeiZHAO/leetcode
/old/binary.py
897
4.21875
4
from typing import List def hammingDistance(x: int, y: int) -> int: ''' The Hamming distance between two integers is the number of positions at which the corresponding bits are different. ''' def DtoB(x: int) -> List[int]: L = [0] * 31 i = 0 while x != 0: L[30 - i] = x % 2 x = x // 2 i += 1 return L x_b = DtoB(x) y_b = DtoB(y) dist = 0 for xb, yb in zip(x_b, y_b): if xb != yb: dist += 1 return dist def hammingDistance2(x: int, y: int) -> int: return bin(x^y).count("1") def hammingDistance3(self, x: int, y: int) -> int: numDifferences = 0 while(x > 0 or y > 0): if (x & 0x01) != (y & 0x01): numDifferences += 1 x >>= 1 y >>= 1 return numDifferences if __name__ == "__main__": print(hammingDistance(2, 0))
false
b0652b6f3148c4213d754423c27d40276ef4baab
ddtriz/Python-Classes-Tutorial
/main.py
1,223
4.375
4
#BASIC KNOWLDEGE ABOUT CLASSES #What is a class? class firstClass():#Determine a class in the code by using [class] name = "" identification = 0 print ("hello") firstClass.name = "John" firstClass.identification = 326536123 #If you print the firstClass you'll get something like <class '__main__.firstClass> #That's because you're printing the class and not any attribute of it. #You can call them by using the [.] after firstClass #if you have a print in your class and you call it #(firstClass()) #it will act like a function. (In this case it will print #hello, as I wrote print("hello") in the class.) firstClass() #OUTPUT:[ hello ] print(firstClass)#OUTPUT:[ <class '__main__.firstClass> ] #Output using Attributes! :D print(firstClass.name)#OUTPUT:[ Jhon ] print(firstClass.identification)#OUTPUT:[ 326536123 ] #You can also create objects to use better classes. #It's like importing something as something. Example: #import pyaudio as pA #pA.listen() bla bla bla #You can do the same with classes. Just assign a name to the class: fC = firstClass() fC.name = "Rose" fC.identification = 112233445566 #That's all the basics about the classes, at least I think. #hope you like it and understood it.
true
f7f462a0cc00c3d68b8d0a5bd282151eea24fb9a
ECastro10/Assignments
/rock_paper_scissors_looped.py
2,085
4.125
4
#import random and computer signs list import random signchoices = ["rock", "paper", "scissors"] player1_score = 0 comp_score = 0 game = 0 while game < 3: hand1 = input("Enter rock, paper, or scissors Player1 > ").lower() compSign = random.choice(signchoices) print("Computer chooses " + compSign) if hand1 == "": print("Nothing was entered for Player 1, invalid game") elif hand1 == compSign: print("Tie!") elif hand1 == "rock" and compSign == "paper": print("Computer wins!") comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "paper" and compSign == "rock": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "paper" and compSign == "scissors": print("Computer wins!") comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "scissors" and compSign == "paper": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) elif hand1 == "scissors" and compSign == "rock": comp_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) print("Computer wins!") elif hand1 == "rock" and compSign == "scissors": print("Player1 wins!") player1_score += 1 game += 1 print("You have won {} games".format(player1_score)) print("The computer has won {} games".format(comp_score)) if comp_score > player1_score: print("Computer Wins!!!") else: print("You win, it was a fluke")
true
1432bcab9faa357c76e538108162711cc296a9aa
Charlesyyun/leetcode
/剑指 Offer 28. 对称的二叉树.py
1,570
4.1875
4
''' 剑指 Offer 28. 对称的二叉树 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。     1    / \   2   2  / \ / \ 3  4 4  3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:     1    / \   2   2    \   \    3    3   示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:root = [1,2,2,null,3,null,3] 输出:false   限制: 0 <= 节点个数 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: original = str(root) mirror = str(mirrorTree(root)) return original == mirror def mirrorTree(root: TreeNode) -> TreeNode: def flip(root): # 递归函数:根节点的左右翻转 if root == None: return root # 终止条件:如果根节点为空,直接返回 root.left, root.right = flip(root.right), flip(root.left) # 右节点翻转后赋值给左节点,左节点翻转后赋值给右节点 return root return flip(root)
false
695c5ac1414507b89920128ef98b87aadf843f17
TarunVenkataRamesh-0515/python-515
/setop.py
971
4.15625
4
#set operations set1={1,2,3,4,5,10,12,13} set2={10,11,12,13,14,15,17,19,1} s1={1,2,3,4,5,10,12,13} s2={10,11,12,13,14,15,17,19,1} a={1,2,3,4,5,10,12,13} b={10,11,12,13,14,15,17,19,1} #union()-->All the elements,returns the union as a new set u=set1.union(set2) print("union",u) #union and update """ in update union of elements will be updated to set1 and union method returns a new set """ set1.update(set2) print("update",set1) #intersection and intersection_update inter=s1.intersection(s2) print("intersection=",inter) s1.intersection_update(s2) print("intersection_update=",s1) #difference() and difference_update() c=b.difference(a) print("difference",c) b.difference_update(a) print("difference_update",b) #output union {1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 17, 19} update {1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 17, 19} intersection= {1, 10, 12, 13} intersection_update= {1, 10, 12, 13} difference {11, 14, 15, 17, 19} difference_update {11, 14, 15, 17, 19}
false
150747e7e7b6a368e0ac7af28d4a4d10358acdbb
mohitsharma2/Python
/Book_program/max_using_if.py
413
4.59375
5
# Program to accept three integers and print the largest of the three.Make use of only if statement. x=float(input("Enter First number:")) y=float(input("Enter Second number:")) z=float(input("Enter Third number:")) max=x if y>max: max=y if z >max: max=z print("Largest number is:",max) """ output===> Enter First number:12 Enter Second number:54 Enter Third number:45 Largest number is: 54.0 """
true
d2db2c0608a6ad6ca1f9c423c55ec4aeffef3939
mohitsharma2/Python
/Book_program/divisor.py
1,068
4.28125
4
#program to find the multiles of a number(divisor) out of given five number. print("Enter the five number below") num1=float(input("Enter first number:")) num2=float(input("Enter second number:")) num3=float(input("Enter third number:")) num4=float(input("Enter fourth number:")) num5=float(input("Enter fifth number:")) divisor=float(input("Enter divisor number:")) count=0 remainder=num1 % divisor if remainder ==0: print(num1) count+=1 remainder=num2 % divisor if remainder ==0: print(num2) count+=1 remainder=num3 % divisor if remainder ==0: print(num3) count+=1 remainder=num4 % divisor if remainder ==0: print(num4) count+=1 remainder=num5 % divisor if remainder ==0: print(num5) count+=1 print(count,"multiple of ",divisor,"found") """ output===> Enter the five number below Enter first number:10 Enter second number:5 Enter third number:15 Enter fourth number:20 Enter fifth number:26 Enter divisor number:5 10.0 5.0 15.0 20.0 4 multiple of 5.0 found """
true
e8fc3a72648cfd8d9b857012a27031e7a08b8357
mohitsharma2/Python
/Blackjack.py
1,629
4.3125
4
""" Name: Blackjack Filename: Blackjack.py Problem Statement: Play a game that draws two random cards. The player then decides to draw or stick. If the score goes over 21 the player loses (goes ‘bust’). Keep drawing until the player sticks. After the player sticks draw two computer cards. If the player beats the score they win. Data: Not required Extension: Aces can be 1 or 11! The number used is whichever gets the highest score. Hint: Not Available Algorithm: Not Available Boiler Plate Code: Not Available Sample Input: Not Available Sample Output: Not Available """ import random input1='' list1=[1,2,3,4,5,6,7,8,9,10,11,12,13] while(input1==''): a=random.choice(list1) b=random.choice(list1) if (a+b)>=21: print('you bust') else: c=random.choice(list1) d=random.choice(list1) if (a+b)>(c+d): print('You win') print('you have',a+b,'computer has',c+d) else: print('You loose') print('you have',a+b,'computer has',c+d) input1=input('Press "Enter" to continue:') ''' output=========================================================== You loose you have 7 computer has 16 Press "Enter" to continue: you bust Press "Enter" to continue: You loose you have 6 computer has 16 Press "Enter" to continue: You loose you have 19 computer has 22 Press "Enter" to continue: you bust Press "Enter" to continue: You loose you have 11 computer has 13 Press "Enter" to continue: You win you have 14 computer has 9 Press "Enter" to continue:h '''
true
3817d594c6261e8d7a51bd820a4c0ed2bfe36dd0
mohitsharma2/Python
/Book_program/sqrt.py
930
4.25
4
# program to calculate and print roots of a quadratic equcation : ax^2 + bx + c=0 (a!=0) import math print("for quadratic equcation : ax^2 + bx + c=0,enter cofficient below:") a=int(input("Enter a:")) b=int(input("Enter b:")) c=int(input("Enter c:")) if a==0: print("Value of 'a' should not be zero.") print("\n Aborting !!!") else: value = b*b - 4 * a * c if value>0: root1=(-b+math.sqrt(value))/(2*a) root2=(-b-math.sqrt(value))/(2*a) print("Roots are real and unequal") print("Root1=",root1,"Root2=",root2) elif value==0: root1= -b/(2*a) print("Roots are real and Equal") print("Root1=",root1,"Root2=",root1) else: print("Roots are Complex and Imaginary") """ output===> Enter a:3 Enter b:5 Enter c:2 Roots are real and unequal Root1= -0.6666666666666666 Root2= -1.0 """
true
0f1f74514cd78b6f952e24f923975d82a18e1260
mohitsharma2/Python
/Book_program/identify_character.py
474
4.3125
4
""" program to print whether a given character is an uppercase or a lowercase character or a digit or any other special character. """ inp1=input("Enter the Character:") if inp1>='A' and inp1<="Z" : print("You entered upper case character.") elif inp1>='a' and inp1<='z' : print("You entered lower case character.") elif inp1>='0' and inp1<='9' : print("You entered numeric character.") else: print("You entered special character.") 0
true
260ea2d6275282bb8ecc34d2488bbdca52459a45
mohitsharma2/Python
/gravity_cal.py
224
4.21875
4
# Gravity Calculator Acceleration=float(input('enter the Acceleration in m/s^2')) Time=float(input('enter the time in seconds ')) distance=(Acceleration*Time*Time )/ 2 print('object after falling for 10 seconds=',distance)
true
2c894119b5321d953fa1346d722d42f190de8c38
alexdavidkim/Python3-Notes
/numeric_types/booleans.py
2,949
4.53125
5
# All objects in Python have a Truthyness or Falsyness. All objects are True except: # None # False # 0 # Empty sequences (list, tuple, string, etc) # Empty mapping types (dictionary, set, etc) # Custom classes that implement a __bool__ or __len__ that returns False or 0 # Therefore, every built-in class in Python has a __bool__ or __len__ function # if 27: # print("I'm True!") # print(bool(None)) # if 0: # print("This won't print!") # my_empty_list = [] # if my_empty_list: # print("This won't print!") # my_truthy_list = [None] # if my_truthy_list: # print("Hello from my_truthy_list!") # class A: # def __bool__(self): # return self == 0 # a = A() # print(bool(a)) # The boolean operators are: not, and, or # Operator preference (Use parentheses even when not necessary): # () # < > <= >= == != in is # not # and # or # True and False will evaluate first becoming True or False # print(True or True and False) # Circuits - booleans are circuits (See Part 1 - Functional - Section 4:55) meaning a closed circuit allows electricity to flow through the circuit (True), and an open circuit cuts the circuit (False). A short-circuit evaluation example would be with the or operator. b doesn't need to be evaluated because a is already True. # a = -1 # b = False # if a or b: # print('Open circuit!') # Inversely, a False value on the left side of the equation with the and operator will short-circuit and always evaluate False. # a = False # b = True # if a and b: # print('This won\'t print') # else: # print('This short circuited!') # Imagine we want to populate data to a view function and we want to make sure there is always something to show the user. about_table_field represents an empty field in a database, therefore the about_me variable we use to populate data to the user will have the fallback data of 'n/a' # about_table_field = '' # about_me = about_table_field or 'N/A' # Again used as a fallback to ensure that b is not None # a = None # b = a or 1 # or - X or Y: if X is truthy, returns X, otherwise evaluates Y and returns it # print('a' or [1,2]) # print('' or [1,2]) # x = '' or 'N/A' # if x: # print(x) # else: # print('Error') # and - X and Y: if X is falsy, return X, otherwise if X is True, evaluate Y and return it # print(None and 100) # print(True and 'Evaluating Y') # We want to avoid a zero division error therefore, we can write an if statement or use the and operator # a = 2 # b = 0 # if b == 0: # print(0) # else: # print(a/b) # print(b and a/b) # We want to return the first character from a string if it exists # s1 = None # s2 = '' # s3 = 'Hello World' # print((s1 and s1[0]) or '') # print((s2 and s2[0]) or '') # print((s3 and s3[0]) or '') # not operator is different than and/or. not is not part of the bool class. and/or both return one of the objects. not returns True/False print(not True)
true
31981e806a88845bb143f49d24aaab942b79b990
alexdavidkim/Python3-Notes
/modules_packages/datetime_pytz.py
1,914
4.34375
4
# https://howchoo.com/g/ywi5m2vkodk/working-with-datetime-objects-and-timezones-in-python import datetime import pytz from pprint import pprint # -------------- Dates ------------------- dean_birthday = datetime.date(2017, 5, 30) # print(specific_date) today = datetime.date.today() # print(today) # print(f'Year: {today.year}, month: {today.month}, day: {today.day}') tdelta = datetime.timedelta(days=7) days_of_dean = today - dean_birthday # print(f'A week ago: {today - tdelta}, a week from today: {today + tdelta}') # print(f'It\'s been {days_of_dean.days} days since Dean was born!') # -------------- Times ------------------- t = datetime.time(9, 30, 45, 100000) # print(t) # print(f'Hours: {t.hour}, minutes: {t.minute}, seconds: {t.second}, microseconds: {t.microsecond}') # --------- Date, Times, Pytz -------------- # All of the above getters and time_delta etc work too # pprint(pytz.common_timezones) dt_today = datetime.datetime.today() # print(f'{dt_today} is the current date/time on this local machine.') # Could use .utcnow() but this isn't timezone aware. So use .now(tz=pytz.UTC). # Can pass in any timezone as argument. dt_utcnow = datetime.datetime.now(tz=pytz.UTC) print(dt_utcnow) # print(f'The current timezone aware UTC time is: {dt_utcnow}.') current_user_time = dt_utcnow.astimezone(pytz.timezone('US/Pacific')) # print(f'If I want to store UTC times in a db, I will need this variable: {current_user_time.time()} to display the users preferred time.') # ------------ Formatting ----------------- # https://docs.python.org/3/library/datetime.html dt_central = datetime.datetime.now(tz=pytz.timezone('US/Central')) # print(dt_central.strftime('%B %d, %Y')) dt_str = 'November 28, 2020' convert_dt_str = datetime.datetime.strptime(dt_str, '%B %d, %Y') # print(convert_dt_str)
false
30ab4a544a884fa139bbbe3c31e9286cccfc3ced
13424010187/python
/LearnPython3-master/10-range()的使用/test.py
634
4.28125
4
# 使用range()函数 # for val in range(5): # print(val) # for(int i = 0; i < 5; i++) { # } # 指定range()的范围 # for val in range(1, 5): # print(val) # for(int i = 1; i < 5; i++) { # } # 生成数组 # nums = list(range(1,5)) # print(range(1,5)) # print(nums) # 奇数数组 # nums = list(range(1,11,2)) # print(nums) # 偶数数组 # nums = list(range(0,11,2)) # print(nums) # 处理函数 # nums = [1,3,5,7,9,2,4,6,8,10] # print(min(nums)) # print(max(nums)) # print(sum(nums)) # lambda写法 nums = [val*2 for val in range(1,5)] print(nums) nums = [] for val in range(1,5): nums.append(val*2) print(nums)
false
d84fa31140a19d15dfd356bed0654068237b7be0
13424010187/python
/源码/10-诡秘的数字巧合/练习1成果包——水仙花数v1.0.py
1,012
4.15625
4
'''练习1成果包——水仙花数v1.0''' ''' 编写程序帮助阿短来判定一个三位整数是否为水仙花数。 输入一个三位整数,输出是否为水仙花数提示信息。 如: Input: 输入数字:123 Output: 123 不是水仙花数 ''' #判断一个数是不是水仙花数 num = int(input('输入数字:')) number= str(num) i = 0 # 循环计数器 daffodil = 0 # 用和原数number来对比的水仙花数 #主循环 while i < len(number): daffodil += int(number[i]) ** 3 i += 1 if int(number) == daffodil: print(number, '是水仙花数') else: print(number, '不是水仙花数') '''for循环实现''' # #判断一个数是不是水仙花数 # num = int(input('输入数字:')) # number= str(num) # daffodil = 0 # 用和原数number来对比的水仙花数 # #主循环 # for i in range(len(number)): # daffodil += int(number[i]) ** 3 # if int(number) == daffodil: # print(number, '是水仙花数') # else: # print(number, '不是水仙花数')
false
629d204d76e6545d713ec221aebff2c8bd627a6a
cstarr7/daily_programmer
/hard_2.py
1,852
4.28125
4
# -*- coding: utf-8 -*- # @Author: Charles Starr # @Date: 2016-03-08 23:51:13 # @Last Modified by: Charles Starr # @Last Modified time: 2016-03-09 00:14:55 #Your mission is to create a stopwatch program. #this program should have start, stop, and lap options, #and it should write out to a file to be viewed later. import datetime as dt class Stopwatch(object): #object contains time and does simple operations def __init__(self): self.start_time = None def start(self): if self.start_time == None: self.start_time = dt.datetime.utcnow() else: print 'The watch is already running.' def lap(self): if not self.start_time == None: delta = dt.datetime.utcnow() - self.start_time print delta.total_seconds() print 'The clock is still running' else: print 'The clock is not running' def stop(self): if not self.start_time == None: delta = dt.datetime.utcnow() - self.start_time() self.start_time = None print delta.total_seconds() print 'The clock is stopped' else: print 'The clock is not running.' def reset(self): if not self.start_time == None: self.start_time = dt.datetime.utcnow() print 'The clock has restarted.' else: print 'The clock is not running.' def menu(stopwatch): #displays a menu for stopwatch operations while True: print 'Stopwatch options:' print '1. Start' print '2. Lap' print '3. Stop' print '4. Reset' print '5. Quit' user_choice = raw_input('Select an operation: ') if user_choice == '1': stopwatch.start() elif user_choice == '2': stopwatch.lap() elif user_choice == '3': stopwatch.stop() elif user_choice == '4': stopwatch.reset() elif user_choice == '5': break else: print 'Please enter a valid menu option.' def main(): #creates stopwatch and sends it to the menu stopwatch = Stopwatch() menu(stopwatch) main()
true
a388858021542a586073ae6f0cea563423bedd17
cstarr7/daily_programmer
/easy_267.py
1,223
4.28125
4
# -*- coding: utf-8 -*- # @Author: Charles Starr # @Date: 2016-07-06 23:20:28 # @Last Modified by: Charles Starr # @Last Modified time: 2016-07-06 23:53:49 #https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/ def input_place(): #ask user what place their dog got, check validity, return int while True: fail_msg = 'Enter a positive integer' try: user_input = int(raw_input('What place did your dog get?')) except: print fail_msg return user_input def not_places(place, show_size=100): #returns list of places that your dog didn't finish place_list = [] for not_place in range(1, show_size+1): if place == not_place: continue place_string = str(not_place) suffix = 'th' important_digits = place_string if len(place_string) > 1: important_digits = place_string[-2:] if important_digits[-1] == '1' and important_digits != '11': suffix = 'st' elif important_digits[-1] == '2' and important_digits != '12': suffix = 'nd' elif important_digits[-1] == '3' and important_digits != '13': suffix = 'rd' place_list.append(place_string + suffix) return place_list def main(): size = input_place() print not_places(size) main()
true
34409c67de5b24a50987e1a86be10ec2e9c299ae
suryanisaac/mathwithcode
/Math_With_Code/Triplet.py
449
4.3125
4
# Program to find if a given set of numbers are pythagorean triplets num1 = int(input("Enter The Largest Number: ")) num2 = int(input("Enter The Second Number: ")) num3 = int(input("Enter The Third Number: ")) pt = True n1s = num1 * num1 n2s = num2 * num2 n3s = num3 * num3 if (n1s == n2s + n3s): pt = True print("The Numbers are Pythagorean Triplets") else: pt = False print("The Numbers are not Pythagorean Triplets")
false
bcdf93ea36a3afa6632324742bf0b9acae82a7ef
nguyent57/Algorithms-Summer-Review
/square_root_of_int.py
1,388
4.28125
4
def square_root(x): # BASE CASE WHEN X == 0 OR X == 1, JUST RETURN X if (x == 0 or x == 1): return(x) # STARTING VALUE FROM 2 SINCE WE ALREADY CHECKED FOR BASE CASE i = 2 # PERFECT SQUARE IS THE SQUARE NUMBER ON THE RIGHT OF THE GIVEN NUMBER # SAY, WE HAVE 7 -> PERSQUARE IS 9, 3 PERSQUARE IS 4 persquare = 2 # AS LONG AS PERFECT SQUARE IS <= X -> INCREMENT ith BY ONE AND # CALCULATE THE PERFECT SQUARE, EXIT WHILE LOOP WHEN LARGER. while (persquare <= x): i += 1 persquare = i * i # CALCULATE THE ROOT OF THE PERSQUARE sqrtpersquare = (persquare/i) # DIVIDE NUMBER BY THE GIVEN NUMBER xnew = x/sqrtpersquare # THEN CALCULATE THAT NUMBER'S AVG BY ADDING THAT NUMBER WITH THE ROOT OF PERSQUARE avgxnew = (xnew + sqrtpersquare)/2 # REPEAT THE PROCESS: X/AVGNEW = AVGNEW-> (AVGXNEW + AVGNEW)/2 avgnew = x /avgxnew newavg = round((avgxnew + avgnew)/2,3) sqrt = newavg*newavg if sqrt>x: avgnew = x/newavg newavg = round((newavg + avgnew) / 2, 3) sqrt = newavg * newavg if sqrt > x: newavg = round((newavg + avgnew) / 2, 3) return (newavg) return(newavg) # Driver Code x = 4 print(square_root(x)) x = 5 print(square_root(x)) x = 7 print(square_root(x)) x = 9 print(square_root(x))
true
fd525d79b0b9b683440ef6e52a268feb1550e4e3
nguyent57/Algorithms-Summer-Review
/shortest_palindrome.py
1,682
4.21875
4
# RUN TIME # USE: TAKE THE REVERSE STRING OF THE GIVEN STRING AND BRING IT TO THE END # TO SEE WHAT IS THE SUFFIX OF THE STRING COMPARING TO THE PREFIX OF THE STRING # REMOVE THE SUFFIX --> SHORTEST PALINDROME def palindrom(str): # CREATE AN EMPTY STRING FOR PALINDROME reverse = '' # FOR EVERY ITEM IN GIVEN STR for char in str: # EMPTY STR WILL ADD THE NEXT ELEMENT TO CURRENT AVAILABLE IN w reverse = char + reverse #print(reverse) """ DAD -> DAD => IF THE REVERSE OF THE GIVEN STRING IS EXACTLY THE SAME => ALREADY PALINDROME """ if reverse == str: print(str) """ BANANA -> BANANAB => COMPARE EVERY CHAR OF REVERSE STRING EXCEPT THE LAST CHAR WITH => STARTING OF THE INDEX 1 OF ORIGINAL STRING => IF THE SAME, THEN CREATE A STRING OF ORIGINAL STRING WITH THE LAST ELEMENT OF THE REVERSE STR """ elif reverse[:-1] == str[1:]: print(reverse[:-1]) pal = str + reverse[-1] print(pal) """ ANAA -> AANAA => COMPARE EVERY CHAR OF REVERSE STRING FROM INDEX 1 WITH => EVERY CHAR OF ORIGINAL STR EXCEPT LAST CHAR => IF THE SAME, THEN CREATE A STRING OF THE FIRST CHAR OF REVERSE STR WITH ORIGINAL STR """ elif reverse[1:] == str[:-1]: pal = reverse[1] + str print(pal) """ TOM -> TOMOT => ELSE, CREATE A STRING OF ORIGINAL STR WITH REVERSE STR STARTING FROM INDEX 1 """ else: pal = str + reverse[1:] print(pal) str=input() palindrom(str)
true
7bbe8947b97d2bd27773d003f3b3eedf9eaa712a
nguyent57/Algorithms-Summer-Review
/all_unique_char.py
814
4.25
4
# METHOD 1: USING A FUNCTION # RUN TIME: O(n) # CREATE A FUNCTION THAT WOULD TAKE ANY STRING def all_unique_char(str): # CREATE A DICTIONARY TO STORE THE COUNT OF EACH CHARACTER count = {} # CREATE AN ARRAY TO STORE THE CHAR char = [] # FOR EVERY ITEM IN STRING for i in str: # IF THE COUNT EXIST -> INCREMENT BY ONE if i in count: count[i] +=1 # ELSE SET IT TO ONE AND APPEND THE CHAR INTO THE ARRAY else: count[i] = 1 char.append(i) # FOR EVERY ITEM IN CHAR ARRAY for i in char: # IF THE COUNT IS LARGER THAN 1 if count[i] > 1: # RETURN FALSE return False # OR RETURN TRUE IF EXISTS return True str = 'TOM' print(all_unique_char(str))
true
0f6633f03b958e1c606f41ec4c82e660b6dfd350
UdayQxf2/tsqa-basic
/BMI-calculator/03_BMI_calculator.py
2,937
5.125
5
""" We will use this script to learn Python to absolute beginners The script is an example of BMI_Calculator implemented in Python The BMI_Calculator: # Get the weight(Kg) of the user # Get the height(m) of the user # Caculate the BMI using the formula BMI=weight in kg/height in meters*height in meters Exercise 3: Write a program to calculate the BMI by accepting user input from the keyboard and check whether the user comes in underweight ,normal weight or obesity. Create functions for calculating BMI and check the user category. i)Get user weight in kg ii)Get user height in meter iii) Use this formula to calculate the BMI BMI = weight_of_the_user/(height_of_the_user * height_of_the_user) iv)Use this level to check user category #)Less than or equal to 18.5 is represents underweight #)Between 18.5 -24.9 indicate normal weight #)Between 25 -29.9 denotes over weight #)Greater than 30 denotes obese # Hint i)Create a function to get the input ii)Create one more function to calculate BMi iii)Create one more function for checking user category """ def get_input_to_calcluate_bmi(): "This function gets the input from the user" print("Enter the weight of the user in Kgs") # Get the weight of the user through keyboard weight_of_the_user = input() # Get the height of the user through keyboard print("Enter the height of the user in meters") height_of_the_user = input() return weight_of_the_user,height_of_the_user def calculate_bmi(weight_of_the_user,height_of_the_user): "This function calculates the BMI" # Calculate the BMI of the user according to height and weight bmi_of_the_user = weight_of_the_user/(height_of_the_user * height_of_the_user) # Return the BMI of the user to the called function return bmi_of_the_user def check_user_bmi_category(bmi): "This function checks if the user is underweight, normal, overweight or obese" if bmi <= 18.5: print("The user is considered as underweight") elif bmi > 18.5 and bmi < 24.9: print("The user is considered as normal weight") elif bmi > 25 and bmi <= 29.9: print("The user is considered as overweight") elif bmi >=30: print("The user is considered as obese") # Program starts here if __name__ == "__main__": # This calling function gets the input from the user weight_of_the_user,height_of_the_user = get_input_to_calcluate_bmi() # This calling function stores the BMI of the user bmi_value = calculate_bmi(weight_of_the_user,height_of_the_user) print("BMI of the user is :",bmi_value) # This function is used to calculate the user's criteria check_user_bmi_category(bmi_value)
true
fba5a5017e2f9b1f5b91a3f877e45a7c63f758eb
UdayQxf2/tsqa-basic
/BMI-calculator/02_BMI_calculator.py
1,797
5.09375
5
""" We will use this script to learn Python to absolute beginners The script is an example of BMI_Calculator implemented in Python The BMI_Calculator: # Get the weight(Kg) of the user # Get the height(m) of the user # Caculate the BMI using the formula BMI=weight in kg/height in meters*height in meters Exercise 2: Write a program to calculate the BMI by accepting user input from the keyboard and check whether the user comes in underweight ,normal weight overweight or obesity. i)Get user weight in kg ii)Get user height in meter iii) Use this formula to calculate the bmi BMI = weight_of_the_user/(height_of_the_user * height_of_the_user) iv)Use this level to check user category #)Less than or equal to 18.5 is represents underweight #)Between 18.5 -24.9 indicate normal weight #)Between 25 -29.9 denotes over weight #)Greater than 30 denotes obese """ print("Enter the weight of the user in Kg's") # Get the weight of the user through keyboard weight_of_the_user = input() # Get the height of the user through keyboard print("Enter the height of the user in meters") height_of_the_user = input() # Calculate the BMI of the user according to height and weight bmi = weight_of_the_user/(height_of_the_user * height_of_the_user) print("BMI of the user is :",bmi) # Check the user comes under under weight, normal or obesity if bmi <= 18.5: print("The user is considered as underweight") elif bmi > 18.5 and bmi < 24.9: print("The user is considered as normal weight") elif bmi > 25 and bmi <= 29.9: print("The user is considered as overweight") elif bmi >=30: print("The user is considered as obese")
true
bd1268244c535712fa6616edbf7b2a015867b30e
mikephys8/The_Fundamentals_pythonBasic
/week7/9-1.py
1,005
4.1875
4
__author__ = 'Administrator' tup = ('a', 3, -0.2) print(tup[0]) print(tup[1]) print(tup[2]) print(tup[-1]) print('-------------') print(tup[:2]) print(tup[1:2]) print(tup[1:3]) print(tup[2:3]) print(tup[2:]) print('-------------') # tuples arer immutable!!cannot be assigned with other # value in opposition with list # tup[0] = 'b' print('-------------') # lists have a lot of methods print(dir(list)) print('\n\n') # but tuples only have count and index print(dir(tuple)) print('-------------') for item in tup: print(item) print('\n') print('The length of tup is: ' + str(len(tup))) print('-------------') for i in range(len(tup)): print('The number of i is: ' + str(i)) print('The tuple in index ' + str(i) +' contains: ' + str(tup[i])) print('-------------') # if you want to create a tuple in repl print((1,2)) # only one element tuple(it just parenthesizes the mathematical expression print((1)) # to create on element tuple print((1,)) # empty tuple(do not require comma) print(())
true
035b6c28e1b373fef200773cdc73a940a98d8f7c
arrpitsharrma/PreCourse_1
/Exercise_4.py
1,528
4.25
4
# Time Complexity : not sure # Space Complexity : not sure # Did this code successfully run on Leetcode : yes # Any problem you faced while coding this : had a hard time dealing with tree, I get stuck when I come across trees and linked list for basic things sometimes # Python program to insert element in binary tree class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None """ Inorder traversal of a binary tree""" def inorder(temp): if temp is None: return inorder(temp.left) print(temp.key, end= " ") inorder(temp.right) """function to insert element in binary tree """ def insert(temp,key): y = None x = temp node = newNode(key) while x is not None: y = x if key < x.key: x = x.left else: x = x.right if y is None: y = node elif key < y.key: y.left = node else: y.right = node return y # Driver code if __name__ == '__main__': root = newNode(10) root.left = newNode(11) root.left.left = newNode(7) root.right = newNode(9) root.right.left = newNode(15) root.right.right = newNode(8) print("Inorder traversal before insertion:", end = " ") inorder(root) key = 12 insert(root, key) print() print("Inorder traversal after insertion:", end = " ") inorder(root)
true