blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d0b83a4a340bcc997c730c024f4793187a0bd2ae | gerblancoa/aguinaldo_sv | /aguinaldo/Datos.py | 1,615 | 4.125 | 4 | def Datos():
"""Función para solicitar los datos del usuario"""
print("""-----------------------------------------------------------------------------------------------------------
| CALCULADORA DE AGUINALDO |
-----------------------------------------------------------------------------------------------------------\n""")
nombre = input("Ingrese su nombre completo: ")
#----DUI----
dui = input("Ingrese su número de DUI (SIN GUIONES): ")
#Verifica que el DUI tenga una longitud válida
while(len(dui) != 9):
print("¡El número de DUI no es válido!")
dui = input("Ingrese nuevamente su número de DUI (SIN GUIONES): ")
#Lambda que nos permite dar formato al número del DUI
dui_real = lambda dui: dui[:-1] + "-" + dui[-1]
#----NIT----
nit = input("Ingrese su número de NIT (SIN GUIONES): ")
#Verifica que el NIT tenga una longitud válida
while(len(nit) != 14):
print("¡El número de NIT no es válido!")
nit = input("Ingrese nuevamente su número de NIT (SIN GUIONES): ")
#Lambda que nos permite dar formato al número del NIT
nit_real = lambda nit: nit[:4] + "-" + nit[4:10] + "-" + nit[10:13] + "-" + nit[-1] #lambda que nos permite dar formato al número del NIT
salario = float(input("Ingrese su sueldo: $"))
tiempo = int(input("Ingrese el número de meses trabajados: "))
return nombre, dui, dui_real, nit, nit_real, salario, tiempo #Devuelve las variables a utilizar
| false |
a452d18e79c15e6563ebffe6b5b6ce8d492d1916 | vivekdhayaal/first-repo | /aoi/algorithms_data_structures/tree_path_bet_two_nodes.py | 2,559 | 4.125 | 4 | # Python Program to find path between
# n1 and n2 using tree DFS
class Node:
def __init__(self, data, children = []):
self.data = data
self.children = children
def pathToNode(node, path, data):
# base case handling
if node is None:
return False
# append the node data in path
path.append(node.data)
# See if the data is same as node's data
if node.data == data:
return True
# Check if data is found in children
for child in node.children:
if pathToNode(child, path, data):
return True
# If not present in children under node,
# remove node data from path and return False
path.pop()
return False
def distance(root, data1, data2):
if root:
# store path corresponding to node: data1
path1 = []
pathToNode(root, path1, data1)
# store path corresponding to node: data2
path2 = []
pathToNode(root, path2, data2)
# iterate through the paths to find the
# common ancestor
i=0
while i<len(path1) and i<len(path2):
# get out as soon as the path differs
# or any path's length get exhausted
if path1[i] != path2[i]:
break
i = i+1
# get the path by deducting the
# intersecting path (or till LCA)
#print "source", data1
parents = path1[i-1:]
parents.reverse()
#print "source's parents", parents
#print "LCA", path2[i-1]
children = path2[i:]
#print "LCA's children", children
#print "destination", data2
return parents + children
else:
return 0
# Driver Code to test above functions
root = Node(1)
rootleft = Node(2)
rootright = Node(3)
root.children = [rootleft, rootright]
rootleftleft = Node(4)
rootrightright= Node(7)
rootrightleft = Node(6)
rootleftright = Node(5)
rootleft.children = [rootleftleft, rootleftright]
rootright.children = [rootrightleft, rootrightright]
rootrightleftright = Node(8)
rootrightleft.children = [rootrightleftright]
dist = distance(root, 4, 5)
print "Path between node {} & {}: {}".format(4, 5, dist)
dist = distance(root, 4, 6)
print "Path between node {} & {}: {}".format(4, 6, dist)
dist = distance(root, 3, 4)
print "Path between node {} & {}: {}".format(3, 4, dist)
dist = distance(root, 2, 4)
print "Path between node {} & {}: {}".format(2, 4, dist)
dist = distance(root, 8, 5)
print "Path between node {} & {}: {}".format(8, 5, dist)
| true |
7358416e2208e2fd60c0f28edfb08070c63971a1 | dalq/python-cookbook | /cookbook/one/6MultiValueMap.py | 383 | 4.125 | 4 | # 字典中讲键映射到多个值上
# 思路,讲value设置为集合(List、Set)
# 如果希望消除重复元素 - Set
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(3)
print(d.get('a'))
# 如果不希望在初始化时自动创建字典表项,可以使用setdefault
# 我的理解应该是先不new出这个对象 | false |
3fbca9ac670c4f2c099f13632cb4ec4e582828fb | AlexxanderShnaider/AcademyPythonLabs | /2.brocks_formula.py | 1,025 | 4.28125 | 4 | # TODO:
# Идеальный вес для мужчин: (рост в сантиметрах - 100) *1.15
# Идеальный вес для женщин: (рост в сантиметрах - 110) *1.15
# Пользователь должен ввести свое имя, рост и вес. Затем программа должна выдать сообщение:
# "Имя ваш идеальный вес – значение".
name = input("Enter your name: ")
# Так як не можна відняти та помножити тип str ми перетворили str на int
height = int(input("Enter your height in cm: "))
gender = input("Enter your gender: ")
coefficient = 1.15
gender_number_value = 0;
if gender == "Male":
gender_number_value = 100
elif gender == "Female":
gender_number_value = 110
else:
print("Wrong gender enter!")
if gender_number_value != 0:
ideal_weight = (height - gender_number_value) * coefficient
print(f"{name}, your ideal weight is - {ideal_weight}.")
| false |
afb38416d9deadd585772a19edddbad676afc7e8 | ChuChuIgbokwe/Python-2.7-code | /alice_words.py | 1,522 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Chukwunyere Igbokwe on March 15, 2016 by 3:11 AM
# with open('alice_in_wonderland.txt', 'r') as f:
# data = [aline.split() for aline in f]
import string
def remove_punctuation(s):
s_without_punct = ""
for letter in s:
if letter not in string.punctuation:
s_without_punct += letter
return s_without_punct
def alice_words():
'''
Write a program called alice_words.py that creates a text file named
alice_words.txt containing an alphabetical listing of all the words,
and the number of times each occurs, in the text version of Alice’s
Adventures in Wonderland.
:return:
'''
with open("alice_in_wonderland.txt", "r") as f:
aline = f.read()
aline = aline.lower()
aline_dict = dict()
items = aline.split()
for i in items:
i = remove_punctuation(i)
count = aline.count(i)
aline_dict[i] = count
# remove spaces
aline_dict.pop('',None)
#sort keys in alphabetical order
keys = aline_dict.keys()
keys.sort()
out = open ("alice_word_count.txt","w")
# for word in keys:
# out.write(word + " " + str(aline_dict[word]))
# out.write('\n')
words = []
for (k,v) in sorted(aline_dict.items()):
# print k, v
words.append(v)
# Get key by value in dictionary
mode = aline_dict.keys()[aline_dict.values().index(max(words))]
print "The word 'Alice' appears ",aline_dict['alice'], "times in this book"
print "the longest word in Alice in Wonderland is",mode, "it has",max(words), "characters"
alice_words() | true |
5e9477a10f6edced28db4ea7f5eda9ad44381e39 | ChuChuIgbokwe/Python-2.7-code | /fibonacci.py | 268 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Created by Chukwunyere Igbokwe on January 27, 2016 by 2:43 PM
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
#n = int(input('Enter a number: '))
print fibonacci(7)
| false |
209d9a593a6a5c8effcef7031c5c4092ba19384c | ChuChuIgbokwe/Python-2.7-code | /dispatch.py | 2,392 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Created by Chukwunyere Igbokwe on September 27, 2016 by 10:29 PM
## Function to find the maximum contiguous subarray
# def maxSubArraySum(a,size):
#
# max_so_far = 0
# max_ending_here = 0
#
# for i in range(0, size):
# max_ending_here = max_ending_here + a[i]
# if max_ending_here < 0:
# max_ending_here = 0
#
# if (max_so_far < max_ending_here):
# max_so_far = max_ending_here
#
# return max_so_far
# Your previous Plain Text content is preserved below:
#
# Definition:
# * A subarray of an array [x0, x1, x2....] is any contiguous part of an array.
#
# Examples:
# * [x0, x1, x2] is a subarray of [x0, x1, x2, x3], but [x0, x2] is not.
# * [] is a subarray of any array
# * An array is a subarray of itself
#
# Goal:
# Write a function that takes as input an array of numbers, and returns the subarray that has the maximum sum.
#
# Examples:
#
# Input: []
# Output: []
#
# Input: [-4]
# Output: []
#
# Input: [1, -3, 1, 4]
# Output: [1, 4]
#
# Input: [12, -5, 6, -7, 18, 20]
# Output: [12, -5, 6, -7, 18, 20]
#
#
#
#
#
def MaxSubArray(array):
initial_max = 0
max_so_far = 0
sub_array = []
for i in range(len(array)):
max_so_far = array[i]
if max_so_far < 0:
initial_max = 0
else:
sub_array.append(array[i])
return sub_array
print MaxSubArray([12, -5, 6, -7, 18, 20])
# def get_max_sum_subset(x):
# bestSoFar = 0
# bestNow = 0
# bestStartIndexSoFar = -1
# bestStopIndexSoFar = -1
# bestStartIndexNow = -1
# for i in xrange(len(x)):
# value = bestNow + x[i]
# if value > 0:
# if bestNow == 0:
# bestStartIndexNow = i
# bestNow = value
# else:
# bestNow = 0
#
# if bestNow > bestSoFar:
# bestSoFar = bestNow
# bestStopIndexSoFar = i
# bestStartIndexSoFar = bestStartIndexNow
#
# return bestSoFar, bestStartIndexSoFar, bestStopIndexSoFar
# def mssl(l):
# best = cur = 0
# curi = starti = besti = 0
# for ind, i in enumerate(l):
# if cur+i > 0:
# cur += i
# else: # reset start position
# cur, curi = 0, ind+1
#
# if cur > best:
# starti, besti, best = curi, ind+1, cur
# return starti, besti, best | true |
9c29c52024229f7593f3f96946935099f224a06f | weiyangedward/Design-of-Computer-Programs | /exam/LogicPuzzle.py | 2,971 | 4.1875 | 4 | """
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid, one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knuth nor the person who bought the tablet is the manager.
6. Knuth arrived the day after Simon.
7. The person who arrived on Thursday is not the designer.
8. The person who arrived on Friday didn't buy the tablet.
9. The designer didn't buy the droid.
10. Knuth arrived the day after the manager.
11. Of the person who bought the laptop and Wilkes, one arrived on Monday and the other is the writer.
12. Either the person who bought the iphone or the person who bought the tablet arrived on Tuesday.
You will write the function logic_puzzle(), which should return a list of the
names of the people in the order in which they arrive. For example, if they
happen to arrive in alphabetical order, Hamming on Monday, Knuth on Tuesday, etc.,
then you would return:
['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
(You can assume that the days mentioned are all in the same week.)
"""
import itertools
def logic_puzzle():
"Return a list of the names of the people, in the order they arrive."
## your code here; you are free to define additional functions if needed
days = mon, tue, wed, thur, fri = [1,2,3,4,5]
orders = list(itertools.permutations(days))
res = next([Hamming, Knuth, Minsky, Simon, Wilkes]
for (laptop, droid, tablet, iphone, _) in orders
if wed == laptop # 1
if fri != tablet # 8
if iphone == tue or tablet == tue # 12
for (Hamming, Knuth, Minsky, Simon, Wilkes) in orders
if Knuth == Simon + 1 # 6
for (programmer, writer, designer, manager, _) in orders
if thur != designer # 7
if Knuth != manager and tablet != manager # 5
if designer != droid # 9
if set([laptop, Wilkes]) == set([writer, mon]) # 11
if programmer != Wilkes # 2
if set([programmer, droid]) == set([Wilkes, Hamming]) # 3
if Knuth == manager + 1 # 10
if writer != Minsky # 4
)
names = ['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
ordernames = dict((d, n) for (d,n) in zip(*(res, names)))
return [ordernames[d] for d in range(1,6)]
print logic_puzzle()
| true |
e91ea7762174e58fe59d7c5a54a79e02bf052257 | Ronin11/Python | /3/zhuLiDoTheThing.py | 634 | 4.15625 | 4 | import random
def modPow(num, pow, mod):
i = 1;
for i in range(1, pow):
i *= num
i %= mod
return i % mod
def isPrime(num, iterations):
if(num == 1 or num == 0):#0 and 1 are defined to be not prime
return str(num)+" is not prime"
elif(num == 2):#2 is prime
return str(num)+" is prime"
elif(num % 2 == 0):#Anything divisible by 2 is obviously not prime
return str(num)+" is not prime"
random.seed()
for i in range(1, iterations):
rand = random.randrange(1,num-1,1)
num2 = rand % (num - 1) +1
if(modPow(num2, num-1,num) == 1):
return str(num)+" is probably prime"
else:
return str(num)+" is not prime"
| false |
eadcc15fe383c94ac3b4539d3de691e2f55a014f | iskibinska/Python-Class | /python1/lesson4/guess.py | 477 | 4.15625 | 4 | count = 1
secret = 18
num = int(input("\nGuess a number between 1 and 20: "))
while True:
if (num == secret or count == 5):
break
elif (num > secret):
num = int(input("It was too high. Guess again: "))
elif (num < secret):
num = int(input("It was too low. Guess again: "))
count += 1
if (num == secret):
print("You guessed right with " + str(count) + " guesses!")
elif (count == 5):
print("You guessed more than five times.")
| true |
7f467cb87066f217c42608111486bc1e41158454 | chaudharyishan/PythonGame | /GuessGame.py | 2,579 | 4.21875 | 4 | import random
print("\t\t\tWelcome to Guess- The Number Game")
print("\n")
print("\tRules: You have to guess the number which I am thinking out,\n\tI will give you a hint wheather the guess number is too HIGH,LOWER \n\tto thenumber which I have guessed")
print("\n\tScore Card: 1st Attempt= 50 Points")
print("\t\t 2nd Attempt= 40 Points")
print("\t\t 3rd Attempt= 30 Points")
print("\t\t 4th Attempt= 20 Points")
print("\t\t 5th Attempt= 10 Points")
print("\n\n")
guessNumber=random.randrange(10)+1;
attempt=0
score=50
userNumber=int(input("Enter the Number which Computer has Guessed between 1-10"))
while attempt<5:
if userNumber==111:
input("\nPress Enter to Exit")
break
else:
if userNumber>guessNumber:
if attempt<4:
print("\tYour Number is HIGHER, Try Again with Lower Number")
userNumber=int(input("\nEnter the Number which Computer has Guessed between 1-10"))
attempt+=1
score-=10
else:
print("\tYour Number is HIGHER")
print("\n\t\tYou Loose the Game:(")
print("\t\tYour Score is 0")
print("\tHard Luck!, Nevermind better luck next time.")
print("\n\t\t\tRemember!")
print("You have lost Game not Life, so don't GIVE UP Try until successed")
attempt=0
score=50
print("When Tired, Simply Enter Number 111 to Exit the Game")
userNumber=int(input("\nEnter the Number which Computer has Guessed between 1-10"))
elif userNumber<guessNumber:
if attempt<4:
print("\tYour Number is LOWERER, Try Again with HIGH Number")
userNumber=int(input("\nEnter the Number which Computer has Guessed between 1-10"))
attempt+=1
score-=10
else:
print("\tLower")
print("\n\t\tYou Loose the Game:(")
print("\t\tYour Score is 0")
print("\tHard Luck!, Nevermind better luck next time.")
print("\n\t\t\tRemember!")
print("You have lost Game not Life, so don't GIVE UP Try until successed")
attempt=0
score=50
print("When Tired, Simply Enter Number 111 to Exit the Game")
userNumber=int(input("\nEnter the Number which Computer has Guessed between 1-10"))
else:
print("\n\t\tCongrats, You Guessed!")
print("\t\tYour Score is ", score)
print("\n\tThanks for Playing, Hope you have a Nice Day")
break
input("\nPress Enter to Exit")
| true |
b4186ab9231f011505719051a7bea461701c62bd | moyea/algorithm-study | /quick-sort.py | 936 | 4.21875 | 4 | #!/usr/bin/python
# coding: utf-8
"""
@desc:快速排序
@version: ??
@author: Qinghua
@contact: muyea@hotmail.com
@file: quick-sort.py
@time: 2017/11/8 11:37
"""
"""
快速排序原理
1)基线条件:数组长度为0或1时,该数组不需要排序
2)如何缩小问题的规模:从数组中取出一个基准值,
将剩余值拆分为一个小于基准值得数组和一个大于基准值得数组,
对于拆分的数组继续拆分,直至满足基线条件
最后小于基准值得数组,基准值,大于基准值合并为一个数组
"""
def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
left = [i for i in arr[1:] if i <= pivot]
right = [i for i in arr[1:] if i > pivot]
print 'left:=>', left, 'pivot:=>', pivot, 'right:=>', right
return quickSort(left) + [pivot] + quickSort(right)
if __name__ == '__main__':
print quickSort([10, 8, 4, 3])
| false |
b8e228996ad5030ef7b455769733e1af4f48661c | PythonCore051020/HW | /HW04/AndriyKapelian/Task_1.py | 515 | 4.1875 | 4 | # function that can transform a number into a string
def number_to_string(num):
transformed_num = str(num)
return transformed_num
# function that reverses the words in a given string
def reverse(st):
# Your Code Here
words = st.split()
words = list(reversed(words))
reversed_string = " ".join(words)
return reversed_string
# fixing Jenny's function
def greet(name):
if name == "Johnny":
return "Hello, my love!"
else:
return "Hello, {name}!".format(name=name) | true |
b0ef182023e47f753991c83199f49d0a3f29d1a9 | mahekdeep/DiceRole | /main.py | 760 | 4.28125 | 4 | #DiceRole
import random
#Setting Input Variables
min = 1
max = 6
#Setting Dices at Ints
dice1 = 0
dice2 = 0
#Using "Y or N" to incidcate if user wants to role again.
roll = "y"
#Asking Users Input for role
print("Would you like to Roll the Dice? ")
roll =input("Please Type y/n: ")
while roll == "y":
print("Rolling the dice...")
dice1 = random.randint(min,max)
dice2 = random.randint(min,max)
print("The values are ", dice1,", ",dice2)
#print(dice1,dice2)
#Asking if the user wants to role the dice again.
roll_again = input("Roll It again?: ")
if roll_again == 'n':
break
if roll_again != 'n' and roll_again != 'y' :
print("Error: Not Acceptable Input Value (y/n). Please try run the code again.")
break
| true |
5eb41bc76833a07bfc27749f767e98d3601b9306 | gourav3017/code-samples | /tasks/primes.py | 1,348 | 4.375 | 4 | #!/usr/bin/env python
from math import sqrt, ceil
"""
Write a program that accepts two integer parameters, X and Y. Have it print all prime numbers between X and Y, inclusive.
"""
def isPrime(n):
"""
Basically the quick test for whether or not a prime
Arguments:
n - an int
Returns:
A boolean of True or false
"""
#0 and 1 are special cases.
if n == 0 or n == 1 or type(n) is not int: return False
for num in xrange(2, int(ceil(sqrt(n)))):
if n % num == 0:
return False
return True
def primes(x, y):
"""
Takes 2 integers and gives you back all the prime
numbers inclusive
Arguments:
x - a positive integer
y - a positive integer
"""
if type(x) is not int or type(y) is not int:
print "All values need to be ints"
return
if x < 0 or y < 0:
print "All values must be non-negative"
return
for val in xrange(x, y+1):
if isPrime(val):
print val
#Regular Ints
primes(0,101)
#Doesn't accept strings
primes(0, 's')
#Doesn't accept Negatives
primes(-1, 10)
primes(10, -1)
#This is a slightly more fun way to pull out the primes and force em in a list
#You need to make sure that you add 1 to the end since xrange goes up to n-1
print filter(isPrime, xrange(0,102))
| true |
d88c1c29fbe31eb04c80fd28265f3178abab60a5 | LeoneVeneroni/python | /exercicios/Aula9/aula9_exercicio4.py | 459 | 4.15625 | 4 | class Ponto:
""" Cria um novo Ponto, com coordenadas x, y """
def __init__(self, x=0, y=0):
""" Inicializa em x, y o novo ponto criado pela classe """
self.x = x
self.y = y
def parametros_reta(self, t):
""" Calcula o coeficiente angular e linear """
a = (self.y - t.y) / (self.x - t.x)
return a, self.y - a*self.x
p = Ponto(4, 11)
print(Ponto(4, 11).parametros_reta(Ponto(6, 15)))
| false |
92c7f7cef33764a1eb52939df7f5e64cc287f8b3 | jeanmicoliveira/Python | /Atividade03_PPSI/Exercício4.py | 489 | 4.1875 | 4 | """
Faça um programa que leia dois números e mostre qual o maior dos dois. O programa deve informar caso sejam iguais.
"""
print('Escolha somente números inteiros.')
n1 = int(input('Informe um número: '))
n2 = int(input('Informe outro número: '))
if n1 == n2:
print('Os números selecionados são iguais.')
if n1 > n2:
print('O primeiro número digitado é maior que o segundo número.')
if n1 < n2:
print('O Segundo número é maior que o primeiro número digitado.')
| false |
fb83c4f3c7b2bf05d334f2fc25567110391ded14 | stanardmp/HundName | /HundName_Betterversion.py | 2,835 | 4.15625 | 4 |
# Load the data
import pandas as pd
data = pd.read_csv("20210103_hundenamen.csv")
# 0. Convert all the hundname to lower case
HundName_list = HundName_list = [data['HUNDENAME'][i].lower() for i in range(len(data))]
# 1. Select all the names form the hundname list that have same len as 'Luca' or 'len(luca) +1 or len(luca)-1
def name_luca_len(list_names, name_target):
"""
elect all the names form the hundname list that have same len( name_target) or len( name_target) +1 or len( name_target)-1
list_names is a list of hund's names
name_target is the target name of the dog a string
"""
same_len = [list_names[i] for i in range(len(list_names)) if len(list_names[i]) == len(name_target)]
len_plus1 = [list_names[i] for i in range(len(list_names)) if len(list_names[i]) == len(name_target) + 1 ]
len_minus1 = [list_names[i] for i in range(len(list_names)) if len(list_names[i]) == len(name_target) -1]
All_list = same_len + len_plus1 + len_minus1
# 2. Remove duplicates name from the list
unique_names = list(set(All_list))
return unique_names
# 3. Select all the names that have at least 3 identical letters found in the target name
def identical_letters(name_target, check_names):
""" Keep only the names that have at least (len(name) - 1) identical letters in them
name_target is the target named
check_names is the list of name we want to chek
"""
collect1 = list()
for n1 in n:
count = 0
for c1, c2 in zip(n1,name_target): # check with letter correct position
if c1 == c2:
count = count + 1
# print(count)
if count == len(name_target) - 1:
# print('keep those names')
collect1.append(n1)
return collect1
# 4. Select all names from the initial list that have name_target in them
# (from which we can delete some letters to have our targeted name).
def deletion_part(list_names, name_target):
"""
Select all names from the initial list that have 'name_target' in them
list_names is the initial list of names
name_target is the targeted name of hund
"""
deletion = []
for i in list_names:
f = name_target in i
if f ==True:
deletion.append(i)
return deletion
# put all together and see
name_target = 'luca' # This canbe changed to any name
unique = name_luca_len(HundName_list, name_target)
identic = identical_letters(name_target, unique)
deletion = deletion_part(HundName_list, name_target)
List_final = deletion + identic
# Remove again duplicates name from the list
List_final = list(set(List_final))
print(List_final, len(List_final))
# Finally, we have a list of hund name that 1 Levenshtein distance away from 'Luca'.
| false |
c210369911fe124ded804f7fee295fb5df3e2663 | skeptycal/algo | /snippets/python/prime_sieve.py | 1,529 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# # Prime Number Sieve
# http://inventwithpython.com/hacking (BSD Licensed)
# https://inventwithpython.com/hacking/chapter23.html
import math
from typing import Tuple, List
def isPrime(num):
""" # Returns True if num is a prime number, otherwise False.
# Note: Generally, isPrime() is slower than primeSieve().
# all numbers less than 2 are not prime """
if num < 2:
return False
# see if num is divisible by any number up to the square root of num
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def primeSieve(sieveSize: int = 10000) -> List[int]:
# Returns a list of prime numbers calculated using
# the Sieve of Eratosthenes algorithm.
sieve = [True] * sieveSize
sieve[0] = False # zero and one are not prime numbers
sieve[1] = False
# create the sieve
# for i in range(2, int(math.sqrt(sieveSize)) + 1):
# pointer = i * 2
# while pointer < sieveSize:
# sieve[pointer] = False
# pointer += i
r: int = int(math.sqrt(sieveSize)) + 1
sieve.extend([i * 2 for i in range(2, r)])
# compile the list of primes
primes = []
primes.extend([i for i in range(sieveSize) if sieve[i]])
return primes
if __name__ == "__main__":
size: int = 1000
prime_list: List[int] = primeSieve(size)
print(prime_list)
print('Largest prime below {} is {}.'.format(size, prime_list[-1]))
| true |
76f4849af5912fe34e19f96fab4e722f3a48f098 | PedroLSF/PyhtonPydawan | /3 -LIST/3.1_IntroLisExample.py | 1,045 | 4.40625 | 4 | ################ Example_1 Method
#method .append() inserts an element on the last position
append_example = [ 'This', 'is', 'an', 'example']
append_example.append('list')
print(append_example)
#.remove tira o ultimo
example_list = [1, 2, 3, 4]
#Using Append
example_list.append(0)
print(example_list)
#Using Remove
example_list.remove(0)
print(example_list)
################### .remove tira elementos de algo
##.remove nao trabalha com posição
################### Lista 2D
class_name_test =[["Jenny",90],["Alexus",85.5],["Sam",83],["Ellie",101.5]]
print(class_name_test)
sams_score = class_name_test[2][1]
print(sams_score)
ellies_score = class_name_test[-1][-1]
print(ellies_score)
#ex2
#negative index a partir de -1
#positive index a partir de 0
incoming_class = [["Kenny", "American", 9], ["Tanya", "Russian", 9], ["Madison", "Indian", 7]]
incoming_class[2][2] = 8
incoming_class[-3][-3] = "Ken"
print(incoming_class)
#.reshape redimensiona o vetor para ourtra dimensao
#o proprio usuario coloca a propria dimensao
| false |
c75993571a65502d628a498cf95f81f676d8767c | PedroLSF/PyhtonPydawan | /6b - CHALLENGE ADV/6.4.2_Tip.py | 492 | 4.34375 | 4 | # Let’s say we are going to a restaurant and we decide to leave a tip.
# We can create a function to easily calculate the amount to tip based on the total cost of the food and a percentage.
# This function will accept both of those values as inputs and return the amount of money to tip.
def tip(total, percentage):
return (total*percentage)/100
# Uncomment these function calls to test your tip function:
print(tip(10, 25))
# should print 2.5
print(tip(0, 100))
# should print 0.0 | true |
ba0912e0ad5371abb3e4affd7c6255dd52abc1cf | PedroLSF/PyhtonPydawan | /6a - CHALLENGE_Basic/6.3.5_Exponents.py | 498 | 4.46875 | 4 | #In this challenge, we will be using nested loops in order to raise a list of numbers to the power of a list of other numbers.
#What this means is that for every number in the first list, we will raise that number to the power of every number in the second list.
def exponents(bases,powers):
new_lst = []
for base in bases:
for power in powers:
new_lst.append(base**power)
return new_lst
#Uncomment the line below when your function is done
print(exponents([2, 3, 4], [1, 2, 3])) | true |
6042920d1d5d685e7fd94a09699c52260cebbac1 | PedroLSF/PyhtonPydawan | /6b - CHALLENGE ADV/6.3.1_LargerSum.py | 485 | 4.21875 | 4 | #calculating which list of two inputs has the larger sum.
#We will iterate through each of the list and calculate the sums
#afterwards we will compare the two and return which one has a greater sum
def larger_sum(lst1, lst2):
sum1 =0
sum2 =0
for index1 in lst1:
sum1 += index1
for index2 in lst2:
sum2 += index2
if sum1 >= sum2:
return lst1
else:
return lst2
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7])) | true |
9e7aff80dbdfb9463101beca436bc975bcc86d02 | Preksha1998/python | /functions/decorators.py | 405 | 4.1875 | 4 | # decorators is used to add the extra features in the existing function
#create fun which take argument as function and inner function and inner function can swap value for that function
def division(a,b):
print(a/b)
def smart_div(func):#take function as argument
def inner_fun(a,b):# same as division
if a < b:
a,b = b,a
return func(a,b)
return inner_fun
div = smart_div(division)
div(2,4)
| true |
fc4a69af6fed5242388dcbf97bb7403b7ef72e02 | MehmetSadik/Python | /assignment_4.py | 236 | 4.125 | 4 | num = int(input("Please enter a positive number(except one): "))
i = 2
while (i <= num) and (num % i != 0):
i += 1
if num == i:
print("{} is a prime number.".format(num))
else:
print("{} is not a prime number.".format(num))
| false |
83c3929e7f45a6b3aedadb8ce43e5de5247a5807 | Gabriel-Ravena/Practicas-Python | /listas/listas.py | 1,633 | 4.3125 | 4 | nombres = ["Gabriel", "Lorena", "Juan", "Beto"]
print(nombres)
#largo de la lista
print("elementos de la lista: ", len(nombres))
#Elementos por numero
print(nombres[0])
print(nombres[1])
print(nombres[2])
print(nombres[3])
#Elementos en una sola linea
print(nombres[0], nombres[1], nombres[2], nombres[3])
#Elementos por indice negativo
print(nombres[-1])
print(nombres[-2])
print(nombres[-3])
print(nombres[-4])
#Elementos en una sola linea llamados por indice negativo
print(nombres[-1], nombres[-2], nombres[-3], nombres[-4])
#Imprimir por rango
print(nombres[0:2])
print(nombres[:3])
print(nombres[1:])
#Cambiar elementos de una lista
nombres[3] = "Ifran"
print(nombres)
#Recorrer elementos con ciclo for
for nombre in nombres:
print(nombre)
#Revisar si elemento existe en la lista
if "Gabriel" in nombres:
print("Gabriel si existe en la lista")
else:
print("Gabriel no existe en la lista")
#Agregar nuevo elemento en la lista
nombres.append("Silvina")
print(nombres)
#Agregar elemento nuevo a la lista en un indice especifico
nombres.insert(2, "Alvaro")
print(nombres)
#Eliminar elemento de la lista
nombres.remove("Alvaro")
nombres.remove("Juan")
print(nombres)
#Eliminar ultimo elemento de la lista
nombres.pop()
print(nombres)
#Remover indice indicado de la lista
del nombres[0]
print(nombres)
#Limpiar todos los elementos de la lista
nombres.insert(1, "Gabriel")
nombres.append("Mariana")
nombres.append("Christian")
nombres.append("Facundo")
nombres.append("Rocio")
print(nombres)
nombres.clear()
print(nombres)
#Eliminar variable(Tira error al no encontrar la variable definida)
del nombres
print(nombres)
| false |
9749fc3e081e500d94552438417c80d8ac07baa6 | yuju13488/pyworkspace | /Homework/if_else/if_else3.py | 1,387 | 4.1875 | 4 | #3.選擇性敘述的練習-electricity
#輸入何種用電和度數,計算出需繳之電費。
#電力公司使用累計方式來計算電費,分工業用電及家庭用電。
# 家庭用電 工業用電
#240度(含)以下 0.15元 0.45元
#240~540(含)度 0.25元 0.45元
#540度以上 0.45元 0.45元
elect=input('What kind of electricity, \'home\' or \'industry\':')
kwh=eval(input('Please input kilowatt hour for uesd:'))
if elect == 'industry':
print('Electricity fee is',kwh*0.45)
elif elect == 'home':
if kwh <= 240:
print('Electricity fee is', kwh*0.15)
elif 240 < kwh <= 540:
print('Electricity fee is', 240*0.15+(kwh-240)*0.25)
elif 540 < kwh:
print('Electricity fee is', 240*0.15+300*0.25+(kwh-540)*0.45)
else:
print('輸入錯誤')
# if kwh <= 240 and elect == 'home':
# print('Electricity fee is',kwh*0.15)
# if kwh <= 240 and elect == 'industry':
# print('Electricity fee is',kwh*0.45)
# if 240 < kwh <= 540 and elect == 'home':
# print('Electricity fee is',240*0.15+(kwh-240)*0.25)
# if 240 < kwh <= 540 and elect == 'industry':
# print('Electricity fee is',kwh*0.45)
# if 540 < kwh and elect == 'home':
# print('Electricity fee is',240*0.15+300*0.25+(kwh-540)*0.45)
# if 540 < kwh and elect == 'industry':
# print('Electricity fee is',kwh*0.45) | false |
bf834b79c46c003e1c13868b6d05271793ccf92e | yuju13488/pyworkspace | /m3/input.py | 444 | 4.125 | 4 | #input輸入的資料為字串
x=input('please input x:')
print(x*3) #字串*3
y=int(input('please input y:')) #將字串轉為數字(僅限單一值)
print(y+3)
print("--------------------")
n1,n2=eval(input('please input n1,n2:')) #eval可處理兩個以上數值,但無法處理字串
print(n1/n2)
str1,str2=eval(input('please input str1,str2:')) #輸入字串時須加單(雙)引號
print(str1+str2)
print("--------------------") | false |
bce0752294a408b97b2969b87932a9e1788b5785 | guido-lab/random-password-generator | /password-generator.py | 1,805 | 4.125 | 4 | import random
import string
class RandPasswordGenerator():
def generate_password(self, lenght, wantNums, wantUppers):
password = ""
chars = string.ascii_letters
# Checking if the user want to include numbers to his password
if wantNums.lower() == "yes":
chars = chars + "1234567890"
elif wantNums.lower() == "no":
pass
else:
return "Invalid input at 'wantNums' input, please enter 'yes' or 'no'! "
# Generating Random password uging random function
for i in range(lenght):
password = password + random.choice(chars)
# Checking if the user want to include upercase chars to his password
if wantUppers.lower() == "yes":
return "Password: " + password
elif wantUppers.lower() == "no":
return "Password: " + password.lower()
else:
return "Invalid input at 'wantUppers' input, please enter 'yes' or 'no'! "
def rigenerate_password(self):
working = True
while working == True:
# inputing params
lenght = int(input("How long do you want the password to be? [in numbers] "))
wantNums = input("Do you want numbers in the password? [yes/no] ")
wantUppers = input("Do you want uppercase letters? [yes/no] ")
gen_pass = self.generate_password(lenght, wantNums, wantUppers)
print(gen_pass)
restart = input("Do you want another password? [yes/no] ")
if restart.lower() == "yes":
working = True
else:
print("Password Generator is shuting down!")
working = False
if __name__ == "__main__":
RandPasswordGenerator().rigenerate_password()
| true |
09d786a57b572c5d43409bee920ae49645622ee2 | RitchieHollis/Python-projects | /Guessing-number game.py | 1,901 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Number guessing game
Author: RitchieHollis
game not finished, works in overall
"""
import random
def loop():
score = 0
random_number = int(random.randint(1,10))
while n == True:
num_pers = input("Choose a number between 1 and 10: ")
if int(num_pers) < 0 or int(num_pers) > 10:
print("You must choose a number between 1 ad 10")
loop()
"""if type(num_pers) != int:
print("Musisz podac liczbe")
loop()"""
if int(num_pers) == random_number:
score = score + 1
print ("Good!")
print("After: ",score,"trials")
choice2 = input("Wanna play again? (Yes/No): ")
if choice2.lower() == 'yes':
loop()
elif choice2.lower() == 'no':
print("Okay, goodbye :-D")
n = False
input()
loop()
elif int(num_pers) > random_number:
print("Nope, it's lower")
score = score + 1
elif int(num_pers) < random_number:
print("Nope, it's higher")
score = score + 1
def main_game():
player_name = input("Hi, what's your name?: ")
choice = input("Hey {}, do you want to play a game? (Yes/No) ".format(player_name))
if choice.lower() == "yes":
loop()
elif choice.lower() == "no":
print("Okay, goodbye :-D")
input()
return
# The following makes this program start running at main_game()
# when executed as a stand-alone program.
if __name__ == '__main__':
main_game()
| true |
f2ee335b0e6c871b8d7691de9c43124596187699 | jpaltahona/iniciado-python | /conditional.py | 281 | 4.21875 | 4 | first_name ="jua"
last_nae = "pierr"
if first_name == "jean":
if last_nae == "pierre":
print('you are jean pierre')
else:
print('you are not jean pierre')
else:
print('tu no eres nadie')
x = 2
if x > 3 and x < 2:
print('x es mayor que 3 y menor que 2') | false |
77362cee3b8da0be4c9deb2de4e2101aa167dfac | LayanCS/LeetCode | /Algorithms/Reverse_Integer.py | 605 | 4.15625 | 4 | # Reverse Integer - Given a 32-bit signed integer, reverse digits of an integer.
# Input: 123 Output: 321
# Input: -123 Output: -321
class Solution:
def reverse(self, x: int) -> int:
if x >= 2**31-1 or x <= -2**31:
return 0
else:
s = str(x)
if x >= 0: # positive
reverse = int(s[::-1])
else:
reverse = -int(str(abs(x))[::-1])
if reverse >= 2**31-1 or reverse <= -2**31:
return 0
else:
return reverse
# You can use also use: Reverse.bit_length() < 32
| true |
b218395e7f738bc45386810128ae33b599531400 | KathrynDH/MyMatrix | /examples.py | 1,345 | 4.40625 | 4 | """
Created on Wed Jun 16 2021
@author: Kathryn Haske
Example usage for MatrixMath Python class
"""
from matrix_math import MatrixMath
def demonstrate(a):
"""
Function to demonstrate some of the MatrixMath methods
Args:
a (MatrixMath): Matrix
Returns:
nothing
"""
print('Matrix:')
a.print_matrix()
try:
print('\nDeterminant: {}'.format(a.determinant()))
except:
print('\nMatrix does not have a determinant')
print('\nMatrix transpose:')
a.transpose().print_matrix()
try:
print('\nMatrix inverse:')
a.inverse().print_matrix()
except:
print('Matrix does not have an inverse')
print('\n')
# Create some matrices as MatrixMath objects
a = MatrixMath([[1,0, 0],[0, 1, 0],[0,0,1]])
b = MatrixMath([[1,2, 3],[4,5, 6]])
c = MatrixMath([[5,2, 3, 10],[4,5, 6, 11],[7,8,9, 12],[13,14,15,20]])
d = MatrixMath([[1,2],[3,4]])
f = MatrixMath([[1+2j,2+5j],[3,4-2j]])
matrices = {'A':a, 'B':b, 'C':c, 'D':d, 'F':f}
for n, m in matrices.items():
print('Matrix {}'.format(n))
demonstrate(m)
print('d + f')
(d + f).print_matrix()
print('\nd - f')
(d - f).print_matrix()
print('\nd * f')
(d * f).print_matrix()
print('\n3 * d')
(3 * d).print_matrix()
print('\n1-2j * f')
((1-2j) * f).print_matrix()
print('\nf * f inverse')
(f * f**-1).print_matrix()
| true |
192d930858c70886a845b1afd8565bee135eb5cf | ashirsh/PY111_work | /Tasks/g1_merge_sort.py | 1,000 | 4.15625 | 4 | from typing import List
def sort(container: List[int]) -> List[int]:
"""
Sort input _list with merge sort
:param container: _list of elements to be sorted
:return: _list sorted in ascending order
"""
def merge(left_part, right_part):
result = []
while left_part or right_part:
if not left_part:
result.extend(right_part)
right_part.clear()
elif not right_part:
result.extend(left_part)
left_part.clear()
elif left_part[0] <= right_part[0]:
result.append(left_part.pop(0))
else:
result.append(right_part.pop(0))
return result
if len(container) == 1:
return container
else:
middle_index = len(container) // 2
return merge(sort(container[:middle_index]), sort(container[middle_index:]))
if __name__ == '__main__':
lst = [1, 3, 2, 5, 8, 7, 4, 6, 9, 0]
print(sort(lst))
| true |
b69914543c01b52fadb42f269ef8957dcdd991d2 | ashirsh/PY111_work | /Tasks/c0_fib.py | 815 | 4.34375 | 4 | def fib_recursive(n: int) -> int:
"""
Calculate n-th number of Fibonacci sequence using recursive algorithm
:param n: number of item
:return: Fibonacci number
"""
if n == 0:
return 0
elif n == 1:
return 1
elif n < 0:
raise ValueError
else:
return fib_recursive(n - 1) + fib_recursive(n - 2)
def fib_iterative(n: int) -> int:
"""
Calculate n-th number of Fibonacci sequence using iterative algorithm
:param n: number of item
:return: Fibonacci number
"""
fib = [0, 1]
if n < 0:
raise ValueError
if n > 1:
for i in range(1, n):
item = fib[i-1] + fib[i]
fib.append(item)
return fib[n]
if __name__ == '__main__':
print(fib_recursive(7))
print(fib_iterative(7))
| false |
0b6315d879d57ebe3c016cf0b06e2aa457ebf7a3 | CKDarling/django | /Python_Web_Development/my_practice_files/py_files/lists.py | 1,614 | 4.28125 | 4 | # Pythons array
# LISTS
my_list=[1,2,2,3,3,3]
my_2list=[3.4,4.5,4.6]
my_3list=['String',3,True,[1,2,3]] #string,numeral,boolean,nested array
print(my_list)
print(my_2list)
print(my_3list)
print(len(my_3list))
another_list=["a","b","c"]
print(another_list[2])
another_list[1]="FUCK YOU" # LISTS ARE MUTABLE
print(another_list)
another_list.append("APPENDED ITEM")
print(another_list)
bitch_list=[1,2,2,2]
another_list.append(bitch_list)
print(another_list)
another_list.extend(bitch_list) # adds 'bitch_list' as new values, not as a list
print(another_list)
item = another_list.pop() # 'popped' the last list item out of the list
# you can also specify the pop -> another_list.pop(3)
print(another_list)
print(item)
another_list.reverse()
print(another_list)
num_list = [1,2323,63465,5332,333]
num_list.sort() # sorts from high to low
print(num_list)
nested_list = [1,2,[3,4]]
print(nested_list[2])
print(nested_list[2][1]) #specifies the position in the second list
# MATRIX
matrix=[[1,2,3],[4,5,6],[7,8,9]]
# List Comprehension
first_col = [row[0] for row in matrix]
print(first_col)
# DICTIONARIES
my_stuff={"Key1":"Value","Key2":"Value2","Key3":{'123':[1,2,"Grab Me"]}}
print(my_stuff["Key1"])
print(my_stuff["Key3"]['123'][2])
my_stuff2 ={'lunch':'eggs',"dinner":'pussy'}
print(my_stuff2['lunch'])
my_stuff2['lunch'] = 'TURKEY BOY'
print(my_stuff2['lunch'])
my_stuff2['breakfast'] = 'bacon'
print(my_stuff2)
# TUPLES - Immutable sequences
# Booleans
# True - 1
# False - 0
#TUPLES
t=(1,2,3)
print(t[1])
# Sets - unnoredered set of unique elements
p = set()
p.add(1)
p.add(2)
p.add(2) # not added
print(p)
| true |
e2ea03d7a5474981ef0e7dce40549cbdeaf52253 | liyuan789/Leetcode_liyuan | /912.Sort_Array_MergeSort.py | 1,321 | 4.1875 | 4 |
def MergeSort(array):
if array is None or len(array) <= 1:
return array
return mergeSort(array, 0, len(array) - 1)
# Split array into two sub-arrays and mergeSort both sides separately
def mergeSort(array, start, end):
# Base Case
if start == end:
return [array[start]]
# Recursion Rule
mid = start + (end - start) // 2
left_sorted = mergeSort(array, start, mid)
right_sorted = mergeSort(array, mid + 1, end)
return merge(left_sorted, right_sorted)
def merge(left_sorted, right_sorted):
result = []
left_idx = 0
right_idx = 0
# 两边都有剩余; 谁小移谁
while left_idx < len(left_sorted) and right_idx < len(right_sorted):
if left_sorted[left_idx] <= right_sorted[right_idx]:
result.append(left_sorted[left_idx])
left_idx += 1
else:
result.append(right_sorted[right_idx])
right_idx += 1
# 左半边有剩余
while left_idx < len(left_sorted):
result.append(left_sorted[left_idx])
left_idx += 1
# 右半边有剩余
while right_idx < len(right_sorted):
result.append(right_sorted[right_idx])
right_idx += 1
return result
print(MergeSort([5, 2, 3, 1]))
print(MergeSort([1, 2, 3, 4]))
print(MergeSort([4, 3, 2, 1]))
| true |
75e5dae5f351e53d5d80ab6bf18f246d2cee791c | jamespeace/cs61a | /disc/08/tree.py | 1,201 | 4.1875 | 4 | #########
# Trees #
#########
class Tree:
def __init__(self, entry, branches=[]) -> None:
self.entry = entry
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)
def is_leaf(self):
return not self.branches
def leaves(tree):
"The leaf values in a tree."
if tree.is_leaf():
return tree.entry
else:
return sum([leaves(b) for b in tree.branches], [])
# Question
# Expression Trees
def eval_with_add(t):
""" Evaluate an expression tree of * and + using only addition.
>>> plus = Tree('+', [Tree(2), Tree(3)])
>>> eval_with_add(plus)
5
>>> times = Tree('*', [Tree(2), Tree(3)])
>>> eval_with_add(times)
6
>>> deep = Tree('*', [Tree(2), plus, times])
>>> eval_with_add(deep)
60
>>> eval_with_add(Tree('*'))
1
"""
if t.entry == '+':
return sum([leaves(b) for b in t.branches])
elif t.entry == '*':
total = 1
for b in t.branches:
total, term = 0, total
for _ in range(eval_with_add(b)):
total = total + term
return total
else:
return t.entry
| false |
1ce12b94f2cc7efefe6059f698b0533546e1994f | y-uchiida/python-training | /paiza-larning/usage_lambda.py | 1,711 | 4.59375 | 5 | # ラムダ式(無名関数)の使いかた
# Λ ← ラムダ記号。素粒子物理学においてラムダ粒子を表したり、宇宙定数の記号に使われたりする
# 無名関数は、名前を指定せずに実行できるまとまった一連の処理のこと
# 関数の引数に、多くない処理をした結果を与えたい…というような場合に利用される
# 以下引用
# lambda(ラムダ式:無名関数)は『無名関数』と言われるように関数の名前を持たず、そして関数のような役割を持っていますが基本的には式です。
# そのため通常の関数のように機能を使い回したりすることができず1回限りの実行処理となります。
# 参考URL: https://dot-blog.jp/news/python-lambda-basic/
# lambda式 を使って、偶数なら""even", 奇数なら"odd" を返す例
# ラムダ式では複数行にまたがる文を使うことはできないが、if文に相当する三項演算子は使用可能
even_or_odd = lambda num: "even" if num % 2 == 0 else "odd"
print("print(even_or_odd(3): {})".format(even_or_odd(1))) # -> "odd"
print("print(even_or_odd(2): {})".format(even_or_odd(2))) # -> "even"
print("print(even_or_odd(5*3+2): {})".format(even_or_odd(5*3+2))) # -> "odd"
print()
# Pythonのコーディング規約PEP8 においては、上記の例 のようにラムダ式に名前をつけるのは非推奨
# 名前を付けて繰り返し呼び出す必要のあるものは、むしろdefを使ってユーザー関数を定義すべき
# lambda式で、値を2乗した結果をmap関数に渡す
map_square = map(lambda x: x**2, [1, 2, 4, 8, 16, 32])
print(list(map_square)) | false |
8e5b31367eb9810b1c2d008457fccfd4b9919061 | y-uchiida/python-training | /paiza-larning/manipurate_tuple.py | 782 | 4.34375 | 4 | # tuple(タプル) の使い方
# 参考URL: https://docs.python.org/ja/3/tutorial/datastructures.html
# tuple は、最初に宣言した内容から変更ができない配列のようなもの
# 他の言語では、類似のデータ構造はないこともある。。。
myhand = ("thumb", "index finger", "middle finger", "ring finger", "little finger")
# 基本はlistと同じなので、for ... in にオブジェクトとして与えれば、順番に値が取れる
print("-------- print fingers in my hand --------")
for finger in myhand:
print(finger)
print()
# tuple[i] で要素にアクセスできるのも同じ
print(myhand[3] + "\n")
# 要素の内容を変更したり、追加や削除はできない
myhand.append("another finger") # エラーになる | false |
4d092cb19ed4f6fa5d757d99f227f1966c43f25e | Aniket1298/engg_math | /scalar.py | 845 | 4.4375 | 4 | import numpy as np
def scalar():
print("Scalar multiplication is the multiplication of a vector by a scalar (where the product is a vector), and must be distinguished from inner product of two vectors (where the product is a scalar)")
print("For example consider a Matrix A and a scalar value k given below")
A=np.array([[2,4],[4,3]])
print ("A \n",A)
print ("k=3")
print ("Now The scalar multiplication of the matrix A with k is")
A=3*A
print (A)
n=int(input("Now Enter number of rows of matrix for matrix multiplication:"))
A=[]
for i in range(n):
row=list(map(int,input().split()))
A.append(row)
k=int(input("Enter a value for scalar multiplication with the Matrix:"))
A=np.array(A)
A=k*A
print ("Resultant matrix Ak is \n",A)
scalar()
| true |
4d2ad390bab6e1aa17636deddc2f745f4844a11e | dsiu13/python-notes | /OOP/exercise.py | 490 | 4.375 | 4 | # Write and object oriented program that performs the following
# tasks:
# 1. Define a class called "Employee" and create an instance
# of that class
# 2. Create an attribute called name and assign it with a
# value
# 3. Change the name you previously defined within a
# method and call this method by making use of the object you
# created
class Employee:
def __init__(self, name):
self.name = name
def work(self):
print("Hello")
Bob = Employee(bob)
Bob.work()
| true |
6959bd07aeb7ffefe3c29beba9a7f87d03cbbdfe | o87702623/270201011- | /lab2/example2.py | 334 | 4.28125 | 4 | #minimum value
num1 = int(input("enter 1st value: "))
num2 = int(input("enter 2nd value: "))
num3 = int(input("enter 3rd value: "))
if num1 < num2 and num1 < num3 :
print(f"min value is {num1}")
elif num2 < num1 and num2 < num3 :
print(f"min value is {num2}")
elif num3 < num1 and num3 < num2 :
print(f"min value is {num3}")
| false |
9c0314c72377ec98912275101a50b46cfab8cfb6 | blad00/HPCTutorial | /TestingFile.py | 1,281 | 4.125 | 4 | def encode(text):
"""
>>> encode("robber language")
"rorobbobberor lolangonguagoge"
>>> encode("Kalle Blomkvist")
"Kokallolle Bloblomkvomkvistost"
>>> encode("Astrid Lindgren")
"Astrostridod Lolindgrondgrenon"
"""
# define vowels
vowels = "aeiou"
decoded, consonants = "", ""
for character in text:
if character.isalpha() and character.lower() not in vowels:
# add character to group of consecutive vowels
consonants += character
else:
# if a group of consecutive vowels was formed, add the group to
# the decoded text, followed by the letter o and a lowercase
# repetition of the group of vowels; after this a new group of
# vowels can be started
if consonants:
decoded += consonants + "o" + consonants.lower()
consonants = ""
# add the non-consonant to the decoded text
decoded += character
# if a group of vowels was formed at the end of the text, that group
# still needs to be added to the decoded text, followed by the letter o and
# a lowercase repetition of the group of vowels
if consonants:
decoded += consonants + "o" + consonants.lower()
# return decoded text
return decoded | true |
c462aa9e4d578d73602c01054e81dcd481c59c2b | Pepperbrow/100DaysOfCode | /Day2.py | 742 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 8 21:00:34 2021
@author: peppe
"""
#To change type, cast by adding int()
x = int(input('Please provide number'))
if x < 10:
print('Smaller')
if x == 11:
print('your number was 11')
if x <= 19:
print('your number was less than or equal to 19')
if x >= 20:
print('Bigger')
print('finis')
type(x)
#NOTE: Do not use tab! Use 4 spaces. Python can get confused.
#try/except
#If someone enters something crazy, you can catch and run something else
#only put the singl line of code that is risky in the try
#def = define function. Reusable code snippet.
def thing():
print('Hello')
print('World!')
thing()
print('Zip')
thing()
| true |
2d90bc573594763bbe7a6e116d584f95cc286c35 | larissacensi/Python | /Exercicio9.py | 306 | 4.125 | 4 | #Programa que pede a temperatura em graus fahrenheit, transforme e mostre a temperatura em graus celsius
#C=(5*(F-32)/9)
fahrenheit = float(input("Digite a temperatura em graus fahrenheit: "))
celsius =round((5*(fahrenheit-32)/9),2)
print(fahrenheit,"graus fahrenheit é igual a",celsius,"graus celsius")
| false |
49126841f094caed58b56a3c875dcdb141c876e8 | easmah/topstu | /userinputWhileLoop/input_while.py | 1,288 | 4.375 | 4 | """ The input() function pauses your program and waits for the user to enter some text. """
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
name = input("Please enter your name: ")
print("Hello, " + name.title())
# Sometimes you’ll want to write a prompt that’s longer than one line.
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your firstname: "
first_name = input(prompt)
print('Hello, ' + first_name.title())
# Using int(0 to accept input. The int() function converts a string representation of a number to a numerical
# representation
age = input("How old ae you: ")
age = int(age)
print(age)
height = input("How tall are you? ")
height = int(height)
if height >= 36:
print("You're tall enough to ride")
else:
print("You'll be able to ride when you're a little older")
# Modulo Operator
""" A useful tool for working with numerical information is the modulo operator (%), which divides one number by
another number and returns the remainder"""
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("Number is " + str(number) + " is even.")
else:
print("The number " + str(number) + " is odd")
| true |
dd98e88cdbb79f0ca620f4ce0cf6979312f19f0b | easmah/topstu | /list/part_of_a_list.py | 574 | 4.3125 | 4 | """Slicning a list"""
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[1:])
print(players[-3:])
#Looping through a Slice
for player in players[:3]:
print(player.title())
#Copying a list
my_foods = ['pizza', 'falafel', 'carrot cake']
friends_foods = my_foods[:]
my_foods.append("rice cake")
friends_foods.append('waakye')
print("My favorite foods are: ")
print(my_foods)
print("My friend's favourite foods are ")
print(friends_foods)
for food in my_foods:
print(food.title()) | false |
316f494a37714d73c09b8f9346ea3bebdf59c8a6 | JannaKim/JavaPythonAlgoStudy | /HongMinSik/Python/파이썬 기초이론/Range.py | 615 | 4.25 | 4 | # for i in range(100) : range(100)은 숫자 100개를 생성하는 객체이다
# range(5, 10) : 숫자를 5~9까지 생성한다
print(range(5, 10)) # range(5, 10) 객체를 생성함
a = list(range(5, 10)) # 5~9까지의 숫자를 리스트로 받는다
print(a)
a = list(range(0, 10, 2)) # 0~10까지의 숫자를 2 증가시키며 리스트로 받는다
print(a)
# range(10, 0) : 10~0으로 하는 것 처럼 보이나, 실제로 불가능
# range(10, 0, -1) : 음수로 감소시키면 가능, reversed함수를 이용하여 감소시키는 것도 가능하다
for i in "Python":
print(i, end = " ")
| false |
c8789e373bca04b52d594e7cc478ebefd0434267 | Tuseeq1/PythonPractice | /9_Time Conversion.py | 873 | 4.375 | 4 | # Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an integer
# or decimal, and if it is 1, then it should be followed by second.
# You might need to use int() to turn a decimal into a float depending
# on how you code this. int(3.0) gives 3
#
# Note that English uses the plural when talking about 0 items, so
# it should be "0 minutes".
#
def convert_seconds(number):
# write your code here
print convert_seconds(3661)
#>>> 1 hour, 1 minute, 1 second
print convert_seconds(7325)
#>>> 2 hours, 2 minutes, 5 seconds
print convert_seconds(7261.7)
#>>> 2 hours, 1 minute, 1.7 seconds | true |
695c744b906306a271e7fd4645a63b58a4215a32 | tommyconner96/cs-module-project-hash-tables | /notes.py | 2,678 | 4.40625 | 4 | # A hash function needs to take a string and return a single number
# It must be deterministic (i.e the same result every time given the same input)
def hash_fn(s):
# convert the string to a UTF-8 (Unicode) representation
encoded_string = s.encode() # O(1)
result = 0
# every character is now a number based off UTF-8 rules
for byte_char in encoded_string:
# simply add the numbers up to get one single new number
result += byte_char
return result
# print(hash_fn("banana")) # => 609
# print(hash_fn("apple")) # => 530
# Lets map the result of hash_fn to an index in some array
# we create an array of size 8
hash_array = [None] * 8
# we can use modulo to bind the number from hash_fn to 0 -> length of the array
# Store banana inside hash_array
# Banana is the key
# Banana is yellow is the value
hash_value = hash_fn("banana") # 609
index = hash_value % len(hash_array)
hash_array[index] = ("banana","banana is yellow")
# Store apple inside hash_array
hash_value = hash_fn("apple") # 530
print(f'apple hashed to the number {hash_value}')
index_of_apple = hash_value % len(hash_array)
print(f'Apple will go into index {index_of_apple}')
hash_array[index] = ("apple", "apple is green")
# Store eggg inside hash_array
## THIS WILL COLLIDE WITH APPLE
# egg_hash_value = hash_fn("eggg") #410
# print(f'egg hashed to the number {egg_hash_value}')
# index_of_egg = egg_hash_value % len(hash_array)
# print(f'Eggg will go into index {index_of_egg}')
# hash_array[index_of_egg] = ("eggg", "This will replace apple")
# Look up Banana in hash_array
# Get the index value for Banana
hash_value = hash_fn("banana") # 609 #O(N) but N === Length of String which is usually very small compared to Array
index = hash_value % len(hash_array) #O(1)
# -------- SUMMARY --------- (i.e lets convert the above into reusable functions)
# Hash function + An Array == Hash_table
# To insert a key and value to this hash_table
# - hash the key to convert it to a number
# - take that number and MOD it by the size of hash_table
# - insert the VALUE into the index given by the MOD operation
def insert_to_hash_table(key, value):
hash_value = hash_fn(key)
index = hash_value % len(hash_array)
hash_array[index] = (key, value)
# To retrieve a value given a specific key from a hash_table
# - hash the key to convert it to a number
# - use MOD to find the index within the underlying array
# - use this new index to find the value in the array
def get_from_hash_table(key):
hash_value = hash_fn(key)
index = hash_value % len(hash_array) # convert the number into a new number between 0 - len(array)
return hash_array[index]
| true |
0b1e6156bffcb601df2f45c6cf1d1e8b252a36b1 | DavidStarshaw/Python | /barcode.py | 433 | 4.15625 | 4 | barcode = raw_input("Type the barcode without the last digit: ")
total = 0
for count, digit in enumerate(barcode):
digit = int(digit)
if (count % 2 == 0):
total += digit
else:
total += digit * 3
difference = (-1 * total) % 10
print "The last digit is: ", difference
"""if (remainder == 0):
difference = 0
else:
difference = 10 - remainder
print "The last digit is: " + str(difference)
""" | true |
10caf2cda3fad122e3999ed24647ccf73c9e7d8b | olegbrz/coding_every_day | /CodeWars/020_011220_valid_parentheses.py | 859 | 4.40625 | 4 | """Write a function called that takes a string of parentheses, and determines
if the order of the parentheses is valid. The function should return true if
the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints
0 <= input.length <= 100
Along with opening (() and closing ()) parenthesis, input may contain any valid
ASCII characters. Furthermore, the input string may be empty and/or not contain
any parentheses at all. Do not treat other forms of brackets as parentheses
(e.g. [], {}, <>).
"""
def valid_parentheses(string):
p_balance = 0
vals = {'(': 1, ')': -1}
for c in string:
if c in vals.keys():
p_balance += vals[c]
if p_balance < 0:
return False
return not p_balance
| true |
ed4446ad65253321e42136f2e85b6bf0f3c8342c | olegbrz/coding_every_day | /CodeWars/001_231120_pascals_triangle.py | 787 | 4.125 | 4 | """
In mathematics, Pascal's triangle is a triangular array of the binomial
coefficients expressed with formula (n k) = n!/(n-k)!, where n denotes a
row of the triangle, and k is a position of a term in the row.
Test.assert_equals(
pascals_triangle(1), [1],"1 level triangle incorrect");
Test.assert_equals(
pascals_triangle(2), [1,1,1],"2 level triangle incorrect");
Test.assert_equals(
pascals_triangle(3), [1,1,1,1,2,1],"3 level triangle incorrect");
"""
import math
def pascals_triangle(n):
triangle = []
def comb(n, x):
return math.factorial(n)/(math.factorial(x)*math.factorial(n-x))
for row in range(0, n):
for col in range(0, row+1):
triangle.append(int(comb(row, col)))
return triangle
print(pascals_triangle(4))
| true |
d228fcc7e86e40715a263f8f4fe8805cd75c134f | DanielSmithP/Code-Challenge-Solutions | /cipher-map.py | 1,835 | 4.125 | 4 | """ Write a module that enables the robots to easily recall their passwords through codes when they return home.
The cipher grille and the ciphered password are represented as an array (tuple) of strings.
Input: A cipher grille and a ciphered password as a tuples of strings.
Output: The password as a string. """
def recall_password(cipher_grille, ciphered_password):
final_answer = []
index = 0
while index <= 3:
positions = get_positions(cipher_grille)
for dictionary in positions:
for key, value in dictionary.items():
final_answer.append(ciphered_password[key][value])
cipher_grille = rotate_grille(cipher_grille)
index += 1
print("".join(final_answer))
return "".join(final_answer)
def get_positions(cipher_grille):
answers = []
for position, line in enumerate(cipher_grille):
for index, character in enumerate(line):
if character == 'X':
answers.append({position : index})
return answers
def rotate_grille(old_g):
new_grille = []
index = 0
for line in old_g:
new_line = "{}{}{}{}".format(old_g[3][index], old_g[2][index], old_g[1][index], old_g[0][index])
new_grille.append(new_line)
index += 1
return new_grille
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert recall_password(
('X...',
'..X.',
'X..X',
'....'),
('itdf',
'gdce',
'aton',
'qrdi')) == 'icantforgetiddqd', 'First example'
assert recall_password(
('....',
'X..X',
'.X..',
'...X'),
('xhwc',
'rsqx',
'xqzz',
'fyzr')) == 'rxqrwsfzxqxzhczy', 'Second example'
| true |
12b91df7530aa626ddb518bf68ad18f4a287fbdd | hoannt110/hoan | /hoan/vehinh.py | 639 | 4.125 | 4 | from turtle import*
speed(5)
color("green","yellow")
def square():
begin_fill()
for i in range(4):
forward(100)
left(90)
end_fill()
return
def triangle():
begin_fill()
for i in range(3):
forward(100)
left(120)
end_fill()
return
print("Enter 1 if you want draw a square")
print("Enter 2 if you want draw a triangle")
print("Enter 3 if you want draw a circle")
a = int(input("Enter a number"))
if a == 1:
square()
if a == 2:
triangle()
if a == 3:
begin_fill()
circle(50)
end_fill()
else:
print("Please enter a number from 1 to 3")
mainloop() | true |
fd9737c97e289f6275c034aecf4a35f4911655cc | vijayv/Projects | /ThinkPython/chapter10.py | 1,853 | 4.21875 | 4 | #!/usr/bin/python
'''
Exercise 10.1. Write a function called nested_sum that takes a nested list of integers and add up the elements from all of the nested lists.
'''
def nested_sum(x):
total = 0
for each in x:
for number in each:
total += number
return total
'''
Exercise 10.2. Use capitalize_all to write a function named capitalize_nested that takes a nested list of strings and returns a new nested list with all strings capitalized.
'''
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
def capitalize_nested(l):
nex = []
for s in l:
nex.append(capitalize_all(s))
return nex
'''
Exercise 10.3. Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
'''
def cumulative_sum(list):
new_list = []
for i in xrange(len(list)):
new_list.append(sum(list[0:i+1]))
return new_list
'''
Exercise 10.4. Write a function called middle that takes a list and returns a new list that contains all but the first and last elements. So middle([1,2,3,4]) should return [2,3].
'''
def middle(list):
return list[1:len(list)-1]
'''
Exercise 10.5. Write a function called chop that takes a list, modifies it by removing the first and last elements, and returns None.
'''
def chop(list):
list.pop(0)
list.pop(len(list)-1)
if __name__ == '__main__':
y = [[12,40],[12,42]]
print nested_sum(y)
words = [['trada', 'matt'], ['berkeley', 'unknown']]
print capitalize_nested(words)
example103 = [1, 2, 3, 4, 5]
print cumulative_sum(example103)
print middle(example103)
chop(example103)
print(example103) | true |
95c85bb92454f8f12885638fefd0e9d29a18de5e | vijayv/Projects | /ThinkPython/chapter15.py | 644 | 4.21875 | 4 | #!/usr/bin/python
'''
Exercise 15.1. Write a function called distance_between_points
that takes two Points as arguments and returns the distance between them.
'''
def distance_between_points(p1, p2):
import math
v1 = (p1['x'] - p2['x'])**2
v2 = (p1['y'] - p2['y'])**2
return math.sqrt(v1 + v2)
'''
Exercise 15.2
'''
class Point(object):
'''Represents a point in 2-D space.'''
if __name__ == '__main__':
p1 = {'x' : 1, 'y' : 4}
p2 = {'x' : 4, 'y' : 2}
print distance_between_points(p1, p2)
blank = Point()
blank.x = 3.0
blank.y = 5.0
print "Printing ", blank
print "Coor x: ", blank.x
| true |
12beb34be50d55ce6546f3b972b2420e1d8bf1a1 | vijayv/Projects | /ThinkPython/exercise7.py | 1,937 | 4.65625 | 5 | #/usr/bin/python
'''
To test the square root algorithm in this chapter, you could compare it with
math.sqrt. Write a function named test_square_root that prints a table like this:
The first column is a number, a; the second column is the square root of a computed with the function
from Section 7.5; the third column is the square root computed by math.sqrt; the fourth column is
the absolute value of the difference between the two estimates.
'''
def square_root(a):
epsilon = .0000001
x, y = 1.0, 0.0
x = a/2
while abs(y-x) > epsilon:
x = y if y > 0 else 1
y = (x + a/x) / 2
return y
def test_square_root(x):
from math import sqrt
my_value = square_root(x)
act_value = sqrt(x)
string = x, my_value, act_value, abs(my_value - act_value)
return string
'''
Exercise 7.4. The built-in function eval takes a string and evaluates it using the Python interpreter.
For example:
Write a function called eval_loop that iteratively prompts the user, takes the resulting input and
evaluates it using eval, and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it
evaluated.
'''
def eval_loop():
inval = ''
while inval <> "\"done\"":
inval = raw_input("What would you like to evaluate? \n")
print eval(inval)
'''
Exercise 7.5. The mathematician Srinivasa Ramanujan found an infinite series that can be used to
generate a numerical approximation of pi:
Write a function called estimate_pi that uses this formula to compute and return an estimate of
pi. It should use a while loop to compute terms of the summation until the last term is smaller than
1e-15 (which is Python notation for 10^15). You can check the result by comparing it to math.pi.
'''
# This looks overly complicated and I don't feel like doing it!
if __name__ == '__main__':
print test_square_root(18)
eval_loop() | true |
2cdf664739631e25f099af33995201d597730b7c | veronikam/aspp_d1 | /generator/example3.py | 717 | 4.3125 | 4 | # 'break' works on the innermost loop. If we want to break out
# of the outer loop, we often have to resort to flag variable.
# Rewrite the following example to use .close() to stop the
# outer loop.
from __future__ import print_function
def counter(n):
i = 1
while i <= n:
yield i
i += 1
def print_table():
outer = counter(10)
total, limit = 0, 100
for i in outer:
inner = counter(i)
print(i, end=': ')
for j in inner:
print(i * j, end=' ')
total += i * j
if total >= limit:
outer.close()
break
print()
print('total:', total)
if __name__ == '__main__':
print_table()
| true |
9b988078f3f77de77793ff7b73798a07a69ae413 | Larry19David/ICC-102-ALGORITMOS | /ejercicio #3 division en python.py | 312 | 4.1875 | 4 | divisor = -1
dividendo = -1
while divisor <= 0 or dividendo <= 0:
divisor = int(input("digite el divisor: "))
dividendo = int(input("digite dividendo: "))
if divisor > 0 and dividendo > 0:
resultado = divisor/dividendo
print(resultado)
else:
print("solo positivos.")
| false |
c7486296cee7c8df3d5b65e28bc96714def03e31 | DoctorBear-it/ServiceLife | /Diffusion/TEST.py | 2,388 | 4.125 | 4 | import numpy as np
from PyQt4 import QtCore, QtGui
class ClassName(object):
"""docstring for ClassName"""
"""
The first def in a class is the __init__, which is the initial properties given
to an instance of the called class. These properties will then be associated
with a specific instance rather than the entire class, as would be the case
using the following definitions not in the __init__ def.
The most common use of super is in the declaration of __init__ of base classes
example:
class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__
"""
def __init__(self, arg):
super(ClassName, self).__init__() #call super (class) with argument (className) and (self), then call the function .__init__
#super is used to control multiple inheritance
self.arg = argument
self.arg2 = [] #Instantiate a list which can be ammended for each instance of the class using the following def
def functionAmmendArg2(self, trait):
self.arg2.append(trait)
#pass #Pass is used as a code completion filler to pass on to the next def if nothing has been defined
def function():
pass
"""
Inheritance is defined by the Parent-child or "is-a" relationship.
Composition is defined by the use of a "has-a" relationship, where one class simply
uses another class to do work, rather than having inherited from said class.
Composition is considered to be a more robust method of coding since multiple
inheritance can become complicated and result in code which is not readily
reusable (as copy-paste modules/tools, for example).
"""
"""
A comment on doc flow control:
use the __name__ property of the document to test wether
the file is being executed on its own or if it has been imported from another module
example:
"""
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
"""
The following is auto completed when one types property
"""
def foo():
doc = "The foo property."
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
return locals()
foo = property(**foo())
""""
Autocompletion of the try, except, else, finally function:
"""
try:
pass
except Exception, e:
raise
else:
pass
finally:
pass | true |
f6b3d7b5574d940fb706e88426ffff899256dc69 | afernsmavany/cohort3 | /python/14_destructuring variables/code14.py | 731 | 4.375 | 4 | # example 1:
x, y = 5, 11
print(x, y)
# example 2:
t = 5, 11
x, y = t
print(x, y)
# example 2:
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}
print(list(student_attendance.items()))
# for student, attendance in student_attendance.items():
# print(f"{student}: {attendance}")
# example 3:
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}
print(list(student_attendance.items()))
for t in student_attendance.items():
print(t)
# print(f"{student}: {attendance}")
# example 4:
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}
print(list(student_attendance.items()))
for student, attendance in student_attendance.items():
print(t)
# print(f"{student}: {attendance}")
| false |
82ad5671e52b08115450d59a72baf3c33577423a | afernsmavany/cohort3 | /python/12_list_comprehension/code12.py | 1,431 | 4.40625 | 4 | #creating a new list of values (doubled):
numbers = [1, 3, 5]
doubled = []
for num in numbers:
doubled.append(num * 2)
#doing the same with list comprehension:
numbers = [1, 3, 5]
doubled = [num *2 for num in numbers]
# or alternately:
numbers = [1, 3, 5]
doubled = [x *2 for x in numbers]
#example 2:
friends = ["Rolf", "Sam", "Samantha", "Saurabh", "Jen"]
starts_s = []
for friend in friends:
if friend.startswith("S"):
starts_s.append(friend)
print(starts_s)
#example 2 with list comprehensions:
friends = ["Rolf", "Sam", "Samantha", "Saurabh", "Jen"]
starts_s = [friend for friend in friends if friend.startswith("S")]
print(starts_s)
#example 3 (list comprehensions create a new list):
friends = ["Sam", "Samantha", "Saurabh"]
starts_s = [friend for friend in friends if friend.startswith("S")]
print(friends)
print(starts_s)
# returns false (because they are 2 different lists):
print(friends is starts_s)
#The elements inside are the same, but the lists are not the same:
print(friends)
print(starts_s)
# returns true (as elements inside list are the same):
print(friends[0] is starts_s[0])
#Access ID's of the list:
print(friends)
print(starts_s)
#will return different ID's (i.e. different memory address):
print("friends: ", id(friends), "starts_s: ", id(starts_s))
#creating the same/ exact copy of the list:
friends = ["Sam", "Samantha", "Saurabh"]
starts_s = friends | true |
8286e666e6664af4bea07ee3687c149b026c0859 | FizzyBubblech/MIT-6.00 | /ps1/ps1a.py | 1,351 | 4.1875 | 4 | # 6.00 Problem Set 1a
# Denis Savenkov
# ps1a.py
# Determines remaining credit card balance after a year of making
# the minimum payment each month
# retrieve user input
out_bal = float(raw_input("Enter the outstanding balance on your credit card: "))
ann_rate = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
min_rate = float(raw_input("Enter the minimum monthly payment rate as a decimal: "))
# initialuze variable to calculate total amount paid
total_paid = 0
# calculate for each month and print out
for month in range(1, 13):
# calculate minimum monthly payment of balance at start of the month
min_monthly = round(min_rate * out_bal, 2)
# calculate interest paid
int_paid = round((ann_rate / 12) * out_bal, 2)
# calculate principal paid off
pr_paid = round(min_monthly - int_paid, 2)
# update balance
out_bal -= pr_paid
# update total amount paid
total_paid += min_monthly
print "Month: " + str(month)
print "Minimum monthly payment: " + "$" + str(min_monthly)
print "Principle paid: " + "$" + str(pr_paid)
print "Remaining balance: " + "$" + str(out_bal)
# print out the result
print "RESULT"
print "Total amount paid: " + "$" + str(total_paid)
print "Remaining balance: " + "$" + str(out_bal)
| true |
f6a2f4d9554bd222116e7491474b633dc45b1669 | DyakonovDmitriy/Lesson1 | /input_output.py | 486 | 4.4375 | 4 | # однострочный комментарий
'''
многострочный комментарий
многострочный комментарий
многострочный комментарий
'''
print("Hello")
print('Hello', 'student', 123, sep = 'xxx')
print('Hello', 'student', 123, end = 'xxx')
print()
#ввод
name=input("Введите имя:")
#print();
print(name);
print(type(name))
age=input("Введите возраст:")
print(int(age),type(int(age)))
| false |
d7eac2dbe0150e769c0bc30b1d704d3b00e15f41 | franciscogregatti/atividades | /Atividade 2 Exercicio 1 | 388 | 4.15625 | 4 | #!usr/bin/env python
#-*- coding: latin1 -*-
#digitar a idade em dias e converter para anos meses e dias
print ('Converter a idade de dias para anos meses e dias')
idadeemdias = int(input('Digite sua idade em dias: '))
anos = int(idadeemdias / 365)
meses = int((idadeemdias % 365) / 30)
dias = int((idadeemdias % 365) % 30)
print (anos, 'anos,', meses,'meses e ', dias,'dias de idade')
| false |
41e75c6b4e1d3c8ff89a1524121403f99ab1a8d6 | yannuuo/review | /嵌套循环的使用.py | 812 | 4.21875 | 4 | """
输入一下图形
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
# i=0
# j=0
# for i in range(1,6):
# # print(i)
# for j in range(1,i+1):
# print(j,end=" ")
# print( )
"""
打印*
*
**
***
****
*****
******
"""
#代码
# for i in range(2,7):
# # print(i)
# for j in range(1,i+1):
# print("*",end=" ")
# print( )
"""
打印 *
* *
* * *
* * * *
* * * * *
* * * * * *
'''
"""
#代码
for i in range(1,7): #外层循环,遍历行数
# print(i)
for j in range(1,i+1): # 内层循环,根据遍历的行数打印数据(根据行数打印数据,第1行,打印1,第二行,打印1,2 第三行,打印1,2,3,...)
print("*",end=" ")
print( )
# i=0
# while i<10:
# for j in range(1,10):
# print('i=',i,'j=',j)
# i+=1
| false |
9c03d043cadc4a85699477765b7866f341071d09 | TheGreatAbyss/CodeSamples | /algos/Floyd-Warshall.py | 2,456 | 4.3125 | 4 | """
Below is the Floyd Warshall algorithm for computing the shortest path between all nodes in a directed graph
The graph can have negative edges, but if it has a negative cycle the algo will stop.
This runs in O(n^3) time
"""
import numpy as np
from collections import defaultdict
node_dict = defaultdict(dict)
distinct_nodes_found = set([])
"""
Example of node_dict
{ node 1 : {
node x: cost,
node y: cost
}
node 2 :{
node x: cost,
node y: cost
}
}
"""
with open("g_test.txt") as f:
for line in f:
(tail, head, cost) = line.strip().split(" ")
node_dict[tail][head] = cost
distinct_nodes_found.add(tail)
distinct_nodes_found.add(head)
n = len(distinct_nodes_found)
# Note I am adding 1 to k, i and j because numpy starts indexing arrays at zero
value_array = np.zeros((n + 1, n + 1, n + 1))
value_array.fill(float('inf'))
# pre-fill step for k = 0, Set Cij for all nodes that are next to each other and are easily known
# just from reading the graph data.
# runs in O(m) time
for tail, head_dict in node_dict.items():
for head, cost in head_dict.items():
value_array[0, head, tail] = cost
# Main loop of dynamic programing algorithm
# Each loop through k tries seeing if there is a shorter path from i to j with k in the middle.
# If we know the shortest path subproblem from i -> k and k -> j, then we know the shortest path i -> j
# is the minimum of either the previous computed shortest path, or i -> k + i ->j
for k in range(1, n + 1, 1):
for i in range(1, n + 1, 1):
for j in range(1, n + 1, 1):
shortest_path = min(value_array[k-1, i, j], value_array[k-1, i, k] + value_array[k-1, k, j])
value_array[k, i, j] = shortest_path
# If there is a negative cost cycle, then a value will show a negative cost getting back to itself
# If this is seen on any iteration of k then stop the loop and exit the program
if np.min(np.diag(value_array[k])) < 0:
print("negative cost cycle found")
print(value_array[k])
for index, item in enumerate(np.diag(value_array[k])):
if item < 0:
print("index: " + str(index) + " item: " + str(item))
quit()
# print all shortest paths
print(value_array[k])
print("the smallest shortest path ")
# I'm assuming i -> i paths count?? The quiz wasn't clear
print(np.min(value_array[k]))
| true |
fe0c30f9c7912786ed195049b63eb7dce03cc3d9 | anhcuonghuynhnguyen/Toplevel-Widgets | /5.MessageBox.py | 1,165 | 4.21875 | 4 | #messagebox.Function_Name(title, message [, options])
''''
Function_Name: This parameter is used to represents an appropriate message box function.
title: This parameter is a string which is shown as a title of a message box.
message: This parameter is the string to be displayed as a message on the message box.
options: There are two options that can be used are:
default: This option is used to specify the default button like ABORT, RETRY, or IGNORE in the message box.
parent: This option is used to specify the window on top of which the message box is to be displayed.
'''
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("300x200")
w = Label(root, text ='GeeksForGeeks', font = "50")
w.pack()
messagebox.showinfo("showinfo", "Information")
messagebox.showwarning("showwarning", "Warning")
messagebox.showerror("showerror", "Error")
messagebox.askquestion("askquestion", "Are you sure?")
messagebox.askokcancel("askokcancel", "Want to continue?", )
messagebox.askyesno("askyesno", "Find the value?")
messagebox.askretrycancel("askretrycancel", "Try again?")
root.mainloop()
| true |
d9e1ed04826886009a8e763dfcfcd249c1326a1e | anhcuonghuynhnguyen/Toplevel-Widgets | /1.TopLevel.py | 2,811 | 4.40625 | 4 | '''A Toplevel widget is used to create a window on top of all other windows.
The Toplevel widget is used to provide some extra information to the user and also when our program deals with more than one application.
These windows are directly organized and managed by the Window Manager and do not need to have any parent window associated with them every time.'''
#toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)
"""root = root window(optional)
bg = background colour
fg = foreground colour
bd = border
height = height of the widget.
width = width of the widget.
font = Font type of the text.
cursor = cursor that appears on the widget which can be an arrow, a dot etc.
Common methods
iconify :turns the windows into icon.
deiconify : turns back the icon into window.
state : returns the current state of window.
withdraw : removes the window from the screen.
title : defines title for window.
frame : returns a window identifier which is system specific. """
from tkinter import *
# Create the root window
# with specified size and title
root = Tk()
root.title("Root Window")
root.geometry("450x300")
# Create label for root window
label1 = Label(root, text = "This is the root window")
# define a function for 2nd toplevel
# window which is not associated with
# any parent window
def open_Toplevel2():
# Create widget
top2 = Toplevel()
# define title for window
top2.title("Toplevel2")
# specify size
top2.geometry("200x100")
# Create label
label = Label(top2,
text = "This is a Toplevel2 window")
# Create exit button.
button = Button(top2, text = "Exit",
command = top2.destroy)
label.pack()
button.pack()
# Display until closed manually.
top2.mainloop()
# define a function for 1st toplevel
# which is associated with root window.
def open_Toplevel1():
# Create widget
top1 = Toplevel(root)
# Define title for window
top1.title("Toplevel1")
# specify size
top1.geometry("200x200")
# Create label
label = Label(top1,
text = "This is a Toplevel1 window")
# Create Exit button
button1 = Button(top1, text = "Exit",
command = top1.destroy)
# create button to open toplevel2
button2 = Button(top1, text = "open toplevel2",
command = open_Toplevel2)
label.pack()
button2.pack()
button1.pack()
# Display until closed manually
top1.mainloop()
# Create button to open toplevel1
button = Button(root, text = "open toplevel1",
command = open_Toplevel1)
but = Button(root, text = "Quit", command= root.destroy).pack()
label1.pack()
# position the button
button.place(x = 155, y = 50)
# Display until closed manually
root.mainloop()
| true |
80a3f43158aec4bc6262f675f8513395053cfe4c | yyyuaaaan/pythonfirst | /crk/3.6.py | 1,415 | 4.25 | 4 | import Queue
"""
__author__ = 'anyu'
Write a program to sort a stack in ascending order. You should not make any assumptions
about how the stack is implemented. The following are the only functions that should be
used to write this program: push | pop | peek | isEmpty.
1,insertion sort, use the helping stack
2,unlimited stack, use recursion i.e.If we were allowed to use unlimited stacks,
we could implement a modified quicksort or mergesort.
With the mergesort solution, we would create two extra stacks and divide the stack
into two parts. We would recursively sort each stack, and then merge them back together
in sorted order into the original stack. Note that this would require the creation of
two additional stacks per level of recursion.
3,priority queue, until all
void Qsort(stack<int> &s){
priority_queue< int,vector<int>,greater<int> > q;
while(!s.empty()){
q.push(s.top());
s.pop();
}
while(!q.empty()){
s.push(q.top());
q.pop();
4 use list as linked list, to do selection sort, or make a linked list by myself
"""
def psort(s):
if not s:
print("stack empty")
return
else:
pqueque = Queue.PriorityQueue()
while not s.isEmpty():
data = s.pop()
pqueque.put(data)
while not pqueque.empty():
data = pqueque.get()
s.push(data)
return s
| true |
be3de17915c0402f455bb8a632d7a4bb0b6ca470 | yyyuaaaan/pythonfirst | /crk/4.1.py | 1,628 | 4.21875 | 4 | """__author__ = 'anyu'
Implement a function to check if a tree is balanced.
For the purposes of this question, a balanced tree is defined
to be a tree such that the heights of the two subtrees of any # this is so called AVL-tree
node never differ by more than one.
"""
class Node(object):
def __init__(self):
self.data=None
self.left=None
self.right=None
def __str__(self):
return "data:"+str(self.data)+"("+str(self.left)+"|"+str(self.right)+")"+"depth:"+str(self.depth)
#O(n^2) naive algorithm
def height(tree):
if tree.left==None and tree.right==None:
return 0
return max(height(tree.left),height(tree.right))+1
def isbalanced(tree):
if tree.left==None and tree.right==None:
return True
else:
return abs(height(tree.left)- height(tree.right)) <=1 and\
isbalanced(tree.left) and isbalanced(tree.right) # this must be checked
#On each node, we recurse through its entire subtree.
# This means that getHeight is called repeatedly on the same nodes.
# The algorithm is therefore O(N2).
#effcient algorithm, get heights of subtrees and check subtrees if balanced at the same time O(V+E)= O()
# similar to DFS, post-order traversal
def isbalanced3(tree, height=0):
if not tree or not tree.left and not tree.right:
return [True,height]
else:
[isleftbalanced, leftheight] = isbalanced(tree.left,height+1)
[isrightbalanced, rightheight] = isbalanced(tree.right,height+1)
return isleftbalanced and isrightbalanced and \
abs(leftheight-rightheight)<=1
isbalanced3(tree,0)
| true |
2647f5ac10bf8a1150aacaef724d89b9fb323130 | gcbastos/Baseball | /Chapter-1/pythagorean.py | 1,330 | 4.21875 | 4 | ###########################################################################
### Chapter 1 - Pythagorean Theorem in Baseball ###
# Mathletics: How Gamblers, Managers, and Sports Enthusiasts #
# Use Mathematics in Baseball, Basketball, and Football #
###########################################################################
import pandas as pd
import numpy as np
import time
from scipy.optimize import minimize_scalar
df = pd.read_csv("MLB-data.csv")
print("First we will identify the best exponent in the range [1, 3] that minimizes the mean absolute deviation between the Pythagorean equation predicted and the actual win-loss percentage of an MLB team")
print("Using data from 2005-2016 MLB seasons...")
time.sleep(3)
# define the objective function we want to minimize
# this is the sum of the absolute differences between the predicted win and actual win %
def mad(x):
df = pd.read_csv("MLB-data.csv")
df['actual-wl']=df['Wins']/(df['Losses']+df['Wins'])
df['ratio'] = df['Runs']/df['Opp Runs']
return np.mean(abs(df['actual-wl']-(df['ratio']**x/(1+(df['ratio']**x)))))
# minimize mad in the range [1, 3]
res = minimize_scalar(mad, bounds = (1,3), method = 'bounded')
print("The exponent that minimizes the mean absolute deviaton/error is: ", str(res.x))
| true |
05cb6d191208de2e4adb3a32d151f6632514c005 | mar1zzo/cs50-havard-edx | /pset6/mario/less/mario.py | 492 | 4.28125 | 4 | # program that prints out a half-pyramid of a specified height
from cs50 import get_int
def main():
n = get_positive_int()
pyramid(n)
# Prompt user for positive integer
def get_positive_int():
while True:
n = get_int("Height: ")
if n > 0 and n < 9:
break
return n
# Print Mario's right-aligned pyramid
def pyramid(n):
for i in range(1, n + 1):
print(" " * (n - i), end="")
print("#" * (i))
# call main function
main() | true |
63402d3ae65bb580f6154c772e87020ddef8c067 | mothermary5951/videau | /Emacs_Folder/ex12.py | 1,166 | 4.3125 | 4 | from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
#Here's a way to just open that file I made, entitled 'Special.txt":
from sys import argv
script, filename = argv
print "We're going to read %r." % filename
target = open(filename)
#
#And another way to open the same file directly from the command line:
#15:34:32 c3po ~/Desktop/mystuff/Emacs_Folder> python
>>> txt = open("special.txt")
>>> txt.read()
He had tan shoes and pink shoelaces.
He had a pink panama with a purple hat band.
Those are words to an old song.
>>> txt.close()
#
| true |
5a3dd0e29ef7247e928bc232f3c59d5258d928b8 | mothermary5951/videau | /Emacs_Folder/ex3emacs.py | 964 | 4.25 | 4 | # escape sequences ("\\", "\'", "\n", "\t", etc.) are ways to change python's
# default behavior.
# formatters are just that: they format output. """ print it all the way it
# it is entered, %s prettier output, %r output exactly like the input, %d used for numbers
# correct output for print "%r" %x and print "%r" %y:
#'\nSteven\nBradley\nJane\nSwati\\Nt* {Gary}\nChristopher\\Nt* {Jeff}'
#'\nAll none-indented names are still here.\nAll indented names are elsewhere.
#\nWho will stay?\nWho will go?\n'
#correct output for print "%s" %x and print "%s" %y (see below):
Steven
Bradley
Jane
Swati
* Gary
Christopher
* Jeff
All none-indented names are still here.
All indented names are elsewhere.
Who will stay?
Who will go?
x = "\nSteven\nBradley\nJane\nSwati\n\t* Gary\nChristopher\n\t* Jeff"
y = """
All none-indented names are still here.
All indented names are elsewhere.
Who will stay?
Who will go?
"""
print "%s" %x
print "%s" %y
| true |
c0898469906298d211ecd0aed108cc4fb6f0562e | ablimit/cs130r | /solution/labs/lab5/translate.py | 853 | 4.125 | 4 |
date = input("Please input a date in numbers:\n")
months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
days = ("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelveth", "Thirteenth")
teens = ("One", "Two", "Three", "Four", "Fif", "Six", "Seven", "Eigh", "Nine")
month = int(date[0:2])
day = int(date[3:])
# print (month,day)
monthName = months[month-1]
dayName = ""
if day<=13:
dayName = days[day-1]
elif day <20:
dayName = teens[day-10-1] + "teenth"
elif day == 20:
dayName = "Twentieth"
elif day < 30:
dayName = "Twenty "+ days[day-20-1]
elif day == 30:
dayName = "Thirtieth"
elif day == 31:
dayName = "Thirty First"
else:
print ("invalid input")
print (monthName,dayName)
| false |
396255eba575b069f46f96c524aa1632c0c42be4 | ablimit/cs130r | /sep18/bmi.elif.py | 518 | 4.1875 | 4 |
# BMI (body mass index) example for Sep 18
# Formula --> BMI = (weight in punds * 703) / (height in inches)^2
# Below 18.5 Underweight
# 18.5 -24.9 Normal
# 25 - 29.9 Overweight
# 30 & Above Obese
bmi = 22.0
print("Your Body Mass Index is " + str(bmi))
if bmi < 18.5:
print(" Eat more protin.")
elif bmi < 25.0:
print("Awesome ! Just stick to your lifestyle.")
elif bmi < 30.0:
print("Resist some pizza and snacks.")
else:
print("It's time to start training for an Ironman Triathlon !")
| true |
de075c4bcea95e820125af141c0d785a2fbd8246 | ablimit/cs130r | /oct02/tuples.py | 1,340 | 4.1875 | 4 | # THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING CODE WRITTEN BY OTHERS.
# empty tuple creation
myGarage = ("MACBOOK")
print (len(myGarage)) # length should be zero
print(myGarage) # prints contents of the tuple
# a tuple with similar (same types) of items
neighborGarage = ("Veyron", "cat", "shoe")
print ("There are " +str(len(neighborGarage)) + " items in your neighbor's garage.")
# basically all sequence operations can be applied to tuples
# c in seq (existance)
item ="Veyron"
if item in neighborGarage:
print("You have your car in the grage.")
else:
print("Call 911.")
# c not in seq (absence)
item ='Macbook'
if item not in myGarage:
print("Your macbook is on your desk.")
else:
print("Are you starting a business ?")
# myGarage is a tuple which contains different kinds of items
# specifally it contais a floating point number, an integer and a boolean value
myGarage = (3.14, 9, True)
#a + b (concatenation)
print( myGarage + neighborGarage ) # generates a new tuples with the items added together
#s * n (n copy of s)
n = 2
print(neighborGarage*n)
# s[i] (ith item of s )
print(neighborGarage[0])
print(neighborGarage[-1])
# print(neighborGarage[-6])
#s[i:j] (slice of s from ith item to jth item) Note: jth item is exclusive
print(neighborGarage[0:2])
| true |
bbe05e7c59c9573d42918bdf7a5fd1f1447e1c95 | ablimit/cs130r | /solution/labs/lab5/palindrome.py | 465 | 4.15625 | 4 |
userInput= input("Please input a word or phrase of your choice:\n")
word = ""
# eliminate non alphabetic characters (space, !, ? , etc)
for letter in userInput:
if letter.isalpha():
word += letter.lower()
# print ("input",word)
length = len(word)
flag = True
for i in range(0,length):
if word[i] != word[length-1-i]:
flag = False
break
if flag:
print (userInput, "is a palindrome.")
else:
print (userInput, "is NOT a palindrome.")
| true |
348cb653794dd2b0775392036c38f9b6c5bd255a | mauerbac/hh-interview-prep | /general_algorithms/find_highest_product.py | 2,644 | 4.25 | 4 | #https://www.interviewcake.com/question/highest-product-of-3
'''Given an array_of_ints, find the highest_product you can get from three of the integers.
The input array_of_ints will always have at least three integers.
'''
#brute force solution
#create a dict {product: (int1,int2,int3)}
#sort dict to find highest
#run O(n^3)
#Input - array= [1, 10, -5, 1, -100]
#Output -> 10 , -5 , -100
def findHighestProduct():
array= [1, 10, -5, 1, -100]
products = {}
length = len(array)
for x in range(length-2):
for y in range(x+1, length):
for z in range(y+1, length):
temp = array[x] * array[y] * array[z]
print array[x], array[y], array[z]
products[temp] = (array[x], array[y], array[z])
#sort dictionary into list.
sorted_list= sorted(products.keys())
#Take highest value by taking last element and find it's keys in the dict
ans= products[sorted_list[len(sorted_list)-1]]
print products
print "the products are " + str(ans[0]) + " " + str(ans[1]) + " " + str(ans[2])
###############################
# Final complexity -> O(n logn)
#Effiecent solution
def findHighestProduct2():
array = [1, 10, -5, 1, -100]
#sort array -> [-100, -5, 1, 1, 10]
sorted_array = sorted(array)
#ensure list is at least 3 elements
length_array= len(sorted_array)
if length_array > 3:
#pick fist and last elements
num1 = sorted_array[0] #-100
num2 = sorted_array[-1] #10
partial_sum = num1 * num2
#now pick 2nd to last vs 2nd element
# -100 * 10 = -1000
if partial_sum * sorted_array[1] > partial_sum * sorted_array[-2]:
num3 = sorted_array[1]
else:
num3 = sorted_array[-2]
print "The products are " + str(num1) + " " + str(num2) + " " + str(num3)
#error checking
elif length_array == 3:
print sorted_array
else:
print "error with number in array"
findHighestProduct2()
def findHighestProduct():
array= [1, 10, -5, 1, -100]
products = {}
length=len(array)
for x in range(length-2):
for y in range(x+1,length):
for z in range(y+1,length):
temp=array[x] * array[y] * array[z]
print array[x],array[y],array[z]
products[temp]= (array[x],array[y],array[z])
#sort dictionary into list.
sorted_list= sorted(products.keys())
#Take highest value by taking last element and find it's keys in the dict
ans= products[sorted_list[len(sorted_list)-1]]
print products
print "the products are " + str(ans[0]) + " " + str(ans[1]) + " " + str(ans[2])
findHighestProduct()
| true |
f351ff15ea73bf52c0cae75e6564ffdac3372306 | vaibhavg12/exercises | /python/exercises/arrays/dijkstra_national_flag.py | 813 | 4.21875 | 4 | """
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
"""
def sort(arr):
left = 0
right = len(arr) - 1
i = 0
while i <= right:
while arr[i] == 2 and i < right:
arr[i], arr[right] = arr[right], arr[i]
right -= 1
while arr[i] == 0 and i > left:
arr[i], arr[left] = arr[left], arr[i]
left += 1
i += 1
return arr
if __name__ == '__main__':
arr = [1, 0, 0, 2, 0, 1, 1, 2, 2, 2, 1, 0]
print sort(arr)
print sort([1, 0])
print sort([2, 1])
print sort([2, 0])
print sort([1, 2, 0])
| true |
1f548569250c04acedd053ef3f4e73320a40983e | neilsharma2003/basic-bubble-sort-without-loops | /bubblesort.py | 560 | 4.28125 | 4 | '''
Insert 3 scrambled floats or integers and
get them sorted in ascending order where
x < y < z
'''
x = input("Insert first number")
y = input("Insert second number")
z = input("Insert third number")
temporary_var = max(x,y)
x = min(x,y)
y = temporary_var
temporary_var = max(y,z)
y = min(y,z)
z = temporary_var
temporary_var = max(x,y)
x = min(x,y) # A re-sort of x and y in the case where y < x
y = temporary_var
print(x)
print(y)
print(z)
# Because the variables are being constantly re-assigned, the temporary variable is a must
| true |
182bd7ac74036a288116fc6418a514bfea262317 | Ashish1608/Rock-Paper-Scissor-Game | /main.py | 1,080 | 4.1875 | 4 | import random
from art import rock, paper, scissors
def result(user_option, computer_option):
if user_option == computer_option:
return "It's a draw!"
else:
if user_option == 2 and computer_option == 0:
return "You lose."
elif user_option == 0 and computer_option == 2:
return "You win!"
elif user_option > computer_option:
return "You win!"
elif user_option < computer_option:
return "You lose."
options = [rock, paper, scissors]
option_names = ["rock", "paper", "scissor"]
user_choice = int(input("What do you choose? Type '0' for Rock, '1' for Paper or '2' for Scissors: "))
computer_choice = random.randint(0, 2)
if (user_choice < 0) or (user_choice > 2):
print("\nThis option is not available. Please provide valid input")
else:
print(f"\nYou Chose: {option_names[user_choice]}")
print(options[user_choice])
print(f"Computer Chose: {option_names[computer_choice]}")
print(options[computer_choice])
print(result(user_choice, computer_choice))
| true |
be0d4c213b8e030b05207eef450d72c2a0a23b80 | henryztong/PythonSnippet | /基础语法/语法练习/默认值参数.py | 676 | 4.375 | 4 | # 原文:https://docs.python.org/zh-cn/3/tutorial/controlflow.html#defining-functions
# 默认值是在 定义过程 中在函数定义处计算的
# 默认值只会执行一次。这条规则在默认值为可变对象(列表、字典以及大多数类实例)时很重要。比如,下面的函数会存储在后续调用中传递给它的参数:
def f(a,L=[]):
print(L)
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
# 如果你不想要在后续调用之间共享默认值,你可以这样写这个函数:
def f(a,L=None):
print(L)
if L is None:
L=[]
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
print(f(3,L=[]))
| false |
995ad076121e5c9fb5f3e99b7737804cd85dcb15 | YufeiCui/CSCA48 | /tutorials/t1/review.py | 991 | 4.4375 | 4 | # 1. let's say we have a matrix which is a list of lists
row = [0, 0]
matrix = [row, row]
print(matrix) # what's the output?
matrix[0][0] = 1
print(matrix) # what's the output?
row[1] = 3
print(matrix) # what's the output?
# 2. mutating lists
def append_to_list(array, item):
array = array + [item]
def append_to_list2(array, item):
array += [item]
def append_to_list3(array, item):
array.append(item)
my_list = [1, 2, "three"]
append_to_list(my_list, "Hello")
append_to_list2(my_list, "World")
append_to_list3(my_list, "Yufei")
print(my_list) # what's the output?
# 3. More stuff
list1 = [11, 99, [4, 5]]
list2 = list1 # not a true copy! just copies the reference
print(list1 is list2)
list2[2][0] = "BOO!"
print(list1) # what's the output?
list3 = list1[:]
print(list1 is list3)
list3[2][0] = "WOO!"
print(list1) # what's the output?
import copy
list4 = copy.deepcopy(list1)
print(list1 is list4)
list4[2][0] = "FOO!"
print(list1) # what's the output?
| true |
ba2f6bf63abbcdfb9d6d03cad9be7e1320081cac | lucasgarciabertaina/hackerrank-python3 | /strings/full_name.py | 304 | 4.1875 | 4 | def print_full_name(first, last):
text = 'Hello first last! You just delved into python.'
text = text.replace("first",first)
text = text.replace("last",last)
print(text)
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name) | true |
8aa84d0aa56f0af66365d206b349f1fc5703924a | samuellsaraiva/1-Semestre | /l04e06mediaParesImpares.py | 2,279 | 4.25 | 4 | '''' 5. Construa o programa que calcule a média aritmética dos números pares.
O usuário fornecerá os valores de entrada que pode ser um número qualquer par ou
ímpar. A condição de saída será o número -1.
6. Complemente o programa anterior, acrescente o cálculo da média aritmética
dos números ímpares.
Teste 1: numero: 1, 2 e -1. Resposta: Média pares: 2
Média ímpares: 1
Teste 2: numero: 1, 5 e 1-. Resposta: Não tem número par
Média ímpares: 3
Teste 3: numero: 2, 4 e -1. Resposta: Média pares: 3
Não tem número ímpar
Teste 4: numero: -1 Resposta: Não tem número par
Não tem número ímpar
'''
soma_par = 0 # Declaração das variáveis
soma_impar = 0
ct_par = 0
ct_impar = 0
print ('Digite ( -1 ) para sair')
while(True): # while(numero != -1): # Laço de repetição while com o uso do break
numero = int(input("Digite um número: "))
if(numero == -1):
break # Interrompe a repetição while
if(numero%2==0): # Se o resto da divisão de numero por 2 for 0
soma_par = soma_par + numero
ct_par = ct_par + 1
else:
soma_impar = soma_impar + numero
ct_impar = ct_impar + 1
# Fim da estrutura de repetição (while)
if (ct_par != 0): #imprime se algum par for digitado
media_par = soma_par/ct_par
print("Média dos pares: %.2f" %(media_par))
else:
print ("Não tem números pares")
if(ct_impar != 0): # imprime se algum impar for digitado
media_impar = soma_impar/ct_impar
print("Média dos ímpares: %.2f" %(media_impar))
else:
print ("Não tem números ímpares")
''' ALTERAÇÕES:
a. Mostre também a quantidade de números pares.
b. Mostre também a quantidade de números ímpares.
c. Mostre também a quantidade de números digitados.
d. Calcule e mostre a porcentagem dos números pares.
'''
| false |
ebe1eab8651fca1197a90c8908172119954234cc | samuellsaraiva/1-Semestre | /l06e09sequencia_ordem.py | 2,765 | 4.25 | 4 | ''' Sintaxe da estrutura de repetição for (para):
. . .
comando antes do for # Executa uma vez
for variavel in range (inicial , final + 1 , passo):
comando dentro do for # Executa várias vezes.
. . . # . . .
comando dentro do for # Executa várias vezes.
comando depois do for, quando sai do for # Executa uma vez
. . .
O range retorna uma lista.
Para cada valor da variavel no intervalo de inicial até final.
9. Melhore o programa anterior, se o usuário fornecer o valor inicial menor que o
valor final, gere a sequência na ordem crescente. E se o valor inicial for maior que
o valor final, gere a sequência na ordem decrescente.
Teste 1: Entrada: 1, 5 Saída: 1 2 3 4 5
Teste 2: Entrada: 5, 1 Saída: 5 4 3 2 1 ---------------------------- '''
# Executa o for dentro dos limites recebidos, variando de forma crescente ou decrescente
inicio = int(input("Digite o valor inicial: ")) # Recebe os valores inicial e final
fim = int(input("Digite o valor final: "))
if inicio < fim: # inicio < fim - indica ordem crescente
for i in range(inicio, fim + 1, 1):
print(i)
else: # inicio > fim - indica ordem decrescente
for i in range(inicio, fim - 1, -1):
print(i)
''' ALTERAÇÕES:
a. Acrescente a mensagem "Os valores são iguais."
b. Mostre também a quantidade de números gerados na sequência.
c. Mostre também a soma de números gerados na sequência.
d. Deixe o programa mais flexível, permita que o usuário forneça o valor do passo.
DICAS ABAIXO:
if inicio < fim: # a. (inicio < fim, indica ordem crescente)
for i in range(inicio, fim + 1, 1):
print(i)
elif inicio > fim: # (inicio > fim ,indica ordem decrescente)
for i in range(inicio, fim - 1, -1):
print(i)
else: # inicio = fim
print("Os números são iguais!", inicio) # a.
ct = 0 # b.
ct = ct + 1 # Dentro dos dois for.
print ("Quantidade: ", ct) # b.
soma = 0 # c.
soma = soma + i # Dentro dos dois for.
print ('Soma ', soma) # c.
--------------------------------------
quit()
'''
| false |
41c1da5e3c8d1a27ca41f9bdabb264564393fd00 | samuellsaraiva/1-Semestre | /l02e04dose_ideal_agua.py | 1,617 | 4.5625 | 5 | ''' 4. A água é um nutriente essencial. Sem ela, o corpo não pode funcionar com perfeição.
Cada pessoa precisa de uma quantidade diferente de água para hidratar o corpo.
A dose ideal, ou seja, a necessidade diária em litros é calculada através desta fórmula:
massa (em kg) vezes 0,03. Elabore o programa que realize esse cálculo.
- Os operadores aritméticos utilizados em Python:
+ → soma
– → subtração
* → multiplicação
/ → divisão
// → divisão de inteiros
** → potenciação
% → módulo (resto da divisão)
Teste: massa = 71 Resposta: qtd_ideal = 2.13
massa = 60 Resposta: qtd_ideal = 1.7999999
'''
# Dose ideal de água
# Converte o valor para float
massa = float(input("Digite sua massa: "))
qtd_ideal = massa * 0.03 # Notação americana, ponto decimal.
print ('Quantidade ideal:', qtd_ideal)
''' Alterações:
a. Na tela de saída, mostre também o valor da massa.
b. Mostre o resultado com uma casa decimal. ----- DICAS ABAIXO:
print ('Valor da massa: ', massa) # a.
print ("Quantidade ideal: {:.1f}" .format (qtd_ideal)) # b.
O valor 1 significa a quantidade de casas decimais.
print ("Quantidade ideal: %.1f " % (qtd_ideal)) # b.
---
print("\n" * 30) # Limpa a tela.
# str converte o valor para string
print('Quantidade ideal:' + str(qtd_ideal))
print(str(qtd_ideal)+" l","é a quantidade de água ideal")
print(str(qtd_ideal)+" l é a quantidade de água ideal")
'''
| false |
32022d31f8db91159ed6515bb69ae9d15fbcf3de | samuellsaraiva/1-Semestre | /l02e11distancia_dois_pontos.py | 983 | 4.15625 | 4 | '''
11. Construa o programa que, tendo como dados de entrada dois pontos quaisquer do
plano, P(x1,y1) e Q(x2,y2), calcule a distância entre eles. Use a seguinte fórmula:
distância = (x2 - x1)2 + (y2 - y1)2 (raiz quadrada)
Testes: P (1, 2) e Q (1, 2) Resposta: distância = 0
P (1, 2) e Q (5, 7) Resposta: distância = 6.4031242374328485
'''
# bliblioteca de funcões matemáticas
import math
# recebe as coordenadas de p
x1 = float(input("Digite a coordenada x do ponto p "))
y1 = float(input("Digite a coordenada y do ponto p "))
# recebe as coordenadas de q
x2 = float(input("Digite a coordenada x do ponto q "))
y2 = float(input("Digite a coordenada y do ponto q "))
# calcula a distância e atribui à variàvel d
d = (pow(x1 - x2, 2) + pow(y1 - y2, 2)) ** 0.5 #d = math.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))
# mostra o resultado
print("A distância é", d)
| false |
ae2c9cb249983f176551afee663d91916e360f34 | samuellsaraiva/1-Semestre | /l03e09lucro_prejuizo_valor.py | 1,941 | 4.15625 | 4 | ''' 8. Analise o resultado de uma transação comercial. Verifique a situação final do
comerciante trabalhando com os valores lidos, ou seja, o preço de compra e o
preço de venda. Gere a tela de saída com uma das seguintes mensagens:
“Teve lucro.”, “Teve prejuízo.” ou “Os valores são iguais.”.
9. Refaça o programa anterior. Se os valores forem diferentes, mostre também
o valor do lucro em reais ou o valor do prejuízo em reais.
Teste 1: compra = 1000 e venda = 1200. Resposta: Lucro = 200
Teste 2: compra = 1200 e venda = 1000. Resposta: Prejuízo = 200
- Sintaxe do if ... elif ... else:
if condicao1: # A indentação é obrigatória.
print (“Mensagem 1”) # Executa, se a condição1 for verdadeira
elif condicao2:
print(“Mensagem 2”) # Executa, se a condição2 for verdadeira
else
print("Mensagem 3") # Executa, se todos os testes anteriores forem falsos.
print("A transação teve lucro de R$ {:.2f}" .format (lucro) )
Teste 1: compra = 1000 e venda = 1200. Resposta: Lucro = 200
Teste 2: compra = 1200 e venda = 1000. Resposta: Prejuízo = 200
'''
# recebe os valores de compra e venda
compra = float(input("Digite o preço de compra:\n"))
venda = float(input("Digite o preço de venda:\n"))
valor = venda - compra # calcula o lucro da venda
if valor > 0: # valor > 0 significa que venda > compra, ou seja, houve lucro
print("A transação teve lucro de R$ " + str(valor))
print("A transação teve lucro de R$ ", valor)
print("A transação teve lucro de R$ {:.2f}".format(valor))
elif valor < 0: # valor < 0 significa que venda < compra, ou seja, houve prejuízo
print("A transação teve prejuízo de R$ " + str(-valor))
else: # valor = 0 significa que venda = compra, ou seja, não houve lucro ou prejuízo
print("A transação não resultou em lucro ou prejuízo")
| false |
b364405c32e582b2d03f49f26ae5da8820ae12cf | samuellsaraiva/1-Semestre | /pratica_teoria3_retorna_dobro.py | 1,861 | 4.34375 | 4 | ''' - Sintaxe do uso de função
def nome_funcao (par1, par2, ... , parn): # par (parâmetro) - o que a função recebe
script # indentação obrigatória.
. . .
return val1, val2, ... , valn
def --> declara que estamos construindo uma funçao
nome_funcao --> nome da função definido pelo desenvolvedor
script --> código da função
return --> indica o fim da função e o que estará sendo retornado
val1, val2, ... , valn --> Valores retornados
- Chamada da função:
nome_funcao (arg1, arg2, ... , argn) # arg (argumento) - o que envio para a função
- Exemplo:
print() é uma função, ou seja, a ideia de criar uma função é a sua reutilização
em vários momentos do programa
3. Crie a função calcula_dobro. Não use o print dentro desta função.
Ele recebe um valor, calcula o dobro e retorna o
dobro do valor recebido. A função principal chama a função passando um valor
inteiro e mostra o valor retornado pela função calcula_dobro ----- '''
def calcula_dobro (p_valor):
dobro = p_valor * 2
return dobro
if __name__ == '__main__': # Função principal.
valor = int(input("Valor: "))
valor_retorno = calcula_dobro(valor)
# O valor retornado pela função é armazenado na variável valor_retorno
print(valor_retorno)
''' ALTERAÇÕES:
a. Acrescente a função calcula_triplo. Ela recebe um valor, calcula o triplo e
retorna o valor calculado.
A função principal mostra o valor retornado pela função calcula_triplo.
----- DICAS:
def calcula_triplo(p_valor): # a.
triplo = p_valor * 2
return triplo
valor_retorno2 = calcula_triplo(valor) # Dentro da função principal.
print(valor_retorno2)
'''
| false |
2d7124e5c1394f9bc691a9646134b460dec43df2 | samuellsaraiva/1-Semestre | /l03e06positivo_nulo_negativo.py | 1,513 | 4.375 | 4 | ''' 6. Elabore o programa que leia um número qualquer e verifique
se ele é positivo, negativo ou nulo.
- Sintaxe do if ... elif ... else:
if condicao1: # A indentação é obrigatória.
print (“Mensagem 1”) # Executa, se a condição1 for verdadeira
elif condicao2:
print(“Mensagem 2”) # Executa, se a condição2 for verdadeira
else
print("Mensagem 3") # Executa, se todos os testes anteriores forem falsos.
Teste 1: numero = 4 Saída: positivo
Teste 2: numero = 0 Saída: nulo
Teste 3: numero = -4 Saída: negativo
'''
numero = float(input("Digite um número: ")) # Lê, converte e atribui à variável
if numero > 0:
print("Número positivo") # Imprime, se numero for maior que 0
elif numero < 0:
print("Número negativo") # Imprime, se numero for menor que 0
else:
print("Número nulo") # Imprime, se numero for igual a 0
''' ALTERAÇÕES:
a. Além da mensagem, mostre também o número digitado pelo usuário.
b. Se o número for positivo, mostre a mensagem, a variável numero e o dobro;
se negativo, mostre a mensagem, a variável numero e o triplo;
se nulo, mostre a mensagem, a variável numero.
--- DICAS ABAIXO:
print ("Valor digitado: ", numero) # a
if numero > 0:
print("Número positivo, ", numero, "Dobro do número ", numero *2)
elif . . .
'''
| false |
cda2709495c5c388196dd0c8b3e215aa926888f0 | carson24x7/2D-Space-War-Game | /strings_and_lists.py | 2,116 | 4.375 | 4 | name = "Carson Miller"
print(name)
print(type(name))
num_chars = len(name)
print(num_chars)
print(name[1])
print(name[2])
print(name[6])
print(name[7])
print(name[8])
print(name[9])
print(name[10])
print(name[11])
print(name[12])
#print(name[13])
print()
print(name[-2])
print(name[-1])
print()
for character in name:
print(character)
print()
pi_digits = [3,1,4,1,5,9,2,6]
movie_titles = ['Avengers Endgame','Avengers Infinity War','Cars','Spiderman Far From Home','Inside Out','Up']
print(pi_digits)
print(type(pi_digits))
num_items = len(pi_digits)
print(num_items)
print()
print(pi_digits[0])
print(pi_digits[1])
print(pi_digits[2])
print(pi_digits[4])
#print(pi_digits[8])
print()
print(pi_digits[-3])
print(pi_digits[-2])
print()
for word in pi_digits:
print(word)
print()
for digit in pi_digits:
if digit > 5:
print(digit)
print()
for word in movie_titles:
print(word[0])
print()
for characters in movie_titles:
num_chars = len(characters)
print(num_chars)
# You try...
# 1. Write a line of code that stores your name in a string
# Carson Miller
# 2. Write a line of code that prints the number of characters in your name.
#13
# 3. Write lines of code that print the first, second, and last characters in your name.
# A,R,M,I,L,L,E,R
# 4. Write a loop that prints each character of your name on a separate line.
#C,A,R,S,O,N M,I,L,L,E,R
# 5. Write a line of code that stores the first 8 digits of pi in a list.
#31415926
# 6. Write a line of code that prints the third and second to last digits of your pi list.
#print(digit[-3]) print(digit[-2]) - 9, 2
# 7. Write a loop that prints each of your digits of pi that is greater than 6.
#9,6
# 8. Write a line of code that stores 6 movies you like in a list.
# Avengers Endgame, Avengers Infinity War, Spiderman Far From Home, Cars, Inside Out and Up.
# 9. Write a loop that prints the first character of each movie title.
#A, A, C, S, I, U.
# 10. Write a loop that prints the number of characters in each movie title.
#16, 21, 4, 23, 10, 2
| false |
169543870f1fff2f3875c6cab8ca1491d3a2b6cb | JackHumphreys/Selection | /date_convertor.py | 1,214 | 4.15625 | 4 | #Date Exercise
date = input("Please enter date as DD/MM/YY: ")
day_input = int(date[:2])
month_input = int(date[3:5])
year_input = int(date[6:8])
if day_input == 1:
day = ("1st")
elif day_input == 2:
day = ("2nd")
elif day_input == 3:
day = ("3rd")
elif day_input >= 4 and day_input <=30:
day = ("{0}th".format(day_input))
else:
day = ("N/A")
if month_input == 1:
month = ("January")
elif month_input == 2:
month = ("February")
elif month_input == 3:
month = ("March")
elif month_input == 4:
month = ("April")
elif month_input == 5:
month = ("May")
elif month_input == 6:
month = ("June")
elif month_input == 7:
month = ("July")
elif month_input == 8:
month = ("August")
elif month_input == 9:
month = ("September")
elif month_input == 10:
month = ("October")
elif month_input == 11:
month = ("November")
elif month_input == 12:
month = ("December")
else:
month = ("N/A")
if year_input >= 30:
year = ("19{0}".format(year_input))
elif year_input <= 30:
year = ("20{0}".format(year_input))
print(day, month, year)
| false |
1a29c0052510499b6522c96e19cd7d86476ae3ad | FelipeDamascena/Treinando-Python | /PythonExercicios-CursoEmVideo/eX004.py | 488 | 4.125 | 4 | ## Faça um programa que leia o que foi escrito no teclado e mostre na tela seu tipo primitivo e todas as informações
a = input('Digite algo: ')
print('Seu tipo primitivo é ', type(a))
print('Só tem espaços? ', a.isspace())
print('É um numero? ', a.isnumeric())
print('É alfabetico? ', a.isalpha())
print('É alfanumérico? ', a.isalnum())
print('Está em letra maiuscula?', a.isupper())
print('Está em letra minuscula?', a.islower())
print('Está capitalizada? ', a.istitle())
| false |
aaf3f190a82329ae42baeb90b5ddafe1d8808e51 | wtomalves/exerciciopython | /ex035triangulo.py | 663 | 4.21875 | 4 | print('***' * 7)
print('Para formarmos um triângulo é necessário tres retas de diferentes centimentos. \nContudo podemos ter dificuldade para a formação de triângulo devido a algumas regras. \nPara saber se os dados que você possui conseguira realizar um triangulo, por favor forceça dos dados!,')
print('***' * 7)
a = int(input('Digite o primeiro número lado "a":'))
b = int(input('Digite o segundo número lado "b":'))
c = int(input('Digite o terceiro número lado "c":'))
if a < b + c and b < a + c and c < a + b:
print("Com esses dados conseguimos fazer um triângulo!")
else:
print(' Com esses dados não conseguimos formar um triângulo!')
| false |
17399c42aaabac73f65215a664bba90f1996bf8a | wtomalves/exerciciopython | /ex075b.py | 814 | 4.15625 | 4 | núm = (int(input('Digite um número: ')), \
int(input('Digite outro número: ')), \
int(input('Digite mais um número: ')),\
int(input('Digite o último número: ')))
print(f'Você digitou os valores {núm}')
print(f'O valor 9 apareceu {núm.count(9)} vezes!')
if 3 in núm:
print(f'O valor 3 apareceu na {núm.index(3)+1}º posição')
else:
print('O valor 3 não foi digitado em nenhuma posição!')
print(f'os números pares sao:', end= ' ')
for n in núm:
if n % 2 == 0:
print(f'{n}', end= ' ')
#Código do professor Guaná!
'''Considerações: Nestecódigo temos uma diminuição de linhas devido ao uso das funções:
núm.count(9) contar quantas vezes o número foi digitado.
{núm.index(3) fará a verificação em qual posição o número aparece.''' | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.