blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
edcd912d6ef4b596f1d28b23a840b57c4339aa70
febbydocdoc/python-workshop
/calculator.py
504
4.125
4
number1 = int(input('masukkan angka pertama: ')) operator = input('pilih operator (+, -, /, *): ') number2 = int(input('masukkan angka kedua: ')) result = 0 if operator == '+': result = number1 + number2 elif operator == '-': result = number1 - number2 elif operator == '/': result = number1 / number2 elif operator == '*': result = number1 / number2 else: print('invalid operatior!') if result is not None: print(f'{number1} {operator} {number2} = {result}')
false
70b31a55c9bb1c410d2cf9605b164699dfafb457
JavonDavis/python-dependency-injector
/examples/providers/factory_method_injections.py
1,764
4.21875
4
"""`Factory` providers with method injections example.""" from dependency_injector import providers from dependency_injector import injections class User(object): """Example class User.""" def __init__(self): """Initializer.""" self.main_photo = None self.credit_card = None def set_main_photo(self, photo): """Set user's main photo.""" self.main_photo = photo def set_credit_card(self, credit_card): """Set user's credit card.""" self.credit_card = credit_card class Photo(object): """Example class Photo.""" class CreditCard(object): """Example class CreditCard.""" # User, Photo and CreditCard factories: credit_cards_factory = providers.Factory(CreditCard) photos_factory = providers.Factory(Photo) users_factory = providers.Factory(User, injections.Method('set_main_photo', photos_factory), injections.Method('set_credit_card', credit_cards_factory)) # Creating several User objects: user1 = users_factory() # Same as: user1 = User() # user1.set_main_photo(Photo()) # user1.set_credit_card(CreditCard()) user2 = users_factory() # Same as: user2 = User() # user2.set_main_photo(Photo()) # user2.set_credit_card(CreditCard()) # Making some asserts: assert user1 is not user2 assert isinstance(user1.main_photo, Photo) assert isinstance(user1.credit_card, CreditCard) assert isinstance(user2.main_photo, Photo) assert isinstance(user2.credit_card, CreditCard) assert user1.main_photo is not user2.main_photo assert user1.credit_card is not user2.credit_card
true
4fec8c33bd70956229b039ed849f1c24838c8f6e
JavonDavis/python-dependency-injector
/examples/miniapps/movie_lister/app_db.py
1,734
4.375
4
"""A naive example of dependency injection on Python. Example implementation of dependency injection in Python from Martin Fowler's article about dependency injection and inversion of control: http://www.martinfowler.com/articles/injection.html This mini application uses ``movies`` library, that is configured to work with sqlite movies database. """ import sqlite3 from dependency_injector import catalogs from dependency_injector import providers from dependency_injector import injections from movies import MoviesModule from movies import finders from settings import MOVIES_DB_PATH class ApplicationModule(catalogs.DeclarativeCatalog): """Catalog of application component providers.""" database = providers.Singleton(sqlite3.connect, MOVIES_DB_PATH) @catalogs.override(MoviesModule) class MyMoviesModule(catalogs.DeclarativeCatalog): """Customized catalog of movies module component providers.""" movie_finder = providers.Factory(finders.SqliteMovieFinder, *MoviesModule.movie_finder.injections, database=ApplicationModule.database) @injections.inject(MoviesModule.movie_lister) def main(movie_lister): """Main function. This program prints info about all movies that were directed by different persons and then prints all movies that were released in 2015. :param movie_lister: Movie lister instance :type movie_lister: movies.listers.MovieLister """ print movie_lister.movies_directed_by('Francis Lawrence') print movie_lister.movies_directed_by('Patricia Riggen') print movie_lister.movies_directed_by('JJ Abrams') print movie_lister.movies_released_in(2015) if __name__ == '__main__': main()
true
caf076c8ea6fd75e02eb04a59543806c5eb37724
krrdms/ITP270Codes
/Scratch/week5/class7.py
1,373
4.21875
4
class car: valid_directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] # initialization function - initializes instance of car class # with direction, speed, and location values def __init__(self): self.direction = "N" self.speed = 0 self.location = (38.8334, -77.2365) self.moving = False # These methods change class attributes # also known as setters def changeMovingDirection(self, speed, direction): if type(speed) is int or float: self.speed = speed if direction in self.valid_directions: self.direction = direction def stop(self): self.speed = 0 def changeStaticDirection(self,direction): if not self.moving: self.direction = direction def setLocation(self, location): self.location = location # these methods return class attributes # also referred to as 'getters" @property def retLatorLong(self, choice): Lat, Long = self.location if choice == 1: return Lat elif choice == 2: return Long else: return Lat,Long @property def retSpeed(self): return self.speed @property def retIsMoving(self): return self.moving @property def getDirection(self): return self.direction
true
c5536d6bbd9151282498d1e7a7f952361133d394
YannTorres/Python-mundo1e2
/Desafios/39AlistamentoMilitar.py
611
4.1875
4
import datetime ano = int(input('Ano de nascimento: ')) idade = datetime.date.today().year - ano tempo = 18 - idade tempo2 = idade - 18 print(f'Quem nasceu em {ano} tem {idade} anos em {datetime.date.today().year}') if idade < 18: print(f'Ainda falta {tempo} ano(s) para o alistamento') print(f'Seu alistamneto será em {datetime.date.today().year + tempo}') elif idade > 18: print(f'Você deveria ter se alistado em {tempo2} ano(s)') print(f'Seu alistamento deveria ter acontecido em {datetime.date.today().year - tempo2}') else: print(f'Você deve se alistar IMEDIATAMENTE')
false
5fffee5eab602c324650102f5782806ebf6790b7
martinber/guia-sphinx
/ejemplos_sphinx/manual/pynprcalc/pynprcalc/funciones/math/basico.py
2,207
4.1875
4
""" Funciones matemáticas básicas. """ def suma(x, y): """ Suma de dos números. .. math:: x + y Args: x (float): Sumando. y (float): Sumando. Returns: float: La suma. """ return x + y def resta(x, y): """ Resta de dos números. .. math:: x - y Args: x (float): Minuendo. y (float): Sustraendo. Returns: float: La resta. """ return x - y def producto(x, y): """ Producto de dos números. .. math:: x y Args: x (float): Factor. y (float): Factor. Returns: float: El producto. """ return x * y def division(x, y): """ La división de dos números. .. math:: \\frac{x}{y} Args: x (float): Dividendo. y (float): Divisor. Returns: float: El cociente. """ return x / y def cuadrado(x): """ El cuadrado de un número. .. math:: x^2 Args: x (float): Base. Returns: float: El cuadrado. """ return x * x def potencia(x, y): """ Potencia de dos números. .. math:: x^y Args: x (float): Base. y (float): Exponente. Returns: float: La potencia. """ return x**y def raiz_cuadrada(x): """ La raiz cuadrada de un número. .. math:: \sqrt{x} Args: x (float): Radicando. Returns: float: La raíz cuadrada. """ return x**(1/2) def raiz(x, y): """ La raíz enésima de un número. .. math:: \sqrt[y]{x} Args: x (float): Radicando. y (float): Índice. Returns: float: La raíz. """ return x**(1/y) def inverso(x): """ El inverso de un número. .. math:: \\frac{1}{x} Args: x (float): Número a invertir. Returns: float: El inverso. """ return 1 / x def opuesto(x): """ El opuesto de un número. .. math:: -x Args: x (float): Número a calcular el opuesto. Returns: float: El opuesto. """ return -x
false
5be47f5dab8d7a4a55585055818fd449b8fa192d
nonecode404/learn
/每日一练.py
543
4.125
4
def insertSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j = j - 1 arr[j+1] = key arr = [12, 11, 13, 5, 6, 9, 20, 28] insertSort(arr) for it in arr: print(it) def binarySearch(arr, l, r, k): mid = (l + r) // 2 if arr[mid] > k : binarySearch(arr, l, mid - 1,k) elif arr[mid] < k : binarySearch(arr, mid+1, r, k) else: return mid print(binarySearch(arr, 0, len(arr) -1 , 11))
false
a3d03e656930abf0f829a3bffd2894d8ebe03ce4
221810304008/python-programs
/game.py
1,366
4.21875
4
# Take random inputs # if equal print "Equal" # Else print whether the given number is "greater" or "lesser" # Ex. b=5 ; a=25 ; a > b # Ex. b=5 ; a=2 ; a < b # Ex. b=5 ; a=7 ; a > b # Ex. b=5 ; a=10 ; a > b # Ex. b=5 ; a=5 ; a = b " Won the game" import random def prime(): flag=0 while(flag==0): n=random.randint(1,250) count=0 for i in range(2,n+1): if(n%i==0): count+=2 if(count==2): flag=1 return n print("WELCOME TO yvshu's WORLD!!!") b=prime() n=str(input('enter your name')) f=0 c=6 for i in range(6): if f!=1 : a=(int(input("enter the number"))) if a==b: print('Won the game',b) f=1 elif a > b: print(a,'is greater than expected number') c-=1 if(c<2): print("You r left with 1 chances only!!! GET READY TO LOSE THE GAME :)") elif a < b: print(a,'is less than expected number') c-=1 if(c<2): print("You r left with 1 chances only!!! GET READY TO LOSE THE GAME :)") if f==0 : print(' oops!!!! ',n,'! Better luck next time!!!!!!!','\n','You were made fool by Yaswanth','\n','Yaswanth number is',b)
true
b42aadad2f9b3fb70aca707d98668806ccb14061
vanshammishra/pyhton-basics
/fileread.py
627
4.3125
4
trf = open('test.txt') print(trf.read()) # read all the contents of the file print(trf.read(5)) # by passing the arguments inside the read() we can read the number of characters that we have # passed in the read(). # to read one single line at a time use readline() print(trf.readline()) # print line by line by using the readline() line = trf.raedline() while line!="": print(line) line = trf.readline() # readlines() is also a method that is used to read the content of the file but at the same time it also creates the # creates the list and stoores each line in it seperately trf.close()
true
6026e6eda4e9601ecfa3913fd3cea3a4e19be7c7
krisbratvold/fundamentals
/rock_paper_scissors.py
949
4.3125
4
import random comp_wins = 0 wins = 0 while wins != 3 and comp_wins !=3: possible_actions = ["rock", "paper", "scissors"] comp_choice = random.choice(possible_actions) choice = input("rock, paper, or scissors?") if choice == comp_choice: print("You tie!") elif choice == "rock": if comp_choice == "scissors": wins += 1 print("You win!") else: comp_wins += 1 print("You lose!") elif choice == "scissors": if comp_choice == "paper": wins += 1 print("You win!") else: comp_wins += 1 print("You lose!") elif choice == "paper": if comp_choice == "rock": wins += 1 print("You win!") else: comp_wins += 1 print("You lose!") else: if wins == 3: print("Champion!") elif comp_wins == 3: print("Loser!")
true
b4ff4df382bd50548eff61c8e2d12e905dc6c57c
isilnazalan/OYK
/matematik.py
1,215
4.15625
4
# buradaki * tüm kütüphaneyi çeker #from math import sqrt #math kütüphanesinin kullanımına, içindekilere bakmak için math. yapmalıyız #print(math.sqrt(16)) #yarıçapı girilen dairenin çevresini ve alanını bulun #from math import pi import math r =6 alan = (math.pi) * r * r print(alan) cevre = 2*(math.pi) * r print(cevre) def uzaklik(*args): x1,x2,y1,y2 = args # x1 = args[0] # x2 = args[1] # y1 = args[2] # y2 = args[3] uzunluk = math.sqrt((math.pow(x1- x2,2) + math.pow (y1 - y2,2))) print(uzunluk) uzaklik(1,6,14,2) import random def uzaklik2(*args): sonuc = sqrt( (args[2]-args[0])**2) + (args[3] - args[1])**2) ) return sonuc def main(): x1,y1,x2,y2 = random.randint(1,20),\ random.randint(1,20),\ random.randint(1,20),\ random.randint(1,20) sonuc = uzaklik(x1,y1,x2,y2) print(f"({x1},{y1} ile ({x2}, {y2})",\ f"arasındaki uzaklık:{sonuc}") main() """def main(), if __name__ =="__main__": aynı anlama gelir. ancak fonksyonumuzun başka bir projede çalışmamasını istiyorsak sadece kendi projesinde çalışsın istiyorsak if'li koşulu kullanırız.
false
946a91bbbc4e5b37b763dbe5bc39697e6b0e52c9
KeitaForCode/Mypythonproject
/exercise1.py
1,844
4.28125
4
#Time to reveiw all the basics data types we learned! this should be relatively straignt forward and quick reassignment ############################### ########## Problem 1 ########## ############################### # Given a string s = 'django' # use indexing to print out the following print('Answers to problem one') #'d' print(s[0]) #'o' print(s[-1]) #'djan' print(s[:4]) #'jan' print(s[1:4]) #'go' print(s[4:6]) #Bonus: Use indexing to reverse the strings print(s[::-1]) ############################### ########## Problem 2 ########## ############################### #Given this nested list l = [3,7,[1,4,'Hello']] #Reassign 'hello' to be 'goodbye' print('Answers to problem two') l[2][2] = 'goodbye'.capitalize() print(l) ############################### ########## Problem 3 ########## ############################### #Using keys and indexing, grab the 'hello' from the following Dictionaries print('Answers to problem three') d1 = {'simple_key': 'Hello'} print(d1['simple_key']) d2 = {'key1':{'key2':'Hello'}} print(d2['key1']['key2']) d3 = {'key1':[{'nest_key':['This is too deep', ['Hello']]}]} print(d3['key1'][0]["nest_key"][1][0]) ############################### ########## Problem 4 ########## ############################### #Use a set to find a unique value of the list below mylist = [1,1,1,1,1,2,2,2,2,3,3,3,3] print('Answers to problem four') print(set(mylist)) ############################### ########## Problem 5 ########## ############################### #You are given two variables: age = 4 name = 'Sammy' #Use print formating to print the following string: "Hello my Dog's name is Sammy and he is 4 years old" print('Answers to problem five') print("hello my dog's name is", name, 'and he is', age, 'years old') print("hello my dog's name is {a} and he is {b} years old.".format(a = name, b=age))
true
ec3c7fb8517b9da299550b7e4b44325f0e7d41b2
Fidge123/Projects
/Text/palindrome.py
328
4.53125
5
# **Check if Palindrome** - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” user_string = input("Enter a possible palindrome: ") if user_string == user_string[::-1]: print("This is a palindrome.") else: print("This isnt a palindrome.")
true
ddd6a250df8d015dcfbd8889d92ae5be19f9ead4
AndersonUniversity/CPSC4500test
/slee2/lab4_final.py
1,295
4.40625
4
__author__ = 'sLee' ''' Lab3 Samuel Lee Sept/28/2015 This program should: Have a function that takes a number as an argument. If the number is three digits, and the digits are in decreasing order, then the function should perform the magic number calculations and return the result (which should be 1089) as an integer. ''' def magic_n(n): # n is a list contain three int """ calculating magic number """ print("numb valid = ", n) g = str(n) # g list type <list> = <string>.split() # g should store each string type number in list separately [] a = g[0] c = g[2] fd = str(99*(int(a)-int(c))) rfd = ''.join(reversed(fd)) result = int(fd) + int(rfd) # print(fd, rfd, diff) # rdiff = ''.join(reversed(str(diff))) # result = diff + int(rdiff) return result def check_valid(n): """ Check if parameter is valid for magic num fuction. Descending order, 3 integers etc. """ # print("testing numb = ", n) if len(str(n)) != 3: print("not valid length") return False g = str(n) a, b, c = g if int(a) <= int(b): # print("first int is less than second int") return False if int(b) <= int(c): # print("second int is less than third int") return False return True
true
22d2464334e7ad261a8ac5afc1f33b733a231a94
ssyelenik/di_exercise
/week_7/day_2/ex_xp2.py/ex_xp2.py
2,514
4.375
4
from datetime import date def fix_missing(birth_date): while len(birth_date)<3: print("Invalid birth date.") birth_date=input_date() return birth_date def input_date(): raw_date=input("Enter your birth date in the format yyyy/mm/dd: ") birth_date=raw_date.split("/") birth_date=fix_missing(birth_date) return birth_date def fix_non_digits(birth_date): print(birth_date[0],birth_date[1],birth_date[2]) try: for index,item in enumerate(birth_date): birth_date[index]=int(birth_date[index]) return birth_date except: print("Invalid birth date. Please reenter.") birth_date=input_date() fix_non_digits(birth_date) return(birth_date) def ask_for_date(): birth_date=input_date() print(birth_date[0],birth_date[1],birth_date[2]) birth_date=fix_non_digits(birth_date) while birth_date[0]>2020 or birth_date[0]<1900: print("Invalid year. Enter your birthdate with a reasonable birth year") birth_date=input_date() birth_date=fix_non_digits(birth_date) while birth_date[1]>12 or birth_date[1]<1: print("Invalid month. Enter a birthdate with a reasonable birth month") birth_date=input_date() birth_date=fix_non_digits(birth_date) while birth_date[2]>31 or birth_date[2]<1: print("Invalid day. Enter your birth date with a reasonable birth day") birth_date=input_date() birth_date=fix_non_digits(birth_date) print(birth_date) return(birth_date) def get_age(born): today = date.today() print(today) extra_year = 1 if ((today.month, today.day) < (born[1], born[2])) else 0 return today.year - born[0] - extra_year def can_retire(age,gender): if gender=="m": if age>=67: print("Congratulations! You can retire!") else: print("Sorry! You can't retire yet!") elif gender=="f": if age>=62: print("Congratulations! You can retire!") else: print("Sorry! You can't retire yet!") gender=input("Enter your gender: (m or f) ") gender.islower() while not (gender=="m" or gender=="f"): gender=input("Invalid entry. Enter your gender: (m or f) ") birth_date=ask_for_date() print("in main",birth_date) age=get_age(birth_date) print("Your birth date is",birth_date,"and you are", age,"years old.") can_retire(age,gender)
false
0edc8a1900147bea0cd98100772a371f1101bf42
mahinanwar/Programming-for-Everybody-Getting-Started-with-Python-
/Week 4/Assignment_2.3.py
498
4.21875
4
#Write a program to prompt the user for hours and rate per hour using input #to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the #program (the pay should be 96.25). You should use input to read a string and #float() to convert the string to a number. Do not worry about error checking #or bad user data. hrs = input("Enter Hours:") new_hrs=float(hrs) rph = input('Enter the Rate Per Hour:') new_rph=float(rph) gross_pay=new_hrs * new_rph print('Pay:',gross_pay)
true
56e4c3037321625d2ed1daeeda5dca7db001fe94
fernandaassi/minicurso-python
/minicurso-Python/aula-1/ex-9.py
1,211
4.3125
4
''' ***** Exercício 9 ***** Refaça o exercício anterior, porém para quaisquer valores de capacitores. ''' # Neste caso precisamos pegar o valor do teclado. # Para isso usamos a função input(). # Porém é necessário transformar os valores em float, já que a função input() # por definição lê os valores no formato de string # A mensagem para o usuário fica dentro dos parênteses do input() # Pegaremos os valores para o capacitor 1, 2 e 3 (c1, c2 e c3 respectivamente) c1 = float(input("Informe o valor do capacitor 1: ")) c2 = float(input("Informe o valor do capacitor 2: ")) c3 = float(input("Informe o valor do capacitor 3: ")) # Valor da capacitancia em paralelo (fórmula dada pela questão) cp = c1 + c2 + c3 # Valor da capacitancia em serie (fórmula dada pela questão) cs = 1 / (1/c1 + 1/c2 + 1/c3) # Vamos mostrar o resultado do exercício na tela. # Neste caso usaremos dois print(): Um pra capacitancia em paralelo e outro para a # capacitancia em serie # O que esta entre "" é o texto que vamos mostrar e as {} é substituída pelo o que # está no parenteses de .format() print("Valor resultante em paralelo: {}".format(cp)) print("Valor resultante em serie: {}".format(cs))
false
b68de1811c17ce01516cd5c3da398807eec48837
fernandaassi/minicurso-python
/minicurso-Python/aula-1/ex-11.py
1,120
4.375
4
''' ***** Exercício 11 ***** Leia o nome do aluno, e a nota das três provas dele. Em seguida, calcule sua média (média aritmética simples) ''' # Para ler um nome do teclado vamos usar a função input() e guardar o resultado # na variável "nome_aluno" # A mensagem para o usuário fica dentro dos parênteses do input() nome_aluno = input("Informe o nome do aluno: ") # Também vamos usar a função input() para ler as 3 notas do aluno, porém é # necessário transformar os valores em float, já que a função input() # por definição lê os valores no formato de string nota1 = float(input("Informe a nota da primeira prova do aluno: ")) nota2 = float(input("Informe a nota da segunda prova do aluno: ")) nota3 = float(input("Informe a nota da terceira prova do aluno: ")) # media: media do aluno das 3 provas (media aritmética simples) media = (nota1 + nota2 + nota3) / 3 # Vamos mostrar o resultado do exercício na tela. # O que esta entre "" é o texto que vamos mostrar e as {} é substituída pelo o que # está no parenteses de .format(). print("A média de {} é {}".format(nome_aluno, media))
false
e54ac96798d2fe95d0011d110fabbd44c8ad2e0d
ypopova01/Python-Progress
/HW 6 - get string from user.py
985
4.5
4
def get_string_from_user(msg): """ Summary: Asks the user to enter a string and - if any error occurs => print: "***Oops, something went wrong! Try again!" and ask again Returns the user input, as string, when no errors occurred. Usage: user_input = get_string_from_user("enter a user name: ") Arguments: msg {[string]} -- [the string to be displayed to the user,] Returns: [string] -- [the string entered from user] """ try: string=input(msg) except EOFError: string = input("***Oops, something went wrong! Try again: ") except KeyboardInterrupt: string = input("***Oops, something went wrong! Try again: ") return string username = get_string_from_user("Please enter a username: ") user_location = get_string_from_user("Where are you from? ") print("Hello, {}. How is the weather in {}?".format(username, user_location))
true
44ed5a0e365d876683f9da8725e16fce51d1cd80
anubhavsrivastava10/WORK
/decorator_types.py
1,634
4.15625
4
# basic rule # 1. It need to take function as a Parameter # 2. Add functionality to the function # 3. function need to return another function # function without parameter def str_upper(func): def inner(): str1 = func() return str1.upper() return inner @str_upper def print_str(): return "Do it" print(print_str()) # function with parameter def div_decorate(func): def inner(a,b): if b==0: return 'NOT Possible' return func(a,b) return inner @div_decorate def div(a,b): return a/b print(div(4,1)) print(div(4,0)) # multiple decorator in single function def str_upper(func): def inner(): str1 = func() return str1.upper() return inner def split_d(func): def wrapper(): str2 = func() return str2.split() return wrapper @split_d @str_upper def ordinary(): return 'good morning' print(ordinary()) # Decorator contains parameter def outer(expre): def upper_d(func): def inner(): return func() + expre return inner return upper_d @outer(input()) def ordinary(): return 'hello ' print(ordinary()) # single decorator on multiple function def div_decorate(func): def inner(*args): list1 = args[1:] for i in list1: if i==0: return 'NOT POSSIBLE' return func(*args) return inner @div_decorate def div1(a,b): return a/b @div_decorate def div2(a,b,c): return a/b/c print(div1(10,5)) print(div2(1,2,3))
true
f571054c6db1d0972e2d3f284d271d07f1c52048
Jonathan143169/cp1404_practicals
/Prac04/quick_picks.py
604
4.15625
4
import random NUMBERS_PER_LINE = 6 MINIMUM = 1 MAXIMUM = 45 def main(): random_picks = int(input("How many quick picks? ")) for picks in range(1, random_picks + 1): number_list = [] for number in range(NUMBERS_PER_LINE): selected_number = random.randint(MINIMUM, MAXIMUM) while selected_number in number_list: selected_number = random.randint(MINIMUM, MAXIMUM) number_list.append(selected_number) number_list.sort() print(" ".join("{:2}".format(selected_number) for selected_number in number_list)) main()
true
5a9b2bd5e75919c8ca8a6a8049510cb7be75c0dd
matsumon/Merge-Sort-and-Insertion-Sort-Programs
/mergeSort.py
2,215
4.15625
4
import time # function: recursiveFunction # purpose: sort a given array of numbers # description: Sorts by splitting an array in half until it hits the base case of 1 element # Afterwards the elements are sorted by adding the highest of the left and right array. def recursiveFunction(array): middle = len(array)//2 if (middle == 0): return(array) else: left = array[int(middle):] right = array[:int(middle)] left = recursiveFunction(left) right = recursiveFunction(right) i = 0 j = 0 combined= [] while((len(array)) != (i+j)): # no more elements in the left array so the right array is concatenated onto the return array if(i==len(left)): combined= combined + right[j:] break # no more elements in the right array so the left array is concatenated onto the return array elif(j==len(right)): combined= combined + left[i:] break # checks elements and if the left is larger than the right the left element is returned if (left[i] > right[j]): combined.append(left[i]) i= i +1 # checks elements and if the right is larger than the left the right element is returned elif(right[j] >= left[i]): combined.append(right[j]) j= j +1 return combined # open input file file = open("data.txt","r") # open output file outputFile= open("merge.out","a") for line in file: # get rid of newline and then make a string into an array line = line.replace("\n", "") intArray = line.split(" ") # get rid of first element intArray.pop(0) # I got this from Stack Overflow, but it turns an array of strings into an array of ints # It does this by going through each element in the array and running the int function on it # Another possible solution would be to use map, but many sources told me it was deprecated intArray = [int(i) for i in intArray] end = len(intArray) start = time.time(); array = recursiveFunction(intArray) endTime = time.time(); print("n:", end, "time:",endTime - start) # make array back into a string and get rid of the brackets and commas string = str(array) string = string.strip("[]") string = string.replace(",","") string = string + "\n" # write results into output file. outputFile.write(string)
true
ea6b1eb667929235bdcc337c90ccd3f49438fc59
Zachary-Jackson/Secret-Messages
/ciphers/caesar.py
1,533
4.15625
4
import string from .cipher import Cipher class Caesar(Cipher): FORWARD = string.ascii_uppercase * 3 def __init__(self, offset=3): """This method initializes Caesar with an encryption alphabet""" self.offset = offset self.FORWARD = string.ascii_uppercase + string.ascii_uppercase[:self.offset+1] self.BACKWARD = string.ascii_uppercase[:self.offset+1] + string.ascii_uppercase def encryption(self, text, *args, **kwargs): """ Uses a given text message and encrypts it using the caesar cipher :param text: The message to be encrypted :return: The encrypted message """ output = [] text = text.upper() for char in text: try: index = self.FORWARD.index(char) except ValueError: output.append(char) else: output.append(self.FORWARD[index+self.offset]) return ''.join(output) def decryption(self, text, *args, **kwargs): """ Uses a given text message and decrypts it using the caesar cipher :param text: The message to be decrypted :return: The decrypted message """ output = [] text = text.upper() for char in text: try: index = self.BACKWARD.index(char) except ValueError: output.append(char) else: output.append(self.BACKWARD[index-self.offset]) return ''.join(output)
true
a8c2ee0d895e03531ea4f26623faefd2eb9d9473
senansalawe/Test
/python/6-for-loop.py
527
4.53125
5
subjects = ['arab', 'eng', 'math'] # this is array print (subjects) # print for array #===================== print (subjects[2]) # select obj from array #===================== subjects.append ('kame') # add new obj to array print (subjects) #===================== print (subjects [1:3]) # view obj in the array between 1 to 3 #===================== #print (subjects[-1]) # view last obj #===================== # subjects.pop (1) # delete obj in array # print(subjects) #===================== for x in subjects: print (x)
true
37736d427da8cb59cd4fe47237bcca5441d16c1d
Sidney-kang/Unit3-04
/leap_year.py
816
4.1875
4
# Created by : Sidney Kang # Created on : 13 Oct. 2017 # Created for : ICS3UR # Daily Assignment - Unit3-04 # This program determines whether a given year is a leap year import ui def check_leap_year_touch_up_inside(sender): # This checks whether the inputed year is a leap year # input year_entered = int(view['user_input_textbox'].text) # process if year_entered % 4 != 0: # output view['check_if_leap_year_label'].text = "It is not a leap year." elif year_entered % 4 == 0 and year_entered % 100 != 0: # output view['check_if_leap_year_label'].text = "It is a leap year." elif year_entered % 4 == 0 and year_entered % 100 == 0: # output view['check_if_leap_year_label'].text = "It is a leap year." view = ui.load_view() view.present('sheet')
true
8a421aeae2da991962ce44a785959be8d8eb17fe
grappaarpit/Student_Grader
/main.py
965
4.34375
4
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 #TODO-1: Create an empty dictionary called student_grades. #> Scores 91 - 100: Grade = "Outstanding" #> Scores 81 - 90: Grade = "Exceeds Expectations" #> Scores 71 - 80: Grade = "Acceptable" #> Scores 70 or lower: Grade = "Fail" student_grades = {} #TODO-2: Write your code below to add the grades to student_grades.👇 for students in student_scores: if student_scores[students]>=91: student_grades[students] = "Outstanding" elif student_scores[students]>=81: student_grades[students] = "Exceeds Expectations" elif student_scores[students]>=71: student_grades[students] = "Acceptable" elif student_scores[students]<=70: student_grades[students] = "Fail" #student_grades[students] = 23 print(student_grades) # 🚨 Don't change the code below 👇 #print(student_grades)
true
3fc5fea7069c1876bde930acd6132ce44998e6dc
SebastianoFazzino/Python3-Programming-by-University-of-Michigan
/Python Classes and Inheritance/Sorting_Lists_of_Istances.py
1,048
4.40625
4
#given a list of istances, we may want to sort them by some index class Fruit(): def __init__(self, name, price): self.name = name self.price = price def sort_priority(self): return self.price FruitList = [ Fruit('Cherry', 10), Fruit('Apple', 5), Fruit('Blueberry', 20) ] #now, the sort the fruit by price, we call the method sorted, #and as key of the method we pass 'sort_priority' function defined in the class for fruit in sorted(FruitList, key = Fruit.sort_priority): print(fruit.name, fruit.price) #we can also use a lambda expression as follows: for fruit in sorted(FruitList, key = lambda fruit: fruit.sort_priority()): print(fruit.name, fruit.price) #more examples: #let's say we want to sort the fruits in FruitListst by word length, from the longest to the shortest: for fruit in sorted(FruitList, key = lambda fruit: len(fruit.name), reverse = True): print(fruit.name)
true
c79be9af8bc2fc28968097037674c0f9ce50c16d
SebastianoFazzino/Python3-Programming-by-University-of-Michigan
/Python Functions, Files and Dictionaries/Optional_parameters.py
1,296
4.34375
4
#Optional parameters def Funct(a, List =[]): List.append(a) return List print(Funct(3)) print(Funct(4)) print(Funct(11)) print(Funct(5, ['Hello'])) #Keyword parameters initial = 7 def f(x,y=3,z=initial): print("x, y, z, are: " + str(x),',', str(y),',', str(z)) f(2,6,8) f(2,z=11) f(x=1,y=(1+initial),z=2) #if we change the value of 'initial' after the function has been invoked, z value won't change: initial = 7 def f(x, y = 3, z = initial): print ("x, y, z are:", x, y, z) initial = 0 #in this case changing this parameter value won't have any effect of the function's parameters f(2) #but if we pass 'initial' as a function's parameter, the parameter's value will change accordingly: f(x=1,y=(1+initial),z=2) #keyword parameters with .format names_scores = [("Jack",[67,89,91]),("Emily",[72,95,42]),("Taylor",[83,92,86])] for name, scores in names_scores: print("The scores {nm} got were: {s1},{s2},{s3}.".format(nm=name,s1=scores[0],s2=scores[1],s3=scores[2])) #We can use the .format method to insert the same value into a string multiple times. names = ["Jack","Jill","Mary"] for n in names: print("'{}!' she yelled. '{}! {}, {}!'".format(n,n,n,"say hello"))
true
8b38601a3815ab29351161b0db69055d052034b7
SebastianoFazzino/Python3-Programming-by-University-of-Michigan
/Data Collection and Processing/Zip_Function.py
1,738
4.71875
5
#The zip function takes multiple lists and turns them into a list of tuples (actually, an iterator, but they work like lists for most practical purposes), #pairing up all the first items as one tuple, all the second items as a tuple, and so on. #Then we can iterate through those tuples, and perform some operation on all the first items, all the second items, and so on. l1 = [3, 4, 5] l2 = [1, 2, 3] l3 =[] #in the code below we add the value of l1[i] to l2[i] using a for loop and append method for i in range(len(l1)): l3.append(l1[i] + l2[i]) print('Using for loop:',l3) #we can zip the two lists together using zip function l3 = list(zip(l1,l2)) #and the output will be a list of tuples print('Using zip function:',l3) #once we've created this zip-together list, we can combine the numbers in the tuples as follow: l4 = [] for num1, num2 in l3: l4.append(num1 + num2) #or, more simply, we could use a list comprehension l5 = [num1 + num2 for (num1, num2) in list(zip(l1, l2))] print('Using list comprehension:',l5) #we can also use map function to execute the same operation: l6 = map(lambda num: num[0] + num[1], zip(l1,l2)) print('Using map function:',list(l6)) print("*************************************") #Exercise: #Below we have provided two lists of numbers, L1 and L2. Using zip and list comprehension, create a new list, L3, #that sums the two numbers if the number from L1 is greater than 10 and the number from L2 is less than 5. This can be accomplished in one line of code. L1 = [1, 5, 2, 16, 32, 3, 54, 8, 100] L2 = [1, 3, 10, 2, 42, 2, 3, 4, 3] L3 = [ (l1+l2) for (l1,l2) in list(zip(L1,L2)) if (l1>10 and l2<5) ] print(L3)
true
b4e2fa8d8ef1b0ee9a9a106a0355f4459e327356
SebastianoFazzino/Python3-Programming-by-University-of-Michigan
/Python Classes and Inheritance/More_Classes_Methods.py
2,117
4.3125
4
#Given the class Point: class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def __str__(self): return "Point ({}, {})".format(self.x, self.y) #let's say that we want to add the value of x or y in p1 to p2, to be able to do so, #we need to create another method in the class: def __add__(self, otherPoint): return(self.x + otherPoint.x, self.y + otherPoint.y) #we can create more method, like substraction: def __sub__(self, otherPoint): return(self.x - otherPoint.x, self.y - otherPoint.y) p1 = Point(15, 3) p2 = Point(-3, 6) #now, given p1 and p2, we can print the sum of their values: print(p1 + p2) #or the substraction: print(p2 - p1) #Methods can return any kind of value as their return value, #but it's good to specify that they can also return other istances. #Given the class Point: class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def getX(self): return self.x def getY(self): return self.y def __str__(self): return "Point ({}, {})".format(self.x, self.y) def __add__(self, otherPoint): return(self.x + otherPoint.x, self.y + otherPoint.y) def __sub__(self, otherPoint): return(self.x - otherPoint.x, self.y - otherPoint.y) #let's say we want the class to accept two points and return a new point #that is halfway between the two. We can proceed as follows: def halfway(self, target): midX = (self.x + target.x) / 2 midY = (self.y + target.y) / 2 return Point(midX, midY) #now, given p1 and p2, we want to return a halfway point that we can call p3: p1 = Point(15, 3) p2 = Point(-3, 6) p3 = p1.halfway(p2) print(p3) #now p3 is a new istance of Point class, so we can do: print(p3.getX()) print(p3.getY())
true
0a99117d4b8d4c828253c4a96a660a88db441da0
nadezhda-python/lesson1_fix
/price.py
1,809
4.15625
4
""" price = 100 discout = 5 price_with_discount = price - price * discout / 100 print (price_with_discount) def discounter(price, discout): if price > 0 and discout > 0 and discout < 100: print (price - price * discout / 100) discounter(100, 2) """ """ Создайте функцию get_summ(one, two, delimiter='&'), которая принимает два параметра, приводит их к строке и отдает объединенными через разделитель delimiter Вызовите функцию, передав в нее два аргумента "Learn" и "python", положите результат в переменную и выведите ее значение на экран Сделайте так, чтобы результирующая строка выводилась заглавными буквами def get_summ(one, two, delimiter='&'): return str(one) + str(delimiter) + str(two) res = get_summ('Learn', 'python') print (res.upper()) """ """Создайте в редакторе файл price.py Создайте функцию format_price, которая принимает один аргумент price Приведите price к целому числу (тип int) Верните строку "Цена: ЧИСЛО руб." Вызовите функцию, передав на вход 56.24 и положите результат в переменную Выведите значение переменной с результатом на экран""" def format_price(price): try: int_price = str(int(price)) except: return None return f'Цена: {int_price} руб.' current_price = format_price('56.24') print(current_price)
false
80e765208deaada4cea7d7bc06bc69c5c67b1f47
aravinthakshan/Guess-the-number
/guess-the-number.py
1,544
4.21875
4
#Importing random module import random #Randomly picking a number num = random.randint(1,100) #Welcome Messages print("Welcome to The Guessing Game") print("I am currently thinking of a number between 1 and 100") print("You are COLD if you are more than 10 away from the number I am thinking of") print("You are WARM if you are within 10 from the number I am thinking of") print("You are COLDER, If you guess farther away from your most recent guess ") print("You are WARMER, If you guess closer to your most recent guess") print("Let's Start") #List to keep track of guesses guess = [0] while True: user_input = int(input("I am thinking of a number between 1 and 100, Enter your guess: ")) #When user enters a number greater than 100 or less than 1 if user_input > 100 or user_input < 1: print("Out of Bounds, Try again") continue #When user guesses correctly if user_input == num: print(f"Congratulations, You have guessed correctly in only {len(guess)} guesses") break guess.append(user_input) # when testing the first guess, guesses[-2]==0, which evaluates to False #And directly moves down to the else condition if guess[-2]: if abs(num - user_input) < abs(num - guess[-2]): print('Warmer') else: print("Colder") #Checks if number is within 10 of num else: if abs(num - user_input) <=10 : print("Warm") elif abs(num - user_input) > 10: print('Cold')
true
eea7f7ea9e3613910f30ca705368c97f3b32ebe1
tshoaitrung/BasicPython
/2_Statement_if_for_while/odd_or_even_len.py
765
4.53125
5
#2. Print out the words if the length of word is even, print out the reverse of words if the length of word is odd ### ODD NUMBER x%2 == 1 vs EVEN NUMBER x%2 == 0 print("Print out the words if the length of word is even, print out the reverse of words if the length of word is odd\n") IP_Str = input("Insert the String you want: ") Proc_Str = IP_Str.split() count_EV = 0 count_OD = 0 for words in Proc_Str : if len(words)%2 == 0 : count_EV += 1 print('The length of {} is even'.format(words)) else: count_OD += 1 print('\tThe length of {} is odd and the reverse is {}.'.format(words,words[::-1])) print('\nTOTAL WORDS IN YOUR STRING HAVE EVEN LENGTH IS {}. '.format(count_EV)) print('TOTAL WORDS IN YOUR STRING HAVE ODD LENGTH IS {}.'.format(count_OD))
true
c271112b2256bd2183f6f177dd95be35cdf68b6d
tshoaitrung/BasicPython
/5_OOP_class/LINE.py
1,707
4.4375
4
### Line class methods to accept corrfinates as a pair of tuples and return the slope and distance of the line import math # to use square root class Line(): def __init__(self,x1 = 0,y1 = 0,x2 = 1,y2 = 1): #LINE (x1,y1) (x2,y2) self.point1 = (x1,y1) #the horizontal self.point2 = (x2,y2) #the vertical def distance(self): return math.sqrt((self.point2[0]-self.point1[0])*(self.point2[0]-self.point1[0]) + (self.point2[1]-self.point1[1])*(self.point2[0]-self.point1[0])) def slope(self): return abs((self.point2[1]-self.point1[1])/(self.point2[0]-self.point1[0])) def print_line(self): print('This line inludes two point: start point is ({},{}) and end point is ({},{})'.format(self.point1[0],self.point1[1],self.point2[0],self.point2[1])) ##################MAIN############################ x1 = y1 = x2 = y2 = 'WRONG' while x1.isdigit() == False: x1 = input('Insert the value of point 1 - Horizontal: ') if x1.isdigit() == True: while y1.isdigit() == False: y1 = input ('Insert the value of point 1 - Vertical: ') if y1.isdigit() == True: while x2.isdigit() == False: x2 = input('Insert the value of point 2 - Horizontal: ') if x2.isdigit() == True: while y2.isdigit() == False: y2 = input ('Insert the value of point 2 - Vertical: ') example_line = Line(int(x1),int(y1),int(x2),int(y2)) example_line.print_line() print('The length of your line is {}'.format(example_line.distance())) print('The slope of your line is {}'.format(example_line.slope()))
true
41e611d6e96a679e2e47151d3283d3e216844679
abu-samRah/Data-Structures-Python
/binarySearch.py
980
4.1875
4
def binary_search_recursive(numbers_list, number_to_find, left_index, right_index, indexs=[]): if right_index < left_index: return -1 med_index = (left_index + right_index)//2 if med_index >= len(numbers_list) or med_index < 0: return -1 med_element = numbers_list[med_index] if number_to_find < med_element: right_index = med_index -1 elif number_to_find > med_element: left_index = med_index + 1 else: numbers_list.pop(med_index) left_index = 0 right_index = len(numbers_list) -1 indexs.append(med_index) binary_search_recursive(numbers_list, number_to_find, left_index, right_index,indexs) return indexs if __name__ == '__main__': numbers_list = [15, 15,17, 17,19, 21,21] number_to_find = 19 index = binary_search_recursive(numbers_list, number_to_find, 0, len(numbers_list)-1) print(f"Number found at index {index} using binary search")
true
0cb9d34fc7f6406fe0a0d1f6e0a10d150e549681
CauchyPolymer/teaching_python
/python_class/a01_class.py
841
4.15625
4
class Square(): NO_OF_EDGES = 4 def __init__(self, edge): self.edge = edge def area(self): return self.edge * self.edge sq1 = Square(3) sq2 = Square(7) sq3 = Square(11) print(sq1.area()) print(sq2.NO_OF_EDGES) class Circle(): PI = 3.14 def __init__(self,radius): self.radius = radius def area(self): return (self.radius**2) * Circle.PI def circumference(self): return (self.radius*2) * Circle.PI circle1 = Circle(3) circle2 = Circle(9) print(circle1.PI) # .class attr가져오는 걸 attr fetch 라고 함//// #print(circle.radius) 실행 안됨. Circle 위로 올라가서 찾기 때문에. circle1 = Circle(3)로 내려가지 않음 circle1.radius는 가능 print("원의 넓이 = " + str(circle1.area())) print("원의 길이 = " + str(circle1.circumference()))
false
904d2f85aeb9c4f9cca22ca0d2957fa2a18a5ad9
CauchyPolymer/teaching_python
/python_intro/12_if.py
1,285
4.1875
4
#분기 와 반복 #분기 : if문을 bool바꾸었을때 참 이면 실행 됨. expression식:계산하면 값이 나옴// statement문: 명령어 한줄 # expression이 statement에 포함 됨. simple statment다 여러개 섞여 있는게 compound statement. if자체는 cs임. #반복 : if True: x = 1 + 2 print(x) if False: print('cherry') a = 1 b = 2 if a < b: print('mango') if 'hello': print('hello back') if []: print('My list') if 5-5: print('zero') print('-' * 40) my_list = ['coke'] if my_list: print('pepsi') fruit = 'apple' if fruit == 'apple': print('apple please') a = True if a and b: print('a and b') else: print('not(a and b)') c = 10 if c > 5: print('big') elif c > 8: #else if -> if가 거짓일때 print('very big') else: #elif가 거짓 일때. else 마지막에 한번 올 수 있음. print('small') d = 50 if d > 5: #하나의 if statement print('large') if d > 25: #별개의 if compound statement! print('very large') print('thank you') elif d > 25: print('extra large') elif d > 45: print('2x large') else: print('small') print('not interested') e = 200 if e > 0: print('positive') if e > 1000: print('4 digit') else: print('negative')
false
ee47c1fe0b059f100a1417ecc847050209058ad1
Gokulapps/Python
/stack.py
1,277
4.125
4
class Stack: def __init__(self,max_size): self.__max_size=max_size self.__elements=[None]*max_size self.__top=-1 def get_max_size(self): return self.__max_size def is_full(self): if(self.__top==self.__max_size-1): return True return False def push(self,data): if(self.is_full()): print("The Stack is Full") else: self.__top+=1 self.__elements[self.__top]=data def is_empty(self): if(self.__top==-1): return True return False def pop(self): if(self.is_empty()): print("The Stack is Empty") else: data=self.__elements[self.__top] self.__top -= 1 return data def display_stack(self): if(self.is_empty()): print("The Stack is Empty") else: for index in range(self.__top+1): print(self.__elements[index]) stack1=Stack(10) stack1.push("Tom") stack1.push("And") stack1.push("Jerry") stack1.push("Show") stack1.push("Error") stack1.display_stack() print("Poped Element:",stack1.pop()) stack1.display_stack() print("Max Size:",stack1.get_max_size())
true
ee7886cad480aaf3fa87bbc19390fcd62aa79cdd
KulkovIvan/GeekPython
/lesson1-1.py
793
4.21875
4
# 1. Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и # сохраните в переменные, выведите на экран. a = 200 print(a) money = 100 print(money) text = "Hello World!" print(text) name = input("Введите ваше имя - ") surname = input("Введите вашу фамилию - ") print('Здравствуйте,',surname ,name,',приятно познакомиться !') num1 = input("Введите первое число - ") num2 = input('Введите второе число - ') sum = int(num1) + int(num2) print('Сумма чисел будет равна',sum)
false
612e45e051aeec03ef30802ede03f4406b550c82
shoaibrayeen/Python
/File Handling/toUpper.py
1,116
4.28125
4
def toUpper(file_1 , file_2): ''' Objective: To convert the contents of file to upperCase and save it another file Input Parameters: file1 : in which contents are in lowercase. file2 : where we have to save contents after converting in upperCase Return Value: None Side effect: A new file – file2 with upperCase contents is produced ''' #Approach : file handling try: fIn = open(file_1, 'r') fOut = open(file_2,'w') except IOError: print('Problem in opening the file'); sys.exit() line = fIn.readline() while(line != ''): fOut.write(str(line).upper()) line = fIn.readline() fIn.close() fOut.close() def main(): ''' Objective: To convert the contents of file to upperCase and save it another file Input Parameter: None Return Value: None ''' #Approach : toUpper() function import sys sys.path.append('/home/administrator/Desktop/python') file1 = input('Enter file name with lowerCase contents : ') file2 = input('Enter file name for saving upperCase contents : ') toUpper(file1,file2) if __name__=='__main__': main()
true
810936b8294fc9b215c03b86bd9c21b01ffa9260
shoaibrayeen/Python
/Problems/Recursion/hanoiRecursion.py
878
4.15625
4
def hanoi(n, source, spare, target): ''' Objective: To solve problem of Tower of Hanoi using n discs and 3 poles Input parameters: n, source, spare, target : numeric values Return Value: None ''' if n==1: print('Move a disk from', source, 'to', target) elif n == 0: return else: hanoi(n-1, source, target, spare) print('Move a disk from', source, 'to', target) hanoi(n-1, spare, source, target) def main(): ''' Objective: To solve Tower of Hanoi problem based on user input Input Parameter: None Return Value: None ''' n = int(input('Enter the number of discs: ')) source = int(input('Enter source pole: ')) spare = int(input('Enter spare pole: ')) target = int(input('Enter target pole: ')) hanoi(n, source, spare, target) if __name__=='__main__': main()
true
a733fbcf83444f34ed6ccade3dee8f8d980e9d2d
shoaibrayeen/Python
/Problems/Basic Programs/maximum3.py
888
4.4375
4
def max3(n1, n2, n3): ''' Objective: To find maximum of three numbers Input Parameters: n1, n2, n3 - numeric values Return Value: number - numeric value ''' def max2(n1, n2): ''' Objective: To find maximum of two numbers Input Parameters: n1, n2 - numeric values Return Value: maximum of n1, n2 - numeric value ''' if n1 > n2: return n1 else: return n2 return max2(max2(n1, n2), n3) def main(): ''' Objective: To find maximum of three numbers provided as input by user Input Parameter: None Return Value: None ''' n1 = int(input('Enter first number: ')) n2 = int(input('Enter second number: ')) n3 = int(input('Enter third number: ')) maximum = max3(n1, n2, n3) print('Maximum number is', maximum) if __name__=='__main__': main()
true
161e8f56f1da5fff98d3905db7bf1dcef81e9512
mikekrsk/project
/work1.py
637
4.21875
4
# Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. first = 1 second = first + 4 text = "пробный текст" print(first) print(second) print(text) zapros_texta = input("Введите текст: ") number1 = input("Введите первое число: ") number2 = input("Введите второе число: ") print(zapros_texta) print(number1, number2)
false
f3a19b1eaf8615b595e8a1112513887ff06af4b2
Sibinvarghese/PythonPrograms
/Functions/fact of a no.py
344
4.25
4
def fact(num1): fact=1 if(num1<0): print("sorry Factorial For Negative Numbers Does Not Exist ") elif(num1==0): print("The Factorial Of Zero is 1") else: for i in range(1,(num1+1)): fact=fact*i print("The Factorial Of",num1,"is",fact) num2=int(input("enter a number : ")) fact(num2)
true
2103777f38ba7720fbfc7df1db79e2259f33871c
panahiparham/pyLecEF
/exercises/mergeSort.py
648
4.15625
4
#!/usr/bin/python3 -tt # In the examples we saw a merge function # now try to implement merge sort # if you don't know the algorithm, do a google search, # it's also useful to look up, recursive functions. # bonus : try to do the merge step in O(n) time, # so the time complexity of the sort becomes the famous O(n.lgn). # assume data is a list of numbers. def merge_sort(data): # TODO: code goes here return # for the merging process you can create another function def main(): # Be sure to test your code here # call it a few time on different lists, and print the result. # GOOD LUCK pass if __name__ == '__main__': main()
true
ee91b06096f06b2303cca75f1acb60a9c6d60608
si21lvi/tallerlogicadeprogramacion_camilogomez
/28.py
256
4.15625
4
print("programa que determina si un numero es postivo o negativo") a=float(input("ingrese el numero")) if a<0: print("el numero es negativo") if a==0: print("este numero no es negativo ni positivo") if a>0: print("el numero es positivo")
false
9e259c5c32cb29b0bf8f5d50a21c9bf9f4e321bf
efnine/learningPython
/misc_other/quadratic.py
659
4.21875
4
# quadratic.py # A program that computes the real roots of a quadratic equation # The program also illustrates the use of Python's math library # NOTE: The program crashes if the equation has no real roots import math #this command makes the math library(module) available def main(): print("This program finds the real solutions to a quadratic equation") print() a,b,c = eval(input("Please enter the coefficients (a,b,c): ")) discRoot = math.sqrt(b*b-4*a*c) root1 = (-b + discRoot) / (2*a) root2 = (-b - discRoot) / (2*a) print() print("The solutions are: ", root1, root2) main()
true
da24b799eabd296e7e2ef69fc50db0aeaa46fc8d
efnine/learningPython
/uoft_ltp_1/week6_filenotes.py
2,617
4.15625
4
def contains(value, lst): """ (object, list of list) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ found = False for sublist in lst: if value in sublist: found = True return found print(contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])) + def contains(value, lst): """ (object, list of list) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ found = False for i in range(len(lst)): for j in range(len(lst[i])): if lst[i][j] == value: found = True return found print(contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])) #def make_pairs(list1, list2): ''' (list of str, list of int) -> list of [str, int] list Return a new list in which each item is a 2-item list with the string from thecorresponding position of list1 and the int from the corresponding position of list2. Precondition: len(list1) == len(list2) >>> make_pairs(['A', 'B', 'C'], [1, 2, 3]) [['A', 1], ['B', 2], ['C', 3]] ''' #pairs = [] #for i in range(len(list1)): #pairs.append([list1[i], list2[i]]) #return pairs for i in range(len(list1)): inner_list = [] inner_list.append(list1[i]) inner_list.append(list2[i]) pairs.append(inner_list) make_pairs(['A', 'B', 'C'], [1, 2, 3]) """" def shift_right(L): last_item = L[-1] for i in range(1, len(L)): L[len(L) - i] = L[len(L) - i - 1] L[0] = last_item mylist = ["A","B","C","D"] shift_right(mylist) print(mylist) """ """ def mystery(s): matches = 0 for i in range(len(s) // 2): if s[i] == s[len(s) - 1 - i]: matches = matches + 1 return matches == (len(s) // 2) """ """ def mystery(s): matches = 0 for i in range(len(s) // 2): if s[i] == s[len(s) - 1 - i]: # <--- How many times is this line reached? matches = matches + 1 return matches == (len(s) // 2) mystery('civil') """ """ def merge(L): merged = [] for i in range(0, len(L), 3): merged.append(L[i] + L[i + 1] + L[i + 2]) return merged print(merge([1, 2, 3, 4, 5, 6, 7, 8, 9])) """
true
657aa536a259cd552db51f98759c6a05603ccbbc
ceik/udacity
/ipnd/stage_4/dictionaries.py
1,144
4.4375
4
# Lesson 4.4: Dictionaries # Dictionaries are another crucial data structure to learn in Python in addition to lists. # These data structures use string keywords to access data rather than an index number in lists. # Using string keywords gives programmers more flexibility and ease of development to use a # string keyword to access an element in this data structure. # https://www.udacity.com/course/viewer#!/c-nd000/l-4181088694/m-3919578552 # Strings vs List vs Dictionary Demo s = "hello" p = ["alpha",23] d = {"hydrogen": 1, "helium": 2} # Replacing values # s[2] = "a" # Will produce error, comment this line to continue with rest of code execution p[1] = 999 d["hydrogen"] = 49 d['lithium'] = 3 d['nitrogen'] = 8 d['nitrogen'] = 7 # Accessing items print s[2] print p[1] print d["hydrogen"] print d population = {'Shanghai':17.8, 'Istanbul': 13.3, 'Karachi': 13.0, 'Mumbai': 12.5} elements = {} elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794} elements['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True} print elements['H'] print elements['He'] print elements['He']['weight']
true
dcbbdaa286195a2352357f2f0cba7d570cd367de
wolfwithbow/calc
/calc1.py
1,053
4.28125
4
print("This is my first calculator app, built from scratch!") #function calculateNumbers def calculateNumbers(self, operation, number_one, number_two): print("Enter number one: ") number_one = input("Enter first number: ") print("Enter desired operation: ") operation = input("Enter operation: ") print("Enter number two: ") number_two = input("Enter second number: ") x = number_one y = number_two op = operation # for each element in array if op == "-": result = x - y print(result) elif op == "-": result = x + y print(result) elif op == "*": result = x * y print(result) elif op == "/": result = (x / y) print(result); # check what calculation symbol they select # if symbol is add # add number1 and number2 # if symbole is minus # minus numbers # if symbol is divide # divide numbers # if symbol if multiply # multiply numbers # return result
true
ae249d96432a06bdc5febd360173982130db6037
michealbradymahoney/CP1404-2019SP2
/Practicals/prac_05/word_occurrences.py
369
4.15625
4
words_dict = {} user_input = input("Text: ") words = user_input.split() for string in words: occurrences = words_dict.get(string, 0) words_dict[string] = occurrences + 1 words = list(words_dict.keys()) words.sort() max_length = max((len(string) for string in words)) for string in words: print("{:{}} : {}".format(string, max_length, words_dict[string]))
true
30302db836c75d1f333c3bf6563feac843c0efdc
robert11156/Random-Guessing-Number-Project
/Guessing Number Project.py
711
4.34375
4
# The computer picks a random number between 1 and 100 # the player know if the guess is too high, too low # or guess the number correctly import random the_number = random.randint(1, 100) name = input("Enter your name: ") print("Hi," ,name, " I am thinking of a number between 1 and 100. Guess the number") #guessestaken print("Welcome to my Guessing Game.") tries = 0 # guessing loop while tries <6: guess = int(input("Guess the number: ")) tries = tries+1 if guess > the_number: print("The number is too large") elif guess < the_number: print("The number is too small") if guess == the_number: print("You have guess the correct number, Congrats")
true
bfa9f94289b903d70752aaebb876db962fb680ad
IANHUANGGG/Santonrini
/santorini/design/iboard.py
2,562
4.40625
4
"""Interface for the Santorini board.""" from abc import ABC, abstractmethod """ Datatypes: A Worker is represented by a class and contains which player it belongs to. A Building is represented by a class and contains the number of floor it contains. A Position is represented by a tuple (int, int) which represents a location on the board. """ class AbstractBoard(ABC): """Abstsract Board for Santorini.""" def __init__(self): """Create a 6x6 board. with 0-floor buildings in each cell. _board is a 2-d array of Buildings representing the Santorini board, _workers is a dictionary of Workers -> Position which represents their positions on the board. """ self._board = [[]] self._workers = {} @property def workers(self): """Return the workers. :rtype dict: the dictionary mapping Workers -> Position """ return self._workers @abstractmethod def place_worker(self, worker, pos): """Place a worker in a starting position on the board. If position is invalid or out of bounds, raise an exception :param Worker worker: a Worker on the board :param Position: a (x, y) position on the board :type Position: (int, int) :rtype Position: the new position of the worker """ pass @abstractmethod def move_worker(self, worker, direction): """Move a worker to a new position on the board. move_worker moves the given worker to the given position. a Worker *must* be placed before it can move This does not check if a worker can move there. If position is invalid or out of bounds, raise an exception. :param Worker worker: a Worker on the board :param Position: a (x, y) position on the board :type Position: (int, int) :rtype Position: the new position of the worker """ pass @abstractmethod def build_floor(self, worker, direction): """Build one floor of a building at a position. build_floor adds a single floor to the given position. All valid positions on the board are buildings, starting at 0 floors. Increments the Building's floor counter by one Building on a position that already has 4 floors does nothing. :param Position: a (x, y) position on the board that does not contain a worker :type Position: (int, int) :rtype int: the new floor count """ pass
true
a73248c325c631660d68ccc7530b4d8dba47cced
dairantzis/BBK_Introduction-to-Computer-Systems_2021
/Optional Python exercises/Optional32-If-else-Minimum-of-two-numbers-dairantzis.py
211
4.1875
4
# # Given the two integers, print the least of them. # numberA = int(input('Please enter a number:')) numberB = int(input('Please enter another number:')) print('The smaller number is:',min(numberA,numberB))
true
97a5209c1606ebaa7f85dd0b9c8b8a54ca39e5ad
dairantzis/BBK_Introduction-to-Computer-Systems_2021
/Week 02/Week 2_Exercise 2.1_While loop prints all even numbers.py
891
4.53125
5
# Example of while loop # The user is asked to input an upper and a lower limit # and the programme then prints the even numbers between them # No input error checking is done lowerLimit = int(input('Please, enter the lower limit integer:')) upperLimit = int(input('Please, enter the upper limit integer:')) print('The even numbers between', lowerLimit, 'and' ,upperLimit, 'are:') number = lowerLimit # the loop control variable is initialised to the lower limit while(number < upperLimit): # the loop will be repeated while number remains < upperLimit if number%2 == 0: # modulo 2 is used to test whether the current number is odd/even print(number,' ',end = '') # if the number is even, then it is printed number = number + 1 # number, the loop control variable, is increased by one, ready for the next iteration
true
573bc539690c52f9fa4da00f350bdca16f31a9a1
dairantzis/BBK_Introduction-to-Computer-Systems_2021
/Week 02/Week 2_Exercise 2.2_While loop prints all factors of a number.py
1,050
4.5
4
# Programme to calculate and print the factors of an integer number provided by the user # The factors of a number are numbers which, when multiplied together, result to the number. # In other words, the factors are the divisors of the number. # # Since the factors divide the number, the remainder of their division of the number is 0. # The modulo function is used to find them. # number = int(input('Please, enter a positive integer:')) n = 1 # n will be the control variable of the loop print('The factors of ',number,' are: ',sep = '', end = '') while n < number: # repeat the loop while n < number (a number is divisible by itself) if number % n == 0: # if number modulo n is zero, then n divides the number print(n,',',sep = '',end = '') # print the number n = n + 1 # increase the number by one and repeat the loop print(n) # print the number itself as a number is divisible by itself
true
583ecf1c0d7ec4f26ab750ec5e72732471f8c280
dairantzis/BBK_Introduction-to-Computer-Systems_2021
/Optional Python exercises/Optional29-Numbers-Total-cost.py
702
4.3125
4
# # A cupcake costs A dollars and B cents. Determine, how many # dollars and cents should one pay for N cupcakes. A program # gets three numbers: A, B, N. It should print two numbers: # total cost in dollars and cents. # dollarsCost = int(input('What is the dollar cost of a cupcake?')) centsCost = int(input('What is the cents cost of a cupcake?')) numberOfCupcakes = int(input('How many cupcakes do you want to buy?')) # calculate the total cost in cents totalCostInCents = numberOfCupcakes * (dollarsCost * 100 + centsCost) # print the result in dollars and cents by using division and modulo print('Total cost is:',totalCostInCents // 100,'dollars and',totalCostInCents % 100,'cents.')
true
07f9199823d5dd7d7214547eea5b1b62659044a0
dairantzis/BBK_Introduction-to-Computer-Systems_2021
/Optional Python exercises/Optional3K-If-else-Next-day.py
840
4.6875
5
# # Given a month (an integer from 1 to 12) and a day in it # (an integer from 1 to 31) in the year 2017, print the # month and the day of the next day to it. # # 2017 was not a leap year, February had 28 days. Set up a dictionary to hold the number of days per month daysOfMonth = {1 : 31,2 : 28,3 : 31,4 : 30,5 : 31,6 : 30,7 : 31,8 : 31, 9: 30, 10 : 31, 11 : 30, 12 : 31} month = int(input('Please enter the month as an integer number:')) day = int(input('Please enter the day of the month as an integer number:')) daysOfTheMonth = daysOfMonth[month] if day < daysOfTheMonth: newDay = day + 1 else: newDay = 1 newMonth = month + 1 if newMonth > 12: newMonth = 1 print('The day that follows the',day,'th day of the',month,'th month,',end=' ') print('is: the',newDay,'th day of the',newMonth,'th month.')
true
0d690ca7cb80f67850d1c44e1be87d8231ef0528
sinobi0/HomeWork-3
/ДЗ3.py
1,905
4.125
4
""" 1. Дан список. Получите новый список, в котором каждое значение будет удвоено: [1, 2, 3] --> [2, 4, 6] """ lst = [int(i) for i in input('Введите список чисел').split()] # Ввод списка с числами for i in range(len(lst)): # Цикл по индексам lst[i]+=lst[i] # На каждом индексе изменяем число, прибавляя к нему это же число print(lst) """ 2. Дан список. Возведите в квадрат каждый из его элементов и получите сумму всех полученных квадратов: [1, 2, 3] --> 14 --> 1^2 + 2^2 + 3^2 = 14 """ lst = [1,2,3] # Список чисел c=0 # Счетчик for i in lst: # Цикл по значениям c+=i*i # Записываем в c каждое число из списка в квадрате и прибавляем print(c) """ 3. Дана строка 'Hello world'. Проверьте, если в этой строке есть символ пробела - " ", тогда преобразуйте строку к верхнему регистру, если же нет, тогда к нижнему. ** s = 'Hello world' if stm: pass else: pass """ s = 'Hello world' if ' ' in s: # Если пробел есть в списке, s=s.upper() # тогда преобразуем в верхний регистр print(s) # Вывод числа else: s = s.lower() print(s) """ 4. Выведите все года, начиная с 1900 по 2020 ** 1900 год 1901 год 1902 год n год 2020 год """ for i in range(1900,2021): print(i, 'год')
false
b7bb5e89ca48c2fcc9575ac42cc44ec8a0483c07
Tam-ala/python-challenge-hw
/PyPoll/Pypoll_Complete.py
2,341
4.125
4
import csv # Make a path to csv csvpath = "Resources/election_data.csv" # Save results in lists and dictionaries. Keep count of votes. total_votes = 0 max_votes = 0 candidate_list = [] candidate_votes = {} candidate_percentage = {} # Open csv and skip the header with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csvheader = next(csvreader) # Create a for loop to tally results for row in csvreader: candidate = row[2] total_votes += 1 if candidate not in candidate_list: candidate_list.append(candidate) candidate_votes[candidate] = 0 candidate_percentage[candidate] = 0 # Get the percentage of each votes per candidate candidate_votes[candidate] += 1 candidate_percentage[candidate] = (candidate_votes[candidate]/total_votes)*100 # Find the winner by max number of votes if candidate_votes[candidate] > max_votes: max_votes = candidate_votes[candidate] winner = candidate # Print out the results print("Election Results") print("--------------------------") print(f"Total Votes: {str(total_votes)}") print("--------------------------") print("Votes per Candidate") for (key, value) in candidate_votes.items(): print (key, value) print("--------------------------") print("Percentage of Votes per Candidate") for (key, value) in candidate_percentage.items(): print (key, value) print("--------------------------") print(f"Winner: {winner}") print("--------------------------") # Export results to a text file with open("ElectionResults.txt","w") as text: text.write("Election Results \n") text.write("--------------------------\n") text.write(f"Total Votes: {str(total_votes)} \n") text.write("-------------------------- \n") text.write("Votes per Candidate \n") for (key, value) in candidate_votes.items(): text.write(key) text.write(f" {value} \n") text.write("-------------------------- \n") text.write("Percentage of Votes per Candidate \n") for (key, value) in candidate_percentage.items(): text.write(key) text.write(f" {value} \n") text.write("-------------------------- \n") text.write(f"Winner: {winner} \n") text.write("-------------------------- \n")
true
a6c2247ae3ef92db0ef11d8c773a6713c04e570d
Teju1565/project
/function.py
515
4.25
4
string = input('please enter a string =') def make dict(x): dictionary = {} for letter in x: dictionary[letter]=1+dictionary.get(letter,0) return dictionary def most_frequent(string): letters = [letter.lower() for letter in string if letter.isalpha()] dictionary = make_dict(letters) result = [] for key in dictionary: result.append((dictionary[key],key)) result.sort(reverse=True) for count,letter in result: print(letter,"=",count,end=",") print(most_frequent(string))
true
29b2c28a1ce094d6d612d636a3e228025a244c61
Snehal-610/Python_Set
/set4/dbu_program027.py
359
4.5
4
#!/usr/bin/python # -*- coding: utf-8 -*- # program 27 : # Define a function that can convert a integer # into a string and print it in console. # Hints: # Use str() to convert a number to string. def convert(n): print(f"This is Input Integer: {n}\nAfter converted Integer is in string is '{str(n)}'.") n = int(input("Enter Integer: ")) convert(n)
true
3a6c70b5e845cf924b118c3eb52ee5d13b5cc060
Snehal-610/Python_Set
/set1/dbu_program048.py
559
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # program 48 : # Write a program which can filter() to make a list # whose elements are even number between 1 and 20 (both included). # Hints: # Use filter() to filter elements of a list. # Use lambda to define anonymous functions. even = filter(lambda a : a % 2 == 0, [i for i in range(1,21)]) print(f"Even Numbers: {list(even)}") # from functools import reduce # ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # rs = reduce(lambda x, y: x + y, list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, ls)))) # print(rs)
true
291879617021cc37b5c54d22849ba2d5ee039974
Snehal-610/Python_Set
/set2/dbu_program026.py
397
4.28125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # program 26 : # Define a function which can compute the sum of two numbers. # Hints: # Define a function with two numbers as arguments. # You can compute the sum in the function and return the value. def fun(num1, num2): return num1 + num2 print("Sum of Two number is: ", fun(int(input('Enter number 1: ')),int(input('Enter number 2: '))))
true
8c9ba28c276624232e6825fb26e25db3173d6e96
Snehal-610/Python_Set
/set1/dbu_program022.py
1,317
4.46875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # program 22 : # Write a program to compute the frequency of the words from the input. # The output should output after sorting the key alphanumerically. # Suppose the following input is supplied to the program: # New to Python or choosing between Python 2 and # Python 3? Read Python 2 or Python 3. # Then, the output should be: # 2:2 # 3.:1 # 3?:1 # New:1 # Python:5 # Read:1 # and:1 # between:1 # choosing:1 # or:2 # to:1 # Hints: # In case of input data being supplied to the question, it should be # assumed to be a console input. string = "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3." # from collections import OrderedDict # # ans = {} # # words = string.split() # unique_words = set(words) # # for item in unique_words: # ans[item] = words.count(item) # z = ans.items() # od = OrderedDict(sorted(ans.items(), key=lambda e: e[0])) # # for item in od.items(): # print(item[0], item[1]) text = "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3." # text = text.split() # countDict = dict() # # for i in text: # if i not in countDict: # countDict[i] = text.count(i) # # countDict = dict(sorted(countDict.items())) # # for k, v in countDict.items(): # print(k, ":", v)
true
b45428ef71548cff8538d1fa24a6ae3550f30c91
KevinZWong/Kevin2
/GuoAssignments/NumberSorting/hw3_E.py
1,681
4.21875
4
def numsort(varlist): total = 0 totalOdd = 0 totalEven = 0 smallestNum = 9999999999999 largestNum = 1 #total for i in range (0, 10, 1): total = i + i #average average = total/10 # you have to loop through the list for i in range (0, 10, 1): if i % 2 == 0: totalOdd = i + i if i % 2 == 1: totalEven = i + i print('Sum of all numbers: ', total) print('The average is: ', average) print('Sum of even numbers: ', totalOdd) print('Sum of odd numbers: ', totalEven) #finding smallest for i in range (0, 10, 1): if varList[i] < smallestNum: smallestNum = varList[i] print('Smallest number: ', smallestNum) #finding Largest if varList[i] > largestNum: largestNum = varList[i] print('Largest number:', largestNum) varlist = [] for i in range(1, 11, 1): var1 = int(input()) varlist.append(var1) numsort(varlist) ''' for i in range(1, 11, 1): print("i= ", i) # take input from key-board, # and convert it into integer, # and assign it into a variable # Please note: var1 is a local-variable, it will die out by every loop var1 = int(input()) # to append the variable into the end of the list # basically, to input the var1 # Please note: varlist is global variable, it stands on # also, varlist is a list, which it could store many variables in the order varlist.append(var1) varlist = [1,2,3,4,5,6,7,8,9,10] numsort2(varlist) # call the function, with list variable, and get out by the order #numsort(varlist[0], varlist[1], varlist[2], varlist[3], varlist[4], varlist[5], varlist[6], varlist[7], varlist[8], varlist[9]) #IN FUNCTION '''
true
84bf142e5037d94d328506a13ca44ed3dbf45a86
bkyileo/algorithm-practice
/python/Permutations.py
910
4.1875
4
__author__ = 'BK' ''' Given a collection of distinct numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. Subscribe to see which companies asked this question ''' class Solution(object): def helper(self,nums,start,re): import copy if start == len(nums): if nums not in re: re.append(copy.copy(nums)) return for i in xrange(start,len(nums)): nums[i],nums[start]=nums[start],nums[i] self.helper(nums,start+1,re) nums[i],nums[start]=nums[start],nums[i] def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ re=[] self.helper(nums,0,re) return re solu = Solution() nums=[1,1,0,0,1,-1,-1,1] print solu.permute(nums)
true
f55438e25df5f735eea83958d266cce3ab125880
EduardoRosero/python
/curso python/VariablesDeClase.py
857
4.34375
4
class Circulo: """Esta representando a un circulo en la vida real para lo cial se necesita una constante universal que es pi""" _pi = 3.1416 #Variable de clase, le pertenece a la clase y no a los objetos (instancias) def __init__(self, radio): self.radio=radio #self.pi = 3.1416 #Le va a pertenecer a cualquier instancia de la clase, pero como es una constante la vamos a ubicar en otra posicion para crear una variable de clase def area(self): return self.radio*self.radio*self._pi circulo_uno = Circulo(4) circulo_dos = Circulo(3) print(circulo_uno._pi) print(circulo_dos._pi) print(Circulo._pi) #No se necesita crear un objeto para usar pi (le petenece a la clase) print(circulo_uno.__dict__)#Nos muestra un diccionario de los atributos de la clase excluyendo los que son variables de clase print(circulo_uno.area())
false
e9698f8c0f21e9e8333be87b736aca5bc6f910f2
Ronaldsantillan/ejercicios-del-deber
/ejemplo3.py
818
4.125
4
#Construir un algoritmo tal, que dado como dato la calificación de un alumno en un examen, escriba #calificación“Aprobado” en caso que esa calificación fuese mayor o igual que 7. class Alumno: def __init__(self): pass def calificacion_del_alumno(self): cali1 = float(input("ingrese primera calificación:")) cali2 = float(input("ingrese segunda calificación:")) cali3 = float(input("ingrese tercera calificación:")) promedio = (cali1+cali2+cali3)/3 if promedio >=7 : print("Aprobado") print("la primera calificaión es de:{} la segunda calificación es de:{} la tercera calificación es de:{} el promedio es de:{}".format(cali1,cali2,cali3,promedio)) alumno=Alumno() alumno.calificacion_del_alumno()
false
4634be99d4e98baf7a0d6d49170da44b8cf08d7e
reshadbinharun/ctci-python
/arrays_and_strings/URLify.py
516
4.25
4
''' URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.) ''' def URLify(input, trueLength): input = input[0 : trueLength - 1] return input.replace(" ", "%20%") print(URLify("the quick brown fox jumped over the lazy cow", 20))
true
73e5c7ae2f2f90da085a854efb67114bd2cc7f49
coleone/Algorithm
/first_non_repeat.py
781
4.15625
4
def first_non_repeat(string): str_hash = {} length = len(string) if length == 0: print "ERROR: Input string length is 0\r\n" return None # This for loop is for assigning values to the keys. for i in range(length): if string[i] not in str_hash.keys(): str_hash[string[i]] = 1 else: str_hash[string[i]] += 1 print str_hash # This for loop is for checking first non repeat letter of the string. for i in range(length): if str_hash[string[i]] == 1: print "First non repeat letter is %s \r\n" %string[i] return string[i] # Return None if all letters are repeated. return None if __name__ == "__main__": string = "abccbsabcdefgabcde" print "Input string is %s\r\n"%string string_2 = first_non_repeat(string) print "string_2 is %s\r\n" %string_2
true
13ec8c11ffc834d6f9480352cb0ea507f7db02c8
vishalbehl/pyhon_coding_practice
/4-Dictionary.py
1,046
4.15625
4
#____________________________________________________________________________# #---------------------------DICTIONARY IN PYTHON-----------------------------# #SYNNTAX: # dictionary={ # 'key': value, # 'key': value # } dictionary={ 'Tree':'plant', 'Python':'Very Useful', 'a':True, 'b':[1,2,3,4,5,6] } print(dictionary['Python']) print(dictionary) print(dictionary['b']) print(dictionary.get('a')) print(dictionary.get('d', 23)) #Set value of 'd':23 if not exist #Create a new empty dictionary(Not Preffered) print(dict(name='Vishal')) #Finding in dictionary print('a' in dictionary) print('plant' in dictionary.values()) #print the dictionary items print(dictionary.items()) #Copy the Dictionary dic2=dictionary.copy() print(dic2) #Remove the given key print(dictionary.pop('Tree')) print(dictionary) #Remove from the end print(dictionary.popitem()) print(dictionary) #Update the dictionary print(dictionary.update({'s':False})) print(dictionary) #Clear the Dictionary print(dictionary.clear())
true
560f24305d4ee4418485aa625fd6a171fdfad1a2
HWYWL/python-examples
/基础/List列表.py
567
4.15625
4
# 这是列表,[] name_list = ["校花", "美女", "小萝莉"] print(name_list) name_list.append("御姐") print(name_list) # 直接遍历 for name in name_list: print(name) # 通过索引遍历 for index in range(len(name_list)): print(name_list[index]) count = name_list.count("美女") print("美女关键字出现的次数 %d" % count) # 逆序反转 name_list.reverse() print(name_list) num_list = [3, 101, 6, 8, 62, 25] print(num_list) # 升序排序 num_list.sort() print(num_list) # 降序排序 num_list.sort(reverse=True) print(num_list)
false
3c7749f40a7cb9d8596b371678d391a86adef8e2
awong05/epi
/reverse-a-single-sublist.py
1,086
4.28125
4
class ListNode: def __init__(self, data=0, next_node=None): self.data = data self.next = next_node """ This problem is concerned with reversing a sublist within a list. See Figure 7.4 for an example of sublist reversal. Write a program which takes a singly linked list L and two integers s and f as arguments, and reverses the order of the nodes from the sth node to the fth node, inclusive. The numbering begins at 1, i.e., the head node is the first node. Do not allocate additional nodes. Hint: Focus on the successor fields which have to be updated. """ def reverse_sublist(L, start, finish): """ Space complexity: O(1) Time complexity: O(f) """ dummy_head = sublist_head = ListNode(0, L) for _ in range(1, start): sublist_head = sublist_head.next sublist_iter = sublist_head.next for _ in range(finish - start): temp = sublist_iter.next sublist_iter.next, temp.next, sublist_head.next = ( temp.next, sublist_head.next temp ) return dummy_head.next
true
21dd0327d98808dcfd0e06e30d3751cd90dea472
awong05/epi
/compute-the-spiral-ordering-of-a-2D-array.py
2,187
4.71875
5
""" A 2D array can be written as a sequence in several orders—the most natural ones being row-by-row or column-by-column. In this problem we explore the problem of writing the 2D array in spiral order. For example, the spiral ordering for the 2D array in Figure 5.3(a) on the following page is <1,2,3,6,9,8,7,4,5>. For Figure 5.3(b) on the next page, the spiral ordering is <1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10>. Write a program which takes an n x n 2D array and returns the spiral ordering of the array. Hint: Use case analysis and divide-and-conquer. """ def matrix_in_spiral_order(square_matrix): """ Space complexity: O(1) Time complexity: O(n**2) """ def matrix_layer_in_clockwise(offset): if offset == len(square_matrix) - offset - 1: spiral_ordering.append(square_matrix[offset][offset]) return spiral_ordering.extend(square_matrix[offset][offset:-1 - offset]) spiral_ordering.extend( list(zip(*square_matrix))[-1 - offset][offset:-1 - offset] ) spiral_ordering.extend( square_matrix[-1 - offset][-1 - offset:offset:-1] ) spiral_ordering.extend( list(zip(*square_matrix))[offset][-1 - offset:offset:-1] ) spiral_ordering = [] for offset in range((len(square_matrix) + 1) // 2): matrix_layer_in_clockwise(offset) return spiral_ordering def matrix_in_spiral_order(square_matrix): """ Space complexity: O(1) Time complexity: O(n**2) """ SHIFT = ((0, 1), (1, 0), (0, -1), (-1, 0)) direction = x = y = 0 spiral_ordering = [] for _ in range(len(square_matrix)**2): spiral_ordering.append(square_matrix[x][y]) square_matrix[x][y] = 0 next_x, next_y = x + SHIFT[direction][0], y + SHIFT[direction][1] if (next_x not in range(len(square_matrix)) or \ next_y not in range(len(square_matrix)) or \ square_matrix[next_x][next_y] == 0 ): direction = (direction + 1) & 3 next_x, next_y = x + SHIFT[direction][0], y + SHIFT[direction][1] x, y = next_x, next_y return spiral_ordering
true
9dceb53150eb3e38587c53d40eca643dbc081e59
awong05/epi
/test-if-a-binary-tree-is-symmetric.py
1,134
4.40625
4
class BinaryTreeNode: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right """ A binary tree is symmetric if you can draw a vertical line through the root and then the left subtree is the mirror image of the right subtree. The concept of a symmetric binary tree is illustrated in Figure 9.3. Write a program that checks whether a binary tree is symmetric. Hint: The definition of symmetry is recursive. NOTES: - All that is important is whether a pair of subtrees are mirror images. """ def is_symmetric(tree): """ Space complexity: O(h) Time complexity: O(n) """ def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_0 and subtree_1: return ( subtree_0.data == subtree_1.data and \ check_symmetric(subtree_0.left, subtree_1.right) and \ check_symmetric(subtree_0.right, subtree_1.left) ) return False return not tree or check_symmetric(tree.left, tree.right)
true
186919263b5104c251fd68484a8ecc5fc3814a01
BeccaFlake/Python
/change_RCF.py
2,046
4.3125
4
#!/usr/bin/env python3 #This program calculates the coins needed to make change for a specified monetary amount #Display Title print("Change Calculator\n\n") #initialize the variables qcounter = 0 dcounter = 0 ncounter = 0 pcounter = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 choice = "y" while choice.lower() == "y": #Ask for the input dollar_amount = float(input("Enter the dollar amount. (For example 3.75, 4.00, or 0.36): ")) change = int(dollar_amount * 100) #Multiply by 100 to convert the input to a intiger without losing the decimal portion #Calculate while change > 0: if change >= 25: #count needed quarters change -= 25 qcounter += 1 quarters = qcounter elif change >= 10: #count needed dimes change -= 10 dcounter +=1 dimes = dcounter elif change >= 5: #count needed nickels change -= 5 ncounter +=1 nickels = ncounter else: #count needed pennies change -= 1 pcounter += 1 pennies = pcounter continue #Display the result print("Quarters: " + str(quarters)) print("Dimes: " + str(dimes)) print("Nickels: " + str(nickels)) print("Pennies: " + str(pennies)) print() #Ask if the user wants to continue (y/n). Continue only if user enters a y or a Y. choice = input("Continue? (y/n): ") print() if input == "y" or "Y": #resets all of the calculation variables to zero when the program goes through another loop qcounter = 0 dcounter = 0 ncounter = 0 pcounter = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 #Print message if user does not choose to continue print("Bye!")
true
b0454c66b6677be101e9315e1a3845957416c290
b2shil/hj
/fibonacci.py
307
4.375
4
#!/usr/bin/python3 #program of fibonacci sequence a = input('enter a starting number of fibonacci sequence : ') b = input('enter an ending number of fibonacci sequence : ') a = int(a) b = int(b) print ('your febonacci sequence range is :' , a ,'to', b) for i in range(a, b): print(a) a , b = b , a+b
false
7193c232f9c2c6e30362ad6d4a4ef3b05bd64f8d
umutozge/prog-book
/code/mean-word-length.py
532
4.28125
4
# The file we will read has a single word in each line # Therefore reading all the lines in a file into a list # directly gives a word list. Words, however, come with # a newline character '\n' at the end; to get rid of this # python provides the method strip(). Observe its use below. f = open("tr-word-list.txt", "r") sum = 0 wlist = f.readlines() # we no longer need the file, so we close the # stream f.close() for w in wlist: sum += len(w.strip()) meanwl = sum/len(wlist) print("The mean word length = ",str(meanwl))
true
5a66b4a8b824560c8dbf1c6626958ab048419571
Klyde0/Learning-Official
/Learning Python.py
723
4.65625
5
# For loops allow us to loop over (iterate) a collection of items (ex. letters in a string, arrays, series of numbers) # STRINGS EXAMPLE # for letter in 'Blackets in Space': # print(letter) # ARRAY EXAMPLE # if for looping in a list, you will print out each element of the array/list # friends = ['Alex', 'John', 'Mark', "Billy"] # for Learning 1 in friends: # print(Learning 1) # if for looping in a list and you are printing out the array/list, you will print out the list however many elements are in that list # friends = ['Alex', 'John', 'Mark', "Billy"] # for Learning 1 in friends: # print(friends) # INTEGER EXAMPLE # for Learning 1 in range(10): # print(Learning 1)
true
c916350daccf0fdf6ce1c3447bd2af2a9dea3ea8
Klyde0/Learning-Official
/Learning Python Booleans and Conditionals.py
1,431
4.5625
5
# if True: # print('Conditional was True') # # # will print statement only if conditional was True # # if False: # print('Conditional was True') # # # language = 'Python' # # if language == 'Python': # print('Conditional was True') # Here the statement is printed because the conditional was true # is = object identity = comparing whether they are the same object in identity # language = 'Javascript' # if language == 'Python': # print('Language is Python') # elif language == 'Java': # print('Language is Java') # elif language == 'Javascript': # print('Language is Javascript') # else: # print('No Match - language is different') # typical conditional statements # if --- elif --- elif --- ... --- else # Booleans = and, or, not # user = 'Admin' # logged_in = False # # if user == 'Admin' and logged_in: # print('Admin Page') # else: # print('Bad Credentials') # # user = 'Admin' # logged_in = True # # if logged_in: # input('Please Log in:') # # elif logged_in == True: # print('Welcome') # else: # print('Bad Credentials') is_male = False is_tall = False if is_male and is_tall: print('You are a Male and Tall') elif is_male and not is_tall: print('You are a short male') elif not is_male and is_tall: print('You are not a male but you are tall') else: print('You are not a male and not tall')
true
495281f995764188ce291c21c4170a2dbb04eb2a
VlasovVitaly/internal
/diofant/diofant_006.py
379
4.3125
4
#!/usr/bin/env python3 # Найти разность (1+2+3... +200)^2 - (1^2+2^2+3^2+...+200^2). def triangular_num(num): return (num * (num + 1)) // 2 def square_summ(num): summ = 0 for i in range(1, num + 1, 1): summ = summ + (i ** 2) return summ part1 = triangular_num(200) ** 2 part2 = square_summ(200) print("Result: {}".format(part1 - part2))
false
d0073544fc3873397fda7c11be24194966688637
MiHHuynh/rmotr-intro-to-python
/GettingStarted/get_string_positions.py
878
4.25
4
# String Positions # Sometimes you need to know the position of a character in a string and you might not want to count to figure it out. So write a quick function to do it for you! # Complete get_string_positions so that it takes the_string and creates a new string showing the position of each character. Example: # print(get_string_positions("xyz")) # ''' # Prints: # 0-x # 1-y # 2-z # ''' # The function uses the enumerate() function on the list in a for loop to get each position and character associated with it. Example: # for position, character in enumerate(list_name): # # do stuff # Then just store the result in a big string. Note you separate the lines by using '\n' the newline character after each line. Good luck! # Hint: You might have to put str() around to position to change it from an integer into a string so you can add it to your result string.
true
599c99cc496952006ce9b5486458d50b1303eb21
AABHINAAV/python-study
/map-filter.py
2,754
4.5
4
# iterable ---> uses __iter__() or __getitem__() and produces the iterator # can be traversed many times # iterator ---> uses __next__() and gets the next value # can be traversed only once ######### # map function returns a map object # map objects are iterator # we can use loop on map objects only once # they use __next() inside them # without map function:-- # l=list(range(1,11)) # def fun(l): # return [i**2 for i in l] # print(fun(l)) # with list comprehension and without map function:-- # l=list(range(1,11)) # print([i**2 for i in l]) ##with map function:--- # syntax:----- map(function name , iterable name) # l=list(range(1,11)) # def fun(num): # return num**2 # # res=list(map(fun,l)) # # print(res) # ######or######### # print(list(map(fun,l))) # map function with lambda expression:--- # l=list(range(1,11)) # print(list(map(lambda num:num**2 , l))) # l=list(range(1,11)) # def fun(num): # return num**2 # res = map(fun,l) # for i in res: # print(i) # for i in res: # print(i) ##no output this time coz res is a map object and map objects can be iterated only once coz they are iterators ###professionals use map objects mostly with predefined function like 'len' and use list compreshension with lambda function for most of the other purposes ###map function with predefined function:--- # l=['abhinav','jassi','nimisha tulera','ankit'] # res = list(map(len,l)) # print(res) # map function returns the result for a condition of all items # filter function returns the items that satisfies the condition # filter function returns an iterable object by default # l=list(range(1,11)) # def fun(num): # return num%2==0 # res1=list(map(fun,l)) # for i,j in enumerate(res1): # if j==True: # print(l[i]) #map function # res2=list(filter(fun,l)) # print(res2) #filter function # #filter function with lamda expression # print(list(filter(lambda num:num%2==0,list(range(1,11))))) # #list comprehension # print([i for i in range(1,11) if i%2==0]) #####iterator vs iterable######## # numbers=[1,2,3,4] #iterables # sqrs=map(lambda num:num**2 , numbers) #iterators # # this is how for loop works:-- # itr=iter(numbers) #---> itr is iterator of iterable 'numbers' # print(next(itr)) # print(next(itr)) # print(next(itr)) # print(next(itr)) # print('') # print(next(sqrs)) # print(next(sqrs)) # print(next(sqrs)) # print(next(sqrs)) # if we use iterator then python will firstly convert them into iterables then use a loop on them # while if we use iterables python weill do that for us # ######### reduce ########## # # from functools import reduce # lst=[1,2,3,4] # num=reduce(lambda x,y:x+y,lst) # print(num)
true
edc6dd8f4343ffa874bf2faa7dd1fd485bf571bf
AABHINAAV/python-study
/MAX-MIN-SORTED.py
1,485
4.1875
4
# printing longest word----- # lst = ['abhinav', 'jaspal', 'ankit'] # method 1----- # def fun(item): # return len(item) # print(max(lst,key=fun)) # method 2----- # print(max(lst, key=lambda item: len(item))) # printing whole info on basis of one data----- # students = [ # {'name': 'abhinav', 'age': 22}, # {'name': 'jassi', 'age': 23}, # {'name': 'ankit', 'age': 25} # ] # # whole data on basis of name length--> # print(max(students,key=lambda item:len(item['name']))) # # whole data on bases of age--> # print(max(students, key=lambda item: item['age'])) # # name on basis of age--> # print(max(students, key=lambda item: item['age'])['name']) # students={ # 'abhinav':{'age':22,'lname':'garg'}, # 'jaspal':{'age':23,'lname':'rana'}, # 'ankit':{'age':25,'lname':'nautiyal'} # } # print(max(students, key=lambda item:students[item]['age'])) # print(students[max(students, key=lambda item:students[item]['age'])]['lname']) #############advance sorted function############### # students = [ # {'name': 'abhinav', 'age': 22}, # {'name': 'jassi', 'age': 23}, # {'name': 'ankit', 'age': 25} # ] # print(sorted(students,key=lambda item:item['age'])) # print(sorted(students,key=lambda item:item['age'], reverse = True)) # students={ # 'abhinav':{'age':22,'lname':'garg'}, # 'jaspal':{'age':23,'lname':'rana'}, # 'ankit':{'age':25,'lname':'nautiyal'} # } # print(sorted(students,key=lambda item:students[item]['age']))
false
52117d5afea3302588d52e95ff6d57cccde602ef
Magno-Proenca/Exercicios-Python
/aula_07/aula_07_IV.py
361
4.125
4
n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro numero: ')) s = n1 + n2 p = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma destes dois numeros é {},\n o produto é {} e a divisão é {:.3f}, '.format(s, p, d), end='') #o \n serve para quebrar a linha print('a divisão inteira é {} \n e a exponenciação é {}'.format(di, e))
false
d4bfb18f08d9835535f59297bb585c9f110c61e8
rossgray/problemos
/Water/water.py
1,518
4.21875
4
# Python 3 def findWaterInCup(cup, total_water, cup_capacity): ''' There is a pyramid with 1 cup at level 1, 2 cups at level 2, 3 at level 3 and so on... It looks something like this 1 2 3 4 5 6 Every cup has capacity C. You pour amount L of water from the top of the pyramid. When cup 1 gets filled it overflows to cup 2 & 3 equally, and when they get filled, Cup 4 and 6 get water only from 2 and 3 respectively but 5 gets water from both the cups and so on. Given C and M, find the amount of water in the ith cup.''' if cup == 1: return min(cup_capacity, total_water) # l = level number, i = first cup on level l l=1 i=1 water_amt = total_water while True: i+=l l+=1 # caculate total amount of water on this level new_water_amt = water_amt-(l-1)*cup_capacity water_amt = max(new_water_amt, 0) #check if desired cup is on this level if cup < i+l: # cup is on this level # now check if the cup is on the outside or the inside of the row if (cup == i) or (cup == i+l-1): # outside cup return min(water_amt/(2*(l-1)), cup_capacity) else: #inside cup return min(water_amt/(l-1), cup_capacity) print(findWaterInCup(3, 10, 5)) print(findWaterInCup(5, 20, 3)) print(findWaterInCup(6, 20, 5))
true
bdf1020447aa1dff6e3c398fd020587d684e85ef
kennylugo/Miscellaneous
/PyFiles/Data Structures & Algorithms/linked_list.py
1,886
4.21875
4
# We create the node class, the node itself takes in data, and a pointer for the next node. # class Node(object): def __init__(self, data_value=None, next_node_pointer=None): self.data_value = data_value self.next_node_pointer = next_node_pointer # Convenience methods def get_data_value(self): return self.data_value def get_next(self): return self.next_node_pointer def set_next(self, new_next): self.next_node_pointer = new_next class LinkedList(object): def __init__(self, head=None): self.head = head # Insert method def insert(self, data_value): # creates a new node, sets the given data inside the node new_node = Node(data_value) # sets the pointer of the current node to point at the head ( first element in linked list) new_node.set_next(self.head) # we set the new as the head of the list self.head = new_node # Size method def size(self): current = self.head count = 0 while current: count += 1 current = current.get_next() return count def search(self, data_value): current = self.head found = False while current and found is False: if current.get_data_value() == data_value: found = True else: current = current.get_next() if current is None: raise ValueError("data value not in list") return current def delete(self, data_value): current = self.head previous = None found = False while current and found is False: if current.get_data_value() == data_value: found = True else: previous = current current = current.get_next() if current is None: raise ValueError("Data Value not in list") if previous is None: self.head = current.get_next() else: previous.set_next(current.get_next()) ll = LinkedList() ll.insert("Hello") ll.insert("World") ll.insert("I") ll.insert("am") ll.insert("Kenny") size = ll.size() print(size)
true
1e6f50f082d59cad6c617c94080c7905f120a634
claudiordgz/udacity--data-structures-and-algorithms
/notes/trees/depth2.py
342
4.1875
4
def print_tree_inorder(tree): """ Implement a in-order traversal here Args: tree(object): A binary tree input Returns: None """ if tree == None: return print_tree_inorder(tree.left) print(tree, end=' ') print_tree_inorder(tree.right) print("In-order:", end=' ') print_tree_inorder(my_tree)
true
76337d74a2dc73002bbc8b11498c9a0d131949b7
katebartnik/katepython
/Exam/Min-maxing.py
513
4.3125
4
""" Define a function named largest_difference that takes a list of numbers as its only parameter. Your function should compute and return the difference between the largest and smallest number in the list. For example, the call largest_difference([1, 2, 3]) should return 2 because 3 - 1 is 2. You may assume that no numbers are smaller or larger than -100 and 100. """ def first_and_last(tab): new_tab = [tab[0], tab[len(tab) - 1]] return new_tab a = [5, 10, 15, 20, 25, 3] print(first_and_last(a))
true
3eecc0bb08d99d59fe37f11356bb78adc0ae17c0
venkateshvadlamudi/Pythontesting
/pythonPractice/Conditionalstatement.py
1,145
4.25
4
# if .. else # Case 1 : a= 30 if a>20: print("true conduction") else: print("false conduction") # Case 2 : if True: print("true conduction") else: print("false conduction") # Case 3 : if True: print("true conduction") else: print("false conduction") # Case 4 : a=10 if a % 2 == 0: print("Even Number") else: print(" odd Number") # Multiple statements under if block if False: print("Statement1") print("Statement2") print("Statement3") else: print("Statement4") print("Statement5") print("Statement6") # separate statement # Single Line print("welcome") if True else print("Python") print("welcome") if False else print("Python") print("welcome") if 20>10 else print("Python") print("welcome") if 20<10 else print("Python") # Multiple statements in Single Line {print("welcome"),print("Python") if True else print("Python"),print("Welcome" )} {print("Python"),print("welcome") if False else print("welcome"),print("Python...")} # elif a=50 if a==10: print("Ten") elif a==20: print("Twenty") elif a==30: print("Thirty") else: # optional print("Not Listed")
false
9828494769fa7662ea84b728fbb3604c359894cd
venkateshvadlamudi/Pythontesting
/pythonPractice/List.py
1,586
4.4375
4
## Creating list in Python ## list1 =list() # creating an empty list print(list) list2= list([20,25]) # creating a list with elements print(list2) list3= list(["tom", "venki", "name"]) # creating a list with strings print(list3) list4= list("python") print(list4) # List index list5 =list([1,2,3,4,5,6]) print([list5[1:3]]) print([list5[1:]]) print([list5[3]]) # List Common operations list1 = [2,2,4,1,32] print(2 in list1) # True print(33 not in list1) # True print(len(list1)) print(max(list1)) print(min(list1)) print(sum(list1)) ## List slicing ## -- Slice list =[11,22,44,788,1,8] print(list[0:5]) print(list[:3]) print(list[2:]) ## + and * operators in list ---> + operators join the two list ## * operator replicates the element in the list list1=[11,33] list2= [1,9] list3=list1+list2 print(list3) list4=[1,2,3,4] list5=list4*3 print(list5) ## Traversing list using for loop ---> we can use for loop to through all the elements of the list list =[1,2,3,4,5] for i in list: print(i,end=" ") ## Commonly used list method with return type list1 = [2,3,4,5,6,7,3,] list1.append(8) print(list1) print(list1.count(3)) list2=[10,11] list1.extend(list2) print(list1) print(list1.index(4)) list1.insert(1,25) print(list1) list1=[1,2,3,4,5,6,7,8,9] print(list1.pop(2)) print(list1) list1.remove(7) print(list1) list1.reverse() print(list1) list1.sort() print(list1) ## List Comprehension ### list1= [x for x in range (10)] print(list1) list2=[x+ 1 for x in range (10)] print(list2) list3=[x for x in range (10) if x % 2==0] print(list3)
true
c6427f6de628f970459a62317d0455b75ed9cb97
JSinkler713/recursion
/recursion.py
2,496
4.1875
4
# Base Case is where it's gonna stop # Recursion it is a way to loop # let i = 200 # while( i > 0) { # console.log(i) # // increment down # i-- # } def navel_gazer(i=1): # base case so we don't go beyon 100 if (i == 100): # do not call the function in the base case return print('hmm') print(i) # need a base case or we continue our loop return navel_gazer(i+1) # navel_gazer() # sum of all the integers from 0 to n where n is our input def get_sum(n=0): # base case where we don't call our function if (n == 0): return 0 # recursive case we call our function in the return return n + get_sum(n - 1) # moving towars our base case get_sum() # 0 print(get_sum(5)) # 1+2+3+4+5 # Palindrome Function """ Input: A string Output: Boolean Purpose: Is the input string a palindrome? """ def is_palindrome(ss): # base case if len(ss) < 2: return True if ss[0] != ss[-1]: return False # recursive case return is_palindrome(ss[1:-1]) # print(is_palindrome("hannah")) x = "hannah" print(is_palindrom(x)) # print(x[1:-1]) # PRACTICE_PROBLEMS def is_palindrome(string): if (len(string) < 2): return True # recursive case if (string[0] != string[-1]): #break out of loop if false along the way return False # have the function call itself without # the first and last char we just checked return is_palindrome(string[1:-1]) print(is_palindrome('abba')) # True print(is_palindrome('TOMATO')) # False def reverse(string): # base case if (len(string) <= 0): return "" # do some logic character = string[-1] # call the function again getting closer to base case return character + reverse(string[:-1]) print(reverse('tomato')) # otamot def pretty_print(dictionary, indent=""): # iterate through every key in the dictionary for key in dictionary: # get the value associated with the key val = dictionary[key] # check the type of the key to see if it's another dict if isinstance(val, dict): print(f"{indent}{key}:") pretty_print(dictionary[key], indent + " ") else: # it's the val isn't a dict then just print out they key and val print(f"{indent}{key}: {val}") o3 = {"a": 1, "b": 2, "c": {"name": "Bruce Wayne", "occupation": "Hero", "friends": {"spiderman": {"name": "Peter Parker"}, "superman": {"name": "Clark Kent"}}}, "d": 4} pretty_print(o3)
true
36ba79ae697f4f80e0e8bf1747ae3f6b161faf0f
Code-Ebullient/accounts
/task.py
1,667
4.1875
4
#Program to setup a company's employee account details import random import string #Employees data containers user_data = [] names = () #Individual details str1 = input("Enter your firstname: ") str2 = input("Your lastname, please: ") email = input("Your email also: ") names = str1[:2]+str2[-2:] #Defining the password function def random_password(): char = string.ascii_letters stringLength = 5 randon_source = ''.join(random.choice(char) for i in range (stringLength)) random_password = names + randon_source return random_password #List class for storing all information while (True): user_data.append({ "firstname": str1, "lastname": str2, "email": email, "password": random_password }) #check for user's satisfaction print (f"{str1}, this password has been generated for you: {random_password} ") cont = input("Are you okay with it? (Y/N) ") if cont == "Y": user_data.append(random_password) break else: new_password = input("Enter your choice password greater than or equal to 7: ") def new_password(): if len(new_password) >= 7: random_password.clear random_password += new_password return new_password else: print("Password must be greater than or equal to 7") new_password = input("Enter password greater than or equal to 7") #new user_data new_user = input("Would you like to enter a new user? (Y/N) ") if new_user =="N": print(user_data) user_data = false else: print("Your details \n") print(f"Here are your details") print(user_data)
true
5fc2668bba922d6961b975b90d62e020d873f226
MCrank/learn-python
/Section2/2.5-UserInput.py
437
4.28125
4
# Firstname, M. Lastname first_name = str(input("Please enter your firstname: ")) middle_name = str(input("Please entre your middle name: ")) last_name = str(input("Please enter your last name: ")) first_name = first_name.capitalize() middle_name = middle_name.capitalize() last_name = last_name.capitalize() name_format = "{first} {middle:.1s} {last}" print(name_format.format(first=first_name, middle=middle_name, last=last_name))
true
56e7a054c876d8ba08a84239fb2e4b6b9acafb0a
JVN-S2-Spring-18/binary-search
/binary_search.py
442
4.28125
4
def binary_search(sorted_list, value): """ Find an element in a sorted list of integers. If the element exists in the array, return the index of the element (0-based). Otherwise, return -1. Args: sorted_list: a list of integers in sorted, ascending order. value: a number to search for. Returns: The position index (0-based) of the value if found. Otherwise, return -1. """ return -1
true
e7e2c2d8d8cdd60ecd88f9af88e924c6eb71668c
kumcp/python-uwsgi-deploy
/source/base/common/datetime_handle.py
2,539
4.125
4
from datetime import datetime, timedelta def convert_string_to_date(string_date, format_date="%Y/%m/%d"): """Convert string to datetime Arguments: string_date {string} -- String datetime Keyword Arguments: format_date {str} -- format of string_date value (default: {"%Y/%m/%d"}) Returns: datetime -- datetime value in datetime module """ return datetime.strptime(string_date, format_date) def get_weekday(string_date, format_day="%A"): return convert_string_to_date(string_date).strftime(format_day) def diff_now(**kwargs): """Return the relative date from now Returns: datetime -- datetime object represent for the specific time """ return datetime.now() + timedelta(**kwargs) def now(timezone=None): """Return current now time. Returns: datetime -- datetime object represent for the specific time """ return datetime.now() def strptime(string_date, format_date="%Y/%m/%d", **kwargs): """A reference to datetime.strptime, but it has a default format_date and the format_date can be auto detected for some common cases Arguments: string_date {string} -- string represent for a date Keyword Arguments: format_date {str} -- format similar parameter to parse into datetime.strptime (default: {"%Y/%m/%d"}) Returns: datetime -- Datetime class base object """ return datetime.strptime(string_date, format_date) def strptime_list(string_date, format_list=[], **kwargs): """A reference to datetime.strptime, and take multiple format. Which format match first will be taken as that format. Arguments: string_date {string} -- string represent for a date Keyword Arguments: format_list {list} -- format list can be parsed (default: {[]}) Returns: datetime -- Datetime class base object """ for format_string in format_list: try: return strptime(string_date, format_string, **kwargs) except ValueError: pass raise ValueError("No format match for time data: %s" % (string_data)) def strftime(datetime_obj, format="%Y/%m/%d"): """A reference to datetime.strftime, but it has a default format Arguments: datetime_obj {datetime} -- datetime object Keyword Arguments: format {str} -- format output (default: {"%Y/%m/%d"}) Returns: str -- Output string """ return datetime_obj.strftime(format)
true
e239809149e6c76910e80d8ca2981e1f2d6f5963
sidlim/BIMM-181
/1. patterns & skew/1. pattern count.py
611
4.28125
4
import sys # Count the number of times a pattern appears in text. # run `python main.py filepath`, where the file's first # line is the text to search and the second is the pattern # to count. def main(): # Open file; first line corpus and second is pattern to match file = open(sys.argv[1], "r") text = file.readline().strip() pat = file.readline().strip() print(count(text, pat)) def count(text, pat): count = 0 for i in range(len(text) - len(pat) + 1): if text[i : i + len(pat)] == pat: count = count + 1 return count if __name__ == "__main__": main()
true
9ea0b0fdedd23897d849f409ec30a1f4682d47c7
harrisonBirkner/PythonSP20
/DictionaryFun/DictionaryFun/DictionaryFun/DictionaryFun.py
1,428
4.375
4
# Dictionary and Set Examples #phoneBook = { 'Beatrice': '555-1111', 'Katie':'555-2222', 'Chris':'555-3333'} #print(phoneBook) #print(phoneBook['Katie']) #if 'Chris' not in phoneBook: # print("No number available for Chris") #else: # print(phoneBook['Chris']) #Try adding to the dictionary #phoneBook['Wilbur'] = '123-0987' #phoneBook['Beatrice'] = '867-5309' #print(phoneBook) #Delete a value from the phonebook #del phoneBook['Katie'] #print(phoneBook) #Find number of elements in our dictionary #numItems = len(phoneBook) #print(numItems) #Creating an empty dictionary #phoneBook={} #phoneBook['Chris'] = '555-1111' #phoneBook['Shelby'] = '555-2222' #print(" ") #print(phoneBook) #print(" ") # For Loop #for key in phoneBook: # print(key) #Creating a Set #mySet = set() #mySet = set ('aabbcc') #print(mySet) #mySet = set (['one', 'two', 'three', 45]) #print(mySet) #Can find the length of the set #print(len(mySet)) #mySet.add(1) #print(mySet) #mySet.update([2,3,4]) #print(mySet) #mySet.remove(1) #print(mySet) #mySet.discard(88) #print(mySet) #set1 = set ([1, 2, 3]) #set2 = set ([3, 4, 5]) #set3 = set1.union(set2) #print (set3) #set4 = set1.intersection(set2) #print(set4) #set5 = set2.difference(set1) #print(set5) #Symmetric Difference of Sets #set1 = set ([1,2,3,4]) #set2 = set ([3,4,5,6]) #set3 = set1 - set2 #print(set3) varTest = "Bill" for char7 in varTest: print(char7.isupper())
true
ccaf3fba4b21d813ecc14e753d80b9ccc696eee6
harrisonBirkner/PythonSP20
/Lab2/Lab2/softwareSales.py
1,244
4.15625
4
#This program asks the user to enter the number of packages purchased. #The program then displays the amount of the discount (if any) and the total amount of the purchase after the discount. qtyPackages = int(input('please input quantity of packages purchased: ')) total = qtyPackages * 99 if qtyPackages > 9 and qtyPackages < 20: discount = qtyPackages * 0.1 print('Discount: $' + format(discount, '10,.2f')) print('Total after discount: $' + format(total - discount, '10,.2f')) elif qtyPackages >= 20 and qtyPackages <= 49: discount = qtyPackages * 0.2 print('Discount: $' + format(discount, '10,.2f')) print('Total after discount: $' + format(total - discount, '10,.2f')) elif qtyPackages >= 50 and qtyPackages <= 99: discount = qtyPackages * 0.3 print('Discount: $' + format(discount, '10,.2f')) print('Total after discount: $' + format(total - discount, '10,.2f')) elif qtyPackages >= 100: discount = qtyPackages * 0.4 print('Discount: $' + format(discount, '10,.2f')) print('Total after discount: $' + format(total - discount, '10,.2f')) else: discount = 0 print('Discount: $' + format(discount, '10,.2f')) print('Total after discount: $' + format(total - discount, '10,.2f'))
true