blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f151f7251513e73367ba365a015df3a0f1fdd07e | zzq5271137/learn_python | /17-生成器/02-my_generator_1.py | 1,366 | 4.46875 | 4 | """
自定义生成器
"""
"""
生成器可以通过函数产生; 如果在一个函数中出现了yield表达式, 那么这个函数将不再是一个普通的函数, 而是一个生成器函数,
yield一次返回一个结果, 并且会冻结当前函数的状态, 当下一次外部调用了next()函数或__next__()方法,
会从上一次冻结的那一行继续往后执行;
"""
def my_generator(): # 和定义函数非常像, 都是使用def关键字
yield 1 # 碰到yield语句时, 会返回该值, 并且将代码冻结在这里, 当下次再次调用时, 会从下一行继续往下执行
yield 2
yield 3
# next()函数可以迭代生成器返回的值, 在调用next()函数时, 会执行我们在定义my_generator()时写的代码
# 其实使用next()函数, 底层还是调用的my_gen的__next__()方法
my_gen = my_generator() # 注意, 这里返回的不是my_generator()里面的值, 而是返回一个生成器
print('my_gen的类型为: %s' % type(my_gen)) # generator
print(next(my_gen))
print(next(my_gen))
print(next(my_gen))
print("###############################################")
# __next__()方法也可以迭代生成器返回的值, 在调用__next__()方法时, 会执行我们在定义my_generator()时写的代码
my_gen = my_generator()
print(my_gen.__next__())
print(my_gen.__next__())
print(my_gen.__next__())
| false |
a80383ff71c1ecea437c30e19ee11f68351ec9c9 | zzq5271137/learn_python | /01-介绍/06-type_convert.py | 1,042 | 4.21875 | 4 | """
数据类型的转换
"""
# 浮点类型转换为整型
print("浮点类型转换为整型")
a = 4.9
b = int(a) # 直接舍弃掉小数部分, 不会四舍五入
print(b)
print(type(b))
print("###############")
# 将字符串类型转换为整型
print("将字符串类型转换为整型")
c = "123"
d = int(c) # int()函数规定字符串不可以包含非数字的字符, 所以不可以转换浮点类型的字符串(想要转换浮点类型的字符串, 使用float()函数)
print(d)
print(type(d))
print("###############")
# 将整型/浮点类型转换为字符串
print("将整型/浮点类型转换为字符串")
e = 123
e_str = str(e)
print(e_str)
print(type(e_str))
f = 123.9
f_str = str(f)
print(f_str)
print(type(f_str))
print("###############")
# 将整型转换为浮点类型
print("将整型转换为浮点类型")
g = 2
h = float(g)
print(h)
print(type(h))
print("###############")
# 将字符串转换为浮点类型
print("将字符串转换为浮点类型")
i = "123.9"
j = float(i)
print(j)
print(type(j))
| false |
642d9c8b27486ea83b434a72ff119256a11d2956 | zzq5271137/learn_python | /20-内存管理/01-object_pool.py | 959 | 4.25 | 4 | """
对象池
"""
"""
小整数对象池:
在一个程序中, [-5, 256]之间的数字是经常被使用的, 因此Python在运行程序过程中, 定义好了一个小整数池,
也就是说从-5到256之间的数字都是提前在内存中建立好的, 不会被系统回收, 并且如果你以后创建了一个变量是在这个范围之内,
那么也都是同一个对象;
"""
# 同一个对象, 因为1在[-5, 256]之间
a = 1
b = 1
print(id(a))
print(id(b))
# 不是同一个对象, 因为-6不在[-5, 256]之间
a = -6
b = -6
print(id(a))
print(id(b))
print("########################################")
"""
字符串对象池:
对于只包含英文字符的字符串, 同样的字符串共用同一个对象
"""
# 是同一个对象, 因为字符串的字符一样
a = 'helloworld'
b = 'helloworld'
print(id(a))
print(id(b))
# 不是同一个对象, 因为字符串的字符不一样
a = 'helloworld1'
b = 'helloworld2'
print(id(a))
print(id(b))
| false |
098e5e698dcee74faf954151360ebe50246dcac3 | zzq5271137/learn_python | /08-函数/02-func_args_1.py | 589 | 4.40625 | 4 | """
函数的参数
"""
# 位置参数与关键字参数
# 位置参数: 就是在调用函数时, 按照函数的形参给定的顺序进行传参
# 关键字参数: 就是在调用函数时, 按照函数的形参名称进行传参(参数的顺序可以随意)
def greet(name, greetstr):
print("{}, {}".format(greetstr, name))
# 位置参数传参
greet("zzq", "Good morning")
# 关键字参数传参
greet(greetstr="Good night", name="zzq")
# 混合传参
greet("zzq", greetstr="Good afternoon")
# 混合参数的注意事项: 位置参数必须要在关键字参数的前面
| false |
8904d4d3551369091dcf0222959812be336416e8 | romero23082000/MisionTic_2022_G6 | /Ejercicios2.py | 1,011 | 4.375 | 4 | # Un niño que cursa tercero de primaria necesita aprender a calcular el
# área para un triangulo rectángulo
# 2. Una pequeña empresa necesita saber en cuanto puede vender el
# producto que fabrica. De dicho producto conocemos el nombre, el código
# y el costo de producción; es necesario que el precio de venta incluya
# 120% como utilidad y un 15% de impuestos.
# 3. Cada estudiante propone 1 ejercicio donde realice las etapas de
# definición del problema y el análisis.
# Ejercicio numero 1
# nombre = input('Nombre del estudiante ')
# print(' la formula para calcular el area de un triangulo es base por altura dividido entre 2')
# print(nombre, "Inserte lo datos para calcular el area del triangulo")
# base = float(input('Base del triangulo-:'))
# altura = float(input('altura del triangulo del triangulo-:'))
# formula = (base * altura)/2
# print('El area del triangulo es-: ', formula)
# Ejercicio numero 2
print('Inserte el nombre del producto')
print(int('inserte el codigo del producto'))
| false |
81ecefccdbd6736e6005211fc04a5a78152d26a6 | romero23082000/MisionTic_2022_G6 | /s15/Reto1.py | 322 | 4.25 | 4 | multiplo = int(input("digite un numero entero: "))
print(f"los multiplos de {multiplo} son: ")
if multiplo % 3 == 0 and multiplo % 5 == 0:
print("Es multiplo de 3 y de 5")
elif multiplo % 3 == 0:
print("Es multiplo de 3")
elif multiplo % 5 == 0:
print("Es multiplo de 5")
else:
print("no es un multiplo")
| false |
05ce106a3490e8fd7e1f9c9d25258ccf3a61e397 | BSidesAugusta/STEM2018 | /Lab 5 - ConvertTemp.py | 692 | 4.40625 | 4 | #############################################
# Filename: Lab 5 - ConvertTemp.py
# Developer: BSides Augusta STEM
# Language: Python 3.4
# Description: This program prompts the user for the temperature
# in Fahrenheit and converts it to Celsius. The Celsius
# temperature value is displayed to the screen and whether
# the temperature is perfect, too cold or very hot.
print ('Enter the Fahrenheit temperature: ')
tempF = float( input() )
tempC = (tempF - 32.0)*(5.0/9.0)
print ('The Celsius temperature is: ', tempC, ' degrees')
if (tempF > 85):
print ('It is very hot!')
elif (tempF < 60):
print ('It is too cold!')
else:
print ('The temperature is perfect!')
| true |
a0c45e6312132663f8fd347366332451a11ba32c | AaronDonaldson74/Python-Notes | /ternary_operators.py | 396 | 4.1875 | 4 | role = 'admin'
# One line ternary operator statment
auth = 'can access' if role == 'admin' else 'cannot access'
print(auth)
# Traditional coding method for the same thing.
if role == 'admin':
auth = 'can access'
else:
auth = 'cannot access'
print(auth)
""" second example """
role = 'Mickey'
love = 'loves Daisy' if role == 'Donald' else "isn't Daisy's lover"
print(f'{role} {love}') | false |
9b315ef5fa212ce8174d09929f0ff1fbd7894020 | tmargarian/ML-Assignments | /HW1/Ranjan/regression_utils.py | 1,602 | 4.25 | 4 | import numpy as np
from sklearn.metrics import r2_score
def helloworld():
#print("Hello, world!")
print("uncomment me")
return
def simple_linear_regression(x, y):
"""
Implement simple linear regression below
y: list of dependent variables
x: list of independent variables
return: b1- slope, b0- intercept
"""
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = sum( (x[i] - x_mean) * (y[i] - y_mean) for i in range(len(x)))
denominator = sum((x[i] - x_mean) ** 2 for i in range(len(y)))
b1 = numerator / denominator
b0 = y_mean - b1 * x_mean
######################
return b1, b0
def multiple_regression(x, y):
"""
x: np array of shape (n, p) where n is the number of samples
and p is the number of features.
y: np array of shape (n, ) where n is the number of samples
return b: np array of shape (n, )
"""
### YOUR CODE HERE ###
X = x.values
b = np.linalg.inv(X.T @ X) @ X.T @ y
######################
return b
def predict(x, b):
### YOUR CODE HERE ###
######################
return yhat
def calculate_r2(y, yhat):
# y: np array of shape (n,) where n is the number of samples
# yhat: np array of shape (n,) where n is the number of samples
# yhat is calculated by predict()
### YOUR CODE HERE ###
# calculate the residual sum of squares (rss) and total sum of squares (tss)
######################
r2 = 1.0 - rss/tss
return r2
def check_r2(y, yhat):
return np.allclose(calculate_r2(y, yhat), r2_score(y, yhat))
| true |
1a89bffeecc593ad5cffc874124817513e6262f1 | DianaJConnolly/TechAcademy | /module36.py | 1,761 | 4.25 | 4 |
#function to sum list values using for loop:
def sumFor(numl):
sumf = 0
for n in numl:
sumf += n
return sumf;
#function to sum list values using for while loop:
def sumWhile(numl):
sumw = 0
count = 0
while count < len(numl):
sumw += numl[count]
count += 1
return sumw;
#recursive function to add elements of list:
def sumRec(numl):
sumR = 0
for n in numl:
if type(n) == type([]): #if the element is a list
sumR += sumRec(n) #call the function recursively to add the internal list elements
else:
sumR += n #else just add the next element
return sumR;
#alternately combine two lists and return alternated list.
def alternate(lst1, lst2):
altl = []
if not(len(lst1) == len(lst2)):
print "error! lists must be of same size, exiting...."
return -1
#need enumerate to get index so we can access different lists
for index, item in enumerate(lst1, start=0):
altl.append(lst1[index])
altl.append(lst2[index])
return altl
## create a custom comparator for findLargest() function
def comparator(x, y):
rtn = 0
str1 = str(x) + str(y)
str2 = str(y) + str(x)
if str1 < str2:
rtn = 1
if str1 > str2:
rtn = -1
return rtn
def findLargest(numList):
numList.sort(comparator)
#convert to string to concatenate
numString = ""
for n in numList:
numString += str(n)
#convert back to integer value
return numString
#use .format to do truncate strings of different lengths based on size parameters
def strTruncate(str):
#print str
strTemp = ""
l = len(str)
if l == 0:
strTemp = "your string is empty"
if l != 0 and l <= 10:
strTemp = '{:.5}'.format(str)
elif l > 10 and l <= 30:
strTemp = '{:.10}'.format(str)
else:
strTemp = "your string is just too big to process"
return strTemp
| true |
eadd04d37da2d7222a4a7b682b69d9371f5e6fc4 | Jonathan-Woo/ESC180-Computer-Programming | /Lab 1/hello.py | 549 | 4.1875 | 4 | #Problem 1
print ("Hello, Python")
#Problem 2
strName1, strName2 = "Luna Wu", "Jonathan Woo"
print ("Hello,", strName1)
print ("Hello,", strName2)
#Rename variables (Problem 4)
strName1, strName2 = "Prof. Cluett", "Prof. Thywissen"
#Problem 3
print(f'Hello, {strName1} and {strName2}. Your names are {strName2} and {strName1}. Hi there. Your names are still {strName1} and {strName2}.')
#Problem 5
greetee = input("What's your name? \n")
if greetee.upper() == "LORD VOLDEMORT":
print("I'm not talking to you.")
else:
print(f'Hello {greetee}')
| true |
032d5d95a795c42ca8fcd6a3be3223bc2e1d388a | Annahariprasad/Python-Programs | /Variables,Data Types & Typecasting.py | 970 | 4.5625 | 5 | #These are Variables
a=57 #Integer datatype
b=86.7 #Float datatype
c="Hello World!" #string datatype
d=3+5j #complex datatype
e='Hi I am Python' #string datatype
print(a+b) #Adding two numbers
print(str(a)+str(b)) #Combining two numbers with String Format
print(a+d) #Adding integer with complex number
print(c+', '+e) #Combining two strings with adding coma
#Here We can't Combine the string with numeric data types
print(type(a)) #print the variable datatype --> (Integer)
print(type(b)) #print the variable datatype --> (Float)
print(type(c)) #print the variable datatype --> (String)
print(type(d)) #print the variable datatype --> (Complex)
print(float(a)+b) #Here we change integer datatype into float datatype and add with float number
#Here can't convert complex into other any datatype
print(str(a)+' '+c+' '+e) #Here we convert integer into string datatype
print(5*c) #Here we print the string five times by multiplying with five integer
| true |
6ed48ccd165b1b70462196a2dfa793a8ad2b16b8 | Annahariprasad/Python-Programs | /Dictionary & Its Functions.py | 2,434 | 4.21875 | 4 | #Dictionary
#Dictionary is Key-Value Pairs
laptops={
'Annahari':'Asus Vivobook 14', #This is Laptops We are using now
'Majahar':'HP CS3006',
'Gnaneswar':'HP Pavilion Gaming',
'Sudheer':'Dell Insipirin'
}
#This is Electronic Gadgets We are using now
devices={
'Annahari':{'Mobile':'Honour 9 lite','Laptop':'Asus Vivobook','Earphones':'Oneplus Wireless Z'},
'Majahar':{'Mobile':'Redmi Y1','Laptop':'HP CS3006','Earphones':'Touchtek Wireless'},
'Gnaneswar':{'Mobile':'Realme Xt','Laptop':'HP Pavilion Gaming','Earphones':'Boat Earphones'},
'Shabareesh':{'Mobile':'Realme 2 Pro','Laptop':'HP Core i5','Earphones':'Ptron Wireless'}
}
print(type(laptops)) #Printing the type of variable and this is dictionary type
print(laptops) #Printing the laptops dictionary
print(laptops['Annahari'],end=", ") #Printing the dictionary with specific key
print(laptops['Majahar'],end=", ") #Printing the dictionary with specific key
print(laptops['Gnaneswar'],end=", ") #Printing the dictionary with specific key
print(laptops['Sudheer']) #Printing the dictionary with specific key
laptops['Adnan']='HP Gaming Laptop' #Adding the another key and it's value in the laptops dictionary
print(laptops) #Printing the laptops dictionary after adding the new key and it's value
del laptops['Adnan'] #Delete the specific key and it's value
print(laptops) #Printing the laptops dictionary after deleting the specific key and it's value
laptops=devices.copy() #Here we copying the devices dictionary into the laptops dictionary by using copy() Function
del devices['Annahari'] #Here we deleting the key value in the devices dictionary
print(devices) #Printing the devices dictionary
print(laptops) #Printing the laptops dictionary
print(laptops.get('Gnaneswar')) #Here We display the specific key value by using get() Function
print(laptops.update({'Finishing':'These are Electroic Devices we are using'}))#Here we Adding or Update the new key in the laptops dictionary
print(laptops)#Printing the laptops dictionary after update the new key and it's value
print(laptops.keys()) #Printing the keys only present in the laptops dictionary by using the key() Function
print(laptops.items()) #Printing the keys and it's value by using the items() Function | false |
d990c47a8af5f132d17e8e2f18460437713a591b | Annahariprasad/Python-Programs | /Prime Numbers.py | 1,050 | 4.1875 | 4 | '''
print('This is numbers from 1 to 20: ')
for i in range(1,21):
print(i, end=' ')
print()
print('This is even numbers from 1 to 20: ')
for i in range(1,20):
if i%2==0:
print(i,end=' ')
print()
print('This is odd numbers from 1 to 20: ')
for i in range(1,20):
if not i%2==0:
print(i,end=' ')
print()
print('This is prime numbers from 1 to 20:')
for i in range(1,20):
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=' ')
'''
#PRIME NUMBERS
'''
This program check the number is prime or not
'''
def prime(given_number):
'''
This function check the number is prime or not
'''
for i in range(2,given_number):
if given_number%i==0:
return 'Not Prime Number'
break
else:
return 'Prime number'
break
a = prime(6)
print(a)
'''
print('Prime Numbers : ',end=' ')
pr = list(filter(prime,range(2500)))
print(pr)
'''
| false |
e2c4cca5e9fb4f78499a6810c4ec53d2fb4cd320 | awdimmick/GCSE-CS | /data_representation/bitmaps.py | 1,770 | 4.21875 | 4 | import set_colour as sc
# Store the 0s and 1s that make up our bitmap in a string
bitmap_data = "01010101 10101010 01010101 10101010 01010101 10101010 01010101 10101010 "
# Split bitmap_data at each space - i.e. into the chunks that will make up each row
bitmap_rows = bitmap_data.split()
sc.set_colour("RED")
# Loop through each row
for row in bitmap_rows:
# Loop through each 0 or 1 (value) within each row
for value in row:
if value == "0":
print(" ", end="") # end = "" is a special argument that we can pass to print() to stop it from printing a
# newline
elif value == "1":
print("*", end="") # try replacing * with \u2588 - this is a Unicode 'block' character - you can find other unicode characters to use here: https://unicode-table.com/en/#2588
print()
# Task 1 - Replace the 0s and 1s in bitmap_data with the values for your own design
# Task 2 - Adapt your program so that it can handle multiple colours by using two bits for each pixel. For example,
# 00 = black, 01 = white, 10 = blue and 11 = red.
# To do this, you will need to find a way to look at every two characters instead of every 1 character within each row.
# You might want to slice your rows every 2 characters (think back to your Manipulating Strings assignments).
#
# You can use the set_colour() procedure to change the colour of the output generated by print(), for
# example, the following code will print "Hello!" in red and then reset the output back to normal:
#
# set_colour("RED") # set to red
# print("Hello!") # print message
# set_colour("RESET") # reset output
#
# You can see which colours you can use by looking inside the set_colour() procedure's code at the start of the program.
| true |
3ff36caf5d93cb8792817ccfcef6889e99ea0417 | danielsaad/oficina-matplotlib | /Exemplos/exemplo-1.py | 740 | 4.125 | 4 | """
Autor: Daniel Saad Nogueira Nunes
Comentários: Exemplo minimalista da plotagem da função f(x) = x utilizando
a biblioteca Matplotlib
"""
import matplotlib.pyplot as plt
import numpy as np
# cria um objeto figura e o coloca em fig
fig = plt.figure()
# da figura criada, é alocada uma matriz 1x1 de gráficos
# ax corresponde a matriz 1
ax = fig.add_subplot(111)
# gera o dominio da função y = x
# domínio da função [0,10) com amostras de tamanho 0.1
x = np.arange(0,10,0.1)
# Gera a imagem da função y = x
y = np.array([ a for a in x ])
# Plota a imagem
l = plt.plot(x,y)
# Coloca um título correspondente na figura
t = ax.set_title("Gráfico da Função " r"$f(x) = x$")
# Mostra o resultado na tela
plt.show()
| false |
c592aefd12f2c7f2addb1c4c66e77c7a662fad8b | TLobaOriginal/PythonApplications | /Applications/AlarmClock/test.py | 2,148 | 4.3125 | 4 | import tkinter as ty
from tkinter import *
from tkinter import messagebox
import os, time, winsound
import tkinter
def createWidgets():
#We use this to create a label and then we place the label on the 0th row
label1 = Label(root, text="Enter in the time in hh:mm -")
label1.grid(row = 0, column=0, padx=5, pady=5)
#This will take user input. It acts as a text box
global entry1
entry1 = Entry(root, width=15)
entry1.grid(row=0, column=1)
label2 = Label(root, text="Enter the message of alarm: ")
label2.grid(row=1, column=0, padx=5, pady=5)
global entry2
entry2 = Entry(root, width=15)
entry2.grid(row=1, column=1)
but = Button(root, text="Submit", width=10, command=submit)
but.grid(row=2, column=1)
global label3
label3 = Label(root, text="")
label3.grid(row=3, column=1)
def message1():
global entry1, label3
AlarmTimeLabel = entry1.get()
label3.config(text="The Alarm is Counting...") #We configure the text to say...
#The alarm clock is given a label
messagebox.showinfo("Alarm Clock", f"The Alarm time: is {AlarmTimeLabel}")
def submit():
global entry1, entry2, label3
AlarmTime = entry1.get()
message1()
currenttime =time.strftime("%H:%M") #We set the time to the current time
alarmmessage = entry2.get()
print(f"The Alarm time is: {AlarmTime}")
while AlarmTime != currenttime:
currenttime = time.strftime("%H:%M")
time.sleep(1)
if AlarmTime == currenttime: #When the right time is received then we play the alarm sound
print("Playing Alarm Sound....")
winsound.PlaySound("*", winsound.SND_ASYNC)
label3.config(text="Alarm Sound Playing>>>>>")
messagebox.showinfo("Alarm Message", f"The Message is: {alarmmessage}")
root = ty.Tk()
root.title("Alarm Clock")
root.geometry("400x150")
createWidgets()
root.mainloop() | true |
a2abe5bac184d9ebc69f31c454b45c707c9f9040 | Sophie-Hughes/obds_training | /Python/maximum.py | 397 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 10:32:31 2020
Find maximum number from list of numbers
@author: Sophie
"""
number_list = [26, 54, 93, 17, 77, 31, 44, 44, 20]
number_max = number_list[0]
for number in number_list:
if number > number_max:
number_max = number
print('The maximum number is', number_max)
number_max.selection_sort | true |
0cd2f7dd7234ea7bd64c4cd36ba2f44411bed5eb | Sophie-Hughes/obds_training | /Python/bubble_sort.py | 1,033 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 13:41:43 2020
@author: Sophie
"""
number_list = [26, 54, 93, 17, 77, 31, 44, 55, 20]
# bubble sort of number_list
# Outer loop - stepping loop - j defines length of list, going down to 0 starts length of list and goes down to 1 by increments of 1
# Stepping loop
for j in range(len(number_list), 1, -1):
for i in range(0, j-1, 1): # inner loop - swapping loop - inner loop pushes largest number to end
if number_list[i]>number_list[i+1]: # pairwise comparison
temp = number_list[i] # creating temporary variable
number_list[i] = number_list[i+1] # swapping varibles part 1: create duplicate
number_list[i+1] = temp
print(number_list)
#print(number_list[i], number_list[i+1])
# tip - instead of using i and j - give it a meaningful variable name - makes following code easier
# better for debugging
# j = step iteration
# i = current index of position in list
| true |
e9472fb31e7ae276f3523abefcf13df21fdc92ee | xufanxingxing/PythonPractice | /min_cost.py | 2,398 | 4.125 | 4 | """
There are n islands connected by m boat rides. Each boat ride starts from island p and arrives at island q with a cost c.
Now given all the islands and boat rides, together with starting island src and the destination dst, find the least cost route from src to dst with up to t stops. (Note: number of stops is the number of island IN BETWEEN src and dst.). If there is no such route, output -1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,700],[0,2,500],[]]
src = 0, dst = 2, t = 1
Output: 200
Explanation:
The graph looks like this:
0 -> (100) 1 -> (100) 2
0 -> (500) 2
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, t = 0
Output: 500
Explanation:
The graph looks like this:
0 -> (100) 1 -> (100) 2
0 -> (500) 2
"""
# print "Hello World"
import sys
def min_cost_route(src, dst, t, n, edges):
if not edges or len(edges) == 0:
return -1
graph = generate_graph(edges)
visit = set()
visit.add(src)
min_cost=[sys.maxsize]
dfs(graph, src, dst, t + 1, 0, visit, min_cost)
if min_cost[0] == sys.maxsize:
return -1
return min_cost[0]
def generate_graph(edges):
graph = {}
# edges = [[0,1,100],[1,2,100],[0,2,500]] -> { 0 : [1, 100],
for e in edges:
new_src = e[0]
new_dst_cost = [e[1], e[2]]
if not new_src in graph.keys():
graph[new_src] = []
graph[new_src].append(new_dst_cost)
return graph
def dfs(graph, src, dst, t, curr_cost, visit, min_cost):
if t < 0:
return
if src == dst:
# print("curr_cost={}, min_cost={}".format(curr_cost,min_cost))
min_cost[0] = min(curr_cost, min_cost[0])
# print("curr_cost={}, min_cost={}".format(curr_cost,min_cost))
return
next_step_list = graph[src]
for step in next_step_list:
print("step={}, curr_cost={}".format(step,curr_cost))
new_src = step[0]
new_cost = step[1]
if not new_src in visit:
visit.add(new_src)
dfs(graph, new_src, dst, t - 1, curr_cost + new_cost, visit, min_cost)
visit.remove(new_src)
return
edges = [[0,1,100],[1,2,100],[0,2,100],[2,1,100],[0,1,400]]
print(generate_graph(edges))
# def min_cost_route(src, dst, t, n, edges):
print(min_cost_route(0, 3, 3, 3, edges))
| true |
6566906da031485bd82dc66ea4a1660dc5f526e1 | Cassie-bot/Final-Project | /Module 1.py | 1,990 | 4.21875 | 4 | #Casandra Villagran
#3/4/2020
#The story is about a boy/girl who has lost their memory and is searching for their family at the same time.
#But in order to do so they must go through the spooky woods.
import time
#Chapter 1
print("CHAPTER 1")
name= input("Hello, Welome! What is your name? ")
print ("Nice to meet you " + name)
time.sleep(1)
#While Loop
i = "yes"
while i:
i =input("Are you ready to get this adventure started? ")
if i == "yes":
print("Great, Let's get started!")
#User is ready to play!
time.sleep(1)
print("Background: Today is Monday, it's been a month since you last seen your family. You fell into a ditch and were lucky to survive, but sadly you lost your memory.")
time.sleep(10)
print("Present day: It was a dark fogy night in the woods and there was no one to be seen, but an old man on a rocking chair.")
time.sleep(10)
print(name + " if you talk to the man you might get some information on where your family is.")
#The user will have the option to ask the man for help which leads to getting a map that will get user through the woods
#Or the user doesn't have to talk to the man, but he wont have a map to help him in the woods
time.sleep(1)
answer= input("Want to talk to him? Type 'yes' or 'no' ")
if answer== "yes":
print("Great, let's go")
print("TO BE CONTINUED...")
break
elif answer== "no":
print("To late he is walking your way!")
print("TO BE CONTINUED...")
break
else:
print("Invalid, but no worries! I know you wanted to talk to him!")
print("TO BE CONTINUED...")
break
elif i == "no":
print(name + " I think you meant yes! Try again!")
#User is not ready to play
else:
print(name + " this in an invalid answer. Try again!")
| true |
658edf6a0592c14e24c50e4b61866b45ada1ac9d | erikdekker22/globalknowledge-python-training | /basic_programs/provide_random_number.py | 1,811 | 4.28125 | 4 | from random import randint
def ask_min_max_numbers():
max_value = int(input("Please specify a maximum value: ")) # ask for max value
min_value = int(input("Please specify a minimum value: ")) # ask for min value
while min_value >= max_value: # loop till you enter a min value that is less than the max value
print("You are stuck in my loop! If you want to get out, please specify a lower value than you maximum value: ")
min_value = int(input("Please specify a new minimum value: "))
else:
print("Fine you are free. You had given the max value of " + str(max_value) + " and a min value of " + str(min_value) + '.')
return min_value, max_value
def select_random_number(min, max):
'''Start een oneindige loop waarin je een random getal genereert tussen min en max.
Toon het nummer en vraag of dit getal geselcteerd moet worden
Indien de gebruiker 'yes' ingeeft, retourneer je het getal.
In alle andere gevallen zeg je dat je een een nieuw getal gaat maken en je blijft in de loop.
'''
chosen_one = randint(min, max)
print("Dear user. You have been provided the number **" + str(chosen_one) + "**. Are you satisfied? Or do you want another one?")
answer = input("Please Type \"Yes\" or \"No\".").upper()
while answer != "YES":
chosen_one = randint(min, max)
print("You have been assigned a new number **" + str(chosen_one) + "**. Are you satisfied? Or do you want another one?")
answer = input("Please Type \"Yes\" or \"No\".").upper()
else:
return chosen_one
def main():
min, max = ask_min_max_numbers()
number = select_random_number(min, max)
message = ("Great! You have finally chosen **" + str(number) + "**.")
print(message)
if __name__ == "__main__":
main() | false |
dad0fcd555f5788394e9a37303005e8c617b6fa2 | KelseyCortez/Lists-Dictionaries | /hotel.py | 1,134 | 4.28125 | 4 | # The goal of the small exercise is to get practice with the syntax for querying and manipulating the data in a single, nested dictionary.
#Write functions to:
#- is_vacant(which_hotel, '101')
#- check if a room is occupied
#- check_in('101', guest_dictionary)
#- assign a person to a room
#- check_out('101')
#- returns the person dictionary in that room
#Please look back at any notes or slides for how to perform any of these actions.
guest = {
'name': ' ',
'phone_number': ' ',
}
hotel = {
'101': ' ',
'102': ' ',
'103': ' ',
'104': ' ',
'105': ' ',
}
guest['name'] = input('What is your name? ')
guest['phone_number'] = input('What is your phone number? ')
what_room = input('Which room? 101, 102, 103, 104, or 105? ')
hotel[what_room] = guest
for key in hotel.keys():
print(f'{key}: {hotel[key]}')
print(hotel)
if hotel[key] == ' ':
print(f'{key} is vacant')
else:
print(f'{key} is occupied by {hotel[key]["name"]}')
check_out = input('Are you checking out? Y or N: ')
if check_out == 'Y':
hotel[guest] = ' '
print('Thanks! We will see you next time! ')
| true |
f4a4dd3e8890d0109051f8d5f82e961432b633d4 | GolubevaElena/-Tasks | /task6.py | 811 | 4.15625 | 4 | #ГолубеваЕ.А.
#1Вариант,6задача
#18.04.17
#Создайте игру, в которой компьютер загадывает имя одного из трех мушкетеров -
#товарищей д'Артаньяна, а игрок должен его угадать.
print( "\tДобро пожаловать в игру 'Отгадай мушкетёра'!")
print("\nЯ загадал одного из мушкетёров.")
print("Постарайтесь отгадать его.\n")
import random
x = random.choice(["Арамис","Артос","Портос"])
name=input("Ваш вариант: ")
if name==x:
print("Правильно!")
else:
print ("Не угадал!")
input("\n\nНажмите Enter для выхода.")
#Голубева Елена
| false |
aa0df5a66830d41ca802c7d4913a0b3c9f310752 | thuurzz/Python | /curso_em_video/mundo_02/repetições_em_python_(while)/ex062+.py | 842 | 4.125 | 4 | # Exercício Python 51: Desenvolva um programa que leia o
# primeiro termo e a razão de uma PA. No final,
# mostre os 10 primeiros termos dessa progressão.
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ex062
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ex063
primeiro = int(input('Digite o primeiro termo da PA: '))
termo = primeiro
razao = int(input('Digite a razão da PA: '))
total = 0
contador = 0
mais = 10
print('=' * 30)
print('10 PRIMEIROS TERMOS DE UMA PA')
print('=' * 30)
# caso não queira, entra 0, encerra o programa
while mais != 0:
total = total + mais
while contador < total:
print(f'{termo} =>', end='')
termo += razao
contador += 1
print('PAUSA')
mais = int(input('Gostaria de mostrar mais termos? Quantos? Se não, digite 0: '))
print('FIM')
| false |
556fe5b03e921731604d81cc93cce3338f6438af | thuurzz/Python | /curso_em_video/mundo_03/funcoesPt2/ex104.py | 747 | 4.1875 | 4 | '''
Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante ‘a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt(‘Digite um n: ‘)
'''
def leiaInt(caracteres):
"""Recebe uma entrada e verifica se é um número inteiro.
Args:
caracteres ([str]): [Frase que pede inteiro.]
Returns:
[int]: [Número inteiro recebido pelo input.]
"""
while True:
num = input(caracteres)
if num.isnumeric():
break
else:
print('ERRO! Digite um número inteiro válido!')
return num
n = leiaInt('Digite um número: ')
print(f'Você digitou o número {n}.') | false |
a8e3daeeb2ab399b488cb195798ab4884ce4237a | thuurzz/Python | /curso_em_video/mundo_02/repetições_python_for/ex049.py | 804 | 4.25 | 4 | # Exercício Python 49: Refaça o DESAFIO 9, mostrando a tabuada de um
# número que o usuário escolher,
# só que agora utilizando um laço for.
'''
n = int(input('digite um número para exibir sua tabuada:'))
print('{} x 1 = {}'.format(n, (n * 1)))
print('{} x 2 = {}'.format(n, (n * 2)))
print('{} x 3 = {}'.format(n, (n * 3)))
print('{} x 4 = {}'.format(n, (n * 4)))
print('{} x 5 = {}'.format(n, (n * 5)))
print('{} x 6 = {}'.format(n, (n * 6)))
print('{} x 7 = {}'.format(n, (n * 7)))
print('{} x 8 = {}'.format(n, (n * 8)))
print('{} x 9 = {}'.format(n, (n * 9)))
print('{} x10 = {}'.format(n, (n * 10)))
'''
n = int(input('Digite um número para exibir sua tabuada: '))
for i in range(1, 11, 1):
total = n * i
print(f'{n} x {i} = {total}')
print(15 * '=')
| false |
1ba6667464cdf44c0c104e81090602515780a8a1 | thuurzz/Python | /curso_em_video/mundo_02/repetições_em_python_(while)/ex062.py | 1,138 | 4.125 | 4 | # Exercício Python 51: Desenvolva um programa que leia o
# primeiro termo e a razão de uma PA. No final,
# mostre os 10 primeiros termos dessa progressão.
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ex062
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ex063
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
n = 10 # mostra os 10 primeiros elementos
ult = a1 + (n - 1) * r
ult += 1
print('=' * 30)
print('10 PRIMEIROS TERMOS DE UMA PA')
print('=' * 30)
# com while
i = 0
while i < n:
an = a1 + (i * r)
print(an)
i += 1
# verifica se quer exxibir mais termos
mais_termos = int(input('Gostaria de mostrar mais termos? Quantos? Se não, digite 0: '))
# caso não queira, entra 0, encerra o programa
if mais_termos == 0:
print('FIM')
else: # com mais termos
a1 = an # O primeiro termo passa a ser o ultimo da primeira PA
n = mais_termos + 1 # lê a quantidade de termos, +1 para mostrar o 1º anterior e ultimo novo
i = 0
while i < n:
an = a1 + (i * r)
print(an, end='=> ')
i += 1
print('FIM')
| false |
1de99ef3cf75742e6314dfa39d6c5eda56a9a423 | thuurzz/Python | /curso_em_video/mundo_03/dicionarios/ex095.py | 2,124 | 4.25 | 4 | # Exercício Python 095: Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.
bdJogadores = []
jogador= {}
while True:
# Lê nome do jogador e quantas partidas jogou
jogador['Nome'] = str(input('Nome do jogador: '))
qtdPartidas = int(input(f'Quantas partidas {jogador["Nome"]} jogou? '))
# Quantidade de gols para cada partida
gols = []
for i in range(qtdPartidas):
gols.append(int(input(f'Gols na partida {i+1}: ')))
jogador['Gols'] = gols
# Total de Gols nas partidas
jogador['Total de Gols'] = sum(jogador['Gols'])
# Adiciona jogador ao Banco de Jogadores
bdJogadores.append(jogador.copy())
jogador.clear()
# Pergunta se quer continuar
while True:
opc = str(input('Deseja continuar? [S/N] ')).upper()[0]
if opc in 'SN':
break
if opc == 'N':
break
print(f"{' TABELA DE JOGADORES ':=^50}")
print(f'{"COD":<5}{"NOME":<10}{"GOLS":<20}{"TOTAL DE GOLS":>10}')
print(f"{'=' * 50}")
codJog = 0
for jogador in bdJogadores:
print(f'{codJog:<5}{jogador["Nome"].upper():<12}{(str(jogador["Gols"])):<20}{jogador["Total de Gols"]:<15}')
codJog += 1
while True:
# Pede Id do jogador para mostrar informações
idJog = int(input('Mostar dados de qual jogador? (999 para)'))
if idJog == 999:
break
try:
# Mostra informações do jogador selecionado
print(f"{' INFORMAÇÕES DO JOGADOR ':=^50}")
print(f'Jogador {bdJogadores[idJog]["Nome"]}.')
# Exibe quantidade gols por partida do jogador
for i in range(len(bdJogadores[idJog]["Gols"])):
print(f'=> No jogo {i} fez {bdJogadores[idJog]["Gols"][i]} gols.')
# Exibe total de gols nas partidas
print(f'Foi um total de {bdJogadores[idJog]["Total de Gols"]} de gols.')
print('=' * 50)
except IndexError:
# Se ID não está na lista, pede de novo
print(f'O ID deste jogador não conta na lista, tente novamente.')
print(f"{' FIM DO PROGRAMA ':=^50}")
| false |
aa949954da5a3634f1f394cfa3fb3fb7d6d63a26 | thuurzz/Python | /curso_em_video/mundo_03/funcoesPt2/ex102.py | 987 | 4.375 | 4 | # Exercício Python 102: Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial.
def fatorial(num=1, show=False):
"""Recebe número e calcula fatorial, se pede para mostrar processo em show, exibe números e processo, se não apenas o resultado.
Args:
num (int, optional): [Valor para calcular fatorial]. Defaults to 1.
show (bool, optional): [Mostra ou não processo dos valores do fatorial]. Defaults to False.
Returns:
[type]: [Retorna valor do fatorial.]
"""
f = 1
for c in range(num, 0, -1):
if show:
print(c, end='')
if c > 1:
print(' x ', end='')
else:
print(' = ', end='')
f *= c
return f
print(fatorial(num=10, show=True))
| false |
34fb3c5b432e5244ea42d84ea202ab66dfe2512b | waleedakram59/demo | /easter.py | 950 | 4.53125 | 5 | """Calculate Gregorian Easter using Gauss's algorithm."""
import sys
def easter_date(year):
"""This function determines which day of the year that the user enters
Easter falls on.
The argument requires that the function should take a four
digit year.
The value it returns is a month and a day which is Easter.
ValueError: if the year is less than 1583. """
a=year%19
b=year%4
c=year%7
k=year//100
p=(13)+(8*k)//25
q=k//4
m=(15-p+k-q)%30
n=(4+k-q)%7
d=(19*a+m)%30
e=(2*b)+(4*c)+(6*d+n)%7
march=22+d+e
april=d+e-9
if d==29 and e==6 and april==26:
april=19
if d==28 and e==6 and (11*m+11)%30<19 and april==25:
april=18
date = f"March {march}" if march < 32 else f"April {april}"
return date
if __name__ == "__main__":
try:
year = int(sys.argv[1])
except IndexError:
sys.exit("this program expects a year as a command-line argument")
except ValueError:
sys.exit("could not convert", sys.argv[1], "into an integer")
print(easter_date(year))
| true |
ba4ec9be19e027c6da1cd86921597862874d8d7e | enzoyoshio/Problemas | /problema1.py | 645 | 4.1875 | 4 | # lista de dicionario dado
listDict = [
{1 : 1, 2 : "oi", "nome" : "obrigado"},
{"Bolo" : "Cenoura", "Camarão" : "Verde", "nome" : "Sagrado"},
{1 : 10, "nome" : "oi", "caracol" : "obrigado"},
{"nome":"obrigado"}
]
# a chave que será procurada
nome = "nome"
# inicializando a lista vazia
lista = []
# verifico para cada nome se ele está ou não no dicionário
for dict1 in listDict:
# se a chave nome estiver no dicionário
# e o valor dela não tiver sido adicionado a lista, só adicionar na lista
if nome in dict1 and dict1[nome] not in lista:
lista.append(dict1[nome])
# printa a lista
print(lista) | false |
490e2bbfe898da96aa8e25a4a3505b5ba98176ad | bhushanyadav07/coding-quiz-data-track- | /quiz1.py | 646 | 4.375 | 4 | #In this quiz you're going to do some calculations for a tiler. Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long.
#Tiles come in packages of 6.
#1.How many tiles are needed?
#2.You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over?
a = (9*7)+(5*7)
print(a)
#and how many tiles are left
print((17*6)-a)
--->You correctly calculated the number of tiles needed. Nice work!
I calculated my answer like this: 9*7 + 5*7
--->You correctly calculated the number of leftover tiles. Well done!
I calculated my answer like this: (17*6) - (9*7 + 5*7)
| true |
9624e2e48995acc812880a8e7dc8f40e54242f50 | mahendraprasadgupta/Python-Practice | /decorator_example.py | 2,221 | 4.875 | 5 | # Decorators
# Decorators are very powerful and useful tool in Python since it allows programmers to modify
# the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function,
# without permanently modifying it. But before diving deep into decorators let us understand some concepts that will come in handy in learning the decorators.
# 1. type decorator
#====================================
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
# 2. Type Decorator
#=============================
# importing libraries
import time
import math
# decorator to calculate duration
# taken by any function.
def calculate_time(func):
# added arguments inside the inner1,
# if function takes any arguments,
# can be added like this.
def inner1(*args, **kwargs):
# storing time before function execution
begin = time.time()
func(*args, **kwargs)
# storing time after function execution
end = time.time()
print("Total time taken in : ", func.__name__, end - begin)
return inner1
# this can be added to any function present,
# in this case to calculate a factorial
@calculate_time
def factorial(num):
# sleep 2 seconds because it takes very less time
# so that you can see the actual difference
time.sleep(2)
print(math.factorial(num))
# calling the function.
factorial(10)
| true |
82a54c97dadefbf0982e70636c68036ef4b417d5 | JohnnyMarlison/math_and_graphic | /freelance/Laba2.py | 235 | 4.28125 | 4 |
from math import sqrt
x = float(input('Введите значение x='))
if x <=-3:
y=3
elif x >-3 and x<=3:
y=3-sqrt(9-(2**x))
elif x>3 and x<=6:
y=-2*x+9
else:
y=x-9
print("X={0:.2f} Y={1:.2f}".format(x, y))
| false |
93f63ec2c5308fe94ebb242a1faa12e6ee82ab9d | dinabseiso/python_projects | /python_projects/mimsmind_bullcow.py | 2,245 | 4.28125 | 4 | def make_lists(number):
""" This list comprehension (yes!) is implemented to create a list
where every item is an integer form of an index within the passed in
string or number.
"""
string_version_of_number = str(number)
return [int(digit) for digit in string_version_of_number]
def cows_and_bulls(guess, random_number):
""" This function pulls a list of numbers from the make_lists() above
in order to evaluate index by index whether there is a match (a bull).
It counts all True hits in a list of tuples (the product of zip()), to see
whether the two values in the tuple match.
It then enters a for loop that iterates through the set of characters in guess_list.
set() only maintains unique values. So, for example, if there are duplicate
integers or characters, only one will be represented in the set. set([1, 2, 2]) will
return [1, 2]. So, for every digit in this set, it will take the minimum number
of matches found in either the guessed value or the randomly generated value. We take
the minimum of the two because unless we have a complete match between guessed value and
the randomly generated one, we will have the most matches between the set that originates
from the guessed value than with our randomly generated value. The only time when this is
not true is when our randomly generated number contains many duplicate integers, which
is why we have the min() function as well. The total number of matches (this includes bulls)
is cumulatively summated. If we did not have min(guess_list.count(digit)), and instead had
evertthing else exclusively, we would run into a problem where it says we have cows when
we really do not have any cows at all.
Because we calculated the total number of cows and bulls, we want to subtract bulls in
order to get our count of cows.
We return the counts as a tuple.
"""
guess_list, random_number_list = make_lists(guess), make_lists(random_number)
bull_count = [digit1 == digit2 for digit1, digit2 in zip(guess_list, random_number_list)].count(True)
cows_and_bulls = 0
for digit in set(guess_list):
cows_and_bulls += min(guess_list.count(digit), random_number_list.count(digit))
cow_count = cows_and_bulls - bull_count
return bull_count, cow_count
| true |
47a23de6f7aed5d8b2cf676623bcd7010ed0c653 | Jim-yeee/jinye | /demo01.py | 982 | 4.125 | 4 | '''
print('hello world') #字符串 str
print(100) #整型 int
print(3.14) #浮点型 float
print(True) #布尔值 bool
print(()) #元组 tuple
print([]) #数组 list
print({}) #字典 dic
print("你好呀","我是美美")
print("嘻嘻"+"哈哈")
print("哈哈"*10)
print((1+2)*10+50)
print(1+1==3) '''
#input输入
'''a=input("请输入你的名字:")
print("你的名字是:",a)'''
# print(type("嘻嘻"))
# print(type(100))
# print(type(3.14))
# print(type(True))
# print(type(()))
# print(type([]))
# print(type({}))
'''a=float(input("请输入数字:"))
b=float(input("请输入数字:"))
print("得出结果为:",a+b)'''
#len 获取字符串长度 (支持字符串、元组、数组、字典)
'''a="sdfjsagdsdfgasjgfjskfjksaggasjk"
print(len(a))'''
#练习:通过代码获取两段内容,并且计算他们的长度之和
a="我是第一段内容"
b="我是第二段内容"
print("他们的长度之和为:",len(a+b)) | false |
f8bfe9f11f29ae98138a902e3aff5c79e51ef3b1 | hassxa96/Programacion | /EjerciciosFunciones/Ejercicio8.py | 501 | 4.1875 | 4 | """
Solicitar números al usuario hasta que ingrese el cero. Por cada uno, mostrar la suma de sus dígitos
(utilizando una función que realice dicha suma).
"""
def suma_digitos(x):
contador=0
while x!=0:
y=x%10 #y=5
contador+=y #contador=11
x=x//10 #x=0
return contador
suma=0
y=int(input("Escribe un número: ")) #y=40
while y!=0:
print(suma_digitos(y)) #4
suma+=y
y=int(input("Escribe un número: ")) #y=13
print("La suma de los dígitos es", suma) | false |
f25523764c62306e63ca88dd69ee5941609657b5 | hassxa96/Programacion | /EjerciciosFunciones/Ejercicio18.py | 715 | 4.375 | 4 | """
Ejercico 3: Realiza un programa en Python que calcule el máximo de una lista de números
introducidos por el teclado. Utiliza una función que se llame máximo que no reciba nada
como entrada y devuelva el máximo. El tamaño de la lista de números lo determina
el usuario, al introducir un –1 se considerará que ya no quiere introducir más números.
"""
def maximo():
lista=[]
mayor=0
x=int(input("Escribe un número: "))
lista.append(x)
while x!=-1:
x=int(input("Escribe un número: "))
lista.append(x)
for i in range(len(lista)):
if lista[i]>mayor:
mayor=lista[i]
return mayor
print("El mayor número de la lista es el", maximo())
| false |
5dcf44da1a230eaf7f0fd70e5b63ca348906559f | git4robot/PyKids | /radix.py | 1,405 | 4.25 | 4 | """A module for convert.
Version:1.5.1(For python 3.2+)
"""
def to_redix(num, from_radix):
"""
num ---------- The number for convert.
from_radix ---------- The radix for convert to DEC.
"""
_len = len(str(num))
_list = list(str(num))
dec = 0
for x in range(_len - 1, -1, -1):
dec = dec + int(_list[_len - x - 1]) * (from_radix ** x)
return dec
def from_redix(num, to_radix):
"""
num ---------- The number for convert.
to_radix ---------- The radix to convert with DEC.
"""
_list = list()
a = num
while a:
to = a % to_radix
a = (a - to) // to_radix
_list.append(str(to))
_list.reverse()
ret = "".join(_list)
return int(ret)
def radix(num, a_radix, b_radix):
"""
num ---------- The number for convert.
a_radix ---------- The first radix for convert to the second radix.
b_radix ---------- The second radix for convert to the first radix.
"""
dec = to_redix(num, a_radix)
radix = from_redix(dec, b_radix)
return radix
if __name__ == "__main__":
print(to_redix(226, 8))
print(to_redix(96, 16))
print(to_redix(10010100, 2))
print("-----")
print(from_redix(113, 8))
print("-----")
print(radix(226, 8, 16))
| false |
156b75b7d19c3418b0cb50cf6550052989c21457 | MatthieuRouland/automate-boring-stuff | /CH04/lenInSomeList.py | 363 | 4.15625 | 4 | ## common technique is using len
catList = ["gogo", "jojo", "stinky"]
for i in range(len(catList)):
print("Index: " + str(i) + " and it represents " + catList[i])
## Check to see if things are IN the list
print('gogo' in catList) ##true
print('soki' in catList) ## false
## Check to see if things are NOT in the list.
print('soki' not in catList) ## true | true |
5e798550f552624a972ccc2109e41fb1528899b1 | raymondzuo/PythonLearningNote | /chpt6/chpt6.py | 1,530 | 4.1875 | 4 | # python没有类型声明,所有的类型都是动态类型,根据对象的类型而确定
# 3时对象,a是对象3的一个引用, a可以修改为指向其他类型的对象
# 对象是python分配的内存空间
# 对象有两个标准的头部信息: 1. 类型标志符号用以标记对象的类型 2.引用的计数器
# 类型数据对象,而不是变量
a = 3
print(type(a))
a = 'haha'
print(type(a))
#垃圾回收, 某个对象的引用计数一旦为0之后,自动回收该对象
b = 4
b = 'cde' # 此时对象"4"已经被回收
#共享引用
c = b
print(c) #此时c,b共同指向了同一个对象
b = 'xyz'#此时b指向了新的对象, 而此时c仍然指向对象'cde'
print('b: ', b, 'c: ', c)
#如果支持修改原对象的类型,要尤其注意对共享引用的影响
e = [1, 2, 3]
f = e
e[0] = 5
print(f) #此时因为e[0]的修改,导致f指向的对象随之发生改变
# 但是如果f是一个复制,那么修改e则不会影响f
f = e[:]
e[0] = 10
print(f)
#共享引用和相等
x = 42
x = 'shrubbery' #此处的42可能不会立即被回收.python为了复用,会缓存42,以便下一个42用到, 大多数的对象都会被立即回收
#等号"==" 操作符用于测试两个对象是否值相等, "is" 操作符用于检查两个对象是否时一个对象
z1 = [1,2]
z2 = [1,2]
print('z1 == z2: ', z1 == z2, ' z1 is z2: ', z1 is z2)
#但是因为小数字被缓存了,所以两个不同的对象,使用is时,仍然可能相等
z3 = 10
z4 = 10
print('z3 == z4', z3 == z4, ' z3 is z4: ', z3 is z4) | false |
bc6e4405403389f31fcf786b67248396bd34e136 | CassandraTalbot32/flashcard | /flashcard.py | 1,123 | 4.3125 | 4 |
from random import *
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
user_response = input('Did you know the definition? enter y for yes: ')
if user_response == 'y':
del glossary[random_key]
elif user_response == 'n':
print ('Ok.')
else:
print ('Please respond with a y or n.')
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
exit = False
while not exit:
user_input = input('Enter s to show a flashcard and q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
if not glossary:
exit = True
else:
print('You need to enter either q or s.')
| true |
ada9825e38bb3e9fed1a4c25edd79f9a3123f514 | AmitAps/learn-python | /oops_python/customersclassexampleone.py | 1,625 | 4.34375 | 4 | class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have the
following properties:
Attributes:
name: A string representing the customer's name.
balance: A float tracking the current balance of the customer's account.
"""
def __init__(self, name):
"""Return a Customer object whose name is *name*."""
self.name = name
def set_balance(self, balance=0.0):
"""Set the customer's starting balance."""
self.balance = balance
def withdraw(self, amount):
"""Return the balance remaining after withdrawing *amount*
dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
self.balance -= amount
return self.balance
def deposit(self, amount):
"""Return the balance remaining after depositing *amount*
dollars."""
self.balance += amount
return self.balance
"""
This may look like a reasonable alternative; we simply need to call set_balance before we begin using the instance.
There's no way, however, to communicate this to the caller. Even if we document it extensively,
we can't force the caller to call amit.set_balance(1000.0) before calling amit.withdraw(100.0).
Since the amit instance doesn't even have a balance attribute until jeff.set_balance is called,
this means that the object hasn't been "fully" initialized.
The rule of thumb is, don't introduce a new attribute outside of the __init__ method, otherwise you've given the caller an object that isn't
fully initialized
"""
| true |
786b379de7c96a5de2c3eecb6fe28e75fd080b64 | AmitAps/learn-python | /forloopnested.py | 352 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 09:12:17 2020
@author: Aps
"""
"""
the range function in the outer loop is evaluated only once, but the range function in the
inner loop is evaluated each time the inner for statement is reached.
"""
x = 4
for j in range(x):
for i in range(x):
print(i)
x = 2 | true |
44ce6024d094a298211a460c202ca1282868fef4 | VakinduPhilliam/Python_Class_Semantics | /Python_Class_Objects.py | 819 | 4.25 | 4 | # Python Class Objects
# Python Class objects support two kinds of operations:
# 1. Attribute references.
# 2. Instantiation.
# Attribute references use the standard syntax used for all attribute references in Python: obj.name.
# For Example;
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
# For the above, MyClass.i and MyClass.f are valid attribute references,
# returning an integer and a function object, respectively.
# On the other hand, Class instantiation uses function notation.
# Just pretend that the class object is a parameterless function that
# returns a new instance of the class.
# For example:
x = MyClass()
# This creates a new instance of the class and assigns this object
# to the local variable x.
| true |
95de015d6b9efa76e9890f39e6c8dd2fe1d9be87 | usapes2/CodeJams | /cookbook/1.9FindingCommonalitiesInTwoDictionaries.py | 733 | 4.28125 | 4 | '''
Having two dictionaries find out what they might have in common
'''
a = {
'x':1,
'y':2,
'z':3
}
b = {
'w':10,
'x':1,
'y':2,
'v':1
}
'''
to find out what the two dictionaries have in common,
simply perform common set operations using the keys() or
items() method.
'''
# Find keys in common
print((a.keys() & b.keys()))
# Find keys in a that are not in b
print(a.keys() - b.keys())
# Find (key,value) pairs in common
print(type(a.items() & b.items()))
for item in ( a.items() & b.items()):
print(type(item))
# Make a new dictionary with certain keys removed using dictionary comprehension:
c = {key:a[key] for key in a.keys() - {'z','w'}}
print(c)
| true |
60dfcc4bb0b0503d49f21b50d0ea4bf4975a4fb4 | Flynnon/leetcode | /src/leetcode_200/116_populating_next_right_pointers_in_each_node.py | 2,089 | 4.15625 | 4 | # 填充同一层的兄弟节点
# 给定一个二叉树
#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
#
# 初始状态下,所有 next 指针都被设置为 NULL。
#
# 说明:
#
# 你只能使用额外常数空间。
# 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
# 你可以假设它是一个完美二叉树(即所有叶子节点都在同一层,每个父节点都有两个子节点)。
# 示例:
#
# 给定完美二叉树,
#
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# 调用你的函数后,该完美二叉树变为:
#
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ / \
# 4->5->6->7 -> NULL
# Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
"""
遍历每个节点时,设置其子节点的兄弟节点即可. 注意 最后一列的节点本身没有兄弟节点,也无需设置..
:param root: TreeLinkNode
:return:
"""
head = root
while head:
prev, cur, next_head = None, head, None
# 如果当前不是最后一行(最后一行才没有左子节点) 且 当前行还没结束
while cur and cur.left:
# 设置左子节点的兄弟节点
cur.left.next = cur.right
# 如果当前节点不是最右列的节点
if cur.next:
# 设置其右子节点的兄弟节点
cur.right.next = cur.next.left
# 遍历下一个节点
cur = cur.next
# 向下移动一行
head = head.left | false |
d60a1a080cbc201452b78a6f982bff88e21e566c | jkcadee/A01166243_1510_assignments | /A1/lotto.py | 931 | 4.40625 | 4 | import random
def number_generator():
"""Creates six random numbers and orders them from lowest to highest"""
length = 6
set_of_six_numbers = random.sample(range(1, 49), length)
# Creating the list of six numbers
set_of_six_numbers.sort()
return set_of_six_numbers
"""
Return a list of specified length with numbers between 1 and 49 going from lowest to highest.
:precondition: Length of the list must be specified
:postcondition: A list containing the amount of numbers specified in the length variable
:return: A list that is the specified length with numbers between 1 and 49, sorted from lowest to highest.
"""
def main():
"""Executes the program"""
print(number_generator())
if __name__ == "__main__":
main()
"""
For this function, automation is used in sorting the numbers in ascending order. Abstraction is also used in only
displaying the sorted list, not the original list.
"""
| true |
304810a4db192fdeb8aee9da5e210a76bff8a9e2 | jkcadee/A01166243_1510_assignments | /A4/question_4.py | 916 | 4.375 | 4 | def selection_sort(unsorted_list):
"""
Sorts the given list.
:param unsorted_list: List.
:precondition: List must only contain integers and have more than one value.
:postcondition: Swap all elements in the list to be in ascending order.
"""
swap = True
while swap:
swap = False
for index, value in enumerate(unsorted_list):
if index < len(unsorted_list) - 1:
if value > unsorted_list[index + 1]:
unsorted_list[index], unsorted_list[index + 1] = unsorted_list[index + 1], unsorted_list[index]
swap = True
def main():
"""Runs the functions"""
a_list = [0, -1, 9, 30, 8]
try:
selection_sort(a_list)
except TypeError:
raise TypeError('Must be a list of sortable items! (More than one element).')
else:
print(a_list)
if __name__ == "__main__":
main()
| true |
25e5f49fd232cee163a6a3bd81089bfcfd740240 | jkcadee/A01166243_1510_assignments | /A1/colour_mixer.py | 1,318 | 4.25 | 4 | def colour_mixer():
"""Takes an input and produces one of four strings depending on it"""
colour = input("Enter your first colour:").strip().capitalize()
colour_2 = input("Enter your second colour:").strip().capitalize()
if colour == "Red" and colour_2 == "Blue":
print("Your secondary colour is purple.")
elif colour == "Yellow" and colour_2 == "Red":
print("Your secondary colour is orange.")
elif colour == "Blue" and colour_2 == "Yellow":
print("Your secondary colour is green.")
else:
print("Invalid input and/or colour combination.")
return
"""
Return the colour combination from two inputted values.
:precondition: Must input the correct three colours
:postcondition: Output a string based on the colours inputted
:return: A string containing the colour combination
"""
def main():
"""Executes the program"""
colour_mixer()
return
if __name__ == "__main__":
main()
"""
I used pattern matching and abstraction for this function. The pattern matching was to match each of the two inputs to
their corresponding colour, seeing if the correct two colours were inputted. The abstraction in this function is that
only the result of what two strings you inputted is shown to you. No other information is displayed or printed.
""" | true |
372071cdc7b98828b194e477461c2fb4308e4e78 | jkcadee/A01166243_1510_assignments | /A4/question_1.py | 1,316 | 4.15625 | 4 | import doctest
def eratothenes(upperbound: int) -> list:
"""
Return a list of only prime numbers, based on how many elements are inside the generated all_numbers list.
:param upperbound: Integer.
:precondition: Must be an integer higher than zero.
:postcondition: Removes any numbers that are not prime numbers from the all_numbers list and returns a list of
prime.
numbers from taken from values from the all_numbers list.
:return: A list of prime numbers taken from all_numbers list.
>>> eratothenes(5)
[2, 3, 5]
>>> eratothenes(1)
[]
>>> eratothenes(10)
[2, 3, 5, 7]
"""
bool_primes_list = [True for i in range(0, upperbound + 1)]
bool_primes_list[0] = False
bool_primes_list[1] = False
for index, value in enumerate(bool_primes_list):
if value:
for multiple in range(index+index, upperbound + 1, index):
bool_primes_list[multiple] = False
primes_list = [index for index, value in enumerate(bool_primes_list) if value]
return primes_list
def main():
"""Runs functions in program"""
try:
print(eratothenes(30))
except ValueError:
raise ValueError("Number should be higher than 0!")
if __name__ == "__main__":
main()
doctest.testmod()
| true |
ebd303d9ada453cb2b2e3fab15e64c012021e205 | IamTheVine/CS-2 | /Chapter8_6.py | 406 | 4.15625 | 4 | # Python for Beginners Immersion Course
# Exercise 8.6
# Albert Molina
# 08-May-2018
# Description : max and min
NumList = list()
while True :
NumInp = input('Enter a number: ')
if NumInp.upper() == 'DONE' : break
try :
NumList.append(float(NumInp))
except :
print(' ' + NumInp + ' is not a number')
print('Maximum: ' + str(max(NumList)))
print('Minimum: ' + str(min(NumList)))
| true |
2b2279bf6352ed76bbebe0c3e3e1b33355de8c46 | xiaohuiliugis/Spatial-Programming | /Liu_Xiaohui_2_3.py | 2,937 | 4.21875 | 4 | # Lab Assignment_ Exercise 3
import math
def recalculate_coordinate(val,_as=None):
"""
Accepts a coordinate as a tuple (degree, minutes, seconds)
You can give only one of them (e.g. only minutes as a floating point number) and it will be duly
recalculated into degrees, minutes and seconds.
Return value can be specified as 'deg', 'min' or 'sec'; default return value is a proper coordinate tuple.
"""
deg, min, sec = val
# pass outstanding values from right to left
min = (min or 0) + int(sec) / 60
sec = sec % 60
deg = (deg or 0) + int(min) / 60
min = min % 60
# pass decimal part from left to right
dfrac, dint = math.modf(deg)
min = min + dfrac * 60
deg = dint
mfrac, mint = math.modf(min)
sec = sec + mfrac * 60
min = mint
if _as:
sec = sec + min * 60 + deg * 3600
if _as == 'sec': return sec
if _as == 'min': return sec / 60
if _as == 'deg': return sec / 3600
return deg, min, sec
def points2distance(slong, slat, elong, elat):
"""
Calculate distance (in kilometers) between two points given as (long, latt) pairs
based on Haversine formula (http://en.wikipedia.org/wiki/Haversine_formula).
slong = Starting Longitude
slat = Starting Latitude
elong = ending Longitude
elat = Ending Latitude
"""
start = ((slong,0,0),(slat,0,0))
end = ((elong,0,0),(elat,0,0))
start_long = math.radians(recalculate_coordinate(start[0], 'deg'))
start_latt = math.radians(recalculate_coordinate(start[1], 'deg'))
end_long = math.radians(recalculate_coordinate(end[0], 'deg'))
end_latt = math.radians(recalculate_coordinate(end[1], 'deg'))
d_latt = end_latt - start_latt
d_long = end_long - start_long
a = math.sin(d_latt/2)**2 + math.cos(start_latt) * math.cos(end_latt) * math.sin(d_long/2)**2
c = 2 * math.asin(math.sqrt(a))
return 6371 * c
'''
def distance(x1,y1,x2,y2):
dx = float(x2)-float(x1)
dy = float(y2)-float(y1)
dsquared = dx**2+ dy**2
return math.sqrt(dsquared)
'''
x1=float(raw_input('Please enter the longitude of the starting point: '))
y1=float(raw_input('Please enter the latitude of the starting point: '))
x2=float(raw_input('Please enter the longitude of the ending point: '))
y2=float(raw_input('Please enter the latitude of the ending point: '))
while True:
reply = raw_input('Is the line complete? Yes or No ?')
d = points2distance(x1,y1,x2,y2)
if reply.upper() == 'YES':
print 'The length of the line is:', d
break
elif reply.upper() == 'NO':
x=float(raw_input('Please enter the longitude of the ending point: '))
y=float(raw_input('Please enter the latitude of the ending point: '))
d=d+points2distance(x1,y1,x,y)
| true |
d4a5293ae17055de6522eeac4c850053de2eaf95 | Joelina/LPTHW | /ex03.py | 958 | 4.46875 | 4 | print "I will now count my chickens:" #says what I'll do
print "Hens", 25.0 + 30.0 / 6.0 #calculates how many of my chickens are hens
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 #calculates how many of my chickens are roosters
print "Now I will count the eggs:" #say what I'll do next
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 #counts the eggs
print "Is it true that 3 + 2 < 5 - 7?" # asks a question
print 3.0 + 2.0 < 5.0 - 7.0 #calculates the question and gives the answer
print "What is 3 + 2?", 3.0 + 2.0 # says what 3 + 2 is
print "What is 5 - 7?", 5.0 - 7.0 # says what 5 - 7 is
print "Oh, that's why it's False." #funny
print "How about some more." #and another one
print "Is it greater?", 5.0 > -2.0 #asks whether 5 > -2 and gives answer
print "Is it greater or equal?", 5.0 >= -2.0 #asks whether 5 >= -2 and gives answer
print "Is it less or equal?", 5.0 <= -2.0 #asks whether 5 <= -2 and gives answer
| true |
d4d6f24190d3ea27aef9dd81427e29e3acca2eb4 | pafou/playground | /python/roboc/card.py | 1,956 | 4.15625 | 4 | # -*-coding:Utf-8 -*
"""This module contains "Card" class."""
class Card:
"""Transition object between a file and a card.
A card is defined by a name and "matrix".
Attributes:
- name: string containing the name of the card
- matrix: 2 dimensional object composed of a list of lists
containing characters.
"""
def show(self):
"""Print the card."""
for line in self.matrix:
print (''.join(line))
def __init__(self, name, text_from_file):
"""Card construction.
self.matrix is initialized from the content of the file.
self.robot_init_position is a list containing robot coordinates.
"""
self.name = name
ordi = 0 #Ordinate of robot position
self.matrix = [] #Initialization of the list
lines = text_from_file.split("\n") #Card is split in lines
for line in lines:
#For each line, a list of characters is created.
my_list = list(line)
absc = 0 #Abscissa of robot position
for char in my_list:
if (char == 'X'):
try:
#Check if self.robot_init_position exists
type(self.robot_init_position)
except AttributeError:
#self.robot_init_position does not exist: we create it
self.robot_init_position = [absc,ordi]
my_list[absc]=" " #X in the matrix is replaced by " "
else:
print ("Error: robot does not exist anymore on the card.")
exit(1)
absc +=1
#Then, list of characters is stored in list 'matrix'
self.matrix.append(my_list)
ordi += 1
def __repr__(self):
return "<Card {}>".format(self.name)
| true |
d2e6a7e6f1992ff99140789d961453d2c77f9aec | lpsedev/python3.0 | /ExercicioPython/tuplas/desafio074.py | 794 | 4.1875 | 4 | """
Desafio 074
Crie um programa que vai gerar cinco números aleatórios e
colocar em uma tupla.
Depois disso, mostre a lisytagem de números gerados e também indique
o menor e o maior valor que estão na tupla.
"""
from random import randint
resp = ''
cont = maior = menor = 0
numerosAleatorios = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10))
for n in numerosAleatorios:
cont += 1
if cont == 1:
maior = n
menor = n
else:
if n > maior:
maior = n
else:
maior = maior
if n < menor:
menor = n
else:
menor = menor
print(f'Valores aleatório {numerosAleatorios}')
print(f'O maior valor da tupla é {maior}')
print(f'O menor valor da tupla é {menor}')
| false |
8cb6dfbe6a7af7b0988fb4a5166ca0250f7d42c8 | lpsedev/python3.0 | /ExercicioPython/tuplas/desafio072.py | 712 | 4.25 | 4 | """
Crie um programa qie tenha um tupla totalmente preenchida
com uma contagem por extenso, de zero até vinte.
Seu programa deverá ler um número pelo teclado(entre 0 e 20)
e mostrá-lo por extenso.
"""
while True:
escolha = int(input('Digite um número de 0 a 20: '))
if escolha < 0 or escolha > 20:
print('DIGITE UM NÚMERO QUE ESTEJA NO INTERVALO DE 0 A 20!')
else:
numero = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis',
'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze',
'dezesseis', 'dezesete', 'dezoito', 'dezenove', 'vinte')
print(f'VOCÊ DIGITOU O NÚMERO "{numero[escolha].upper()}"')
| false |
7dc6513b05c20020792c9db7e2057e2029e2baa2 | RubenVS010/python_excercises | /ex2.py | 830 | 4.46875 | 4 | #!/usr/bin/python
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
#
#Hint: how does an even / odd number react differently when divided by 2?
#
#Extras:
#
#If the number is a multiple of 4, print out a different message.
#Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message.
#================================================================================================
print("Please enter a number to get us started with checking if it's equal or unequal")
number = int(raw_input())
mod = number % 2
if mod > 0:
print("You've chosen an unequal number")
else:
print("you've chosen a equal number") | true |
2d590177fd831c05620c948549ed82f266a396e1 | cse031sust02/my-python-playground | /basic/data_structures/list.py | 1,462 | 4.78125 | 5 | # List is a collection which is :
# - Mutable (Changeable)
# - Ordered
# - Allows duplicate members
countries = ["Bangladesh", "India", "Pakistan"]
print("Country List : ", countries)
# Accessing Items
# ========================
print("First item of the list is : ", countries[0])
print("Last item of the list is : ", countries[-1])
print("Second & Third items of the list is : ", countries[1:3])
# looping through list
print("Items in the list : ")
for country in countries:
print(country)
total = len(countries)
print("Total Items : ", total)
is_bd = "Bangladesh" in countries
print("Is Bangladesh in the list? :", is_bd)
# Changing Items
# ======================
print("Changing the second item")
countries[1] = "Afganistan"
print("Adding Bhutan to the list")
countries.append("Bhutan")
print("Removing Pakistan from the List")
countries.remove("Pakistan")
# when we create a new list from another like this : list2 = list1,
# any changes made in list1 will automatically be made in list2.
# Because list2 is only a reference to list1
countries2 = countries
print("Adding Nepal to second list")
countries2.append("Nepal")
print("New Country List : ", countries)
# Copy a List
# ====================
countries_copy = countries.copy()
# or we can use, list(countries)
print("New Copied List : ", countries_copy)
# note : We can now made changes to the new `countries_copy` list,
# It will NOT affect the original `countries` list
| true |
3b706ef21115db2fef963e85ed84fab8758a79a3 | cse031sust02/my-python-playground | /oop/class_vs_static_method.py | 1,583 | 4.15625 | 4 | # - In class methods, the first parameter (cls) points to the class
# - In instance methods, the first parameter (self) points to the instance
# - In static methods, it does not point to class or instance
class Employee:
company = "My Demo Company"
# normal constructor
def __init__(self, name, id): # <- regular instance method
self.name = name
self.id = id
def check_in(self): # <- regular instance method
print("{} (ID - {}) has checked in".format(self.name, self.id))
@classmethod
def set_company(cls, company_name): # <- class method
cls.company = company_name
# We can use class methods as alternative constructors
@classmethod
def add_from_string(cls, employee_string): # <- class method
name, id = employee_string.split("-")
emp = cls(name, id)
return emp
# Static Methods are just like normal function. These are methods
# that have a logical connection to the Class, but does not need a
# class or instance as an argument.
@staticmethod
def is_workday(): # <- static method
print("Everyday is a workday")
# Using the normal constructor
emp1 = Employee("Talha", "001")
print(emp1.company)
emp1.check_in()
# Using the normal constructor
emp2 = Employee("Abbas", "002")
print(emp1.company)
emp2.check_in()
Employee.set_company("New Company")
print(emp1.company)
print(emp1.company)
# Using the alternative constructor
emp3 = Employee.add_from_string("Miaj-003")
print(emp3.__dict__)
print(emp3.company)
emp1.is_workday()
emp3.check_in()
| true |
ca7b052b480f63d6d87e6072b086c7bc7a745b40 | Yanlu109/lab1 | /main.py | 489 | 4.28125 | 4 | #Author Yan Lu yfl5541@psu.edu
#Collaborator Marco Falcucci mzf5527@psu.edu
#Collaborator Samantha Nelson szn254@psu.edu
#Collaborator Finn Thompson fet5024@psu.edu
Temp = float(input("Enter temperature: "))
unit = input("Enter unit in F/f or C/c: ")
if unit == "C" or unit =="c":
f = float((Temp*9/5)+32)
print(f"{Temp}° in Celsius is equivalent to {f}° Fahrenheit.")
elif unit=="F" or unit=="f":
c = float((Temp-32)*5/9)
print(f"{Temp}° in Fahrenheit is equivalent to {c}° Celsius.")
else:
print(f"Invalid unit({unit}).")
| false |
555ade711ae87e88b6b281e75550577b65920980 | Ukabix/projects | /python/codewars kata/12 list ends.py | 504 | 4.125 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only
# the first and last elements of the given list. For practice, write this code inside a function.
import random
def listCreate():
num = random.randint(1,10)
print(num)
list1 = list(range(1, num + 1))
print(list1)
return list1
def listOrder(num):
list2 = []
list2.extend([num[0], num[-1]])
#print(list2)
return list2
print(listOrder(listCreate()))
| true |
37cfbfe77907a363416ce1001262491c322055ab | Ukabix/projects | /python/codewars kata/binary_add.py | 739 | 4.46875 | 4 | """Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
The binary number returned should be a string.
Examples:
add_binary(1, 1) == "10" (1 + 1 = 2 in decimal or 10 in binary)
add_binary(5, 9) == "1110" (5 + 9 = 14 in decimal or 1110 in binary)
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(add_binary(1,1),"10")
test.assert_equals(add_binary(0,1),"1")
test.assert_equals(add_binary(1,0),"1")
test.assert_equals(add_binary(2,2),"100")
test.assert_equals(add_binary(51,12),"111111")
"""
def add_binary(a,b):
result = bin(a+b)
return result[2:] | true |
efb83559d4841429a47f0ac661858058bb79f78d | PhilHuang-d/python--- | /Note/Python基础/7-内置函数、作用域、闭包、递归/第七次作业.py | 1,232 | 4.21875 | 4 | #python基础 第七次作业
#1.把老师上课例子都敲一遍(不需要截图,但是一定要做)
'''
|<< >>| 鹏保宝播放器这两个按钮可以倍速播放
'''
#2.定义一个函数,输入一个序列(序列元素是同种类型),
#判断序列是顺序还是逆序,顺序输出UP,逆序输出DOWN,否则输出None
def fun(*arg):
li = list(arg)
if(sorted(li)==li):
print('顺序序列up')
elif(sorted(li,reverse=True)==li):
print('DOWN')
else:
print('None')
#3.写一个函数,对列表li2 = [9,8,3,2,6,4,5,7,1],进行从小到大的排序。最后返回排序后的列表
li2 = [9,8,3,2,6,4,5,7,1]
def px(a):
return sorted(a)
#4一个列表,有4个由数字组成的长度为4的元组,对这四个元组,
#按每个元组的第2个数字大小排序
li4 = [(6,2),(3,4),(7,8),(5,6)]
def s(a):
return sorted(a,key=lambda x: x[1],reverse=True)
#5思考题:有一个名为list_apd的函数,
#如下所示,请你多次调用这个函数,对比返回值,是否与你预期的一致?
#想到什么写什么,可以空着
def list_apd(b,a=[]):
a.append(b)
return a
| false |
1b07f60000ea7586d4f8bb5dfe40087375ffbc4f | PhilHuang-d/python--- | /Note/Python基础/10-文件、异常/第十次作业.py | 839 | 4.125 | 4 | #第十次 作业:
'''
'''
#1.打开文件,修改内容,写入另一个文件。
# 把文件reform.txt中的名人名言改成“某某说:......”的形式保存到另一个文件中。
'例:雨果说:大胆是取得进步所付出的代价。'
#2.针对实例化矩行类时,输入字符串等错误参数,写一个提示异常。
'''
class Rectangle:
def __init__(self,length,width):
if isinstance(length,(int,float)) and isinstance(width,(int,float)):
#if ( type(length) == int or type(length) == float ) and (type(width) ==int or type(widh) == float):
self.length = length
self.width = width
else:
return 'ERROR'
def area(self):
return self.length * self.width
'''
'''
try:
n
except Exception:
print(Exception)
'''
| false |
0bd5724a6ded0e59360283afb2908147443bd2ec | PhilHuang-d/python--- | /Note/Python基础/8-类/第八次作业解答课.py | 2,817 | 4.125 | 4 | #python面向对象作业1
#1.把老师上课例子都敲一遍(不需要截图,但是一定要做)
#2.定义一个矩形的类:
# 要求:1.有长和宽的属性 int float
# 2.有一个计算面积的方法
##isinstance
class Rectangle:
def __init__(self,length,width): #构造方法
if isinstance(length,(int,float)) and isinstance(width,(int,float)):
self.length = length
self.width = width
def area(self):
return self.length * self.width
#如何判断self就是实例化对象
##class test(object):
## def __init__(self):
## if isinstance(self,test): #True
## print('老铁我真的是的')
## else:
## print('no')
##
## def isin(self):
## print(type(self))
## print(type(test)) #元类 metaclass
## if type(self) == type(test): #False
## print('老铁我还是得')
##
## else:
## print('扎心了')
## object
##
## Animal
##
## Dog Cat
##
##
#
# 缩进快捷键 tab ctrl+[ 或者 ]
#3.写一个正方形的类,继承矩形类
# 要求:有一个判断是不是正方形的方法
class Rectangle:
def __init__(self,length,width): #构造方法
if isinstance(length,(int,float)) and isinstance(width,(int,float)):
self.length = length
self.width = width
else:
print('请输入int or float')
def area(self):
return self.length * self.width
class Square(Rectangle): #sikuaiao qiaokelite
def judgement(self):
if self.length == self.width:
return 'It is square'
else:
return 'It is not square'
#这个函数:在学生报名的时候,把所有学生的姓名添加到列表里,返回值为添加成功后的列表
def apd(*arg,li=[]):
li.append(arg)
return li #return 后面的语句不执行
def li_apd(*arg,li=None):
if li == None: # li == None True
li = []
li.append(arg) #只能添加一个元素 dir(list.append) *arg arg
return li
#总结: 避免使用可变对象作为参数
##1.可变与不可变 可变 list,dict,set 不可变:str,tuple
##2.li.append(*arg)
# number : int float complex bool #
# str
# list
# tuple
# dict
# set
de = '老心,扎铁了,我是个变量'
def de():
print('老铁扎心了,我是个函数')
class test1:
def __init__(self,name,age):
self.name =name
self.age = age
def new_age(self):
new_age = self.age +20
print(new_age)
| false |
66eae9835ef2f199d4a1662a6e7c89421691b07c | srujan2209/Python-Training | /fry18.py | 251 | 4.28125 | 4 | # Write a program to print the number is prime or not
num = int(input("Enter Number: "))
for i in range(2, num):
if num <= 1:
print("Not prime")
elif num % i == 0:
print("Not prime")
break
else:
print("Prime",num)
| true |
05452acf56ccbc0f4c697959092e87a73e419efa | srujan2209/Python-Training | /even_odd.py | 470 | 4.21875 | 4 | # Count the number of even and odd numbers from a series of numbers
# Input
# numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
# Output
# Number of even numbers : 4
# Number of odd numbers : 5
Input_number = (1,2,3,4,5,6,7,8,9)
Even_Number = 0
Odd_Number = 0
for i in Input_number:
if i%2==0:
Even_Number=Even_Number+1
else:
Odd_Number=Odd_Number+1
print("Even Number:",Even_Number)
print("Odd Number:",Odd_Number)
| true |
44e6c7597bacd22ac236b04c093eec24c3b22a0a | chensi06lj/Python_project | /lec03BMR计算/BMR_v2.0.py | 956 | 4.1875 | 4 | """
作者:陈思
功能:BMR计算器
版本:2.0
日期:27/03/2019
"""
def body(a,b,c,d):
# 判断性别
if a == '男':
bmr = (13.7 * b)+(5.0 * c)-(6.8 * d)+66
elif a == '女':
bmr = (9.6 * b)+(1.8 * c)-(4.7 * d)+655
else:
bmr = -1
# 结果输出
if bmr != -1:
print('基础代谢率为'+str(bmr)+'大卡')
else:
print('请输入正确的性别')
def main():
"""
主函数
"""
isexit=input('是否退出程序(Y/N):')
while isexit == 'N':
gender = input('请输入性别:')
weight = float(input('请输入体重(kg):'))
height = float(input('请输入身高(cm):'))
age = float(input('请输入年龄:'))
body(gender,weight,height,age)
print() #输出空行
isexit = input('是否退出程序(Y/N):')
if __name__ == '__main__':
main() | false |
f17f35f10d05ace982d81aebd90b14d2fd817c6d | ebmcneely/python-ds | /26_vowel_count/vowel_count.py | 520 | 4.21875 | 4 | def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
low_phrase = phrase.lower()
vowel_count_dict = {}
only_vowels = [char for char in low_phrase if char in ['a','e','i','o','u']]
for char in only_vowels:
vowel_count_dict[char] = only_vowels.count(char)
return vowel_count_dict
| false |
6160cdef0f55b191373e9aa76fea0ff3cc599d92 | RajenderDandyal/easy-python | /classes.py | 2,936 | 4.1875 | 4 | class MyClass:
f_name = " rajender"
l_name = "dandyal"
def full_name(self):
return self.f_name + " " + self.l_name
raj = MyClass()
print(raj.f_name, raj.l_name, raj.full_name())
# Class => Library
# layers of abstraction => display available books, to lend a book, to add a book
# Class => Customer
# Layers of abstraction => request for a book, return a book
class Library:
def __init__(self, listOfBooks):
self.availableBooks = listOfBooks
def displayAvailableBooks(self):
print()
print("Available Books: ")
for book in self.availableBooks:
print(book)
def lendBook(self, requestedBook):
if requestedBook in self.availableBooks:
self.availableBooks.remove(requestedBook)
print(f"You have borrowed: {requestedBook}")
def addBook(self, returnedBook):
self.availableBooks.append(returnedBook)
print(f"You have returned:{returnedBook}")
class Customer:
def requestBook(self):
print("Enter the name of a book you would like to borrow: ")
self.book = input()
return self.book
def returnBook(self):
print("Enter the name of book you want to return: ")
self.book = input()
return self.book
library = Library(['Think and Grow Rich', "Rich Dad & Poor Dad"])
customer = Customer()
#
# while True:
#
# print("Enter 1 to display the available books")
# print("Enter 2 to request for a book")
# print("Enter 3 to return a book")
# print("Enter 4 to exit")
# userChoice = int(input())
#
# if userChoice is 1:
# library.displayAvailableBooks()
# elif userChoice is 2:
# requestedBook = customer.requestBook()
# library.lendBook(requestedBook)
# elif userChoice is 3:
# returnedBook = customer.returnBook()
# library.addBook(returnedBook)
# elif userChoice is 4:
# quit()
# inheritance
class Apple:
manufacturer = "Apple Inc."
contactWebsite = "www.apple.com/contact"
def contactDetails(self):
print("To contact us, log on to ", self.contactWebsite)
class Os:
multiTasking = True
# multiple inheritance
class MacBook(Apple, Os):
def __init__(self):
self.yearOfManufacture = 2017
def manufactureDetails(self):
print(f"This MacBook was manufactured in the year {self.yearOfManufacture} by {self.manufacturer}")
def isMultiTasking(self):
print(f"Is this Macbook multitasking: {self.multiTasking}")
macBook = MacBook()
macBook.manufactureDetails()
macBook.contactDetails()
macBook.isMultiTasking()
# python also dosent have public protected private keywords
# so as a good developers practice .. these naming syntax are considered by all developers,
# to think methods as public, private, protected
# Public => methodName
# Protected => _methodName -- use in class and its derived class/inheriting class
# Private => __methodName -- use only in class itself -- not even by inheriting class
# static => @staticMethod -- use only in class itself -- inheriting class can also use, --
# but instance of class will not have access to static methods
| true |
c0f82a228074325413677ec4ea24c65fe63a73d9 | alpaka99/algorithm | /algorithm_class/완전검색_그리디/p_연습3/s1.py | 453 | 4.125 | 4 | """
연습 문제3. 2의 거듭제곱
2의 거듭 제곱을 반복과 재귀버전으로 구현하시오.
"""
my_list = [5, 2, 7, 1, 3, 8, 9, 3, 5, 2]
# 반복
def power_of_two_iteration(k):
answer = 1
for _ in range(4):
answer *= 2
return answer
print(power_of_two_iteration(4))
# 재귀
def power_of_two_recursion(k):
if k == 0:
return 1
return power_of_two_recursion(k-1)*2
print(power_of_two_recursion(4)) | false |
c3da19eca0ec8104d4faee2e18b8d1785f03ceda | alpaka99/algorithm | /algorithm_class/그래프/p_연습1/s1.py | 934 | 4.125 | 4 | """
연습 문제1. Stack 구현
- 사이즈가 5인 고정 배열 Stack을 구현하시오.
"""
SIZE = 5
stack = [0]*5
top = -1
def is_full():
if top == SIZE:
print('stack is full')
return True
else:
return False
def is_empty():
if top == -1:
print('stack is empty')
return True
else:
return False
def push(n:int):
if is_full():
return
global top
top += 1
stack[top] = n
def pop():
global top
if is_empty():
return
else:
top -= 1
return stack[top+1]
push(1)
push(2)
push(3)
push(4)
push(5)
item = pop() # 5
print('Pop item {}'.format(item))
item = pop() # 4
print('Pop item {}'.format(item))
item = pop() # 3
print('Pop item {}'.format(item))
item = pop() # 2
print('Pop item {}'.format(item))
item = pop() # 1
print('Pop item {}'.format(item))
item = pop() # None
print('Pop item {}'.format(item)) | false |
74fa2cb311ab497e4939777ee8dc049a106e4fd8 | nwkwok/Python | /rock-paper-scissors/main.py | 2,117 | 4.21875 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
rps = ['rock', 'paper', 'scissors']
rps_length = len(rps)
random_rps = random.randint(0, rps_length-1)
computer_choice = rps[random_rps]
print(computer_choice)
user_input = input("What's it gonna be? Rock, paper or scissors?\n")
user_input = user_input.lower()
'You Selected: \n'
if user_input == 'rock':
print(rock + "\n You selected rock!")
elif user_input == 'paper':
print(paper + "\n You selected paper!")
elif user_input == 'scissors':
print(scissors + "\n You selected scissors!")
'The computer selected \n'
if computer_choice == 'rock':
print(rock + "\n The computer selected rock!")
elif computer_choice == 'paper':
print(paper + "\n The computer selected paper!")
elif computer_choice == 'scissors':
print(scissors + "\n The computer selected scissors!")
if user_input != rps[0] or rps[1] or rps[2]:
text = "\nType R-O-C-K, P-A-P-E-R OR S-C-I-S-S-O-R-S... C\'mon... it\'s not that hard!\n"
"I guess this means you lose...?"
if user_input == 'rock':
if computer_choice == 'scissors':
text = "\nLooks like you win!"
elif computer_choice == 'paper':
text = "\nLooks like you lose!"
elif computer_choice == 'rock':
text = "\nLooks like it\'s a draw!"
if user_input == 'paper':
if computer_choice == 'rock':
text = '\nLooks like you win!'
elif computer_choice == 'scissors':
text = '\nLooks like you lose!'
elif computer_choice == 'paper':
text = "\nLooks like it\'s a draw!"
if user_input == 'scissors':
if computer_choice == 'paper':
text = '\nLooks like you win!'
elif computer_choice == 'rock':
text = '\nLooks like you lose!'
elif computer_choice == 'scissors':
text = "\nLooks like it\'s a draw!"
print(text)
| false |
61960d9acb4854c998827b80e18a6a1de316b1ef | roblynch1/Portfolio | /PYTHON/Temperature convertor.py | 838 | 4.1875 | 4 | print "If you wish to convert from Celcius enter 'C'"
print "If you wish to convert from Fahrenheit enter 'F'"
choice = raw_input().lower()
if choice == 'c':
str_inp = raw_input('Enter Celsius Temperature:')
try:
cel = float(str_inp)
fahr = ( cel * 9.0 ) / 5.0 + 32.0
print cel, 'degrees celcius is ', fahr, 'degrees Fahrenheit'
except:
print 'You must input numeric values for Celcius'
elif choice == 'f':
str_inp = raw_input('Enter Fahrenheit Temperature:')
try:
fahr = float(str_inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print fahr, 'degrees Fahrenheit is ', cel, 'degrees Celcius'
except:
print 'You must input numeric values for Fahrenheit'
else:
print "This program requires you to enter 'C' or 'F'"
print 'finished'
| true |
4386b515eb81d308736d86ef2f74856f02a29d41 | Pocolius/web-caesar | /caesar.py | 1,144 | 4.25 | 4 | def alphabet_position(letter):
lower_string = 'abcdefghijklmnopqrstuvwxyz'
upper_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if letter in lower_string:
return lower_string.find(letter)
elif letter in upper_string:
return upper_string.find(letter)
def rotate_character(char, rot):
lower_string = 'abcdefghijklmnopqrstuvwxyz'
upper_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if char in lower_string:
new_pos = alphabet_position(char) + (rot % 26)
return lower_string[new_pos % 26]
elif char in upper_string:
new_pos = alphabet_position(char) + (rot % 26)
return upper_string[new_pos % 26]
else:
return char
def encrypt(string, rot):
encrypted_string = ''
for char in string:
result = rotate_character(char, rot)
encrypted_string = encrypted_string + result
return encrypted_string
def main():
string = input("Please enter a phrase you want to encrypt.")
rot = int(input("Please enter a number (in integer form) of letters you want to rotate by."))
print(encrypt(string, rot))
if __name__ == '__main__':
main() | false |
0b4aede8221df2ada14297bd320806353ba30811 | CFStumpf/python_cryptography | /caesercypher.py | 1,027 | 4.5625 | 5 | #Caesar Cipher - excercise from Hacking Cyphers
message = ""
#key used for encryption and decryption
key = 7
#set program to either encrypt or decrypt
mode = "encrypt"
#acceptable symbols to encrypt
letters = "ABCDEFGHIJKLMONPQRSTUVWXYZ"
#empty string to store the encrypted or decrypted message
translated = ""
#capitalize message
message = message.upper()
#actual work or encryption or decryption happens here
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
if mode == "encrypt":
num = num + key
elif mode == "decrypt":
num = num - key
#what to do if num is larger than len(letters) or is less than 0.
if num >= len(letters):
num = num - len(letters)
elif num < 0:
num = num + len(letters)
#add encrypted or decrypted (or ignored) symbol to end of translated
translated = translated + letters[num]
else:
translated = translated + symbol
#print string to screen
print(translated)
| true |
9824d2caf0208b039ad6f268b17bdb8e96be0891 | Kim-Ly-L/LPTHW | /EX19/ex19.py | 1,050 | 4.15625 | 4 | # The function; it's gonna take in all the following arguments:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
# First argument
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
# Second argument (a little bit annoying though since it's extra work...
# ... in comparison to l.11)
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# Math, not much to add to that
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
# Okay that's interesting,apparently, the function can combine arguments...
# ... or take information from a previous arg to implement the new arg
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
| true |
02177561a1e06a6934d46e83242c6e1f6ebca040 | shafreenasharief/lockdown-coding | /Oddeven.py | 728 | 4.15625 | 4 | # Python program to count Even and Odd numbers in a List
# list of numbers
list1 =[2, 7, 5, 64, 14]
list2 = [12, 14, 95, 3]
even_count, odd_count = 0, 0
num = 0
# using while loop
while(num < len(list1)):
# checking condition
if list1[num] % 2 == 0:
even_count += 1
else:
odd_count += 1
# increment num
num += 1
print("Even:", even_count)
print("Odd: ", odd_count)
even_count=0
odd_count=0
num = 0
while(num < len(list2)):
# checking condition
if list2[num] % 2 == 0:
even_count += 1
else:
odd_count += 1
# increment num
num += 1
print("Even:", even_count)
print("Odd: ", odd_count)
| true |
c063ead7beef8d353b2d53d9b7d3d651935c24c6 | DecadentOrMagic/XY_python3_lxf | /02_函数/01_调用函数.py | 998 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 通过help(x)查看x函数的帮助信息
# help(abs)
# 调用abs函数(求绝对值的函数)
print(abs(100))
print(abs(-10))
print(abs(12.34))
# 调用函数的时候,如果传入的参数数量不对,会报TypeError的错误,并且Python会明确地告诉你:abs()有且仅有1个参数,但给出了两个
# abs(1,2)
# 如果传入的参数数量是对的,但参数类型不能被函数所接受,也会报TypeError的错误,并且给出错误信息:str是错误的参数类型
# abs('s')
# max()可以接收任意多个参数,并返回最大的那个
print(max(1,2,5,-8))
# 数据类型转换函数
print(int('123'))
print(int(12.34))
print(float('12.34'))
print(str(1.23))
print(str(100))
print(bool(1))
print(bool(''))
print(bool('dafjdaldf'))
# 函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”
a = abs
print(a(-1))
| false |
33b121e90fb9a3ea8f1c6a766ff919b1d7c3edcb | DecadentOrMagic/XY_python3_lxf | /03_高级特性/01_切片.py | 2,041 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 取一个list或tuple的部分元素是非常常见的操作。比如,一个list取前3个元素,组成一个新的list应该怎么做?
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
# 笨办法:
l = [L[0],L[1],L[2]]
print(l)
# 如果取前n个元素组成一个新的list怎么办?
r = []
n = 3
for i in range(n):
r.append(L[i])
print(r)
# 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了切片(Slice)操作符,能大大简化这种操作。
# 对应上面的问题,取前3个元素,用一行代码就可以完成切片:
print(L[0:3])
# L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
# 如果第一个索引是0,还可以省略:
print(L[:3])
# 类似的,既然Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片
print(L[-2:])
# 记住倒数第一个元素的索引是-1
print(L[-2:-1])
# 切片操作十分有用。我们先创建一个0-99的数列
L = list(range(100))
print(L)
# 取前十个数
print(L[:10])
# 取后10个数
print(L[-10:])
# 前11-20个数
print(L[11:20])
# 前十个数,每两个取一个
print(L[:10:2])
# 所有数,每五个取一个
print(L[::5])
# 什么都不写,只写[:]就可以原样复制一个list
print(L[:])
# tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple
t = tuple(range(10))
print(t[:3])
print((0,1,2,3,4,5)[:3])
# 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
s = 'ABCDEFGH'
print(s[:3])
print('ABCDEFGH'[:3])
# 在很多编程语言中,针对字符串提供了很多各种截取函数(例如,substring),其实目的就是对字符串切片。Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单。
| false |
ed1b91d772d81bceb6dfc8038279c674059db041 | Gabriel2409/pytricks | /c4_07_08_iterator_slice_and_skip.py | 1,427 | 4.125 | 4 | #%%
"""
slice of iterator
skip first part of iterator
"""
#%%
mylist = [0, 1, 2, 3, 4, 5, 6]
mylist[1:3] # it works
# %%
iter(mylist)[1:3] # does not work
# %%
def count():
n = 0
while True:
yield n
n += 1
# %%
mycount = count()
# %%
mycount[10:20] # does not work either
# %%
import itertools
for element in itertools.islice(mycount, 10, 20):
print(element)
# %%
next(mycount) # huh It seems i consumed my iterator !
# %%
# * lets play with slicer. What happens if i iterate through my iterator and the slicer at the same time ?
mycount2 = count()
slicer = itertools.islice(mycount2, 10, 15, 2)
# %%
next(mycount2)
# %%
next(slicer)
# %%
"""
slicer consumed the iterator until it found the desired item (the one at index 10 in the remaining iterator); Then each time i call it, it looks at the current item in the iterator and adds 2. It keeps an internal count to stop at the right moment
"""
# %%
# * Skip first part of iterable
with open("fake_config.txt", "wt") as f:
f.write("#\n")
print("# fake comment", file=f)
print("# another fake comment", file=f)
print("beginning of the file", file=f)
print("# comment in the file", file=f)
print("middle of the file", file=f)
print("end of the file", file=f)
# %%
with open("fake_config.txt", "rt") as f:
for line in itertools.dropwhile(lambda line: line.startswith("#"), f):
print(line, end="")
# %% | true |
0a1043d807267ffc6a340fcd599c8e3dffc719f9 | Gabriel2409/pytricks | /52_array_datastruct.py | 1,963 | 4.1875 | 4 | # %%
"""
lists, tuples
array
str
bytes
ascii experiments
"""
# %% Array are contiguous data structures : They store information in adjoining blocks of memory. (by opposition to linked data structure which are chunks of memory linked by pointer, like linked-lists)
# %% lists are dynamic array : elements can be added or removed and python will automatically add or release memory
# You can hold different types together but the downside is that the data is less tightly packed => more memory needed
list((1,2,3)) # nice repr
# %%
# lists are mutable
a = [1, 2, 3]
a[1] = "fff"
print(a)
del a[1]
print(a)
# %%
# lists can hold arbitrary data type
[1,"44f", (1,2,3), [1,2], {4:4}]
# %% Tuples (immutable containers) : all elements must be defined at creation time
tup = 1,2,"three"
print(tup)
# %%
tup[1] = "rr"
# %%
del tup[2]
# %%
# adding element create copy of the tuple
tup + ("banzai",)
# %%
# Array from array module : only support one type (must be specified at creation)
import array
aa = array.array('d',[1,2])
print(aa)
aa[1] = "45"
# %%
# str
data = [12,25,31,42,54,67]
data2 = [0,0,0,0,0,0]
for i in range(len(data)):
j = data[i]
if j % 2:
data2[i] = j
print(data2)
# %% str : immutable and recursive
mystr = "test"
print(type(mystr), type(mystr[1]))
# %%
mystr[1] ="e"
# %%
del mystr[2]
# %% unpacking
print(list(mystr))
# %%
print("/".join(list(mystr)))
# %%
# bytes : immutable sequences of single bytes (integer between 0 and 255)
# bytes are immutable but have a dedicated mutable type (bytearray)
arr = bytes((0,1,25,63))
print(arr[1])
# %% bytes have their own syntax
print(arr)
# %% range in 0 - 255
bytes((0,566))
# %%
arr[1] = 2
# %%
del arr[1]
# %% bytearray
arr2 = bytearray(arr)
arr2[1] = 5
# %%
# key takeaway : if you need to use array datastructures, start with a list or a tuple. If you have a very specific usecase, change the type then (it is often useful in the optimization part, not at first).
| true |
3b41eb01de5c747ae6644d26e56141067c002f16 | altynaisalieva/PG1926 | /largestNum.py | 454 | 4.15625 | 4 |
def maxNum (arr,n):
max=arr[0];
for i in range (1,n):
if (arr[i]>max):
max=arr[i];
return max
if __name__ == "__main__" :
arr = [];
number=int(input("Enter number of elements: "))
for i in range(0,number):
arr1=int(input("Enter num to array: "))
arr.append(arr1)
n = len(arr);
print(arr)
maxn=maxNum(arr,n)
print("Largest in given array is ", maxn)
| true |
48578fa080347c7e9467d8d0fcbb81141daa2bc8 | BettM/love_python_game | /love_game.py | 1,515 | 4.125 | 4 | print("Welcome to my first game better half")
name = input("What is your name ? ")
age = int(input("What is your age? "))
print("hello",name,"you are",age,"years old")
if age >= 18:
print("You are old enough to date!")
play = input(print("Do you want to date me?")).lower()
if play == "yes":
print("Al ask some questions if you get them right we date!")
love = input(print("Do you love me?"))
if love == "yes":
print("yes..I love you")
feelings =input(print("Do you have any feelings for me?"))
if feelings == "yes":
print("Thats love at first sight..i aint intrested")
else:
print("i believe you aint sure..please do some soul searching")
elif love == "no":
print("we cant force love")
friends = input(print("can we be friends?"))
if friends == "yes":
print("Its is nice having you as my friend")
drink=input(print("Do you drink alcohol"))
if drink=="yes":
print("sorry we cant be friends.byee")
else:
print("Hope to have an awsome time ahead as we share ideas")
else:
print("see yah")
else:
print('Sorry Darling you ain\'t my type')
else:
print("thanks for your time,you are just pretty too young to date")
| true |
c2902f32ee1cf532bae58b533af7affe58f61004 | ab-be/freight-transport-network | /dijkstra/modules/dijkstra.py | 2,362 | 4.375 | 4 | def dijkstra(graph, node_a, node_z):
"""
Implementation of dijkstra shortest path algorithm.
Find the shortest path between vertex 'a' and 'z' from a weighted graph
with links.
Args:
graph: Dictionary-like Graph with all the nodes and its weighted links.
node_a: Node of origin.
node_z: Node of destination.
"""
# check nodes are in graph
assert node_a in graph
assert node_z in graph
# infinite will be the sum of all weights
inf = 0
for node in graph:
for link, weight in graph[node]:
inf += weight
# set initial distances to node_a of all nodes as infinite
node_distances = dict([(node, inf) for node in graph])
# set distance of node_a to itself to zero
node_distances[node_a] = 0
# create a set with all nodes in the graph
nodes_set = set([node for node in graph])
# create a dictionary that will have the previous vertix of each node
previous_vertix = {}
# aux method to get distance of a certain vertix to node_a
def get_distance(vertix):
return node_distances[vertix]
# main iteration of dijkstra algorithm
while node_z in nodes_set:
# get node with minimum distance from the set of nodes
node = min(nodes_set, key=get_distance)
# remove selected node from the set
nodes_set.discard(node)
# iterate through vertices of the selected node
for vertix, weight in graph[node]:
# check if vertix is in the set
if vertix in nodes_set:
# check if path through this vertix would be shorter
if node_distances[node] + weight < node_distances[vertix]:
# update distance of vertix with the shorter one found
node_distances[vertix] = node_distances[node] + weight
# update the previous_vertix to be the new closer node
previous_vertix[vertix] = node
# reconstruct the path found creating a list of nodes
path_to_z = []
node = node_z
while node != node_a:
path_to_z.append(node)
node = previous_vertix[node]
path_to_z.append(node_a)
path_to_z.reverse()
# get the distance of node_z from node_a
distance_to_z = node_distances[node_z]
return distance_to_z, path_to_z
| true |
f2c00e14bd0415d57a538e08bf84be8038b426b7 | PhilipB777/P-and-S | /es.py | 1,194 | 4.1875 | 4 | # Philip Brady
# This is the Weekly Task 7.
# The program takes in the name of a file and returns
# the total number of e's contained within the file text.
filename = input("Enter the file name: ")
# Initialised the e counter.
ecount = 0
# Opened the inputed file in the read format.
with open (filename, 'r') as f:
# This loop goes through each line in the file.
for line in f:
# The split function is used to create a list
# of words for each line.
words = line.split()
# This nested loop goes through each word of the
# words list.
for word in words:
# This nested loop goes through each letter
# of the word.
for letter in word:
# If the letter is an 'e' then the e
# counter is increased by 1.
if letter == "e":
ecount += 1
print("The total number of e's in the file '{}' is {}."
.format(filename, ecount))
# I got the idea for this code from
# https://www.sanfoundry.com/python-program-read-file-counts-number/
# I also studied the split function further in
# https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str | true |
8e9c06bc2938283a92731e415ea163c4bb2b019a | artorious/python3_dojo | /closure_in.py | 809 | 4.28125 | 4 | #!/usr/bin/env python3
"""Demonstration of a simple closure
An example of a closure transporting a captured variable into a
function call.
NOTE:
A closure is a function that can capture the context of its surrounding
environment.
"""
def evaluate(function, param1, param2):
"""
Returns <function>, called with <param1> and <param2>
"""
return function(param1, param2)
if __name__ == '__main__':
from custom_modules.get_integer_from_user import get_integer
print('Guess my age or DOB : ', end='')
sample = get_integer() # Var : Only captured by lambda expr, not evaluate()
# Call evaluate() with a function (lambda expression) and two integer values
print(evaluate(
lambda x, y: True if x == sample or y == sample else False, 30, 1987
))
| true |
d5a9853e4387507b131c1164d1845a86e6f56329 | artorious/python3_dojo | /add_non_negatives.py | 569 | 4.4375 | 4 | #!/usr/bin/env python3
''' Adds up a sequence of non-negative integers from user.
User ends list with a negative integer to display the sum of the non-negative
integers. Displays 0 if the user enters no non-negative integers.
'''
# Init
entry = 0 # Control loop
sum = 0
# Get user input
print('Enter numbers to sum up, negative numbers ends list: ')
while entry >= 0:
try:
entry = int(input('>>> '))
if entry > 0: # Check for negative integer
sum += entry
except ValueError:
print('Expected integers')
print('Sum =', sum) | true |
460c460e817e5ce024ec99cf1bd707bc2445cacb | artorious/python3_dojo | /custom_modules/circle.py | 2,074 | 4.59375 | 5 | #!/usr/bin/env python3
""" A play at Python Custom Types - Circle Objects
Attributes:
center: A tuple representing the Circle's center's (x,y) coordinates
radius: An integer representing the Circle's radius
"""
class Circle(object):
""" Represents a geometric circle object """
def __init__(self, center, radius=1):
""" (Circle, tuple, float) -> Circle
Initialize instance variables
The Circle's center's <center> and <radius>;
negative radius not accepted
"""
# Disallow a negative radius
if radius < 0:
raise ValueError('Negative radius: NOT VALID')
self.center = center
self.radius = radius
def get_radius(self):
""" (Circle) -> float
Return the radius of the circle
"""
return self.radius
def get_center(self):
""" (Circle) -> tuple
Return the coordinates of the center
"""
return self.center
def get_area(self):
""" (Circle) -> float
Compute and Return the area of the circle
"""
from math import pi
return pi * self.radius * self.radius
def get_circumference(self):
""" (Circle) -> float
Compute and Return the circumference of the circle
"""
from math import pi
return 2 * pi * self.radius
def move(self, new_pos):
""" (Circle, tuple) -> tuple
Moves the center of the circle to point <new_pos>
performs variable re-assignment
"""
self.center = new_pos
def grow(self):
""" (Circle) -> float
Increases the radius of the circle
performs variable re-assignment
"""
self.radius += 1
def shrink(self):
""" (Circle) -> float
Decreases the radius of the circle;
does not affect a circle with radius zero
performs variable re-assignment
"""
if self.radius > 0:
self.radius -= 1
| true |
3e2c18187040b0a46188af335e199d8c93b20ab2 | artorious/python3_dojo | /find_factors.py | 1,115 | 4.1875 | 4 | #!/usr/bin/env python3
'''Prints all the integers and their associated factors from 1-n'''
from custom_modules.get_positive_number_from_user import get_positive_num
print(__doc__) # Program Greeting
# init
count = 1 # Start from 1 (The numbers being examined)
value = int(get_positive_num()) # Get positive integer from user
##------- The Algorithm -------- ##
while count <= value: # Dont go past max
factor = 1 # 1 is a universal factor
print('{0:>3}: '.format(repr(count)), end='') # Which integer are we examining?
while factor <= count: # Factors are <= the number being examined
if count % factor == 0: # Test whether factor is a factor of the number being examined
print(factor, end=' ') # Dispaly the factor if yes
factor += 1 # Try next possible factor
print() # Move to the next line
count += 1 # Examine next number
| true |
44a5e94920ae4b70aa0c57bb627b385c6b7d74cc | artorious/python3_dojo | /regular_generator.py | 614 | 4.28125 | 4 | #!/usr/bin/env python3
""" A play at generators
NOTE:
A generator is an object that generates a sequence of values.
Code that uses a generator may obtaian one value at a time without the
possibility of revisiting earlier values. (consume a generator's product)
"""
def generate_multiples(m, n):
"""
Create a generator inside of a function and 'return' it with yield keyword
Yields the first <n> multiples of <m>
"""
count = 0
while count < n:
yield m * count
count += 1
if __name__ == '__main__':
for mult in generate_multiples(3, 6):
print(mult) | true |
64fd329320f88651ab34ddc760a7f089c19acf22 | artorious/python3_dojo | /custom_modules/graphical_object.py | 2,005 | 4.25 | 4 | #!/usr/bin/env python3
""" A graphical object on a Turtle graphics Window """
from multiple_inheritance_sample import Top
class GraphicalObject(Top):
"""
A Graphical object that allows the user to reposition it anywhere
within the widow using the mouse.
Contains all the code to manage the Turtle graphics environment.
"""
def __init__(self, **kwargs):
""" Initializes a GraphicalObject object
Keyword args include:
screen is the Turtle graphics screen
turtle is the Turtle graphics pen
intially appear at location (x, y)
"""
super(GraphicalObject, self).__init__(**kwargs) # Explicitly invoke superclass constructor
print('Initializing graphical object')
self.screen = kwargs['screen']
self.turtle = kwargs['turtle']
self.x_pos = kwargs['x_pos']
self.y_pos = kwargs['y_pos']
self.screen.delay(0) # Fastest drawing speed
self.turtle.speed(0) # Fastest turtle actions
self.turtle.hideturtle() # make turtle invisible
self.screen.onclick(self.do_click) # Set mouse press handler
self.move_to(x_pos=kwargs['x_pos'], y_pos=kwargs['y_pos'])
def run(self):
""" Run the graphical program """
self.screen.mainloop()
def draw(self):
""" Renders the object within the window.
Derived classes override this method to meet their specific needs
"""
pass
def do_click(self, x_pos, y_pos):
""" Called when the user presses the mouse button
(<x_pos>, <y_pos>) is the new location of the display
"""
self.move_to(x_pos, y_pos) # Move to a new location
self.draw() # Redraw at new location
def move_to(self, x_pos, y_pos):
""" Relocates a movable object to position (<x_pos>, <y_pos>) """
self.x_pos, self.y_pos = x_pos, y_pos
| true |
ebbc51ceda672bb22927a6922af238ce0fad63af | artorious/python3_dojo | /skip_ahead_with_continue.py | 395 | 4.1875 | 4 | #!/usr/bin/env python3
'''Skip ahead to the next iteration.
Reads an integer, prints it's square if it's odd, and skip if it's even.
'''
while True:
value = input('Integer, please [q to quit]: ')
if value.upper() == 'Q': # Quit
break
number = int(value)
if number % 2 == 0: # Even No.
continue
print('{0:,} squared is {1:,}'.format(number,number * number))
| true |
4156610ba9e0bce91475077f8ccf46ddb39c4302 | artorious/python3_dojo | /box_measure_dimensions.py | 2,684 | 4.375 | 4 | #!/usr/bin/env python3
""" A play on Local Function Definitions """
from math import fabs
def surface_area(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4,
x5, y5, z5, x6, y6, z6, x7, y7, z7, x8, y8, z8):
"""(floats) -> float
Computes the surface area of a rectangular box (cuboid) defined by the
3D points (x,y,z) of it's eight corners
7------8
/| /|
3------4 |
| | | |
| 5----|-6
|/ |/
1------2
"""
# Local helper function to compute area
def area(length, width):
""" Computes the area of a <length> x <width> rectangle """
return length * width
# Init dimensions
length = fabs(x2 - x1)
height = fabs(y3 - y1)
width = fabs(z5 - z1)
front_area = area(length, height) # Front face
side_area = area(width, height) # Side face
top_area = area(length, width) # Top face
# Surface Area: front/back face, left/right face, top/bottom face
return (2 * front_area) + (2 * side_area) + (2 * top_area)
def volume(length, width, height):
""" (float, float, float) -> float
Computes the volume of a rectangular box (cuboid) defined by it's
length, width and height
"""
return length * width * height
def get_point(msg):
"""(str) -> tuple
prints a message specified by <msg> and allows the user to enter the
(x, y, z) coordinates of a point.
Returns the point as a tuple
"""
print(msg)
x = float(input('Enter x coordinate: '))
y = float(input('Enter y coordinate: '))
z = float(input('Enter z coordinate: '))
return x, y, z
def main():
"""
Get coordinates of the box's corners from the user
Compute then display surface area and volume of the box
"""
print('Enter the coordinates of the box\'s corners')
print('''
7------8
/| /|
3------4 |
| | | |
| 5----|-6
|/ |/
1------2
''')
x1, y1, z1 = get_point('Corner 1')
x2, y2, z2 = get_point('Corner 2')
x3, y3, z3 = get_point('Corner 3')
x4, y4, z4 = get_point('Corner 4')
x5, y5, z5 = get_point('Corner 5')
x6, y6, z6 = get_point('Corner 6')
x7, y7, z7 = get_point('Corner 7')
x8, y8, z8 = get_point('Corner 8')
print('Surface Area: {0}'.format(surface_area(
x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, x5, y5, z5,
x6, y6, z6, x7, y7, z7, x8, y8, z8
)))
# Init dimensions
length = fabs(x2 - x1)
height = fabs(y3 - y1)
width = fabs(z5 - z1)
print('Volume : {0}'.format(volume(length, width, height)))
if __name__ == '__main__':
main()
| true |
f44d72f2f068922721e031382dc273994bd2f4c4 | pBogey/hello-world | /06. Loops/02. The Collatz 3n + 1 sequence.py | 1,339 | 4.3125 | 4 | """
30.08.2018 20:19
Taken from How To Think Like a Computer Scientist 3rd edition
Collatz 3n+1 sequence: the interesting question was first posed by a German mathematician called Lothar Collatz: the
Collatz conjecture (also known as the 3n + 1 conjecture), is that this sequence terminates for all positive values of n.
So far, no one has been able to prove it or disprove it! (A conjecture is a statement that might be true, but nobody
knows for sure.)
"""
def arguments(prompt_msg):
while True: # create loop for error check
try:
variable = float(input(prompt_msg)) # convert user input to integer
except ValueError:
# if input is not a number, retry
print("invalid number, please try again:")
continue
else:
# user input was valid, end
break
return variable
n = arguments("Please input a value for n: ")
print("n =", n, "\n")
print('while n != 1: \nprint(n, end="; ") \nif n % 2 == 0: \nn = n // 2 \nelse: \nn = n * 3 + 1\n\n')
while n != 1:
print(n, end="; " '\t') # put ";" after every "n" printed and shift cursor to next tab stop
if n % 2 == 0: # n is even
n = n // 2
else: # n is odd
n = n * 3 + 1
print(n, end=".\n") # print "." after the last "n" printed
| true |
fd73676c24c7b8ddd26f3323cd064142a094b033 | pBogey/hello-world | /14. Random/03. RandomList.py | 860 | 4.125 | 4 | """
16.12.2018 22:31
Create random list of integers
Bogdan Prădatu - Example from How to Think Like a Computer Scientist 3rd Edition
"""
import random
def random_int_list(n, lower, upper):
"""
Generate a list containing 'n' random ints between
'lower' bound and 'upper' bound. Upper bound is an open bound.
The result list cannot contain duplicates.
"""
rand_list = []
rng = random.Random()
if n > upper - lower:
return "'n' must be at least equal to the range"
else:
for i in range(n):
while True:
candidate = rng.randrange(lower, upper)
if candidate not in rand_list:
break
rand_list.append(candidate)
return rand_list
print(random_int_list(5, 1, 10000000))
print(random_int_list(10, 0, 10))
print(random_int_list(10, 1, 6))
| true |
00ff323c2f82938c5de76e22a2cf107d2c0ab884 | pBogey/hello-world | /08. Strings/ReverseString.py | 823 | 4.3125 | 4 | """
18.11.2018 20:07
reverse string letters
"""
print("This program will reverse the elements of a string \n")
string1 = input("Enter your text: ")
def rev(string):
"""Reverses the order of elements of given string.
String must be previously defined."""
string2 = ""
i = 0
for w in string:
string2 += string[len(string)-1-i]
i = i + 1
return string2
print(string1)
print(rev(string1))
print("\nMirror function: ", string1+rev(string1))
def test_rev():
test_string1 = "happy"
test_string2 = "Python"
test_string3 = ""
test_string4 = "a"
if (
rev(test_string1) == "yppah"
and rev(test_string2) == "nohtyP"
and rev(test_string3) == ""
and rev(test_string4) == "a"):
print("\n\nTest ok!")
test_rev()
| true |
83daa149e69c2426c55b0ca5f9dec598cd3bd512 | 0neMiss/cs-module-project-hash-tables | /hashtable/ex4.py | 1,147 | 4.15625 | 4 |
def has_negatives(list):
# Your code here
#if the list has a length
if len(list) > 0:
#populating the dictionary with the list with the iteration as the key: and the value at the index as the value
dict = {i: list[i] for i in range(0 ,len(list))}
print(dict)
result = []
neg_list = []
for item in range(0, len(dict)):
#set variable for the value at the index
value = dict.get(item)
if value <= 0:
neg_list.append(value)
else:
print(value)
#if the value at that index is greater than 0 calculate the negative version of that number
num_neg = value - (value * 2)
print(num_neg)
#if that exists in the dictionary
if num_neg in neg_list:
print(value)
#append to the result array
result.append(value)
print(result)
return result
else:
return None
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.