blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2112a1c6e94348196d065f4748b6454345c2e112
tboydv1/project_python
/Python_book_exercises/chapter2/exercise13.py
331
4.125
4
#Validate for and integer input user_str = input("Input an integer: ") status = True while status: if user_str.isdigit(): user_int = int(user_str) print("The integer is: {}".format(user_int) ) status = False else: print("Error try again") user_str = input("Input an in...
true
6b0e05cdb97a6ca0eee0c64096017f46fd05cafe
tboydv1/project_python
/practice/circle.py
223
4.3125
4
from math import pi tmp_radius = input("Enter radius of circle ") radius = int(tmp_radius) circumference = 2 * (pi * radius) print("Circumference is: ", circumference) area = pi * radius**2 print("Area is: ", area)
true
76bfd7b4ce465902718576aa06d26cc654c9e599
tboydv1/project_python
/Python_book_exercises/chapter1/cosine.py
1,060
4.34375
4
from math import *; print("Angles of triangle with lengths: 7, 3, 9", end = "\n\n") ##Find angle C when side a = 9, b = 3, c = 7 ##formula= c**2 = a**2 + b**2 - 2 * a * b * Cos(c) side_a, side_b, side_c = 9, 3, 7; a_b = -(2 * side_a * side_b); #Square all sides pow_a = side_a**2 pow_b = side_b**2 pow_c = side_c**2...
false
f1d8cf960efa1ba7bafb12d84d48afc8b947d61c
tboydv1/project_python
/practice/factors.py
284
4.125
4
#get the input num = int(input("Please type a number and enter: ")) #store the value sum = 0 print("Factors are: ", end=' ') #generate factors for i in range(1, num): if(num % i == 0): print(i, end=' ') #sum the factors sum += i print() print("Sum: ",sum)
true
bbfc551d1ee571c9be6c68747b56ca85a56fcf4b
abaratif/code_examples
/sums.py
813
4.34375
4
# Example usage of zip, map, reduce to combine two first name and last name lists, then reduce the combined array into a string def combineTwoLists(first, second): zipped = zip(first, second) # print(zipped) # [('Dorky', 'Dorkerton'), ('Jimbo', 'Smith'), ('Jeff', 'Johnson')] # The list comprehension way listCom...
true
a54d2cbae58df936803b259917a95ed7f960f92b
sree-07/PYTHON
/escape_sequences.py
1,829
4.25
4
"""sep & end methods""" # a="python";b="programming" # print(a,b,sep=" ") #python programming # print(a,b,end=".") #python programming. # print("sunday") #python programming.sunday """ combination of end & str &sep """ # a="food" # b="from swiggy" # c="not av...
false
9cdf697a26228c198b2915a66ea9d32fae0fa091
sree-07/PYTHON
/type_casting_convertion.py
1,113
4.46875
4
"""int--->float,string""" # a=7 # print(a,type(a)) #7 <class 'int'> # b=float(a) # print(b,type(b)) #7.0 <class 'float'> # c=str(b) # print(c,type(c)) #7.0 <class 'str'> # x=10 # print("the value of x is",x) #the value of x is 10 # print("the value of x is %d"%x) #the value of x is 10 # z=s...
false
ffb500f887d8bcbcf33ce505ead46306f72e262e
anuragknp/algorithms
/float_str.py
285
4.1875
4
def convert_to_binary(n): bin = '' while n > 1: bin = str(n%2) + bin n = n/2 bin = str(n) + bin return bin def convert_float_to_binary(n): bin = '' while n != 0: n = n*2 bin += str(int(n)) n -= int(n) return bin print convert_float_to_binary(0.625)
false
958718e8a3414f0271687d4be32493d7fd50460e
MOGAAAAAAAAAA/magajiabraham
/defining functions 2.py
328
4.125
4
text="Python rocks" text2 = text + " AAA" print(text2) def reverseString(text): for letter in range(len(text)-1,-1,-1): print(text[letter],end="") def reverseReturn(text): result="" for letter in range(len(text)-1,-1,-1): result = result + text[letter] return result print(reverseReturn(...
true
a28faa5287000d5c056df0058c3834f299dccb1c
Guilherme-Galli77/Curso-Python-Mundo-3
/Teoria-e-Testes/Aula023 - Tratamento de Erros e Exceções/main2.py
1,173
4.15625
4
try: a = int(input("Num: ")) # 8 b = int(input("Denominador: ")) # 0 r = a / b except: print(f"Erro!") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO") print("="*50) # Outro formato de tratamento de exceção try: a = int(input("Num: ")) # 8 b...
false
fc017550df1a79ae77378faba63cbcaee9793ec8
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex081 - Extraindo dados de uma Lista.py
850
4.1875
4
# Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: # A) Quantos números foram digitados. # B) A lista de valores, ordenada de forma decrescente. # C) Se o valor 5 foi digitado e está ou não na lista. c = 0 lista = list() while True: valor = int(input("...
false
096ace50fea78a700ab0dad3900b7df4284e45d6
Guilherme-Galli77/Curso-Python-Mundo-3
/Exercicios/Ex079 - Valores únicos em uma Lista.py
680
4.25
4
#Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos # e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. # No final, serão exibidos todos os valores únicos digitados, em ordem crescente. Lista = list() while True: valor = int(input("Di...
false
d19ff58945bad7e67ba9308119a5b8a6d23cfa88
sakars1/python
/num_digit validation.py
494
4.21875
4
while 1: name = input("Enter your name: ") age = input("Enter your date of birth: ") num = input("Enter your phone number: ") if name == '' or num == '' or age == '': print("Any field should not be blank...") elif name.isalpha() and age.isdigit() and int(age) > 18 and num.isdigit(): ...
true
728f6e51eb42897c5bcdd390ae706596bb2c073d
taddes/algos_python
/Interview Questions/Sudoku/sudoku_solve.py
1,503
4.28125
4
# sudokusolve.py """ Sudoku Solver Note: A description of the sudoku puzzle can be found at: https://en.wikipedia.org/wiki/Sudoku Given a string in SDM format, described below, write a program to find and return the solution for the sudoku puzzle in the string. The solution should be returned ...
true
fadd06193eb3ae24ee17ada185a248199306506b
krishxx/python
/practice/Prg100Plus/Pr130.py
402
4.21875
4
''' 130. Write a program to Print Largest Even and Largest Odd Number in a List ''' li=list() print("enter numbers in to the list") num=input() while num!='': li.append(int(num)) num=input() sz=len(li) i=0 lo=-1 le=-1 while i<sz: if li[i]%2==0 and li[i]>le: le=li[i] i=i+1 elif li[i]%2!=0 and li[i]>lo: lo=li[i...
false
69c86dc61b1da9b98e2566a9e37b717a61758631
krishxx/python
/practice/Prg100Plus/Pr118.py
227
4.40625
4
''' 118. Write a program to Print an Identity Matrix ''' num=int(input("enter size of sq matrix: ")) for i in range(1,num+1): for j in range (1,num+1): if i==j: print(1,end=' ') else: print(0,end=' ') print("\n")
false
4f1c683a98d112484891549d7ea6a08a21a00056
juanfcreyes/python-exercises
/more_dictionaries.py
613
4.15625
4
def anagrams(array): wordsMap = {} for item in array: if "".join(sorted(item)) in wordsMap: wordsMap.get("".join(sorted(item))).append(item) else: wordsMap.setdefault("".join(sorted(item)),[item]) return wordsMap valuesort = lambda m: [pair[1] for pair in sorted(m.it...
false
06e11a4041d7be64059dd1b27ae2212e7ca51f73
Husnah-The-Programmer/simple-interest
/Simple interest.py
300
4.125
4
# program to calculate simple interest def simple_interest(Principal,Rate,Time): SI = (Principal * Rate * Time)/100 return SI P =float(input("Enter Principal\n")) R =float(input("Enter Rate\n")) T =float(input("Enter Time\n")) print("Simple Interest is",simple_interest(P,R,T))
true
b2352c3fca442ba2280b8a535d627917d562eb96
michelejolie/PDX-Code-Guild
/converttemperuter.py
223
4.25
4
# This program converts from Celsius to Fahrenheit user_response=input('Please input a temperature in celsius :') #celsius=int(user_response) celsius=float(user_response) fahrentheit=((celsius *9) /5)+32 print(fahrentheit)
false
48d494fbc16f2458590d4a9bbfcbddfd1a951cff
michelejolie/PDX-Code-Guild
/sunday.py
829
4.15625
4
# how to use decorators from time import time #def add(x, y=10): #return x + y #before = time() #print('add(10)', add(10)) #after = time() #print('time taken:', after - before) #before = time() #print('add(20,30)', add(20, 30)) #after = time() #print('time taken:', after - before) #before = time() #print...
true
f5f6d942565e076577c15ce93bd4a4da936b9c33
zxs1215/LeetCode
/208_implement_trie.py
1,505
4.125
4
class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.val = None self.children = [] self.has_word = False def next(self, val): for child in self.children: if child.val == val: return chil...
true
d12abc250671e0de9f9a0e2eda5c64f364a77968
Veena-Wanjari/My_Programs
/multiplication_table.py
449
4.1875
4
user_number = input("Enter a number: ") while (not user_number.isdigit()) or (int(user_number) < 1) or (int(user_number) > 12): print("Must be an integer between 1 to 12") user_number = input("Enter a number: \n") user_number = int(user_number) print("====================") print(f"This is the multiplic...
true
7407571d242fbbce0ee8acbff83e8335fe6cbd28
ravipatel0113/My_work_in_Bootcamp
/Class Work/3rd Week_Python/1st Session/04-Stu_DownToInput/Unsolved/DownToInput.py
491
4.125
4
# Take input of you and your neighbor name = input("What is your name?") ne_name = input("What is the neighbor name?") # Take how long each of you have been coding Time_code = int(input("How long have you been coding?")) netime_code = int(input("How long your neighbour " +ne_name+" have been coding?")) # Add total mont...
true
597023e28d4b38161e6a5fad504c54278e1389d6
johnarley2007/UPB
/PYTHON/SumaDosNumeros.py
1,725
4.125
4
print ("Bienvenido al programa inicial, que calcula la suma de dos números.") print ("********************************************************************") a=input ("Por favor escriba el primer número: ") b=input ("Por favor escriba el segundo número: ") a1=int(a) b1=int(b) resultado=a1+b1 print ("Esta es la suma de l...
false
682029f90434b9087e0c6cb55cf9b51e262d5f2b
HARIDARUKUMALLI/devops-freshers
/Bhaskar_Folder/python scripting/pallindrome.py
279
4.21875
4
print("enter a number") num=int(input()) temp=num pnum=0 r=0 while temp>0: r=temp%10 pnum=pnum*10+r temp=temp//10 if(num==pnum): print("the given number "+ str(num) +" is a pallindrome") else: print("the given number "+ str(num) +" is not a pallindrome")
false
26b555ce40fec377f30e19cf0d8be4559c9333a3
rajgubrele/hakerrank_ds_linkedlist_python
/GitHub Uploaded(6).py
1,341
4.40625
4
#!/usr/bin/env python # coding: utf-8 # ## # Linked Lists ---> Insert a Node at the Tail of a Linked List # # You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head nod...
true
071257cb1b4d48596a33736dc019efa68b75a599
omarv94/Python
/HelloWord.py
1,302
4.1875
4
# print ("hello word") # numero1 =int(input('Ingrese numero 1 : ')) # numero2 =int(input('Ingrese numero 2 : ')) # numero3 =int(input('Ingrese numero 3 : ')) # if numero1 == numero2 and numero1 == numero3: # print('Empate') # elif numero1 == numero2 and numero1 > numero3: # print('numero uno y numero dos son m...
false
4d375df74abf5ab4144f3b0c1f03d1ab0a1bd7b9
zhouyangf/ichw
/pyassign1/planets.py
2,088
4.375
4
"""planets.py:'planets.py' is to present a animation of a simplified planetary system. __author__ = "Zhou Yangfan" __pkuid__ = "1600017735" __email__ = "pkuzyf@pku.edu.cn" """ import turtle import math def planets(alist): """This fuction can be used to present a animation of a simplified planetary system....
true
70fde40430c1bfb1690917e8723c1dab3eb2ec25
Asurada2015/Python-Data-Analysis-Learning-Notes
/Pythontutorials/7_8_9ifjudgement_demo.py
866
4.28125
4
# x = 1 # y = 2 # z = 3 # if x < y < z: # print('x is less tha y ,and y is less than z') # x is less tha y ,and y is less than z # x = 1 # y = 2 # z = 0 # if x < y > z: # print('x is less than y, and y is less than z') # x is less than y, and y is less than z # x = 2 # y = 2 # z = 0 # # if x != y: # x == y #...
false
e12225a9370f69a16dae31fbf89e58334cdc33d4
Asurada2015/Python-Data-Analysis-Learning-Notes
/Pythontutorials/21_tupleAndlist_demo.py
394
4.28125
4
"""元组和列表""" # 元组利用()进行表示 # 列表用[]进行表示 a_tuple = (12, 3, 5, 15, 6) # 元祖的表示也可以不加上() another_tuple = 2, 4, 6, 7, 8 a_list = (12, 3, 67, 7, 82) # 遍历 for content in a_list: print(content) for content in a_tuple: print(content) for index in range(len(a_list)): print('index=', index, 'number of index', a_list[ind...
false
0b8576c1b56616cb0c5670e34c219393a4dbb0a3
robotlightsyou/pfb-resources
/sessions/002-session-strings/exercises/swap_case.py
1,668
4.65625
5
#! /usr/bin/env python3 ''' # start with getting a string from the user start = input("Please enter the text you want altered: ") # you have to declare your variable before you can add to it in the loop output = "" for letter in start: # check the case of the character and return opposite if alphabetical # i...
true
1b2f01a13a7a3c06ee81bba16a1e1f48d2395f76
aishwarydhare/clock_pattern
/circle.py
816
4.375
4
# Python implementation # to print circle pattern import math # function to print circle pattern def printPattern(radius): # dist represents distance to the center # for horizontal movement for i in range((2 * radius) + 1): # for vertical movement for j in range((2 * radius) + 1): ...
true
c5af48ec69547612a320bdd702e6459ba063fa19
smartkot/desing_patterns
/creational/abstract_factory.py
1,073
4.46875
4
""" Abstract factory. Provide an interface for creating families of related or dependent objects without specifying their concrete classes. """ class AbstractFactory(object): def create_phone(self): raise NotImplementedError() def create_network(self): raise NotImplementedError() class Pho...
true
716a00c586059ea21b993b45fd63484701b35ddb
merlose/python-exercises
/while_loops.py
1,514
4.125
4
# the variable below counts up until the condition is false number = 1 while number <= 5: print (number) number = number + 1 print ("Done...") # don't forget colons at ends of statements example2 = 50 while example2 >= 1: print (example2) example2 = example2 / 5 print ("Finish")...
true
8ba0ae06c3eee4a3a3b8572c714a9f34566cd78d
amalmhn/PythonDjangoProjects
/diff_function/var_arg_methods.py
635
4.28125
4
# def add(num1,num2): # res=num1+num2 # print(res) # # add(10,20) #variable length argument methods def add(*args): # "*" will help to input infinite arguments total=0 for num in args: total+=num print(total) #values will accpet as tuple add(10,20) add(10,20,30) add(10,11,12,13,14) pri...
true
7995ded5977d1ff9af72d6e9e31ec84b39b398da
JuanAntonaccio/Master_Python
/exercises/06-previous_and_next/app.py
268
4.28125
4
#Complete the function to return the previous and next number of a given numner.". def previous_next(num): a=num-1 b=num+1 return a,b #Invoke the function with any interger at its argument. number=int(input("ingrese un numero: ")) print(previous_next(number))
true
8733e32ae529b1f56f1931d019a70f78ac018ab4
daru23/my-py-challenges
/finding-percentage.py
1,267
4.1875
4
""" You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user ...
true
e441d23235c744a5b2d20d239307ddf4d13f3b63
evelandy/text-based-temperature-Converter
/tempConverter.py
2,067
4.3125
4
#!/usr/bin/env python3 """evelandy/W.G. Nov. 29 2018 7:16pm text-based-temperature-converter Python36-32 """ def celsius(fahr): return "{} degrees fahrenheit converted is {} degrees celsius".format(temp, int((5 / 9) * (fahr - 32))) def fahrenheit(cel): return "{} degrees celsius converted is {} degrees fahre...
false
26c7ace59a7074f0584cd63e7f21eedc2159579e
ephreal/CS
/searching/python/binary_search.py
549
4.21875
4
def binary_search(search_list, target): """" An implementation of a binary search in python. Returns the index in the list if the item is found. Returns None if not. """ first = 0 last = len(search_list) - 1 while first <= last: midpoint = (first + last) // 2 if search...
true
7f8ca8e54858853fb057e7076eed9b9c634b82b6
PacktPublishing/The-Complete-Python-Course
/1_intro/lectures/15_dictionaries/code.py
921
4.625
5
friend_ages = {"Rolf": 24, "Adam": 30, "Anne": 27} print(friend_ages["Rolf"]) # 24 # friend_ages["Bob"] ERROR # -- Adding a new key to the dictionary -- friend_ages["Bob"] = 20 print(friend_ages) # {'Rolf': 24, 'Adam': 30, 'Anne': 27, 'Bob': 20} # -- Modifying existing keys -- friend_ages["Rolf"] = 25 print(fr...
true
8c8020d86d108df7264b3448c4f6cbfa6c6fc7a3
PacktPublishing/The-Complete-Python-Course
/10_advanced_python/lectures/05_argument_unpacking/code.py
2,507
4.90625
5
""" * What is argument unpacking? * Unpacking positional arguments * Unpacking named arguments * Example (below) Given a function, like the one we just looked at to add a balance to an account: """ accounts = { 'checking': 1958.00, 'savings': 3695.50 } def add_balance(amount: float, name: str) -> float: ...
true
85748dc41cd9db69df420983540035e866d89a7e
PacktPublishing/The-Complete-Python-Course
/2_intro_to_python/lectures/7_else_with_loops/code.py
591
4.34375
4
# On loops, you can add an `else` clause. This only runs if the loop does not encounter a `break` or an error. # That means, if the loop completes successfully, the `else` part will run. cars = ["ok", "ok", "ok", "faulty", "ok", "ok"] for status in cars: if status == "faulty": print("Stopping the producti...
true
533360c4d458f8e2fc579b60af0441f5ec49ec17
PacktPublishing/The-Complete-Python-Course
/6_files/files_project/friends.py
735
4.3125
4
# Ask the user for a list of 3 friends # For each friend, we'll tell the user whether they are nearby # For each nearby friend, we'll save their name to `nearby_friends.txt` friends = input('Enter three friend names, separated by commas (no spaces, please): ').split(',') people = open('people.txt', 'r') people_nearby...
true
c712a62a9b104cbb2345f00b18dfdee6712d5c0c
PacktPublishing/The-Complete-Python-Course
/2_intro_to_python/lectures/15_functions/code.py
894
4.3125
4
# So far we've been using functions such as `print`, `len`, and `zip`. # But we haven't learned how to create our own functions, or even how they really work. # Let's create our own function. The building blocks are: # def # the name # brackets # colon # any code you want, but it must be indented if you want it to run...
true
fab51111c8d19f063d67d289cfeef4c9a71bb801
PacktPublishing/The-Complete-Python-Course
/7_second_milestone_project/milestone_2_files/app.py
1,197
4.1875
4
from utils import database USER_CHOICE = """ Enter: - 'a' to add a new book - 'l' to list all books - 'r' to mark a book as read - 'd' to delete a book - 'q' to quit Your choice: """ def menu(): database.create_book_table() user_input = input(USER_CHOICE) while user_input != 'q': if user_input ...
true
42677deb29fcb61c5aeff5b093742d97952c9e27
PacktPublishing/The-Complete-Python-Course
/10_advanced_python/lectures/10_timing_your_code/code.py
1,661
4.5
4
""" As well as the `datetime` module, used to deal with objects containing both date and time, we have a `date` module and a `time` module. Whenever you’re running some code, you can measure the start time and end time to calculate the total amount of time it took for the code to run. It’s really straightforward: """...
true
90aa93be4b574939d568c13f67129c50c4f34d19
ItzMeRonan/PythonBasics
/TextBasedGame.py
423
4.125
4
#--- My Text-Based Adventure Game --- print("Welcome to my text-based adventure game") playerName = input("Please enter your name : ") print("Hello " + playerName) print("Pick any of the following characters: ", "1. Tony ", "2. Thor ", "3. Hulk", sep='\n') characterList = ["Tony", "Thor", "Hulk"] characterNumber = ...
true
5d9f81915ee5b355e49e86ed96da385f40c81280
Zerobitss/Python-101-ejercicios-proyectos
/practica47.py
782
4.1875
4
""" Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del cu...
false
975c2263afb1696d97671eba3731aa05349ee3f4
Zerobitss/Python-101-ejercicios-proyectos
/practica1.py
1,668
4.125
4
""" Una juguetería tiene mucho éxito en dos de sus productos: payaso y muñeca. Suele hacer venta por correo y la empresa de logística les cobra por peso de cada paquete así que deben calcular el peso de los payasos y muñecas que saldrán en cada paquete a demanda. Cada payaso pesa 112 g y la muñeca 75 g. Escribir un pro...
false
96cffff7188de858043be7752354bdf527b6042c
Zerobitss/Python-101-ejercicios-proyectos
/practica85.py
1,985
4.46875
4
""" Escribir una función que simule una calculadora científica que permita calcular el seno, coseno, tangente, exponencial y logaritmo neperiano. La función preguntará al usuario el valor y la función a aplicar, y mostrará por pantalla una tabla con los enteros de 1 al valor introducido y el resultado de aplicar la fun...
false
23c8d095e97226e3c7558de15a692abda0bd0e01
kunal-singh786/basic-python
/ascii value.py
219
4.15625
4
#Write a program to perform the Difference between two ASCII. x = 'c' print("The ASCII value of "+x+" is",ord(x)) y = 'a' print("The ASCII value of "+y+" is",ord(y)) z = abs(ord(x) - ord(y)) print("The value of z is",z)
true
8173f27556c3d20308fed59059819a509afaf083
marianraven/estructuraPython
/ejercicio7.py
287
4.15625
4
#Escribir un programa que pregunte el nombre del usuario por consola y luego imprima #por pantalla la cadena “Hola <nombre_usuario>”. Donde <nombre_usuario> es el #nombre que el usuario introdujo. nombreIngresado= str(input('Ingrese su nombre:')) print('Hola......', nombreIngresado)
false
de2c66cc004eae8ba588f8e775fc8266e9867df5
jbascunan/Python
/1.Introduccion/2.diccionarios.py
966
4.3125
4
# las llaves puede ser string o enteros diccionario = { 'a': 1, 'b': 2, 'c': 3 } # diccionario de llave enteros diccionario1 = { 1: "nada", 2: "nada2" } print(diccionario1) # agregar clave/valor diccionario['d'] = 4 # modifica valor diccionario['e'] = 5 # si la llave existe se actualiza sino la c...
false
87a6d5e514a8d472b5fe429ddf28190fb3e38547
EddieMichael1983/PDX_Code_Guild_Labs
/RPS.py
1,514
4.3125
4
import random rps = ['rock', 'paper', 'scissors'] #defining random values for the computer to choose from user_choice2 = 'y' #this sets the program up to run again later when the user is asked if they want to play again while user_choice2 == 'y': #while user_choice2 == y is TRUE the program keeps going user...
true
698c8d06b87bda39846c76dff4ddb1feb682cf4f
ManchuChris/MongoPython
/PrimePalindrome/PrimePalindrome.py
1,739
4.1875
4
# Find the smallest prime palindrome greater than or equal to N. # Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. # For example, 2,3,5,7,11 and 13 are primes. # Recall that a number is a palindrome if it reads the same from left to right as it does from right to left. # ...
true
ebe3d0b8c5d85eb504e9c68c962c1fa8343eab3b
aartis83/Project-Math-Painting
/App3.py
2,137
4.1875
4
from canvas import Canvas from shapes import Rectangle, Square # Get canvas width and height from user canvas_width = int(input("Enter the canvas width: ")) canvas_height= int(input("Enter the canvas height: ")) # Make a dictionary of color codes and prompt for color colors = {"white": (255, 255, 255), "blac...
true
c7a71766c0e273939c944342abd04ad7c6043f51
MrLawes/quality_python
/12_不推荐使用type来进行类型检查.py
2,031
4.4375
4
""" 作为动态性的强类型脚本语言,Python中的变量在定义的时候并不会指明具体类型,Python解释器会在运行时自动进行类型检查并根据需要进行隐式类型转换。按照Python的理念,为了充分利用其动态性的特征是不推荐进行类型检查的。如下面的函数add(),在无需对参数进行任何约束的情况下便可以轻松地实现字符串的连接、数字的加法、列表的合并等多种功能,甚至处理复数都非常灵活。解释器能够根据变量类型的不同调用合适的内部方法进行处理,而当a、b类型不同而两者之间又不能进行隐式类型转换时便抛出TypeError异常。 """ def add(a, b): return a + b """ 不刻意进行类型检查,而是在出错的情...
false
c047864044d2270efeef97adf40483da5cdbeced
MrLawes/quality_python
/10_充分利用Lazy evaluation的特性.py
1,057
4.25
4
""" Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面: 1)避免不必要的计算,带来性能上的提升。对于Python中的条件表达式if x and y, 在x为false的情况下y表达式的值将不再计算。而对于if x or y, 当x的值为true的时候将直接返回,不再计算y的值。因此编程中应该充分利用该特性。 """ """ 2)节省空间,使得无限循环的数据结构成为可能。Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素...
false
d202ee1b2a40990f05daa809841df5bab91c8c9e
sharatss/python
/techgig_practice/age.py
1,547
4.15625
4
""" Decide yourself with conditional statement (100 Marks) This challenge will help you in clearing your fundamentals with if-else conditionals which are the basic part of all programming languages. Task: For this challenge, you need to read a integer value(default name - age) from stdin, store it in a variable and...
true
a9786b118e8755d0b94e2318f514f27d7eeaa263
sharatss/python
/techgig_practice/special_numbers.py
1,070
4.125
4
""" Count special numbers between boundaries (100 Marks) This challenge will help you in getting familiarity with functions which will be helpful when you will solve further problems on Techgig. Task: For this challenge, you are given a range and you need to find how many prime numbers lying between the given range....
true
e6c0effb856be274dabe3f6fc6913cf9a5d1440b
alyhhbrd/CTI110-
/P3HW1_ColorMixer_HubbardAaliyah.py
1,225
4.3125
4
# CTI-110 # P3HW1 - Color Mixer # Aaliyah Hubbard # 03032019 # # Prompt user to input two of three primary colors; output as error code if input color is not primary # Determine which secondary color is produced of two input colors # Display secondary color produced as output # promt user for input print('LET`S MIX ...
true
df088fb37c67578d8327ad3fd90b2eebfaba85dd
dk4267/CS490
/Lesson1Question3.py
1,151
4.25
4
#I accidentally made this much more difficult than it had to be inputString = input('Please enter a string') #get input outputString = '' #string to add chars for output index = 0 #keeps track of where we are in the string isPython = False #keeps track of whether we're in the middle of the word 'python' for ch...
true
67b81266248d8fb5394b5ffbd7a950a2ae38f5b2
appsjit/testament
/LeetCode/soljit/s208_TrieAddSearchSW.py
2,080
4.125
4
class TrieNode: def __init__(self, value=None): self.value = value self.next = {} self.end = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word: str) -> None: """ ...
true
3d72b16a663cdd2f59f293615dbe063462f877dd
forat19-meet/meet2017y1lab3
/helloWorld.py
2,137
4.375
4
>>> print("hello world") hello world >>> print('hello world') hello world >>> print("hello gilad") hello gilad >>> # print("Hello World!") >>> print("Γειά σου Κόσμε") Γειά σου Κόσμε >>> print("Olá Mundo") Olá Mundo >>> print("Ahoj světe") Ahoj světe >>> print("안녕 세상") 안녕 세상 >>> print("你好,世界") 你好,世界 >>> print("नमस्ते दु...
false
5db6b90a933778253e1c023dce68643d026d367b
voitenko-lex/leetcode
/Python3/06-zigzag-conversion/zigzag-conversion.py
2,703
4.28125
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conv...
true
6303d1c3706e99b0bbd18d019cd124323d4d90e4
adamabad/WilkesUniversity
/cs125/projects/weights.py
1,289
4.25
4
# File: weights.py # Date: October 26, 2017 # Author: Adam Abad # Purpose: To evaluate pumpkin weights and average their total def info(): print() print("Program to calculate the average of a") print("group of pumpkin weights.") print("You will be asked to enter the number of") print("pumpkins...
true
02cdf23d234d56f3de0f9af1fed602ecaeb3046e
moniqueds/FundamentosPython-Mundo1-Guanabara
/ex033.py
733
4.3125
4
#Faça um programa que leia três números e mostre qual é maior e qual é o menor. from time import sleep print('Você irá informar 3 números a seguir...') sleep(2) a = int(input('Digite o primeiro número: ')) b = int(input('Digite o segundo número: ')) c = int(input('Digite o terceiro número: ')) print('Analisand...
false
671b743b1a208bb2f23e00ca96acad7710bd932f
slutske22/Practice_files
/python_quickstart_lynda/conditionals.py
1,192
4.21875
4
# %% raining = input("Is it raining outside? (yes/no)") if raining == 'yes': print("You need an umbrella") # %% userInput = input("Choose and integer between -10 and 10") n = int(userInput) if n >= -10 & n <= 10: print("Good Job") # %% def minimum(x, y): if x < y: return x else: retu...
true
19830b17fe1289929e9d9d7f6312715ea6cafeb7
SDSS-Computing-Studies/006b-more-functions-ye11owbucket
/problem2.py
774
4.125
4
#!python3 """ ##### Problem 2 Create a function that determines if a triangle is scalene, right or obtuse. 3 input parameters: float: one side float: another side float: 3rd side return: 0 : triangle does not exist 1 : if the triangle is scalene 2 : if the triangle is right 3 : if the triangle is obtuse Sam...
true
e935b348e9f40316060ccab9f045ce3b7151a1fe
scriptedinstalls/Scripts
/python/strings/mystrings.py
574
4.25
4
#!/usr/bin/python import string message = "new string" message2 = "new string" print message print "contains ", len(message), "characters" print "The first character in message is ", message[0] print "Example of slicing message", message, "is", message[0:4] for letter in message: print letter if message == m...
true
e6b681234935ea15b7784a76d9921a900e137e7f
hboonewilson/IntroCS
/Collatz Conjecture.py
885
4.46875
4
#Collatz Conjecture - Start with a number n > 1. Find the number of steps it... #takes to reach one using the following process: If n* is even, divide it by 2. #If *n is odd, multiply it by 3 and add 1. collatz = True while collatz: input_num = int(input("Give me a number higher than 1: ")) if input_...
true
85299f7db32018c1b3be12b6ebdae3c521fe3842
HenriqueSamii/TP1-Fundamentos-de-Programa-o-com-Python
/tp1IntroPiton11.py
285
4.40625
4
#11. Faça uma função no Python que, utilizando a ferramenta turtle, desenhe um triângulo de lado N. import turtle def triangulo(n): for target_list in range(3): turtle.forward(int(n)) turtle.left(120) x = input("Tamanho do triângulo - ") triangulo(x)
false
84e2b62c922b04f427741fd805c3705f657783ea
HenriqueSamii/TP1-Fundamentos-de-Programa-o-com-Python
/tp1IntroPiton5.py
2,316
4.375
4
#5. Trabalhar com tuplas é muito importante! Crie 4 funções nas quais: # # 1.Dada uma tupla e um elemento, verifique se o elemento existe na tupla # e retorne o indice do mesmo # 2.Dada uma tupla, retorne 2 tuplas onde cada uma representa uma metade da tupla original. # 3.Dada uma tupla e um elemento, elimine esse el...
false
2a251fb6764b5d54e052d754a0931951e0c590a7
AWOLASAP/compSciPrinciples
/python files/pcc EX.py
343
4.28125
4
''' This program was written by Griffin Walraven It prints some text to the user. ''' #Print text to the user print("Hello!! My name is Griffin Walraven.") #input statement to read name from the user name = input("What is yours? ") print("Hello ", name, "!! I am a student at Hilhi.") print("I am in 10th grade an...
true
3bc172ed239a7420049479378bc660dab7ce772e
ambikeshkumarsingh/LPTHW_ambikesh
/ex3.py
477
4.25
4
print("I will count my chickens:" ) print("Hens", 25 +30/6) print("Roosters",100-25*3 %4) print("Now I will count the eggs") print(3 + 2 + 1- 5 + 4 % 2-1 /4 + 6) print("Is is true that 3+2<5-7") print(3+2<5-7) print("What is 3+2 ? ", 3+2) print("What is 5-7 ?", 5-7) print("Oh! that's why It is fa...
true
cffc2440c9d7945fe89f9cc7d180ee484f0a7689
bartoszkobylinski/tests
/tests/tests.py
1,544
4.3125
4
import typing import unittest from app import StringCalculator ''' class StringCalculator: def add(self, user_input: str) -> int: if user_input is None or user_input.strip() == '': return 0 else: numbers = user_input.split(',') result = 0 ...
true
e465bf117aef5494bb2299f3f2aaa905fb619b52
purple-phoenix/dailyprogrammer
/python_files/project_239_game_of_threes/game_of_threes.py
1,346
4.25
4
## # Do not name variables "input" as input is an existing variable in python: # https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python # # By convention, internal functions should start with an underscore. # https://stackoverflow.com/questions/11483366/protected-method-in-python ## ## # @param o...
true
40dcaf6d0f51e671ed643d3c49d2071ed65df207
yb170442627/YangBo
/Python_ex/ex25_1.py
339
4.34375
4
# -*- coding: utf-8 -*- def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) words = "where are you come from?" word = break_words(words) print word word1 = sort_words...
true
a5341d137334ccca3977d0c4b85f17feeeaca78c
yb170442627/YangBo
/Python_ex/ex39.py
457
4.125
4
# -*- coding: utf-8 -*- cities = {'SH': 'ShangHai', 'BJ': 'BeiJing','GZ': 'GanZhou'} cities['GD'] = 'GuangDong' cities['SD'] = 'ShanDong' def find_city(themap, state): if state in themap: return themap[state] else: return "Not Found." cities['_find'] = find_city while True: print "State?(E...
false
448f476ddbd8ec3582c3913c8926f3181dfb8cf7
yb170442627/YangBo
/Python_ex/ex33_1.py
831
4.1875
4
# -*- coding: utf-8 -*- def append_num(num): # 定义了一个append_num(num)函数 i = 0 # 声明了一个常量 i numbers = [] # 声明了一个空的列表 numbers = [] while i < num: # 执行while循环 print "At the top i is %d" % i numbers.append(i) #调用列表的append方法,当i< num成立的时候,把i的值追加到numbers这个空的列表中 i = i ...
false
b86bc57163990cb644d6449b1e70a5eb435325b4
Green-octopus678/Computer-Science
/Need gelp.py
2,090
4.1875
4
import time import random def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y score = 0 operator = 0 question = 0 #This part sets the variables for the question number, score and the operator print('Welcome to my brilliant maths quiz\n') time.sleep(1.5) print() prin...
true
a5f3fdde75ca1ba377ace30608a3da5012bb5937
itspratham/Python-tutorial
/Python_Contents/Python_Loops/BreakContinue.py
443
4.21875
4
# User gives input "quit" "Continue" , "Inbvalid Option" user_input = True while user_input: user_input = str(input("Enter the valid input:")) if user_input == "quit": print("You have entered break") break if user_input == "continue": print("You habe entered continue") conti...
true
7563439f6f667bbe4c71a7256353dcf50de0ee8c
itspratham/Python-tutorial
/Python_Contents/data_structures/Stacks/stacks.py
1,842
4.21875
4
class Stack: def __init__(self): self.list = [] self.limit = int(input("Enter the limit of the stack: ")) def push(self): if len(self.list) < self.limit: x = input("Enter the element to be entered into the Stack: ") self.list.append(x) return f"{x} in...
true
2bdc343f4849c59a59823ce162851b6fb846c280
itspratham/Python-tutorial
/Python_Contents/data_structures/Array_Rearrangement/2.py
413
4.34375
4
# Write a program to reverse an array or string # Input : arr[] = {1, 2, 3} # Output : arr[] = {3, 2, 1} # # Input : arr[] = {4, 5, 1, 2} # Output : arr[] = {2, 1, 5, 4} def arrae(arr): l1 = [] n = len(arr) # i=0 # while i<n: # l1.append(arr[n-i-1]) # n = n-1 for i in range(n): ...
false
1c92251342d8af5183a31dd0d3bcff67fca50a81
itspratham/Python-tutorial
/Python_Contents/Python_Decision_Statements/IfElseif.py
333
4.15625
4
# Time 00 to 23 # Input the time from the user tm = int(input("Enter the time:")) if 6 < tm < 12: print("Good Morning") elif 12 < tm < 14: print("Good Afternoon") elif 14 < tm < 20: print("Good Evening") elif 20 < tm < 23: print("Good Night") elif tm < 6: print("Early Morning") else: print("In...
false
eaa4cb4848a01460f115a9dec5fe56ef329fc578
Blu-Phoenix/Final_Calculator
/runme.py
2,632
4.40625
4
""" Program: Final_Calculator(Master).py Developer: Michael Royer Language: Python-3.x.x Primum Diem: 12/2017 Modified: 03/28/2018 Description: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over. Input: The user will be asked f...
true
449219be2325b86c67ba461085f50b70fffbe537
yujunjiex/20days-SuZhou
/day01/task05.py
1,552
4.125
4
# coding: UTF-8 """ 卡拉兹(Callatz)猜想: 对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。 这样一直反复砍下去,最后一定在某一步得到n=1。 卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题, 结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展…… 我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1? 输入格式:每个测试输入包含...
false
1aa2f192350934e720cb2546d7a7eebf9e09732e
un1xer/python-exercises
/zippy.py
1,073
4.59375
5
# Create a function named combo() that takes two iterables and returns a list of tuples. # Each tuple should hold the first item in each list, then the second set, then the third, # and so on. Assume the iterables will be the same length. # combo(['swallow', 'snake', 'parrot'], 'abc') # Output: # [('swallow', 'a'), ('...
true
b7f4f3872363f50ad2649090dd3437614be8230d
tshihui/pypaya
/programmingQuestions/fibonacci.py
756
4.25
4
############### ## Fibonacci ## ## 2/2/2019 ## ############### def fib(n): """ Fibonacci sequence """ if n == 1 : return([0]) print('The first ', n, ' numbers of the Fibonacci sequence is : [0]') elif n == 2: return([0,1]) print('The first ', n, ' numbers of the Fibonacci se...
false
d5688cef9797d4ab6a2f8c48a36bb813e317600f
goufix-archive/py-exercises
/exercicios/sequencial/18.py
1,643
4.125
4
import math name = 'alifer' # Faça um Programa para uma loja de tintas. O programa deverá pedir # o tamanho em metros quadrados da área a ser pintada. # Considere que a cobertura da tinta é de 1 litro para cada # 6 metros quadrados e que a tinta é vendida em latas de 18 litros, # que custam R$ 80,00 ou em galões de 3,6...
false
eb9560d4677463b71c5b709a4f1f6013c0c26314
brunolcarli/AlgoritmosELogicaDeProgramacaoComPython
/livro/code/sistemaPython/main.py
1,011
4.28125
4
import funcionalidades #importa o modulo de funcionalidades que criamos while True: #criamos um loop para o programa print('#'*34) #fornecemos um menu de opcoes print(">"*11,"BEM-VINDO","<"*11) print("Escolha a operacao desejada") print("[1] Cadastrar produto") prin...
false
fc80005a87f4659595c0e83bef75e7c1e2c22cef
brunolcarli/AlgoritmosELogicaDeProgramacaoComPython
/livro/code/capitulo6/exemplo53.py
451
4.1875
4
def quadrado(numero): #a definicao de uma funcao e igual a de um procedimento return numero**2 #usamos a instrucao return para retornar um valor entrada = int(input("Insira um numero: ")) #pedimos um numero quad = quadrado(entrada) #chamamos a funcao e guardamos o retorno em quad print("O quadrado de %i e %i" %...
false
b2eb47334a63860d472823f9a3bc5814ee3780e7
mariagarciau/EjAmpliacionPython
/ejEscalera.py
795
4.375
4
"""Esta es una escalera de tamaño n= 4: # ## ### #### Su base y altura son iguales a n. Se dibuja mediante #símbolos y espacios. La última línea no está precedida por espacios. Escribe un programa que imprima una escalera de tamaño n . Función descriptiva Complete la función de staircase. staircase tiene los sigu...
false
983a91b383f63fedd4ba16a2cb8f2eaceaffc57a
rlugojr/FSND_P01_Movie_Trailers
/media.py
926
4.3125
4
'''The media.Movie Class provides a data structure to store movie related information''' class Movie(): '''The media.Movie constructor is used to instantiate a movie object. Inputs (required): movie_title --> Title of the movie. movie_year --> The year the movie was released. ...
true
b79f79e1f9631e96d485282e5024d7bc917a01bf
egreenius/ai.python
/Lesson_4/hw_4_6.py
1,879
4.28125
4
''' Home work for Lesson 4 Exercise 6 6. Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, б) итератор, повторяющий элементы некоторого списка, определенного заранее. Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл...
false
e93bd1d37465c9976728899914d468b036f3b1f3
kannan5/Algorithms-And-DataStructures
/Queue/queue_py.py
829
4.21875
4
""" Implement the Queue Data Structure Using Python Note: In This Class Queue was implemented using Python Lists. List is Not Suitable or Won't be efficient for Queue Structure. (Since It Takes O(n) for Insertion and Deletion). This is for Understanding / Learning Purpose. """ cl...
true
8e5c3324d1cf90eb7628bf09eca7413260e39cb7
kannan5/Algorithms-And-DataStructures
/LinkedList/circularlinkedlist.py
2,310
4.3125
4
"Program to Create The Circular Linked List " class CircularLinkedList: def __init__(self): self.head = None def append_item(self, data_val): current = self.head new_node = Node(data_val, self.head) if current is None: self.head = new_node new_node.next...
true
193052cadf507e12e1d77e76fff1989b3e9e396a
Tiger-C/python
/python教程/第七集.py
1,238
4.25
4
#第七集 # #``````````````````````start````````````````````````````````````` # nums=[1,2,3,4,5]#此行必开 # for num in nums: # if num == 3: # print('Found!') # break #停止 # print(num) # for num in nums: # if num == 3: # print('Found!') # continue #继续 # print(num) # for num in nums: # for le...
false
03b1ff13856c5d60fdcaf16916aca5f5acc6dff4
xingyunsishen/Python_CZ
/51-对象属性和方法.py
830
4.125
4
#-*- coding:utf-8 -*- '''隐藏对象的属性''' """ #定义一个类 class Dog: def set_age(self, new_age): if new_age > 0 and new_age <= 100: self.age = new_age else: self.age = 0 def get_age(self): return self.age dog = Dog() dog.set_age(-10) age = dog.get_age() print(age) dog.a...
false
952b645f8ba4d792112e905bc646976bec523670
blairsharpe/LFSR
/LFSR.py
1,205
4.125
4
def xor(state, inputs, length, invert): """Computes XOR digital logic Parameters: :param str state : Current state of the register :param list inputs: Position to tap inputs from register Returns: :return output: Output of the XOR gate digital logic :rtype int : """ ...
true