blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0819ffcd81a015ea16ff6493531e4f70a635f304
guillermd/Python
/Learning Projects Python/Ejercicios/ejercicio2.py
1,931
4.34375
4
class ejercicio2(): #Escribir un programa que pregunte el nombre del usuario en la consola # y un número entero e imprima por pantalla en líneas distintas # el nombre del usuario tantas veces como el número introducido. def HacerEjercicio(self): nombre=input("Dame tu nombre:") vueltas=input("cuantas vueltas quieres?") for i in range(int(vueltas)): print(nombre, "\n") class ejercicio3(): #Escribir un programa que pregunte el nombre del usuario en la consola y #después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, #donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el número de letras que tienen el nombre. #Escribir un programa que realice la siguiente operación aritmética (3+2 partido de 2*5)elevado a 2 class ejercicio4(): #Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de masa corporal # y lo almacene en una variable, y muestre por pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el # índice de masa corporal calculado redondeado con dos decimales. #Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son los números introducidos por el usuario, y <c> y <r> son el cociente y el resto de la división entera respectivamente. #Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión. #Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas. ej=ejercicio2() ej.HacerEjercicio()
false
9bc0f38b22e60a26543a6f607b4b58bdacb28b41
guillermd/Python
/Learning Projects Python/Basic/Tuplas.py
649
4.28125
4
miTupla=("item1", 18, "item3") print(miTupla) #busqueda de elementos print(miTupla.index("item3")) #Convertir una tuppla en Lista miLista=list(miTupla) print (miLista) #Convertir una lista en tupla miLista.append(7) miTupla2=tuple(miLista) print (miTupla2) #buscar elementos en la tupla => in print("item1" in miTupla) #contar las veces que esta un elemento en la tupla print(miTupla.count(18)) #longitud de una tupla print(len(miTupla2)) #asignar cada item de la tupla a una variable distitna. Asigna por orden cada valor a la variable miTupla3=("pepe", 13,3,2010) nombre, dia, mes, anyo = miTupla3 print(nombre); print(dia);print(mes);print(anyo)
false
7ccff781110f6a1cdefcda48c00fca3c9be5e0b6
AbrahamCain/Python
/PasswordMaker.py
1,501
4.375
4
#Password Fancifier by Cyber_Surfer #This program takes a cool word or phrase you like and turns it into a decent password #you can comment out or delete the following 3 lines if using an OS other than Windows import os import sys os.system("color e0") #It basically alters the colors of the terminal #Enter a password and store it in the variable "word" word = input("Give me a word/phrase to turn into a password of at least 10 characters please:\n\n--->") word = word.lower() #check the length of the password/phrase count = len(word) if count >= 10: for i in word: if "e" in word: word = word.replace("e", "3") #replace e's with 3's if "a" in word: word = word.replace("a", "@") #replace a's with @'s if "s" in word: word = word.replace("s", "$") #replace s's with $'s word = word.title() #make the first letter of words uppercase #make 3 other options for passwords if the environment doesn't allow spaces, underscores, or dashes underscore = word.replace(" ", "_") tac = word.replace(" ", "-") nospace = word.replace(" ", "") #print results print("Here are four different options:") print("1.",word) print("2.",underscore) print("3.",tac) print("4.",nospace) #Let user know the password is too short else: print("That password is too short. Try something over 10 characters next time.") #End/Exit the program input("Press ENTER To Exit") exit(0)
true
74a3dd1a7ec3f71e4dd641f42e22738c989128d4
Autumn-Chrysanthemum/complete-python-bootcamp
/Python-Object-and-Data-Structure-Basics/Section_5/If_elif_else.py
635
4.125
4
# control flow # if some_condition: # execute some code # elif some_other_condition: # do something different # else: # do something else if True: print("It is True") hungry = True if hungry: print("feed me") else: print("i not hungry") location = "Bank" if location == "Auto Shop": print("Cars are cool") elif location == "Bank": print("Money is cool") elif location == "Store": print("Let go shopping") else: print("I don not know much") name = "Samy" if name == "Natalia": print("hello Natalia") elif name == "Samy": print("hello Samy") else: print("what is your name? ")
false
0f679c78696c3d221458ece5c214502f58449c9d
GuillermoDeLaCruz/python--version3
/name.py
726
4.4375
4
# name = "ada lovelace" print(name.title()) print(name.upper()) print(name.lower()) # Combining or Concatenating Strings # Python uses the plus symbol (+) to combine strings first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name print(full_name) print("Hello, " + full_name.title() + "!") print("Python") print("\tPython") print("Languages:\nPython\nC\nJavaScript") print("Languages:\n\tPython\n\tC\n\tJavaScript") #1 favorite_language = 'python ' print(favorite_language) favorite_language.rstrip() print(favorite_language) #2 rstrip() removes whitespaces from the right # lstrip() from left # strip() from both favorite_language = favorite_language.rstrip() print(favorite_language)
true
741bf635cffb29fe1c30c23b9516cc1d77ea00af
abhijitmamarde/py_notebook
/programs/class_str_repr_methods.py
558
4.1875
4
class Point: '''Defines simple 2D Points''' def __init__(self): self.x = 10 self.y = 20 def __str__(self): return "Point(x=%d, y=%d)" % (self.x, self.y) def __repr__(self): return "P(x=%d, y=%d)" % (self.x, self.y) def show(self, flag, capital): '''prints the object on command line''' print(self.x, self.y) p = Point() p.show() p = Point() print(p) print("Point p is:", p) print("Point p is: %s" % p) print("Point p: %s" % repr(p)) s1 = "Point is:" + str(p) print(s1) print(p.__doc__)
false
f841f92cb177b6123adc3c8db14ecd6680078069
annabaig2023/Madlibs
/main.py
521
4.28125
4
# string concatenation # swe = "Anna Baig" # print (swe + " likes to code") # # print (f"{swe} likes to code") # # print ("{} likes to code".format(swe)) swe = input("Name: ") adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous person: ") madlib = ("Hi! My name is " + swe + ". Computer programming is so " + adj + "! It makes me so excited all the time because I love to " + verb1 + "! Stay hydrated and " + verb2 + " like you are " + famous_person) print(madlib)
false
ad8ad997ed8f9103cff43928d968f78201856399
kevyo23/python-props
/what-a-birth.py
1,489
4.5
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # what-a-birth.py - simple birthday monitor, check and add birthdays # Kevin Yu on 28/12/2016 birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} all_months = 'January February March April May June July August September October November December' while True: print('Enter a name: (blank to quit)') name = raw_input() if name == '': break if not name.isalpha(): print ('Invalid name entered - must contain letters only, eg Daniel') continue name = name.title() if name in birthdays: print(name + ' has a birthday on ' + birthdays[name]) else: print('No birthday record found for ' + name) print('What month is ' + name + '\'s birthday?') while True: print('Enter a month:') month = raw_input() if not name.isalpha() or month.title() not in all_months: print('Invalid month entered - must contain letters only, eg January') continue break month = month.title() month = month[:3] while True: print('Enter a date:') date = raw_input() if not date.isdigit() or int(date) < 1 or int(date) > 31: print('Invalid date entered - must contain numbers only, eg 21') continue break birthdays[name] = month + ' ' + date print ('Birthday database updated.')
true
dc5b049c6635da54baaa0f9246d722aa090cf8f6
HelenMaksimova/python_lessons
/lesson_4/lesson_4_5.py
768
4.15625
4
# Реализовать формирование списка, используя функцию range() и возможности генератора. # В список должны войти четные числа от 100 до 1000 (включая границы). # Необходимо получить результат вычисления произведения всех элементов списка. from functools import reduce start_list = [elem for elem in range(100, 1001) if elem % 2 == 0] print(f'Список чётных чисел от 100 до 1000:\n{start_list}') product_list = reduce(lambda num_1, num_2: num_1 * num_2, start_list) print(f'Произведение всех чисел в списке равно: {product_list}')
false
f98aeb7d429aae2a54eaaa52530889c6129ddc57
Vikas-KM/python-programming
/repr_vs_str.py
741
4.375
4
# __str__ vs __repr__ class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage # print and it returns always string # for easy to read representation def __str__(self): return '__str__ : a {self.color} car with {self.mileage} mileage'.format(self=self) # typing mycar in console calls this # unambiguous # for internal use, for developers def __repr__(self): return '__repr__ :a {self.color} car with {self.mileage} mileage'.format(self=self) my_car = Car('red', 123) # see which methods they are calling # comment __STR__ method see what is the output again print(my_car) print(str(my_car)) print('{}'.format(my_car)) print(repr(my_car))
true
cbb68b5a739a298268d2f150aa25841ff4156ffe
sp2013/prproject
/Assgn/Linear_Regression2.py
1,597
4.1875
4
''' Linear_Regression2.py Implements Gradient Descent Algorithm ''' import numpy as np import random import matplotlib.pyplot as plt def linear_regression2(): ''' 1. Read training data in to input, output array. 2. Initialize theta0 - y intercept, theta1 - slope of line. 3. Repeat following steps until convergence: a. Compute theta0. b. Compute theta1. c. Compute cost. d. Check convergence by finding the difference between previous and current cost. 4. Plot data with line using theta0, theta1. ''' x = np.array([10, 9, 2, 15, 10, 16, 11, 16]) y = np.array([95, 80, 10, 50, 45, 98, 38, 93]) m = x.size theta0 = random.random() theta1 = random.random() delta = 1000000; error = 0.05 learningrate = 0.001 prevJtheta = 1000 Jtheta = 1000 while (delta > error): # compute theta0 hx = theta0 + theta1*x s1 = (hx - y).sum() / m temp0 = theta0 - learningrate * s1 # compute theta1 s2 = ((hx - y) * x).sum() / m temp1 = theta1 - learningrate * s2 theta0 = temp0 theta1 = temp1 #compute cost hx = theta0 + theta1 * x tempx = (hx - y) * (hx - y) Jtheta = tempx.sum() / (2 * m) delta = abs(prevJtheta - Jtheta) prevJtheta = Jtheta plt.xlabel('X') plt.ylabel('Y') axis = plt.axis([0, 20, 0, 100]) plt.grid(True) plt.plot(x, y, 'k.') plt.plot(x, theta1*x + theta0, '-') plt.show() return theta0, theta1
true
5c33baae0e50f099028f50a221f18e0d1437f30a
babzman/Babangida_Abdullahi_day30
/Babangida_Abdullahi_day30.py
1,429
4.28125
4
def nester(n): """Given a string of digits S, This function inserts a minimum number of opening and closing parentheses into it such that the resulting string is balanced and each digit d is inside exactly d pairs of matching parentheses.Let the nesting of two parentheses within a string be the substring that occurs strictly between them. An opening parenthesis and a closing parenthesis that is further to its right are said to match if their nesting is empty, or if every parenthesis in their nesting matches with another parenthesis in their nesting. The nesting depth of a position p is the number of pairs of matching parentheses m such that p is included in the nesting of m. """ if type(n) is not str: return "Parameter must be in string" for t in n: if t not in "0123456789": return "Parameters must be numbers and greater than zero" if len(n)==1: return "("*int(n)+n+")"*int(n) no=list(n) u=no no[0]="("*int(no[0])+no[0] no[-1]=no[-1]+")"*int(no[-1]) num=[int(i) for i in list(n)] diff=[int(num[i])-int(num[i+1]) for i in range(len(no)-1)] for d in range(len(diff)): if diff[d]>0: u[d]=u[d]+")"*diff[d] if diff[d]<0: u[d]=u[d]+"("*abs(diff[d]) return "".join(u) #test cases print(nester("-111000")) print(nester("4512")) print(nester("000")) print(nester("302"))
true
74789b8d7f88978a688db1b902cdb8954f315a22
AlvinJS/Python-practice
/Group6_grades.py
747
4.15625
4
# Function to hold grade corresponding to score def determinegrade(score): if 80 <= score <= 100: return 'A' elif 65 <= score <= 79: return 'B' elif 64 <= score <= 64: return 'C' elif 50 <= score <= 54: return 'D' else: return 'F' count = 0 # Use range(10) because function should repeat 10 times for name in range(10): # Ask user to input name which is stored in name as a string name = str(input('Please enter your name: ')) # Ask user to input score which is stored in grade as an integer grade = int(input('What is your score? ')) # count shows you which iteration you are on count = count + 1 print(count,'Hello',name,'your grade is:',determinegrade(grade))
true
fab1979adbfa20245e24943f73ba15566cd06f69
magotheinnocent/Simple_Chatty_Bot
/Simple Chatty Bot/task/bot/bot.py
1,188
4.25
4
print("Hello! My name is Aid.") print("I was created in 2020.") print("Please, remind me your name.") name = str(input()) print(f"What a great name you have, {name}!") print("Let me guess your age.") print("Enter remainders of dividing your age by 3, 5 and 7") remainder1 = int(input()) remainder2 = int(input()) remainder3 = int(input()) age = (remainder1 * 70 + remainder2 * 21 + remainder3 * 15) % 105 print(f"Your age is {age}; that's a good time to start programming!") print("Now I will prove to you that I can count to any number you want") number=int(input()) i = 0 while i <= number: print(f"{i}!") i += 1 print("Let's test your programming knowledge.") print("Why do we use methods?") answer_1 = list("1. To repeat a statement multiple times.") answer_2 = list("2. To decompose a program into several small subroutines.") answer_3 = list("3. To determine the execution time of a program.") answer_4 = list("4. To interrupt the execution of a program.") answer = input() while answer != "2": print('Please, try again.') answer = input() if answer == "2": print("Completed, have a nice day!") print("Congratulations, have a nice day!")
true
fd73641925aa29814156330883df9d132dbcb802
goodwjsphone/WilliamG-Yr12
/ACS Prog Tasks/04-Comparision of two.py
296
4.21875
4
#write a program which takes two numbers and output them with the greatest first. num1 = int(input("Input first number ")) num2 = int(input("Input second number ")) if num1 > num2: print (num1) else: print(num2) ## ACS - You need a comment to show where the end of the if statement is.
true
a7b9758e30b5b2ef0ae6a43a68671ce37f709c9a
joao-pedro-serenini/recursion_backtracking
/fibonacci_problem.py
678
4.1875
4
def fibonacci_recursion(n): if n == 0: return 1 if n == 1: return 1 return fibonacci_recursion(n-1) + fibonacci_recursion(n-2) # top-down approach def fibonacci_memoization(n, table): if n not in table: table[n] = fibonacci_memoization(n-1, table) + fibonacci_memoization(n-2, table) # return table return table[n] # bottom-up approach def fibonacci_tabulation(n, table): for i in range(2, n+1): table[i] = table[i-1] + table[i-2] # return table return table[n] # print(fibonacci_recursion(5)) t = {0: 1, 1: 1} # print(fibonacci_memoization(5, t)) print(fibonacci_tabulation(5, t))
false
a606701ff19aeb87aa7747cd39d40feb826ccb29
PhyzXeno/python_pro
/transfer_to_x.py
991
4.25
4
# this piece of code will convert strings like "8D4C2404" into "\x8D\x4C\x24\x04" # which will then be disassembled by capstone and print the machine code import sys from capstone import * # print("the hex string is " + sys.argv[1]) the_str = sys.argv[1] def x_encode(str): the_str_len = len(str) count = 0 the_x_str = r"\x" # \x is not some kind of encodeing. It is an escape character, the fllowing two characters will be interpreted as hex digit # in order not to escape here, we need raw string to stop character escaping while 1: the_x_str = the_x_str + sys.argv[1][count:count+2] + r"\x" count += 2 if count == the_str_len: return(the_x_str[:-2].decode("string_escape")) # this will convert raw string into normal string def x_disassem(str): CODE = str # CODE = "\x89\xe5" # print(type(CODE)) md = Cs(CS_ARCH_X86, CS_MODE_64) for i in md.disasm(CODE, 0x1000): print "0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str) x_disassem(x_encode(the_str))
true
7bc36647921f253c1ed133c6593de0c35104d261
AgustinParmisano/tecnicatura_analisis_sistemas
/ingreso/maxmin.py
592
4.3125
4
#!/usr/bin/python # coding=utf-8 ''' Realizar un programa que lea dos números enteros desde teclado e informe en pantalla cuál de los dos números es el mayor. Si son iguales debe informar en pantalla lo siguiente: “Los números leídos son iguales”. ''' num1 = int(raw_input('Ingrese un número: ')) num2 = int(raw_input('Ingrese otro número: ')) if num1 > num2: print(" El número %s es mayor que %s" % (num1, num2)) elif num1 < num2: print("El número %s es mayor que %s" % (num2, num1)) else: print("Los números %s y %s son iguales" % (num1, num2))
false
ba9f1fd6c7c56f7673b760b605b0fc17d14e0556
mylgcs/python
/训练营day02/01_函数.py
851
4.15625
4
# 将一个常用的功能封装为一个单独的代码片段,用一个单词来表示,通过这个单词,只需极简结的代码,即可实现这个功能, # 这样的代码片段,称为"函数"! # 比如print 和 input就是函数 # 函数 def print_poetry(): print("春眠不觉晓,处处蚊子咬,夜来嗡嗡声,叮的包不少。") # 函数调用 print_poetry() # 函数的参数与返回值 # 通过参数将数据传递给函数,通过返回值将运算的结果回传 def add(a, b): return a + b # 运算结果可以赋值给另一个变量,也可以直接使用 c = add(1, 2) print(c) # 调用函数的式子,也是有值的,返回值就是函数调用表达式的值 print(add(3, 5) + 4) # 传参可以带标签 def p_pow(num, power): return num ** power print(p_pow(num=10, power=2))
false
de62d877172215f9cbb0b30b24e8009b3485bf47
cpkoywk/IST664_Natural_Language_Processing
/Lab 1/assignment1.py
1,148
4.21875
4
''' Steps: get the text with nltk.corpus.gutenberg.raw() get the tokens with nltk.word_tokenize() get the words by using w.lower() to lowercase the tokens make the frequency distribution with FreqDist get the 30 top frequency words with most_common(30) and print the word, frequency pairs ''' #Import required modules import nltk from nltk import FreqDist from nltk.corpus import brown #check what file they've got in gutenberg nltk.corpus.gutenberg.fileids() #I will pick 'shakespeare-hamlet.txt' file0 = nltk.corpus.gutenberg.fileids()[-3] #file0 = 'shakespeare-hamlet.txt' #1. get the text with nltk.corpus.gutenberg.raw() hamlettext=nltk.corpus.gutenberg.raw(file0) #2. Get the tokens with nltk.word_tokenize() hamlettokens = nltk.word_tokenize(hamlettext) #3. Get the words by using w.lower() to lowercase the tokens hamletwords = [w.lower() for w in emmatokens] #4. make the frequency distribution with FreqDist fdist = FreqDist(hamletwords) fdistkeys=list(fdist.keys()) #5. get the 30 top frequency words with most_common(30) and print the word, frequency pairs top30keys=fdist.most_common(30) for pair in top30keys: print (pair)
true
eb9d5ad1a3bb38c87c64f435c2eabd429405ddc3
niall-oc/things
/codility/odd_occurrences_in_array.py
2,360
4.28125
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. Write a function: def solution(A) that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. For example, given array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7, as explained in the example above. Write an efficient algorithm for the following assumptions: N is an odd integer within the range [1..1,000,000]; each element of array A is an integer within the range [1..1,000,000,000]; all but one of the values in A occur an even number of times. # 100% solution https://app.codility.com/demo/results/trainingCB48ED-3XU/ """ import time def solution(A): """ Bitwise or between 2 numbers where N==N produces a 0. Therefore even pairing of numbers will produce zero. The remainder of the bitwise or operation will be equal to the one odd occurance in the array. """ result=0 for item in A: result ^= item return result if __name__ == '__main__': tests = ( # Test cases are in pairs of (expected, (args,)) (7, ([1,1,2,2,7],)), ) for expected, args in tests: # record performance of solution tic = time.perf_counter() res = solution(*args) toc = time.perf_counter() print(f'ARGS produced {res} in {toc - tic:0.8f} seconds') if args[0] is None: continue # This is just a speed test try: assert(expected == res) except AssertionError as e: print(f'ERROR {args} produced {res} when {expected} was expected!')
true
203ae511e881868303be870501531fb41c688fea
niall-oc/things
/codility/dis_analysis.py
840
4.125
4
def factorial(n): # recursive if not n: return 1 else: return n * factorial(n-1) def factorial_for(n): if not n: return 1 else: r = 1 for i in range(1, n+1): r = i*r return r def factorial_while(n): if not n: return 1 else: i = r = 1 while i < n+1: r = i*r i += 1 return r def fibonacci(n): # recursive if not n: return 0 elif n<3: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def fibonacci_itr(n, seq=False): # iterator if not n: r = [0] elif n<3: r = [0,1,1] if n == 2 else [0,1] else: r = [0,1,1] for _ in range(3, n+1): r += [r[-2] + r[-1]] return r if seq else r[-1]
false
db239ae5d7cc670f71e8af8d99bc441f4af2503a
niall-oc/things
/puzzles/movies/movies.py
2,571
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Given the following list in a string seperated by \n characters. Jaws (1975) Starwars 1977 2001 A Space Odyssey ( 1968 ) Back to the future 1985. Raiders of the lost ark 1981 . jurassic park 1993 The Matrix 1999 A fist full of Dollars 10,000 BC (2008) 1941 (1979) 24 Hour Party People (2002) 300 (2007) 2010 Produce the following output. 2000s : 3 1970s : 3 1980s : 2 1990s : 2 1960s : 1 """ import re year_pattern = re.compile("[0-9]{4}") # or [0-9]{4} def find_year(title): """ Returns a 4 digit block nearest the right of the string title. OR Returns None. EG. Starwars (1977) # year is 1997 2001 A space odyssey 1968 # year is 1968 2010 # NO year 1985. # NO year 75 # NO year usage: >>> find_year("starwars (1977)") 1977 :param str title: A string containing a movie title and year of relaease. :return str: Year of release """ # find all patterns that match the year pattern matches = year_pattern.findall(title) # if any matches if matches: # record for convienence year = matches[-1] too_short = len(title) < 8 # If the year is the title then return None if year == title: return None # If we have enough room for 1 block of 4 digits and its at the start elif too_short and title.startswith(year): return None else: return year def rank_decades(movies): """ Returns a dictionary of decades -> number of movies released. usage: >>> rank_decades(['starwars 1977']) {'1970s': 1} :param list movies: A collection of title strings :return dict: decades and number of releases. """ results = {} for movie in movies: year = find_year(movie) # If we found a release year then count it if year: # A way to map year to decade decade = "{0}0s".format(year[:3]) else: decade = "None" results[decade] = results.setdefault(decade, 0) + 1 return results if __name__ == "__main__": f = open('movie_releases.txt') movie_data = f.read() all_movies = movie_data.split('\n') rank = rank_decades(all_movies) for decade, count in sorted(rank.items(), key=lambda s: s[1], reverse=True): print "%s : %s" % (decade, count,)
true
e6ea4c49d3012708cededb29a1f79f575561c82f
niall-oc/things
/codility/frog_jmp.py
2,058
4.15625
4
# -*- coding: utf-8 -*- """ Author: Niall O'Connor # https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the small frog must perform to reach its target. Write a function: def solution(X, Y, D): that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 Write an efficient algorithm for the following assumptions: X, Y and D are integers within the range [1..1,000,000,000]; X ≤ Y. # 100% solution https://app.codility.com/demo/results/trainingWK4W5Q-7EF/ """ import time def solution(X, Y, D): """ Simply divide the jumps into the distance. Distance being y-X and ensuring a finaly jump over the line! """ distance = (Y-X) hops = distance // D if distance%D: # landing even is not over the line! hops += 1 return hops if __name__ == '__main__': tests = ( # Test cases are in pairs of (expected, (args,)) (3, (10, 85, 30,)), ) for expected, args in tests: # record performance of solution tic = time.perf_counter() res = solution(*args) toc = time.perf_counter() print(f'ARGS produced {res} in {toc - tic:0.8f} seconds') if args[0] is None: continue # This is just a speed test try: assert(expected == res) except AssertionError as e: print(f'ERROR {args} produced {res} when {expected} was expected!')
true
fdec6fee3a57a11783c40eafcb9125b11e174f51
Anshu-Singh1998/python-tutorial
/fourty.py
289
4.28125
4
# let us c # Write a function to calculate the factorial value of any integer enyered # through the keyboard. def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = int(input("Input a number to compute the factorial : ")) print(factorial(n))
true
5ca65e5362eca7bf9cfeda1021564e6c20ccb4a5
Anshu-Singh1998/python-tutorial
/eight.py
228
4.25
4
# let us c # input a integer through keyboard and find out whether it is even or odd. a = int(input("Enter a number to find out even or odd:")) if a % 2 == 0: print("the number is even") else: print("the number is odd")
true
4516d98fd3db1d9c9049bb6cb3d1fe18e9e7914b
Anshu-Singh1998/python-tutorial
/nineteen.py
268
4.15625
4
# From internet # Write a program to remove an element from an existing array. from array import * num = list("i", [4, 7, 2, 0, 8, 6]) print("This is the list before it was removed:"+str(num)) print("Lets remove it") num.remove(2) print("Removing performed:"+str(num))
true
a17e198eeaac4a06b472845f6dffdd2bcf1f74c3
damsonli/mitx6.00.1x
/Mid_Term/problem7.py
2,190
4.4375
4
''' Write a function called score that meets the specifications below. def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet (a=1 ... z=26) times its distance from start of word. Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2. 2) The score for a word is the result of applying f to the scores of the word's two highest scoring letters. The first parameter to f is the highest letter score, and the second parameter is the second highest letter score. Ex. If f returns the sum of its arguments, then the score for 'adD' is 12 """ #YOUR CODE HERE Paste your entire function, including the definition, in the box below. Do not leave any print statements. ''' def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet (a=1 ... z=26) times its distance from start of word. Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2. 2) The score for a word is the result of applying f to the scores of the word's two highest scoring letters. The first parameter to f is the highest letter score, and the second parameter is the second highest letter score. Ex. If f returns the sum of its arguments, then the score for 'adD' is 12 """ #YOUR CODE HERE i = 0 scores = [] word = word.lower() for letter in word: score = (ord(letter) - ord('a') + 1) * i scores.append(score) i += 1 scores = sorted(scores, reverse=True) return f(scores[0], scores[1]) def f(num1, num2): print(num1) print(num2) return num1 + num2 print(score('adDe', f))
true
622b10cab635fa09528ffdeab353bfd42e69bdc7
damsonli/mitx6.00.1x
/Final Exam/problem7.py
2,105
4.46875
4
""" Implement the class myDict with the methods below, which will represent a dictionary without using a dictionary object. The methods you implement below should have the same behavior as a dict object, including raising appropriate exceptions. Your code does not have to be efficient. Any code that uses a Python dictionary object will receive 0. For example: With a dict: | With a myDict: ------------------------------------------------------------------------------- d = {} md = myDict() # initialize a new object using your choice of implementation d[1] = 2 md.assign(1,2) # use assign method to add a key,value pair print(d[1]) print(md.getval(1)) # use getval method to get value stored for key 1 del(d[1]) md.delete(1) # use delete method to remove key,value pair associated with key 1 """ class myDict(object): """ Implements a dictionary without using a dictionary """ def __init__(self): """ initialization of your representation """ self.keys = [] self.values = [] def assign(self, k, v): """ k (the key) and v (the value), immutable objects """ if k not in self.keys: self.keys.append(k) self.values.append(v) else: index = self.keys.index(k) self.values[index] = v def getval(self, k): """ k, immutable object """ if k not in self.keys: raise KeyError(k) else: index = self.keys.index(k) return self.values[index] def delete(self, k): """ k, immutable object """ if k not in self.keys: raise KeyError(k) else: index = self.keys.index(k) self.keys.pop(index) self.values.pop(index) md = myDict() print(md.keys) print(md.values) md.assign(1,2) print(md.keys) print(md.values) md.assign('a', 'c') print(md.keys) print(md.values) md.assign(1,3) print(md.keys) print(md.values) print(md.getval(1)) #print(md.getval('d')) md.delete(1) print(md.keys) print(md.values) md.delete('d')
true
de17bb8bd8f94f087845cd59e2ad83f7b43f8ebd
Nicolanz/holbertonschool-web_back_end
/0x00-python_variable_annotations/3-to_str.py
269
4.21875
4
#!/usr/bin/env python3 """Module to return str repr of floats""" def to_str(n: float) -> str: """Function to get the string representation of floats Args: n (float): [float number] Returns: str: [str repr of n] """ return str(n)
true
94c63cf09da1e944b67ca243ee40f67ad3550cf5
Nicolanz/holbertonschool-web_back_end
/0x00-python_variable_annotations/9-element_length.py
435
4.28125
4
#!/usr/bin/env python3 """Module with correct annotation""" from typing import Iterable, Sequence, List, Tuple def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]: """Calculates the length of the tuples inside a list Args: lst (Sequence[Iterable]): [List] Returns: List[Tuple[Sequence, int]]: [New list with the length of the tupes] """ return [(i, len(i)) for i in lst]
true
aedfe44fe94a31da053f830a56ad5842c77b4610
jesseklein406/data-structures
/simple_graph.py
2,747
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """A data structure for a simple graph using the model from Martin BroadHurst http://www.martinbroadhurst.com/graph-data-structures.html """ class Node(object): """A Node class for use in a simple graph""" def __init__(self, name, value): """Make a new node object""" self.name = name self.value = value class G(tuple): """A data structure for a simple graph""" def __init__(self): """Make a new simple graph object""" self.nodes_ = set() self.edges_ = set() def __repr__(self): return (self.nodes_, self.edges_) def nodes(self): """return a list of all nodes in the graph""" return list(self.nodes_) def edges(self): """return a list of all edges in the graph""" return list(self.edges_) def add_node(self, n): """adds a new node 'n' to the graph""" self.nodes_.add(n) def add_edge(self, n1, n2): """adds a new edge to the graph connecting 'n1' and 'n2', if either n1 or n2 are not already present in the graph, they should be added. """ if n1 not in self.nodes_: self.nodes_.add(n1) if n2 not in self.nodes_: self.nodes_.add(n2) self.edges_.add((n1, n2)) def del_node(self, n): """deletes the node 'n' from the graph, raises an error if no such node exists """ self.nodes_.remove(n) for edge in self.edges_.copy(): if n in edge: self.edges_.remove(edge) def del_edge(self, n1, n2): """deletes the edge connecting 'n1' and 'n2' from the graph, raises an error if no such edge exists """ self.edges_.remove((n1, n2)) def has_node(self, n): """True if node 'n' is contained in the graph, False if not. """ return n in self.nodes_ def neighbors(self, n): """returns the list of all nodes connected to 'n' by edges, raises an error if n is not in g """ if n not in self.nodes_: raise ValueError("Node not in graph") neighbors = set() for edge in self.edges_: if edge[0] is n: neighbors.add(edge[1]) return list(neighbors) def adjacent(self, n1, n2): """returns True if there is an edge connecting n1 and n2, False if not, raises an error if either of the supplied nodes are not in g """ if n1 not in self.nodes_ or n2 not in self.nodes_: raise ValueError("Both nodes not in graph") for edge in self.edges_: if n1 in edge and n2 in edge: return True return False
true
097a3e342b6f3d947ea81924e8b89a1563b425bc
ElAouane/Python-Basics
/104_List.py
1,195
4.5625
5
#LIST #Defining a list #The syntax of a list is [] crazy_landlords = [] #print(type(crazy_landlords)) # We can dynamically define a list crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] #Access a item in a list. #List are organized based on the index crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] print(crazy_landlords) print(crazy_landlords[1]) #We can also redefine at a specific index #Change Raj to Rajesh crazy_landlords[1] = 'Rajesh' print(crazy_landlords) #Adding a record to the list crazy_landlords.append('Raj') crazy_landlords.insert(0, 'Hamza') print(crazy_landlords) #Remove an item from a list crazy_landlords.remove('Raj') print(crazy_landlords) #Remove using the index using POP crazy_landlords.pop() #<= Remove the highest index in the list crazy_landlords.pop(0) #<= Remove the specific index in the list print(crazy_landlords) #We can have mixed data list hybrid_list = ['JSON', 'Jason', 13, 53, [1, 2]] print(hybrid_list) #Tuples #immutable lists my_tuple = (2, 'Hello', 22, 'more values') print(my_tuple) #Range Slicing crazy_landlords[0 : 1] #<= from 0 to 1 not inclusive crazy_landlords[1 : 2] #<= from 1 to 2 not inclusive
false
dfc818c931c516d40f82d5d2b16c18bd2b2ff20d
vibhor3081/GL_OD_Tracker
/lib.py
2,986
4.1875
4
import pandas as pd def queryTable(conn, tablename, colname, value, *colnames): """ This function queries a table using `colname = value` as a filter. All columns in colnames are returned. If no colnames are specified, `select *` is performed :param conn: the connection with the database to be used to execute/fetch the query :param tablename: the tablename to query :param colname: the column to filter by :param value: the value to filter by :param colnames: the columns to fetch in the result """ if not colnames: colnames = "*" else: colnames = ', '.join(colnames) df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname}='{value}'", conn) return df def queryTableNew(conn, tablename, colname1, value1, colname2, value2, *colnames): """ This function queries a table using `colname = value` as a filter. All columns in colnames are returned. If no colnames are specified, `select *` is performed :param conn: the connection with the database to be used to execute/fetch the query :param tablename: the tablename to query :param colname: the column to filter by :param value: the value to filter by :param colnames: the columns to fetch in the result """ if not colnames: colnames = "*" else: colnames = ', '.join(colnames) df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname1}='{value1}' AND {colname2}= '{value2}'", conn) return df def currencyFormatter(n): """ Format a number as it if were currency. Force two decimal places of precision :param n: a number to format """ s = format(round(n, 2), ',') # formatted with ','s as the 100s separator if '.' not in s: s += '.' tail = len(s.rsplit('.',1)[-1]) s += '0'*(2-tail) # rpad decimal precision to 2 places return s def cumsumByGroup(df): """ Given a dataframe, group the dateaframe by AccounNumber. Sort each group by date, multiply the Amount by -1 for CR/DR and perform a cumsum :param df: a pandas dataframe containing transaction information across multiple accounts for one customer """ df.sort_values(by=['AccountNumber', 'Date'], inplace=True, ignore_index=True) # we can sort by date here, just the one time, rather than having to sort each group individually # get a signed amount by CR/DR df['NetAmount'] = df.Amount df.loc[df.CRDR=='DR', 'NetAmount'] = df[df.CRDR=='DR']['NetAmount']*-1 df['AvailableBalance'] = None # new column for the cumsum for accountNum in df.AccountNumber.unique(): # cumsum for each account number df.loc[df.AccountNumber==accountNum, 'AvailableBalance'] = df[df.AccountNumber==accountNum].NetAmount.cumsum() df.sort_values(by=['Date'], inplace=True, ignore_index=True) # sort again by date, so that all transactions are stratified by date df.fillna(value='', inplace=True) # so that None's don't show up in the st.write(df) return df
true
e617e0788ff6129a6717d7cc26bb2a9fe2e7f12b
yasmineElnadi/python-introductory-course
/Assignment 2/2.9.py
330
4.1875
4
#wind speed ta=float(input("Enter the Temperature in Fahrenheit between -58 and 41:")) v=eval(input("Enter wind speed in miles per hour:")) if v < 2: print("wind speed should be above or equal 2 mph") else: print("the wind chill index is ", format(35.74 + (0.6215*ta) - (35.75* v**0.16) + (0.4275 * ta * v**0.16), ".5f"))
true
1b6d2d0843efad0980c4fa09aa7388c3b1eb609c
birkirkarl/assignment5
/Forritun/Æfingardæmi/Hlutapróf 1/practice2.py
241
4.28125
4
#. Create a program that takes two integers as input and prints their sum. inte1= int(input('Input the first integer:')) inte2= int(input('Input the second integer:')) summan= int(inte1+inte2) print('The sum of two integers is:',+summan)
true
18ad8bcf6e920438f101c955b30c4e4d11f72e4b
birkirkarl/assignment5
/Forritun/Assignment 10 - lists/PascalTriangle.py
422
4.15625
4
def make_new_row(row): new_row = [] for i in range(0,len(row)+1): if i == 0 or i == len(row): new_row.append(1) else: new_row.append(row[i]+row[i-1]) return new_row # Main program starts here - DO NOT CHANGE height = int(input("Height of Pascal's triangle (n>=1): ")) new_row = [] for i in range(height): new_row = make_new_row(new_row) print(new_row)
true
35b5bcedc003939f44bef58326dd49e725717da4
LucianoUACH/IP2021-2
/PYTHON/Funcion1/funcion1.py
219
4.25
4
print("Ingrese el valor de X:") x = float(input()) #f = ((x+1)*(x+1)) + ((2*x)*(2*x)) f = (x+1)**2 + (2*x)**2 # el operador ** la potencia print("El resultado es: " + str(f)) # str() tranforma un número a una palabra
false
b74ac298e5cba51c032cee6114decf658a67f494
dhurataK/python
/score_and_grades.py
804
4.1875
4
def getGrade(): print "Scores and Grades" for i in range(0,9): ip = input() if(ip < 60): print "You failed the exam. Your score is: "+str(ip)+" Good luck next time!" elif (ip >= 60 and ip <= 69): print "Score: "+str(ip)+"; Your grade is D" elif (ip >= 70 and ip <= 79): print "Score: "+str(ip)+"; Your grade is C" elif (ip >= 80 and ip <= 89): print "Score: "+str(ip)+"; Your grade is B" elif (ip >= 90 and ip <= 100): print "Score: "+str(ip)+"; Your grade is A" elif (ip > 100): print "Invalid score! "+str(ip) print "End of the program. Bye! " getGrade() # Looks great, but what happens if I supply a grade below 60 or over 100? Just something to think about.
true
739202147eac8f44a40e213cbd6bafdcc26dcea1
17leungkaim/programming-portfolio
/grading.py
426
4.1875
4
# program to figure out grades score = int(raw_input("Enter your test score")) if score >= 93: print "A" elif score >= 90: print "-A" elif score >= 87: print "B+" elif score >=83: print "B" elif score >=80: print "-B" elif score >=77: print "+C" elif score >=73: print "C" elif score >=70: print "-C" elif score >=67: print "+D" elif score >=63: print "D" elif score >=60: print "-D" elif score >=50: print "F"
false
495dffd2bb07f45cc5bb355a1a00d113c2cd6288
cadyherron/mitcourse
/ps1/ps1a.py
981
4.46875
4
# Problem #1, "Paying the Minimum" calculator balance = float(raw_input("Enter the outstanding balance on your credit card:")) interest_rate = float(raw_input("Enter the annual credit card interest rate as a decimal:")) min_payment_rate = float(raw_input("Enter the minimum monthly payment rate as a decimal:")) monthly_interest_rate = interest_rate / 12 number_of_months = 1 total_amount_paid = 0 while number_of_months <= 12: min_payment = round(min_payment_rate * balance, 2) total_amount_paid += min_payment interest_paid = round(interest_rate / 12 * balance, 2) principle_paid = min_payment - interest_paid balance -= principle_paid print "Month: ", number_of_months print "Minimum monthly payment: ", min_payment print "Principle paid: ", principle_paid print "Remaining balance: ", balance number_of_months += 1 print "RESULT" print "Total amount paid: ", total_amount_paid print "Remaining balance: ", balance
true
f3fb695d70656cd48495be8fc89af09dd3cee40a
learning-triad/hackerrank-challenges
/gary/python/2_if_else/if_else.py
838
4.40625
4
#!/bin/python3 # # https://www.hackerrank.com/challenges/py-if-else/problem # Given a positive integer n where 1 <= n <= 100 # If n is even and in the inclusive range of 6 to 20, print "Weird" # If n is even and greater than 20, print "Not Weird" def check_weirdness(n): """ if n is less than 1 or greater than 100, return "Not Applicable" if n is odd, return "Weird" if n is even and in the inclusive range of 6 to 20, return "Weird" if n is even and in the inclusive range of 2 to 5, return "Not Weird" if n is even and greater than 20, return "Not Weird" """ if n < 1 or n > 100: return "Not Applicable" return "Not Weird" if n % 2 == 0 and (2 <= n <= 5 or n > 20) else "Weird" if __name__ == '__main__': n = int(input().strip()) result = check_weirdness(n) print(result)
true
d13d318c78f4f902ef6b1a1474a832c70db6b9f2
demptdmf/python_lesson_3
/range.py
2,788
4.21875
4
# Когда использовать RANGE # позволяет создать последовательность целых чисел numbers = range(10) print(numbers) print(type(numbers), '— это диапазон') print(list(range(1, 20, 2))) # Напечатать список от 1 до 20 с шагом "2" — 1+2, 3+2, 5+2 и так далее for number in range(1, 20, 2): # Просто напечатать эти же самые цифры, но без списка print(number, '-', type(number)) print() winners = ['Max', 'Leo', 'Kate'] for i in range(1, len(winners)): # Для элемента в диапазоне длины списка winners print(i, winners[i]) # выводить номер элемента (+1, иначе начало будет с 0, т.к. это список) и его значение print() print('Вывод простых чисел') for n in range(2, 10): # для числа от 2 до 9 for x in range(2, n): # для множителя (х) от 2 до числа N if n % x == 0: # если остаток деления N на X = 0 (если число N делится на Х без остатка) print(n, 'равно:', x, '*', n//x) # то печатать это число N с условием: оно берется из "множитель" * "число/множитель" break else: # цикл потерпел неудачу, не найдя множитель print(n, '— это простое число') print() print('Вывод через CONTINUE \n' 'Оператор continue продолжает выполнение со следующей итерации цикла') for num in range(2, 10): if num % 2 == 0: print(num, '— четное число') continue # идет сразу к след строчке кода, и потом повторяется if. print(num, '— нечетное число') print() for num in range(2, 10): if num % 2 == 0: print(num, '— четное число') else: print(num, '— нечетное число') # В первом случае мы идем подряд по коду, и условием является "после найденного четного числа к следующему числу пишем "нечетное". # Во втором примере мы перебираем цифры, и если число делится на 2 — пишем "четное", если нет — "нечетное"
false
c6f81be710ff83f95f7b3ed87711cdcc40251903
florenciano/estudos-Python
/livro-introducao-a-programacao-em-python/cap10/classe-objeto-all.py
2,004
4.125
4
# -*- coding: utf-8 -*- #abrindo conta no banco Tatú class Cliente(object): def __init__(self, nome, telefone): self.nome = nome self.telefone = telefone #movimentando a conta """ Uma conta para representar uma conta do banco com seus clientes e seu saldo """ class Conta(object): def __init__(self, clientes, numero, saldo = 0): super(Conta, self).__init__() self.clientes = clientes self.numero = numero self.saldo = saldo self.operacoes =[] self.deposito(saldo) def resumo(self): print("CC Número: %s Saldo: %10.2f" % (self.numero, self.saldo)) def saque(self, valor): if self.saldo >= valor: self.saldo -= valor self.operacoes.append(["SAQUE", valor]) def deposito(self, valor): self.saldo += valor self.operacoes.append(["DEPOSITO", valor]) def extrato(self): print("Extrato CC Nº %s\n" % self.numero) for x in self.operacoes: print("%10s %10.2f" % (x[0], x[1])) print("\n Saldo: %10.2f\n" % self.saldo) #cadastrando os primeiros clientes joao = Cliente("João da Silva", "777-1234") maria = Cliente("Maria da Silva", "555-1234") #criando a conta do joao (nome, nº conta, valor inicial) conta_corrente_joao = Conta(joao, 8759, 0) #movimentando a conta do joao conta_corrente_joao.resumo() conta_corrente_joao.deposito(1000) conta_corrente_joao.resumo() conta_corrente_joao.saque(50) conta_corrente_joao.resumo() conta_corrente_joao.deposito(190) conta_corrente_joao.resumo() conta_corrente_joao.saque(360) conta_corrente_joao.resumo() conta_corrente_joao.saque(97.15) conta_corrente_joao.resumo() conta_corrente_joao.saque(250) conta_corrente_joao.resumo() conta_corrente_joao.extrato() #classe para armazenar todas as contas do banco Tatu class Banco(object): def __init__(self, nome): self.nome = nome self.clientes = [] self.contas = [] def abre_contas(self, conta): self.contas.append(conta) def lista_contas(self): for c in self.contas: print(c) tatu = Banco("Tatú") tatu.abre_contas([conta_corrente_joao]) tatu.lista_contas()
false
6373d12759eabd9b3ffadbc995b49d28b9f6fae7
Ftoma123/100daysprograming
/day30.py
550
4.375
4
#using range() in Loop for x in range(6): print(x) print('____________________') #using range() with parameter for x in range(2,6): print(x) print('____________________') #using range() with specific increment for x in range(2,20,3): #(start, ende, increment) print(x) print('____________________') #else for x in range(0,6): print(x) else: print('finished') print('____________________') #nested loop adj = ['red', 'big', 'tasty'] fruits = ['Apple', 'Banana', 'Cherry'] for x in adj: for y in fruits: print(x, y)
false
1083052e37b5556980972557425aeac95fa7931b
arensdj/math-series
/series_module.py
2,753
4.46875
4
# This function produces the fibonacci Series which is a numeric series starting # with the integers 0 and 1. In this series, the next integer is determined by # summing the previous two. # The resulting series looks like 0, 1, 1, 2, 3, 5, 8, 13, ... def fibonacci(n): """ Summary of fibonacci function: computes the fibonacci series which is a numeric series starting with integers 0 and 1. The next integer in series is determined by summing the previous two and looks like 0, 1, 1, 2, 3, 5, 8, 13, ... Parameters: n (int): positive integer n Returns: int: Returns the nth value of the fibonacci numbers """ array = [] index = 1 array.append(index) array.append(index) total = 0 for i in range(index, n): total = array[i - 1] + array[i] array.append(total) return array[i] # This function produces the Lucas Numbers. This is a related series of integers # that start with the values 2 and 1. # This resulting series looks like 2, 1, 3, 4, 7, 11, 18, 29, ... def lucas(n): """ Summary of lucas function: computes the lucas series which is a related series of integers that start with the values 2 and 1 and looks like 2, 1, 3, 4, 7, 11, 18, 29, ... Parameters: n (int): positive integer n Returns: int: Returns the nth value of the lucas numbers """ array = [] index = 1 array.append(index+1) array.append(index) total = 0 for i in range(index, n): total = array[i -1] + array[i] array.append(total) return array[i] # This function produces numbers from the fibonacci series if there are no # optional parameters. Invoking this function with the optional arguments 2 and 1 # will produce values from the lucas numbers. def sum_series(n, arg1=0, arg2=1): """ Summary of sum_series function: computes a series of numbers based on the arguments. One required argument will produce fibonacci numbers. One argument and optional arguments 2 and 1 produces the lucas series. Parameters: n (int): positive integer n arg1 (int): (optional) positive integer arg1 arg2 (int): (optional) positive integer arg2 Returns: int: Returns the nth value of either the fibonacci numbers or the lucas numbers """ array = [] total = 0 index = 1 # if optional arguments are not included in function call, produce # fibonacci numbers if ( (arg1 == 0) and (arg2 == 1) ): array.append(index) array.append(index) else: # optional numbers were included in function call. Produce lucas numbers array.append(index+1) array.append(index) for i in range(index, n): total = array[i - 1] + array[i] array.append(total) return array[i]
true
a8b4639a8a2de162236ba3ced3ce9229a2d1579d
Nadjamac/Mod1_BlueEdtech
/Aula11_Dicionários/Aula11_Dicionarios_Conteúdo.py
1,012
4.15625
4
#Criando uma lista de tuplas -> estrutura de dados que associa um elemento a outro # lista = [("Ana" , "123-456") , ("Bruno" , "321-654") , ("Cris" , "213 - 546") , ("Daniel" , "231 - 564") , ("Elen" , "111-222")] #Sintaxe de um dicionário # dicionario = {"Ana" : "123-456"} #Criando um dicionário # lista_dicionario = dict(lista) # print(lista_dicionario) # Acessando um valor dentro de um dicionário #O valor é acessado pela chave do dicionário # print(lista_dicionario["Ana"]) # print(lista_dicionario.get("Ana")) # nome = input("Digite um nome: ") # print(lista_dicionario.get(nome , "Valor não encontrado!") atores_vingadores = {"Chris Evans" : "Capitão América" , "MArk Ruffalo" : "Hulk" , "Tom Hiddeltston" : "Loki" , "Chris Hemworth" : "Thor" , "Robert Downey Jr" : "Homem de Ferro" , "Scarlett Johansson" : "Viúva Negra"} ator = input("Digite o nome do ator: ") print(atores_vingadores.get(ator , "O nome não existe!")) #interagindo com chave e valor for chave , valor in atores_vingadores.items(): print(f"O valor da chave {chave} é: {valor}")
false
e7189b646cedb06f82885acbe6801cb776aa9a96
chocolate1337/python_base
/lesson_011/01_shapes.py
1,122
4.125
4
# -*- coding: utf-8 -*- import simple_draw as sd # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол наклона # - длина стороны # # Функция-фабрика должна принимать параметр n - количество сторон. def get_polygon(n): def geometry(point, angle=30, length=100): point_1 = point for angles in range(0, n - 1, 1): v = sd.get_vector(point, angle=angles * (360 // n) + angle, length=length) point = v.end_point v.draw() sd.line(point_1, point) return geometry draw_triangle = get_polygon(n=3) draw_triangle(point=sd.get_point(200, 200), angle=1, length=50) sd.pause() # зачет!
false
ce9d1cd697671c12003a39b17ee7a9bfebf0103d
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/letter-frequency-3.py
890
4.125
4
import string if hasattr(string, 'ascii_lowercase'): letters = string.ascii_lowercase # Python 2.2 and later else: letters = string.lowercase # Earlier versions offset = ord('a') def countletters(file_handle): """Traverse a file and compute the number of occurences of each letter return results as a simple 26 element list of integers.""" results = [0] * len(letters) for line in file_handle: for char in line: char = char.lower() if char in letters: results[ord(char) - offset] += 1 # Ordinal minus ordinal of 'a' of any lowercase ASCII letter -> 0..25 return results if __name__ == "__main__": sourcedata = open(sys.argv[1]) lettercounts = countletters(sourcedata) for i in xrange(len(lettercounts)): print "%s=%d" % (chr(i + ord('a')), lettercounts[i]),
true
1215bc74ec9edc0701ce6004ccd9031ad6c079ff
The-SIVA/python
/average length of the word in the sentence.py
343
4.15625
4
sentenct_list = input().split() length_of_sentence_list = len(sentenct_list) sum_of_all_words_lengths = 0 for word in sentenct_list: length_of_word = len(word) sum_of_all_words_lengths += length_of_word average_length_of_words_in_sentence = (sum_of_all_words_lengths/length_of_sentence_list) print(average_length_of_words_in_sentence)
false
7424e3d1c91b4052176e86aeedc9261a86490a14
kiukin/codewars-katas
/7_kyu/Descending_order.py
546
4.125
4
# Kata: Descending Order # https://www.codewars.com/kata/5467e4d82edf8bbf40000155/train/python # Your task is to make a function that can take any non-negative integer as a argument and # return it with its digits in descending order. Essentially, rearrange the digits to # create the highest possible number. # Examples: # Input: 21445 Output: 54421 # Input: 145263 Output: 654321 # Input: 123456789 Output: 987654321 def descending_order(num): sorted_num = sorted([d for d in str(num)],reverse=True) return int("".join(sorted_num))
true
36a0cb1db271953430c191c321286014bc97ed6d
Asabeneh/Fundamentals-of-python-august-2021
/week-2/conditionals.py
997
4.40625
4
is_raining = False if is_raining: print('I have to have my umbrella with me') else: print('Go out freely') a = -5 if a > 0: print('The value is positive') elif a == 0: print('The value is zero') elif a < 0: print('This is a negative number') else: print('It is something else') # weather = input('What is the weather like today? ').lower() # if weather == 'rainy': # print('Go out with an umbrella') # elif weather == 'cloudy': # print('There is a possibility of rain.') # elif weather == 'sunny': # print('Go out freely and enjoy the sunny day.') # elif weather == 'snowy': # print('It may be slippery.') # else: # print('No one knows about today weather') a = 3 value = 'Positive' if a > 0 else 'Negative' print(value) if a > 0: if a % 2 == 0: print('It is a positive even number') else: print('It is a positive odd number') elif a == 0: print('The number is zero') else: print('The number is negaive')
true
d6e5435f634beb7a11f6095bb3f697fbeb426fb8
hossein-askari83/python-course
/28 = bult in functions.py
898
4.25
4
number = [0, 9, 6, 5, 4, 3, -7, 1, 2.6] print("-----------") # all , any print(any(number)) # if just one of values was true it show : true (1 and other numbers is true) print(all(number)) # if just one of values was false it show : false (0 is false) print("-----------") # min , max print(max(number)) # show maximum of numbers print(min(number)) # show minimum of numbers print("-----------") # sorted , reversed print(sorted(number)) # sort numbers from smallest to biggest print(list(reversed(number))) # show reversed list print("-----------") # len , abs print(len(number)) # show number of value in list print(abs(number[6])) # abs = absolute : show "قدر مطلق" print("-----------") # sum , round print(sum(number)) # show sum of list values # note : sum (varible , some sumber) if write a number after varible it show sum of "numbers + number" print(round(number[8]))
true
4b77591a779a29ea29cad5805a335ee7b5b9da5f
rintukutum/functional-gene-annotation
/fact_function.py
205
4.15625
4
def factorial (n): f = 1 while (n >0 ): f = f * n n = n - 1 return f print("Input your number") n= int(input()) print ("factorial of your input number:", factorial(n))
false
f7df70c87749177fdb0473207659ba0ee49741c0
beyzakilickol/week1Wednesaday
/palindrome.py
591
4.15625
4
word = input('Enter the word: ') arr = list(word) second_word = [] for index in range(len(arr)-1, -1 , -1): second_word.append(arr[index]) print(second_word) reversed = ''.join(second_word) print(reversed) def is_palindrome(): if(word == reversed): return True else: return False print(is_palindrome()) #-----------------------------------second way----------------------- #word = input('Enter the word: ') #reversed = word[::-1] #def is_palindrome(): # if(word == reversed): # return True # else: # return False #print(is_palindrome())
false
24f522cdedbbbe2c80fb94ba468f366102de7d06
beepboop271/programming-contest-stuff
/CCC-15-J1.py
248
4.125
4
month = input() day = input() if month < 2: output = "Before" elif month > 2: output = "After" else: if day < 18: output = "Before" elif day > 18: output = "After" else: output = "Special" print output
false
b707c3f7f4ebc050b4f9b97502c8505a35acb690
guohuahua2012/samples
/OOP/study_class.py
1,305
4.15625
4
#coding=utf-8 ''' author:chunhua ''' ''' 对象的绑定方法 在类中,没有被任何装饰器的方法就是绑定的到对象到的方法,这类方法专门为对象定制 ''' class People1: country = 'China' def __init__(self, name): self.name = name def eat(self): print("%s is eating--1" %self.name) people1 = People1('nick') print(people1.eat()) ''' 类的绑定方法 @classmothod修饰的方法是绑定到类的方法。这类方法专门为类定制。通过类名调用绑定到类的方法时, 会将类本身当做参数传递给类方法的第一参数 ''' class People2: country = 'China' def __init__(self, name): self.name = name # 绑定到类的方法 @classmethod def eat(cls): print("chunhua is eating--2") # 通过类名调用,绑定到类的方法eat() People2.eat() ''' 非绑定方法 在类内部使用@staticmethod 修饰的方法,即为非绑定方法。这类方法和普通定义的函数没有区别, 不与类或对象绑定,谁都可以调用,且没有自动传值的效果。 ''' class People3: country = 'China' def __init__(self, name): self.name = name @staticmethod def eat(): print('s% is eating--3') People3.eat() People3('nick').eat()
false
0e4a586b1bfb3a97d3311b61d8653e0041c42eb0
sinceresiva/DSBC-Python4and5
/areaOfCone.py
499
4.3125
4
''' Write a python program which creates a class named Cone and write a function calculate_area which calculates the area of the Cone. ''' import math class ConeArea: def __init__(self): pass def getArea(self, r, h): #SA=πr(r+sqrt(h**2+r**2)) return math.pi*r*(r+math.sqrt(h**2+r**2)) coneArea=ConeArea() radius=input("Input the radius (numeric):") height=input("Input the height (numeric):") print("Area is {}".format(coneArea.getArea(float(radius),float(height))))
true
928d5d403a69cd99e6c9ae579a6fc34b87965c1c
kostyafarber/info1110-scripts
/scripts/rain.py
468
4.125
4
rain = input("Is it currently raining? ") if rain == "Yes": print("You should take the bus.") elif rain == "No": travel = int(input("How far in km do you need to travel? ")) if travel > 10: print("You should take the bus.") elif travel in range(2, 11): print("You should ride your bike.") elif travel < 2: print("You should walk.") # if you use the range function with a if statement you use in not the equality operator
true
a2d0a7288f4fc9ce22f9f1447e1e70046b80b30b
tschutter/skilz
/2011-01-14/count_bits_a.py
733
4.125
4
#!/usr/bin/python # # Given an integer number (say, a 32 bit integer number), write code # to count the number of bits set (1s) that comprise the number. For # instance: 87338 (decimal) = 10101010100101010 (binary) in which # there are 8 bits set. No twists this time and as before, there is # no language restriction. # import sys def main(): number = int(sys.argv[1]) if number < 0: number = -number #import gmpy #print gmpy.digits(number, 2) nsetbits = 0 while number != 0: if number % 2 == 1: nsetbits += 1 number = number // 2 # // is integer division print "Number of bits set = %i" % nsetbits return 0 if __name__ == '__main__': sys.exit(main())
true
1d48da6a7114922b7e861afa93ddc03984815b0c
iZwag/IN1000
/oblig3/matplan.py
477
4.21875
4
# Food plan for three residents matplan = { "Kari Nordmann": ["brod", "egg", "polser"], "Magda Syversen": ["frokostblanding", "nudler", "burger"], "Marco Polo": ["oatmeal", "bacon", "taco"]} # Requests a name to check food plan for person = input("Inquire the food plan for a resident, by typing their name: ") # Prints feedback for the inquiry if person in matplan: print(matplan[person]) else: print("Sorry, that person doesn't seem to be a resident here.")
true
914134c3475f4618fa39fbbde917a4ada837968f
iZwag/IN1000
/oblig5/regnefunksjoner.py
1,933
4.125
4
# 1.1 # Function that takes two parameters and returns the sum def addisjon(number1, number2): return number1 + number2 # 1.2 # Function that subtracts the second number from the first one def subtraksjon(number1, number2): return number1 - number2 # 1.2 # Function that divides the first argument by the second # Also added an assertion to test for 0 in denominator def divisjon(number1, number2): assert(number2 != 0),"Division by 0 is illegal" return number1/number2 # 1.3 # Converts inches to centimeter and tests for an input <= 0 def tommerTilCm(antallTommer): assert(antallTommer > 0), "Inches must be greater than 0" return antallTommer * 2.54 # 1.4 # User input is run through the above functions and tested def skrivBeregninger(): print("Utregninger:") number1 = float(input("Skriv inn tall 1: ")) number2 = float(input("Skriv inn tall 2: ")) print("") print("Resultat av summering: %.1f" % addisjon(number1, number2)) print("Resultat av subtraksjon: %.1f" % subtraksjon(number1, number2)) print("Resultat av divisjon: %.1f" % divisjon(number1, number2)) print("") print("Konvertering fra tommer til cm:") number3 = float(input("Skriv inn et tall: ")) print("Resultat: %.2f" % tommerTilCm(number3)) # 1.1 # Prints the results of addition print(addisjon(1,3)) # 1.2 # Testing all the other functions with assert assert(subtraksjon(5,7) == -2),"Subtraction didn't work!" assert(subtraksjon(1,-8) == 9),"Subtraction didn't work!" assert(subtraksjon(-5,-5) == 0), "Subtraction didn't work!" assert(divisjon(10,2) == 5),"Division didn't work!" assert(divisjon(-2,2) == -1),"Division didn't work!" assert(divisjon(-8,4) == -2),"Division didn't work!" # 1.3 # Tests the inches to cm function assert(tommerTilCm(3) > 0),"Converting from inches didn't work!" # 1.4 # Runs the user test without arguments skrivBeregninger()
true
67b284c3f8dcaed9bdde75429d81c7c96f31847c
keithkay/python
/python_crash_course/functions.py
2,432
4.78125
5
# Python Crash Course # # Chapter 8 Functions # functions are defined using 'def' def greeting(name): """Display a simple greeting""" # this is an example of a docstring print("Hello, " + name.title() + "!") user_name = input("What's your name?: ") greeting(user_name) # in addition to the normal positional arguements for a function, you can # pass 'keyword arguements' to a function, and provide a default for an # arguement, essentially making it optional (you can also just make it # optional without a default by using ='' def describe_pet(pet_name, animal_type='cat'): """Display information about a pet""" print("\nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") # now when calling 'describe_pet' we either ensure they are in the correct # order, or we explictly assign them, illustrated here: describe_pet('harry', 'hamster') describe_pet(animal_type='dog', pet_name='willie') describe_pet('lois') # functions can also return a value, using, you guessed it 'return' def format_name(fname, lname, mname=''): """Return a full name, neatly formatted.""" if mname: full_name = fname + ' ' + mname + ' ' + lname else: full_name = fname + ' ' + lname return full_name.title() my_name = format_name('keith', 'kAy') print(my_name) print(format_name('J', 'Seymor', 'Thomas')) # functions can be set up to receive and arbitrary number of arguements # using '*' tells Python to create a tuple in which to store all the # arguements received def make_pizza(*toppings): """Print a list of the toppings requested""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') # you can also use '**' to pass a dictionary of unknown structure, but # the dictionary must be passed as keyword-value pairs def build_profile(fname, lname, **user_info): """ Build a dictionary containing everyting we know about a user. """ profile = {} profile['first_name'] = fname profile['last_name'] = lname for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print("") print(user_profile)
true
03ec200798e7dfd44352b6997e3b6f2804648732
keithkay/python
/python_crash_course/classes.py
776
4.5
4
# Python Crash Course # # Chapter 9 OOP # In order to work with an object in Python, we first need to # define a class for that object class Dog(): """A simple class example""" def __init__(self, name, age): """Initializes 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 rolling over in response to a command""" print(self.name.title() + " rolled over!") my_dog = Dog('rosey',11) print("My dog's name is " + my_dog.name.title() + ".") print(my_dog.name.title() + " is " + str(my_dog.age) + " years old.") my_dog.sit() my_dog.roll_over()
true
d146d5541c713488ed3e3cc0497baea68cf368ff
tcsfremont/curriculum
/python/pygame/breaking_blocks/02_move_ball.py
1,464
4.15625
4
""" Base window for breakout game using pygame.""" import pygame WHITE = (255, 255, 255) BALL_RADIUS = 8 BALL_DIAMETER = BALL_RADIUS * 2 # Add velocity component as a list with X and Y values ball_velocity = [5, -5] def move_ball(ball): """Change the location of the ball using velocity and direction.""" ball.left = ball.left + ball_velocity[0] ball.top = ball.top + ball_velocity[1] return ball def game(): """Main function for the game.""" WIDTH = 800 HEIGHT = 600 # Define the ball as a square box the size of the ball # We can use this to check collision later ball = pygame.Rect(300, HEIGHT - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER) # Initialize pygame pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Breaking Blocks") clock = pygame.time.Clock() # Game Loop while True: # Set max frames per second clock.tick(30 # Fill the screen on every update screen.fill(BLACK) # Event Handler for event in pygame.event.get(): if event.type == pygame.QUIT: return # Move ball ball = move_ball(ball) # Draw ball pygame.draw.circle(screen, WHITE, (ball.left + BALL_RADIUS, ball.top + BALL_RADIUS), BALL_RADIUS) # Paint and refresh the screen pygame.display.flip() if __name__ == "__main__": game()
true
56cb3dc1b9ef863246aa518d8a83b90b3f0c2d9d
trcooke/57-exercises-python
/src/exercises/Ex07_area_of_a_rectangular_room/rectangular_room.py
830
4.125
4
class RectangularRoom: SQUARE_FEET_TO_SQUARE_METER_CONVERSION = 0.09290304 lengthFeet = 0.0 widthFeet = 0.0 def __init__(self, length, width): self.lengthFeet = length self.widthFeet = width def areaFeet(self): return self.lengthFeet * self.widthFeet def areaMeters(self): return round(self.areaFeet() * self.SQUARE_FEET_TO_SQUARE_METER_CONVERSION, 3) if __name__ == "__main__": length = input("What is the length of the room in feet? ") width = input("What is the width of the room in feet? ") print("You entered dimensions of " + length + " feet by " + width + " feet.") print("The area is") room = RectangularRoom(float(length), float(width)) print(str(room.areaFeet()) + " square feet") print(str(room.areaMeters()) + " square meters.")
true
750f8c4d04bdd56ed851412e6b4b478ff9b4a0c3
gchh/python
/code/7-5.py
1,295
4.1875
4
class Student(object): def __init__(self,name): self.name=name s=Student('Bob') s.score=90 print(s.__dict__) del s.score print(s.__dict__) class Student1(object): name ='Student' p=Student1() print(p.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 print(Student1.name) #打印类的name属性 p.name='Micheal'#给实例绑定name属性 print(p.name) print(Student1.name) del p.name#删除实例的name属性 print(p.name)#再次调用p.name,由于实例的name属性没有找到,类的name属性就显示出来了 p.score=89 print(p.score) del p.score #print(p.score) # 学生 class Student(object): # 用于记录已经注册学生数 student_number = 0 def __init__(self, name): self.name = name # 注册一个学生:注册必填项名字,选填项利用关键字参数传递。注册完成,学生数+1 def register(name, **kw): a = Student(name) for k, v in kw.items(): setattr(a, k, v) Student.student_number += 1 return a bob = register('Bob', score=90) ah = register('Ah', age=8) ht = register('ht', age=8, score=90, city='Beijing') print(getattr(bob, 'score')) print(getattr(ah, 'age')) print(ht.city) print(ht.__dict__) print(Student.student_number)
false
71400d34dacc010d4351186485e9266fda5e7513
kosvicz/swaroop
/user_input.py
338
4.15625
4
#!/usr/bin/env python3 #--*-- conding: utf-8 --*-- def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Введите текск: ') if(is_palindrome(something)): print('Да, это палиндром') else: print('Нет, это не палиндром')
false
9ba7fb40eacf3ebca5c5fb9a5ac9e823f1ef9df0
mccabedarren/python321
/p12.p3.py
1,098
4.46875
4
#Define function "sqroot" (Function to find the square root of input float) #"Sqroot" calculates the square root using a while loop #"Sqroot" gives the number of guesses taken to calculate square root #The program takes input of a float #if positive the program calls the function "sqroot" #if negative the program prints the error message: "Error: Number must be greater than 0" def sqroot(number): epsilon = 0.01 step = epsilon**2 numguesses=0 root = 0.0 while abs(number-root **2) >=epsilon and root <=number: root += step numguesses +=1 if numguesses % 100000 == 0: print('Still running. Number of guesses:',numguesses) print ('Number of guesses:',numguesses) if abs (number-root**2) < epsilon: return ('The approximate square root of',number,'is',root) else: return('Failed to find the square root of',number) number = float(input('Enter the number for which you wish to calculate the square root:')) if number > 0: print (sqroot(number)) else: print("Error: Number must be greater than 0")
true
dc5b545562df84e36ce8696cdaa33e0239a37001
mccabedarren/python321
/p13.p2.py
431
4.46875
4
#Program to print out the largest of two user-entered numbers #Uses function "max" in a print statement def max(a,b): if a>b: return a else: return b #prompt the user for two floating-point numbers: number_1 = float(input("Enter a number: ")) number_2 = float(input("Enter another number: ")) print ("The largest of", number_1,"and", number_2, "is", max(number_1, number_2)) print("Finished!")
true
e0fc45ba2b2da28b629f3c6bf7ce6c85d4334ca4
elizabethadventurer/Treasure-Seeker
/Mini Project 4 part 1.py
1,575
4.28125
4
# Treasure-Seeker #Introduction name = input("Before we get started, what's your name?") print("Are you ready for an adventure", name, "?") print("Let's jump right in then, shall we?") answer = input("Where do you thnk we should start? The old bookstore, the deserted pool, or the abandoned farm?") if answer == "the deserted pool" or "deserted pool" or "Pool" or "The deserted pool" or "pool" or "the pool" or "Deserted pool" or "deserted pool" or "the pool": print("Oooh, a spooky pool? Sure, why not? Lets see if there's even any water left...maybe a drowned spirit?!") if answer == "the old bookstore" or "the bookstore" or "bookstore" or "The old bookstore" or "Bookstore": print("The bookstore huh? Sounds like the lesser of three evils.") if answer == "the abandoned farm" or "the farm" or "The farm" or "Farm" or "The abandoned farm" or "farm": print("Hmm...sounds dangerous..but since you picked it...I guess I must join you. Whatever happens....happens.") name2 = input("Honestly...there seems to be more to this than meets the eye. Do you trust me ?") if name2 == "Yes" or name2 =="yes": print("Thanks for the confidence boost!") answer2 = input("We should move forward...right? *Answer in yes/no") if answer2 == "Yes" or answer2 == "yes": print("Okay...) if answer2 == "No" or answer2 == "no": print("Whew, bye bye.") exit(3) if name == "No" or name == "no": print("Ouch, okay. Good luck getting through this without any hints...in fact I suggest you restart the game...cuz you ain’t going nowhere no more.") exit()
true
55ca7df15d0ec947e09b3c0390030ea750143a6c
zingpython/webinarPytho_101
/five.py
233
4.25
4
def even_or_odd(): number = int(input("Enter number:")) if number % 2 == 1: print("{} is odd".format(number)) elif number % 2 == 0: print("{} is even".format(number)) even_or_odd() # "Dear Mr.{} {}".format("John","Murphy")
false
6e6545bf2e9b4a7ff360d8151e6418168f777ff8
sagarujjwal/DataStructures
/Stack/StackBalancedParens.py
986
4.15625
4
# W.A.P to find the given parenthesis in string format is balanced or not. # balanced: {([])}, [()] # non balanced: {{, (() from stack import Stack def is_match(p1, p2): if p1 == '[' and p2 == ']': return True elif p1 == '{' and p2 == '}': return True elif p1 == '(' and p2 == ')': return True else: return False def is_paren_balanced(paren_string): s=Stack() is_balanced=True index=0 while index < len(paren_string) and is_balanced: paren=paren_string[index] if paren in '[{(': s.push(paren) else: if s.is_empty(): is_balanced = False else: top=s.pop() if not is_match(top,paren): is_balanced = False index+=1 if s.is_empty() and is_balanced: return True else: return False #print(is_paren_balanced('([{(){}()}])')) print(is_paren_balanced('[{(){}{}]'))
true
380769147add0ecf5e071fa3eb5859ee2eded6da
alexmeigz/code-excerpts
/trie.py
1,185
4.40625
4
# Trie Class Definition # '*' indicates end of string class Trie: def __init__(self): self.root = dict() def insert(self, s: str): traverse = self.root for char in s: if not traverse.get(char): traverse[char] = dict() traverse = traverse.get(char) traverse['*'] = '*' def find(self, s: str) -> bool: traverse = self.root for char in s: if not traverse.get(char): return False traverse = traverse.get(char) return traverse.get('*', '') == '*' def delete(self, s: str) -> bool: traverse = self.root for char in s: if not traverse.get(char): return False traverse = traverse.get(char) if not traverse.get('*'): return False traverse.pop("*") return True ''' # Sample Usage if __name__ == "__main__": t = Trie() t.insert("hello") print(t.find("he")) t.insert("he") print(t.find("he")) t.delete("he") print(t.find("he")) print(t.root) '''
true
03995a46974520e6d587e3c09a24fa1c98a6423f
brownboycodes/problem_solving
/code_signal/shape_area.py
443
4.1875
4
""" Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. """ def shapeArea(n): return n**2+(n-1)**2
true
298ce4a268c6242ee4b18db1b5029995ebaa183f
brownboycodes/problem_solving
/code_signal/adjacent_elements_product.py
362
4.125
4
""" Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. """ def adjacentElementsProduct(inputArray): product=0 for i in range(0,len(inputArray)-1): if inputArray[i]*inputArray[i+1]>product or product==0: product=inputArray[i]*inputArray[i+1] return product
true
98edf9ce118f9641f55d08c6527da8d01f03b49a
kirubeltadesse/Python
/examq/q3.py
604
4.28125
4
# Kirubel Tadesse # Dr.Gordon Skelton # J00720834 # Applied Programming # Jackson State University # Computer Engineering Dept. #create a program that uses a function to determine the larger of two numbers and return the larger to the main body of the program and then print it. You have to enter the numbers from the keyboard so you have to use input. #defining the function def printLarg(): x = input("Enter your first number: ") y = input("Enter your second number: ") holder=[x,y] larg = max(holder) print("the larger number is : ") print(larg) return larg #calling the function printLarg()
true
9b773282655c5e3a6a35f9b59f22ddb221386870
AyvePHIL/MLlearn
/Sorting_alogrithms.py
2,275
4.21875
4
# This is the bubbleSort algorithm where we sort array elements from smallest to largest def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n - 1): # range(n) also work but outer loop will repeat one time more than needed (more efficient). # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1. Swap if the element found is greater than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr # Another bubble sort algorithm but returns the no. of times elements were swapped from small to large def minimumSwaps(arr): swaps = 0 temp = {} for i, val in enumerate(arr): temp[val] = i for i in range(len(arr)): # because they are consecutive, I can see if the number is where it belongs if arr[i] != i + 1: swaps += 1 t = arr[i] # Variable holder arr[i] = i + 1 arr[temp[i + 1]] = t # Switch also the tmp array, no need to change i+1 as it's already in the right position temp[t] = temp[i + 1] return swaps def minimumSwappnumber(arr): noofswaps = 0 for i in range(len(arr)): while arr[i] != i + 1: temp = arr[i] arr[i] = arr[arr[i] - 1] arr[temp - 1] = temp noofswaps += 1 print noofswaps # A QuickSort algorithm where we pivot about a specified int in a array by partitioning the array into two parts def quick_sort(sequence): if len(sequence)<=1: return(sequence) else: pivot = sequence.pop() items_bigger = [] items_smaller = [] for item in sequence: if item > pivot: items_bigger.append(item) else: items_smaller.append(item) return quick_sort(items_smaller) + [pivot] + quick_sort(items_bigger) # This is the testing phase, where the above algorithms are tested and tried by FIRE🔥🔥🔥 testing_array = [3, 56, 0, 45, 2324, 2, 12, 123, 434, 670, 4549, 3, 4.5, 6] print(bubbleSort(testing_array)) print(quick_sort(testing_array)) print(minimumSwappnumber(testing_array))
true
2486925e16396536f048f25889dc6d3f7675549a
NathanielS/Week-Three-Assignment
/PigLatin.py
500
4.125
4
# Nathaniel Smith # PigLatin # Week Three Assignment # This program will take input from the usar, translate it to PigLatin, # and print the translated word. def main (): # This section of code ask for input from the usar and defines vowels word = input("Please enter an English word: ") vowels = "AEIOUaeiou" # This section of code translates the usars input into PigLatin if word[0] in vowels: print(word + "yay") else: print(word[1:] + word[0] + "ay") main ()
true
4d872b88871da0fd909f4cb71954a3f0f8d0f43f
RocketDonkey/project_euler
/python/problems/euler_001.py
470
4.125
4
"""Project Euler - Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def Euler001(): num = 1000 r = range(3, num) for index, i in enumerate(xrange(3, num)): if sum(bool(j) for j in (i%3, i%5)) > 1: r[index] = 0 return sum(r) def main(): print Euler001() if __name__ == '__main__': main()
true
54406e46376433c727027b350e1b7b6a6f818181
kamil-fijalski/python-reborn
/@Main.py
2,365
4.15625
4
# Let's begin this madness print("Hello Python!") int1 = 10 + 10j int2 = 20 + 5j int3 = int1 * int2 print(int3) print(5 / 3) # floating print(5 // 3) # integer str1 = "Apple" print(str1[0]) print(str(len(str1))) print(str1.replace("p", "x") + " " + str1.upper() + " " + str1.lower() + " " + str1.swapcase()) # method "find" works like "instr" in SQL # tuples are immutable and they can be nesting tuple1 = ("A", "B", 1, 2, 3.14, 2.73) print(type(tuple1)) print(tuple1[2]) tupleStr = tuple1[0:2] print(tupleStr) tupleNest = (("Jazz", "Rock"), "Dance", ("Metal", "Folk")) print(tupleNest[0][1]) # list are mutable -> square brackets / list can nested other lists and tuples list1 = [5, 1, 3, 10, 8] print(sorted(list1)) list1.extend([7, 12]) # extend adds two elements -> APPEND adds one element (list with elements 7, 12) print(list1) list1[0] = 100 # are mutable print(list1) del(list1[2]) print(list1) str2 = "Quick brown fox jumps over the lazy dog" listSplit = str2.split() print(listSplit) listSplit2 = listSplit[:] # clone existing list # sets / collection -> unique element => curly brackets set1 = set(list1) print(set1) set1.add(256) set1.add(512) print(set1) set1.remove(100) print(set1) check = 512 in set1 # checking if element exists in given set print(check) set88 = {2, 4, 5, 7, 9} set99 = {1, 3, 5, 8, 9} print(set88 & set99) # intersect of the two sets / or "intersection" method print(set88.union(set99)) print(set88.difference(set99)) # dictionaries -> key: value # keys are immutable and unique, values can be mutable and duplicates dict1 = {1: "one", 2: "two", 3: "three"} print(dict1) print(dict1[3]) dict1[1000] = "thousand" # adding new element print(dict1) del(dict1[2]) # delete element print(dict1) print(2 in dict1) # checking if element exists in dict print(dict1.keys()) print(dict1.values()) age = 25 if age < 25: print("less") elif age > 25: print("more") else: print("equal") squares = {"red", "blue", "yellow", "black", "purple"} for i in squares: print(i) str88 = "" for r in range(10, 15): str88 = str88 + str(r) + " " print(str88) str99 = "" while age < 30: str99 = str99 + "bu" + " " age += 1 print(str99 + "BUM!") def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) nn = input("Give me a word... ") print(factorial(len(nn)))
true
7b2d9aa4ece7d8a777def586cb3af02685eac071
omer-goder/python-skillshare-beginner
/conditions/not_in_keyword.py
347
4.1875
4
### 17/04/2020 ### Author: Omer Goder ### Checking if a value is not in a list # Admin users admin_users = ['tony','frank'] # Ask for username username = input("Please enter you username?") # Check if user is an admin user if username not in admin_users: print("You do not have access.") else: print("Access granted.")
true
f457e6763c190e10b297912019aa76ad7dc899a4
omer-goder/python-skillshare-beginner
/dictionary/adding_user_input_to_a_dictionary.py
997
4.375
4
### 04/05/2020 ### Author: Omer Goder ### Adding user input to a dictionary # Creat an empty dictionary rental_properties = {} # Set a flag to indicate we are taking apllications rental_open = True while rental_open: # while True # prompt users for name and address. username = input("\nWhat is your name?") rental_property = input("What is the address of the property you would like to rent?") # Store the responses in a dictionary rental_properties[username] = rental_property # Ask if the user knows anyone else who would like to rent their property repeat = input("\nDo you know anyone how might like to rent out their propery?\t(Y/N)").lower() if repeat == 'y': continue # just to check code upgrading option else: rental_open = False # Adding propery is complete print('\n---Property to rent---') for username, rental_property in rental_properties.items(): print(username.title() + " have a property at " + rental_property.title() + " to rent.")
true
fd1ccd8e94a9a2f7d68ce5caade21b4727a5356e
omer-goder/python-skillshare-beginner
/conditions/or_keyword.py
418
4.21875
4
### 17/04/2020 ### Author: Omer Goder ### Using the OR keyword to check values in a list # Names registered registered_names = ['tony','frank','mary','peter'] username = input("Please enter username you would like to use.\n\n").lower() #Check to see if username is already taken if username in registered_names: print("Sorry, username is already taken.") else: print("This username is available")
true
34c12dde56d3cb3176565750b4292d6a062105df
omer-goder/python-skillshare-beginner
/list/a_list_of_numbers.py
552
4.25
4
### 15/04/2020 ### Author: Omer Goder ### Creating a list of numbers # Convert numbers into a list numbers = list(range(1,6)) print(numbers) print('\n') # print("List of even number in the range of 0 to 100:") even_numbers = list(range(0,102, 2)) print(even_numbers) print('\n') print("List of square values of 1 to 10:") squares = [] for value in range(1,11): square = value ** 2 squares.append(square) print(squares) print('\n') digits = [1,2,3,4,5] print(min(digits)) print(max(digits)) print(sum(digits)) print('\n')
true
97360bd4a55477713e3868b9c9af811143151aca
omer-goder/python-skillshare-beginner
/class/class_as_attribute(2).py
1,127
4.34375
4
### 11/05/2020 ### Author: Omer Goder ### Using a class as an attribute to another class class Tablet(): """This will be the class that uses the attribute.""" def __init__(self, thickness, color, battery): """Initialize a parameter as a class""" self.thickness = thickness self.color = color self.battery = battery self.screen = Screen() class Screen(): """This will be the attribute for the other class.""" def __init__(self, glass_grade = 'gorilla glass', color = 'BW', screen_size = '8"'): """Initalize the attributes of the Attrib class.""" self.glass = glass_grade self.color = color self.screen_size = screen_size def screen_type(self): """Print the attributes""" print("Glass: " + self.glass + "\nSize: " + self.screen_size + ".") def screen_color(self): """Print the arguments.""" print("This is a " + self.color + " screen.\n") my_tablet = Tablet('5 mm', 'green', '4800 mAh') my_tablet.screen.screen_type() my_tablet.screen.screen_color() my_screen = Screen('Gorilla 8', 'color', '10"') my_tablet.screen = my_screen my_tablet.screen.screen_type() my_tablet.screen.screen_color()
true
f385856290585e7e625d82c6f1d0b6f5aa171f71
akram2015/Python
/HW4/SECURITY SCANNER.py
631
4.4375
4
# this program Prompt user for a file name, and read the file, then find and report if file contains a string with a string ("password=") in it. # file name = read_it.txt found = True userinput = input ("Enter the file name: ") string = input ("Enter the string: ") myfile = open (userinput) # open the file that might contain a string for line in myfile: if string in line: print ("The line which contain the string", string, "is: ", line) # print the line that contain the string found = False myfile.close() if found: print ("The string", string, "does not exist in", userinput, "file!")
true
c6ee4574166c0e00e6e7bddad59ca354677ea66a
akram2015/Python
/HW3/BunnyEars.py
431
4.3125
4
# Recursive function that return the number of ears for bunnies def bunny_ears(n): # n number of bunnies if n <= 0: # 0 bunny condition return 0 elif n % 2 == 0: # for even numbers of bunnies return bunny_ears(n-1) + 2 else: # for odd numbers of bunnies return bunny_ears(n-1) + 3 x = int(input("Enter a number of bunnies: ")) print("The number of ears are:", bunny_ears(x))
false
8e2989008f52b56dee43360378533c5b4a757d90
josego85/livescore-cli
/lib/tt.py
2,078
4.40625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import re ''' module to convert the given time in UTC to local device time _convert() method takes a single time in string and returns the local time convert() takes a list of time in string format and returns in local time NOTE: any string not in the format "digits:digits" will be returned as is USAGE: >>>convert(['19:45','18:15','5:45','512','FT']) ['01:00','00:00','11:30','512','FT'] isgreat(time1,time2) takes two time strings such as "4:30" and "12"15" and returns if the first time is greater than the second. if time1>time2: return 1 if time2>time1: return -1 if time1==time2: return 0 NOTE: the function stalls if not in the above format USAGE: >>>isgreat("3:00","4:15") -1 ''' if time.daylight: offsetHour = time.altzone / 3600.0 else: offsetHour = time.timezone / 3600.0 hour = int(-offsetHour) minute = int(-offsetHour * 60 % 60) def _convert(time): if bool(re.match(r'[0-9]{1,2}:[0-9]{1,2}', time)): time = list(map(int, time.split(':'))) time[1] += minute time[0] += hour if time[1] > 59: time[1] -= 60 time[0] += 1 elif time[1] < 0: time[1] += 60 time[0] -= 1 if time[0] < 0: time[0] += 24 elif time[0] > 23: time[0] -= 24 time = _fix(str(time[0])) + ":" + _fix(str(time[1])) return time def _fix(y): if len(y) == 1: y = '0' + y return y def convert(times): times = list(map(_convert, times)) return times def is_great(time1, time2): t1 = list(map(int, time1.split(':'))) t2 = list(map(int, time2.split(':'))) if t1[0] > t2[0]: return 1 elif t2[0] > t1[0]: return -1 else: if t1[1] > t2[1]: return 1 elif t2[1] > t1[1]: return -1 else: return 0 def datetime_now(): return time.strftime("%c")
true
0c900e9b4ad2f2b3e904ee61661cda39ed458646
shivraj-thecoder/python_programming
/Swapping/using_tuple.py
271
4.34375
4
def swap_tuple(value_one,value_two): value_one,value_two=value_two,value_one return value_one,value_two X=input("enter value of X :") Y=input("enter value of Y :") X, Y=swap_tuple(X,Y) print('value of X after swapping:', X) print('value of Y after swapping:', Y)
true
ad00ddf3a4f192d2017d9bb8fbb5dd4d90d9a065
Mengeroshi/python-tricks
/3.Classes-and-OOP/4.3.copying_arbitrary_objects.py
779
4.1875
4
import copy """Shallow copy of an object """ class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'Point({self.x!r}, {self.y!r})' a = Point(23, 42) b = copy.copy(a) print(a) print(b) print(a is b) class Rectangle: def __init__(self, topleft, bottomright): self.topleft = topleft self.bottomright = bottomright def __repr__(self): return(f'Rectangle({self.topleft!r}, {self.bottomright!r})') rect = Rectangle(Point(0,1), Point(5, 6)) srect = copy.copy(rect) print(rect) print(srect) print(rect is srect) rect.topleft.x = 999 print(rect) print(srect) """ Deep copy of an object """ deep_rect = copy.deepcopy(rect) deep_rect.topleft.x = 222 print(rect) print(deep_rect)
false
1c77967940f1f8b17e50f4f2632fb34a13b3daf0
sweetysweat/EPAM_HW
/homework1/task2.py
692
4.15625
4
""" Given a cell with "it's a fib sequence" from slideshow, please write function "check_fib", which accepts a Sequence of integers, and returns if the given sequence is a Fibonacci sequence We guarantee, that the given sequence contain >= 0 integers inside. """ from typing import Sequence def check_fibonacci(data: Sequence[int]) -> bool: seq_len = len(data) fib1 = 0 fib2 = 1 if seq_len == 0 or seq_len == 1: return False if data[0] == 0 and data[1] == 1: for i in range(2, seq_len): fib1, fib2 = fib2, fib1 + fib2 if not fib2 == data[i]: return False return True else: return False
true
d10cd2ab04df7e4720f72bf2f5057768e8bfad3f
sweetysweat/EPAM_HW
/homework8/task_1.py
1,745
4.21875
4
""" We have a file that works as key-value storage, each line is represented as key and value separated by = symbol, example: name=kek last_name=top song_name=shadilay power=9001 Values can be strings or integer numbers. If a value can be treated both as a number and a string, it is treated as number. Write a wrapper class for this key value storage that works like this: storage = KeyValueStorage('path_to_file.txt') that has its keys and values accessible as collection items and as attributes. Example: storage['name'] # will be string 'kek' storage.song_name # will be 'shadilay' storage.power # will be integer 9001 In case of attribute clash existing built-in attributes take precedence. In case when value cannot be assigned to an attribute (for example when there's a line 1=something) ValueError should be raised. File size is expected to be small, you are permitted to read it entirely into memory. """ import re from typing import Union class KeyValueStorage: def __init__(self, path: str): self.storage = dict() self.create_class_attributes(path) def create_class_attributes(self, path: str): with open(path, 'r') as f: for line in f: key, value = line.strip().split('=') if not re.search(r'^[a-zA-z_][\w]*$', key, re.ASCII): raise ValueError("The key can only contain ASCII symbols and can't starts with numbers!") value = int(value) if value.isdigit() else value self.storage[key] = value def __getattr__(self, attr_name: str) -> Union[str, int]: return self.storage[attr_name] def __getitem__(self, attr_name: str) -> Union[str, int]: return self.storage[attr_name]
true
4209cfd3b879e1c02531a7e8dae52dee26d2cce0
bahadirsensoz/PythonCodes
/fahrenheit.py
266
4.28125
4
while(True): print("CELSIUS TO FAHRENHEIT CONVERTER") celsius = float(input("Please enter your degree by celcius:")) #Ali Bahadır Şensöz fahr=1.8*celsius+32 print("Your temperature " +str(celsius) + " Celsius is " +str(fahr) + " in Fahrenheit.")
false
50e50015e425e4ba5a924775ded68b79cba31edc
sawall/advent2017
/advent_6.py
2,729
4.21875
4
#!/usr/bin/env python3 # memory allocation # #### part one # # The debugger would like to know how many redistributions can be done before a blocks-in-banks # configuration is produced that has been seen before. # # 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. # # Given the initial block counts in your puzzle input, how many redistribution cycles must be # completed before a configuration is produced that has been seen before? def day6(): inp = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5' memory = [int(i) for i in inp.strip().split()] past_states = [] num_banks = len(memory) cycles = 0 while (hash(tuple(memory)) not in past_states): past_states.append(hash(tuple(memory))) realloc_blocks = max(memory) realloc_cursor = memory.index(max(memory)) memory[realloc_cursor] = 0 while realloc_blocks > 0: realloc_cursor += 1 memory[(realloc_cursor) % num_banks] += 1 realloc_blocks -= 1 cycles += 1 print('-= advent of code DAY SIX =-') print(' part one: total cycles until loop detected = ' + str(cycles)) #### part two # # Out of curiosity, the debugger would also like to know the size of the loop: starting from a state # that has already been seen, how many block redistribution cycles must be performed before that # same state is seen again? loop_start = past_states.index(hash(tuple(memory))) print(' part two: loop size = ' + str(cycles - loop_start)) day6()
true
910db0a0156d0f3c37e210ec1931fd404f1357e9
aymhh/School
/Holiday-Homework/inspector.py
1,095
4.125
4
import time print("Hello there!") print("What's your name?") name = input() print("Hello there, " + name) time.sleep(2) print("You have arrived at a horror mansion!\nIt's a large and spooky house with strange noises coming from inside") time.sleep(2) print("You hop out of the car and walk closer...") time.sleep(2) print("You tread carefully onto the rotten woodpath porch.") time.sleep(2) print("You trip over a loose plank of wood and fall over") time.sleep(2) print("Your knee hurts. But you notice something under the porch...") time.sleep(2) print("It's a box...") time.sleep(2) print("Inside it was a blooded hand!") time.sleep(2) print("You wonder wether to go inside or leave...") question = input("What is your next move?\n - Type in `inside` to go inside the house\n - Type in `leave` to leave away!\n") if question == "inside": print("you pick yourself up and head inside the house and only to be greated with a mysterious character, the door slams behind you and you are trapped!") if question == "leave": print("you rush back into your car and drift away, very far!")
true
24d025d8a89380a8779fbfdf145083a9db64fc07
shahad-mahmud/learning_python
/day_16/unknow_num_arg.py
324
4.15625
4
def sum(*nums: int) -> int: _sum = 0 for num in nums: _sum += num return _sum res = sum(1, 2, 3, 5) print(res) # Write a program to- # 1. Declear a funtion which can take arbitary numbers of input # 2. The input will be name of one or persons # 3. In the function print a message to greet every one
true
382a8a2f5c64f0d3cd4c1c647b97e19e2c137fda
shahad-mahmud/learning_python
/day_3/if.py
417
4.1875
4
# conditional statement # if conditon: # logical operator # intendation friend_salary = float(input('Enter your salary:')) my_salary = 1200 if friend_salary > my_salary: print('Friend\'s salary is higher') print('Code finish') # write a program to- # a. Take a number as input # b. Identify if a number is positive # sample input 1: 10 # sample output 1: positive # sample inout 2: -10 # sample output:
true
ec55765f79ce87e5ce0f108f873792fecf5731f6
shahad-mahmud/learning_python
/day_7/python_function.py
347
4.3125
4
# def function_name(arguments): # function body def hello(name): print('Hello', name) # call the funciton n = 'Kaka' hello(n) # Write a program to- # a. define a function named 'greetings' # b. The function print 'Hello <your name>' # c. Call the function to get the message # d. Modify your function and add a argument to take your name
true
b0824befae2b1d672ac6ec693f97e7c801366c0c
srinivasdasu24/regular_expressions
/diff_patterns_match.py
1,534
4.53125
5
""" Regular expression basics, regex groups and pipe character usage in regex """ import re message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.' phoneNum_regex = re.compile( r'\d\d\d-\d\d\d-\d\d\d\d') # re.compile to create regex object \d is - digit numeric character mob_num = phoneNum_regex.search(message) # print(phoneNum_regex.findall(message)) # findall returns a list of all occurences of the pattern print(mob_num.group) # regex object has group method which tells the matching pattern # pattern with different groups - groups are created in regex strings using parentheses phoneNum_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') # this pattern will have twwo groups mob_num = phoneNum_regex.search(message) mob_num.group() # gives entire match mob_num.group(1) # gives first 3 digits 1 is first set of parentheses , 2 is second and so on mob_num.group(2) # gives remaining pattern # o/p is : '415-555-1011' # :'415' # : '555-1011' # pattern with matching braces( () ) phoneNum_regex = re.compile(r'\(\d\d\d\) \d\d\d-\d\d\d\d') mo = phoneNum_regex.search('My number is (415) 555-4243') mo.group() # o/p is : '(415) 555-4243 # matching multiple patterns bat_regx = re.compile(r'Bat(man|mobile|copter|bat)') # pipe | symbol used to match more than one pattern mo = bat_regx.search('I like Batman movie') mo.group() # o/p is 'Batman' # if search method doesn't find pattern it returns None mo = bat_regx.search('Batmotorcycle lost a wheel') mo == None # prints True
true