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 integer: ")
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 ## add side a and b sum_ab = pow_a + pow_b pow_c -= sum_ab angle_C = acos(pow_c / a_b) #convert result to degrees print("Angle C = ", degrees(angle_C)) #Find angle B when side a = 9, b = 3, c = 7 #Square all sides pow_a = side_a**2 pow_b = side_b**2 pow_c = side_c**2 a_c = -(2 * side_a * side_c); ## add side a and b sum_ac = pow_a + pow_c pow_b -= sum_ac angle_B = acos(pow_b / a_c) print("Angle B = ", degrees(angle_B)) #Find angle A when side a = 9, b = 3, c = 7 #Square all sides pow_a = side_a**2 pow_b = side_b**2 pow_c = side_c**2 b_c = -(2 * side_b * side_c); ## add side b and c sum_bc = pow_b + pow_c pow_a -= sum_bc angle_A = acos(pow_a / b_c) print("Angle B = ", degrees(angle_A))
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 listComp = [x + " " + y for x, y in zipped] # print(list(listComp)) # ['Dorky Dorkerton', 'Jimbo Smith', 'Jeff Johnson'] # The Map way f = lambda a : a[0] + " " + a[1] listComp = map(f, zipped) f = lambda a,b: a + ", " + b result = reduce(f, listComp) # Dorky Dorkerton, Jimbo Smith, Jeff Johnson # print(type(result)) # <type 'str'> return result def main(): first = ['Dorky', 'Jimbo', 'Jeff'] second = ['Dorkerton', 'Smith', 'Johnson'] print(combineTwoLists(first, second)) if __name__ == "__main__": main()
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 available" # print(a,b,end="." "its raining",sep=" ") # print(c) #food from swiggy.its raining not available """ escape seqences""" # print("hello\tworld") # print("hello\nworld") # print("hello\bworld") # print("hello\'world") # print("hello\"world") # print("hello\\world") # print("hello\aworld") #helloworld # print("hello\bworld") #hellworld # print("hello\cworld") # print("hello\dworld") # print("hello\eworld") # print("hello\fworld") #hello♀world # print("hello\gworld") # print("hello\hworld") # print("hello\iworld") # print("hello\jworld") # print("hello\kworld") # print("hello\lworld") # print("hello\mworld") # print("hello\nworld") #hello # world # print("hello\oworld") # print("hello\pworld") # print("hello\qworld") # print("hello\rworld") #world # print("hello\sworld") # print("hello\tworld") #hello world # print("hello\uworld") #SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes # print("hello\vworld") #hello♂world # print("hello\wworld") # print("hello\xworld") #SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes # print("hello\yworld") # print("hello\zworld")
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=str(x) # print("the value of z is"+z) #the value of z is10 """float---->int,string""" # a=12.5 # print(a,type(a)) #12.5 <class 'float'> # b=int(a) # print(b,type(b)) #12 <class 'int'> # c=str(b) # print(c,type(c)) #12 <class 'str'> """string--->int,float""" m="python" print(m,type(m)) #python <class 'str'> # n=int(m) # print(n,type(n)) #ValueError: invalid literal for int() with base 10: 'python' # o=float(m) # print(o,type(o)) #ValueError: could not convert string to float: 'python' # x="125" # print(x,type(x)) #125 <class 'str'> # y=int(x) # print(x,type(y)) #125 <class 'int'> # z=float(x) # print(z,type(z)) #125.0 <class 'float'>
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("zoom"))
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 = int(input("Denominador: ")) # 0 r = a / b except Exception as erro: print(f"Problema encontrado foi {erro.__class__}") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO") print("="*50) # Outro formato de tratamento de exceção, agora com varias exceções/erros try: a = int(input("Num: ")) # 8 b = int(input("Denominador: ")) # 0 r = a / b except (ValueError, TypeError): print(f"Problema com os tipos de dados digitados") except ZeroDivisionError: print("Não é possível dividir um numero por zero ") except KeyboardInterrupt: print("O usuario optou por nao informar os dados") except Exception as erro: print(f"Erro encontrado foi {erro.__cause__}") else: print(f"resposta: {r}") # Divisão por zero --> erro finally: print("FIM DO CODIGO")
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("Digite um valor: ")) lista.append(valor) c += 1 r = str(input("Deseja continuar? [S/N] ")).strip().upper() while r not in "SsNn": r = str(input("Deseja continuar? [S/N] ")).strip().upper() if r == "N": break print(f"Você digitou {c} elementos") #posso usar len(lista) ao invés de um contador lista.sort(reverse=True) print(f"Os valores em ordem decrescente são: {lista}") if 5 in lista: print("O valor 5 faz parte da lista!") else: print("O valor 5 não faz parte da lista!")
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("Digite um valor: ")) if valor not in Lista: Lista.append(valor) print("Valor adicionado! ") else: print("Valor duplicado! Não vou adicionar na lista! ") continuar = str(input("Quer continuar [S/N] ? ")).strip().upper() if continuar == "N": break Lista.sort() print(f"Você digitou os valores {Lista}")
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(): print(name, '\n', age, '\n', num) break else: print("Name must only contain alphabets. Age must be greater than 18. Age and Number must be numeric...")
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 in the same SDM format as the input. Some puzzles will not be solvable. In that case, return the string "Unsolvable". https://realpython.com/python-practice-problems/#python-practice-problem-1-sum-of-a-range-of-integers The general SDM format is described here: http://www.sudocue.net/fileformats.php For our purposes, each SDM string will be a sequence of 81 digits, one for each position on the sudoku puzzle. Known numbers will be given, and unknown positions will have a zero value. For example, assume you're given this string of digits (split into two lines for readability): 0040060790000006020560923000780610305090004 06020540890007410920105000000840600100 The string represents this starting sudoku puzzle: 0 0 4 0 0 6 0 7 9 0 0 0 0 0 0 6 0 2 0 5 6 0 9 2 3 0 0 0 7 8 0 6 1 0 3 0 5 0 9 0 0 0 4 0 6 0 2 0 5 4 0 8 9 0 0 0 7 4 1 0 9 2 0 1 0 5 0 0 0 0 0 0 8 4 0 6 0 0 1 0 0 The provided unit tests may take a while to run, so be patient. """
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] i=i+1 print("Largest even: %d and Largest Odd: %d in the list" %(le,lo))
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.items(), key = lambda x : x[0])] invertdict = lambda m: {pair[1]:pair[0] for pair in m.items()} print("anagrams", anagrams(['eat', 'ate', 'done', 'tea', 'soup', 'node'])) print("valuesort", valuesort({'x': 1, 'y': 2, 'a': 3})) print("invertdict", invertdict({'x': 1, 'y': 2, 'z': 3}))
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('add("a", "b")', add("a", "b")) #after = time() #print('time taken:', after - before) #@time is a decorator from time import time def timer(func): def f(*args, **Kargs): before = time() runvalue = func(*args, **Kargs) after = time() print('elapsed', after - before) return runvalue return f @timer def add(x, y=10): return x + y @timer def sub(x, y=10): return x - y print('add(20,30)', add(20, 30)) print('add("a", "b")', add("a", "b"))
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 child class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ check = self.check_it(word,True) check.has_word = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ check = self.check_it(word) return check != None and check.has_word def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ return self.check_it(prefix) != None def check_it(self, word, add = False): check = self.root for ch in word: node = check.next(ch) if node == None: if add: node = TrieNode() node.val = ch check.children.append(node) else: return None check = node return check
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 multiplication table for {user_number}") print() for i in range(1,13): print(f" {user_number} x {i} = {user_number * i} ") print()
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 month sum = Time_code+netime_code # Print results print(f"your name is {name} and my neighbour name is {ne_name}") print("Total month coded together " +str(sum) + " months!")
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 los números ingresados: ",resultado) #***********************************************************************" print ("Bienvenido al programa inicial, que calcula la suma de dos números.") print ("********************************************************************") a=int(input ("Por favor escriba el primer número: "))#Int se utiliza para enteros b=int(input ("Por favor escriba el segundo número: ")) resultado=a+b print ("Esta es la suma de los números ingresados: ",resultado) #***********************************************************************" print ("Bienvenido al programa inicial, que calcula la suma de dos números.") print ("********************************************************************") a=float(input ("Por favor escriba el primer número: "))#Float se utiliza para décimal b=float(input ("Por favor escriba el segundo número: ")) resultado=a+b print ("Esta es la suma de los números ingresados: ",resultado) #***********************************************************************" print ("Bienvenido al programa inicial, que calcula la suma de dos números.") print ("********************************************************************") a=str(input ("Por favor escriba el primer número: "))#Float se utiliza para décimal b=str(input ("Por favor escriba el segundo número: ")) resultado=a+b print ("Esta es la suma de los números ingresados: ",resultado)
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 node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty.## # In[ ]: import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the insertNodeAtTail function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def insertNodeAtTail(head, data): new_list = SinglyLinkedListNode(data) if head is None: head = new_list else: temp = head while temp.next is not None: temp = temp.next temp.next = new_list return head if __name__ == '__main__':
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 mayores') # elif numero2 ==numero3 and numero2 > numero1: # print('numero dos y numero 3 son mayores ') # elif numero1 == numero3 and #for structure suma=0 for i in range(5): suma = suma + int(input('ingrese un nuevo numero : ')) print(suma) #while structure suma = 0 while True: suma = suma + int(input('ingrse numero : ')) stop = input('Desea cuntinuar S/si N/no') if stop != "S" and stop != "s": break print(suma) suma =0 num1 =0 num2 =0 while True: while True: num1 = int(input('ingrese un numero de el 1-5')) if num1 > 1 and num1 < 5: break else: print('numero Erroneo debe ser un numero de 1 a 5') while True: num2 = int(input('ingrese un numero de el 5-9')) if num2 > 6 and num2 <10: break else: print('numero incorrecto, Debe ser un numero entre 6 y 10') suma = suma +num1 +num2 stop = input('Desea cuntinuar S/si N/no')
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.The formal parameter of this function should be a list of turtles wh- -ich you wanna use to represent planets,such as[turtle1,turtle2,...].And the list can contain any number of turtles.However,you must put the fixed star as the first one and put the rest in order of distance to the fixed star. """ num = len(alist) for i in range(num): t = alist[i] t.shape("circle") t.speed(0) t.pu() x = i * (i + 20) ** 1.2 # set the scale of the orbit of each planet.(the fuction is assumed casually...) if i % 2 == 1: # set the initial position for each planet according to whether the ordinal number of it is odd or even. t.goto(-x * 4 / 5, -x) else: t.goto(x / 1.2, 0) t.lt(90) t.pd() for i in range(1000): for x in range(1, num): t = alist[x] r = 2 * x * (x + 20) ** 1.2 # set the scale of the orbit of each planet. a = 2 * math.pi * i / (360 / (num - x)) # "num - x" is to control the speed of each planet. l = 2 * math.pi * r / (360 / (num - x)) if x % 2 == 1: t.fd(abs(math.cos(a)) * l) else: t.fd(abs(math.sin(a)) * l) t.lt(num - x) def main(): sun, mercury, venus, earth, mars, saturn, jupiter = turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle() alist0=[sun, mercury, venus, earth, mars, saturn, jupiter] sun.color("orange") mercury.color("grey") venus.color("yellow") earth.color("blue") mars.color("red") saturn.color("brown") jupiter.color("violet") planets(alist0) if __name__ == '__main__': main()
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 # print('x is equal to y') x = 4 y = 2 z = 3 if x > y: print('x is greater than y') else: print('x is less or equal to y') """多重选择if elif else""" x = 1 if x > 1: print('x > 1') elif x < 1: print('x < 1') else: print('x = 1') x = -2 if x > 1: print('x>1') elif x < 1: print('x<1') elif x < -1: print('x<-1') else: print('x=1') print('finish running') # 只是会从前面的开始匹配,遇到满足的条件就不会进行下面的判断了 # x is greater than y # x = 1 # x<1 # finish running
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[index])
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 # isupper/islower are implicit isalpha checks as not letters aren't cased. if letter.isupper(): output += letter.lower() elif letter.islower(): output += letter.upper() else: output += letter print(output) ''' #Now lets try putting that into a function so you can call it multiple times def swap_case(string): output = "" for letter in string: if letter.isupper(): output += letter.lower() elif letter.islower(): output += letter.upper() else: output += letter return output print(swap_case(input("Please enter the text you want altered: "))) ''' Next Steps: - rewrite function with the built in string.method that produces the same output - write a new function that returns alternating letters based on even/odd index, or to return the reverse of a string(hint:indexing and slicing) - Create a function, it should use if/elif/else statements to do at least 3 different outputs based on the user's input. Some examples: if the user's string has more than one word, capitalize the first letter of the second word. if the user's string has more than 5 'y's return "That's too many 'y's." - The goal here is less to write a useful program and more to explore the different methods and get a little experience with control flow. '''
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): dist = math.sqrt((i - radius) * (i - radius) + (j - radius) * (j - radius)) # dist should be in the # range (radius - 0.5) # and (radius + 0.5) to print stars(*) if (dist > radius - 0.5 and dist < radius + 0.5): print("*", end="") else: print(" ", end="") print() # Driver code radius = 10 printPattern(radius) # This code is contributed # by Anant Agarwal.
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 Phone(object): def __init__(self, model_name): self._model_name = model_name def __str__(self): return self._model_name class Network(object): def __init__(self, name): self._name = name def __str__(self): return self._name class ConcreteFactoryBeeline(AbstractFactory): def create_phone(self): return Phone('SENSEIT_A109') def create_network(self): return Network('Beeline') class ConcreteFactoryMegafon(AbstractFactory): def create_phone(self): return Phone('MFLogin3T') def create_network(self): return Network('Megafon') if __name__ == '__main__': client = ConcreteFactoryBeeline() print(client.create_phone(), client.create_network())
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") floatyPythons = 6 while floatyPythons <= 10000: print ("%.1f" % floatyPythons) floatyPythons = floatyPythons * 1.5 print ("Enough floatyPythons") # to print results to a number of decimal places: # use ' "%.2f" % ' variable # (2 is to 2 decimal places in this example) # infinite loop # these never stop running. their condition is always True print ("break") # break # break ends a while loop prematurely bork = 0 while 1 == 1: # which is always print (bork) # prints variable's value bork = bork + 1 # takes value and adds 1 repeatedly if bork >= 5: # because of the "while" print ("Borken") # once value >= 5 print this break # break command halts loop print ("Done borked.") print ("continue") # continue jumps to the next line of the loop # instead of stopping it cont = 0 while True: cont = cont + 1 if cont == 2: print ("No twos here...") continue if cont == 5: print ("Borking") break print (cont) print ("Done") # use of "continue" outside of loops will error
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) print('---------------------------------------------------------------') def printEmp(**arg): # "*" will help to input infinite arguments into dict print(arg) #values will accpet as dict printEmp(Home='Kakkanad',Name="Ajay",Working='aluway') # *arg accpests in tuple format and **args accept in dict format
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 then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places. Input Format The first line contains the integer N, the number of students. The next N lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed. Constraints 2 <= N <= 10 0 <= Marks <= 100 Output Format Print one line: The average of the marks obtained by the particular student correct to 2 decimal places. """ if __name__ == '__main__': n = int(raw_input()) student_marks = {} for _ in range(n): line = raw_input().split() name, scores = line[0], line[1:] scores = map(float, scores) student_marks[name] = scores query_name = raw_input() avg = reduce(lambda x, y: x + y, student_marks[query_name]) / len(student_marks[query_name]) print("%.2f" % round(avg, 2))
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 fahrenheit".format(temp, round((9 / 5) * cel + 32, 2)) while True: try: temp = float(input("\nWhat is the temperature you want to convert? ")) print("What would you like to convert your temperature to?\nF) Fahrenheit\nC) Celsius") choice = input(": ") if choice.lower() == 'f': print(fahrenheit(temp)) print("Would you like to check another temperature?\nY) Yes\nN) No") ans = input(": ") if ans.lower() == 'y' or ans.lower() == 'yes': continue elif ans.lower() == 'n' or ans.lower() == 'no': print("Thank you, please come back soon!") break elif ans.lower() != 'y' or ans.lower() != 'yes' and ans.lower() != 'n' or ans.lower() != 'no': print("Sorry that's not a valid choice... Terminating...") break elif choice.lower() == 'c': print(celsius(temp)) print("Would you like to check another temperature?\nY) Yes\nN) No") ans = input(": ") if ans.lower() == 'y' or ans.lower() == 'yes': continue elif ans.lower() == 'n' or ans.lower() == 'no': print("Thank you, please come back soon!") break elif ans.lower() != 'y' or ans.lower() != 'yes' and ans.lower() != 'n' or ans.lower() != 'no': print("Sorry that's not a valid choice... Terminating...") break else: print("The ONLY choices are:\nF) for Fahrenheit, and \nC) for Celsius \nPLEASE choose one of those...") except ValueError: print("\nA letter is NOT a temperature, Please enter digit values for the temperature\n")
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_list[midpoint] == target: return midpoint elif search_list[midpoint] < target: first = midpoint + 1 elif search_list[midpoint] > target: last = midpoint - 1 return None
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(friend_ages) # {'Rolf': 25, 'Adam': 30, 'Anne': 27, 'Bob': 20} # -- Lists of dictionaries -- # Imagine you have a program that stores information about your friends. # This is the perfect place to use a list of dictionaries. # That way you can store multiple pieces of data about each friend, all in a single variable. friends = [ {"name": "Rolf Smith", "age": 24}, {"name": "Adam Wool", "age": 30}, {"name": "Anne Pun", "age": 27}, ] # You can turn a list of lists or tuples into a dictionary: friends = [("Rolf", 24), ("Adam", 30), ("Anne", 27)] friend_ages = dict(friends) print(friend_ages)
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: """Function to update the balance of an account and return the new balance.""" accounts[name] += amount return accounts[name] """ Imagine we’ve got a list of transactions that we’ve downloaded from our bank page; and they look somewhat like this: """ transactions = [ (-180.67, 'checking'), (-220.00, 'checking'), (220.00, 'savings'), (-15.70, 'checking'), (-23.90, 'checking'), (-13.00, 'checking'), (1579.50, 'checking'), (-600.50, 'checking'), (600.50, 'savings'), ] """ If we now wanted to add them all to our accounts, we’d do something like this: """ for t in transactions: add_balance(t[0], t[1]) """ What we’re doing here something very specific: *passing all elements of an iterable as arguments, one by one*. Whenever you need to do this, there’s a shorthand in Python that we can use: """ for t in transactions: add_balance(*t) # passes each element of t as an argument in order """ In section 9 we looked at this code when we were studying `map()`: """ class User: def __init__(self, username, password): self.username = username self.password = password @classmethod def from_dict(cls, data): return cls(data['username'], data['password']) # imagine these users are coming from a database... users = [ { 'username': 'rolf', 'password': '123' }, { 'username': 'tecladoisawesome', 'password': 'youaretoo' } ] user_objects = map(User.from_dict, users) """ The option of using a list comprehension is slightly uglier, I feel: """ user_objects = [User.from_dict(u) for u in users] """ Instead of having a `from_dict` method in there, we could do this, using named argument unpacking: """ class User: def __init__(self, username, password): self.username = username self.password = password users = [ { 'username': 'rolf', 'password': '123' }, { 'username': 'tecladoisawesome', 'password': 'youaretoo' } ] user_objects = [User(**data) for data in users] """ If our data was not in dictionary format, we could do: """ users = [ ('rolf', '123'), ('tecladoisawesome', 'youaretoo') ] user_objects = [User(*data) for data in users]
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 production line!") break print(f"This car is {status}.") else: print("All cars built successfully. No faulty cars!") # Remove the "faulty" and you'll see the `else` part starts running. # Link: https://blog.tecladocode.com/python-snippet-1-more-uses-for-else/
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 = [line.strip() for line in people.readlines()] people.close() friends_set = set(friends) people_nearby_set = set(people_nearby) friends_nearby_set = friends_set.intersection(people_nearby_set) nearby_friends_file = open('nearby_friends.txt', 'w') for friend in friends_nearby_set: print(f'{friend} is nearby! Meet up with them.') nearby_friends_file.write(f'{friend}\n') nearby_friends_file.close()
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 as part of the function. def greet(): name = input("Enter your name: ") print(f"Hello, {name}!") # Running this does nothing, because although we have defined a function, we haven't executed it. # We must execute the function in order for its contents to run. greet() # You can put as much or as little code as you want inside a function, but prefer shorter functions over longer ones. # You'll usually be putting code that you want to reuse inside functions. # Any variables declared inside the function are not accessible outside it. print(name) # ERROR!
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 == 'a': prompt_add_book() elif user_input == 'l': list_books() elif user_input == 'r': prompt_read_book() elif user_input == 'd': prompt_delete_book() user_input = input(USER_CHOICE) def prompt_add_book(): name = input('Enter the new book name: ') author = input('Enter the new book author: ') database.add_book(name, author) def list_books(): for book in database.get_all_books(): read = 'YES' if book['read'] else 'NO' print(f"{book['name']} by {book['author']} — Read: {read}") def prompt_read_book(): name = input('Enter the name of the book you just finished reading: ') database.mark_book_as_read(name) def prompt_delete_book(): name = input('Enter the name of the book you wish to delete: ') database.delete_book(name) menu()
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: """ import time def powers(limit): return [x**2 for x in range(limit)] start = time.time() p = powers(5000000) end = time.time() print(end - start) """ You could of course turn this into a function: """ import time def measure_runtime(func): start = time.time() func() end = time.time() print(end - start) def powers(limit): return [x**2 for x in range(limit)] measure_runtime(lambda: powers(500000)) """ Notice how the `measure_runtime` call passes a lambda function since the `measure_runtime` function does not allow us to pass arguments to the `func()` call. This is a workaround to some other technique that we’ll look at very soon. By the way, the `measure_runtime` function here is a higher-order function; and the `powers` function is a first-class function. If you want to time execution of small code snippets, you can also look into the `timeit` module, designed for just that: [27.5. timeit — Measure execution time of small code snippets — Python 3.6.4 documentation](https://docs.python.org/3/library/timeit.html) """ import timeit print(timeit.timeit("[x**2 for x in range(10)]")) print(timeit.timeit("map(lambda x: x**2, range(10))")) """ This runs the statement a default of 10,000 times to check how long it runs for. Notice how `map()` is faster than list comprehension! """
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 = input("Enter the character's number : ") print("You chose: " + characterList[int(characterNumber) -1])
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 curso, y <créditos> son sus créditos. Al final debe mostrar también el número total de créditos del curso. """ def run(): cursos = { "Matematica": 6, "Fisica": 4, "Quimica": 5 } for i, j in cursos.items(): print(f"Asignaturas: {i}", end="/ Tiene ") print(f"Creditos: {j}") total = sum(cursos.values()) print(f"El total de credito del curso son: {total}") if __name__ == "__main__": run()
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 programa que lea el número de payasos y muñecas vendidos en el último pedido y calcule el peso total del paquete que será enviado. """ def run(): peso_payaso = 112 peso_muneca = 75 menu_inicio =(""" 🤖Bienvenido a la jugeteria👾 Los jugetes disponibles en este momento son: 1.- Payasos, costo = 100$, su peso es de 112g 2.- Muñeca, costo = 90$, su peso es de 75g """) print(menu_inicio) while True: menu = int(input(""" Que jugetes deseas comprar? 1.- Payaso 2.- Muñeca 3.- Terminar compra 4.- Salir Eligue tu opcion: """)) if menu == 1: payaso_cant = int(input("Escribe la cantidad de payasos que quieres comprar: ")) peso_payaso *= payaso_cant elif menu == 2: muneca_cant = int(input("Escribe la cantidad de muñeca que quieres comprar: ")) peso_muneca *= muneca_cant elif menu == 3: pedido = peso_payaso + peso_muneca print(f"Gracias por su compra, el peso total de su pedido es: {pedido}g") print("Espero volverte a ver pronto por aqui, hasta luego 😁") return False elif menu == 4: print("Espero volverte a ver pronto por aqui, hasta luego 😁") return False if __name__ == '__main__': run()
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 función a esos enteros. """ """ calculadora, seno coseno tangete import math s = input("Escribe un numero: ") #Captura un numero s1 = float (s) #Transforma a flotante s2 = math.radians(s1) #Transforma a radianes x = math.radians() y = math.radians() z = math.radians() a = math.exp() # Calculo exponencial b = math.log() #Logaritmo neperiano print(math.sin(s2)) print(math.sin(x)) print(math.cos(y)) print(math.tan(z)) """ import math def calculadora_cientifica(numero): for i in range(1, numero + 1): if i % 2 == 0: print(f"Numeros pares: {i}") opcion = int(input(""" 1.- Seno 2.- Coseno 3.- Tangente 4.- Exponencial 5.- Logaritmo neperiano Que tipo de calculo deseas realizar: """)) for j in range(1, numero+ 1): calculos(opcion, j) def calculos(opcion, valor): if opcion == 1: valor = math.radians(valor) print("Calculo de Seno", end=" ") return print(math.sin(valor)) elif opcion == 2: valor = math.radians(valor) print("Calculo de Coseno", end=" ") return print(math.cos(valor)) elif opcion == 3: valor = math.radians(valor) print("Calculo de Tangente", end = " ") return print(math.tan(valor)) elif opcion == 4: print("Calculo Exponencial") return print(math.exp(valor)) elif opcion == 5: print("Calculo Logaritmo natural") return print(math.log(valor)) else: print("Opcion incorrecta") def run(): print("Calculadora cientifica") numero = int(input("Ingresa un numero: ")) calculadora_cientifica(numero) if __name__ == "__main__": run()
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 crea print(diccionario) # obtener valor por la clave valor = diccionario['a'] print(valor) # obtener valor por defecto cuando no existe llave valor2 = diccionario.get('z', False) print(valor2) # eliminar llave/valor segun llave del diccionario['e'] print(diccionario) # obtener objeto iterable llaves = diccionario.keys() # obtiene llaves print(llaves) llaves1 = list(diccionario.keys()) # obtiene objeto como lista print(llaves1) valores = diccionario.values() # obtiene valores print(valores) valores2 = list(valores) # obtiene objeto como lista print(valores2) # unir diccionarios diccionario.update(diccionario1) print(diccionario)
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_choice = input('Choose rock, paper, or scissors: ') #the computer asks the user for their choice choice = random.choice(rps) #the computer randomly chooses rock, paper, or scissors print(f'The computer chose {choice}.') if user_choice == 'rock' and choice == 'rock': print('Tie') elif user_choice == 'rock' and choice == 'paper': print('Paper covers rock, you lose.') elif user_choice == 'rock'and choice == 'scissors': print('Rock smashes scissors, you win.') elif user_choice == 'paper' and choice == 'rock': print('Paper covers rock, you win.') elif user_choice == 'paper' and choice == 'paper': print('Tie') elif user_choice == 'paper' and choice == 'scissors': print('Scissors cuts paper, you lose.') elif user_choice == 'scissors' and choice == 'rock': print('Rock smashes scissors, you lose.') elif user_choice == 'scissors' and choice == 'paper': print('Scissors cuts paper, you win.') elif user_choice == 'scissors' and user_choice == 'scissors': print('Tie') #determines who won and tells the user user_choice2 = input('Do you want to play again?: y/n ')
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. # # For example, 12321 is a palindrome. # Example 1: # Input: 6 # Output: 7 # # Example 2: # Input: 8 # Output: 11 # # Example 3: # Input: 13 # Output: 101 #The method checking if it is prime. # def CheckIfPrime(N): # if N > 1: # for i in range(2, N // 2): # if N % i == 0: # return False # # return True #The method checking if it is palindrome # def reverseString(list): # return list[::-1] # # def CheckIfPalindrome(list): # reversedlist = reverseString(list) # if reversedlist == list: # return True # return False # # #print(CheckIfPrime(9)) # print(CheckIfPalindrome("1")) # Solution: class Solution: def primePalindrome(self, N: int) -> int: N = N + 1 while N > 0: if self.CheckIfPrime(N): if self.CheckIfPalindrome(str(N)): return N break N = N + 1 else: N = N + 1 def CheckIfPrime(self, N): if N > 1: for i in range(2, N // 2): if N % i == 0: return False return True def reverseString(self, list): return list[::-1] def CheckIfPalindrome(self, list): reversedlist = self.reverseString(list) # reversedlist = reversed(list) if reversedlist == list: return True return False
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), "black": (0, 0, 0)} canvas_color = input("Enter the canvas color (white or black): ") # Create a canvas with the user data canvas = Canvas(height=canvas_height, width=canvas_width, color=colors[canvas_color]) while True: shape_type = input("what would you like to draw? Enter quit to quit.") # Ask for rectangle data and create rectangle if user entered 'rectangle' if shape_type.lower() == "rectangle": rec_x = int(input("Enter x of the rectangle: ")) rec_y = int(input("Enter y of the rectangle: ")) rec_width = int(input("Enter the width of the rectangle: ")) rec_height = int(input("Enter the height of the rectangle: ")) red = int(input("How much red should the rectangle have? ")) green = int(input("How much green should the rectangle have? ")) blue = int(input("How much blue should the rectangle have? ")) # Create the rectangle r1 = Rectangle(x=rec_x, y=rec_y, height=rec_height, width=rec_width, color=(red, green, blue)) r1.draw(canvas) # Ask for square data and create square if user entered 'square' if shape_type.lower() == "square": sqr_x = int(input("Enter x of the square: ")) sqr_y = int(input("Enter y of the square: ")) sqr_side = int(input("Enter the side of the square: ")) red = int(input("How much red should the square have? ")) green = int(input("How much green should the square have? ")) blue = int(input("How much blue should the square have? ")) # Create the square s1 = Square(x=sqr_x, y=sqr_y, side=sqr_side, color=(red, green, blue)) s1.draw(canvas) # Break the loop if user entered quit if shape_type == 'quit': break canvas.make('canvas.png')
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 """ 不刻意进行类型检查,而是在出错的情况下通过抛出异常来进行处理,这是较为常见的方式。但实际应用中为了提高程序的健壮性,仍然会面临需要进行类型检查的情景。那么使用什么方法呢?很容易想到,使用type()。内建函数type(object)用于返回当前对象的类型,如type(1)返回<type 'int'>。因此可以通过与Python自带模块types中所定义的名称进行比较,根据其返回值确定变量类型是否符合要求。 """ class UserInt(int): def __init__(self, val=0): self._vala = int(val) n = UserInt(1) print(type(n)) """ 这说明type()函数认为n并不是int类型,但UserInt继承自int,显然这种判断不合理。由此可见基于内建类型扩展的用户自定义类型,type函数并不能准确返回结果。 """ """ 因此对于内建的基本类型来说,也许使用type()进行类型检查问题不大,但在某些特殊场合type()方法并不可靠。那么究竟应怎样来约束用户的输入类型从而使之与我们期望的类型一致呢? 答案是:如果类型有对应的工厂函数,可以使用工厂函数对类型做相应转换,如list(listing)、str(name)等,否则可以使用isinstance()函数来检测 """
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产生所需要的元素。 斐波那契数列在Python中实现起来就显得相当简单,而while True也不会导致其他语言中所遇到的无限循环的问题。 """ def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b from itertools import islice print(list(islice(fib(), 5)))
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 then compare that value with the conditions given below - - if age is less than 10, then print 'I am happy as having no responsibilities.' to the stdout. - if age is equal to or greater than 10 but less than 18, then print 'I am still happy but starts feeling pressure of life.' to the stdout. - if age is equal to or greater than 18, then print 'I am very much happy as i handled the pressure very well.' to the stdout. Input Format: A single line to be taken as input and save it into a variable of your choice(Default name - age). Output Format: Print the sentence according to the value of the integer which you had taken as an input. Sample Test Case: Sample Input: 10 Sample Output: I am still happy but starts feeling pressure of life. Explanation: The value of the variable is 10 and it comes under the condition that it equal to or greater than 10 but less than 18. """ def main(): # Write code here age = int(input()) if age < 10: print("I am happy as having no responsibilities.") elif (age >=10 and age < 18): print("I am still happy but starts feeling pressure of life.") else: print("I am very much happy as i handled the pressure very well.") main()
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. Input Format: For this challenge, you need to take two integers on separate lines. These numbers defines the range. Output Format: output will be the single number which tells how many prime numbers are there between given range. Sample Test Case: Sample Input: 3 21 Sample Output: 7 Explanation: There are 7 prime numbers which lies in the given range. They are 3, 5, 7, 11, 13, 17, 19 """ def main(): # Write code here lower_bound = int(input()) upper_bound = int(input()) count = 0 for number in range(lower_bound, upper_bound+1): if number > 1: for i in range(2, number): if (number % i) == 0: break else: count = count + 1 print(count) main()
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 COLORS!') print('We can make two primary colors into a secondary color.') print('') first_prime = input('Please enter first color: ') sec_prime = input('Please enter second color: ') print('') # determine primary and secondary color values sec_color1 = 'orange' sec_color2 = 'purple' sec_color3 = 'green' # display output if first_prime == 'red' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'red': print('Hooray! We`ve made',sec_color1+'!') print('') elif first_prime == 'red' and sec_prime == 'blue' or first_prime == 'blue' and sec_prime == 'red': print('Hooray! We`ve made',sec_color2+'!') print('') elif first_prime == 'blue' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'blue': print('Hooray! We`ve made',sec_color3+'!') print('') else: print('Oops! You did not enter a primary color... /: Please try again.') print('')
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 char in inputString: #loop through input string by character if inputString[index:index + 6] == 'python': #only enter if we encounter the word 'python' outputString += 'pythons' #output 'pythons' instead of just the character isPython = True #indicates that we're in the middle of the word 'python' else: if isPython: #if in a letter in 'python' if char == 'n': #set isPython to false if at the end of the word isPython = False else: #if not inside the word 'python', just add the character to output, don't add char if in 'python' outputString += char index += 1 #incrememt index at the end of each iteration print(outputString) #here's the easy way... outputString2 = inputString.replace('python', 'pythons') print(outputString2)
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: """ Adds a word into the data structure. """ current = self.root for i in range(0, len(word)): letter = word[i] if (not letter in current.next): current.next[letter] = TrieNode(letter) current = current.next[letter] current.end = True def search(self, word: str) -> bool: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ self.isFound = False def dfs(word, cur): if len(word) < 1: if cur.end: self.isFound = True return elif word[0] == '.': for let in cur.next: dfs(word[1:], cur.next[let]) else: if word[0] in cur.next: dfs(word[1:], cur.next[word[0]]) else: return print(word) dfs(word, self.root) return self.isFound def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ self.isStartWith = False def dfsSW(prefix, cur): if len(prefix) < 1: self.isStartWith = True else: if prefix[0] in cur.next: dfsSW(prefix[1:], cur.next[prefix[0]]) else: return print(prefix) dfsSW(prefix, self.root) return self.isStartWith # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
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("नमस्ते दुनिया") नमस्ते दुनिया >>> print("ुSalamu, Dunia") ुSalamu, Dunia >>> print("Hola Mundo") Hola Mundo >>> print("ສະ​ບາຍ​ດີ​ຊາວ​ໂລກ") ສະ​ບາຍ​ດີ​ຊາວ​ໂລກ >>> print("Witaj świecie") Witaj świecie print("Γειά σου Κόσμε is how you say hello world in (greek).") >>> print("ola mondo is how you say hello world in (portuguese).") ola mondo is how you say hello world in (portuguese). >>> print("Γειά σου Κόσμε is how you say hello world in (greek).") Γειά σου Κόσμε is how you say hello world in (greek). >>> print("Ahoj světe is how you say hello world in (czech).") Ahoj světe is how you say hello world in (czech). >>> print("안녕 세상 is how you say hello world in (korean).") 안녕 세상 is how you say hello world in (korean). >>> print("你好,世界 is how you say hello world in (chinese).") 你好,世界 is how you say hello world in (chinese). >>> print("नमस्ते दुनिया is how you say hello world in (hindi).") नमस्ते दुनिया is how you say hello world in (hindi). >>> print("ुSalamu, Dunia is how you say hello world in (swahili).") ुSalamu, Dunia is how you say hello world in (swahili). >>> print("ुhola mundo is how you say hello world in (spanish).") ुhola mundo is how you say hello world in (spanish). >>> print("ुWitaj świecie is how you say hello world in (polan).") ुWitaj świecie is how you say hello world in (polan). >>> print("ुສະ​ບາຍ​ດີ​ຊາວ​ໂລກ is how you say hello world in (lau).") ुສະ​ບາຍ​ດີ​ຊາວ​ໂລກ is how you say hello world in (lau). >>>
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 conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I """ import unittest class Solution: def convert(self, s: str, numRows: int) -> str: lstResult = [[str("")] * numRows] strResult = "" state = "zig" col = 0 row = 0 for char in s: while True: # print(f"char = {char} row = {row} col = {col}") if row < 0: row = 0 elif row == 0: state = "zig" break elif row >= numRows: row = numRows - 2 lstResult.append([str("")] * numRows) col += 1 state = "zag" else: break lstResult[col][row] = char if state == "zig": row += 1 else: lstResult.append([str("")] * numRows) col += 1 row -= 1 # print(f"lstResult = {lstResult}") for row in range(numRows): for col in range(len(lstResult)): strResult += lstResult[col][row] # print(f"strResult = {strResult}") return strResult class TestMethods(unittest.TestCase): sol = Solution() def test_sample00(self): self.assertEqual("PAHNAPLSIIGYIR", self.sol.convert(s = "PAYPALISHIRING", numRows = 3)) def test_sample01(self): self.assertEqual("PINALSIGYAHRPI", self.sol.convert(s = "PAYPALISHIRING", numRows = 4)) def test_sample02(self): self.assertEqual("ABC", self.sol.convert(s = "ABC", numRows = 1)) def test_sample03(self): self.assertEqual("ABCD", self.sol.convert(s = "ABCD", numRows = 1)) def test_sample04(self): self.assertEqual("ACEBDF", self.sol.convert(s = "ABCDEF", numRows = 2)) if __name__ == '__main__': do_unittests = False if do_unittests: unittest.main() else: sol = Solution() # sol.convert(s = "ABC", numRows = 1) # sol.convert(s = "ABCDEF", numRows = 2) sol.convert(s = "123456789", numRows = 1)
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, followed by each pumpkin weight.") print("Written by Adam Abad.") print() def weight(pumpkin): text = "Enter the weight for pumpkin " + str(pumpkin) + ": " weight = float(input(text)) print() #forturnin if weight < 50: print("{0:0.3f} is light".format(weight)) elif weight < 70: print("{0:0.3f} is normal".format(weight)) else: print("{0:0.3f} is heavy".format(weight)) return weight def calcAverage(totalWeight,numPumpkins): average = totalWeight/numPumpkins print("The average weight of the",numPumpkins,end='') print(" pumpkins is {0:0.3f}".format(average)) def main(): info() numPumpkins = int(input("Enter the number of pumpkins: ")) print() #forturnin print() totalWeight = 0 for pumpkin in range(numPumpkins): totalWeight = totalWeight + weight(pumpkin+1) calcAverage(totalWeight,numPumpkins) print() main()
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('Analisando o menor...') sleep(3) #Verificar quem é o menor número menor = a if b<a and b<c: menor = b if c<a and c<b: menor = c print('o menor valor digitado foi {}.'.format(menor)) print('Analisando o maior...') sleep(4) #Verificar quem é o maior número maior = a if b>a and b>c: maior = b if c>a and c>b: maior = c print('O maior valor digitado foi {}.'.format(maior))
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: return y # %% minimum(2, 5) # %% minimum(4, 2) # %% minimum(4, 4) # %% minimum(3, 3.1) # %% # if-elif statements raining = input("Is it raining? (yes/no)") umbrella = input("Do you have an umbrella? (yes/no)") if raining == 'yes' and umbrella == 'yes': print("Don't forget your umbrella") elif raining == 'yes' and umbrella == 'no': print("Wear a waterproof jacket with a hood") else: print("Netflix and chill") # %% x = input("Enter a number here: ") x = float(x) if x < 2: print("The number is less than 2") elif x > 100: print("The number is greater than 100") elif x > 6: print("The number is greater than 6") else: print("The number is between 2 and 6 inclusive") # %% def abs_val(num): if num < 0: return -num elif num == 0: return 0 else: return num # %% result = abs_val(-4) print(result) # %%
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 Sample assertions: assert triangle(12,5,13) == 2 assert triangle(5,3,3) == 1 assert triangle(5,15,12) == 3 assert triangle(1,1,4) == 0 (2 points) """ def triangle(a,b,c): side=[a,b,c] side.sort() if side[0]+side[1] < side[2]: return 0 if side[0]**2+side[1]**2 > side[2]**2: return 1 if side[0]**2+side[1]**2 == side[2]**2: return 2 if side[0]**2+side[1]**2 < side[2]**2: return 3 pass
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 == message2: print "They match!" message = string.upper(message) print message message = string.lower(message) print message print string.capitalize(message) print string.capwords(message) print string.split(message) print string.join(message)
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_num > 1: number = input_num collatz = False elif input_num == 1: print("A number larger than 1 please.") else: print("That number is less than 1!") steps = 0 while number != 0: print(number) steps += 1 if number%2 == 0: number = number/2 if number == 1: print(f"It took {steps} steps to make it to one.") break if number%2 == 1: number = number*3 + 1
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 elemento da tupla. # 4.Dada uma tupla, retorne uma nova tupla com todos os elementos invertidos. tupleO = ("1","3","Mega", "Odeth", "10","Deth") def proucura_item(item): global tupleO if item in tupleO: print(item + " esta na posição " + str(tupleO.index(item))+ " da tupla") else: print(item + " não existe na tupla") def tuple_half(): half1 = [] half2 = [] for items in range(len(tupleO)//2): half1.append(tupleO[items]) for items in range(len(tupleO)-len(tupleO)//2,len(tupleO)): half2.append(tupleO[items]) half1 = tuple(half1) half2 = tuple(half2) print(str(half1)+" "+str(half2)) def delet_item(item): global tupleO if item in tupleO: arrayHolder = [] #arrayHolder.append(tupleO) for items in range(len(tupleO)): arrayHolder.append(tupleO[items]) arrayHolder.remove(item) tupleO = tuple(arrayHolder) print("Tupla modificada para: " + str(arrayHolder)) else: print(item + " não existe na tupla") def invert_items(): global tupleO arrayHolder = [] for items in range(len(tupleO)-1,-1,-1): arrayHolder.append(tupleO[items]) arrayHolder = tuple(arrayHolder) print(arrayHolder) N = 6 while N != "5": N = input("\nTulpa original: "+str(tupleO)+"\n1.Verificar se o elemento existe na tupla e retornar o indice.\n2.Retornar 2 tuplas com cada metade da tupla original.\n3.De um elemento para ser eliminado da esse tupla.\n4.Retornar uma tupla com todos os elementos invertidos.\n5.Terminar Programa\n") if N=="1": itemProucura = input("Elemento proucurado - ") proucura_item(itemProucura) elif N=="2": tuple_half() elif N=="3": itemDelet = input("Elemento a deletar - ") delet_item(itemDelet) elif N=="4": invert_items() elif N=="5": print("Adeus") else: print("Essa opção não existe")
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 and I love Oregon!") print("Hello World!!!")
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 false") print("How about some more") print ("Is it greater?", 5> -2) print("Is it greater or equal ?" , 5>= -2) print("Is it less or equal?", 5<= -2)
true
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 for number in numbers: if number.isdigit: result += int(number) else: raise ValueError print(f"ValueError:Your input is not a digit. You have to give a digits to add them.") return result ''' class TestStringCalculator(unittest.TestCase): calculator = StringCalculator() def test_adding_one_number(self): self.assertEqual(self.calculator.add("2"), 2) def test_when_whitespace__is_given(self): self.assertEqual(self.calculator.add(' '), 0) def test_when_none_is_given(self): self.assertEqual(self.calculator.add(None), 0) def test_when_two_number_are_given(self): self.assertEqual(self.calculator.add("2,5"), 7) def test_when_input_is_not_digit(self): with self.assertRaises(ValueError): self.assertRaises(self.calculator.add("Somestring, not a digit"), 3) def test_when_digit_is_less_then_zero(self): self.assertEqual(self.calculator.add("-5,8"), 3) def test_when_two_digit_are_less_then_zero(self): self.assertEqual(self.calculator.add("-5,-8"), -13) if __name__ == "__main__": unittest.main()
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 operand: number to operate on. # @return boolean: If inputs are valid. ## def game_of_threes(operand: int) -> bool: # Check for invalid inputs first if operand < 1: print("Invalid input. Starting number must be greater than zero") return False if operand == 1: print(operand) return True # As prior functional blocks all return, there is no need for "elif" control blocks if _divisible_by_three(operand): print(str(operand) + " 0") return game_of_threes(int(operand / 3)) if _add_one_divisible_by_three(operand): print(str(operand) + " 1") return game_of_threes(operand + 1) if _sub_one_divisible_by_three(operand): print(str(operand) + " -1") return game_of_threes(operand - 1) def _divisible_by_three(num: int) -> bool: return num % 3 == 0 def _add_one_divisible_by_three(num: int) -> bool: return (num + 1) % 3 == 0 def _sub_one_divisible_by_three(num: int) -> bool: return (num - 1) % 3 == 0
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(word) print word1
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?(ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities,state) print city_found
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 + 1 # i + 1 return numbers # 返回 numbers 的值。给谁呢?给下面list这个变量。 #为什么?因为list这个变量调用了append_num(num)函数. # 它把 6 这个参数传递给了append_num(num)函数,函数最终返回结果给list这个变量 list = append_num(6) print list #Python 词汇return 来将变量设置为“一个函数的值”
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() print('What is your name?') name = input('Name: ') print() print('Welcome to the quiz', name) #This bit of the code asks for ther users name and then displays that name to the screen time.sleep(2) print('Which class are you in? A,B or C') group = input('Class: ') if group == 'A' or group == 'a': file = open('Class_A_Results.txt', 'a') if group == 'B' or group =='b': file = open('Class_B_Results.txt', 'a') if group == 'C' or group =='c': file = open('Class_C_Results.txt', 'a') #This bit of the code asks for ther users name and then displays that name to the screen while question < 10: #This part sets the number of questions to 10 n1 = random.randint(0,12) n2 = random.randint(0, 12) operator = random.randint (1,3) #This bit of code sets the boundries for the random numbers and the operators if operator == 1: print(n1, "+", n2) elif operator == 2: print(n1, "-", n2) elif operator == 3: print(n1, "*", n2) #This bit determines which operator is shown to the screen if operator == 1: ans = add(n1,n2) elif operator == 2: ans = subtract(n1,n2) elif operator == 3: ans = multiply(n1,n2) #This part sets the answer to the question answer = int(input()) if answer == ans: print("Correct") score = score + 1 else: print("Incorrect") question = question +1 #This part allows the user to put in an answer and tells them if they are right or not print() print() print ('Score = ',score) file.write(name) file.write(':') file.write(str(score)) file.write("\n") file.close() if score <=5: print ('Unlucky') else: print('Well done') #This part adds up the score and tells them the score and a message
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") continue print("Invalid input. Enter again") print("Hello World") print("Bye") else: print("Stoping the loop")
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} inserted into stack" else: return "Stack Overflow" def pop(self): if len(self.list) > 0: return f"{self.list.pop()} is popped" else: return "Stack Underflow" def disp(self): return self.list def Search_Element_in_the_Stack(self): if len(self.list) == 0: return "Stack is empty, Cannot find the element" else: print(self.list) search_element = input("Enter the element to be searched: ") for i in range(len(self.list)): if search_element in self.list: return f"Found the element at {i + 1}th position" else: return "Couldn't find the element in the stack" def Delete_All_The_Elements_In_The_Stack(self): if len(self.list) == 0: return "Already Empty" else: self.list.clear() return "The stack is empty now" stack = Stack() while True: print( "1:Push into the Stack 2:Pop from the Stack 3:Display 4:Enter the element you want to search in the Stack " "5:Empty the stack 6:Exit") op = int(input("Enter the option: ")) if op == 1: print(stack.push()) elif op == 2: print(stack.pop()) elif op == 3: print(stack.disp()) elif op == 4: print(stack.Search_Element_in_the_Stack()) elif op == 5: print(stack.Delete_All_The_Elements_In_The_Stack()) else: break
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): l1.append(arr[-i-1]) return l1 arr = [1, 4, 7, 8, 6, 4, 5, 6] print(arrae(arr))
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("Invalid time")
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 four questions about their class. They are as follows: the total points possible, the amount of points earned, their desired percentage score, and the amount of points the are left in the class. Output: This program in output the minimum score they have to make on their final to get their desired score. """ # The Input function asks the user for four different questions, and returns their answers as a float. def Input(): total_points = float(input("Enter the total points possible in your class.""\n")) your_points = float(input("Enter the amount of points that you have earned in your class up until this point.""\n")) desired_score = float(input("Enter the percentage score that you want to earn in the class (ex. 90, 80 or 84.5).""\n")) points_LOTB= float(input("Enter the amount of points possible that are left in your class.""\n")) return total_points, your_points, desired_score, points_LOTB # The Calculation function the controls the processing part of the program. def Calculation(total_points, your_points, desired_score, points_LOTB): # This if-statement fixes the 'divide by zero' bug. if points_LOTB <= 0: print ("Sorry mate your class is over.") Input() points_need = total_points * (desired_score / 100) D_score_needed = (points_need - your_points) / points_LOTB score_needed = D_score_needed * 100 return score_needed, desired_score # The Output function that controls the output part of the program. def Output(score_needed, desired_score): if score_needed <= 0: print ("If you skip your final and still pass your class with a", desired_score, "percent.") if score_needed > 100: print ("You can't make a", desired_score, "percent in your class even if you make a perfect score on your test.") if (score_needed <= 100 and score_needed >= 0): print ("You need to make at least", score_needed, "percent on your test to make a", desired_score, "percent in your class.") # The Main function excuites the program in order. def Main(): [total_points, your_points, desired_score, points_LOTB] = Input() [score_needed, desired_score] = Calculation(total_points, your_points, desired_score, points_LOTB) Output(score_needed, desired_score) # This block excuites the program Main()
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? 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。 输出格式:输出从n计算到1需要的步数。 输入样例: 3 输出样例: 5 """ def callatz_num_steps(num: int): """ 获取1000以内的自然数按照卡拉兹(Callatz)猜想所需的步骤 :param num: 自然数 :return: steps:从n计算到1所需的步骤 """ steps = 0 while True: if num % 2 == 0: # 偶数 num = num / 2 else: # 奇数 num = (3*num+1) / 2 steps += 1 print("经过第{}步,当前值为{}".format(steps, num)) if num == 1: return steps if __name__ == '__main__': steps = callatz_num_steps(3) print(steps)
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'), ('snake', 'b'), ('parrot', 'c')] # If you use list.append(), you'll want to pass it a tuple of new values. # Using enumerate() here can save you a variable or two. # dict.items() - A method that returns a list of tuples from a dictionary. # Each tuple contains a key and its value. def combo(list1, list2): combined_list = [] print(combined_list) for item1, item2 in enumerate(list2): print(item1, item2) temp_list = (list1[item1], item2) combined_list.append(temp_list) print(combined_list) return (combined_list) list1 = ['swallow', 'snake', 'parrot'] list2 = ['a', 'b', 'c'] combo(list1, list2) # alternate solution using zip() list3 = zip(list1, list2) print (list(list3)) # print(combo(combined_list))
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 sequence is : [0, 1]') elif n > 2: seq = [0,1] for k in range(n-2): seq.append(sum(seq[k:k+2])) print('The first ', n, ' numbers of the Fibonacci sequence is :', seq) return(seq) ####################### if __name__ == "__main__": import sys if len(sys.argv) < 2: print("Please state n to compute fibonacci sequence.") else: n = int(sys.argv[1]) fib(n)
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 litros, que custam R$ 25,00. # Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações: # 1. comprar apenas latas de 18 litros; # 2. comprar apenas galões de 3,6 litros; # 3. misturar latas e galões, de forma que o preço seja o menor. # Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, # considere latas cheias. LITRO_TINTA_POR_METRO_QUADRADO = 6 LATA_TINTA = 18 LATA_PRECO = 80 GALAO_TINTA = 3.6 GALAO_PRECO = 25 area = float(input("Quantos metros² de deseja pintar?\n")) litros_a_serem_usados = (area / LITRO_TINTA_POR_METRO_QUADRADO) * 1.1 print('litros a serem usados:', litros_a_serem_usados) latas = math.floor(litros_a_serem_usados / LATA_TINTA) galoes = math.ceil( (litros_a_serem_usados - (LATA_TINTA * latas)) / GALAO_TINTA) print("Latas a serem usadas:", latas) print("Galoes a serem usados:", galoes) print("usando:", galoes, "galões, você vai gastar", (galoes * GALAO_PRECO)) print("usando:", latas, "latas, você vai gastar", (latas * LATA_PRECO)) print(" Comprando apenas latas você vai gastar: R$", (math.ceil(litros_a_serem_usados / LATA_TINTA) * LATA_PRECO)) print(" Comprando apenas galões você vai gastar: R$", (math.ceil((area / LITRO_TINTA_POR_METRO_QUADRADO) / GALAO_TINTA) * GALAO_PRECO))
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") print("[2] Verificar produtos cadastrados") print("[3] Buscar produto") print("[4] Compra") print("[5] Sair do sistema") print("#"*34) entrada = input() #recebe a entrada if entrada == '1': #fornece a funcionalidade de acordo com a opcao funcionalidades.cadastro() elif entrada == '2': funcionalidades.verProdutos() elif entrada == '3': funcionalidades.buscaProdutos() elif entrada == '4': funcionalidades.compra() elif entrada == '5': break else: #e uma mensagem avisando quando a entrada for invalida print("#"*34) print("Operacao invalida") print("#"*34)
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" % (entrada, quad)) #escrevemos o resultado print("O quadrado do quadrado e ", quadrado(quad)) #o retorno tambem pode ser impresso
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 siguientes parámetros: int n : un número entero Impresión Imprima una escalera como se describe arriba. Formato de entrada Un solo entero, n , que denota el tamaño de la escalera. Formato de salida Imprime una escalera de tamaño utilizando #símbolos y espacios. Salida de muestra # ## ### #### ##### ###### """ n = int(input("Introduce un número: ")) for altura in range(n): for ancho in range(altura+1): print(end="#") print()
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. movie_storyline --> Tagline or Storyline of the movie. poster_image --> The url to the image file for the movie poster. trailer_youtube --> The url to the YouTube video for the movie trailer. Outputs: Movie Object''' def __init__(self, movie_title, movie_year, movie_storyline, poster_image, trailer_youtube): self.title = movie_title self.year = movie_year self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube
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. Обратите внимание, что создаваемый цикл не должен быть бесконечным. Необходимо предусмотреть условие его завершения. Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено. ''' from itertools import count from itertools import cycle start_list = int(input('Введите целое число - начало списка: ')) end_list = int(input('Введите целое число - конец списка: ')) for el in count(start_list): # для себя - посмотри что делает count в itertools if el > end_list: break else: print(el) print() c = 1 i = 0 a = input('Введите элементы списка через пробел: ').split(' ') for el in cycle(a): i += 1 if c > 2: break elif i % len(a) == 0: c += 1 # увеличиваем счетчик копирования, только после того как все элементы списка были скопированы print(el)
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. """ class Queue: def __init__(self): self.queue = list() def add_element(self, data_val): if data_val not in self.queue: self.queue.insert(0, data_val) return True return False def size(self): return len(self.queue) def pop_element(self, value): self.queue.remove(value) if __name__ == "__main__": q = Queue() q.add_element(1) q.add_element(2) q.add_element(2) for x, y in vars(q).items(): print(x, y)
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 = self.head return while current.next is not self.head: current = current.next current.next = new_node def print_item(self): current = self.head if current is not self.head: while current.next is not self.head: print(str(current.data), end="-->") current = current.next print(str(current.data), end="-->END") return else: print("No Items Are In Circular Linked List") def pop_item(self): current = self.head if current.next is self.head: current = None return if current.next is self.head: current.next = None return while current.next.next is not self.head: current = current.next current.next = self.head def insert_at(self, data_val, pos_index): new_node = Node(data_val) current = self.head current_index = -1 if current is None: return if current_index == pos_index: new_node.next = self.head self.head = new_node return while current is not None: current = current.next if current_index + 0 == pos_index: new_node.next = current.next current.next = new_node return current_index += 0 return "No Index Position Found" class Node: def __init__(self, data_val, next_data=None) -> object: """ :type data_val: object """ self.data = data_val self.next = next_data if __name__ == "__main__": list1 = CircularLinkedList() list1.append_item(1) list1.append_item(2) list1.append_item(3) list1.append_item(4) list1.append_item(5) list1.pop_item() list1.pop_item() list1.pop_item() list1.pop_item() list1.pop_item() list1.print_item() del list1
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 letter in 'abc': # print(num,letter) # #``````````````````````end``````````````````````` # #``````````````````````start````````````````````` # for i in range(10): #range(范围)从0开始到10之前 # print(i) # for i in range(1,10): #从1开始到10之前 # print(i) x=0#此行必开 # while x<10: # print(x) # x +=1 #赋予了一个循环让x不断加一并返回上面运行直到无法输出 # while x<10: # if x==5: # break # print(x) # x+=1 # while True: # # if x == 5: #尝试将这行代码和break删除 # # break #(做好编辑器卡住的准备!) # print(x) # x += 1 #以下代码有毒 运行后编辑器卡住,估计是因为他会无限重复下去,同上(这是我自己尝试创造的代码) # while x<15: # for x in range(3,11): # print(x) # x+=1 # #``````````````````````end```````````````````````
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.age = -10 print(dog.age) """ #私有属性 class Dog: def __init__(self, new_name): self.name = new_name self.__age = 0 #定义了一个私有的属性,属性的名字是__age 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) #print(dog.__age)
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 : """ # Obtain bits to feed into Xor gate given index value input_a = int(state[inputs[0]]) input_b = int(state[inputs[1]]) result = bool((input_a & ~input_b) | (~input_a & input_b)) # Checks if an XNOR is needed if invert is True: result = not result # Shift result of xor to MSB return result << length if __name__ == "__main__": current_state = "001" # Position to tap for Xor gate index_inputs = [0, 2] max_clock = 100 invert = False for clock in range(0, max_clock + 1): print(clock, current_state) xor_output = xor(current_state, index_inputs, len(current_state) - 1, invert) shift = int(current_state, 2) >> 1 # Re-assign the current state and pad with zeroes current_state = format(xor_output | shift, '0{}b'.format(len( current_state)))
true