blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0c26e158842e1f3fcbd260a1115982c3a3303a6a
BenMarriott/1404
/prac_02/exceptions.py
1,036
4.28125
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? When usings floating point numbers 2. When will a ZeroDivisionError occur? When attempting n/0 3. Could you change the code to avoid the possibility of a ZeroDivisionError? """ """"" try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") """"" """ CP1404/CP5632 - Practical Fill in the TODOs to complete the task """ finished = False result = 0 while not finished: try: result = int(input("Please enter an integar: \n")) # TODO: this line finished = True except (ValueError): # TODO - add something after except print("Please enter a valid integer.\n") print("Valid result is:", result)
true
5a530c11bf9ff825ace09f85299d8ac1419ce7a3
nitishprabhu26/HackerRank
/Practice - Python/005_Loops.py
760
4.46875
4
if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2) # The range() function # The range function is a built in function that returns a series of numbers. At a minimum, it needs one integer parameter. # Given one parameter, n, it returns integer values from 0 to n-1. For example, range(5) returns the numbers 0 through 4 in sequence. # To start at a value other than 0, call range with two arguments. For example, range(1,5) returns the numbers 1 through 4. # Finally, you can add an increment value as the third argument. For example, range(5, -1, -1) produces the descending sequence from 5 through 0 and range(0, 5, 2) produces 0, 2, 4. If you are going to provide a step value, you must also include a start value.
true
219a8fe816e6bad703c55d6b75435fc761ace602
supriya1110vuradi/Python-Tasks-Supriyav
/task4.py
753
4.34375
4
# Write a program to create a list of n integer values and do the following # Add an item in to the list (using function) # Delete (using function) # Store the largest number from the list to a variable # Store the Smallest number from the list to a variable a = [1, 2, 3, 4, 5, 6] hi = max(a) lo = min(a) print(hi) print(lo) b = [1, 2, 3, 4, 5] del b[3] print(b) c = list([1, 2, 3, 4]) c.append(8) print(c) # Create a tuple and print the reverse of the created tuple # method1 d = (1, 2, "hey", "hello", 3, 4) print(d) e = reversed(d) print(tuple(e)) # method2 tuples = (1, 2, 3, 4, 5, 67, 8) reversedTuples = tuples[::-1] print(reversedTuples) # Create a tuple and convert tuple into list f = (1, 2, "hi", "hey", 8, 10) lis = list(f) print(lis)
true
8e488771b4e8aa522e9246dc9f50aec625dbd872
long2691/activities
/activity 5/comprehension.py
1,521
4.15625
4
prices = ["24", "13", "16000", "1400"] price_nums = [int(price) for price in prices] print(prices) print(price_nums) dog = "poodle" letters = [letter for letter in dog] print(letters) print(f"we iterate over a string into al ist : {letters}") capital_letters = [letter.upper() for letter in letters] #long version of same thing above capital_letters = [] for letter in letters: capital_letters.append(letter.upper()) no_o = [letter for letter in letters if letter != 'o'] print(no_o) #same as abvoe but longer - no o's no_o = [] for letter in letters: if letter != 'o': no_o.append(letter) june_temperature = [72,65,59,87] july_temperature = [87,85,92,79] august_temperateure = [88,77,66,100] temperature = [june_temperature, july_temperature, august_temperateure] lowest_summer_temperature = [min(temps) for temps in temperature] lowest_summer_temperature = [] print(lowest_summer_temperature) for temps in temperature: lowest_summer_temperature.append(min(temps)) print(sum(lowest_summer_temperature)/len(lowest_summer_temperature)) print(lowest_summer_temperature) print(lowest_summer_temperature[0]) print(lowest_summer_temperature[1]) print(lowest_summer_temperature[2]) print("=" * 30) #longhand def name(parameter): return "Hello" + parameter def average(data1,data2): return sum(data)/len(data1) + (sum(data2)/len(data2)) print(name("Loc")) print(Average([1,2,3,4,5],)) #git status #git add . # git status # git commit -m "Description comment" # git push origin master
true
ccd5218382ffe23b84fffc1e0d137feb35b0ea18
andthenenteredalex/Allen-Downey-Think-Python
/thinkpy107.py
404
4.125
4
""" Allen Downey Think Python Exercise 10-7 This function checks if two words are anagrams and returns True if they are. """ def is_anagram(word_one, word_two): one = sorted(list(word_one)) two = sorted(list(word_two)) if one == two: return True elif one != two: return False word = 'hello' word2 = 'hlehol' anagram = is_anagram(word, word2) print anagram
true
aa0616170bc2dbbd2dca519e550437bb0365ac12
daviddlhz/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-write_file.py
403
4.25
4
#!/usr/bin/python3 """write to a text file""" def write_file(filename="", text=""): """writes to a file Keyword Arguments: filename {str} -- name of file (default: {""}) text {str} -- text beingwritten (default: {""}) Returns: int -- number of charaters """ with open(filename, mode="w", encoding="utf-8") as fd: fd.write(text) return len(text)
true
330654c09eb6cbb1f913f2734102f51b225c8bcd
oneyedananas/learning
/for Loops.py
553
4.5
4
# performs code on each item in a list i.e. iteration. loops are a construct which can iterate through a list. # uses a while loop and a counter variable words = ["milda", "petr", "karel", "pavel"] counter = 0 max_index = len(words) - 1 # python starts counting from 0 so -1 is needed # print(max_index) now returns 3: range of the list - 1 while counter <= max_index: word = words[counter] # take appropriate string from the list 'words' print(word + "!") # concatenation counter = counter + 1 # so that we can move to the next item
true
0685f623b4f9cb897a13d09f537b410e4bf76868
apranav19/FP_With_Python
/map_example.py
499
4.40625
4
""" Some simple examples that make use of the map function """ def get_name_lengths(names): """ Returns a list of name lengths """ return list(map(len, names)) def get_hashed_names(names): """ Returns a list of hashed names """ return list(map(hash, names)) if __name__ == '__main__': people = ["Mary", "Isla", "Sam"] print("Length of names: " + str(get_name_lengths(people))) print("=================") print("Hashed Names: " + str(get_hashed_names(people))) print("=================")
true
7778dff5d30424e4f1b98c98fdddd1642f86dfe9
fangyuandoit/PythonLearnDemo
/菜鸟教程/Python3_05列表.py
2,271
4.3125
4
''' 序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。 Python有6个序列的内置类型,但最常见的是列表和元组。 序列都可以进行的操作包括索引,切片,加,乘,检查成员。 此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。 列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。 列表的数据项不需要具有相同的类型 ''' list1 = ['Google', 'Runoob', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]; #使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示: print ("list1[0]: ", list1[0]) print ("list2[1:5]: ", list2[1:5]) #你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示: print ("第三个元素为 : ", list1[2]) list1[2] = 2001 print ("更新后的第三个元素为 : ", list1[2]) #del 语句来删除列表的的元素,如下实例: del list1[0] print ("原始列表 : ", list) print ("删除第三个元素 : ", list) #list1.remove("Google") print(list1) ''' Python列表函数&方法 Python包含以下函数: 序号 函数 1 len(list) 列表元素个数 2 max(list) 返回列表元素最大值 3 min(list) 返回列表元素最小值 4 list(seq) 将元组转换为列表 ''' ''' Python包含以下方法: 序号 方法 1 list.append(obj) 在列表末尾添加新的对象 2 list.count(obj) 统计某个元素在列表中出现的次数 3 list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) 4 list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 5 list.insert(index, obj) 将对象插入列表 6 list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 7 list.remove(obj) 移除列表中某个值的第一个匹配项 8 list.reverse() 反向列表中元素 9 list.sort( key=None, reverse=False) 对原列表进行排序 10 list.clear() 清空列表 11 list.copy() 复制列表 '''
false
f09901aec3a56dbb7675a4131d01c97ff0173943
DanielDavid48/Exercicios-PY
/ex14.py
767
4.1875
4
import os print('Bem vindo ao convertor de temperaturas!') print(f'Escolha uma das opções abaixo:{os.linesep}A - para converter celsius para fahrenheit{os.linesep}B - para converter fahrenheit para celsius') opcao = input('Opção escolhida: ') # Celsius para fahrenheit # fahrenheit para celsius if opcao == 'A': temp = float(input('Insira a temperatura em °C: ')) conversao1 = temp * 1.8 + 32 print(f'{temp} graus celsius em fahrenheit é {conversao1:.2f} graus fahrenheit.') elif opcao == 'B': tempfa = float(input('Insira a temperatura em °F: ')) femc = (tempfa - 32)/1.8 print(f'{tempfa} graus fahrenheit em celsius é {femc:.2f} graus celsius') else: print('Você digitou uma opção inválida!')
false
662ba6e340e968f95adeebeb601083823e26d4ea
EstebanBrito/taller-basico-python
/basics.py
1,211
4.375
4
# VARIABLES EN PYTHON # No es necesario definir tipo (static, public, etc) # ni tipo (int, float, etc) mi_variable = 45 print(mi_variable) mi_variable = 3.9 print(mi_variable) mi_variable = True print(mi_variable) mi_variable = 'otro valor' print(mi_variable) mi_variable = [1, 6, 3, 3] print(mi_variable) # Operaciones (+, -, *, /) resul = 4 // 7 print(resul) resul = 3**3 print(resul) # I/0 # Cadenas mi_cadena = input('Ingresa una cadena: ') print(mi_cadena * 3) # Números (conversión explícita) mi_variable = int(input('Ingresa un número: ')) print(mi_variable * 3) # FORMATEO DE CADENAS nombre = 'Alejandro' apellido = 'Pérez' valor1 = 8.6 valor2 = 4.2 # Estandar print('Me llamo %s %s. Mucho gusto' % (nombre, apellido)) # %d (enteros), %f (flotantes) print('El producto de %d y %d es %.2f' % (valor1, valor2, valor1*valor2)) # Usando format() print('Me llamo {} {}. Mucho gusto'.format(nombre, apellido)) print('El producto de {1} y {0} es {2}'.format(valor1, valor2, valor1*valor2)) # Cadenas f (f strings). Introducidas en Python 3.6. Evaluan la expresión. print(f'Me llamo {nombre.upper()} {apellido}. Mucho gusto.') print(f'Me llamo {valor1} y {valor2} es {valor1*valor2}')
false
fe4ba27c40751233f94c4468944fd300c65ac1f8
luizpericolo/PythonProjects
/Text/count_words.py
793
4.46875
4
# Count Words in a String - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary. string = '' while string.upper() != 'QUIT': string = raw_input("Enter a text to get a summary of strings or 'quit' to exit: ") if string.upper() != 'QUIT': words = {} symbols = [',', '.', '!', '?', '@', '#', '$', '%', '&', '*', '(', ')', '-', '+', '/', '\\', '{', '}'] for word in string.split(' '): if word != ' ': for symbol in symbols: if word.find(symbol): word = word.replace(symbol, '') if word not in words: words[word] = 1 else: words[word] += 1 for word, count in words.iteritems(): print "Word '{0}' appeared {1} time(s) in the text.".format(word, count) print 'Bbye!'
true
54c7954e9b17b56aff806ec9f0ba48216e308f9a
IncapableFury/Triangle_Testing
/triangle.py
2,034
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 13:44:00 2016 Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple python program to classify triangles @author: jrr @author: rk @ """ def classify_triangle(side1: int, side2: int, side3: int) -> str: """ Your correct code goes here... Fix the faulty logic below until the code passes all of you test cases. This function returns side1 string with the type of triangle from three integer values corresponding to the lengths of the three sides of the Triangle. return: If all three sides are equal, return 'Equilateral' If exactly one pair of sides are equal, return 'Isoceles' If no pair of sides are equal, return 'Scalene' If not side1 valid triangle, then return 'NotATriangle' If the sum of any two sides equals the squate of the third side, then concatenate result with 'Right' BEWARE: there may be side1 bug or two in this code """ def check_if_right(side1, side2, side3, epsilon=0.001): return abs(1 - (side1 * side1 + side2 * side2) / (side3 * side3)) < epsilon # require that the input values be >= 0 and <= 200 and have type integer if side1 > 200 or side2 > 200 or side3 > 200: return 'InvalidInput' if side1 <= 0 or side2 <= 0 or side3 <= 0: return 'InvalidInput' if not (isinstance(side1, int) and isinstance(side2, int) and isinstance(side3, int)): return 'InvalidInput' # now we know that we have side1 valid triangle (side1, side2, side3,) = sorted([side1, side2, side3]) # side1<side2<c if not side1 + side2 > side3: return "NotATriangle" is_right = check_if_right(side1, side2, side3) if side1 == side2 == side3: triangle_type = "Equilateral" elif side1 == side2 or side2 == side3 or side1 == side3: triangle_type = "Isoceles" else: triangle_type = "Scalene" return triangle_type + "+Right" if is_right else triangle_type
true
d0935a48ad03c078bcb50b9adef38fa64e53df8f
cdueltgen/markov_exercise
/markov.py
1,053
4.28125
4
""" markov.py Reference text: section 13.8, how to think like a computer scientist Do markov analysis of a text and produce mimic text based off the original. Markov analysis consists of taking a text, and producing a mapping of prefixes to suffixes. A prefix consists of one or more words, and the next word to follow the prefix in the text. Note, a prefix can have more than one suffix. Eg: markov analysis with a prefix length of '1' Original text: "The quick brown fox jumped over the lazy dog" "the": ["quick", "lazy"] "quick": ["brown"] "brown": ["fox"] "fox": ["jumped"] ... etc. With this, you can reassemble a random text similar to the original style by choosing a random prefix and one of its suffixes, then using that suffix as a prefix and repeating the process. You will write a program that performs markov analysis on a text file, then produce random text from the analysis. The length of the markov prefixes will be adjustable, as will the length of the output produced. """
true
d7c1582e72c291ced406a9a47731bae6cbf5cbd8
cassiorodrigo/python
/aula14.py
340
4.125
4
s = str(input('Digite seu sexo [M/F] ')).strip().upper()[0] while s not in 'MmFf': s = str(input('Entrada Invalida, por favor digite [M/F]: ')).strip().upper()[0] print('Você digitou {}.'.format(s)) '''r = 'S' while r == 'S': n = int(input('Digite um numero: ')) r = str(input('Quer continuar: [S/N ')).upper() print('FIM')'''
false
e4e4d1aa65cca834a26d27edd85da4a0543a96f7
NYU-Python-Intermediate-Legacy/jarnold-ipy-solutions
/jarnold-2.2.py
2,270
4.15625
4
#usr/bin/python2.7 import os import sys def unique_cities(cities): # get rid of empty items if cities.has_key(''): del cities[''] unique_cities = sorted(set(cities.keys())) return unique_cities def top_ten_countries(countries): # get rid of empty items if countries.has_key(''): del countries[''] # sort by integer of value top_ten_countries = sorted(countries, key=lambda i: int(countries[i]), reverse=True) return top_ten_countries[0:9] def top_ten_machine_names(machine_names): # get rid of empty items if machine_names.has_key(''): del machine_names[''] # sort by integer of value top_ten_machine_names = sorted(machine_names, key=lambda i: int(machine_names[i]), reverse=True) return top_ten_machine_names[0:9] # find out what info the user wants def what_would_you_like(cities, countries, machine_names): print """What information would you like from the bit.ly data? a) A set of unique cities b) The top ten most popular country codes c) The top ten most popular machine names """ answer = raw_input("Please type the letter name of your selection: ") if answer == "a": print unique_cities(cities) elif answer == "b": print top_ten_countries(countries) elif answer == "c": print top_ten_machine_names(machine_names) else: print "Sorry, I didn't get that answer" # recursively calls itself to run the prompt again what_would_you_like(cities, countries, machine_names) def main(): # set up empty dicts cities = {} countries = {} machine_names = {} # get the data from the tsv for line in open('bitly.tsv').readlines()[1:]: elements = line.strip('\n\s').split('\t') # read the data into the dictionaries try: city = elements[3] country = elements[4] machine_name = elements[2].split('/')[2] if city in cities: cities[city] += 1 else: cities[city] = 1 if country in countries: countries[country] += 1 else: countries[country] = 1 if machine_name in machine_names: machine_names[machine_name] += 1 else: machine_names[machine_name] = 1 # keep going if the information isn't found except: continue # provide data to user what_would_you_like(cities, countries, machine_names) main()
true
424c14cc7e7547593ae9bf715e78108b363d2cc3
ZuzaRatajczyk/Zookeeper
/Problems/Lucky ticket/task.py
466
4.125
4
# Save the input in this variable ticket = (input()) first_digit = int(ticket[0]) second_digit = int(ticket[1]) third_digit = int(ticket[2]) fourth_digit = int(ticket[3]) fifth_digit = int(ticket[4]) sixth_digit = int(ticket[5]) # Add up the digits for each half half1 = first_digit + second_digit + third_digit half2 = fourth_digit + fifth_digit + sixth_digit # Thanks to you, this code will work if half1 == half2: print("Lucky") else: print("Ordinary")
true
8da21b78fd90a65b70bb461f0370564724ab1dc8
ckabuloglu/interview_prep
/levelOrder.py
939
4.15625
4
''' Level Order Traversal Given a binary tree, print the nodes in order of levels (left to right for same level) ''' # Define the Tree structure class BSTNode: def __init__(self, val): self.val = val self.left = None self.right = None # Define the add method to add nodes to the tree def add(root, val): if not root: return BSTNode(val) elif root.val < val: root.right = add(root.right, val) else: root.left = add(root.left, val) return root # Define the function that print the level order tree Traversal def levelOrder(root): queue = [root] levels = [] while queue: current = queue.pop(0) if current: levels.append(current.val) queue.append(current.left) queue.append(current.right) else: levels.append(None) return levels # Define the trees and test cases a = BSTNode(4) add(a, 3) add(a, 1) print levelOrder(a)
true
2c50bed4074123edcc2f4feab539c300a65071be
Garrison50/unit-2-brid
/2.3 Vol/SA.py
279
4.15625
4
def main(): import math radius = float(input("Enter the radius of the sphere")) volume = ((4/3) * math.pi * (pow(radius,3))) sa = (4 * math.pi * (pow(radius,2))) print ("The volume is:", round(volume,2)) print ("The surface area is:", round(sa,2)) main()
true
643730d15360ecc6c8e59db671e489a17932fe08
shakyaruchina/100DaysOfCode
/dayTen/calculator.py
1,182
4.25
4
#Calculator from art import logo #add function def add(n1,n2): return n1+n2 #subtract functuon def subtract(n1,n2): return n1-n2 #divide function def divide(n1,n2): return n1/n2 #multiply function def multiply(n1,n2): return n1*n2 #operation dictionary{key:value} operations = { "+":add, "-":subtract, "/":divide, "*":multiply, } def calculator(): print(logo) num1 = float(input("What is the first number ? ")) #prints each operations key for operation in operations: print(operation) go_continue = True while go_continue: operation_symbol = input("Pick an operation ") num2 = float(input("What is the next number ? ")) #key value calculation = operations[operation_symbol] #add(n1,n2), subtract(n1,n2) answer = calculation(num1,num2) print(f"{num1} {operation_symbol}{num2} = {answer}") if input(f"Type 'y' to continue calculating with {answer}: or type 'n' to start a new calculation:") == "y": num1 = answer else: go_continue = False calculator() #recursion : function that calls itself calculator()
true
827904d6c3c5dd080ce6b3b353967d2f1cc52131
rafaelzottesso/2019-ES-Algoritmos
/aula11-while.py
1,168
4.21875
4
""" -- Estrutura básica do laço de repetição while -- variável de controle iniciada while(condição): . . . incremento da variável de controle """ # # Variável de controle iniciada # cont = 1 # # Condição do while montada de acordo com a variável de controle # while( cont <= 1000 ): # # Código a ser processado # print("Valor de cont:", cont) # # # Dentro do while pode ter qualquer coisa... # # Pedir coisa para usuário, if, elif, else, etc # # inclusive outro while :ooo # # # Alteração/incremento no valor da variável de contrle # cont = cont + 1 # # Fim do while # Fazendo o contador inverso... cont = 5 while (cont >= 1): print(cont) cont = cont - 1 # Pedindo várias notas ao usuário cont = 1 # inicia o contador soma = 0 # inicia a variável de soma while(cont <= 4): nota = int(input("Informe uma nota:")) soma = soma + nota # junta a soma atual com a nota cont = cont + 1 # aumenta o contador # Por fim, faz esse print 1x só porque está fora do while print("Média: ", soma/4) # Continuação do programa, independente do resultado do while print("Fora do while!")
false
4f6d15c068cce2a7b00df861c2feea7d41a326cb
SamanehGhafouri/DataStructuresInPython
/doubly_linked_list.py
2,468
4.125
4
# Doubly Linked List # Advantages: over regular (singly) linked list # - Can iterate the list in either direction # - Can delete a node without iterating through the list (if given a pointer to the node) class Node: def __init__(self, d, n=None, p=None): self.data = d self.next_node = n self.prev_node = p def __str__(self): return '(' + str(self.data) + ')' class DoublyLinkedList: def __init__(self, r = None): self.root = r self.last = r self.size = 0 def add(self, d): if self.size == 0: self.root = Node(d) self.last = self.root else: new_node = Node(d, self.root) self.root.prev_node = new_node self.root = new_node self.size += 1 def find(self, d): this_node = self.root while this_node is not None: if this_node.data == d: return d elif this_node.next_node == None: return False else: this_node = this_node.next_node def remove(self, d): this_node = self.root while this_node is not None: if this_node.data == d: if this_node.prev_node is not None: if this_node.next_node is not None: this_node.prev_node.next_node = this_node.next_node this_node.next_node.prev_node = this_node.prev_node else: this_node.prev_node.next_node = None self.last = this_node.prev_node else: self.root = this_node.next_node this_node.next_node.prev_node = self.root self.size -= 1 return True else: this_node = this_node.next_node return False def print(self): if self.root is None: return this_node = self.root print(this_node, end='->') while this_node.next_node is not None: this_node = this_node.next_node print(this_node, end='->') print() dll = DoublyLinkedList() for i in [5, 9, 3, 8, 9]: dll.add(i) print("size= "+str(dll.size)) dll.print() dll.remove(8) print("size="+str(dll.size)) print(dll.remove(15)) print(dll.find(15)) dll.add(21) dll.add(22) dll.remove(5) dll.print() print(dll.last.prev_node)
true
d16a5a86ee12545676d76241cf3a10d74e709455
Darkeran/Python3
/Exercicios/LoopW_Validação.py
1,289
4.28125
4
# Faça um programa que leia e valide as seguintes informações: # # Nome: maior que 3 caracteres; # Idade: entre 0 e 150; # Salário: maior que zero; # Sexo: 'f' ou 'm'; # Estado Civil: 's', 'c', 'v', 'd'; Nome = input("Digite seu nome: ") while len(Nome) < 3: Nome = input("Digite seu nome: ") Idade = int(input("Digite sua idade: ",)) while Idade < 1 or Idade > 150: Idade = int(input("Digite sua idade: ",)) Salario = float(input("Qual é o seu sálario R$:?")) while Salario < 1: Salario = float(input("Qual é o seu sálario R$:?")) Sexo = input("Qual é o seu sexo? \n(F)-Feminino: \n(M)-Masculino:").upper() while Sexo != "M" and Sexo != "F": Sexo = input("Qual é o seu sexo? \n(F)-Feminino: \n(M)-Masculino:").upper() Estado_Civil = input("Estado Civil?\n(S)-Solteiro, \n(C)-Casado, \n(D)-Divorciado, \n(V)-Viúvo: ").upper() while Estado_Civil != "S" and Estado_Civil != "C" and Estado_Civil != "D" and Estado_Civil != "V": Estado_Civil = input("Estado Civil?\n(S)-Solteiro, \n(C)-Casado, \n(D)-Divorciado, \n(V)-Viúvo: ").upper() print("Nome:%s" %Nome) print("Idade:",Idade) print("Salario R$%.2f" %Salario) print("Sexo:%s" %Sexo) print("Estado Civil:%s" %Estado_Civil)
false
66352731d8b952a633dea499c56cc58903051b4d
nikitakumar2017/Assignment-4
/assignment-4.py
1,450
4.3125
4
#Q.1- Reverse the whole list using list methods. list1=[] n=int(input("Enter number of elements you want to enter in the list ")) for i in range(n): n=int(input("Enter element ")) list1.append(n) print(list(reversed(list1))) #Q.2- Print all the uppercase letters from a string. str1=input("Enter string ") for i in str1: if (i>='A' and i<='Z'): print(i) #Q.3- Split the user input on comma's and store the values in a list as integers. str1=input("Enter some numbers seperated by comma's ") list1=[] list2=[] list1=str1.split(',') for i in list1: i=int(i) list2.append(i) print(list2) #Q.4- Check whether a string is palindromic or not. str1=input("Enter a string ") length=len(str1) high=length-1 i=0 low=0 flag=0 while (i<length and flag==0): if(str1[low]==str1[high]): high-=1 low+=1 flag=0 else: flag=1 i+=1 if(flag==0): print("Yes") else: print("No") #Q.5- Make a deepcopy of a list and write the difference between shallow copy and deep copy. import copy as c list1=[1,2,[3,4],5] list2=c.deepcopy(list1) list1[2][0]=7 print(list1) print(list2) ''' Difference between shallow copy and deep copy is that in shallow copy if the original object contains any references to mutable object then the duplicate reference variable will be created pointing to the old object and no duplicate object is created whereas in deep copy a duplicate object is created. '''
true
413958b6351cf01a519968f52f16d73dffab40b8
fansOnly/Python-test
/learning/常用内建模块/itertools_.py
2,859
4.25
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # itertools # itertools提供了非常有用的用于操作迭代对象的函数。 import itertools ######################################################################################### # count()会创建一个无限的迭代器 # natuals = itertools.count(1) # for n in natuals: # if n < 5: # print(n) # print('*'*100) ######################################################################################### # cycle()会把传入的一个序列无限重复下去: # cycles = itertools.cycle('ABC') # i = 1 # for c in cycles: # if i < 5: # print(c) # i += 1 # print('*'*100) ######################################################################################### # repeat()负责把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数: ns = itertools.repeat('X', 5) for x in ns: print(x) print('*'*100) ######################################################################################### # 无限序列虽然可以无限迭代下去,但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列: natualsx = itertools.count(1) ns = itertools.takewhile(lambda x: x<=5, natualsx) print(list(ns)) print('*'*100) ######################################################################################### # chain() # chain()可以把一组迭代对象串联起来,形成一个更大的迭代器: for c in itertools.chain('ABC', 'XYZ'): print(c) print('*'*100) ######################################################################################### # groupby() # groupby()把迭代器中相邻的重复元素挑出来放在一起: for key, group in itertools.groupby('AAaaBbbCCcc'): print(key, list(group)) print('*'*100) for key, group in itertools.groupby('AAaaBbbCCcc', lambda c: c.upper()): print(key, list(group)) print('*'*100) # practice 计算圆周率可以根据公式: # 利用Python提供的itertools模块,我们来计算这个序列的前N项和: def pi(N): # ' 计算pi的值 ' # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... natuals = itertools.count(1,2) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. odds = itertools.takewhile(lambda x: x <= 2*N-1, natuals) # print(list(odds)) # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... it = itertools.cycle([4, -4]) nums = list(map(lambda x: next(it)/x, list(odds))) # print(list(nums)) # step 4: 求和: return sum(nums) # return reduce(lambda x, y: x + y, nums) # 测试: print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok') print('*'*100)
false
33a7477b0c51e7f8a4750b3ba62a8902b52f9313
bsdharshini/Python-exercise
/5) While.py
1,837
4.125
4
''' Take 10 integers from keyboard using loop and print their average value on the screen. sum=0 for i in range(0,10): n=int(input()) sum=sum+n print(sum) ''' ''' Print the following patterns using loop : a. * ** *** **** n i star 4 0 1 4 1 2 n=int(input()) for i in range(0,n): print() for j in range(0,i+1): print("*",end="") ''' ''' b. * *** ***** *** * n i space star 5 0 4 1 5 1 2 3 5 2 0 5 5 3 2 3 5 4 4 1 n=int(input()) i,j,k=0,0,0 space=n-(2*i)-1 for i in range(0,n): for j in range(0,space): print("") space-=1 for k in range(0,(n-space)): print("*",end="") for j in range(0,space+2): print("") for k in range(0,(n-space)): print("*",end="") print() ''' ''' Print multiplication table of 24, 50 and 29 using loop. for i in range(1,11): one=24*i print("24 * {} =".format(i),one) print("\n") for j in range(1,11): two=50*i print("50 * {} =".format(j),two) print("\n") for k in range(1,11): three=29*i print("29 * {} =".format(k),three) print("\n") ''' ''' Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.- 4! = 1*2*3*4 = 24 3! = 3*2*1 = 6 2! = 2*1 = 2 Also, 1! = 1 0! = 1 Write a program to calculate factorial of a number. n=int(input()) fact=1 for i in range(1,n+1): fact=fact*i n print(fact) ''' """ Take integer inputs from user until he/she presses q ( Ask to press q to quit after every integer input ). Print average and product of all numbers. """ n=0 su=0 product=1 while(n!='q'): n=int(input()) su+=n product*=n print(su) print(product)
false
2abdecd0c2820f8db9ae2efc4252f9815c80d18d
bsdharshini/Python-exercise
/1)printprintprint.py
1,189
4.375
4
#https://www.codesdope.com/practice/python-printprintprint/ #1)Print anything you want on the screen. print("hello") # 2) Store three integers in x, y and z. Print their sum x=10 y=20 z=30 sum=x+y+z print(sum) #3) Store three integers in x, y and z. Print their product. x,y,z=10,20,30 print(x*y*z) #4) Check type of following: print(type("CodesDope")) print(type(15)) print(type(16.2)) print(type(9.33333333333333333333)) #5) Join two string using '+'. print('hi '+'you') #6) Store two values in x and y and swap them. x,y=10,5 x,y=y,x print(x,y) """ 7) Create a class named 'Rectangle' with two data members- length and breadth and a method to claculate the area which is 'length*breadth'. The class has three constructors which are : 1 - having no parameter - values of both length and breadth are assigned zero. 2 - having two numbers as parameters - the two numbers are assigned as length and breadth respectively. 3 - having one number as parameter - both length and breadth are assigned that number. Now, create objects of the 'Rectangle' class having none, one and two parameters and print their areas. """ """ 8) """
true
bf794f5e450f517f9aa56012b18298c471d68999
Kapiszko/Learn-Python
/ex11.py
426
4.15625
4
print("How old are you?", end=' ') age = int(input("Please give your age ")) print("How tall are you?", end=' ') height = int(input("Please give your height ")) print("How much do you weigh?", end=' ') weight = int(input("Please give your weight ")) print (f"So, you're {age} old, {height} tall and {weight} heavy.") sum_of_measurements = age + height + weight print("The sum of your measurements is", sum_of_measurements)
true
fc41dcd6953857498946355e64e58b32429fcc45
YashMistry1406/Competitve_Coding-
/sde problems/Array/sort color.py
1,119
4.15625
4
# Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, # with the colors in the order red, white, and blue. # We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. # You must solve this problem without using the library's sort function. # Example 1: # Input: nums = [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] # Example 2: # Input: nums = [2,0,1] # Output: [0,1,2] # Example 3: # Input: nums = [0] # Output: [0] # Example 4: # Input: nums = [1] # Output: [1] class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ lo=0 mid=0 hi= len(nums)-1 while mid <= hi: if nums[mid]==0: nums[lo],nums[mid]=nums[mid],nums[lo] lo+=1 mid+=1 elif nums[mid] == 1: mid+=1 else: nums[mid],nums[hi]=nums[hi],nums[mid] hi-=1 return nums
true
4a96f7c36e897f6af65eaa60077bd988d9b7e34b
serubirikenny/Shoppinlist2db
/shop.py
1,043
4.125
4
class ShoppingList(object): """class to represent a shopping list and CRUD methods""" def __init__(self, name): self.name = name self.items = {} def add_item(self, an_item): if an_item.name in self.items: self.items[an_item.name] += an_item.quantity else: self.items[an_item.name] = an_item.quantity def remove_item(self, name): if name not in self.items: print 'Item not on shopping list.' else: if self.items[name] > 1:#reduce the item numbers by 1 if there's more than 1 self.items[name] -= 1 elif self.items[name] == 0 or self.items[name] == 1:#else remove the item from the list entirely del self.items[name] def show_list(self): print self.items return self.items class Item(object): """class to represent items on a shopping list""" def __init__(self, name, quantity=1): self.name = str(name) self.quantity = int(quantity)
true
12682f41edb0a57e5774e5404b11b7a72c1698a8
aarushikool/CrypKool
/OTP.py
2,228
4.3125
4
from random import randint import matplotlib.pyplot as plt #string alphabet is declared here to convert ALPHABET into numerical values #ALPHABET[0] is a blank space ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encrypt(text, key): text= text.upper() cipher_text = '' for index, char in enumerate(text): key_index = key[index] char_index = ALPHABET.find(char) cipher_text += ALPHABET[(char_index + key_index) % len(ALPHABET)] return cipher_text def decrypt(msg, key): plain = '' for index, char in enumerate(msg): key_index = key[index] char_index = ALPHABET.find(char) plain += ALPHABET[(char_index - key_index) % len(ALPHABET)] return plain def random_sequence(text): #we store the random values in a list random_sequence = [] #generating as many random values as the number of characters in the plain_text #size of the key = size of the plain_text for rand in range(len(plain_text)): random_sequence.append(randint(0,len(ALPHABET))) return random_sequence def frequency_analysis(plain_text): #the text is case insensitive plain_text = plain_text.upper #we will be using a dictionary to store letter frequencies letter_frequencies= {} #initialize the dictionary for letter in ALPHABET: letter_frequencies[letter] = 0 #let's consider the text we want to analyse for letter in plain_text: #we keep incrementing the occurence of the given letter if letter in ALPHABET: letter_frequencies[letter] += 1 return letter_frequencies #histogram of letter_frquencies def plot_distribution(frequencies): centers = range(len(ALPHABET)) plt.bar(centers, frequencies.values(), align='center', tick_label=frequencies.keys()) plt.xlim([0,len(ALPHABET)-1]) plt.show() if __name__ == "__main__": plain_text = 'HELLO I AM HERE BRO' key= random_sequence(plain_text) print("Original message is %s " % plain_text.upper()) cipher= encrypt(plain_text,key) print("Encrypted message is %s " % cipher) decrypted_text= decrypt(cipher,key) print("Decrypted message is %s " % decrypted_text) plot_distribution(frequency_analysis(cipher))
true
cc9caf4d73ee3d43b06d3698abc27888924ac923
garymorrissey/Programming-And-Scripting
/collatz.py
537
4.125
4
# Gary Morrissey, 11-02-2018 # The Collatz Conjecture program i = int(input("Please enter any integer:")) # Prompts you to choose a number, with the next term being obtained from the previous term while i > 1: if i % 2 == 0: i = i / 2 # If the previous term is even, the next term is one half the previous term print(i) else: i = (3 * i) + 1 # Otherwise, the next term is 3 times the previous term plus 1 print(i) # The conjecture is that no matter what value of n, the sequence will always reach 1
true
2b2bdc77c6e116371e56d5df4bb7699bc2dff31a
AmaanHUB/IntroPython
/variables_types/python_variables.py
847
4.34375
4
# How can we create a variable? # variable_name = value # creating a variable called name to store user name name = "Amaan" # declaring a String variable # creating a variable called age to store user age age = 23 # Integer # creating a variable called hourly_wage to store user hourly_wage hourly_wage = 15 # Integer # creating a variable called travel_allowance to store user travel_allowance travel_allowance = 3.5 # Float # # # # Types of variables in Python: # # String, int, float, boolean # print(travel_allowance) print(age) print(hourly_wage) # How can we take user data? # We can use a method called input() to get data from user # getting user input with the input() method name = input("Please enter your name: ") print(name) # How can we find out the type of variable? # type() method tells us the data type print(type(age))
true
19387eba9e667955c01c4fe19571af19b890c1d8
clowe88/Code_practicePy
/simple_cipher.py
277
4.15625
4
phrase = input("Enter a word or phrase to be encrypted: ") phrase_arr = [] finished_phrase = "" for i in phrase: phrase_arr.append(i) for x in phrase_arr: num = ord(x) cipher = chr(num + 12) finished_phrase += cipher print (finished_phrase)
true
087bc5cc5c04f905117e7950cfd64b1b927a01f9
manasmishracse/Selenium_WebDriver_With_Python
/PythonTesting/Demo Code/ReadFile.py
305
4.1875
4
# Reading a File Line by Line in Python and reverse it in o/p. lines = [] rev = "" file = open('File_Demo.txt', 'r') lines = file.readlines() print("{}{}".format("Content in File is ", lines)) for i in lines: rev = i + rev print("{}{}".format("Reversed Content of the File is:", rev)) file.close()
true
a7e708c106dc18cdd1b222f807dc6225cb2a2347
satyam-seth-learnings/machine_learning
/Machine Learning using Python(NIELIT Lucknow)/My Code/Assignments/Assignment-3(Day-6)/4.Circle.py
428
4.25
4
# Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle. class Circle: def __init__(self,r): self.radius=r def area(self): return 3.14*self.radius**2 def perimeter(self): return 2*3.14*self.radius c1=Circle(10) print(f'Radius: {c1.radius}') print(f'Area: {c1.area()}') print(f'Perimeter: {c1.perimeter()}')
true
14746feb3f6c2ef1b1487b1c772a1d17be4e8a8f
satyam-seth-learnings/machine_learning
/Machine Learning using Python(NIELIT Lucknow)/My Code/Assignments/Assignment-1(Day-3)/5.Write a Python program to interchange first and last elements in a list.py
277
4.34375
4
# Write a Python program to interchange first and last elements in a list. # Logic-1 l=[1,2,3,4,5] print(f'List: {l}') l[0],l[-1]=l[-1],l[0] print(f'List: {l}') # Logic-2 # l=[1,2,3,4,5] # print(f'List: {l}') # l.insert(0,l.pop()) # l.append(l.pop(1)) # print(f'List: {l}')
false
5aa478055b9109df4e9b32ddf801473d80399148
satyam-seth-learnings/machine_learning
/Machine Learning using Python(NIELIT Lucknow)/My Code/Assignments/Assignment-2(Day-4)/8.Find cube of all numbers of list and find minimum element and maximum element from resultant list.py
309
4.28125
4
# Using lambda and map calculate the cube of all numbers of a list and find minimum element and maximum element from the resultant list. l=[1,2,6,4,8,9,10] cubes=list(map(lambda x: x**3,l)) print(f'Cube of all numbers: {cubes}') print(f'Minimum element: {min(cubes)}') print(f'Maximum element: {max(cubes)}')
true
0afc2bd9622c2a0a32a3c369733d6df66d8284ce
roycrippen4/python_school
/Assignments/triangle.py
928
4.625
5
# Python Homework 1 - Triangles sides and angles # Roy Crippen # ENG 101 # Due 11/18/2019 # The goal of this code is to take three sides of a triangle from a user and to compute the angles of said triangle. from math import degrees from math import acos # First I will receive the sides of the triangle from the user side_a = int(input('What is side a? ')) side_b = int(input('What is side b? ')) side_c = int(input('What is side c? ')) # Then I will compute the angles of the triangle. ang_a = degrees(acos((side_b**2 + side_c**2 - side_a**2) / (2 * side_b * side_c))) ang_b = degrees(acos((side_c**2 + side_a**2 - side_b**2) / (2 * side_c * side_a))) ang_c = 180 - ang_a - ang_b # Then I print the results print('\nThe sides of the triangle are ' + str(side_a) + ', ' + str(side_b) + ', and ' + str(side_c)+'.') print('The angles (in degrees) of the triangle are ' + str(ang_a) + ', ' + str(ang_b) + ', and ' + str(ang_c)+'.')
true
6b47c5254cee29f96045124913f14fee0f53b3c8
lazumbra/Educative-Data-Structures-in-Python-An-Interview-Refresher
/LinkedList/Doubly Linked Lists/main.py
1,673
4.125
4
from LinkedList import LinkedList from Node import Node def delete(lst, value): deleted = False if lst.is_empty(): print("List is Empty") return deleted current_node = lst.get_head() if current_node.data is value: # Point head to the next element of the first element lst.headNode = current_node.next_element # Point the next element of the first element to None current_node.next_element.previous_element = None deleted = True # Both links have been changed. print(str(current_node.data) + " Deleted!") return deleted # Traversing/Searching for node to Delete while current_node: if value is current_node.data: if current_node.next_element: # Link the next node and the previous node to each other prev_node = current_node.previous_element next_node = current_node.next_element prev_node.next_element = next_node next_node.previous_element = prev_node # previous node pointer was maintained in Singly Linked List else: current_node.previous_element.next_element = None deleted = True break # previousNode = tempNode was used in Singly Linked List current_node = current_node.next_element if deleted is False: print(str(value) + " is not in the List!") else: print(str(value) + " Deleted!") return deleted lst = LinkedList() for i in range(11): lst.insert_at_head(i) lst.print_list() delete(lst, 5) lst.print_list() delete(lst, 0) lst.print_list()
true
51f497fa15c6f77934f98cf1595b66cb7a455ae7
charleycodes/hb-code-challenges
/concatenate-lists-2-13.py
872
4.3125
4
# Whiteboard Easier # Concepts Lists def concat_lists(list1, list2): """Combine lists. >>> concat_lists([1, 2], [3, 4]) [1, 2, 3, 4] >>> concat_lists([], [1, 2]) [1, 2] >>> concat_lists([1, 2], []) [1, 2] >>> concat_lists([], []) [] """ # If we didn't put these on sep lines, (just returned list1.extend(list2)), # the function would have returned None. # Also, if we'd used append instead, for test1, we would have gotten: # [1, 2, [3, 4]] list1.extend(list2) return list1 ##################################################################### # END OF ASSESSMENT: You can ignore everything below. if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
true
afaf0b4d56ec34e86b518d0b0f05a5b31c19e9dc
XiaoA/python-ds
/33_sum_range/sum_range.py
1,279
4.125
4
def sum_range(nums, start=0, end=None): """Return sum of numbers from start...end. - start: where to start (if not provided, start at list start) - end: where to stop (include this index) (if not provided, go through end) >>> nums = [1, 2, 3, 4] >>> sum_range(nums) 10 >>> sum_range(nums, 1) 9 >>> sum_range(nums, end=2) 6 >>> sum_range(nums, 1, 3) 9 If end is after end of list, just go to end of list: >>> sum_range(nums, 1, 99) 9 """ """My first thought was to use a `reduce` function. But even when Imported the library, I had issues. # return functools.reduce(nums) # I learned that the built-in `Sum` function would probably perform better. # Ref: https://docs.python.org/3/library/functions.html#sum # https://realpython.com/python-reduce-function/#comparing-reduce-and-accumulate # The SB implementation first checks for cases where there is no 'end', and returns the sum of the entire list, before slicing the start/end indices: """ if end is None: end = len(nums) return sum(nums[start:end + 1]) # When might the `reduce` function be a better approach? I'll need to look into that more.
true
2a5576f2f7f10af9f2f23ad68f7270d85e9ef6e3
Chaser/PythonHardWay
/Ex27/Ex27_MemorizingLogic.py
2,805
4.34375
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 #NOT Routines print "NOT Routines\n" print not(False) #True print not(True) #False print "-------------------------\n" print "OR Routines\n" print True or False #True print True or True #True print False or True #True print "-------------------------\n" print "AND Routines\n" print True and False #False print True and True #True print False and True #True print False and False #False print "-------------------------\n" print "NOT OR Routines\n" print not(True or False) #False print not(True or True) #False print not(False or True) #False print not(False or False) #True print "-------------------------\n" print "NOT AND Routines\n" print not(True and False) #True print not(True and True) #False print not(False and True) #True print not(False and False) #True print "-------------------------\n" print "!= Routines\n" print (1 != 0) #True print (1 != 1) #False print (0 != 1) #True print (0 != 0) #False print "-------------------------\n" print "== Routines\n" print (1 == 0) #False print (1 == 1) #True print (0 == 1) #False print (0 == 0) #True
true
45fd466c0cfd03262a9baad12133103943aa88c6
sanket-k/Assignment_py
/python-files/Question 3.py
2,008
4.4375
4
# coding: utf-8 # ### Question 3 # ### Note: problem similar to Question 2 # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The # element value in the i-th row and j-th column of the array should be i*j. # # Note: i=0,1.., X-1; j=0,1,¡ Y-1. # # #### Example # # Suppose the following inputs are given to the program: # # 3,5 # # Then, the output of the program should be: # # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # ### Version 1 # In[4]: #define function to display matrix by accepting variables def displayMatrix(x,y): dim_array = [[0 for j in range(y)] for i in range(x)] # define array for i in range(x): # use recurvise loop to reach entered numbers for j in range(y): dim_array[i][j] = i * j # allocate array by multiplying the row and columns return(dim_array) # return array # In[5]: x = int(input("Input the number of rows : ")) # input the number of rows y = int(input("Input the number of columns : ")) # input number of columns print("the 2-Dimensional array is : {}". format(displayMatrix(x,y))) # display the array # ### Verision 2 # In[3]: row_num = int(input("Input number of rows: ")) # input rows col_num = int(input("Input number of columns: ")) # input columns multi_list = [[0 for col in range(col_num)] for row in range(row_num)] # allocate array for row in range(row_num): # recursive loop to reach entered numbers for col in range(col_num): multi_list[row][col]= row*col # allocate array by multiplying the row and columns print("the 2-Dimensional array is : {}".format(multi_list)) # display the array
true
ab4216252416679138e20fa13c9abdb37f7c73cc
KalinHar/OOP-Python-SoftUni
/workshop/hash_table.py
2,142
4.21875
4
class HashTable: """"The HashTable should have an attribute called array of type: list, where all the values will be stored. Upon initialization the default length of the array should be 4. After each addition of an element if the HashTable gets too populated, double the length of the array and re-add the existing data. You are not allowed to inherit any classes. Feel free to implement your own functionality (and unit tests) or to write the methods by yourself.""" def __init__(self): self.array = [None] * 2 def extend_array(self): new_array = [None for _ in range(len(self.array) * 2)] for kvp in self.items(): k, v = kvp new_array[self.hash(k)] = (k, v) self.array = new_array def hash(self, key: str): # a function that should figure out where to store the key - value pair total = 0 for i in range(len(key)): total += ord(key[i]) * (7**i) return total % len(self.array) def add(self, key: str, value: any): # adds a new key - value pair using the hash function if self.array[self.hash(key)] != None: # check for collision and extend array if it self.extend_array() self.add(key, value) self.array[self.hash(key)] = (key, value) def get_value(self, key: str): # returns the value corresponding to the given key return self.array[self.hash(key)][1] def get_pair(self, key: str): # returns the kvp corresponding to the given key return self.array[self.hash(key)] def items(self): return [kvp for kvp in self.array if kvp] # additional "magic" methods, that will make the code in the example work correctrly h = HashTable() h.add("weer", 1) h.add("wer", 2) h.add("er", 3) h.add("we", 4) h.add("wee", 5) h.add("seeer", 6) h.add("ersa", 7) h.add("wed", 8) h.add("wcee", 9) print(h.items()) # we have -> 9 elements => len array must be 8+1 = 16 print(len(h.array)) # but len = 32=2**5 => 1 unexpected collision was happened and 4 expected print(h.get_value("er")) print(h.get_pair("wcee"))
true
2777acf9d2f2467191d3227386993968e22a57d7
everqiujuan/python
/day04/code/07_列表list的方法2.py
1,441
4.125
4
# index() : 找出指定元素在列表中第一次出现的下标 list1 = [11, 22, 33, 66, 22, 22, 33, 44] print(list1.index(33)) # 2 # print(list1.index(100)) # 报错, ValueError: 100 is not in list # 内置函数/内置方法 # max() : 找列表中的最大值 m = max(list1) print(m) # min() : 找最小值 print(min(list1)) # sum() : 求和 print(sum(list1)) # 排序 # sort() : 升序,从小到大 list2 = [1, 4, 2, 3, 6, 5, 7, 9, 8] list2.sort() print(list2) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # 降序 list2.sort(reverse=True) print(list2) # [9, 8, 7, 6, 5, 4, 3, 2, 1] # 倒序 # reverse() list2 = [1, 4, 2, 3, 6, 5, 7, 9, 8] list2.reverse() print(list2) # copy() # 拷贝,复制 # 赋值 list3 = [1, 2, 3] list4 = list3 list3[2] = 100 print(list3, list4) # [1, 2, 100] [1, 2, 100] # 浅拷贝,浅复制 list3 = [1, 2, 3] list4 = list3.copy() # 【掌握】 # list4 = list3 * 1 list3[2] = 100 print(list3, list4) # [1, 2, 100] [1, 2, 3] list5 = [1, 2, [3, 4]] list6 = list5.copy() list5[2][0] = 99 print(list5, list6) # [1, 2, [99, 4]] [1, 2, [99, 4]] # 深拷贝,深复制 import copy list5 = [1, 2, [3, 4]] list6 = copy.deepcopy(list5) list5[2][0] = 99 print(list5, list6) # [1, 2, [99, 4]] [1, 2, [3, 4]] # 多维列表 # 一维列表 list1 = [1,2] # 二维列表 list2 = [ [1,2,3], [4,5,6], [7,8,9] ]
false
e542c39b036173198db1d19f045a3959957d5d6f
everqiujuan/python
/day13/code/06_多重继承.py
1,265
4.1875
4
# 人 Person # 员工 Employee # 主管 Manager # 继承:从一般(父类)到特殊(子类) # 父类 class Person(object): def __init__(s, name): s.name = name print("Person,self:", id(s)) def run(self): print(self.name, "在跑步") # 子类 class Employee(Person): def __init__(self, name1, age): print("Employee,self:", id(self)) # self=employee # Person.__init__(self, name1) # self.name = name1 # super() : 表示父类对象 super().__init__(name1) # 隐式调用 self.age = age def eat(self): print(self.name, "在吃饭") # 子类对象 Employee("黄峥", 38) # print("employee:", id(employee)) # print(employee.name, employee.age) # employee.run() # employee.eat() # 山寨货 小米新品的电视机 300块 3亿 # 孙子类 class Manager(Employee): def __init__(self, name, age, sex): super().__init__(name, age) self.sex = sex def sleep(self): print(self.name, "在睡觉") #创建孙子类对象 # manager = Manager('黄峥', 38, '男') # print(manager.name, manager.age, manager.sex) # manager.run() # manager.eat() # manager.sleep()
false
f2d1cdcbd86af861339970878e3c4bcecd5bf9df
everqiujuan/python
/day09/code/07_迭代器&迭代器对象.py
1,326
4.3125
4
from collections import Iterator # 迭代器 from collections import Iterable # 可迭代对象,迭代器对象 # 迭代器 # 迭代器对象:可以使用for-in循环遍历的 # 迭代器对象:可以使用for-in循环的 # list, tuple, dict, set, str, generator对象 都是迭代器对象 print(isinstance([1, 2], Iterable)) # True print(isinstance((1, 2), Iterable)) # True print(isinstance({}, Iterable)) # True print(isinstance({1, 2}, Iterable)) # True print(isinstance("hello", Iterable)) # True print(isinstance((i for i in range(1,3)), Iterable)) # True # 迭代器: 可以使用for-in遍历,且可以next() print(isinstance([1, 2], Iterator)) # False print(isinstance((1, 2), Iterator)) # False print(isinstance({}, Iterator)) # False print(isinstance({1, 2}, Iterator)) # False print(isinstance("hello", Iterator)) # False print(isinstance((i for i in range(1, 3)), Iterator)) # True # iter: 可以将迭代器对象 转换成 迭代器 list1 = [11, 22, 33] res = iter(list1) # print(res) # <list_iterator object at 0x00000000027B7208> # print(next(res)) # 11 # print(next(res)) # 22 # print(next(res)) # 33 # print(next(res)) # 报错 # list(): 将迭代器转换成列表迭代器对象 list2 = list(res) print(list2) # [11, 22, 33]
false
a352cb58f7c04e49769d48edab362c55e03a2142
karslio/PYCODERS
/Assignments-04-functions/11-equal_reverse.py
242
4.25
4
def equal_reverse(): word = input('enter a word') newString = word[::-1] if word == newString: return True else: return False print(equal_reverse()) # Ex: madam, tacocat, utrecht # Result: True, True, False
true
55aa5c2b12663d078a37ff58edcda05416d69f04
madisonstewart2018/quiz1
/main 6.py
1,184
4.46875
4
#this function uses the variables matrix and vector. def matVec(matrix, vector): ''' The function takes in a matrix with a vector, and for each element in one row multiplies by each number in the vector and then adds them together. Function returns a new vector. ''' new_x = [] for i in range(len(matrix)): #i.e. in range(3) so (0, 1, 2) product = 0 for j in range(len(vector)): #i.e. in range(3) so (0, 1, 2) product += matrix[i][j] * vector[j] #the product is then the prodcut (0) + matrix of i(outer range(3)) and j(inner range(3)) times the vector of j(outer range(3)). The computer goes through and multiplies all of this together. new_x.append(product) #adds the prodcut found above to the end of new_x. So it puts the answer(product) in the brackets of new_x. return new_x #this is the testing variables. testmatrix01 = [[1, 2, 3], [3, 4, 5], [6, 7, 8]] testmatrix02 = [1] testmatrix03 = 'this is a test' testvector01 = [1, 2, 3] testvector02 = [[1, 2, 3], [3, 4, 5], [5, 6 ,7]] testvector03 = 5 print(matVec(testmatrix01, testvector01)) #print(matVec(testmatrix02, testvector02)) #print(matVec(testmatrix03, testvector03))
true
081346e448fc60eec12caf9bab5aca15080bb962
BrianClark1/Python-for-Everybody-Specialization
/Chapter 11/11.2.py
827
4.21875
4
#Looking inside of a file, Extracting numbers and summing them name = input("Enter file:") #Prompt User to input the file if len(name) < 1 : name = "RegexRealSum.txt" #Allows user to simply press enter to open specific file handle = open(name) #assigns the file to a variable name inp = handle.read() #Reads the entire file, newlines and all and puts it into a single string import re #To use regular expressions in your program you must import the librARY getnum = re.findall('[0-9]+', inp) #Looks for integers using finaall and regular expressions from the string getnumint = list(map(int, getnum)) #Map function interates through the list converting each string to an integer sum = 0 for thing in getnumint: #Simple definite loop to sum the parts of the list together sum = sum + thing print(sum) #Print Result
true
f9ddc7d5c1236760550c5d868536c748d1769e88
nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available
/completed Tutorials/bubbleSort.py
706
4.28125
4
#The main difference between bubble sort and insertion sort is that #bubble sort performs sorting by checking the neighboring data elements and swapping them if they are in wrong order #while insertion sort performs sorting by transferring one element to a partially sorted array at a time. #BUBBLE SORT myList = [15,24,62,53,25,12,51] maxIndex = 6 #remember its maxIndex not max number of elements print('This is the unsorted list ' + str(myList)) n = maxIndex for i in range(maxIndex): for j in range (n): if (myList[j] > myList[j+1]): temp = myList[j] myList[j] = myList[j+1] myList[j+1] = temp n-=1 print('This is the sorted list ' + str(myList))
true
b87526548062f13ae7e10e90185550b9c896cee5
nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available
/completed Tutorials/global, local, nonlocal scope variables.py
1,113
4.59375
5
#The nonlocal keyword is used to work with variables inside nested functions, #where the variable should not belong to the inner function. #Use the keyword nonlocal to declare that the variable is not local. #Example 01 (with nonlocal) def myfunc01(): x = "John" #x is 'John' def myfunc02(): nonlocal x #this refers to the previous x x = "hello" #and now has become 'hello' myfunc02() return x #hence this will be 'hello' print(myfunc01()) #Example02 (without nonlocal) def myfunc1(): x = "John" #this will be 'John' def myfunc2(): x = "hello" #this doesn't refer to the previous x, its a new x myfunc2() return x print(myfunc1()) #Example03 (global scope) global a a = 10 def hi(): a = 52 print(a) #52 output hi() print(a) #10 output #Example 04 (local scope) s = 10 #these are by default made global def myfucn(): b = 7 #variables inside a function are said to be local print(b) # displays 7 print(s) # displays 10 myfucn() print(b) # displays that b is not defined since its local to the function myfunc()
true
ee9e7af06d173872648edb0c4ae4ce925981a930
saketborse/Blink-to-Roll-Dice-with-Eye-Detection
/diceroll.py
648
4.15625
4
import random def dice(): # range of the values of a dice min_val = 1 max_val = 6 # to loop the rolling through user input roll_again = "yes" # loop while roll_again == "yes" or roll_again == "y": #print("Rolling The Dices...") #print("The Values are :") # generating and printing 1st random integer from 1 to 6 #print(random.randint(min_val, max_val)) # generating and printing 2nd random integer from 1 to 6 #print(random.randint(min_val, max_val)) roll_again = "no" out = str(random.randint(min_val, max_val)) return out
true
56bfcf0cd7d2ffcca129085aa597ec7d19ca1b22
aandr26/Learning_Python
/Coursera/Week3/Week3b/Projects/format.py
1,239
4.21875
4
# Testing template for format function in "Stopwatch - The game" ################################################### # Student should add code for the format function here def format(t): ''' A = minutes, B = tens of seconds, C = seconds > tens of seconds D = remaining tens of seconds. A:BC:D ''' A = ((t // 10) // 60) #print ("This is A " + str(A)) B = (((t // 10) % 60) // 10) #print ("This is B " + str(B)) C = (((t // 10) % 60) % 10) #print ("This is C " + str(C)) D = ((t // 1) % 60) % 10 #print ("This is D " + str(D)) return (str(A) + ":" + str(B) + str(C)+ "." + str(D)) ################################################### # Test code for the format function # Note that function should always return a string with # six characters print (format(0)) print (format(7)) print (format(17)) print (format(60)) print (format(63)) print (format(214)) print (format(599)) print (format(600)) print (format(602)) print (format(667)) print (format(1325)) print (format(4567)) print (format(5999)) ################################################### # Output from test #0:00.0 #0:00.7 #0:01.7 #0:06.0 #0:06.3 #0:21.4 #0:59.9 #1:00.0 #1:00.2 #1:06.7 #2:12.5 #7:36.7 #9:59.9
true
20b6edc6c257810f00377bc18c4fb0c4d5fe7d3a
aandr26/Learning_Python
/Coursera/Week3/Week3b/Exercises/expanding_cricle.py
865
4.125
4
# Expanding circle by timer ################################################### # Student should add code where relevant to the following. import simplegui WIDTH = 200 HEIGHT = 200 radius = 1 # Timer handler def tick(): global radius global WIDTH radius += 2 # Draw handler def draw(canvas): global WIDTH global HEIGHT global radius if radius <= (WIDTH/2): canvas.draw_circle([WIDTH/2, HEIGHT/2], radius, 2, "Red") elif radius >= (WIDTH/2): timer.stop() canvas.draw_circle([WIDTH/2, HEIGHT/2], radius, 2, "Red") canvas.draw_text("It's too big ya dingus!", [WIDTH/8, HEIGHT/2], 18 ,"Red") # Create frame and timer frame = simplegui.create_frame("Circle", WIDTH, HEIGHT) frame.set_draw_handler(draw) timer = simplegui.create_timer(100, tick) # Start timer frame.start() timer.start()
true
1da99068500ac43445324a856ac14ff1f7e1c626
rebel47/PythonInOneVideoByCodeWithHarry
/chapter2solutions.py
886
4.28125
4
# To add two numbers # a = int(input("Enter the first number: \n")) # b = int(input("Enter the second number: \n")) # print("Sum of first and second number is:",a+b) # To find the remainder # a = int(input("Enter the number whose remainder you want to know: \n")) # print("The reaminder of the given number is:", a%2) # Check type of variable of assigned using input function # a = input("Enter your anything you want to: \n") # print(a) # print(type(a)) # To find whether a is greater than b or not # a = 34 # b = 80 # print(a>b) # To find the average of the two number given by the users # a = int(input("Enter the first number")) # b = int(input("Enter the second number")) # avg = (a+b)/2 # print("Average of two number is:", avg) # To find the square of the number given by the user a = int(input("Enter the number: \n")) a *= a print("Square of the given number is:", a)
true
a608c36a28981eb16358dfb74e1414d1b028aacb
rebel47/PythonInOneVideoByCodeWithHarry
/chapter3solutions.py
829
4.40625
4
# # Print user name with Good afternoon message # name = input("Enter your name:\n") # print("Good afternoon", name) # #Print the given name by adding user name # name = input("Enter the Candidate Name:\n") # date = input("Enter the Date:\n") # letter = '''Dear <|NAME|>, # You are selected!! # Date: <|DATE|>''' # letter = letter.replace("<|NAME|>", name) # letter = letter.replace("<|DATE|>", date) # print(letter) # # WAP to detect double spaces in a string and replace them with single spaces # story = "hello my name is Ayaz Alam and today I am going to learn Python" # doubleSpaces = story.find(" ") # print(doubleSpaces) # print(story.count(" ")) # print(story.replace(" ", " ")) # Format the given text by using escape sequence letter = '''Dear Harry, \n\tThis Python course is nice. \nThanks! ''' print(letter)
true
52deb61b876f65ec65d06c4285f7e34db66ccdec
arushss/Python_Task
/Task01.py
2,516
4.5
4
# Create three variables in a single line and assign different values to them and make sure their data types are different. # Like one is int, another one is float and the last one is a string. x, y, z = 10, 20.5, "Consultadd" print ("x is: ", x) print ("y is: ", y) print ("z is: ", z) # Create a variable of value type complex and swap it with another variable whose value is an integer. cmplx = 20+5j x, cmplx = cmplx, x print("Values after swapping are:") print("x is: ", x) print("Cmplex variable is: ", cmplx) # Swap two numbers using the third variable as the result name and do the same task without using any third variable. print("x and y will be swapped with third variable called name") name = x x = y y = name print ("x and y value after swapping is: ", x, y) print("swapping x and y again without using third variable") x,y = y,x print("x and y value after swapping without third variable is: ", x, y) # Write a program to print the value given by the user by using both Python 2.x and Python 3.x Version. print("Enter any number from keyboard") val = input() print("value you have entered is: ", val) # this is printing the value using python 3.x version print("printing value for 2.x version is going to give us an error because currently I am working on version 3.x but the below line is commented for that purpose") # print "value of x in version 2.x is", val # Write a program to complete the task given below: # Ask the user to enter any 2 numbers in between 1-10 and add both of them to another variable call z. # Use z for adding 30 into it and print the final result by using variable results. print("enter two numbers one by one with values between 1 and 10") a = int(input()) b = int(input()) z = a + b results = z + 30 print("The final value is: ", results) # Write a program to check the data type of the entered values. HINT: Printed output should say - The input value data type is: int/float/string/etc print("enter anything so that its data type can be checked") val2 = eval(input ()) print("The data type of entered value is: ", type(val2)) # If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again. Will it change the value. If Yes then Why? # yes the value will be changed because that's why the variable is used for. # It means we have an access to the memory which can store the data of any type and # python is smart enough to change the data type of that variable depending upon the value stored in it.
true
2f60538072b1e817495b6a4df3036e4a06c72713
BoLindJensen/Reminder
/Python_Code/Snippets/Files/MoreFiles/Open.py
1,513
4.125
4
''' The function open() opens a file. file: path to file (required) mode: read/write/append, binary/text encoding: text encoding eg. utf-8. It is a good idea to always specify this, as you never know what other file systems use as their default Modes: 'r' Read 'w' Write 'x' eXclusive creation, fails if the file already exists. 'a' Append to the file if it exists. 'b' Binary mode 't' Text mode (Default) '+' open a disk file for updating(reading and writing) 'U' Universal new lines mode(legasy code) check: http://docs.python.org/3/library/codecs.html#standard-encodings ''' import sys print(sys.getdefaultencoding()) my_filename = "text.txt" # Make the file f = open(my_filename , mode='wt', encoding ='utf-8') #print(help(f)) # Write something into the file f.write("This is a long message,") f.write(" that continues. \n") f.write("Now it ends.") f.close() #print(f) # Open a file g = open(my_filename, mode= 'rt', encoding= 'utf-8') # Read 16 chars of the file print(g.read(16)) # Read everything from last read print(g.read()) print(g.read()) # no more information in file. print(g.seek(0)) # return cartridge to 0 print(g.readline()) print(g.readline()) print(g.seek(0)) # return cartridge to 0 print(g.readlines()) # Give a list g.close() # and we are done with the file # append to a file. h = open(my_filename, mode= 'at', encoding= 'utf-8') h.writelines( ['\n' 'Added lines \n' 'Remember the newlines character, ' 'if you need it \n' '...']) h.close()
true
ec4d7456fbfaa7bef8bbe1244174b7c984ffd999
BoLindJensen/Reminder
/Python_Code/Snippets/Lists/List_Comprehension.py
225
4.59375
5
# https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions # L3 returns all elements of L1 not in L2. L1 = [1,2,6,8] L2 = [2,3,5,8] L3 = [x for x in L1 if x not in L2] print(L3) #L3 will contain [1, 6].
true
570d466855d3abeb761c3bb07e1f53628b2df264
BoLindJensen/Reminder
/Python_Code/Snippets/Lists/List_Comprehension2.py
950
4.34375
4
''' Python Comprehension works on list[], set{}, dictionaries{key:value} List Comprehension style is Declarative and Functional it is readable, expressive, and effective. [ expr(item) for item in items ] [ expr(item) for item in iterable ] [ expr(item) for item in iterable if predicate(item) ] ''' words = "What is this list comprehension i hear so much about, what can it help me with?" words_list = words.split() # This List comprehension print([len(word) for word in words_list]) # Is the same as this foreach loop. word_lengths = [] for word in words_list: word_lengths.append(len(word)) print(word_lengths) from math import sqrt def is_prime(x): if x < 2: return False for i in range(2,int(sqrt(x)) +1): if x % i == 0: return False return True print([x for x in range(101)]) print("Using is_prime() function as optional filter clause") print([x for x in range(101) if is_prime(x)])
true
cbf441034155917915332a6323df036be5b2f1da
mdmasrurhossain/Learning_Python_Zulu
/quiz_1/Q5.py
567
4.375
4
### Q5: Write a list of of all the datatypes in pythons myList = [16, 'Icecream', [4, "hello"], (5, 10), {'age': 3}] print(myList) print("Number Datatype: ", myList[0]) print("String Datatype: ", myList[1]) print("List Datatype: ", myList[2]) print("Tuple Datatype: ", myList[3]) print("Dictionary Datatype: ", myList[4]) ###OUTPUT#### # [16, 'Icecream', [4, 'hello'], (5, 10), {'age': 3}] # # Number Datatype: 16 # # String Datatype: Icecream # # List Datatype: [4, 'hello'] # # Tuple Datatype: (5, 10) # # Dictionary Datatype: {'age': 3}
false
dd428f0b5d9ab2b2a47a7882f75840f9d0dfcfde
jeyaprakash1/List_String_programs
/list_test.py
889
4.375
4
# append function to add element l=[10,20,30,10] l2=l.index(30) print(l2) # insert function to insert a element l1=['a','b','c'] l1.insert(3,'d') print(l1) # Extend one list to another list s1=["one","two","three"] print(len(s1)) s2=[4,5] s1.extend(s2) print(s1) print(len(s1)) # Remove function to remove particular element sen=['sun','mon','fri'] sen.remove('fri') print(sen) # pop function to remove elements in last position and particular position list1=['prakash','gandhi','muthu','vignesh'] list1.pop() print(list1) list1.pop(2) print(list1) # Reverse function to reverse a list l1=['a','b','c','d'] l1.reverse() print(l1) # Split a string and its stored in list l= " Wish you happy birthday " grp=l.split() print(grp) # join function sen=["hi","hello"] sen=' '.join(sen) print(sen) l=[10,20,30,40,50,10,70,80,10] l2=l.index(10,2,9) print(l2)
false
d31d9c60357120583f0fb35784016b5d561aef81
sgttwld/tensorflow-2-simple-examples
/1b_gradientdescent_gradient.py
831
4.15625
4
""" Example of gradient descent to find the minimum of a function using tensorflow 2.1 with explicit gradient calculation that allows further processing Author: Sebastian Gottwald Project: https://github.com/sgttwld/tensorflow-2.0-simple-examples """ import tensorflow as tf import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' optimizer = tf.keras.optimizers.SGD(learning_rate=.05) x = tf.Variable(tf.random.normal(shape=(), mean=2.0, stddev=0.5)) f = lambda: (x**2-2)**2 def opt(f,x): with tf.GradientTape() as g: y = f() grad = g.gradient(y, x) ## here we could do some gradient processing ## grad = ... optimizer.apply_gradients(zip([grad], [x])) print('init','x =',x.numpy(), 'f(x) =',f().numpy()) for n in range(10): opt(f,x) print('ep',n,'x =',x.numpy(), 'f(x) =',f().numpy())
true
0a1c8843bdb901ced9951f32ad87bccab0c4e5cd
Marin-Tony/Calculator
/Basic.py
1,593
4.15625
4
def oprtn(a, b): print("1.Addition") print("2.Subtraction") print("3.Division") print("4.Multiplication") #print("5.Percentage") print("5.Remainder") print("Choose the Number specified before each operation to be performed:") oper_selectd = input(" ") if oper_selectd == "1": return add(a, b) elif oper_selectd == "2": return sub(a, b) elif oper_selectd == "3": return div(a, b) elif oper_selectd == "4": return mul(a, b) elif oper_selectd == "5": return rem(a, b) else: print("INVALID") def add(num1, num2): num3 = num1 + num2 return num3 def sub(num1, num2): num3 = num1-num2 return num3 def div(num1, num2): num3 = num1/num2 return num3 def mul(num1, num2): num3 = num1*num2 return num3 def rem(num1, num2): num3 = num1 % num2 return num3 rept = 'y' while rept == 'y': num1 = int(input("Enter the number1: ")) num2 = int(input("Enter the number2: ")) res = oprtn(num1, num2) print("The result is ", res) rept = input("If you want to do more calculations, type \'y\' else press ENTER KEY") else: cal_type = input("\nIf you want to do advanced calculations please type \'ADVANCED\' \n else press enter") if cal_type == "advanced": import advncd else: #print("To exit from the calculator, please press ENTER KEY") quit()
false
22c04d4835001a9a7160a5be71e2395427a0f8b6
FernandoSka/Programing-works
/algorithms/forc.py
398
4.21875
4
arreglo = ["elemento1", 1, 2, 3, "hola", 1.8] for element in range(0, len(arreglo)): print(arreglo[element]) break for element in arreglo: print(element) break for element in range(0, len(arreglo)): print(element) break #1. mostrar elementos de la matriz matriz = [["hola ", 5, 8], ["mundo", 12, 9.8], ["better", 100, 1.15]] #2. mostrar solo los elementos de tipo string
false
9ca4f40c2b05a7da51e640000c6a37ca88bf91a8
suvratjain18/CAP930Autum
/23AugPractical.py
1,078
4.59375
5
# What Is Sets #collection of well defined things or elements #or # Unorderd collection of distinct hashable elements #In First Create a set s={1,2,3} print(s) print(type(s)) t={'M','K','R'} print(t) print(type(t)) # How you can declare Empty Set using below here # empty_set=set() # it will convert list to string below example set_from_list=set([1,2,1,4,3]) basket={"apple","orange","apple","pear","banana"} len(basket) # Output is 4 Because it detects only distinct ones orange in basket #check membership functions for fruit in basket: print(fruit,end='/') a=set('abracadabra') b=set('alacazam') print(a) print(b) a-b # means common between two sets a is not showing # Output above command a-b {'d', 'b', 'r'} >>> a|b # It means union # Output of both sets {'l', 'z', 'r', 'b', 'a', 'd', 'c', 'm'} a&b # letters in both a and b a^b # letters in a or b but not both (a-b U b-a) a=set('missippi') # its Output is in sets {'m','i','s','p'} a.add('r') # its add in a set a.remove('r') # its remove r in the set a.pop() # it removes the set value from the first
true
661fe7a34a439278c3830a9b13f4b5f6b8d0521e
AnatoliKosarev/Python-beginner-course--Teclado-
/filesPython/fileImports/user_interactions/myfile.py
1,138
4.21875
4
print(__name__) """ The file that we run always has a __name__ variable with a value of "__main__". That is simply how Python tells us that we ran that file. Running code only in script mode Sometimes we want to include some code in a file, but we only want that code to run if we executed that file directly—and not if we imported the file. Since we know that __name__ must be equal to "__main__" for a file to have been run, we can use an if statement. We could type this in myfile.py: """ def get_user_age(): return int(input("Enter your age: ")) if __name__ == "__main__": get_user_age() """ That could allow us to run myfile.py and see if the get_user_age() function works. That is one of the key use cases of this construct: to help us see whether the stuff in a file works when we normally don't want it to run. Another use case is for files which you don't normally run yourself. Sometimes you may write a file that is for use by another program, for example. Using this construct would allow you to run your file for testing, while not affecting its functionality when it's imported by another program. """
true
b0410a2b46b734f18da31834065151d53cd37a41
AnatoliKosarev/Python-beginner-course--Teclado-
/advancedPythonDevelopment/itertoolsCombinatoricIterators.py
2,369
4.84375
5
# permutations """ permutations is concerned with finding all of the possible orderings for a given collection of items. For example, if we have the string "ABC", permutations will find all of the ways we can reorder the letters in this string, so that each order is unique. """ from itertools import permutations p_1 = permutations("ABC") print(*p_1) # ('A', 'B', 'C') ('A', 'C', 'B') ('B', 'A', 'C') ('B', 'C', 'A') # ('C', 'A', 'B') ('C', 'B', 'A') """ By default, permutations returns different orderings for the entire collection, but we can use the optional r parameter to limit the function to finding shorter permutations. """ p_2 = permutations("ABC", r=2) # ('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B') """ Providing an r value greater than the length of the collection passed into permutations will yield an empty permutations object. """ p_3 = permutations("ABC", r=4) print(*p_3) # # combinations """ combinations returns an iterable object containing unique combinations of elements from a provided collection. Note that combinations isn't concerned with the order of elements, so combinations will treat ('A', 'B') as being identical to ('B', 'A') in its results. The length of the resulting combinations is controlled by the r parameter once again, but in the case of combinations, this argument is mandatory. """ from itertools import combinations c_1 = combinations("ABC", r=2) # ('A', 'B') ('A', 'C') ('B', 'C') c_2 = combinations("ABC", r=3) # ('A', 'B', 'C') """ It is possible to get duplicate elements back from combinations, but only if the provided iterable contains multiple instances of a given element. (1, 2, 3, 1), for example. """ c_3 = combinations((1, 2, 3, 1), r=2) # (1, 2) (1, 3) (1, 1) (2, 3) (2, 1) (3, 1) """ In this case (1, 2) and (2, 1) are not simply the same elements in a different order, the 1s are in fact different elements in the original collection. """ """ It's possible to include instances where an item is paired with itself using the combinations_with_replacement function. It works just like combinations, but will also match every element to itself. """ from itertools import combinations, combinations_with_replacement c_4 = combinations((1, 2, 3), r=2) # (1, 2) (1, 3) (2, 3) c_5 = combinations_with_replacement((1, 2, 3), r=2) # (1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)
true
cda9d69009f9846ad202a73821a95a31b7a0a404
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/enumerateInLoop.py
1,488
4.375
4
friends = ["Rolf", "John", "Anna"] for counter, friend in enumerate(friends, start=1): print(counter, friend) # 1 Rolf # 2 John # 3 Anna friends = ["Rolf", "John", "Anna"] friends_dict = dict(enumerate(friends)) print(friends_dict) # {0: 'Rolf', 1: 'John', 2: 'Anna'} # если не переводить в другой тип (dict, list, etc.) - enumerate очиститься после первого цикла, т.к. использует iterator(), например: friends = ["Rolf", "John", "Anna"] friends_dict2 = enumerate(friends) for counter, name in friends_dict2: print(counter, name) friends_dict3 = list(friends_dict2) print(len(friends_dict3)) movies = [ ( "Eternal Sunshine of the Spotless Mind", "Michel Gondry", 2004 ), ( "Memento", "Christopher Nolan", 2000 ), ( "Requiem for a Dream", "Darren Aronofsky", 2000 ) ] for counter, (title, director, year) in enumerate(movies, start=1): # enumerate = (2, ("Memento", "Christopher Nolan", 2000)) for each tuple print(f"{counter}. {title} ({year}), by {director}") # that's why скобки (title, director, year) важны, если без них - мы хотим четыре элемента, хотя по факту у нас их 2 - counter, tuple, # а со скобками - мы асайним в переменные значения из tuple
false
3814a7116033ae2935d0ef09c8d7fae42f29c027
AnatoliKosarev/Python-beginner-course--Teclado-
/advancedPythonDevelopment/namedTuple.py
524
4.1875
4
from collections import namedtuple Student = namedtuple("Student", ["name", "age", "faculty"]) names = ["John", "Steve", "Mary"] ages = [19, 20, 18] faculties = ["Politics", "Economics", "Engineering"] students = [ Student(*student_data) for student_data in zip(names, ages, faculties) ] print(students) oldest_student = max(students, key=lambda student: student.age) # In the code above, we've set a custom key for max so that it compares our tuples based on the age element in each tuple print(oldest_student)
true
bb7ba363b2297d7d57b85e3c9b2cd9ce71147235
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/zipFunction.py
2,299
4.65625
5
""" Much like range, zip is lazy, which means it only calculates the next value when we request it. We therefore can't print it directly, but we can convert it to something like a list if we want to see the output """ from itertools import zip_longest student_ids = (112343, 134555, 113826, 124888) names = ("mary", "Richard", "Noah", "KATE") print(*zip(student_ids, names)) student_dict = dict(zip(student_ids, names)) print(student_dict) student_dict2 = dict(zip(names, student_ids)) print(student_dict2) student_dict3 = list(zip(student_ids, names, [1, 2, 3, 4, 5])) # value "5" is ignored because student_ids, names have only 4 elements, to avoid this - zip_longest should be used print(student_dict3) pet_owners = ["Paul", "Andrea", "Marta"] pets = ["Fluffy", "Bubbles", "Captain Catsworth"] for owner, pet in zip(pet_owners, pets): print(f"{owner} owns {pet}.") movie_titles = [ "Forrest Gump", "Howl's Moving Castle", "No Country for Old Men" ] movie_directors = [ "Robert Zemeckis", "Hayao Miyazaki", "Joel and Ethan Coen" ] movies = list(zip(movie_titles, movie_directors)) # clears after the first loop if not converted to list, dict or tuple - list(zip(movie_titles, movie_directors)) for title, director in movies: print(f"{title} by {director}.") movies_list = list(movies) print(f"There are {len(movies_list)} movies in the collection.") print(f"These are our movies: {movies_list}.") """ unzip = *zipped_collection Using the * operator, we can break up a zip object, or really any collection of collections. For example, we might have something like this: """ zipped = [("John", 26), ("Anne", 31), ("Peter", 29)] # We can use the * operator in conjunction with zip to split this back into names and ages: names, ages = zip(*zipped) print(names) # ("John", "Anne", "Peter") print(ages) # (26, 31, 29) """ _____________________________________________________ zip_longest when we use zip, zip will stop combining our iterables as soon as one of them runs out of elements. If the other iterables are longer, we just throw those excess items away. """ l_1 = [1, 2, 3] l_2 = [1, 2] combinated = list(zip(l_1, l_2)) print(combinated) # [(1, 1), (2, 2)] combinated2 = list(zip_longest(l_1, l_2, fillvalue="_")) print(combinated2) # [(1, 1), (2, 2), (3, '_')]
true
36c9c7f2a4f0f955a46fd85c4116897bfbf61143
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/input.py
239
4.15625
4
my_name = "Bob" your_name = input("Enter your name: ") # always returns string print(f"Hello, {your_name}. My name is {my_name}") print() age = int(input("enter your age: ")) months = age * 12 print(f"you have lived for {months} months")
true
0422da106ef0fb9b7e226007c4836aaf20985bc8
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonTextBook/exercises/dictionary/ex-6.7.py
548
4.21875
4
person1 = { 'name': 'John', 'lastname': 'Lennon', 'age': '33', 'city': 'Liverpool' } person2 = { 'name': 'James', 'lastname': 'Hetfield', 'age': '45', 'city': 'San Francisco' } person3 = { 'name': 'Fat', 'lastname': 'Mike', 'age': '19', 'city': 'Los Angeles' } people = [person1, person2, person3] # for person in people: # for data in person.values(): # print(data) for person in people: name, lastname, age, city = person.values() print(f"{name} {lastname}, {age}, {city}")
false
b012c287ee491ed19617ebc9ec1b5d82b89e3d10
AnatoliKosarev/Python-beginner-course--Teclado-
/pythonFundamentals/listComprehension.py
2,079
4.53125
5
# can be used with lists, tuples, sets, dictionaries numbers = [0, 1, 2, 3, 4] doubled_numbers1 = [] for number in numbers: doubled_numbers1.append(number * 2) print(doubled_numbers1) # same can be done with list comprehension which is much shorter doubled_numbers2 = [number2 * 2 for number2 in numbers] print(doubled_numbers2) doubled_numbers3 = [number3 * 2 for number3 in range(10)] print(doubled_numbers3) # we can reuse the base list numbers = [number * 2 for number in numbers] print(numbers) friend_ages = [22, 35, 31, 27] age_strings = [f"My friend is {age} years old" for age in friend_ages] print(age_strings) friend = input("Enter your friend's name: ") names = ["Rolf", "Phil", "Vito"] friends_lower = [name.lower() for name in names] if friend.lower() in friends_lower: print(f"{friend.title()} is one of your friends.") names = ("mary", "Richard", "Noah", "KATE") ages = (36, 21, 40, 28) people = [(name.title(), age) for name, age in zip(names, ages)] print(people) # List comprehensions also allow for more than one for clause # We can use this to find all the possible combinations of dice rolls for two dice, for example: roll_combinations = [(d1, d2) for d1 in range(1, 7) for d2 in range(1, 7)] # for для d1 - внешний цикл, для d2 - внутренний print(roll_combinations) # dictionary comprehension student_ids = (112343, 134555, 113826, 124888) names = ("mary", "Richard", "Noah", "KATE") students = {} for student_id, name in zip(student_ids, names): student = {student_id: name.title()} students.update(student) print(students) students2 = { student_id: name.title() # the value we want to add to the new collection for student_id, name in zip(student_ids, names) # a loop definition which determines where the original values are coming from } print(students2) students3 = { student_ids[i]: names[i].title() # the value we want to add to the new collection for i in range(len(student_ids)) # a loop definition which determines where the original values are coming from } print(students3)
true
af12948c9b1f6161862ae5079d03bf8d3595e44e
jsdiuf/leetcode
/src/Powerful Integers.py
1,611
4.1875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2019/1/6 12:06 Given two non-negative integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0. Return a list of all powerful integers that have value less than or equal to bound. You may return the answer in any order. In your answer, each value should occur at most once. Example 1: Input: x = 2, y = 3, bound = 10 Output: [2,3,4,5,7,9,10] Explanation: 2 = 2^0 + 3^0 3 = 2^1 + 3^0 4 = 2^0 + 3^1 5 = 2^1 + 3^1 7 = 2^2 + 3^1 9 = 2^3 + 3^0 10 = 2^0 + 3^2 Example 2: Input: x = 3, y = 5, bound = 15 Output: [2,4,6,8,10,14] Note: 1 <= x <= 100 1 <= y <= 100 0 <= bound <= 10^6 """ import math class Solution: def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ if x == 1 and y == 1: return [2] if bound >= 2 else [] if x == 1: jtop = int(math.log(bound - 1, y)) return [1 + y ** j for j in range(jtop+1)] if y == 1: itop = int(math.log(bound - 1, x)) return [1 + x ** i for i in range(itop+1)] ans = set() itop = int(math.log(bound - 1, x)) jtop = int(math.log(bound - 1, y)) for i in range(itop+1): for j in range(jtop+1): t = x ** i + y ** j if t <= bound: ans.add(t) else: break return list(ans) s = Solution() print(s.powerfulIntegers(1, 2, 100))
true
c167226fbfec1a0ecbf43cfcda87b6e51317e656
jsdiuf/leetcode
/src/N-ary Tree Preorder Traversal.py
835
4.15625
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-23 9:19 Given an n-ary tree, return the preorder traversal of its nodes' values. For example, given a 3-ary tree: Return its preorder traversal as: [1,3,5,6,2,4]. Note: Recursive solution is trivial, could you do it iteratively? """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ res = [] def helper(node): if node: res.append(node.val) if res.children: for n in node.children: helper(n) helper(root) return res
true
80c0e24423aa62f932ec85bb6c172dfac5c9244b
jsdiuf/leetcode
/src/Valid Parentheses.py
2,026
4.125
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-3 9:47 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true """ class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ map = {"(": -3, "{": -2, "[": -1, "]": 1, "}": 2, ")": 3} if s == "": return True if len(s) % 2 != 0: return False stack = [] for e in s: n = len(stack) # not empty if map[e] < 0: stack.append(e) continue if n > 0 and map[stack[n - 1]] + map[e] == 0: stack.pop() continue return False return len(stack) == 0 def isValid2(self, s): """ ([)] """ stack = [] for c in s: if c == '(': stack.append(')') elif c == '{': stack.append('}') elif c == '[': stack.append(']') elif len(stack) == 0 or stack.pop() != c: return False return len(stack) == 0 def isValid3(self, s): """这也行!!!!! :type s: str :rtype: bool """ n = len(s) if n == 0: return True if n % 2 != 0: return False while '()' in s or '{}' in s or '[]' in s: s = s.replace('{}', '').replace('()', '').replace('[]', '') return s == '' s = Solution() print(s.isValid("{{}[()][]}"))
true
40d26a6f9730deb24c97e2793f492213daac4437
jsdiuf/leetcode
/src/Sort Array By Parity II.py
1,137
4.1875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-14 9:32 Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 """ class Solution: def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ odd = [] # 奇数 even = [] # 偶数 for i in range(len(A)): if A[i] & 1 == 0: odd.append(A[i]) else: even.append(A[i]) ans = [] for i in range(len(odd)): ans.append(odd[i]) ans.append(even[i]) return ans return [(odd[i],even[i]) for i in range(len(odd))] s = Solution() print(s.sortArrayByParityII([4, 2, 5, 7]))
true
15def978d14ace9dc60ae954f9c18cb1184acff7
sauerseb/Week-Two-Assignment
/program3.py
439
4.34375
4
# __author__ = Evan Sauers (sauerseb) # CIS-125-82A # program3.py # # This program prompts the user for a distance measured in kilometers, converts it to miles, and prints out the results. # K= kilometers # M= miles # Ask user for a distance in kilometers # Convert to miles # (K * .62) K = eval(input("Please enter a distance in kilometers: ")) M = (K * .621371192) print("The distance" , K, " in kilometers is equal to " , M, "miles")
true
3381cbb4e997978ffa139b47868fdb282a00a7db
langestefan/pyluhn
/luhn/luhn.py
1,094
4.25
4
"""Calculate checksum digit from any given number using Luhn algorithm.""" def create_luhn_checksum(number): """ Generates luhn checksum from any given integer number. :param number: Number input. Any integer number. :return: Calculated checksum digit """ str_number = str(number) n_digits = len(str_number) parity = n_digits % 2 sum_n = 0 # Loop over digits, start at most right hand point for index in range(n_digits, 0, -1): digit = int(str_number[index - 1]) if parity == index % 2: digit += digit if digit > 9: digit -= 9 sum_n += digit return (sum_n * 9) % 10 def verify_checksum(number_plus_cs): """ Verify a given number that includes a Luhn checksum digit. :param number_plus_cs: A number + appended checksum digit. :return: True if verification was successful, false if not. """ number = str(number_plus_cs)[:-1] checksum = number_plus_cs % 10 if create_luhn_checksum(number) is not checksum: return False else: return True
true
c0c74fe14d6ff278ee0bc0396d298cf903aa505f
kingsleyndiewo/codex-pythonium
/simple_caesar_cipher.py
806
4.40625
4
# A simple Caesar cipher # Author: Kingsley Robertovich # Caesar cipher is a type of substitution cipher in which each letter in the plaintext is # 'shifted' a certain number of places down the alphabet. In this example we use the ASCII # character set as our alphabet def encipher(clearText, offset = 5): cipherText = '' for c in clearText: s = ord(c) + offset cipherText += chr(s) return cipherText def decipher(ciphertext, offset = 5): clearText = '' for c in cipherText: s = ord(c) - offset clearText += chr(s) return clearText if __name__ == '__main__': # get some input clearText = input("Please enter a message to encipher: ") cipherText = encipher(clearText) print(cipherText) newClear = decipher(cipherText) print(newClear)
true
d4cabe574a786147dba2fbb9cee912e24a4a120d
adam-barnett/LeetCode
/unique-paths-ii.py
1,689
4.125
4
""" Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [[0,0,0], [0,1,0], [0,0,0]] The total number of unique paths is 2. Note: m and n will be at most 100. Problem found here: http://oj.leetcode.com/problems/unique-paths-ii/ """ """ I solve the problem in place on the input grid, switching all of the values of the obstacles from 1 to -1 so they can be appropriately ignored. """ class Solution: # @param grid_obs, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, grid_obs): if not grid_obs or not grid_obs[0]: return 0 if grid_obs[0][0] == 1: return 0 for i in xrange(len(grid_obs)): for j in xrange(len(grid_obs[i])): if i == 0 and j == 0: grid_obs[i][j] = 1 elif grid_obs[i][j] == 1: grid_obs[i][j] = -1 else: if i: grid_obs[i][j] += max(grid_obs[i-1][j], 0) if j: grid_obs[i][j] += max(grid_obs[i][j-1], 0) return max(grid_obs[-1][-1], 0) #test sol = Solution() test_cases = [ ([[0]],1), ([[1]],0), ([[0,1]],0), ([[0,0,0],[0,1,0],[0,0,0]],2)] for (case, expected) in test_cases: print '\nFor the grid:', case, ' there are:', expected, 'routes' print 'our system finds:', sol.uniquePathsWithObstacles(case), print 'routes'
true
71a1e30327e58b46a8851048359e520621d8f088
miaoranren/calculator-2-exercise
/calculator.py
1,411
4.375
4
"""A prefix-notation calculator. Using the arithmetic.py file from Calculator Part 1, create the calculator program yourself in this file. """ from arithmetic import * while True: response = input("> ") tokens = response.split(' ') if tokens[0] == 'q': print("You will exit!") break elif len(tokens) < 2: print("Not enough inputs") continue operator = tokens[0] num1 = tokens[1] #This is the case with only two index , we default num2 as None. if len(tokens) < 3: num2 = None else: num2 = tokens[2] result = None if not num1.isdigit() or num2.isdigit() : print("There are not numbers!") break elif operator == "+": result = add(float(num1),float(num2)) elif operator == "-": result = subtract(float(num1),float(num2)) elif operator == "*": result = multiply(float(num1),float(num2)) elif operator == "/": result = divide(float(num1),float(num2)) elif operator == "square": result = square(float(num1)) elif operator == "cube": result = cube(float(num1)) elif operator == "pow": result = power(float(num1),float(num2)) elif operator == "mod": result = mod(float(num1),float(num2)) else: print('Please enter two integers!') print(result)
true
896c5d1adeafa4ca6833465080583d18dc10dea3
gyuruza921/p139
/main2.py
1,489
4.15625
4
# coding : utf-8 # 文字コードの宣言 #買い物プログラム # 残金 money = 0 # 商品毎の単価 # りんご apple = {"name": "りんご", "price": 500} # = {"name": "", "price": } # バナナ banana = {"name": "バナナ", "price": 400} # ぶどう grape = {"name": "ぶどう", "price": 300} # 果物のリスト fruits = {"apple":apple, "banana":banana, "grape":grape} print(fruits) # 個数 count = 0 # # 計算 # # 所持金を設定 money = input("金額を入力してください") money = int(money) # 購入する商品を選択 options = ["apple", "banana", "grape"] item = input("商品を選択してください(りんご:0、バナナ:1、ブドウ:2)") print(options[int(item)]) item = int(item) # 購入する個数を選択 count = input("購入する個数を入力してください") count = int(count) # 合計金額 total_price = fruits[options[int(item)]]["price"] * count # 結果を表示する # 合計金額が残金より小さい場合 if total_price < money: print(fruits[options[item]]["name"] + "を" + str(count) + "個買いました") print("残金は" + str(money - total_price) + "です") # 合計金額が残金と等しい場合 elif total_price == money: print(str(fruits[options[item]]["name"]) + "を" + str(count) + "個買いました") print("残金は0です") # 合計金額が残金より大きい場合 elif total_price > money: print("今の所持金では買えません")
false
e8860d7c2095fa654b7e6ed28f9a60ce73931491
ptg251294/DailyCodingProblems
/ParanthesesImbalance.py
801
4.3125
4
# This problem was asked by Google. # # Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make # the string valid (i.e. each open parenthesis is eventually closed). # # For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, # since we must remove all of them. def count_invalid_parentheses(input_string): count = 0 invalid_count = input_string.find('(') for index in range(invalid_count, len(input_string)): if input_string[index] == '(': count += 1 else: count -= 1 return abs(count) + invalid_count if __name__ == '__main__': given_string = '(((((()(((' answer = count_invalid_parentheses(given_string) print(answer)
true
c56e83834fe1e889bd985dd43b7d9d62976554d2
ptg251294/DailyCodingProblems
/One2OneCharMapping.py
770
4.125
4
# This problem was asked by Bloomberg. # # Determine whether there exists a one-to-one character mapping from one string s1 to another s2. # # For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d. # # Given s1 = foo and s2 = bar, return false since the o cannot map to two characters. def mapping(): dictionary = {} for i in range(len(str1)): if str1[i] in dictionary and str2[i] != dictionary.get(str1[i]): return False else: dictionary[str1[i]] = str2[i] print('mapping------------>', dictionary) return True if __name__ == '__main__': str1 = 'abc' str2 = 'bcd' print(mapping() if len(str1) == len(str2) and len(str1) > 0 and len(str2) > 0 else False)
true
1a4c2d8a5ff279c6b64d15c8f91670a2f83f956c
Giuco/data-structures-and-algorithms
/course-1-algorithmic-toolbox/week-1/1-max-pairwise-product/max_pairwise_product.py
796
4.15625
4
# python3 from typing import List def max_pairwise_product_original(numbers: List[int]) -> int: n = len(numbers) max_product = 0 for first in range(n): for second in range(first + 1, n): max_product = max(max_product, numbers[first] * numbers[second]) return max_product def max_pairwise_product(numbers: List[int]) -> int: biggest = float("-inf") biggest_2 = float("-inf") for number in numbers: if number >= biggest: biggest_2 = biggest biggest = number elif number >= biggest_2: biggest_2 = number return biggest_2 * biggest if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product(input_numbers))
true
03e1f167ce7bf0212b7556e2bb5ef2615ada7488
longm89/Python_practice
/513_find_bottom_left_tree_value.py
1,010
4.125
4
""" Given the root of a binary tree, return the leftmost value in the last row of the tree. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: """ We will use BFS to go level by level We travel from right to left and save the value of the last node in the tree The time complexity is O(number of nodes) """ left_most_value = None queue = [root] first_pos = 0 while first_pos < len(queue): current_node = queue[first_pos] left_most_value = current_node.val first_pos += 1 if current_node.right: queue.append(current_node.right) if current_node.left: queue.append(current_node.left) return left_most_value
true
a18b926704febe19ac9cd70081b09b3ea583fc98
ppysjp93/Effective-Computation-in-Physics
/Functions/lambdas.py
852
4.4375
4
# a simple lambda lambda x: x**2 # a lambda that is called after it is defined (lambda x, y=10: 2*x +y)(42) # just because it isi anonymous doesn't mean we can't give it a name! f = lambda: [x**2 for x in range(10)] print(f()) # a lambda as a dict value d = {'null': lambda *args, **kwargs: None} # lambda as a keyword argument f in another function def func(vals, f=lambda x: sum(x)/len(x)): f(vals) # a lambda as a keyword argument in a function call func([6, 28, 496, 8128], lambda data: sum([x**2 for x in data])) # lambda's are often used when sorting containers. We can adapt the sorted # built-in function so that there is a 'key-function' which is applied to # each element in the list. The sorting then occurs on the return value of # the 'key-function' nums = [8128, 6, 496, 28] sorted(nums) sorted(nums, key=lambda x: x%13)
true
5c01549c5e88fef47d466803ace0862a8f2331c2
ppysjp93/Effective-Computation-in-Physics
/Functions/generators.py
1,482
4.4375
4
def countdown(): yield 3 yield 2 yield 1 yield 'Blast off!' # generator g = countdown() next(g) x = next(g) print(x) y, z = next(g), next(g) print(z) for t in countdown(): if isinstance(t, int): message = "T-" + str(t) else: message = t print(message) # A more complex example could be creating a generator that finds the # the square of a range of values up to n and adds one to each one. def square_plus_1(n): for x in range(n): x2 = x * x yield x2 + 1 for sp1 in square_plus_1(10): print(sp1) # This is a good example of abstraction that has been used to tidy the # complexities of the function away. # PALINDROME GENERATOR # You can create a palindrom generator that makes use of two sub generators # the first yields all the values forwards and the second yields all the values # backwards. # This is the generic definition of the sub generator def yield_all(x): for i in x: yield i # paindrom using 'yield from' semantics which is more concise def palindromise(x): yield from yield_all(x) # yields forwards yield from yield_all(x[::-1]) # yields backwards for letter in palindromise("hello"): print(letter, end = "") # The above is equivalent to this full expansion: def palindromize_explicit(x): for i in x: yield i for i in x[::-1]: yield i print("\n") for letter in palindromize_explicit("olleh"): print(letter, end = "")
true
edbb19417baa55c576dd4c029d3f475b060d9e64
computerMoMo/algorithm-python
/select_sort.py
558
4.25
4
# -*- coding:utf-8 -*- import sys def find_largest(sort_arr): res_index = 0 res = sort_arr[0] for i in range(0, len(sort_arr)): if sort_arr[i] > res: res = sort_arr[i] res_index = i return res_index def select_sort(sort_arr): new_arr = [] length = len(sort_arr) for i in range(0, length): res_index = find_largest(sort_arr) new_arr.append(sort_arr.pop(res_index)) return new_arr if __name__ == '__main__': test_arr = [0, 2, 5, 6, 7, -1] print select_sort(test_arr)
false
2c7926ba3280dbee2c3bb85dd16100a607c5374a
SDSS-Computing-Studies/004-booleans-ssm-0123
/task1.py
602
4.5
4
#! python3 """ Have the user input a number. Determine if the number is larger than 100 If it is, the output should read "The number is larger than 100" (2 points) Inputs: number Outputs: "The number is larger than 100" "The number is smaller than 100" "The number is 100" Example: Enter a number: 100 The number is 100 Enter a number: 102 The number is larger than 100 """ num = input("Give me a number") num = float(num) if num > 100 : print("This number is larger than 100") elif num == 100 : print("This number is 100") elif num < 100 : print("This number is smaller than 100")
true
2ec3881522fe87180342c17ac80690cbc867112d
KateBilous/Python_Class
/Task_13.py
1,050
4.34375
4
# Пользователь вводит длины катетов прямоугольного треугольника. # Написать функцию, которая вычислит и выведет на экран площадь треугольника и его периметр. # Площадь прямоугольного треугольника S = 1/2 a*b import math class SquareAndPerimOfTriangle: @staticmethod def print_input(): a = int(input(print("Enter first side"))) b = int(input(print("Enter second side"))) return a, b def print_output(): print('Площадь треугольника равна', square_of_triangle()) print('Периметр треугольника равн', perim_of_triangle()) side1, side2 = SquareAndPerimOfTriangle.print_input() def square_of_triangle(): square = 0.5 * (side1 * side2) return square def perim_of_triangle(): c = math.sqrt(side1 ** 2 + side2 ** 2) perim = side1 + side2 + c return perim print_output()
false
02b0aeebab04235c4ebd3f1944e059e6faf581d2
kayartaya-vinod/2019_04_PYTHON_NXP
/examples/ex08.py
708
4.21875
4
''' More loop examples: Accept two numbers and print all primes between them ''' from ex07 import is_prime from ex06 import line def print_primes(start=1, end=100): while start <= end: if is_prime(start): print(start, end=', ') start += 1 print() line() # this function re-writes (overwrites/overrides) the above function definition def print_primes(start=1, end=100): for n in range(start, end+1): if is_prime(n): print(n, end=', ') print() line('*') def main(): print_primes() print_primes(50) print_primes(end=50) print_primes(start=50) print_primes(200, 500) print_primes(end=200, start=50) if __name__=='__main__': main()
true
058a01fa70d67c4322fa03dcb7b7ba1bfbf2d5b8
gabrielriqu3ti/GUI_Tkinter
/src/grid.py
381
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 13 22:24:18 2020 @author: gabri """ from tkinter import * root = Tk() # Creating Label Widget myLabel1 = Label(root, text = "Hello World!") myLabel2 = Label(root, text = "My name is Gabriel H Riqueti") # Shoving it onto the screen myLabel1.grid(row = 0, column = 0) myLabel2.grid(row = 1, column = 0) root.mainloop()
true
876187f5eba3156eeca16e965f281ff5a00a898d
StudentTechClubAsturias/TallerGitBasico
/esPrimo.py
843
4.125
4
""" Autor: X """ #Nota: los primos son: Naturales, > 1, divisibles entre ellos mismo y entre 1 def esPrimo(n): """ Metodo para comprobar si un numero n dado es primo o no params: un numero n return: True si es primo y False de no serlo """ #Si es menor que 2 no puede ser primo if n < 2: return False #El rango de 2 hasta n for i in range(2, n): if n / i == 1: return False return True def esPrimoIntervalo(i, k): """ Metodo que comprueba si los numeros de un intervalo son primos o no params: intervalo [i ,k) return: retorna una lista de duplas """ return [(x, esPrimo(x)) for x in range(i, k)] """ #Probando que funciona <<esPrimo(n)>> primos = [3, 5, 7, 11, 13, 17, 19, 23, 29] print [(x, esPrimo(x)) for x in primos] """ """ #Probando que funciona <<esPrimoIntervalo(n)>> print esPrimoIntervalo(0, 1000) """
false
8117eed08dbe2803db65510843a217ad1602808e
yhoang/rdm
/IRI/20170619_IRI.py
2,620
4.3125
4
#!/usr/bin/python3.5 ### printing methods # two ways to print in Python name = 'Florence' age = 73 print('%s is %d years old' % (name, age)) # common amongst many programming languages print('{} is {} years old'.format(name, age)) # perhaps more consistent with stardard Python syntax ### dictionary shopping_dict = {'item-0': 'bread', 'item-1': 'potatoes', 'item-2': 'eggs', 'item-3': 'flour', 'item-4': 'rubber duck', 'item-5': 'pizza', 'item-6': 'milk'} # different ways to iterate through each key/value and print it for key in shopping_dict: print(key) print(shopping_dict[key]) for key, value in shopping_dict.items(): print(key,value) for i in shopping_dict.keys(): print(i) for i in shopping_dict.values(): print(i) ### input method temperature = int(input()) ### Check if a variable or data type for example, a list (my_list) exists (not empty) my_list=() if 'my_list' in globals(): print("my_list exists in globals") if 'my_list' in locals(): print("my_list exists in locals") ### lists/array handling shopping = ['bread', 'potatoes', 'ggs', 'flour', 'rubber duck', 'pizza', 'milk'] extrashopping = ['cheese', 'flour', 'eggs', 'spaghetti', 'sausages', 'bread'] # Combining lists all_items = shopping + extrashopping # and then remove redundancy using set() unique_items = set(all_items) # or combining it right away without adding doubles # slower though! (3times slower?) for i in extrashopping: if i not in shopping: shopping.append(i) ### performance measurement import timeit start = timeit.timeit() end = timeit.timeit() print (end - start) ### read/write example with python3+ def read_each_line_of_each_file(pathname): # name of path with multiple files with open(pathname+"/receptor_proteins.csv",'w') as csv_out: for files in os.listdir(pathname): if files.endswith(".csv"): csv_out.write("%s: \n" % files) with open(pathname+"/"+files,'r') as csv_files: for entry in csv_files: if ('receptor') in entry.lower(): csv_out.write("%s\t%s\n" % (entry.split("\t")[0],entry.split("\t")[3])) pathname = 'demo_folder' # name of path with multiple files read_each_line_of_each_file(pathname) with open(pathname+"/receptor_proteins.csv",'r') as new_csv: for entry in new_csv: print(entry) ### module sys allows you to pipe elements to code # call in bash python script.py element1 element2 element3 # in script: import sys var = [] for i in sys.argv: var.append(i)
true
fe7219d3dcbcb122404675c79678ec2aa46fec85
pascalmcme/myprogramming
/week5/lists.py
392
4.25
4
list = ["a","b","c"] #changeable and orderable collection tuple = (2,3) # not changeable print(type(list)) print(len(tuple)) list.append(99) print(list) newlist = list + [1] print(newlist) lista = [1,2,'a',True] # different data types in list print(lista[0]) print(lista[1:]) # 1 to end print(lista[::-1]) print(lista[::2]) #note we start counting at 0 x = lista.pop(0) print(x)
true