blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
03be2c4df4c404636dd5599ca939e5692cba538d
mecomontes/Python
/Desde0/listConprehension.py
2,545
4.40625
4
"""Qué son las list comprehensions Básicamente son una forma de crear listas de una manera elegante simplificando el código al máximo. Como lo oyes, Python define una estructura que permite crear listas de un modo un tanto especial. Te lo mostraré con un ejemplo:""" numeros = [1, 2, 34, 86, 4, 5, 99, 890, 45] pares = [] for num in numeros: if num % 2 == 0: pares.append(num) print('numeros pares: ',pares) """El código anterior crea una lista de números pares a partir de una lista de números. Para este tipo de situaciones es ideal el uso de las list comprehensions. El código anterior se puede modificar de la siguiente manera con la sintaxis de las list comprehensions:""" pares = [num for num in numeros if num % 2 == 0] print('numeros pares: ',pares) """Cómo se usan las list comprehensions La estructura de las list comprehensions es la siguiente: [ expresion(i) for i in list if condición ] Es decir, entre corchetes definimos una expresión seguida de un bucle for al que opcionalmente le pueden seguir otros bucles for y/o una condición. ❗️El resultado siempre es una lista. El código anterior es similar al siguiente: nueva_lista = [] for i in list: if condición: nueva_lista.append(expresion(i)) Ejemplos de uso de list comprehensions A continuación te muestro diferentes formas de aplicar lo aprendido aunque ejemplos hay miles:""" ### Capitalizar las palabras de una lista palabras = ['casa', 'perro', 'puerta', 'pizza'] cap = [palabra.title() for palabra in palabras] print('Capitalizar palabras: ',cap) ### Calcular los cuadrados del 0 al 9 cuadrados = [num**2 for num in range(10)] print('cuadrados: ',cuadrados) ###Calcular los cuadrados del 0 al 9 de los números pares cuadrados_pares = [num**2 for num in range(10) if num % 2 == 0] print('cuadrado de los pares: ',cuadrados_pares) ### Listar los ficheros python del directorio actual que comienzan por ‘f’ import os ficheros_python = [f for f in os.listdir('.') if f.endswith('.py') and f.startswith('f')] print('ficheros python: ',ficheros_python) ### Número, doble y cuadrado de los números del 0 al 9 num_doble_cuadrado = [(num, num*2, num**2) for num in range(10)] print(f'numero {0}, doble {1}, cuadrado{2}',num_doble_cuadrado) ### Ejemplo de doble bucle for saludos = ['hola', 'saludos', 'hi'] nombres = ['j2logo', 'antonio', 'vega'] frases = ['{} {}'.format(saludo.title(), nombre.title()) for saludo in saludos for nombre in nombres] print('frases: ',frases)
false
5b1d73fe53c06e6973112db0962a48fa454a40a1
mecomontes/Python
/Fundamentos Python/Fun_Seleccion1.py
1,638
4.21875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- def Fun_Crea_Lista(): import random # Crea una lista a partir de numeros aleatorios # Generar un numero aleatorio(7-10) # Generar una lista de números aleatorios de acuerdo al número generado en el punto anterior # Mostrar: # El numero aleatorio # La lista # Genera un numero aleatorio(7,10) Numero_Aleatorio=int(random.randrange(7,10)) # Crea la lista vacía Lista = [] for i in range(Numero_Aleatorio): Numero_Aleatorio2=int(random.randrange(1,100)) Lista.append(Numero_Aleatorio2) #Salida print(" Lista Creada ") print("Numero de Elementos: %d" % Numero_Aleatorio) print(Lista) return Lista # Programa 1 - ORDENAMIENTO POR SELECCION # Ordenamiento en orden ascendente def Fun_Seleccion1(Lista_Elementos): # Ordenar la lista en orden ascendente # Clasificacion de la Lista for i in range(len(Lista_Elementos)): indiceMenor=i for j in range(i+1,len(Lista_Elementos)): if Lista_Elementos[j] < Lista_Elementos[indiceMenor]: indiceMenor=j if i != indiceMenor: Auxiliar= Lista_Elementos[i] Lista_Elementos[i]=Lista_Elementos[indiceMenor] Lista_Elementos[indiceMenor]=Auxiliar print("") print(" ORDENAMIENTO POR SELECCION (A)") print (Lista_Elementos) # Función: Crea una lista a partir de numeros aleatorios Lista = Fun_Crea_Lista() # Función: Ordenamiento por Selección (A) Fun_Seleccion1(Lista)
false
e68f7daf7a588470c36b131e13606b458298906d
sunnyyants/crackingPython
/Recursion_and_DP/P9_5.py
1,169
4.21875
4
__author__ = 'SunnyYan' # Write a method to compute all the permutation of a string def permutation(string): if string == None: return None permutations = [] if(len(string) == 0): permutations.append("") return permutations firstcharacter = string[0] remainder = string[1:len(string)] words = permutation(remainder) for word in words: for i in range(0,len(word)+1): substring = insertCharAt(word, firstcharacter, i) permutations.append(substring) return permutations def insertCharAt(word, firstc, i): begin = word[0:i] end = word[i:] return (begin) + firstc + (end) def permute2(s): res = [] if len(s) == 1: res = [s] else: for i, c in enumerate(s): #print "i:" + str(i) #print "c:" + str(c) for perm in permute2(s[:i] + s[i+1:]): res += [c + perm] return res # Testing Part... print "All the permutation of set 'abc' will be showing as below:" list = permutation("abc") print list print "All the permutation of set 'abcd' will be showing as below:" print permute2("abcd")
true
70269b4f1997e6509e7323da0d8a7592355e0ef5
sunnyyants/crackingPython
/Trees_and_Graph/P4_4.py
850
4.1875
4
__author__ = 'SunnyYan' # Given a binary tree, design an algorithm which creates a linked list # of all the nodes at each depth(e.g., if you have a tree with depth D, # you'll have D linked lists from Tree import BinarySearchTree from P4_3 import miniHeightBST def createLevelLinkedList(root, lists, level): if(root == None): return None if(len(lists) == level): linkedlist = [] lists.append(linkedlist) else: linkedlist = lists[level] linkedlist.append(root.key) createLevelLinkedList(root.leftChild,lists,level+1) createLevelLinkedList(root.rightChild,lists,level+1) return lists T4 = BinarySearchTree(); i = [1,2,3,4,5,6] T4.root = miniHeightBST(i,0,len(i) - 1) T4.root.printSubtree(5) lists = [] result = createLevelLinkedList(T4.root, lists, 0) for i in result: print i
true
2db3135898b0a57ef68bc4005a12874954b4809f
sunnyyants/crackingPython
/strings_and_array/P1_7.py
893
4.40625
4
__author__ = 'SunnyYan' # # Write an algorithm such that if an element in an M*N matrix is 0, # set the entire row and column to 0 # def setMatrixtoZero(matrix): rowlen = len(matrix) columnlen = len(matrix[0]) row = [0]*rowlen column = [0]*columnlen for i in range(0, rowlen): for j in range(0, columnlen): if matrix[i][j] == 0: row[i] = 1 column[j] = 1 for i in range(0, rowlen): for j in range(0, columnlen): if row[i] or column[j]: matrix[i][j] = 0 return matrix matrixrow = [] matrixcol = [] # initialized the matrix by using list for row in range(0, 3): for column in range(0, 4): matrixcol.append(column+row) matrixrow.append(matrixcol) matrixcol=[] print "Before setting" print matrixrow print "After setting" print setMatrixtoZero(matrixrow)
true
cf53a1b7300099ea8ecbe596ac2cb6574642e05f
sainath-murugan/small-python-projects-and-exercise
/stone, paper, scissor game.py
1,231
4.21875
4
from random import randint choice = ["stone","paper","scissor"] computer_selection = choice[randint(0,2)] c = True while c == True: player = input("what is your choice stone,paper or scissor:") if player == computer_selection: print("tie") elif player == ("stone"): if computer_selection == ("scissor"): print("hey there you won, computer selects scissor.so,stone smaches scissor") break else: print("hey there you lose,computer selects paper.so, paper covers stone") break elif player == ("paper"): if computer_selection == ("scissor"): print("hey there you lose, computer selects scissor.so, scissor cuts paper") break else: print("hey there you won, computer selects stone.so, paper covers stone") break elif player ==("scissor"): if computer_selection ==("stone"): print("hey there you lose computer selects stone.so, stone smaches scissor") break else: print("hey there you won,computer selects paper.so scissor cuts paper") break else: print("enter a valid word!!!") break
true
0bea4a359a651daeb78f174fe3fb539e118c39ad
asperaa/programming_problems
/linked_list/cll_create.py
1,345
4.34375
4
# class for Circular linked list node class Node: # function to initiate a new_node def __init__(self, data): self.data = data self.next = None # class for circular linked list class CircularLinkedList: # function to initialise the new_node def __init__(self): self.head = None # function to push data in the front of circular linked list def push(self, data): # create a new node new_node = Node(data) # point next of new_node to head of CLL new_node.next = self.head # temp variable as a mover temp = self.head # CLL is not empty if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = new_node else: new_node.next = new_node self.head = new_node # function to print a circular linked list def print_list(self): temp = self.head while(True): print(temp.data, end=" ") temp = temp.next if temp == self.head: break print() if __name__ == "__main__": dll = CircularLinkedList() dll.push(10) dll.push(9) dll.push(8) dll.push(7) dll.push(6) dll.print_list()
true
316c16a74400b553599f007f61997e65a5ed0069
asperaa/programming_problems
/linked_list/rev_group_ll.py
1,889
4.25
4
""" Reverse a group of linked list """ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: # initialise the head of the linked list def __init__(self): self.head = None # add a new node to the end of linked list def add_node(self, data): # create a new node new_node = Node(data) # check if the node is empty if self.head is None: self.head = new_node return # mover node mover = self.head while(mover.next): mover = mover.next mover.next = new_node def reverse_k_group(self, temp_head, k): current_node = temp_head next = None prev_node = None count = 0 # break the loop on reaching the group limit # and on end of ll while(current_node is not None and count < k): next = current_node.next current_node.next = prev_node prev_node = current_node current_node = next count += 1 # stop recursion on reaching the end of loop if next is not None: temp_head.next = self.reverse_k_group(next, k) # keep the head of the linked list updated self.head = prev_node # prev_node is the new_head of the input list return prev_node def print_list(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next print() if __name__ == "__main__": ll = LinkedList() ll.add_node(1) ll.add_node(2) ll.add_node(3) ll.add_node(4) ll.add_node(5) ll.add_node(6) ll.add_node(7) ll.add_node(8) ll.print_list() ll.reverse_k_group(ll.head, 3) ll.print_list()
true
f7fa6a108c3a05c476fa48b679ec81b9dab0edd7
asperaa/programming_problems
/linked_list/rev_ll.py
1,383
4.25
4
# Node class class Node: def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def reverse(self): if self.head is None: print("Empty ll") return # initialise the prev_node and current node as None and head of ll prev_node = None curr_node = self.head while(curr_node is not None): next_node = curr_node.next # save the next of curr_node in a next_node var curr_node.next = prev_node # set the next of curr_node as prev_node prev_node = curr_node # set the prev_node as curr_node curr_node = next_node # set the curr_node as the next node that you saved earlier self.head = prev_node # set the head of ll as the last node def print_list(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next print() if __name__ == "__main__": ll = LinkedList() ll.push(8) ll.push(7) ll.push(4) ll.push(90) ll.push(10) ll.print_list() ll.reverse() ll.print_list()
true
e05982cee993abbc9163123021f57d352d644225
asperaa/programming_problems
/stack/queue_using_stack.py
834
4.34375
4
"""Implement queue using stack i.e only use stack operations""" class Queue: def __init__(self): self.s1 = [] self.s2 = [] def empty(self): return len(self.s1) == 0 def push(self, val): self.s1.append(val) def pop(self): while len(self.s1) != 0: self.s2.append(self.s1.pop()) popped = self.s2.pop() while len(self.s2) != 0: self.s1.append(self.s2.pop()) return popped def peek(self): while len(self.s1) != 0: self.s2.append(self.s1.pop()) topped = self.s2[-1] while len(self.s2) != 0: self.s1.append(self.s2.pop()) return topped if __name__ == "__main__": q = Queue() q.push(1) q.push(2) q.push(3) print(q.pop()) print(q.peek())
false
956495f4026844ed336b34512c87aceec11c0ef8
asperaa/programming_problems
/linked_list/reverse_first_k.py
2,093
4.375
4
"""Reverse the first k elements of the linked list""" # Node class for each node of the linked list class Node: # initialise the node with the data and next pointer def __init__(self, data): self.data = data self.next = None # Linked list class class LinkedList: # initialise the head of the class def __init__(self): self.head = None # add a node to the front of the linked list def add_front(self, data): # create a new node new_node = Node(data) # check if the linked list is empty if self.head is None: self.head = new_node return new_node.next = self.head self.head = new_node # function to reverse first k nodes of the linked list def reverse_frist_k(self, k): # check if the ll is empty if self.head is None: return current_node = self.head next_node = None prev_node = None count = 0 while(current_node and count < k): next_node = current_node.next current_node.next = prev_node prev_node = current_node current_node = next_node count += 1 # point the next of the original first node # to the first node of the un-reversed ll self.head.next = next_node # change the head of the linked list to # point to the new node (first node of reversed part of ll) self.head = prev_node # print the linke the linked list def print_list(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next print() if __name__ == "__main__": ll = LinkedList() ll.add_front(8) ll.add_front(7) ll.add_front(6) ll.add_front(5) ll.add_front(4) ll.add_front(3) ll.add_front(2) ll.add_front(1) # print the original linked list ll.print_list() # reverse the linked list ll.reverse_frist_k(5) # print the reversed linked list ll.print_list()
true
b1507117769677b028c86f588a88e91e67ef410f
asperaa/programming_problems
/binary_search/sqrt(x).py
385
4.1875
4
"""sqrt of a number using binary search""" def sqrtt(x): if x < 2: return x l = 2 r = x//2 while l <= r: pivot = l + (r-l)//2 num = pivot*pivot if num > x: r = pivot - 1 elif num < x: l = pivot + 1 else: return pivot return r if __name__ == "__main__": print(sqrtt(15))
false
9bd1ec0e8941bae713a60098d73bc0d7f996bf9c
eldimko/coffee-machine
/stage3.py
1,047
4.34375
4
water_per_cup = 200 milk_per_cup = 50 beans_per_cup = 15 water_stock = int(input("Write how many ml of water the coffee machine has:")) milk_stock = int(input("Write how many ml of milk the coffee machine has:")) beans_stock = int(input("Write how many grams of coffee beans the coffee machine has:")) cups = int(input("Write how many cups of coffee you will need:")) most_water_cups = water_stock // water_per_cup most_milk_cups = milk_stock // milk_per_cup most_beans_cups = beans_stock // beans_per_cup # find the smallest amount of cups out of the list in order to find the most cups of coffee that are possible to be made most_cups_list = [most_water_cups, most_milk_cups, most_beans_cups] most_cups_list.sort() most_cups = most_cups_list[0] if most_cups == cups: print("Yes, I can make that amount of coffee") elif most_cups < cups: print("No, I can make only {} cups of coffee".format(most_cups)) elif most_cups > cups: print("Yes, I can make that amount of coffee (and even {} more than that)".format(most_cups - cups))
true
69a1845303537328dfd0db3c2379b2d094643633
satya497/Python
/Python/storytelling.py
1,340
4.15625
4
storyFormat = """ Once upon a time, deep in an ancient jungle, there lived a {animal}. This {animal} liked to eat {food}, but the jungle had very little {food} to offer. One day, an explorer found the {animal} and discovered it liked {food}. The explorer took the {animal} back to {city}, where it could eat as much {food} as it wanted. However, the {animal} became homesick, so the explorer brought it back to the jungle, leaving a large supply of {food}. The End """ def tellStory(): userPicks = dict() addPick('animal', userPicks) addPick('food', userPicks) addPick('city', userPicks) story = storyFormat.format(**userPicks) print(story) def addPick(cue, dictionary): '''Prompt for a user response using the cue string, and place the cue-response pair in the dictionary. ''' prompt = 'Enter an example for ' + cue + ': ' response = input(prompt).strip() # 3.2 Windows bug fix dictionary[cue] = response tellStory() input("Press Enter to end the program.")
true
0f4005420c98c407a9d02e6f601c2fccbf536114
satya497/Python
/Python/classes and objects.py
775
4.46875
4
# this program about objects and classes # a class is like a object constructor #The __init__() function is called automatically every time the class is being used to create a new object. class classroom: def __init__(self, name, age): # methods self.name=name self.age=age def myfunc1(self): print("my name is "+self.name) print(self.name+" age is "+str(self.age)) p1=classroom("satya",23) p2=classroom("ravi",21) p3=classroom("akhil",24) p1.age=22 p1.myfunc1() p2.myfunc1() p3.myfunc1() class myclass: def reversing(self,s): return ' '.join(reversed(s.split())) print(myclass().reversing('my name is')) str1 = "how are you" str2=str1.split(" ") output = ' '.join(str2) print(reversed(str2))
true
5b7f40cc69402346f9a029c07246da2286022c7f
Vk686/week4
/hello.py
212
4.28125
4
tempName = "Hello <<UserName>>, How are you?" username = input("Enter User Name: ") if len(username) < 5: print("User Name must have 5 characters.") else: print(tempName.replace("<<UserName>>",username))
true
1596d1d1e7ef22f858dad005741768c7887a5a0e
wardragon2096/Week-2
/Ch.3 Project1.1.py
296
4.28125
4
side1=input("Enter the first side of the triangle: ") side2=input("Enter the second side of the triangle: ") side3=input("Enter the thrid side of the triangle: ") if side1==side2==side3: print("This is an equilateral triangle.") else: print("This is not an equilateral triangle.")
true
63bcca7240f1f8464135732d795e80b3e95ddd1f
RichardLitt/euler
/007.py
565
4.125
4
# What is the 10001st prime? # Import library to read from terminal import sys # Find if a number is prime def is_prime(num): if (num == 2): return True for x in range(2, num/2+1): if (num % x == 0): return False else: return True # List all primes in order def list_primes(stop): found = 0 current_num = 2 while (found != stop): if (is_prime(current_num)): found += 1 previous_num = current_num current_num += 1 print previous_num list_primes(int(sys.argv[1]))
true
2c91f734d48c6d0ab620b6b5a9715dc4f5e4ddb7
smoke-hux/pyhton-codes
/2Dlistmatrixes.py
1,044
4.46875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 05:54:12 2020 @author: root """ matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1]) matrix[0][1] = 20 print(matrix[0][1]) #we can use nested loops to iterate over every item in the list for row in matrix:#in each row it will contain one list one item for item in row:#used to loop over eacch row that is a list items print(item) numbers = [5, 2, 1, 7, 4] numbers.append(20)#append is used to add item to a list print(numbers) numbers.insert(0, 10)#used when one wants to insert a value to the where one desires and the first digit is the index and the second digits is the number you want to add print(numbers) numbers.remove(10)# if you want to remove an item in the list print(numbers) numbers.pop()#removes the last item on the list print(numbers) print(numbers.index(54))#is used tocheck the index of a given value in the list and also the existence of the given value print(50 in numbers)
true
4d1f17b48ad9d60432702e4f440b5b42e8182796
ViniciusLoures/BCC701
/[P-04]/p04q04.py
1,223
4.125
4
# Vinicius Alves Loures França 20.1.1039 years = int(input('Anos de experiência: ')) language = int(input('Linguagens de programação: ')) projects = int(input('Projetos: ')) diff_years = 3 - years diff_language = 3 - language diff_projects = 5 - projects diff_years_senior = 10 - years diff_language_senior = 5 - language diff_projects_senior = 10 - projects if years < 3 or language < 3 or projects < 5: print('Concorrendo à Vaga Júnior. Para concorrer à Vaga Pleno, faltam: ') if diff_years > 0: print(f'− {diff_years} anos de experiência') if diff_language > 0: print(f'− {diff_language} linguagens de programação') if diff_projects > 0: print(f'- {diff_projects} projetos') elif years >= 10 and language >= 5 and projects >= 10: print('Concorrendo à Vaga Sênior') elif years >= 3 and language >= 3 and projects >= 5: print('Concorrendo à Vaga Pleno. Para concorrer à Vaga Sênior, faltam: ') if diff_years_senior > 0: print(f'− {diff_years_senior} anos de experiência') if diff_language_senior > 0: print(f'− {diff_language_senior} linguagens de programação') if diff_projects_senior > 0: print(f'- {diff_projects_senior} projetos')
false
7f44a3ce1ebc5dc682fb9a71a62413640101ed46
mdev-qn95/python-code40
/challenge-counter-app.py
642
4.15625
4
# Basic Data Types Challenge 1: Letter Counter App print("Welcome to the Letter Counter App") # Get user input name = input("\nWhat's your name: ").title().strip() print("Hello, " + name + "!") print("I'll count the number of times that a specific letter occurs in a message.") message = input("\nPlease enter a message: ") letter = input("Which letter would you like to count the occrrences of: ") # Standardize message = message.lower() letter = letter.lower() # Get the count and display results letter_count = message.count(letter) print("\n" + name + ", your message has " + str(letter_count) + " character '" + letter + "' in it.")
true
e5162cfd848d2079cd0a2783413cdce62c365e39
rajkamalthanikachalam/PythonLearningMaterial
/com/dev/pythonSessions/07Functions.py
2,940
4.5625
5
# Function: a piece of code to execute a repeated functions # Recursion: A function calling itself # Arguments : *arg is used to pass a single arguments # Key words : **args is used to pass a multiple arguments in key & value format # Lambda functions : Anonymous functions or function without name # Function def function(username): print(username) function(username="test1") def function(username, password): print(username, password) function("user1", "test123") # You can pass arguments in both way function(username="user1", password="test123") # You can pass arguments in both way # Functions with no arguments def function1(): # syntax to define a function print("My First Function with no argument") function1() # Functions with single arguments def function2(a): print("Function with single argument : %d" % a) return function2 function2(100) # Functions with two arguments and return def function3(a, b): c = a+b print("Function with two arguments : %d" % c) return c function3(10, 15) # Functions with default/Optional parameter def function4(name="None Selected"): print(name) function4() function4("India") function4("Australia") # Functions with List def function5(name): for index in name: print(index) countryName = ["India", "Australia", "Africa", "America"] function5(countryName) # Functions with if- Else statement def function6(country_name): if country_name == "India": print("Capital is New Delhi") elif country_name == "Australia": print("Capital is Melbourne") elif country_name == "Africa": print("Capital is Cape Town") elif country_name == "America": print("Capital is Washington DC") else: print("Not in the list") function6("China") # Recursion : Function calling itself , ie factorial of 5 (5*4*3*2*1) def recursion(num): if num > 1: num = num * recursion(num-1) return num print(recursion(5)) # Arguments print("********************************Arguments**************************************") def arguments(*arg): for x in arg: print(x) arguments(10, 12, 15, 18, 19) arguments("Maths", "Science", "History", "English") print("********************************Key word Arguments**************************************") # **args is syntax # for key, value in args.items(): is syntax def arguments(**args): for key, value in args.items(): print("%s == %s" % (key, value)) arguments(user1="test1", user2="test2", user3="test3") arguments(xyz=10, abc=20, ijk=30) # Lambda # syntax lambda x: define the function after colon print("********************************Lambda**************************************") cube = lambda n: n*n*n cubeX = cube(4) print("Cube of C is %d" % cubeX) total = lambda mark: mark+30 sumTotal = total(150) print("Total mark earned is %d" % sumTotal)
true
3c83bcb69b992b68845482fbe0cf930bb0faaf22
Japan199/PYTHON-PRACTICAL
/practical2_1.py
257
4.21875
4
number=int(input("enter the number:")) if(number%2==0): if(number%4==0): print("number is a multiple of 2 and 4") else: print("number is multiple of only 2") else: print("number is odd")
true
98d91f20f106a8787e87e6e18bfb0388bb96a24e
Douglass-Jeffrey/Assignment-0-2B-Python
/Triangle_calculator.py
499
4.25
4
#!/usr/bin/env python3 # Created by: Douglass Jeffrey # Created on: Oct 2019 # This program calculates area of triangles def main(): # this function calculates the area of the triangles # input num1 = int(input("Input the base length of the triangle: ")) num2 = int(input("Input the height of the triangle: ")) # process answer = (num1*num2)/2 # output print("") print("The area of the triangle is {} units^2".format(answer)) if __name__ == "__main__": main()
true
73b8058f76913080f172dd81ab7b76b1889faa11
ibrahimuslu/udacity-p2
/problem_2.py
2,115
4.15625
4
import math def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ def findPivot(input_list,start,end): if start == end: return start if (end - start) == 1: return end if (start - end) == 1: return start mid = (start+ end)//2 if input_list[mid] > input_list[end]: return findPivot(input_list,mid,end) elif input_list[mid] < input_list[end]: return findPivot(input_list,start,mid) else: return mid pivot = findPivot(input_list,0,len(input_list)-1) size = len(input_list) # print(input_list[pivot]) def findNumber(input_list, number, pivot, start, end): # print(input_list, number, pivot,start, end) if number == input_list[pivot]: return pivot elif number >= input_list[pivot] and number <= input_list[end]: return findNumber(input_list, number, math.ceil((end-pivot)/2)+pivot, pivot,end) elif number >= input_list[0] and number <= input_list[pivot-1]: return findNumber(input_list, number, math.ceil((pivot-start)/2), 0,pivot-1) else: return -1 return findNumber(input_list, number, pivot, 0, size-1) def linear_search(input_list, number): for index, element in enumerate(input_list): if element == number: return index return -1 def test_function(test_case): input_list = test_case[0] number = test_case[1] a=linear_search(input_list, number) b=rotated_array_search(input_list, number) # print(a, b) if (a == b): print("Pass") else: print("Fail") test_function([[6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22, 1, 2, 3, 4], 3]) test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 8]) test_function([[6, 7, 8, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 10])
true
894bc08ece7968512d1214ea6853199951b49de5
ffismine/leetcode_github
/普通分类/tag分类_链表/2_两数相加.py
1,657
4.125
4
""" 2. 两数相加 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ # 思考: # 需要注意几个点:1,位数不相等 2,进位 3,最后还要进位 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from tag_listnode import ListNode class Solution: # 2. 两数相加 # 示例: # 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) # 输出:7 -> 0 -> 8 # 原因:342 + 465 = 807 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: res = cur = ListNode(-1) ten = 0 one = 0 v = 0 while l1 or l2: va1 = l1.val if l1 else 0 va2 = l2.val if l2 else 0 v = va1 + va2 + ten ten = v // 10 one = v % 10 cur.next = ListNode(one) if l1: l1 = l1.next if l2: l2 = l2.next cur = cur.next if ten != 0: cur.next = ListNode(ten) return res.next l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(9) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) Solution().addTwoNumbers(l1, l2)
false
b2b27d69caeab17bc3150e1afe9c1e1de3ac5d9e
aniketchanana/python-exercise-files
/programmes/listMethods.py
922
4.46875
4
# methods are particular to a given class # append insert & extend first_list = [1,2,3,4,5] # first_list.append([1,2,3]) # print(first_list) # [1, 2, 3, 4, 5, [1, 2, 3]] simply pushes it inside the list # no matter what is that <<append takes in only one arguement>> # first_list.extend([1,2,3,4]) # print(first_list) # first_list.insert(2,"hi") # print(first_list) # first_list.clear() # print(first_list) # print(first_list.pop(first_list.index(3))) # print(first_list) # first_list.remove(2) # print(first_list) #---------------------------------------------------------------# # important functions related to list # list.index(element) # list.index(element,startIndex) # list.index(element,startIndex,endIndex) # list.count(element) # first_list.reverse() # print(first_list) # first_list.sort() # str = "a,n,i,k,e,t" # print(str.split(",")) # join works with list of strings # print(' .'.join(str))
true
5fbbfd843c662a09a20b1e5bad1861a2a82f53fa
aniketchanana/python-exercise-files
/programmes/bouncer.py
270
4.125
4
age = input("How old are you") if age : age = int(age) if age >= 18 and age < 21 : print("Need a wrist band") elif age>=21 : print("you can enter and drink") else : print("too little to enter") else : print("Input is empty")
true
3b582f75705736982841af1acc369baa26287f05
ethomas1541/Treehouse-Python-Techdegree-Project-1
/guessing_game.py
2,919
4.15625
4
""" Treehouse Python Techdegree Project 1 - Number Guessing Game Elijah Thomas /2020 """ """ Tried to make my code a bit fancy. I have a bit of knowledge beyond what's been taught to me thus far in the techdegree, and I plan to use it to streamline the program as much as I can. """ #Also, fair warning, I use a ton of \n newlines to make the output look better. import random def start_game(): guesses = 0 #Amount of user's guesses so far feedback = "What is your guess?" #This variable will be what's printed when asking the user for their guess. It changes based on the user's answer and how it relates to the answer (lesser/greater) plural = "guess" #This just determines whether "guess" or "guesses" is printed at the end of the game, just a grammatical fix. guessed = [] #List containing any numbers the player has already guessed. answer = random.choice(range(1, 11)) print("\nWelcome to my number guessing game!\nI'm going to pick a number between 1 and 10. Can you guess what it is?\n") while True: #Main loop in which the entire game runs. Breaks when the user wins. while True: #Loop to obtain acceptable input (integer 1-10). Will only break if this is achieved. userInput = input(f"\n{feedback}\n\n") try: userInt = int(userInput) if userInt < 1: print("\nThat's too low!") raise ValueError elif userInt > 10: print("\nThat's too high!") raise ValueError break except ValueError: print("\nPlease enter a whole number between 1 and 10.") guesses += 1 if guesses > 1: plural = "guesses" if userInt == answer: break #This will break the main loop, and the user will win the game. elif userInt < answer: feedback = "The answer's bigger!" else: feedback = "The answer's smaller!" if userInt in guessed: feedback += " You already guessed that!" #Adds a comment to the feedback variable if the user already guessed this number. else: guessed.append(userInt) #Adds the user's input into the list of guesses if it's not already there. if input(f"\nCongratulations! You guessed it! The answer was {answer}! You got it in {guesses} {plural}!\n\nPlay again? (y/n)\n\n") in ("y", "Y", "yes", "Yes"): #This is a long line, but it basically announces that you won and asks if you want to play again, all in the same stroke. start_game() else: exit() start_game() #I was going for the "exceeds expectations" requirements for this project, but chose to omit the high-score system. I thought it'd be a bit too tedious to implement it, so I'm good with just meeting the expectations.
true
7e8e5cd20755bc9967dc6800b3614fdc9c8cc8d3
Sheax045/SWDV660
/Week1/week-1-review-Sheax045/temp_converter.py
371
4.375
4
# Please modify the following program to now convert from input Fahrenheit # to Celsius def doConversion(): tempInFAsString = input('Enter the temperature in Fahrenheit: ') tempInF = float( tempInFAsString ) tempInC = ( tempInF - 32 ) / 1.8 print('The temperature in Celsius is', tempInC, 'degrees') for conversionCount in range( 3 ): doConversion()
true
72e99be26206ee4fefa8154ca8ee53403f01ae6d
JavierEsteban/TodoPython
/Ejercicios/DesdeCero/1.- Variables y Tipos de Datos/3.- Ejercicios.py
1,580
4.28125
4
## Hallar el promedio de notas con los pesos enviados def main(): nota_1 = 10 nota_2 = 7 nota_3 = 4 notafinal = 10*0.15 + 7*0.35 + 4*0.5 print(notafinal) # Completa el ejercicio aquí if __name__ =='__main__': main() #Ejercicio que cada ultimo registro de la matriz sume los 3 primeros. def main(): matriz = [ [1, 1, 1, 3], [2, 2, 2, 7], [3, 3, 3, 9], [4, 4, 4, 13] ] ##print(matriz[1][:]) ##print(len(matriz)) ##print(sum(matriz)) print("########### Antes ###############") print(matriz) contador = 0 while contador < len(matriz): print(matriz[contador][:3]) matriz[contador][3] = sum(matriz[contador][:3]) contador = contador + 1 print("########### Después ###############") print(matriz) if __name__ == '__main__': print("################# Ejecutando Programa #####################") main() ####Los nombres está al reves def main(): cadena = "zeréP nauJ,01" print("########### Antes ###############") print("\n"*2) print(cadena) print("\n"*2) print("########### Después ###############") print("\n"*2) print(cadena[::-1]) if __name__ =='__main__': main() #Ejercicio que cada ultimo registro de la matriz sume los 3 primeros. def main(): matriz = [ [1, 1, 1, 3], [2, 2, 2, 7], [3, 3, 3, 9], [4, 4, 4, 13] ] print(matriz) for indice, i in enumerate(matriz): i[3] = sum(i[:3]) print(matriz) if __name__ =='__main__': main()
false
9e62ba08fa01e6a2d0e3c9aecf93e43c0600992e
hemiaoio/learn-python
/lesson-01/currency_converter_v4.0.py
573
4.25
4
def convert_currency(in_money,exchange_rate): out_money = in_money * exchange_rate return out_money USD_VS_RMB = 6.77 currency_str_value = input("请输入带单位的货币:") # 获取货币单位 unit = currency_str_value[-3:] if unit == 'CNY': exchange_rate = 1/USD_VS_RMB elif unit == 'USD': exchange_rate = USD_VS_RMB else: exchange_rate = -1 if exchange_rate != -1: in_money = eval(currency_str_value[:-3]) result = convert_currency(in_money,exchange_rate) print('计算结果:',result) else: print('不支持的单位')
false
7f5a62963e620a00f8e30baf529d82007c1d9076
hemiaoio/learn-python
/lesson-01/currency_converter_v2.0.py
522
4.1875
4
USD_VS_RMB = 6.77 currency_str_value = input("请输入带单位的货币:") # 获取货币单位 unit = currency_str_value[-3:] if unit == 'CNY': rmb_str_value = currency_str_value[:-3] rmb_value = eval(rmb_str_value) usd_value = rmb_value / USD_VS_RMB print('CNY to USD :', usd_value) elif unit == 'USD': usd_str_value = currency_str_value[:-3] usd_value = eval(usd_str_value) rmb_value = usd_value * USD_VS_RMB print('USD to CNY:', rmb_value) else: print('暂不支持此单位')
false
f1c33d5a000f7f70691e10da2bad54de62fc9a8d
sugia/leetcode
/Integer Break.py
648
4.125
4
''' Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1. Example 2: Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. Note: You may assume that n is not less than 2 and not larger than 58. ''' class Solution: def integerBreak(self, n: int) -> int: if n == 2: return 1 if n == 3: return 2 res = 1 while n > 4: res *= 3 n -= 3 res *= n return res
true
a3fc906021f03ed53ad43fbc133d253f74e56daa
sugia/leetcode
/Valid Palindrome.py
697
4.15625
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false ''' class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ alpha = [] for c in s: if c.isalnum(): alpha.append(c.lower()) for i in xrange(len(alpha) // 2): if alpha[i] != alpha[len(alpha) - i - 1]: return False return True
true
396253f9798266c4b6b291f272aa7b79c6fa0a0a
sugia/leetcode
/Power of Two.py
498
4.125
4
''' Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Example 2: Input: 16 Output: true Example 3: Input: 218 Output: false ''' class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ bit_count = 0 while n > 0: bit_count += n & 1 n >>= 1 if bit_count == 1: return True return False
true
1c59ace51e212ef319a09a5703d88b878ca494e8
sugia/leetcode
/Group Shifted Strings.py
1,102
4.15625
4
''' Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. Example: Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Output: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] ''' class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ dic = {} for s in strings: key = self.getKey(s) if key in dic: dic[key].append(s) else: dic[key] = [s] return dic.values() def getKey(self, s): vec = [ord(c) for c in s] tmp = vec[0] for i in xrange(len(vec)): vec[i] -= tmp if vec[i] < 0: vec[i] += 26 return ''.join([chr(x + ord('a')) for x in vec])
true
cd46ca9292716451523c2fb59813627274928af3
sugia/leetcode
/Strobogrammatic Number II.py
1,197
4.15625
4
''' A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"] ''' class Solution(object): def findStrobogrammatic(self, n): """ :type n: int :rtype: List[str] """ ''' 1 = 1 6 = 9 8 = 8 9 = 6 0 = 0 ''' res = [] tmp = ['' for i in xrange(n)] pairs = {1:1, 6:9, 8:8, 9:6, 0:0} self.find(pairs, 0, n - 1, tmp, res) return res def find(self, pairs, start, end, tmp, res): if start == end: for i in [0, 1, 8]: tmp[start] = i res.append(''.join([str(x) for x in tmp])) elif start > end: res.append(''.join([str(x) for x in tmp])) else: for k, v in pairs.iteritems(): if start == 0 and k == 0: continue tmp[start] = k tmp[end] = v self.find(pairs, start + 1, end - 1, tmp, res)
true
e0e326f07a8f166d9e424ddd646e563b5e817da9
sugia/leetcode
/Solve the Equation.py
2,867
4.3125
4
''' Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient. If there is no solution for the equation, return "No solution". If there are infinite solutions for the equation, return "Infinite solutions". If there is exactly one solution for the equation, we ensure that the value of x is an integer. Example 1: Input: "x+5-3+x=6+x-2" Output: "x=2" Example 2: Input: "x=x" Output: "Infinite solutions" Example 3: Input: "2x=x" Output: "x=0" Example 4: Input: "2x+3x-6x=x+2" Output: "x=-1" Example 5: Input: "x=x+2" Output: "No solution" ''' class Solution(object): def solveEquation(self, equation): """ :type equation: str :rtype: str """ equal_idx = equation.index('=') if equal_idx == -1: return 'Infinite solution' left = self.get(equation[:equal_idx]) right = self.get(equation[equal_idx+1:]) variable = [] constant = [] for x in left: if 'x' in x: variable.append(x) else: constant.append(self.neg(x)) for x in right: if 'x' in x: variable.append(self.neg(x)) else: constant.append(x) v = self.solve(variable) c = self.solve(constant) if v == '0': if c == '0': return 'Infinite solutions' else: return 'No solution' else: a = v[:-1] if a: a = int(a) else: a = 1 return 'x=' + str(int(c) // a) def get(self, s): vec = [] start = 0 for end in xrange(1, len(s)): if s[end] in '+-': vec.append(s[start:end]) start = end vec.append(s[start:]) return vec def neg(self, x): if x[0] == '+': return '-' + x[1:] if x[0] == '-': return x[1:] return '-' + x def solve(self, vec): if not vec: return '0' res = 0 sign = False if 'x' in vec[0]: sign = True for x in vec: if x[-1] == 'x': y = x[:-1] if y == '' or y == '+': y = 1 elif y == '-': y = -1 else: y = int(x[:-1]) res += y else: res += int(x) if sign: if res == 0: return '0' elif res == 1: return 'x' else: return str(res) + 'x' else: return str(res)
true
8c3ae2289cd214e6288ede5de4a2e296f5d3983b
sugia/leetcode
/Largest Triangle Area.py
1,047
4.15625
4
''' You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points. Example: Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]] Output: 2 Explanation: The five points are show in the figure below. The red triangle is the largest. Notes: 3 <= points.length <= 50. No points will be duplicated. -50 <= points[i][j] <= 50. Answers within 10^-6 of the true value will be accepted as correct. ''' class Solution(object): def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ res = 0 for i in xrange(len(points)): for j in xrange(i+1, len(points)): for k in xrange(j+1, len(points)): res = max(res, self.getArea(points[i][0], points[i][1], points[j][0], points[j][1], points[k][0], points[k][1])) return res def getArea(self, x1, y1, x2, y2, x3, y3): return abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0
true
55926ff3a2bebfaad166335cff41c9edc9aba9a6
joseph-palermo/ICS3U-Assignment-02B-Python
/assignment_two.py
527
4.34375
4
#!/usr/bin/env python3 # Created by: Joseph Palermo # Created on: October 2019 # This program calculates the area of a sector of a circle import math def main(): # This function calculates the area of a sector of a circle # input radius = int(input("Enter the radius: ")) angle_θ = int(input("Enter the angle θ: ")) # process area = math.pi * radius ** 2 * angle_θ / 360 # output print("") print("The area is: {:,.2f}cm^2 " .format(area)) if __name__ == "__main__": main()
true
89a55032338f6872b581bbabdfa13670f9520666
Derin-Wilson/Numerical-Methods
/bisection_.py
998
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 4 19:12:56 2020 @author: esha """ # Python program for implementation # of Bisection Method for # solving equations # An example function whose # solution is determined using # Bisection Method. # The function is x^3 - x^2 + 2 def func(x): return x**3 - x**2 + 2 # Prints root of func(x) # with error of EPSILON def bisection(a,b): if (func(a) * func(b) >= 0): print("You have not assumed right a and b\n") c = a while (((b-a))>= 0.01): # Find middle point c = (a+b)/2 # Check if middle point is root if (func(c) == 0.0): break # Decide the side to repeat the steps if (func(c)*func(a) < 0): b = c else: a = c print("The value of root is : ","%.4f"%c) # Driver code # Initial values assumed a =-200 b = 300 bisection(a, b)
true
b04dee090d6f39bb7ad5a6f31f8a1ad99ada9234
clhking/lpthw
/ex4.py
1,277
4.28125
4
# Set a variable for the number of cars cars = 100 # Set a variable (using a float) for space in each car space_in_a_car = 4 # Set a variable with number of drivers drivers = 30 # Set a variable with number of passengers passengers = 90 # Set up the variable for cars not driven being # of cars minus number of drivers cars_not_driven = cars - drivers # set a variable cars = drivers # this could be wrong in the future, there should be a check for cars gte drivers cars_driven = drivers # setup carpool_capacity being space in cars multiplied by cars_driven carpool_capacity = cars_driven * space_in_a_car # setup avg_pass_per_car as being passengers divided by cars_driven average_passengers_per_car = passengers / cars_driven # print out number of cars print "There are", cars, "cars available." # print out number of drivers print "There are only", drivers, "drivers available." # print out number of cars not driven print "There will be", cars_not_driven, "empty cars today." # print out the carpool capacity print "We can transport", carpool_capacity, "people today." # print out number of passengers print "We have", passengers, "to carpool today." # print out avg # of passengers per car print "We need to put about", average_passengers_per_car, "in each car."
true
3d7c45fb38fd221bca8a9cb22f7509d0106fca65
EricksonSiqueira/curso-em-video-python-3
/Mundo 3 estruturas de dados/Aula 16 (tuplas)/Desafio 074(maior e menor).py
808
4.1875
4
# Crie um programa que vai gerar cinco números aleatório # e colocar em uma tupla. Depois disso, mostre a listagem de números # gerados e também indique o menor e o maior valor que estão na tupla. from random import randint numeros = (randint(0, 20), randint(0, 20), randint(0, 20), randint(0, 20), randint(0, 20)) menor = maior = 0 print("Números gerados : ", end='') for c in range(0, 5): print(numeros[c], end=' ') # minha solução """if c == 0: menor = numeros[c] maior = numeros[c] else: if numeros[c] > maior: maior = numeros[c] if numeros[c] < menor: menor = numeros[c] print(f'\nO menor número é {menor}\nO maior é {maior}')""" #Solução Guanabara print(f"\nO menor valor é {min(numeros)}\nO maior é {max(numeros)}")
false
8a55c35f58b0e598cb6e544df24dcdb02048824c
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 15 (do while)/Desafio 071 (Caixa eletronico).py
1,134
4.21875
4
# Crie um programa que simule o funcionamento de um caixa eletrônico. # No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e # o programa vai informar quantas cédulas de cada valor serão entregues. # OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. print("{:=^34}".format(' BANCO DO ERISU ')) valor = float(input("Quando você deseja sacar? R$")) cinquenta = vinte = dez = um = 0 while True: if valor // 50 >= 1: cinquenta = valor // 50 valor = valor % 50 print(f"Total de {cinquenta:.0f} cedulas de R$50") elif valor // 20 >= 1: vinte = valor // 20 print(f"Total de {vinte:.0f} cedulas de R$20") valor = valor % 20 elif valor // 10 >= 1: dez = valor // 10 valor = valor % 10 print(f"Total de {dez:.0f} cedulas de R$10") elif valor // 1 >= 1: um = valor // 1 valor = valor % 1 print(f"Total de {um:.0f} cedulas de R$1") if valor <= 0: break print("="*36) print("OBRIGADO POR UTILIZAR OS SERVIÇOS DO BANCO ERISU!\nTENHA UM ÓTIMO DIA! VOLTE SEMPRE!")
false
906d4238eda704289808ee8c99a5388d10f4c948
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 14 (while)/Desafio 065 (Maior e Menor).py
762
4.15625
4
# Crie um programa que leia vários números inteiros pelo teclado. No final da # execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. r = 's' s = 0 media = 0 maior = 0 menor = 0 c = 0 while r != 'n': n = int(input("Digite um número: ")) if c == 0: maior = n menor = n media = n else: if n > maior: maior = n if n < menor: menor = n media += n c += 1 r = str(input("Deseja continuar? [s/n] ")).lower().strip() media = media/c print(f"Você digitou {c} números e a média foi {media}.\nO maior valor foi {maior} e o menor foi {menor}.")
false
5a693ea54065d8ee521cddb8be003f7f357813bb
joelhrobinson/Python_Code
/object types.py
668
4.25
4
########################## # this is a list mylist = [1, "joel", 2, 'henry', 3, 'Robinson', 4, "Brenda"] print ('mylist=',mylist) mydict = {"mykey":"value", "Name":"Frankie"} print ('mydictionary=',mydict) mytuple = tuple(mylist) print ('mytuple=',mytuple) print (type(mytuple)) ################################ # parse strings mystring = "Hello" print (" string indexing starts at zero", mystring[0]) # indexing starts at zero print (" string (1) and string (-1) ", mystring[1], mystring[-4]) # prints an e and an e print ("Hello with line feed here: \n world") # LINE FEED print ("Hello with tab here: \t world") # TAB
false
c7796becfd43fdc5339bf2b707390c090a2ed8c9
SergioOrtegaMartin/Programacion-Python
/3er Trimestre/Ej 11/Ej 11.py
2,537
4.15625
4
'''a)Hacer un ejercicio donde se crea una agenda en formato csv Para ello el usuario introduce 3 valores (nombre, tel, email) hasta que el nombre sea una cadena vacia Esta función debe ser un archivo csv que guardaremos como ‘agenda.csv’''' '''b)crear otra funcion (carga)que le paso el nombre de la agenda y me la carga en un diccionario que tiene como clave el nombre y como valor el registro completo como una tupla por ejemplo: {pepe: ('pepe', 44, 622367745)}''' '''c) Una tercera funcion permite consultar de forma interactiva el telefono y el mail pide nombre y devuelve telefono y mail BUCLE''' '''Controlar como excepciones que el fichero no exista, que en el fichero exista un formato diferente al que tenemos (Que haya mas de 3 valores), y en la lectura verificar que el contacto exista(contacto error)''' modo = input('Si quieres añadir texto a un fichero, pulsa la tecla a, si quieres reemplazar el contenido pulsa le tecla w \n') fichero = input('Introduce el nombre del fichero \n') def agenda(fichero,modo): try: f = open(fichero + '.csv', modo) print('Agenda creada con el nombre --->', fichero) print('Escribirás linea a linea hasta que introduzcas el nombre vacio') #f.write('Nombre, telefono, email') #f.write('\n') nombre = input('Introduce el nombre: \n') while nombre!= '': f.write(nombre + ',') telefono = input('Introduce el telefono: \n') f.write(telefono + ',') email = input('Introduce el email: \n' ) f.write(email + ',') f.write('\n') nombre = input('Introduce el nombre: \n') except(PermissionError): print('No tienes permisos para abrir el archivo, prueba a cerrarlo si lo tienes abierto con otro programa') agenda(fichero,modo) '''b)crear otra funcion (carga)que le paso el nombre de la agenda y me la cargue en un diccionario que tiene como clave el nombre y como valor el registro completo como una tupla por ejemplo: {pepe: ('pepe', 44, 622367745)}''' def carga(fichero): try: lista=[] diccionario={} f = open(fichero) lineas = [linea.split(',') for linea in f] for linea in lineas: linea.pop() diccionario[linea[0]]=tuple(linea) print(diccionario) except FileNotFoundError: print("Este fichero no existe")
false
e82a0d351645c38a97eb004714aae9ab377e13f4
vaelentine/CoolClubProjects
/mags/codewars/get_middle_char.py
1,231
4.3125
4
""" Get the middle character From codewars https://www.codewars.com/kata/56747fd5cb988479af000028/train/python You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. #Examples: Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A" """ # unit test case import unittest def get_middle(s): # if length of word % 2 == 0, you'd return index 1 & 2 #middle character of dog, len 3, would be 1. return s[len(s)/2-1:len(s)//2+1] if len(s) % 2 == 0 else s[len(s)/2] class TestFunction(unittest.TestCase): def test1(self): self.assertEqual(get_middle("test"), "es") def test2(self): self.assertEqual(get_middle("testing"), "t") def test3(self): self.assertEqual(get_middle("middle"), "dd") def test4(self): self.assertEqual(get_middle("A"), "A") def test5(self): self.assertEqual(get_middle("of"), "of") if __name__ == '__main__': unittest.main()
true
51b06ab89a0b7a96d973ad14a2a75703697e5d2c
JMBarberio/Penn-Labs-Server-Challenge
/user.py
2,532
4.15625
4
class User(): """ The user class that contains user information. Attributes: ----------- name : str The name of the user. clubs : list The list of the clubs that the user is in fav_list : list The bool list of whether or not a club has been favorited """ def __init__(self, name, clubs): self.__name = name self.__clubs = clubs self.__fav_list = [] for club in range(0, len(clubs)): self.__fav_list.append(False) def get_user_name(self): """ Getter for the club name Returns: -------- str The club name """ return self.__name def set_user_name(self, new_name): """ Setter for the club name Arguements: ----------- new_name : str The new user name """ self.__name = new_name def get_user_clubs(self): """ Getter for the list of clubs Returns: -------- list The list of clubs """ return self.__clubs def get_fav_list(self): """ Getter for the favorite list Returns: -------- list The bool list of favorites """ return self.__fav_list def add(self, new_club): """ Adds a new club to the club list Arguements: ----------- new_club : Club The new club to be added TODO: add throws for club not found """ self.__clubs.append(new_club) self.__fav_list.append(false) def remove(self, club): """ Removes a club from the club list if the club is in the current list Pops the boolean from the bool list at the corresponding index If the corresponding bool was True, the favorite count for that club is decreased Arguments: ---------- club : Club The club to be removed Throws: ------- """ try: index = self.__clubs.index(club) if self.__fav_list[index] == True: club.decrease() self.__clubs.remove(club) self.__fav_list.pop(index) except ValueError: raise e
true
817d35dd6ee95282807850ca348a78528516beed
jhill57/Module-4-Lab-Activity-
/grading corrected.py
1,553
4.4375
4
# Calculating Grades (ok, let me think about this one) # Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing. # Average Grade # 90+ A # 80-89 B # 70-79 C # 60-69 D # 0-59 F # Exams: 89, 90, 90 # Average: 90 # Grade: A # Student is passing. # Exams: 50, 51, 0 # Average: 33 # Grade: F # Student iis failing. # this code was edited by Jordan on 2/8/2020 exam_one = int(input("Input exam grade one: ")) exam_two = int(input("Input exam grade two: ")) exam_3 = int(input("Input exam grade three: ")) # for this list use [] and not paranthesis # separate each with a comma..... the addition takes place is sum = sum + grade grades = (exam_one + exam_two + exam_3) sum = 0 # for grade in grades: for grades in grades: # sum = sum + grade sum = sum , grades # avg = sum / len(grades) avg = grades/3 if avg >= 90: letter_grade = "A" elif avg >= 80 and avg < 90: letter_grade = "B" elif avg > 70 and avg < 80: letter_grade = "C" elif avg >= 60 and avg <= 70: letter_grade = "D" #this should be else: since it is the last condition and no need for comparing avg any more. elif avg >= 50 and avg <= 59: letter_grade = "F" for grade in grades: print("Exam: " + str(grade)) #the last two prints are not part of the loop -- remove indentation print("Average: " + str(avg)) print("Grade: " + letter_grade) if letter-grade == "F": print ("Student is failing.") else: print ("Student is passing.")
true
1b48abeed7454fea2a67ed5afc2755932e093d32
CTEC-121-Spring-2020/mod-6-programming-assignment-tylerjjohnson64
/Prob-3/Prob-3.py
521
4.125
4
# Module 7 # Programming Assignment 10 # Prob-3.py # <Tyler Johnson> def main(): number = -1 while number <0.0: x = float(input("Enter a positive number to begin program: ")) if x >= 0.0: break sum = 0.0 while True: x = float(input("Enter a positive number to be added (negative to quit): ")) if x >= 0.0: sum = sum + x else: break print("This is the sum of numbers enterered: ",sum) main()
true
c9804338656ff356407de642e3241b44cc91d085
leon0241/adv-higher-python
/Term 1/Book-1_task-6-1_2.py
659
4.28125
4
#What would be the linked list for.. #'brown', 'dog.', 'fox', 'jumps', 'lazy', 'over', 'quick', 'red', 'The', 'the' #... to create the sentence... #'The quick brown fox jumps over the lazy dog' linkedList = [ ["brown", 2], #0 ["dog.", -1], #1 ["fox", 3], #2 ["jumps", 5], #3 ["lazy", 7], #4 ["over", 9], #5 ["quick", 0], #6 ["red", 1], #7 ["The", 6], #8 ["the", 4] #9 ] def print_linked_list(list, link): while link != -1: #Loop until end item, link = list[link] #Unpack the node print(item, end = ' ') #Display the item print() start = 8 print_linked_list(linkedList, start)
true
907c008de30d2238a729f5245af0623721d5f96e
leon0241/adv-higher-python
/Project Euler/Resources/prime_algorithms.py
1,225
4.21875
4
import math def find_primes(n): #Finds primes below n primeList = [2] for i in range(3, n, 2): primeList.append(i) #Makes array of odd number to number n(even numbers are not prime) for i in range(3, (int(math.sqrt(n)) + 1), 2): #cycle for i = 3 for j in primeList: if j % i == 0 and j > i: primeList.remove(j) return primeList def find_max_prime(n): #Finds the largest prime below n list = find_primes(n) return max(list) def check_prime(n): #Checks if n is a prime if n == 1: #Checks if n = 1 return False #Is not prime elif n <= 3: #Checks if n = 2 or 3 return True #Is prime i = 5 while i * i <= n: #k±1 shows prime number idk if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True #Returns true if it is prime def find_nth_prime(n): #Finds nth prime #Inequality for nth prime #pn > n*ln(n*ln(n)) for n ≥ 6. upperBound = n * math.log(n * math.log(n)) #Sets upper boundary intUpper = round(upperBound) #Rounds to nearest integer primeList = find_primes(intUpper) #Finds of primes below boundary return primeList[n - 1] #Return nth prime
false
b56a066a3e11ed1e8e3de30a9ed73c35975e8c2e
leon0241/adv-higher-python
/Pre-Summer/nat 5 tasks/task 6/task_6a.py
218
4.1875
4
name = input("what's your name? ") age = int(input("what's your age? ")) if age >= 4 and age <= 11: print("you should be in primary school") elif age >= 12 and age <= 17: print("you should be in high school")
true
f827f2a2a2f34903b2b9dfc738b603573f69aac4
gitHirsi/PythonNotes
/001基础/018面向对象/07搬家具.py
1,154
4.15625
4
""" @Author:Hirsi @Time:2020/6/11 22:32 """ # 定义家具类 两个属性:名字和占地面积 class Furniture(): def __init__(self, name, area): self.name = name self.area = area # 定义房屋类 4个属性:地理位置,房屋面积,剩余面积,家具列表 class House(): def __init__(self, address, area): self.address = address self.area = area self.free_area = area self.furniture = [] def add_furniture(self, item): """添加家具方法""" if self.free_area >= item.area: self.furniture.append(item.name) self.free_area -= item.area else: print('家具太大,剩余空间无法容纳!') def __str__(self): return f'房子坐落于{self.address},占地面积是{self.area}㎡,' \ f'剩余空间{self.free_area}㎡,里面的家具有{self.furniture}' bed = Furniture('双人床', 6) sofa = Furniture('沙发', 12) piano=Furniture('豪华钢琴',115) house = House('武汉', 120) house.add_furniture(bed) house.add_furniture(sofa) house.add_furniture(piano) print(house)
false
76c2bacefc0f6f33dfaf37682b8be84303754cdb
gitHirsi/PythonNotes
/001基础/019面向对象_继承/08私有属性和方法.py
1,609
4.1875
4
""" @Author:Hirsi @Time:2020/6/12 22:10 """ """ 1.定义私有属性和方法 2.获取和修改私有属性值 """ # 师傅类 class Master(object): def __init__(self): self.kongfu = '《师傅煎饼果子大法》' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 学校类 class School(object): def __init__(self): self.kongfu = '《学校煎饼果子大法》' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') # 徒弟类 class Prentice(School, Master): def __init__(self): self.kongfu = '《独创煎饼果子大法》' # 定义私有属性 self.__money = 2000000 # 定义函数:获取私有属性值 def get_money(self): return self.__money # 定义函数:修改私有属性值 def set_money(self,money): self.__money=money # self.__money=600 #也可不穿参数money,直接赋值 # 定义私有方法 def __info_print(self): print('这是私有方法') def make_cake(self): self.__init__() print(f'运用{self.kongfu}制作煎饼果子') def make_Master_cake(self): Master.__init__(self) Master.make_cake(self) def make_School_cake(self): School.__init__(self) School.make_cake(self) # 徒孙类 class TuSun(Prentice): pass QQ = TuSun() # print(QQ.money) # money定义私有后,无法访问 # QQ.info_print() # info_money定义私有后,无法访问 print(QQ.get_money()) QQ.set_money(12138) print(f'修改后:{QQ.get_money()}')
false
1eaba137311948a4042e1c25a0238d79db17f27b
SouriCat/pygame
/7_Intermédiaire __ La portee des variables et utilisation dans les fonctions.py
1,500
4.25
4
## Fonctionnement normal d'une fonction et des variables ##--> la variable locale est Dispo dans tous le documents, mais les fonctions doivent l'avoir en parametre pour l'utiliser var1 = "parametre1" var2 = "parametre2" def fonction(parametre1, parametre2): print (parametre1, "a bien été passé dans la fonction") print (parametre2, "a bien été passé dans la fonction") variable_locale = parametre1 + parametre2 return variable_locale retour_de_la_variable_locale = fonction(var1, var2) print () ##--> La portée des variables. Certaines variables peuvent être disponible dans tout le document : les tableaux, les var globale et les tuples # La fausse variable locale variable_locale_racine = "variable simple " # Le tableau naturellement global tableau = [10,10,10] # Les tuples sont des variables globales que l'on ne peut modifier tuple1 = (10, 20, 30, 40) def fonction_2(): # Variables superglobales global variable_locale_racine # Va chercher la variable dans les fonctions parentes, sans qu'elle passe par les paramètres variable_locale_racine += " avec un texte ajouté avec la fonction -fonction-" # Le tableau est utilisable partout. Une modif ici affecte l'ensemble tableau[0] += 5 # Utilisation des tuples. variable_tuple = tuple1[2] variable_tuple += 1 print ("tuple", variable_tuple) fonction_2() print (variable_locale_racine) print (tableau)
false
a32adf43016c39fa5c413703b48ff5628cc6f0cf
SouriCat/pygame
/8_Intermédiaire __ Manipulation de chaines de caractères.py
1,726
4.3125
4
##### Manipulation des chaines de caractères str1 = 'Bonjour' # unicode str2 = "Bonjour" # utf8 ##---> L'echappement permet d'afficher des signes utilisés pour coder #\' \" ##---> Retour chariot, a mettre a la fin de la ligne #\n\ ## retour chariot facile : # str3 = """ texte sur # plusieurs lignes """ ##---> Concatenation de plusieurs chaines str4 = "a"+"b"+"c" ##---> Repetition d'une chaine str5 ="abc" * 3 ##---> Imprime une partie de la chaine de caractères str6 = "Langage : Python" print (str6[2]) ##n print (str6[0:2]) ##La print (str6[:4] ) ##Lang print (str6[4:] ) ##age : Python ##---> Modifier un chaine de caractère print () # Les chaines de caractères ne sont pas modifiable directement -->TypeError: object doesn't support item assignment # Il faut ruser avec cette methode salut = 'bonjour à tous' salut = 'B' + salut[1:] print (salut) ##---> Cherche un caractère : # Retourne False si "h" n'est pas dans str. S'il y est, affiche True str7 = "Langage : Python" print ("h" in str7) # Cherche la lettre et renvoie son index print (str7.index("h")) ##---> Cherche un mot ou plus dans la chaine de caractère : foin = "Cette leçon vaut bien deux fromages, dont un fromage râpé ?" aiguille = "fromage" print (foin.rfind(aiguille)) ##---> Minuscules ou Majuscules ? print () # Minuscules print (foin.lower()) # Majuscules print (foin.upper()) # Premier caractere en majuscule print (foin.capitalize()) ##---> Remplacer un ou plusieurs caracteres #replace(old, new) phrase = "Si ce n'est toi c'est donc ton frère" print (phrase.replace(" ","_")) #Si_ce_n'est_toi_c'est_donc_ton_frère
false
67ef1b27449b3dd39629b8cc675e519ac462663e
RitaJain/Python-Programs
/greater2.py
226
4.25
4
# find greatest of two numbers using if else statment a=int(input("enter a ?")) b=int(input("enter b ?")) if (a>b): print("a is greater than b", a) else: print("b is greater than a",b)
true
1c1b6f7379b46515bab0e2bcddf0ed78bf527cc4
vipulm124/Python-Basics
/LearningPython/LearningPython/StringLists.py
355
4.40625
4
string = input("Enter a string ") #Method 1 reverse = '' for i in range(len(string)): reverse += string[len(string)-1-i] if reverse==string: print("String is a pallindrome. ") else: print("Not a pallindrome. ") #Method 2 rvs = string[::-1] if rvs == string: print("String is a pallindrome. ") else: print("Not a pallindrome. ")
true
bd17263b5e1af3fc2ec8ea1929959c1844ffecbc
arias365/juego-python
/3ra.py
2,731
4.1875
4
nombre = input("digite su nombre: ") print("hola ", nombre, " bienvenido") #tema de la clases 7 n1 = int(input('introduce n1: ')) n2 = int(input('introduce n2: ')) print(type(n1)) print('la suma de los numeros es: ', n1 + n2) print('la suma de los numeros es: {}'.format(n1+n2)) print('la suma de ', n1, ' y ', n2, 'es', n1+n2) print('la suma de {} y {} es {}'.format(n1, n2, n1+n2)) print(f'la suma de {n1} y {n2} es {n1+n2}') #ejemplo de como usar condicionales, primer ejemplo usando if a = int(input('¿cuantos años tiene tu computador?: ')) if a >= 0 and a <= 2: print('tu computador es nuevo') print ('puedes continuar con tu PC') print('-'*6) edad = int(input('Digite la edad de la persona: ')) #Condicional elif if edad < 16 : print('Todavia no puede conducir') elif edad < 18 : print('puede obteneer un permiso para conducir') elif edad < 70 : print('puede obtener la licencia estandar') else: print('requiere de una licencia especial') """ creando menus dentro de python, entrenamiento de condicionales con caracteristicas especiales(metodos)str """ menu = """ Bienvenidos al restro de usuarios, llene los campos que usted prefiera a continuacion seleccionando un numero del 1 al 3: [1] Digitar su Nombre [2] Digitar su edad [3] Digitar su correo electronico """ #python es un leguaje orientado a objetos print(menu) #variable opcion(objeto) opcion = input('Digita una opcion entre 1 y 3: ') if opcion == '1': # == : operador de comparacion, =: operador de asignacion. nombre = input('Digita tu nombre: ') #print(nombre.isnumeric())->true, print(nombre.isalpha())->false. if nombre.isalpha() == true: print('Tu nombre es {}'.format(nombre)) else: print('Has digitado un nombre no valido...') print('Tun nombre es {}'.format(nombre)) elif opcion == '2': #pass: declaración null que se usa generalmente como marcador de posición. edad = input('Digita tu edad: ') #print(nombre.isnumeric())->true, print(nombre.isalpha())->false. if edad.isnumeric() == true: print('Tu edad es {}'.format(edad)) else: print('Has digitado numero no valido...') elif opcion == '3': email = input('Digita tu email: ') """ email = 'cae@gmail.com' print(email.find('@'))->3:posicion print(email.find('.'))->posicion 9 email = 'caegmail.com' : sin @ print(email.find('@'))-> -1:porque no encontro @ tambien no es necesario en : if nombre.isalpha() == true:, el ==true """ if email.find('@')>=0 and email.find('.')>=0: print('Tu email es {}'.format(email)) else: print('Has digitado un email no valido...') else: print('debes digitar un numero entre 1 y 3') print('---'*20)
false
5c40d587eb5bea2adab8c6a6ae27c461ec45ed74
bhattaraiprabhat/Core_CS_Concepts_Using_Python
/hash_maps/day_to_daynum_hash_map.py
995
4.40625
4
""" Built in python dictionary is used for hash_map problems """ def map_day_to_daynum(): """ In this problem each day is mapped with a day number. Sunday is considered as a first day. """ day_dayNum = {"Sunday":1, "Monday":2, "Tuesday":3, "Wednesday":4, "Thursday":5, "Friday":6, "Saturday":7} #Display method 1: print (day_dayNum) #Display method 2 for key, value in day_dayNum.items(): print (key, value) #Display method 3 print (day_dayNum["Sunday"]) #Add elements: day_dayNum["NewDay"]="Noday" print (day_dayNum) #Remove elements: del day_dayNum["NewDay"] print (day_dayNum) #Remove with exception: try: del day_dayNum["Monday"] except KeyError as ex: print("No such key") print (day_dayNum) try: del day_dayNum["Monday"] except KeyError as ex: print("No such key") print (day_dayNum) map_day_to_daynum()
true
3dc10b40ad44521c1b628324e38b976f88cca26d
bhattaraiprabhat/Core_CS_Concepts_Using_Python
/recursion/fibonacci_series.py
580
4.25
4
""" This module calculates Fibonacce series for a given number input: an integer return : Fibonacce series """ def main(): number = input("Enter an integer : ") for i in range (int(number)): print ( fibonacci(i), end= ", " ) print () def fibonacci(n): """ Calculates the Fibonacci series input: n return : 1, 1, 2, 3, 5, 8, 13, .... """ if n==0: result =0 elif n==1: result =1 else: result = fibonacci(n-1) + fibonacci(n-2) return result if __name__=="__main__": main()
false
1e6eb33a7057383f2ae698c219830b5408ba7ab5
lilamcodes/creditcardvalidator
/ClassMaterials/parking lot/review.py
1,563
4.34375
4
# 1. Dictionary has copy(). What is it? # DEEP dict1 = {"apple": 4} dict2 = dict1.copy() dict1["apple"] = 3 # print("dict1", dict1) # print("dict2", dict2) # SHALLOW dict1 = {"apple": [1,2,3]} dict2 = dict1.copy() copy = dict1 dict1["apple"].append(5) # print("dict1", dict1) # print("dict2", dict2) # print("copy with equal sign", copy) # 2. How to open a csv? How to open a text file? # NOTE the string in the open() function is a path!!!! not just the name. # If no path (such as .., or /) is in the string, it assumes the file is right next to it. with open("example.txt") as examp: # read() makes a string copy of the file. exampString = examp.read() # print(exampString) # print(type(exampString)) import csv with open("example.csv") as examp: # WITH reader() # exampCSV = csv.reader(examp) # for row in exampCSV: # print(row) # WITH DictReader() exampCSV = csv.DictReader(examp) # for row in exampCSV: # print("State",row["State"]) # 3. sorted()? What is it? def add(number1, number2): return number1 + number2 def func(number): return number * -1 x = [3,2,4] # y = sorted(x, key=func) y = sorted(x) # print("x",x) # print("y",y) # 4. append() vs insert() exampleList = [1,2,3,4] # Example with append() # Adds the value to the end automatically! No choice!! exampleList.append(5) # print(exampleList) # Example with insert # Adds the value to the index position you say! Also, does not get rid of # the value that is already at that index position. exampleList.insert(0, 5) print(exampleList)
true
f9ca56364b52e6da5cb52c00396872294c04e5eb
lilamcodes/creditcardvalidator
/ClassMaterials/day7/beginner_exercises.py
1,701
4.59375
5
# Beginner Exercises # ### 1. Create these classes with the following attributes # #### Dog # - Two attributes: # - name # - age # #### Person # - Three Attributes: # - name # - age # - birthday (as a datetime object) # ### 2. For the Dog object, create a method that prints to the terminal the name and age of the dog. # - i.e.: # ``` # Dog.introduce() ===> "Hi I am Sparky and I am 5 years old." # ``` # ### 3. Create a function that will RETURN the Person objects birthday day of the week this year. # - i.e.: # ``` # Bob.birthday() ===> "Thursday" # ``` class Dog(): def __init__(self,name,age): self.name=name self.age=age def __str__(self): return self.name + "" + str(self.age) class Person(): def __init__(self,name, age, birthday): self.name=name self.age=age self.birthday=birthday def __st__(self): return self.name + "" + str(self.birthday) # d = Dog("Sparky",5) # print("the dog's name is" + self.name p1 = Person('Linda','11', today) from datetime import datetime, date today=date.today() datetime_object = datetime.strptime('Sep 19 2017 1:33PM', '%b %d %Y %I:%M%p') # print ("Bob's birthday is {:%b %d}".format(datetime_object) + ", which is thursday") Kesha's Version from datetime import datetime class Dog(): def __init__(self, name, age): self.name = name self.age = age class Person(): def __init__(self, name, birthday): self.name = name self.birthday = datetime.strptime(birthday,'%m %d %Y') self.age = int(str(datetime.today())[:4])-int(str(self.birthday)[:4]) dave = Person('dave','12 03 1989') print(dave.birthday) print('Dave is {} years old!'.format(dave.age))
true
bd8cab740890c73454f7fc27c28c9ee41db707b5
YarDK/lesson2
/comparison.py
1,323
4.59375
5
''' Сравнение строк Написать функцию, которая принимает на вход две строки Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 Если строки одинаковые, вернуть 1 Если строки разные и первая длиннее, вернуть 2 Если строки разные и вторая строка 'learn', возвращает 3 Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты ''' def comparison_string(string1, string2): if type(string1) != str or type(string2) != str: return 0 elif string1 == string2: return 1 elif string1 != string2 and len(string1) > len(string2): return 2 elif string1 != string2 and string2 == "learn": return 3 else: return "Условия не выполнены для: " + string1 + " " + string2 print(comparison_string("str", 123)) # 0 print(comparison_string("str","str")) #1 print(comparison_string("str_large","str")) #2 print(comparison_string("str", "learn")) #3 print(comparison_string("str", "learn23")) # Условия не выполнены для: str learn23
false
1b82d057d603672ef90d083bbc59dd34de075736
saurabh-ironman/Python
/sorting/QuickSort/quicksort.py
1,419
4.15625
4
def partition(array, low, high): #[3, 2, 1] # [1, 2, 3] # choose the rightmost element as pivot pivot = array[high] # pointer for greater element i = low - 1 # traverse through all elements # compare each element with pivot for j in range(low, high): if array[j] <= pivot: # if element smaller than pivot is found # swap it with the greater element pointed by i i = i + 1 # swapping element at i with element at j (array[i], array[j]) = (array[j], array[i]) # swap the pivot element with the greater element specified by i (array[i + 1], array[high]) = (array[high], array[i + 1]) # return the position from where partition is done return i + 1 def quicksort(array, start, end): if start < end: p = partition(array, start, end) print(p) quicksort(array, start, p - 1) quicksort(array, p + 1, end) def quicksort2(array): if array == []: return [] if len(array) == 1: return array pivot, *rest = array smaller = [element for element in array if element < pivot] bigger = [element for element in array if element > pivot] return quicksort2(smaller) + [pivot] + quicksort2(bigger) if __name__ == "__main__": #array = [10, 2, 7, 8, 3, 1] array = [1, 2] # array = [8, 7, 2, 1, 0, 9, 6] print(quicksort2(array))
true
57cb8daab27142956246f0a849924a1a4103cd21
n9grigoriants/python
/removing.py
374
4.125
4
nums = [1, 2, 3, 4, 5, 6, 7, 8] print(nums) nums.remove(3) #используем , если заранее известно значение объекта для удаления print(nums) #nums.remove(5) возникнет ошибка nums.pop() print(nums) res = nums.pop(2) print(nums) print("Был удален элемент со значением " + str(res))
false
ffc17a58e989094e5a31092826b501a6b22f2652
JayWelborn/HackerRank-problems
/python/30_days_code/day24.py
417
4.125
4
def is_prime(x): if x <=1: return False elif x <= 3: return True elif x%2==0 or x%3==0: return False for i in range(5, round(x**(1/2)) + 1): if x%i==0: return False return True cases = int(input()) for _ in range(cases): case = int(input()) if is_prime(case): print("Prime") else: print("Not prime")
true
27a8884bada5af0cb7fea5b1fcc5d6e255188150
jeetkhetan24/rep
/Assessment/q11.py
755
4.28125
4
""" Write a Python program to find whether it contains an additive sequence or not. The additive sequence is a sequence of numbers where the sum of the first two numbers is equal to the third one. Sample additive sequence: 6, 6, 12, 18, 30 In the above sequence 6 + 6 =12, 6 + 12 = 18, 12 + 18 = 30.... Also, you can split a number into one or more digits to create an additive sequence. Sample additive sequence: 66121830 In the above sequence 6 + 6 =12, 6 + 12 = 18, 12 + 18 = 30.... Note : Numbers in the additive sequence cannot have leading zeros. """ a = [6,6,12,18,30] i=1 for i in range(0,len(a)-3): if(a[i]+a[i+1]==a[i+2]): x=1 else: x=0 break if(x==1): print("The sequence is additive") else: print("The sequence is not additive")
true
4f73f3d4dee08f41dbcf97fba090d1a2cf605c01
chc1129/python_jisen
/04/strFstring.py
703
4.53125
5
# 文字列の変数置換 # f-string -- 式を埋め込める title = 'book' f'python practive {title}' # 変数の値で置換 print( f'python practive {title}' ) f'python practice {"note" + title}' # 式を利用 print( f'python practice {"note" + title}' ) def print_title(): print(f'python practice {title}') print_title() title = 'sketchbook' print_title() # f-stringは実行時に評価される note = 'note' # Python 3.7まで f'title={title}, note={note}' print( f'title={title}, note={note}' ) # Python 3.8以降はシンプルに書ける f'{title=}, {note=}' print( f'{title=}, {note=}' ) # 属性や式にも利用できる f'{title.upper()=}' print( f'{title.upper()=}' )
false
6febde39059c62422f858e99718fa7471c7aa50b
Aternands/dev-challenge
/chapter2_exercises.py
1,538
4.25
4
# Exercises for chapter 2: # Name: Steve Gallagher # EXERCISE 2.1 # Python reads numbers whose first digit is 0 as base 8 numbers (with integers 0-7 allowed), # and then displays their base 10 equivalents. # EXERCISE 2.2 # 5---------------> displays the number 5 # x = 5-----------> assigns the value "5" to the variable "x". Does not display anything. # x + 1-----------> displays the sum of 5 and 1------>6. # The script evaluates x + 1, but does not display a result. Changing the last line to "print x + 1" # makes the script display "6" # EXERCISE 2.3 width = 17 height = 12.0 delimeter = '.' #1. width/2 ---------> 8 (Floor Division-answer is an integer) #2. width/2.0--------> 8.5 (Floating Point Division- answer is a float) #3. 1 + 2 * 5--------> 11 (integer) #4. delimeter * 5----> '.....' (string) # EXERCISE 2.4 #1. (4/3.0)*(math.pi)*(5**3)------>523.5987755982989 #2. bookcount = 60 # shipping = 3 + (bookcount-1) * .75 # bookprice = 24.95 * .6 # totalbookprice = bookprice * bookcount # totalbookprice + shipping-------------------->945.4499999999999 (round to $945.45) #3 (8 * 60) + 15---------> 495 (easy pace in seconds per mile) # 495 * 2---------------> 990 (total time in seconds at easy pace) # (7 * 60) + (15)-------> 435 (tempo pace in seconds per mile) # 435 * 3---------------> 1305 (total time in seconds at tempo pace) # 1305 + 990------------> 2295 (total time in seconds) # divmod (2295, 60)-----> (38, 15)---------> 38:15 (total time in minutes) # 7:30:15 am
true
6362fb8b4b02d0ad66a13f68f59b233cdde2038b
jgarcia524/is210_lesson_06
/task_01.py
847
4.5625
5
#!usr/bin/env python # -*- coding: utf-8 -*- """Listing even and odd numbers""" import data from data import TASK_O1 def evens_and_odds(numbers, show_even=True): """Creates a list of even numbers and a list of odd numbers. Args: numbers (list): list of numbers show_even (bool): determines whether the function returns list of even or odd values; default set to True Returns: A list of either odd or even values from numbers list. Examples: >>> evens_and_odds([1,2,3,4,5],show_even=False) [1, 3, 5] >>> evens_and_odds([1,2,3,4,5]) [2, 4] """ even = [x for x in numbers if x % 2 is 0] odd = [x for x in numbers if x % 2 is not 0] if show_even is False: return odd else: return even
true
e35d9de64d658fff3adf421be31b0caf23f3e2b1
pfreisleben/Blue
/Modulo1/Aula 14 - Exercicios Obrigatórios/Exercicio 2.py
493
4.125
4
# 02 - Utilizando estruturas de repetição com variável de controle, faça um programa que receba # uma string com uma frase informada pelo usuário e conte quantas vezes aparece as vogais # a,e,i,o,u e mostre na tela, depois mostre na tela essa mesma frase sem nenhuma vogal. frase = input("Digite a frase: ").lower() vogais = 0 for letra in frase: if letra in "aeiou": vogais += 1 frase = frase.replace(letra, ' ') print(f'Quantidade de vogais: {vogais}') print(frase)
false
c77b54073b94153f22acc361fe864339194caf9f
pfreisleben/Blue
/Modulo1/Aula 10 - While/Exercicio 1.py
353
4.25
4
""" Exercício 1 - Escreva um programa que pede a senha ao usuário, e só sai do looping quando digitarem corretamente a senha. """ senha = "9856321" digitada = input("Digite sua senha: ") while digitada != senha: print("Senha incorreta, digite novamente!") digitada = input("Digite sua senha: ") print(f'Você digitou a senha correta!')
false
315cdba74cd51658d39a788a872a3e33c62eac6f
pfreisleben/Blue
/Modulo1/Aula 14 - Exercicios Obrigatórios/Exercicio 7.py
573
4.1875
4
# 07 - Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma # lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares # e ímpares em ordem crescente. lista = [[], []] continua = 0 while continua < 7: numero = int(input("Digite um número: ")) if numero % 2 == 0: lista[0].append(numero) else: lista[1].append(numero) continua += 1 lista[0].sort() lista[1].sort() print(f'Lista de valores pares: {lista[0]}') print(f'Lista de valores ímpares: {lista[1]}')
false
6b17a68c013f999b3547abbedd93f12166061c72
pfreisleben/Blue
/Modulo1/Aula 12 - CodeLab Dicionário/Desafio.py
1,865
4.1875
4
""" DESAFIO: Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: A) Quantas pessoas estão cadastradas. B) A média da idade. C) Uma lista com as mulheres. D) Uma lista com as idades que estão acima da média. OBS: O programa deve garantir que o sexo digitado seja válido, e que quando perguntar ao usuário se deseja continuar a resposta seja somente sim ou não. """ from numpy import mean pessoas = [] continua = True while continua: print(f'Vamos iniciar um novo cadastro! ') pessoa = {} nome = input("Informe o seu nome: ").lower() sexo = input("Informe o seu sexo(M/F): ").lower() while sexo not in ("m", "f"): print(f'Sexo informado é inválido! Digite corretamente!') sexo = input("Informe o seu sexo(M/F): ") idade = int(input("Digite a sua idade: ")) pessoas.append({"Nome": nome, "Sexo": sexo, "Idade": idade}) deveContinuar = input("Uma nova pessoa irá se cadastrar? S/N").lower() while deveContinuar not in ("s", "n"): print(f'Opção digitada é incorreta, por favor selecione corretamente') deveContinuar = input("Uma nova pessoa irá se cadastrar? S/N").lower() if deveContinuar == "n": continua = False print(f'Quantidade de pessoas cadastradas: {len(pessoas)}') idades = [] for i in pessoas: idades.append(i["Idade"]) print(f'A média da idade das pessoas é: {mean(idades)}') mulheres = [] for i in pessoas: if i.get("Sexo") == 'f': mulheres.append(i.get("Nome")) print(f'As mulheres cadastradas são: {", ".join(mulheres)}') idadeAcimaMedia = [] for i in pessoas: if i.get("Idade") > mean(idades): idadeAcimaMedia.append(str(i.get("Idade"))) print(f'As idades acima da média são: {",".join(idadeAcimaMedia)}')
false
d2e2b75a85e09aab40dca105c1cf1cabe404ea07
ScottPartacz/Python-projects
/Pick_3_Lotto.py
2,334
4.1875
4
# Scott Partacz 1/25/2018 ITMD 413 Lab 3 import time import random def check (picked,wining_numbers) : if(wining_numbers == picked) : win_or_lose = True elif(wining_numbers != picked) : win_or_lose = False return win_or_lose; def fireball_check(fireball,picked,wining_numbers) : count = 0; temp1 = sorted([fireball,picked[1],picked[2]]) temp2 = sorted([fireball,picked[0],picked[2]]) temp3 = sorted([fireball,picked[0],picked[1]]) #checks to see if the fireball would make the numbers a match if(temp1 == wining_numbers) : count += 1 if(temp2 == wining_numbers) : count += 1 if(temp3 == wining_numbers) : count += 1 return count fireball_wining = 0 fireball_flag = input("do you want to play fireball? (enter y/n) ") list = sorted(random.sample(range(0, 10), 3)) fireball = random.randint(0,10) #this is used to check the program is working #print(list,fireball); while(True) : print("Plese enter your 3 numbers sperated by a space") numbers = [int(x) for x in input().split()] numbers.sort() # checks if you entered 3 numbers if(len(numbers) != 3) : print("\nError: 3 numbers were not entered") continue # checks if the numbers pick are between 0-9 elif((numbers[0] > 9 or numbers[0] < 0) or (numbers[1] > 9 or numbers[1] < 0) or (numbers[2] > 9 or numbers[2] < 0)) : print("\nError: one of the numebrs entered wasnt 0-9") continue break if(fireball_flag == "y") : fireball_wining = fireball_check(fireball,numbers,list) flag = check(numbers,list) # checks the lotto result if ((flag == True) and fireball_wining > 0) : print("\nyou won $100 dollar cash prize and firball won too so an extra $50 times ",fireball_wining) elif ((flag == False) and fireball_wining > 0) : print("\nyou lost but since you had fireball you win $50 times ",fireball_wining) elif (flag == True) : print("\nyou win $100 dollar cash prize will be sent your way soon") elif (flag == False) : print("\nNice try, better luck next time ") print("\nThe wining numbers were: ",end =" ") print(list) print("\nThe Fireball number was: ",end =" ") print(fireball) print (" ") print ("Scott Partacz") print ("Date:",time.strftime("%x")) print ("Current time:",time.strftime("%X"))
true
8c13e0f0fe77d59c514d3b071f1488169a461755
Eduardo271087/python-udemy-activities
/section-9/multiple-exceptions.py
1,285
4.28125
4
variable = float(input("Introduce algo: ")) # Si se introduce una letra # File "/home/eduardo-fernandez/source/python-udemy-activities/section-9/multiple-exceptions.py", line 1, in <module> # variable = float(input("Introduce algo: ")) # ValueError: could not convert string to float: 'l' a = 2 print("Resultado: ", a * variable) try: variable = float(input("Introduce un número: ")) a = 2 print("Resultado: ", a * variable) except: print("Ingresaste cualquier otra cosa menos la que se te pidió") while True: try: variable = float(input("Introduce un número: ")) a = 2 print("Resultado: ", a * variable) except: print("Ingresaste cualquier otra cosa menos la que se te pidió, te voy a dar otra oportunidad") else: print("Iniciaste sesión perfectamente, amigo") break while True: try: variable = float(input("Introduce un número: ")) a = 2 print("Resultado: ", a * variable) except: print("Ingresaste cualquier otra cosa menos la que se te pidió, te voy a dar otra oportunidad") # El else se ejecuta cuando no se arrojan excepciones else: print("Iniciaste sesión perfectamente, amigo") break # El finally se ejecuta siempre finally: print("Perfecto mi amigo, terminó todo esto")
false
92cd0001b602a0cdea7e03d6170ba6bd500aca0f
bauglir-dev/dojo-cpp
/behrouz/ch01/pr_13.py
227
4.46875
4
# Algorithm that converts a temperature value in Farenheit to a value in Celsius farenheit = float(input("Enter a temperature value in Farenheit: ")) celsius = (farenheit - 32) * (100/180) print(str(celsius) + ' Celsius.'))
true
d5dde1216cb6e77f8b92a47de57268447c4189c3
V4p1d/Assignment-1
/Exercise_4.py
406
4.40625
4
# Write a program that receives three inputs from the terminal (using input()). # These inputs needs to be integers. The program will print on the screen the sum of these three inputs. # However, if two of the three inputs are equal, the program will print the product of these three inputs. # Example 1: n = 1, m = 2, l = 3, output = 1 + 2 + 3 = 6 # Example 2: n = 1, m = 2, l = 2, output = 1 * 2 * 2 = 4
true
2af76dc77f4cebd7d13f517141f6ef633c073700
prakhar-nitian/HackerRank----Python---Prakhar
/Sets/Set_.intersection()_Operation.py
2,053
4.3125
4
# Set .intersection() Operation # .intersection() # The .intersection() operator returns the intersection of a set and the set of elements in an iterable. # Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set. # The set is immutable to the .intersection() operation (or & operation). # >>> s = set("Hacker") # >>> print s.intersection("Rank") # set(['a', 'k']) # >>> print s.intersection(set(['R', 'a', 'n', 'k'])) # set(['a', 'k']) # >>> print s.intersection(['R', 'a', 'n', 'k']) # set(['a', 'k']) # >>> print s.intersection(enumerate(['R', 'a', 'n', 'k'])) # set([]) # >>> print s.intersection({"Rank":1}) # set([]) # >>> s & set("Rank") # set(['a', 'k']) # Task # The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, # some have subscribed only to French, and some have subscribed to both newspapers. # You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French # newspaper. Your task is to find the total number of students who have subscribed to both newspapers. # Input Format # The first line contains n, the number of students who have subscribed to the English newspaper. # The second line contains n space separated roll numbers of those students. # The third line contains b, the number of students who have subscribed to the French newspaper. # The fourth line contains b space separated roll numbers of those students. # Constraints # 0 < Total number of students in college < 1000 # Output Format # Output the total number of students who have subscriptions to both English and French newspapers. # Enter your code here. Read input from STDIN. Print output to STDOUT eng_num = int(raw_input()) eng_set = raw_input().split() eng_set = set(map(int, eng_set)) fren_num = int(raw_input()) fren_set = raw_input().split() fren_set = set(map(int, fren_set)) print len(eng_set.intersection(fren_set))
true
843ddcb5a7fd997179c284d6c18074282a70ab0a
KULDEEPMALIKM41/Practices
/Python/Python Basics/67.bug.py
295
4.5625
5
print('before loop') for i in range(10,0,-1): # -1 is write perameter for reverse loop. print(i) print('after loop') print('before loop') for i in range(10,0): # if we are not give iteration in range function. it is by default work print(i) # on positive direction. print('after loop')
true
ad929f0d120653cf303cf7d59018eccdedae04c6
KULDEEPMALIKM41/Practices
/Python/Python Basics/114.multiple.py
2,399
4.3125
4
# 4. multiple inheritance => # (base for C)CLASS A CLASS B(base for C) # | | # | | # ______________________________________ # | # | # CLASS C(derived for A and B) # Drawback of other technology => # 1.if base class will contain functionality with same name it may # generate ambiguity problem. # 2. their is no possibility to extends(inherit) multiple class # simultaneously. #Example:- class A: def aData(self): print('class A member invoked') class B: def bData(self): print('class B member invoked') class C(A,B): def cData(self): print('class C member invoked') obj=C() obj.aData() obj.bData() obj.cData() print('\n\n\n') #Example:- class A: def Data(self): print('class A member invoked') class B: def Data(self): print('class B member invoked') class C(A,B): # first class member function is call which same name. def cData(self): print('class C member invoked') obj=C() obj.Data() obj.cData() print('\n\n\n') #Example:- class A: def Data(self): print('class A member invoked') class B: def Data(self): print('class B member invoked') class C(B,A): # first class member function is call which same name. def cData(self): print('class C member invoked') obj=C() obj.Data() obj.cData() print('\n\n\n') #Example:- class A: def Data(self): print('class A member invoked') class B: def Data(self): print('class B member invoked') class C(B,A): # first class member function is call which same name. def Data(self): super(C,self).Data() print('class C member invoked') obj=C() obj.Data() print('\n\n\n') #Example:- class A: def Data(self): print('class A member invoked') class B: def bData(self): print('class B member invoked') class C(A,B): # first class member function is call which same name. def Data(self): super(C,self).Data() print('class C member invoked') obj=C() obj.bData() obj.Data() print('\n\n\n') #Example:- class A: def aData(self): print('class A member invoked') class B: def Data(self): print('class B member invoked') class C(A,B): # first class member function is call which same name. def Data(self): super(C,self).Data() print('class C member invoked') obj=C() obj.aData() obj.Data() print('\n\n\n')
true
722f02a018763d5c18297e2977130e8be8c2093c
KULDEEPMALIKM41/Practices
/Python/Python Basics/36.control.py
536
4.1875
4
#Control Structure -> # 1.Conditional Statement 2.Control Statement 3.Jumping Procedure # a) if-statement a) while loop a) break # b) if-else statement b) for loop b) continue # c) if-elif-else(ladder if-else c) pass #Conditional Statement -> it is use to implement decision making in an application. # a) if Statement -> #program for find greater number. a=int(input('enter any number a \t')) b=int(input('enter any number b \t')) if a>b: print('a is greater') if b>a: print('b is greater')
false
534146d46f8c71c9edec393105942add3bc01f5a
KULDEEPMALIKM41/Practices
/Python/Single Py Programms/statistics_module.py
1,459
4.15625
4
from statistics import * a = [1,10,3.5,4,6,7.3,4] b = [2,2,3,8,9] print("mean(a) - ",mean(a)) # The mean() method calculates the arithmetic mean of the numbers in a list. print("mean(b) - ",mean(b)) print("median(a) - ",median(a)) # The median() method returns the middle value of numeric data in a list. print("median(b) - ",median(b)) print("mode(a) - ",mode(a)) # The mode() method returns the most common data point in the list. print("mode(b) - ",mode(b)) print("median_grouped(a) - ",median_grouped(a,interval=2)) # The median_grouped() method return the 50th percentile (median) of grouped continuous data print("median_grouped(b) - ",median_grouped(b,interval=2)) # interval by default is 1. print("median_high(a) - ",median_high(a)) # The median_low() method returns the high middle value of numeric data in a list. print("median_high(b) - ",median_high(b)) print("median_low(a) - ",median_low(a)) # The median_low() method returns the low middle value of numeric data in a list. print("median_low(b) - ",median_low(b)) print("harmonic_mean(a) - ",harmonic_mean(a)) # The harmonic_mean() method returns the harmonic mean of data. print("harmonic_mean(b) - ",harmonic_mean(b)) print("variance(a) - ",variance(a)) # The variance() method returns the sample variance of data. print("variance(b) - ",variance(b)) print("stdev(a) - ",stdev(a)) # The stdev() method returns the square root of the sample variance. print("stdev(b) - ",stdev(b))
true
302d09455ea91820c27d2529516bbd55efcf6348
KULDEEPMALIKM41/Practices
/Python/Python Basics/40.if-else.py
263
4.125
4
#program for find divisiable number from 5 and10. #jo 10 se divisiable hogi vo 5 se almost divide hogi. n=int(input('Enter any number')) if n%10==0: print('divisible') else: #we will give different indentation in if and else part. print('not divisible')
false
0702ece64a2e2eaffc7fa970ddf974ec2f244dbf
minhnhoang/hoangngocminh-fundamental-c4e23
/session3/password_validation.py
424
4.28125
4
pw = input("Enter password: ") while True: if len(pw) <= 8: print("Password length must be greater than 8") elif pw.isalpha(): print("Password must contain number") elif pw.isupper() or pw.islower(): print("Password must contain both lower and upper case") elif pw.isdigit(): print("Password must contain character") else: break pw = input("Enter password: ")
true
c298d41657f00d72a8718da8741c9d0cf24acc3a
oreolu17/python-proFiles
/list game.py
1,284
4.1875
4
flag = True list = [ 10,20,30,40,50] def menu(): print("Enter 1: to insert \n Enter 2: to remove \n Enter 3: to sort \n Enter 4: to extend \n Enter 5 to reverse \n Enter 6: to transverse") def insertlist(item): list.append(item) def remove(item): list.remove(item) def sort(item): list.sort() def extend(item): list.extend() def reverse(item): list.reverse() def playgame(): flag = True while (flag): menu() choice = input() choice = int(choice) if choice == 1: item = input ('Enter the item you want to add to the list') insertlist(item) elif choice == 2: item = input ('Enter the item you want to remove') remove(item) elif choice == 3: item = input('Enter an item you want to sort') sort(item) elif choice == 4: item = input('Enter an item you want to extend') extend(item) elif choice == 5: item = input('Enter an item you want to reverse') reverse(item) elif choice == 6: for d in list: print(d) playagain = input ('Do you want to play again? ') if playagain == 'no': flag = False playgame()
true
cf0ffad1f8470707cf05177287c5a085b8db0098
shubham3207/pythonlab
/main.py
284
4.34375
4
#write a program that takes three numbers and print their sum. every number is given on a separate line num1=int(input("enter the first num")) num2=int(input("enter the second num")) num3=int(input("enter the third num")) sum=num1+num2+num3 print("the sum of given number is",sum)
true
d3a882a461e6f5b853ea7202592418618539c5e1
llmaze3/RollDice.py
/RollDice.py
679
4.375
4
import random import time #Bool variable roll_again = "yes" #roll dice until user doesn't want to play while roll_again == "yes" or roll_again == "y" or roll_again == "Yes" or roll_again == "Y" or roll_again == "YES": print("\nRolling the dice...") #pause the code so that it feels like dice is being rolled #sleep 1 second time.sleep(1) #pick variable between 1 and 6 dice1=random.randint(1, 6) dice2=random.randint(1, 6) print("The values are:") print("Dice 1 =", dice1, "Dice 2 =", dice2) if dice1 == dice2: print("You rolled a double") else: print("Keep trying!") #option to change yes to no roll_again = input("\nRoll the dice again? (Y/N) ")
true
246d6138de3857dd8bf9a4488ebcce3d9f1c7144
StevenLOL/kaggleScape
/data/script87.py
1,355
4.34375
4
# coding: utf-8 # Read in our data, pick a variable and plot a histogram of it. # In[4]: # Import our libraries import matplotlib.pyplot as plt import pandas as pd # read in our data nutrition = pd.read_csv("../input/starbucks_drinkMenu_expanded.csv") # look at only the numeric columns nutrition.describe() # This version will show all the columns, including non-numeric # nutrition.describe(include="all") # Plot a histogram using matplotlib. # In[15]: # list all the coulmn names print(nutrition.columns) # get the sodium column sodium = nutrition[" Sodium (mg)"] # Plot a histogram of sodium content plt.hist(sodium) plt.title("Sodium in Starbucks Menu Items") # Plot a histogram using matplotlib with some extra fancy stuff (thanks to the Twitch chat for helping out!) # In[25]: # Plot a histogram of sodium content with nine bins, a black edge # around the columns & at a larger size plt.hist(sodium, bins=9, edgecolor = "black") plt.title("Sodium in Starbucks Menu Items") # add a title plt.xlabel("Sodium in milligrams") # label the x axes plt.ylabel("Count") # label the y axes # Plot a histogram using the pandas wrapper of matplotlib. # In[26]: ### another way of plotting a histogram (from the pandas plotting API) # figsize is an argument to make it bigger nutrition.hist(column= " Sodium (mg)", figsize = (12,12))
true
2c8305b951b42695790cc95fef57b5f3751db447
GowthamSiddarth/PythonPractice
/CapitalizeSentence.py
305
4.1875
4
''' Write a program that accepts line as input and prints the lines after making all words in the sentence capitalized. ''' def capitalizeSentence(sentence): return ' '.join([word.capitalize() for word in sentence.split()]) sentence = input().strip() res = capitalizeSentence(sentence) print(res)
true
b78fea29f88fee4293581bbbfae5da0fa60065b9
GowthamSiddarth/PythonPractice
/RobotDist.py
1,030
4.4375
4
''' A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. ''' from math import sqrt def getRobotDistance(): dx, dy = 0, 0 while True: ip = input().strip() if not ip: break else: lst = ip.split() direction, dist = lst[0], int(lst[1]) if direction == "UP": dy += dist elif direction == "DOWN": dy -= dist elif direction == "LEFT": dx -= dist elif direction == "RIGHT": dx += dist return round(sqrt(dx * dx + dy * dy)) res = getRobotDistance() print(res)
true
c1a94cfefd636be989ea3c0df1a2f40ecefd6390
GowthamSiddarth/PythonPractice
/PasswordValidity.py
1,368
4.3125
4
''' A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 letter between [A-Z] 3. At least 1 character from [$#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. ''' import re def isValidPassword(password): l = len(password) if not re.search(pattern="[a-z]", string=password): return False elif not re.search(pattern="[A-Z]", string=password): return False elif not re.search(pattern="[0-9]", string=password): return False elif not re.search(pattern="[$#@]", string=password): return False elif re.search(pattern="[^a-zA-Z0-9$#@]", string=password): return False elif 6 > l > 12: return False else: return True def getValidPasswords(passwords): return [password for password in passwords if isValidPassword(password)] passwords = input().strip().split(',') res = getValidPasswords(passwords) print(res)
true
2b78532e935cc48136266b96a4a8d5070d14852b
GowthamSiddarth/PythonPractice
/EvenValuesFromTuple.py
268
4.1875
4
''' Write a program to generate and print another tuple whose values are even numbers ''' def getEvenNumsFromTuple(nums): return tuple(x for x in nums if x % 2 == 0) nums = list(map(int, input().strip().split(','))) res = getEvenNumsFromTuple(nums) print(res)
true
7e576a799df097e9afe67872e3313acab43be54b
wxl789/python
/day12/11-单继承.py
1,784
4.40625
4
#定义一个父类 class Cat(object): def __init__(self,name,color="白色"): self.name = name self.color = color def run(self): print("%s-----在跑"%self.name) #定义一个子类,继承Cat父类 """ 继承的格式: class 子类名(父类名) 子类在继承的时候,在定义类时,小括号中为父的名字 父类的属性和方法,会继承给子类(公有) """ class Bosi(Cat): def setNewName(self,newName): self.name = newName def eat(self): print("%s-----在吃"%self.name) #创建子类对象 bs = Bosi("波斯猫") print("bs的名字为:%s"%bs.name) print(bs.color) bs.eat() bs.run() class Animal(object): def __init__(self,name="动物",color="白色"): self.__name = name self.color = color def __run(self): print(self.__name) print(self.color) def run(self): print(self.__name) print(self.color) class Dog(Animal): def dogRun(self): #print(self.__name)#不能获取父类私有的属性 print(self.color) def dogRun1(self): # self.__run()#不能继承父类的私有的方法 self.run() A = Animal() # print(A.__name)#不能访问私有属性 print(A.color) # A.__run()#不能访问私有的方法 print("------华丽的分割线--------") D = Dog(name="小花狗",color="花色") D.dogRun() D.dogRun1() """ 继承: 子类只能继承父类公有的属性和方法, 私有属性和方法不能被子类继承 私有的属性,不能通过对象直接进行访问,但是可以通过方法进行访问 私有的方法:不能通过对象进行访问 私有的属性/方法,不会被子类所继承,也不能被访问 """
false
5cc975cd608316355f65da33885eb43ebac6db92
wxl789/python
/Day16/2-代码/面向对象/10- __str__.py
631
4.3125
4
# __str__函数:__str__():当打印实例对象的时自动调用。 # 注:该方法必须有一个str类型的返回值 # __str__是给用户用来描述实例对象的方法 # 优点:当我们需要打印实例对象的多个属性时,可以使用__str__, # 这种方式会简化我们的代码量。 class Person(): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex # 在类中重写__str__方法 def __str__(self): return self.name + str(self.age) + str(self.sex) p1 = Person('lily', 12, 23) p2 = Person("lucy", 34, 67) print(p1)
false
cbf356727ec572000df535ab177a4bd2c056ff9f
wxl789/python
/Day07/2-代码/函数/7-不定长参数(元组).py
1,209
4.25
4
# 不定长参数 # 概念:能够在函数内部处理比形参个数多的实参 def sum1(a,b): print(a + b) def sum2(a,b,c): print(a + b + c) # 加了 (*) 的变量,可以存放多个实参。 # 加了 * 的形参,数据类型为元组类型,如果调用时未传入传入参数,默认 # 为一个空元组,如果传入了实参,将传入的实参按传入顺序依次放到元组中。 def fun1(*args): print(args) fun1() fun1(1) fun1(1,2,3) print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&") # 计算传入的实参的和 def fun2(*args): res = 0 for i in args: res += i print(res) fun2(1) fun2(1,2) # 有普通形参及不定长参数 def fun3(num1,num2, *args): print(num1) print(num2) print(args) # fun3(1) # error fun3(1,2) fun3(2,3,4) fun3(4,5,6,7,8,9) # 不能使用关键字参数 # TypeError: fun3() got multiple values for argument 'num1' # fun3(7,8,9,num1=1,num2=8) # fun3(num1=1,num2=2,7,8,9) # 语法错误 # 当不定长参数在前面时,函数调用需要使用关键字格式 def fun4(*args,num1): print(num1) print(args) print("-------------------------------") fun4(1,2,3,4,num1=200)
false