blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
dcf82c1d994f980388094411e11da0c36af8b939
|
BhagyashreeKarale/function
|
/output2.py
| 1,629
| 4.28125
| 4
|
# def primeorNot(num):
# if num > 1:#it will only take numbers more then 1,not even 1
# for i in range(2,num):#all the numbers from 2 to the given number.i.e in this case 406
# if (num % i) == 0:
# print(num,"is not a prime number")
# print(i,"times",num//i,"is",num)
# break#break can be ysed only within a loop
# else:#else block is at wrong place
# print(num,"is a prime number")
# else:#for 1 or less than 1
# print(num,"is not a prime number")
# primeorNot(407)
# this program will give result based on the respective i
# for example:
# consider number 9
# we are starting the loop from num 2
# therefore as 9 is not divisible by two, it will print 9 is a prime number,which is False
# next i value is 3
# 9 is divisible by 3
# therefore now it will print 9 is not a prime number and we have applied break statement under this block
# therefore now the loop will stop
# this ain't the correct code
def primeorNot(num):
if num > 1:#it will only take numbers more then 1,not even 1 406
for i in range (2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:#for 1 or less than 1
print(num,"is neither a prime number nor a composite number")
primeorNot(407)
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<output>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>#
# 407 is not a prime number
# 11 times 37 is 407
| true
|
ab111b6810f7652e3f3b52e2eb1934971f8484c9
|
BhagyashreeKarale/function
|
/palindrome.py
| 622
| 4.375
| 4
|
# Write a Python function that checks whether a passed string is palindrome or not.
def palindromecheck(string):
rlist=(string[::-1])
if rlist == string:
print("It is a palidrome")
else:
print("It isn't a palidrome")
# another one for palidrome:
def palidromecheck2(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos <= left_pos:
if string[right_pos] != string[left_pos]:
print("It isn't a palidrome")
return False
left_pos = left_pos + 1
right_pos = right_pos - 1
print("It is a palidrome")
return True
| true
|
fa78625e9347e095937a81f272cfd909fc52a231
|
DanielFernandoYepezVelez/Fundamentos-Python
|
/18-EjerciciosComfenalco/04-DecisionesLogicasCuartaClase/07-NumeroMayor.py
| 528
| 4.25
| 4
|
numeroUno = float(input('Ingrese Un Numero Uno: '))
numeroDos = float(input('Ingrese Un Numero Dos: '))
numeroTres = float(input('Ingrese Un Numero Tres: '))
print('')
if numeroUno > numeroDos and numeroUno > numeroTres:
print(f'El Numero Mayor Es: {numeroUno}')
elif numeroDos > numeroUno and numeroDos > numeroTres:
print(f'El Numero Mayor Es: {numeroDos}')
elif numeroTres > numeroUno and numeroTres > numeroDos:
print(f'El Numero Mayor Es: {numeroTres}')
else:
print('Todos Los Numeros Son Iguales')
| false
|
8adc894f3d9f759ba556e3f5038e058aff0b357e
|
DanielFernandoYepezVelez/Fundamentos-Python
|
/03-Operadores/07-FuncionesNumeros.py
| 988
| 4.15625
| 4
|
SEPARADOR = '-----------------------'
def suma(a = 0, b = 0):
print(a + b)
print('\nSuma => ')
suma(5.1, 4.9)
suma(2.999, 33)
suma(3)
print(f'{SEPARADOR}\n')
def resta(a = 0, b = 0):
print(a - b)
print('Resta => ')
resta(12.2, .2)
resta(5, 10)
resta(5)
print(f'{SEPARADOR}\n')
def producto(a = 0, b = 0): return a * b
productoUno = producto(5, 5)
productoDos = producto(7.5, 6.12)
productoTres = producto(7)
print('Producto => ')
print(productoUno)
print(productoDos)
print(productoTres)
print(f'{SEPARADOR}\n')
""" OJO CON EL CERO!!! """
def division(a = 0, b = 0): return a / b
divisionUno = division(8, 4)
divisionDos = division(5.4, 3.4)
divisionTres = division(5, 5)
print('División => ')
print(divisionUno)
print(divisionDos)
print(divisionTres)
print(f'{SEPARADOR}\n')
def modulo(a = 0, b = 0): return a % b
moduloUno = modulo(4, 2)
moduloDos = modulo(5, 3)
moduloTres = modulo(7, 9)
print('Modulo => ')
print(moduloUno)
print(moduloDos)
print(moduloTres)
| false
|
d924bc7e14da2270ea730ebcef771abbe9cd065f
|
DanielFernandoYepezVelez/Fundamentos-Python
|
/11-Diccionarios/04-MasMetodos.py
| 944
| 4.15625
| 4
|
SEPARADOR = '--------------------'
jugador = {}
print(jugador)
print(f'{SEPARADOR}\n')
""" Para Agregar Un Nuevo Jugador Al Diccionario Vacio """
jugador['nombre'] = 'Danielito Fernandito'
jugador['puntaje'] = 0
print(jugador)
print(f'{SEPARADOR}\n')
# Incrementando El Puntaje
jugador['puntaje'] = 110
print(jugador)
print(f'{SEPARADOR}\n')
""" Acceder A Un Valor Existente En El Diccionario """
print(jugador.get('puntaje'))
print(f'{SEPARADOR}\n')
""" Acceder A Un Valor Que NO!! Existe En El Diccionario """
print(jugador.get('consola'))
print(jugador.get('consola', 'No Existe En El Diccionario')) # Mensaje Personalizado
print(f'{SEPARADOR}\n')
""" Iterar En Los Diccionarios (Objetos), Muy Similar Como Se Puede Iterar En Las Listas (Arrays)"""
for llave, valor in jugador.items():
print(f'llave: {llave} Valor: {valor}')
print(f'{SEPARADOR}\n')
""" Eliminar De La Lista """
del jugador['nombre']
del jugador['puntaje']
print(jugador)
| false
|
72871b67dd71410aedb185651c2764a1397aa5f0
|
DorotaNowak/machine-learning
|
/simple-linear-regression/simple_linear_regression.py
| 1,057
| 4.15625
| 4
|
# Simple linear regression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Salary_Data.csv')
# print(dataset.head())
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)
# Fitting Simple Linear Regression to the training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the test set results
y_pred = regressor.predict(X_test)
# Plots
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train))
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train))
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
| true
|
b10395a36be87b043ed18ad3973f2ae4eeb955ca
|
tdominic1186/ATBS
|
/Chapter 2/question13while.py
| 214
| 4.28125
| 4
|
"""
13. Write a short program that prints the numbers 1 to 10 using a for loop.
Then write an equivalent program that prints the numbers 1 to 10 using
a while loop.
"""
i = 1
while i < 11:
print(i)
i += 1
| true
|
e168e246982a5e6861163b33e13510592705ae44
|
adivis/PythonProg
|
/prob_5.py
| 1,233
| 4.1875
| 4
|
"""
Problem Statement:-
You are given few sentences as a list (Python list of sentences). Take a query string as an input from the user. You have to pull out the sentences matching this query inputted by the user in decreasing order of relevance after converting every word in the query and the sentence to lowercase. Most relevant sentence is the one with the maximum number of matching words with the query.
Sentences = [“Python is cool”, “python is good”, “python is not python snake”]
Input:
Please input your query string
“Python is”
Output:
3 results found:
python is not python snake
python is good
Python is cool
"""
print("Enter the length of list of sentences")
n = int(input())
lst_sen = []
for i in range(n):
print("enter the sentence in list")
lst_sen.append(input().lower())
print(lst_sen)
search = input("Please enter your query\n").lower()
print(search)
search_lst = search.split(' ')
print(search_lst)
lst_occ = []
for i in lst_sen:
count = 0
for j in search_lst:
if i.count(j)>0:
count = count + i.count(j)
lst_occ.append(count)
for i in range(0,len(lst_sen)):
print(lst_sen[lst_occ.index(max(lst_occ))])
lst_occ[lst_occ.index(max(lst_occ))] = -2
| true
|
5122893d898726377da5c2910fca3575eeb09348
|
my-xh/DesignPattern
|
/01创建型模式/05原型模式/克隆模式.py
| 1,036
| 4.34375
| 4
|
from copy import copy, deepcopy
class Clone:
"""克隆的基类"""
def clone(self):
"""浅拷贝"""
return copy(self)
def deep_clone(self):
"""深拷贝"""
return deepcopy(self)
class Person(Clone):
"""人"""
def __init__(self, name, age):
self.__name = name
self.__age = age
def show_myself(self):
print(f'我是 {self.__name}, 年龄 {self.__age} .')
def coding(self):
print('我是码农,我用程序改变世界,Coding......')
def reading(self):
print('阅读使我快乐! 知识使我成长! 如饥似渴地阅读是生活的一部分......')
def fall_in_love(self):
print('春风吹, 月亮明, 花前月下好相约......')
if __name__ == '__main__':
tony = Person('tony', 27)
tony.show_myself()
tony.coding()
print()
tony1 = tony.clone()
tony1.show_myself()
tony1.reading()
print()
tony2 = tony.deep_clone()
tony2.show_myself()
tony2.fall_in_love()
| false
|
add5d0a107fddbb992a75b508eda4f0d9b2e5b55
|
my-xh/DesignPattern
|
/01创建型模式/01工厂方法/简单工厂模式.py
| 1,214
| 4.15625
| 4
|
from abc import ABCMeta, abstractmethod
class Coffee(metaclass=ABCMeta):
"""咖啡"""
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@abstractmethod
def get_taste(self):
pass
class LatteCoffee(Coffee):
"""拿铁咖啡"""
def get_taste(self):
return '轻柔而香醇'
class MochaCoffee(Coffee):
"""摩卡咖啡"""
def get_taste(self):
return '丝滑与醇厚'
class Coffeemaker:
"""咖啡机"""
@staticmethod
def make_coffee(coffee_bean):
if coffee_bean == '拿铁咖啡豆':
coffee = LatteCoffee('拿铁咖啡')
elif coffee_bean == '摩卡咖啡豆':
coffee = MochaCoffee('摩卡咖啡')
else:
raise ValueError(f'不支持的参数: {coffee_bean}')
return coffee
if __name__ == '__main__':
latte = Coffeemaker.make_coffee('拿铁咖啡豆')
print(f'{latte.name} 已为您准备好了, 口感: {latte.get_taste()}。请慢慢享用!')
mocha = Coffeemaker.make_coffee('摩卡咖啡豆')
print(f'{mocha.name} 已为您准备好了, 口感: {mocha.get_taste()}。请慢慢享用!')
| false
|
764a3d777da00681901ef7251ac5c2925d57576c
|
kazamari/Stepik
|
/course_568/2.245_repetition coding.py
| 687
| 4.375
| 4
|
'''
Encoding of repeats is carried as the following: s = 'aaaabbсaa' is converted into 'a4b2с1a2', that is, the groups of
the same characters of the input string are replaced by the symbol and the number of its repetitions in this string.
Write a program that reads a line from the file corresponding to the string, compressed using the repetition coding, and
performs the reverse operation, obtaining the source string.
Output the obtained string into a file and attach it as a solution to this problem.
The original string does not contain any numbers; it means that the code is definitely interpretable.
Sample Input:
a3b4c2e10b1
Sample Output:
aaabbbbcceeeeeeeeeeb
'''
| true
|
9a34599d4bab721fd842873a090fe7ab2eb559ea
|
kazamari/Stepik
|
/course_431/3.2_Math functions.py
| 853
| 4.28125
| 4
|
'''
Напишите функцию f(x), принимающую дробное число x и возвращающую значение следующей функции, определённой на всей
числовой прямой:
f(x)=⎧⎩⎨⎪⎪1−(x+2)2,−x2,(x−2)2+1,при x≤−2при −2<x≤2при 2<x
Требуется реализовать только функцию, решение не должно осуществлять операций ввода-вывода.
Sample Input 1:
4.5
Sample Output 1:
7.25
Sample Input 2:
-4.5
Sample Output 2:
-5.25
Sample Input 3:
1.0
Sample Output 3:
-0.5
'''
def f(x):
# put your python code here
if x <= -2:
return 1 - (x + 2)**2
elif -2 < x <=2:
return -(x / 2)
elif x > 2:
return (x - 2)**2 + 1
| false
|
16b4c66261f6057635577382f87f38df85f3c289
|
kazamari/Stepik
|
/course_568/2.316_re-occurrence-of-a-symbol.py
| 2,386
| 4.625
| 5
|
'''
In this problem, we will look how to implement re-occurrence of a symbol using regular expressions.
We may use the three various constructions to implement the repeat:
1. Wildcards { }, inside which we can place the minimum/maximum number of repeats that we are satisfied with, or the
exact number of repeats that we are looking for. For example, the pattern "A{3, 5}" will fit all substrings, consisting
of consecutive characters А, with length from 3 to 5, and the pattern "T{4}" will fit only those substrings, which
contain 4 T in a row.
2. Wildcard *. This wildcard means any number of occurrences of a character (or a group of characters): from zero to
any number you want. Thus, the pattern "A*" fits all sequences, consisting of any number of consecutive А, and fits an
empty string (as zero also fits).
3. Wildcard +. This wildcard means any positive number of occurrences of a character (or a group of characters): from
zero to any number you want. This way, the pattern "A+" fits all sequences, consisting of any number of consecutive А.
Unlike "А*", the empty string will not fit.
All repeat meta characters are applied to a character after which they occur (or group of characters).
Examples of usage:
import re
results = re.findall("A+", "AAATATAGCGC")
print(results)
results = re.findall("TA{2}", "AATATAGCGTATA")
print(results)
Given the list of phone numbers (each line contains one phone number). Your task is to check whether these phone numbers
are "cool": a phone number is called "cool", if it contains 3 or more same digits in a row. For example, number
19992034050 is a "cool" one, but 19500237492 is not.
Your task is to leave only the cool numbers: the standard output should contain "cool" numbers, each number on a
separate line.
Sample Input:
89273777416
89273777167
89273776902
89273778915
89273778982
89273774216
89273771708
89273772982
89273775302
89273775244
89273777007
89273778140
89273778817
89273770487
89273772728
89273773272
89273777273
89273779341
89273779862
89273772225
Sample Output:
89273777416
89273777167
89273777007
89273777273
89273772225
'''
# Posted from PyCharm Edu
import re, sys
results = [line.strip() for line in sys.stdin if re.match(r'.*(\d)\1{2}.*', line)]
print('\n'.join(results))
| true
|
6afb4c76020ade8c19294dbd36574926ed37223f
|
kazamari/Stepik
|
/course_568/2.325_message-encoding.py
| 578
| 4.46875
| 4
|
'''
We will be dealing with a trivial example of message encoding, where the mapping of original symbols to the "code" is
simply taking the ASCII value of the symbol. For example, the "code" version of the letter 'A' would be 65.
You will be given as input a string of any length consisting of any possible ASCII characters. You must print out the
numerical ASCII value of each character of the string, separated by spaces.
Sample Input:
Hello, World!
Sample Output:
72 101 108 108 111 44 32 87 111 114 108 100 33
'''
print(' '.join([str(ord(i)) for i in input()]))
| true
|
7a09b5c4a6616f296b64ef2f9797799193fdc167
|
ZacharyLasky/Algorithms
|
/recipe_batches/recipe_batches.py
| 956
| 4.125
| 4
|
#!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
min_batch = None
for ingredient in recipe:
if ingredient in ingredients:
batches = ingredients[ingredient] // recipe[ingredient]
if min_batch is None:
min_batch = batches
else:
min_batch = min(batches, min_batch)
else:
return 0
return min_batch
recipe_batches(
{'milk': 2, 'sugar': 40, 'butter': 20},
{'milk': 5, 'sugar': 120, 'butter': 500}
)
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 100, 'butter': 50, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true
|
29a00d5c563dc100b8e3e07fd813b23838961cff
|
Nyajur/python-pill
|
/18 exponent_again.py
| 572
| 4.125
| 4
|
base = float(input("Please enter a number: "))
exponential = float(input("Pleae enter a power to raise to: "))
def raiser():
return base**exponential
print(raiser())
def raiser():
base = float(input("Please enter a number: "))
exponential = float(input("Pleae enter a power to raise to: "))
return base**exponential
print(raiser())
def raiser(base,exponential):
return base**exponential
print(raiser(2,4))
def raiser(base,exponential):
result = 1
for i in range(exponential):
result =result*base
return result
print(raiser(2,4))
| true
|
eaa3e22cabb29391f6aaf4531f8b76e7d465c321
|
xlaw-ash/VSLearn-Python
|
/PythonBasics/comprehensions.py
| 1,624
| 4.90625
| 5
|
# for loops have some special uses with List Comprehensions
# Make a list of letters in greeting string.
greeting = 'Hello World!'
letters = []
for letter in greeting:
letters.append(letter)
print(letters)
letters = []
# Above 3 statements can be combined in a single line.
letters = [letter for letter in greeting] # letter is added to list. It is same as append.
print(letters)
# Note that list comprehension is same as append method with loop. It is just a short way to create list.
# List comprehensions can be used with arithmetic operations
# Make a list of multiples of 5 from 1 to 50, i.e. Table of 5.
table_of_5 = [x * 5 for x in range(1,11)]
print(table_of_5)
# Make list of even numbers from 1 to 20
evens = [x for x in range(1,11) if x % 2 == 0]
print(evens)
# Nested List comprehensions
# Make a list of even multiples of 5
evens_5 = [x for x in [x * 5 for x in range(1,11)] if x % 2 == 0]
print(evens_5)
# Above nested statement looks a bit confusing, but it is quite simple. Inner list is created and then outer list is created from inner list.
# [x * 5 for x in range(1,11)] creates a list of multiples of 5 from 5 to 50.
# Outer list comprehension takes input from list of multiples of 5 and creates new list of even numbers in list of multiples of 5.
# Creating one list and then creating next list using first list is same as nested list comprehension.
# Note that above example is just to show nested list compreshension.
# More efficient way to make a list of even multiples of 5 by creating only one list.
evens_5 = []
evens_5 = [x * 5 for x in range(1,11) if (x * 5) % 2 == 0]
print(evens_5)
| true
|
8aac407392e79b9f910e117562de31c5dd678d7a
|
xlaw-ash/VSLearn-Python
|
/PythonBasics/booleans.py
| 2,490
| 4.625
| 5
|
# Booleans have only two values. Either True or False.
# Booleans are used for conditions.
yes = True
no = False
print(yes)
print(type(yes))
# Booleans are mostly used with logical operators. There are three main logical operators.
# 'and' operator between two conditions returns True only when both conditions are True, else it returns False.
print("'and' operator matrix")
print('and\tTrue\tFalse')
print(f'True\t{True and True}\t{True and False}')
print(f'False\t{False and True}\t{False and False}')
# 'or' operator between two conditions returns True when either condition is True.
print("'or' operator matrix")
print('or\tTrue\tFalse')
print(f'True\t{True or True}\t{True or False}')
print(f'False\t{False or True}\t{False or False}')
# 'not' operator is applied to a condition to reverse it's result. In other words, True becomes False and False becomes True
print(f'not false: {not False}')
print(f'not True: {not True}')
# There are various comparison operators which are used to get boolean result. [Left Value operator Right Value]
# '>' : Greater than operator. Returns True when Left Value is greater than Right Value.
print(3>2) # Prints True since 3 is greater than 2.
print(2>5) # Prints False
# '<' : Less than operator. Returns True when Left Value is less than Right Value.
print(3<2) # Prints False since 3 is greater than 2
print(2<5) # Prints True
# '==' : Equality operator. Returns True when both values are equal.
print(3==3) # Returns True since 3 is equal to 3.
print(3.0==3) # Returns True even though 3.0 is float and 3 is int because the values are same.
# Note that to check equality, two equal signs are used because single equal sign is used as assignment operator. a = 3 assigns 3 to a. a == 3 will check if a is equal to 3.
# '!=' : 'Not equal to operator'. This operator is used to check if the two values are unqual.
# Check if num is odd.
num = 15
print(num % 2 != 0) # Odd numbers are divisible by 2. So, the remainder of num divided by 2 should not be 0. This prints True.
# Check if num is even.
num = 20
print(num % 2 == 0) # Even numbers are divisible by 2. So, the remainder of num divided by 2 should be 0. This prints True
# '>=' : Returns True when Left Value is greater than or equal to Right value
# '<=' : Returns True when Left Value is less than or equal to Right value
# Print True if num is between 10 and 20 inclusive
num = 15
print(num >= 10 and num <= 20) # Prints True
num = 25
print(num >= 10 and num <= 20) # Prints False
| true
|
d4701afadc306985d744bdc1b613fd1a5330fd4b
|
kehillah-coding-2020/ppic04-ForresterAlex
|
/set_d.py
| 1,748
| 4.5625
| 5
|
#!/usr/bin/env python3
#
# pp. 148, 151
#
"""
4.36 Modify the frequency chart function to draw wide bars instead of
lines.
"""
"""
4.37* Modify the frequency chart function so that the range of the x axis
is not tightly bound to the number of data items in the list but
rather uses some minimum and maximum values.
"""
"""
4.38* Another way to compute the frequency table is to obtain a list of
key-value pairs using the `items` method. This list of tuples can be
sorted and printed without returning to the original dictionary.
Reqrite the frequency table function using this idea.
"""
"""
4.39* A good programming practice is to take a step back and look at your
code and to factor out the parts that you have reused into separate
functions. This is the case with our `frequencyTable()` function.
Modify `frequencyTable()` so that it returns the dictionary of
frequency counts it creates.
"""
"""
4.40* Now write a separate function to print the frequency table using the
dictionary created by the `frequencyTable()` function in the previous
problem.
"""
"""
4.41* Modify `frequencyChart()` from listing 4.10 to use the new
`frequencyTable()` function.
"""
"""
4.42 Modify the frequency chart function to include a graphical
representation of the mean.
"""
"""
4.43 Modify the frequency chart function to draw a line representing plus
or minus 1 standard deviation from the mean.
"""
"""
4.44 Using `random.uniform`, generate a list of 1,000 numbers in the range
0-50. Graph the frequency distribution along with the mean and
standard deviation.
"""
"""
4.45 Using the `random.gauss`, generate a list of 1,000 numbers in the
range 0-50. Graph the frequency distribution along with the mean and
standard deviation.
"""
| true
|
679e5e6734b9f3fa577e914c7b6ca3655dfc3884
|
StefanoskiZoran/Python-Learning
|
/Practise provided by Ben/Clock Calculator by Me.py
| 1,210
| 4.125
| 4
|
"""
Request the amount of seconds via keyboard, turn the seconds into months/days/years/decades etc.
"""
def main():
seconds_request = int(input(f'Please input your desired seconds: '))
minute_result = 0
hour_result = 0
day_result = 0
month_result = 0
year_result = 0
decade_result = 0
century_result = 0
millennia_result = 0
seconds = seconds_request % 60
minute_result = seconds_request / 60
minute = minute_result % 60
hour_result = minute_result / 60
hour = hour_result % 60
day_result = hour_result / 24
day = day_result % 60
week_result = day_result / 7
week = week_result % 7
month_result = day_result / 30
month = month_result % 30
year_result = month_result / 12
year = year_result % 12
decade_result = year_result / 10
decade = decade_result % 10
century_result = decade_result / 10
century = century_result % 10
millennia_result = century_result / 10
millennia = millennia_result % 10
print(f'{millennia:02.0f}:{century:02.0f}:{decade:02.0f}:{year:02.0f}:{month:02.0f}:{week:02.0f}:{day:02.0f}:{hour:02.0f}:{minute:02.0f}:{seconds:02.0f}')
if __name__ == '__main__':
main()
| true
|
8d57357f8a8dd14248f31e1478f1ce51918bf617
|
jaredjk/FunWithFunctions
|
/FunWithFunctions.py
| 482
| 4.125
| 4
|
# for i in range(1,2001):
# if i%2 !=0:
# print "Number is {}. This is an odd Nnumber".format(i)
# else:
# print "Number is {}. This is an even Nnumber".format(i)
def multiply(arr,num):
for i in range(len(arr)):
arr[i] *= num
return arr
a = [2,4,10,15]
b = multiply(a,5)
print b
def layered_multiples(arr):
for i in range(len(arr)):
arr[i] = [1]*arr[i]
return arr
x = layered_multiples(multiply([2,4,5],3))
print x
| false
|
254aa0ded80bba9f1cefcf1bee130276579604a6
|
KitsuneNoctus/makeschool
|
/site/public/courses/CS-1.2/src/PlaylistLinkedList-StarterCode/main.py
| 1,584
| 4.5
| 4
|
from Playlist import Playlist
playlist = Playlist()
while True:
# Prints welcome message and options menu
print('''
Welcome to Playlist Maker 🎶
=====================================
Options:
1: View playlist
2: To add a new song to playlist
3: To remove a song from playlist
4: To search for song in playlist
5: Return the length of the playlist
=====================================
''')
# Prints welcome message and options menu
user_selection = int(input('Enter one of the 5 options: '))
# Option 1: View playlist
if user_selection == 1:
playlist.print_songs()
# Option 2: To add a new song to playlist
elif user_selection == 2:
song_title = input('What song do you want to add? ')
playlist.add_song(song_title)
# Option 3: To remove a song from playlist
elif user_selection == 3:
song_title = input('What song do you want to remove? ')
playlist.remove_song(song_title)
# Option 4: To search for song in playlist
elif user_selection == 4:
song_title = input('Which song do you want to find? ')
index = playlist.find_song(song_title)
if index == -1:
print(f"The song {song_title} is not in the set list.")
else:
print(f"The song {song_title} is song number {index+1}")
# Option 5: Return the length of the playlist
elif user_selection == 5:
print(f"This set list has {playlist.length()} songs.")
# Message for invalid input
else:
print('That is not a valid option. Try again.\n')
| true
|
f3c543fb60d13114cd3e3b1b80176cae8c1f4d6b
|
KitsuneNoctus/makeschool
|
/site/public/courses/CS-2.2/Challenges/Solutions/challenge_1/src/vertex.py
| 1,155
| 4.25
| 4
|
class Vertex(object):
""" Vertex Class
A helper class for the Graph class that defines vertices and vertex neighbors.
"""
def __init__(self, vertex_id):
"""Initialize a vertex and its neighbors.
neighbors: set of vertices adjacent to self,
stored in a dictionary with key = vertex,
value = weight of edge between self and neighbor.
"""
self.id = vertex_id
self.neighbors = {}
def add_neighbor(self, vertex, weight=1):
"""Add a neighbor along a weighted edge."""
if vertex not in self.neighbors:
self.neighbors[vertex] = weight
def __str__(self):
"""Output the list of neighbors of this vertex."""
return f"{self.id} adjacent to {[x.id for x in self.neighbors]}"
def get_neighbors(self):
"""Return the neighbors of this vertex."""
return self.neighbors.keys()
def get_id(self):
"""Return the id of this vertex."""
return self.id
def get_edge_weight(self, vertex):
"""Return the weight of this edge."""
return self.neighbors[vertex]
| true
|
54433cda9ab97c3b60023dd046cc7aafc1f06908
|
KitsuneNoctus/makeschool
|
/site/public/courses/CS-2.1/Code/prefixtreenode.py
| 2,797
| 4.40625
| 4
|
#!python3
class PrefixTreeNode:
"""PrefixTreeNode: A node for use in a prefix tree that stores a single
character from a string and a structure of children nodes below it, which
associates the next character in a string to the next node along its path from
the tree's root node to a terminal node that marks the end of the string."""
# Choose an appropriate type of data structure to store children nodes in
# Hint: Choosing list or dict affects implementation of all child methods
CHILDREN_TYPE = list # or dict
def __init__(self, character=None):
"""Initialize this prefix tree node with the given character value, an
empty structure of children nodes, and a boolean terminal property."""
# Character that this node represents
self.character = character
# Data structure to associate character keys to children node values
self.children = PrefixTreeNode.CHILDREN_TYPE()
# Marks if this node terminates a string in the prefix tree
self.terminal = False
def is_terminal(self):
"""Return True if this prefix tree node terminates a string."""
# TODO: Determine if this node is terminal
def num_children(self):
"""Return the number of children nodes this prefix tree node has."""
# TODO: Determine how many children this node has
def has_child(self, character):
"""Return True if this prefix tree node has a child node that
represents the given character amongst its children."""
# TODO: Check if given character is amongst this node's children
def get_child(self, character):
"""Return this prefix tree node's child node that represents the given
character if it is amongst its children, or raise ValueError if not."""
if self.has_child(character):
# TODO: Find child node for given character in this node's children
...
else:
raise ValueError(f'No child exists for character {character!r}')
def add_child(self, character, child_node):
"""Add the given character and child node as a child of this node, or
raise ValueError if given character is amongst this node's children."""
if not self.has_child(character):
# TODO: Add given character and child node to this node's children
...
else:
raise ValueError(f'Child exists for character {character!r}')
def __repr__(self):
"""Return a code representation of this prefix tree node."""
return f'PrefixTreeNode({self.character!r})'
def __str__(self):
"""Return a string view of this prefix tree node."""
return f'({self.character})'
| true
|
484d28af9a47fbb40976d28da8fe83b6f7391613
|
mattester/moocPython
|
/步骤二:python函数与模块/day20/文件的读取.py
| 1,120
| 4.125
| 4
|
def read_file():
"""读取文件"""
file_name = 'test2.txt' #保存文件的名字
#使用绝对路径
file_path = 'D:\\pythontest\\python基础知识\\步骤二\\day20\\test2.txt'
#使用普通方式打开文件
f = open(file_name,encoding="utf-8")
'''
读取文件内容()所有
rest = f.read()
关闭
print(rest)
读取指定文件内容
rest = f.read(8)
print(rest)
rest = f.read(8)
print(rest)
rest = f.read(8)
print(rest)
'''
#随机读取(中文慎用)
f.seek(5) #跳过5个字符
print(f.read(5))
print(f.read(5))
print(f.read(5))
#readline():读取一行数据,可以指定参数,表示读取前几个字符(字节)
print(f.readline())
print(f.readline())
print(f.readline())
#readlines():读取所有的行,并返回列表
# rest = f.readlines(4)
# print(rest)
# print(len(rest))
# 读取所有行
rest = f.readlines(4)
print(len(rest))
for i in rest:
print(i)
f.close()
if __name__ == "__main__":
read_file()
| false
|
6e332a122b6c6a83a49e2bdcc66aaba3bfb8a191
|
MayankMaheshwar/DS-and-Algo-solving
|
/hypersonic2.py
| 585
| 4.125
| 4
|
"""
1) Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
"""
ans = 0
for i in range(arr):
ans ^= arr[i]
print(ans)
| true
|
a1fcaf556a09f43581122e608c1995ec37bbc260
|
nrkavya/python-training
|
/1.py
| 308
| 4.375
| 4
|
#Create a program to compare three numbers and find the bigger numbers
no1 = int(input("Enter no1"))
no2= int(input ("Enter no2"))
no3 = int(input("enter no3"))
if(no1>no2 and no1>no3):
print("no1 is greatest")
elif(no2>no1 and no2>no3):
print("no2 is greatest")
else:
print("no3 is greatest")
| true
|
60308a1f2aa94fa65c89ca7461b1ec664a7beba5
|
riceh3/210CT-CW
|
/binary_search.py
| 1,358
| 4.15625
| 4
|
def binary_search(entry): # Divide and Conquer
""" Search through input for values within the given high & low parameters """
length = len(entry)
middle = length/2 # Find the middle value in the list
middle = int(middle)
if entry[middle] == low or entry[middle] == high:
print("TRUE")
elif middle < 1: # Value not in range
print("FALSE")
else:
if entry[middle] > low and entry[middle] < high:
print("TRUE")
elif low < entry[middle]:
entry = entry[:middle] # Disregard first half of list
binary_search(entry)
return entry
elif high > entry[middle]:
entry = entry[middle:] # Disregard second half of list
binary_search(entry)
return entry
else:
print("FALSE")
try: # Check for input errors
entry = [2,3,5,7,9,13]
low = 10
high = 14
if low < high:
binary_search(entry)
else:
print("Low parameter must be less than High parameter")
except NameError:
print("Input must be all integers")
| true
|
352df6ef19d9ae8f85443aaf9a811a585e57bf37
|
lazywhitecat/Pratical
|
/Prac_03/temperatures.py
| 1,130
| 4.21875
| 4
|
def main():
#temperature conversion system
determine_temperature_type = input('Enter your temperature type in celsius(c) or fahrenheit(f):')
while True:
if determine_temperature_type == 'c':
celsius_value = float(input('Enter your celsius number:'))
fahrenheit = convert_celsius_to_fahrenheit(celsius_value)
print('The fahrenheit value is {:.2f}'.format(fahrenheit))
break
elif determine_temperature_type == 'f':
celsuis_value = float(input('Enter your fahrenheit number:'))
celsius = convert_fahrenheit_to_celsius(celsuis_value)
print('The celsius value is {:.2f}'.format(celsius))
break
else:
print('Invalid temperature type')
determine_temperature_type = input('Enter your temperature type in celsius(c) or fahrenheit(f):')
def convert_celsius_to_fahrenheit(temperature):
#convert celsius to fahrenheit
return 9 / 5 * temperature + 32
def convert_fahrenheit_to_celsius(temperature):
#convert fahrenheit to celsius
return 5 / 9 * (temperature-32)
main()
| false
|
cf981cdb74758f85e6e9801b94a2394911268a0a
|
LizzieDeng/kalman_fliter_analysis
|
/docs/cornell CS class/lesson 21. Object-Oriented Design/demos/point.py
| 1,932
| 4.21875
| 4
|
"""
A module with a simple Point3 class.
This module has a simpler version of the Point class. The primary purpose
of this module is to show off the built-in methods __str__ and __repr___
Author: Walker White (wmw2)
Date: October 20, 2019
"""
import math
class Point3(object):
"""
A class to represent a point in 3D space
Attribute x: The x-coordinate
Invariant: x is a float
Attribute y: The y-coordinate
Invariant: y is a float
Attribute z: The y-coordinate
Invariant: z is a float
"""
# INITIALIZER
def __init__(self,x=0.0,y=0.0,z=0.0):
"""
Initializes a new Point3
Parameter x: the x-coordinate (default is 0.0)
Precondition: x is a float (or optional)
Parameter y: the y-coordinate (default is 0.0)
Precondition: y is a float (or optional)
Parameter z: the z-coordinate (default is 0.0)
Precondition: z is a float (or optional)
"""
self.x = x # x is parameter, self.x is field
self.y = y # y is parameter, self.y is field
self.z = z # z is parameter, self.z is field
def __str__(self):
"""
Returns: this Point as a string '(x, y, z)'
"""
return '('+str(self.x)+', '+str(self.y)+', '+str(self.z)+')'
def __repr__(self):
"""
Returns: unambiguous representation of Point3
"""
return str(self.__class__)+str(self)
def distance(self,other):
"""
Returns: Distance from self to other
Parameter other: the point to measure to
Precondition: other is a Point3
"""
assert type(other) == Point3, repr(other)+' is not a Point3'
dx = (self.x-other.x)*(self.x-other.x)
dy = (self.y-other.y)*(self.y-other.y)
dz = (self.z-other.z)*(self.z-other.z)
return math.sqrt(dx+dy+dz)
| true
|
d52820228570073946ec653e69322c7d30a2d315
|
LizzieDeng/kalman_fliter_analysis
|
/docs/cornell CS class/Lesson 28. Generators/demos/filterer.py
| 1,139
| 4.1875
| 4
|
"""
Module to demonstrate the idea behind filter
This module implements the filter function. It also has
several support functions to show how you can leverage it
to process data. You may want to run this one in the
Python Tutor for full effect.
Author: Walker M. White (wmw2)
Date: May 24, 2019
"""
def filter(f,data):
"""
Returns a copy of data, removing anything for which f
is false
Parameter f: The function to apply
Precondition: f is a BOOLEAN function taking exactly one argument
Parameter data: The data to process
Precondition: data an iterable, each element satisfying precond of f
"""
accum = []
for item in data:
if f(item):
accum.append(item)
return accum
def iseven(x):
"""
Returns True if x is even
Parameter x: The number to add to
Precondition: x is an int
"""
return x % 2 == 0
def ispos(x):
"""
Returns True if x > 0
Parameter x: The number to add to
Precondition: x is an int or float
"""
return x > 0
# Add this if using the Python Tutor
#a = [-2,1,4]
#b = filter(iseven, a)
#c = filter(ispos, a)
| true
|
c1478e4316bf8c3c4c764d4192dcb54b7d1140fa
|
LizzieDeng/kalman_fliter_analysis
|
/docs/cornell CS class/lesson 17. Recursion/demos/com.py
| 1,950
| 4.53125
| 5
|
"""
A recursive function adding commas to integers.
These functions show the why the choice of division at the recursive step matters.
Author: Walker M. White (wmw2)
Date: October 10, 2018
"""
import sys
# Allow us to go really deep
#sys.setrecursionlimit(999999999)
# COMMAFY FUNCTIONS
def commafy(s):
"""
Returns a copy of s, with commas every 3 digits.
Example:
commafy('5341267') = '5,341,267'
Parameter s: string representing an integer
Precondition: s a string with only digits, not starting with 0
"""
# You can't always check everything with an assert
# However, check what you can
assert type(s) == str, repr(s) + ' is not a string'
# Work on small data (BASE CASE)
if len(s) <= 3:
return s
# Break up into halves (RECURSIVE CASE)
left = commafy(s[0:-3])
right = s[-3:]
# Combine the answer
return left + ',' + right
def commafy_int(n):
"""
Returns n as a string, with commas every 3 digits.
Example:
commafy('5341267') = '5,341,267'
Parameter n: number to convert
Precondition: n is an int with n >= 0
"""
assert type(n) == int, repr(n)+' is not an int' # get in the habit
assert n >= 0, repr(n)+' is negative' # get in the habit
# Use helpers
return commafy(str(n))
# Work on small data (BASE CASE)
#if n < 1000:
# return str(n)
# Break up into halves (RECURSIVE CASE)
#left = commafy(n//1000)
#right = to3(n % 1000)
# Combine the answer
#return left + ',' + right
def to3(p):
"""
Returns a string representation of p with at least 3 chars
Adds leading 0's if necessary
Parameter n: number to pad
Precondition: p is an int
"""
assert type(p) == int, repr(p)+' is not an int' # get in the habit
if p < 10:
return '00' + str(p)
elif p < 100:
return '0' + str(p)
return str(p)
| true
|
0ff7c36732279dd198f5034931b84041c0ac45d4
|
LizzieDeng/kalman_fliter_analysis
|
/docs/cornell CS class/lesson 16. For-Loops/demos/mut.py
| 906
| 4.40625
| 4
|
"""
Module to demonstrate how to modify a list in a for-loop.
This function does not use the accumulator pattern, because we are
not trying to make a new list. Instead, we wish to modify the
original list. Note that you should never modify the list you are
looping over (this is bad practice). So we loop over the range of
positions instead.
You may want to run this one in the Python Tutor for full effect.
Author: Walker M. White (wmw2)
Date: May 24, 2019
"""
def add_one(lst):
"""
(Procedure) Adds 1 to every element in the list
Example: If a = [1,2,3], add_one(a) changes a to [2,3,4]
Parameter lst: The list to modify
Precondition: lst is a list of all numbers (either floats
or ints), or an empty list
"""
size = len(lst)
for k in range(size):
lst[k] = lst[k]+1
# procedure; no return
# Add this if using the Python Tutor
#a = [3,2,1]
#add_one(a)
| true
|
e633be9b864b2ae81f2275718708f73f9aff44e6
|
LizzieDeng/kalman_fliter_analysis
|
/docs/cornell CS class/lesson 26. While-Loops/demos/newton.py
| 1,256
| 4.40625
| 4
|
"""
A module to show while-loops and numerical computations.
This is one of the most powerful uses of a while loop: using it to run
a computation until it converges. There are a lot of algorithms from
Calculus and Numerical Analysis that work this way.
Author: Walker M. White
Date: April 15, 2019
"""
def sqrt(c,err=1e-6):
"""
Returns: the square root of c to with the given margin of error.
We use Newton's Method to find the root of the polynomial f(x) = x^2-c
Newton's Method produces a sequence where
x_(n+1) = x_n - f(x_n)/f'(x_n) = x_n - (x_n*x_n-c)/(2x_n)
which we simplify to
x_(n+1) = x_n/2 + c/2 x_n
We can stop this process and use x_n as an approximation of the square root
of c. The error when we do this is less than |x_n*x_n - c|. So we loop
until this error is less than err.
Parameter c: The number to compute square root
Precondition: c >= 0 is a number
Parameter err: The margin of error (OPTIONAL: default is e-6)
Precondition: err > 0 is a number
"""
# Start with a rough guess
x = c/2.0
while abs(x*x-c) > err:
# Compute next in Newton's Method sequence
x = x/2.0+c/(2.0*x)
return x
| true
|
cb35550231866abfbadca029a1c91a125a2e9e2f
|
gunishj/python_async_multiprocessing
|
/AsyncIO/implementing_asyncio.py
| 1,157
| 4.5625
| 5
|
import asyncio
import time
def sync_f():
print('one', end=' ')
time.sleep(1) # I'm simulating an expensive task like working with an external resource. I want it to wait for 1 sec
print('two', end=' ')
# ASYNCHRONOUS
async def async_f():
print('one', end=' ')
await asyncio.sleep(1)
print('two', end=' ')
async def main():
# Note that there are 3 awaitable objects: coroutines, tasks and futures.
tasks = [async_f() for _ in range(3)]
# we schedule the coroutines to run asap by gathering the tasks like this:
await asyncio.gather(*tasks)
s = time.time()
# The entrance point of any asyncio program is asyncio.run(main()), where main() is a top-level coroutine.
# asyncio.run() was introduced in Python 3.7, and calling it creates an event loop
# and runs a coroutine on it for you. run() creates the event loop.
asyncio.run(main()) # prints out: one one one two two two and takes 1 second
print(f'Execution time (ASYNC):{time.time()-s}')
print('\n')
s = time.time()
for _ in range(3):
sync_f() # prints out: one two one two one two and takes 3 seconds
print(f'Execution time (SYNC):{time.time()-s}')
| true
|
d0b10155a5fea50e349d21c7ad7167f747d58ce8
|
Regenyi/python
|
/simplecalc.py
| 1,026
| 4.34375
| 4
|
#Regényi Ádám / CC , Python 1st SI Assignment
while True:
nr1 = input("Enter a number (or a letter to exit:) ")
if nr1.isdigit():
nr1int = int(nr1)
else:
exit()
list1 = ["+", "-", "*", "/"]
operation = input("Enter an operation (+, -, *, /) : ")
while operation not in list1: #"+" or "-" or "/" or "*"
operation = input("Please enter an operation (+, -, *, /) : ")
nr2 = input("Enter another number: ")
while nr2.isdigit() == False :
nr2 = input("Please enter another number: ")
while nr2 == "0":
print("You can't divide by zero!")
nr2 = (input("Enter another number: "))
if operation == "+":
result = int(nr1) + int(nr2)
if operation == "-":
result = int(nr1) - int(nr2)
if operation == "*":
result = int(nr1) * int(nr2)
if operation == "/":
result = int(nr1) / int(nr2) #when the result is an integer it will still display #.0
print("Result:", (result))
| false
|
0fcd16dcfa157c95f8ff55b16fb8e8f687a96e62
|
Regenyi/python
|
/Thonny_continue.py
| 729
| 4.15625
| 4
|
menu = """-- Calculator Menu --
0. Quit
1. Add two numbers
2. Subtract two numbers
3. Multiply two numbers
4. Divide two numbers"""
selection = None
while selection != 0:
print(menu)
selection = int(input("Select an option: "))
if selection not in range(5):
print("Invalid option: %d" % selection)
continue
if selection == 0:
continue
a = float(input("Please enter the first number: "))
b = float(input("Please enter the second number: "))
if selection == 1:
result = a + b
elif selection == 2:
result = a - b
elif selection == 3:
result = a * b
elif selection == 4:
result = a / b
print("The result is %g." % result)
| true
|
fa669ab56fb32241a23d3f9d00857001571cb2b2
|
Regenyi/python
|
/sorting.py
| 1,608
| 4.1875
| 4
|
#Sorting algo - RA CC Python SI1 A3
import re
#getting the number from the user:
input_numbers = []
input_numbers = input("\nTell me positive integers that you want to sort, by separting them with a coma (so for example: 10,2,45):\n\n")
#exception handler for wrong format:
while True:
if (len(input_numbers)<6 or len(input_numbers)>100):
input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ")
elif re.search("[a-z]",input_numbers):
input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ")
elif not re.search("[,]",input_numbers):
input_numbers = input("Wrong format!\nTell me the numbers that you want to sort, by separting them with a coma (so for example: 10,2,45)\n: ")
else:
break
input_numbers = input_numbers.split(",")
print("\nYou gave these numbers:\n")
print(*input_numbers, sep=',')
input_numbers = list(map(int, input_numbers))
#the actual sorting starts here:
def sorting():
iteration = 1
N = len(input_numbers)
while iteration < N:
j = 0
while j <= N-2:
if input_numbers[j] > input_numbers [j+1]:
temp = input_numbers[j+1]
input_numbers[j+1] = input_numbers[j]
input_numbers[j] = temp
else:
j += 1
else:
iteration += 1
sorting()
print("\nSorted numbers:\n")
print(*input_numbers, sep=',')
print("")
| true
|
a3c4170dbc8d48142cf7f8319ba45775e1956886
|
Tij99/compsci-jmss-2016
|
/triangleXs.py
| 384
| 4.28125
| 4
|
# Write a program to print out an isosceles triangle of Xs
# rewrite the program to work for an arbitrary number of rows (ie the user can
# enter the required number of rows)
def triangle(height):
for i in range(height):
spaces = height - i - 1
xs = 2 * i + 1
print("-" * spaces + "|" * xs + "-" * spaces)
h = int(input("how many lines?"))
triangle(h)
| true
|
d289d24ab9aee8fe7b75a91d8282d06f9e5a5740
|
VitorSchweighofer/exertec
|
/Exercicio4/exercicio 4/exe6.py
| 531
| 4.15625
| 4
|
numero1 = int(input('Digite o numero inferior aqui: '))
numero2 = int(input("Digite o numero superior aqui: "))
divisores = 0
if (numero1>numero2):
print('O suposto limite inferior está maior que o superior')
for divisor in range(numero1, numero2+1):
if (divisor == 2):
print('2')
if (divisor == 3):
print ('3')
if (divisor == 5):
print ('5')
if (divisor == 7):
print ('7')
if (divisor % 2 > 0) and (divisor % 3 >0) and (divisor % 5>0) and (divisor % 7 >0) and (divisor != 1):
print('%i' %(divisor))
| false
|
f8ac9454b1333d1fce5f4f43c2d3b54731b979b7
|
ArthurkaX/W3SCHOOL-learning
|
/Python basic P1/Ex_3.py
| 286
| 4.40625
| 4
|
# Write a Python program to display the current date and time
import datetime
print('first variant:')
print('current date & time is:')
print(datetime.datetime.now())
now = datetime.datetime.now
print('second variant:')
print('{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
| true
|
d5fac45dfae4e162546dd53c4a2b3bd154bcc4a3
|
ArthurkaX/W3SCHOOL-learning
|
/Python basic P1/Ex_1.py
| 514
| 4.25
| 4
|
# Write a Python program to print the following string in a specific format
some_txt = 'Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are'
x = 0
for a in some_txt:
if a.isupper() == True and a != 'I':
print()
if a == 'H':
x = 1
if a== 'U' or a== 'L':
x = 2
for tab in range(x):
print('\t' , end = '')
x = 0
print(a, end = '')
| true
|
50426db78b533ce033a059f1157c9f0d44123146
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_9_Classes/Dog.py
| 800
| 4.21875
| 4
|
class Dog(object):
"""A simple attempt to model a dog."""
def __init__(self,name,age):
"""Initialize name and age attribute"""
self.name=name
self.age=age
def sit(self):
"""Simulate a dog sitting in response to a command"""
print(self.name.title()+" is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command"""
print(self.name.title()+" rolled over!")
my_dog=Dog('willie',6)
print("My dog's name is "+my_dog.name.title()+".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
your_dog=Dog('lucy',3)
print("\nYour dog's name is "+your_dog.name.title() + ".")
print("Your dog's age is " + str(your_dog.age))
your_dog.sit()
your_dog.roll_over()
| true
|
91b3c0eace34899e1e0f2c1e40853ace87382362
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_3_Intoducing_Lists/bicyclesIntroToLists.py
| 1,152
| 4.625
| 5
|
#In Python, square brackets indicate a list, and individual elements in the list are separated by commas.
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
#Because this isnt the output you want your users to see, lets learn how to access the individual items in a list.
#To access an ele- ment in a list, write the name of the list followed by the index of the item enclosed in square brackets.
print bicycles[0]
#When we ask for a single item from a list, Python returns just that element without square brackets or quotation marks:
print bicycles[0].title() #prints the 1st element of the list
#index positions star at 0,not 1-->
#subtract 1 from actual position to get index position.
#To check from the right side of a list or the lasr element
#of the list--> start with -1 index position-->will return last element
print bicycles[-1]
print bicycles[-2]#second last and so on ..
#Now , How to use individual values of a list for a message? Simple:
message="My first bicycle was a "+bicycles[0].title()+"."
print message
#At 17, we build a sentence using the value at bicycles[0] and store it in the variable message.
| true
|
0ba59210ae47c36fd6abeab0670ead59fef062f7
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_3_Intoducing_Lists/untitled folder/3-3.py
| 462
| 4.46875
| 4
|
# 3-3. Your Own List: Think of your favorite mode of
# transportation, such as a motorcycle or a car, and
# make a list that stores several examples. Use your
# list to print a series of statements about these items,
# such as “I would like to own a Honda motorcycle.”
cars = ['audi' , 'bmw' , 'mercedes']
print("I would like own an " + cars[0].title())
print("I would like to own a " + cars[1].upper())
print("I would like to own a " + cars[2].title())
| true
|
d88e288cffdaf538374ae33bc2f91b3410b3b143
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_9_Classes/electric_car.py
| 2,219
| 4.46875
| 4
|
class Car(object):
"""A simple attempt to represent a car"""
def __init__(self,make,model,year):
"""Initialize attributes to describe a car"""
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name"""
long_name=str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""Set the odometer reading to given value.
Reject the change if anyone tries to roll the odometer back."""
if self.odometer_reading <= mileage:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self , increment_mileage):
self.odometer_reading += increment_mileage
def fill_gas_tank(self):
check = self.odometer_reading % 50
if check == 0:
print("It's time to fill the gas tank.")
else:
print("Fill gas after " + str(50 - check) + " miles.")
my_car=Car('audi','a4',2016)
print(my_car.odometer_reading)
my_car.update_odometer(60)
my_car.read_odometer()
my_car.fill_gas_tank()
class ElecticCar(Car):
"""Represents aspects of a car, specific to electric vehicles"""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class.
Then initalize attributes specific to an electic car."""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Prints a statement describing the battery size."""
print("This car has " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print("This car doesn't have a gas tank.")
my_tesla = ElecticCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
| true
|
d11e007939ad611f6f34dbf43ef9949442310658
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_7_User_Input_And_While_Loop/Practice2/4.rollercoaster.py
| 209
| 4.15625
| 4
|
height = raw_input("How tall are you , in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enought to ride!")
else:
print("You will be able to ride when you're a little older.")
| true
|
68b3d1a63e3df0f1f75e4fc83af3a3dd2b29f093
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_3_Intoducing_Lists/untitled folder/3-2Greetings.py
| 477
| 4.25
| 4
|
# 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each persons name,
# print a message to them. The text of each message should be the same, but each message should be personalized
# with the persons name.
friend_list=['manan','samarth','rohan','rishi']
print ("Hello, "+friend_list[0].title()+"!")
print ("Hello, "+friend_list[1].title()+"!")
print ("Hello, "+friend_list[2].title()+"!")
print ("Hello, "+friend_list[3].title()+"!")
| true
|
3389a5cd1051d2edcf6125b7adb4452d591f0726
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_9_Classes/practice2/9-6.IceCreamStand.py
| 1,332
| 4.21875
| 4
|
class Restaurant():
"""An attempt to model a restaurant"""
def __init__(self,restaurant_name,cuisine_type):
"""Initializing name and age attributes"""
self.name = restaurant_name
self.cuisine = cuisine_type
def describe_restaurant(self):
# Describes the restaurant name and cuisine
print(self.name.title() + " serves " + self.cuisine + " food.")
def open_restaurant(self):
# Opens the restaurant and welcomes customers.
print(self.name.title() + " is now Open. \nCome. \nHave some delicious " + self.cuisine + " food.")
restaurant1 = Restaurant("big chill","italian")
class IceCreamStand(Restaurant):
"""An attempt to model a restaurant , specific to InceCreamStand"""
def __init__(self,restaurant_name,cuisine_type):
"""Initializing attributes of parent class , Restaurant"""
super().__init__(restaurant_name,cuisine_type)
self.flavors = ['vanilla','chocolate','mint','blueberry','strawberry'] #
def display_flavors(self):
print("Here is the list of flavors: ")
for flavor in self.flavors:
print(flavor)
IceCreamStand1 = IceCreamStand('mother dairy','ice cream')
IceCreamStand1.describe_restaurant()
IceCreamStand1.open_restaurant()
IceCreamStand1.display_flavors()
| true
|
9a707f3c487622e2c8caa16d2d8ca8c4d7507911
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_8_Functions/practice2/16.profile.py
| 989
| 4.53125
| 5
|
# Sometimes you'll want to accept an arbitary number of
# argument but you won't know ahead of time
# what kind of information will be passed to the
# function.
# Write a function that accepts as many key-value pairs as the
# calling statement provides.
# Example : Building user profiles.
# You're sure that you'll get information about the user but
# you're not sure that what kind of information will be
# given to you.
# The function build_profile() taken in the first and the last
# name but also takes in an arbitrary number of keyword
# arguments.
def build_profile(first,last, **user_info):
"""Build a dictionary containing everything we know about a user"""
profile = {}
profile['First name' ] = first
profile['Last name'] = last
print(user_info)
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert','einstein',
location = 'princeton', field = 'physics')
print(user_profile)
| true
|
c9349dd22148f7f878bb1be59820cc8e1b6ddcd5
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_10_File_And_Exceptions/10-6.Addition.py
| 1,950
| 4.15625
| 4
|
while True:
try:
first_number = raw_input("Give me two numbers and i will add them." +
"\nEnter 'quit' to quit program anytime."+
"\nFirst Number: ")
if first_number == 'quit':
break
else:
first_number = int(first_number)
second_number = raw_input("Second Number: ")
if second_number == 'quit':
break
else:
second_number = int(second_number)
except ValueError:
print("You wrote in a word. Type in a number next time.")
continue
else:
print(first_number + second_number)
'''What the try block does:'''
# First it tells the user what the program will do.
# Next, it tell the use that he/she can quit at anytime.
# Next, It asks for the first number.
# Now if the user enters: 'quit'
# The program will exit/break.
# Till here , if the user has entered a non-integer value except 'quit'..
# The program will go to the first else block(first_number = int(first_number)
# Here, it will catch the error (ValueError) , if there is any.
# Similarly: The process is same for second_number.
# Anytime a ValueError comes due to entering non-integer value(except 'quit'):
# The program shift to the except block.
'''What the except block does'''
# Anytime a ValueError comes due to entering non-integer value(except 'quit'):
# The program shift to the except block.
# 1.the except block displays a friendly message telling the user to enter a number instead
# of a word next time.
# 2. continue: Goes back to the starting of the loop and prompts for first number again.
# Starts the whole program again.
'''What the else block does:'''
# If no error occurs, it prints the sun of the 2 numbers.
# if first_number != 'quit':
# second_number = raw_input("Second Number: ")
# if second_number != 'quit':
# second_number = int(second_number)
# print(first_number + second_number)
| true
|
f2d74a5bea40e74454c884bfefb8ec99d9b9d276
|
rishabhchopra1096/Python_Crash_Course_Code
|
/Chapter_5_If_Statements/banned_users_CheckWhetherAValueIsInAList.py
| 986
| 4.125
| 4
|
print "Checking whether a value is not in a list "
# Other times, its important to know if a value does not appear in a list.
# You can use the keyword not in this situation. For example, consider a
# list of users who are banned from commenting in a forum. You can check whether
# a user has been banned before allowing that person to submit a comment.
banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users:
print(user.title()+", you can post a comment if you wish.")
print "What are Boolean Expressions?"
print " Boolean expression=Conditional tests-->It is either True or False"
# Boolean values are often used to keep track of certain conditions, such as whether
# a game is running or whether a user can edit certain content on a website:
# game_active = True
# can_edit = False
# Boolean values provide an efficient way to track the state of a program or a
# particular condition that is important in your program.
| true
|
d41a8dd0a5d9aa2cd89cfc6d11ee9c75b1c31dbb
|
TetyanaLi/hillel_python
|
/LEVEL_1/LESSON_4/lesson4-1.py
| 782
| 4.21875
| 4
|
#1. В первый день спортсмен пробежал `x` километров,
# а затем он каждый день увеличивал пробег на 10% от предыдущего значения.
# По данному числу `y` определите номер дня, на который пробег спортсмена составит не менее `y` километров.
#Программа получает на вход числа `x` и `y` и должна вывести одно число - номер дня.
day_distance = int(input('Введите км: '))
new_distance = int(input("Введите дистанцию: "))
day_numb = 1
while day_distance <= new_distance:
day_distance *= 1.1
day_numb += 1
print(day_numb)
| false
|
5beb2bb5627236220420ff6078a2c7d299b9b140
|
TetyanaLi/hillel_python
|
/LEVEL_1/LESSON_11/lesson 11-3.py
| 1,340
| 4.46875
| 4
|
#3. Написать функцию которая вернет самое длинное слово в строке:
# longest_word("What makes a good man") -> makes
#x = input('Введите действительное число с двумя знаками после десятичной точки: ')
some_list = 'What makes a good man'
def longest_word(some_list):
elements = some_list.split()
new_list = []
for i in elements:
new_list.append(len(i))
d = dict(zip(new_list, elements))
lw = d.get(max(new_list))
return lw
print(longest_word(some_list)) # 1 ВАРИАНТ
def longest_word(some_list):
elements = {len(val): val for val in some_list.split()}
return elements[max(elements)]
some_list = 'What makes a good man'
print(longest_word(some_list)) # 2 ВАРИАНТ
def longest_word(some_string):
return max(some_string.split(), key=len)
some_list = 'What makes a good man'
print(longest_word(some_list)) # 3 ВАРИАНТ
#some_list = str('What makes a good man')
#elements = some_list.split()
#def longest_word(elements[0:]):
#print(elements)
#print(len(elements))
#new_list = []
#for i in elements:
# new_list.append(len(i))
#print(new_list)
#print(max(new_list))
#d = dict(zip(new_list,elements))
#print(d)
#print(d.get(max(new_list)))
| false
|
a994791a052a4abfb6a9a54e89d6c88d58224e4b
|
herzenuni/herzenuni-sem3-assignment4-191217-AnnGoga
|
/treemin.py
| 713
| 4.15625
| 4
|
def minimum_three_mpy(*args):
if len(args) < 3:
print("minimum_three_mpy : 3 arguments minimum")
return None
try:
mpy = args[0] * args[1] * args[2]
counter = 0
for i in range(len(args)):
for j in range(i + 1, len(args)):
for k in range(j + 1, len(args)):
counter += 1
new_mpy = args[i] * args[j] * args[k]
print("[", counter, "] args : ", args[i], " ", args[j], " ", args[k], "new_mpy : ", new_mpy)
if new_mpy < mpy:
mpy = new_mpy
print("[", counter, "] update mpy : ", mpy)
return mpy
except TypeError as ex:
print(ex)
return None
if __name__ == "__main__":
print("minimum mpy of 1,2,3,4,5,6 : ", minimum_three_mpy(1,2,3,4,5,6))
| false
|
aae8f905c66d6d76f3413fe0c3c93baca99e2acb
|
GabrielReira/Python-Exercises
|
/42 - Números ordenados.py
| 575
| 4.125
| 4
|
all_values = []
n = int(input('Quantos valores você deseja digitar? '))
for i in range(n):
value = int(input('Digite um valor: '))
# Se for o primeiro item ou se for maior que o último valor.
if (i == 0) or (value > all_values[-1]):
all_values.append(value)
# Se estiver entre os itens do meio.
else:
list_index = 0
while list_index < len(all_values):
if value <= all_values[list_index]:
all_values.insert(list_index, value)
break
list_index += 1
print(all_values)
| false
|
35adb2b17002fca26b19cf9b8b7c05c7a5862f44
|
0x420x42Rodriguez/100-Days-of-Code
|
/Day 4/RockPaperScissors.py
| 1,506
| 4.375
| 4
|
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
print("Welcome to Rock, Paper, Scissors. ")
user_choice = input("Type 'rock' 'paper' or 'scissors' to make your choice! ").lower()
computer_choice = random.randint(1, 3) # Get random number for computer choice
if computer_choice == 1: # Get computer input to print ASCII art
print(f"The computer chose \n {paper}")
elif computer_choice == 2:
print(f"The computer chose \n {paper}")
else:
print(f"The computer chose \n {scissors}")
if user_choice == "rock":
print(rock)
if computer_choice == 1:
print("It's a tie!")
elif computer_choice == 2:
print("Paper beats rock, you lose!")
else:
print("Rock beats scissors, you win!")
if user_choice == "paper":
print(paper)
if computer_choice == 1:
print("Paper beats rock, you win!")
elif computer_choice == 2:
print("It's a tie!")
else:
print("Scissors beat paper, you lose!")
if user_choice == "scissors":
print(scissors)
if computer_choice == 1:
print("Rock beats scissors, you lose!")
elif computer_choice == 2:
print("Scissors beat paper, you win!")
else:
print("It's a tie!")
| false
|
7d900b9d8a49c9f3b4753b7c8effd72764ddbbf6
|
sweenejp/learning-and-practice
|
/treehouse/python-beginner/monty_python_tickets.py
| 1,349
| 4.15625
| 4
|
SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
# $2 service charge per transaction
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining > 0:
print("There are only {} tickets remaining!\nBuy now to secure your spot for the show!".format(tickets_remaining))
name = input("Hi there! What's your name? ")
order = input("Okay, {}, how many tickets would you like? ".format(name))
try:
order = int(order)
if order > tickets_remaining:
raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
# Include the error text in the output
print("Oh no, we ran into an issue.")
print("{} Please try again".format(err))
else:
amount_due = calculate_price(order)
print("Great, {}! You ordered {} tickets. Your amount due is ${}".format(name, order, amount_due))
intent_to_purchase = input('Do you want to proceed with your purchasing order?\nPlease enter "yes" or "no" ')
if intent_to_purchase.lower() == 'yes':
print('SOLD!')
tickets_remaining -= order
else:
print('Thank you for stopping by, {}.'.format(name))
print('We are so sorry! This event is sold out. :(')
| true
|
8b69c22357ef25ddca9167989f2337674fe78784
|
sweenejp/learning-and-practice
|
/practicepythondotorg/exercise_14.py
| 692
| 4.1875
| 4
|
# Write a program (function!) that takes a list and returns a new list that contains all the
# elements of the first list minus all the duplicates.
#
# Extras:
#
# Write two different functions to do this - one using a loop and constructing a list,
# and another using sets. Go back and do Exercise 5 using sets, and write the solution for that
# in a different function.
def remove_duplicates(x):
return list(set(x))
def other_remove_duplicates(x):
a_list = []
for item in x:
if item not in a_list:
a_list.append(item)
return a_list
print(remove_duplicates([1, 1, 3, 5, 6, 7, 7, 7, 10]))
print(other_remove_duplicates([1, 1, 3, 5, 6, 7, 7, 7, 10]))
| true
|
cb066d54e563da61e1c97f7621ac4ac43c42e3e1
|
sweenejp/learning-and-practice
|
/treehouse/python-beginner/team.py
| 1,286
| 4.21875
| 4
|
# TODO Create an empty list to maintain the player names
player_names = []
# TODO Ask the user if they'd like to add players to the list.
wants_to_add = input("Would you like to add a player to the team?\nYes/no: ")
# If the user answers "Yes", let them type in a name and add it to the list.
while wants_to_add.lower() == "yes":
new_player = input("Enter the name of the player: ")
player_names.append(new_player)
wants_to_add = input("Would you like to add a player to the team?\nYes/no: ")
# If the user answers "No", print out the team 'roster'
# TODO print the number of players on the team
print("\nThere are {} players on your team.".format(len(player_names)))
# TODO Print the player number and the player name
# The player number should start at the number one
player_number = 1
for player in player_names:
print("Player {}: {}".format(player_number, player))
player_number += 1
# TODO Select a goalkeeper from the above roster
keeper = input("Please select the goalkeeper by entering that person's player number. (1-{}): ".format(len(player_names)))
keeper = int(keeper)
print("Great!!! The goalkeeper for the game will be {}.".format(player_names[keeper - 1]))
# TODO Print the goal keeper's name
# Remember that lists use a zero based index
| true
|
28301a007b829871cd518834994588e9f088b53b
|
Kinosa777/Lits-Python
|
/convert_n_to_m.py
| 1,377
| 4.21875
| 4
|
def convert_n_to_m(x, n, m):
"""Converts a number in n-based system into a number in m-based system."""
def convert_n_to_dec(x):
"""Converts a n-based number into decimal.
No int(num, base) function for number conversion is used."""
if n == 10:
return x
elif n == 1:
return len(x)
else:
dec = 0
for i in range(0, len(x)):
dec += (chars.index(x[i]) * (n ** (len(x) - i - 1)))
return dec
def convert_dec_to_m(dec, result=''):
"""Converts a decimal number into a m-based number.
Recursion is used."""
dec = int(dec)
if m == 10:
return str(dec)
elif m == 1:
return '0'*dec
else:
if dec < m:
return str(dec) + result
else:
result = str(chars[dec % m]) + result
return convert_dec_to_m(dec // m, result)
x = str(x)
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for ch in x:
if ch not in chars[:n]:
return False
return convert_dec_to_m(convert_n_to_dec(x))
print(convert_n_to_m([123], 4, 3))
print(convert_n_to_m("0123", 5, 6))
print(convert_n_to_m("123", 3, 5))
print(convert_n_to_m(123, 4, 1))
print(convert_n_to_m(-1230, 11, 16))
print(convert_n_to_m("A1Z", 36, 16))
| true
|
7298c7eca57f058c10682bcdfffb19a25c863293
|
leisurexi/python-study
|
/03/listtuple.py
| 1,697
| 4.125
| 4
|
# author: leisurexi
# date: 2021-01-11 23:25
# 列表和元组示例,列表和元素都是一个可以放置任意数据类型的有序集合
# 列表是动态的,长度大小不固定,可以随意地添加、删除或者改变元素
lists = [1, 2, 3, "hello"]
lists[2] = 20
lists.append(5)
print(f'列表添加和修改元素后: {lists}')
lists.remove(1)
print(f'列表删除元素后: {lists}')
# -1 代表最后一个元素,-2 代表倒数第二个元素以此类推
print(f'列表负数索引: {lists[-1]}')
# 切片包前不包后
print(f'列表切片: {lists[1:3]}')
# 元组是静态的,长度大小固定,无法增加、删除或者改变元素
tuple = (1, 2, 6)
# tuple[2] = 20 # 此处会抛出异常
# 给元组添加一个元素,实际上是创建了一个新的元祖,然后将原先的4个元素一次填充进去
tuple = tuple + (5,)
print(f'元组添加元素后: {tuple}')
print(f'元组负数索引: {tuple[-1]}')
# 切片包前不包后
print(f'元组切片: {tuple[1:3]}')
# 元组反转,reversed 函数返回一个倒转后的迭代器,用 list 函数转换为列表
print(f'元组反转后: {list(reversed(tuple))}')
# 返回排序好的新列表
print(f'元组排序后: {sorted(tuple)}')
print(tuple)
# 思考题:以下2中方式在效率上有什么区别?
'''
区别主要在于list()是一个function call,Python的function call会创建stack,
并且进行一系列参数检查的操作,比较expensive,反观[]是一个内置的C函数,可以直接被调用,因此效率高。
'''
# 创建空列表
# option A
empty_list = list()
print(empty_list.__sizeof__())
# option B
empty_list = []
print(empty_list.__sizeof__())
| false
|
235fdaa0a8994a442342fd0521db8ffaebbdbd10
|
tohkev/Module-5-Hwk
|
/loopy_loops.py
| 671
| 4.125
| 4
|
if __name__ == '__main__':
pokemon = ('pikachu', 'charmander', 'bulbasaur')
print(pokemon[1])
starter1 = pokemon[0]
starter2 = pokemon[1]
starter3 = pokemon[2]
print(starter1, starter2, starter3)
name_tuple = tuple('Kevin')
print(name_tuple)
is_there_i = 'i' in name_tuple
print(is_there_i)
for i in range(2, 11):
print(i)
i = 2
while i < 11:
print(i)
i += 1
string = 'This is a simple string'
for letter in string:
print(letter)
set_of_strings = ('this', 'is', 'a', 'simple', 'set')
for i in range(3):
for word in set_of_strings:
print(word)
| false
|
3aecd3afc0558b00aa683aeb245b1e2876f78706
|
hazim/Treehouse---Python-Basic
|
/check_please.py
| 519
| 4.21875
| 4
|
import math
def split_check(total, number_of_people):
# we want to round up the number in order to make sure that the person paying is not paying the extra out of their own pocket
return math.ceil(total_due / split_among)
try:
total_due = float(input("What is the total? \n"))
split_among = int(input("How many people are we spliting it among? \n"))
except ValueError:
print('Oh No! Enter a number please. ')
else:
amount_due = split_check(total_due, split_among)
print(f'Each person owes ${amount_due}')
| true
|
c593de4528944eecdd6c30ddeb1d1ccc27517dec
|
Three-Y/MyPythonLearning
|
/ibbie_16_列表.py
| 2,048
| 4.1875
| 4
|
"""
列表(list,相当于java中的数组)
格式:变量名=["hhh","xxx","jjj","aaa"]
索引值从0开始
可以存放不同类型的数据,但是通常存放类型相同的数据
"""
"""创建列表"""
name_list = ["hhh", "jjj", "jjj", "aaa"]
print(name_list)
"""根据索引取值"""
name_list[2]
# name_list[4] # IndexError: list index out of range
print(name_list[2])
"""根据内容取索引"""
name_list.index("aaa")
# name_list.index("111") # ValueError: '111' is not in list
print(name_list.index("aaa"))
"""修改列表的值"""
name_list[0] = "ibbie"
print(name_list)
"""在末尾添加一个元素"""
name_list.append("yan")
print(name_list)
"""在末尾添加一组元素"""
temp_list = ["1","2","3"]
name_list.extend(temp_list)
print(name_list)
"""在指定索引位置插入元素"""
name_list.insert(3, "doge")
print(name_list)
"""从列表中删除指定的内容"""
name_list.remove("jjj") # 如果要删除的内容有多个,只删除最前面的一个
print(name_list)
"""pop方法删除元素,pop能返回被删除的元素"""
temp = name_list.pop() # 不传递参数,默认删除最后一个元素,返回被删除元素
print(temp)
print(name_list)
temp = name_list.pop(1) # # 传递参数,删除指定索引的元素,返回被删除元素
print(temp)
print(name_list)
"""清空列表"""
name_list.clear()
print(name_list)
"""列表的长度"""
name_list = ["hhh", "jjj", "jjj", "aaa"]
number_list = [7, 2, 2, 2, 10, 6]
print(len(number_list))
"""列表中指定内容的个数"""
print("列表中元素2出现了 %d 次" % number_list.count(2))
"""对列表进行排序"""
name_list.sort() # 升序排序
number_list.sort()
print(name_list)
print(number_list)
name_list.sort(reverse=True) # 降序排序,指定reverse为True
number_list.sort(reverse=True)
print(name_list)
print(number_list)
name_list.reverse() # 反转列表
number_list.reverse()
print(name_list)
print(number_list)
"""迭代列表的元素"""
for name in name_list:
print("我叫 %s" % name)
| false
|
84a49f93c9e05a35e7ae543e8b03dc7f9cb0a8ce
|
Three-Y/MyPythonLearning
|
/ibbie_32_父类的公有属性和方法.py
| 825
| 4.34375
| 4
|
"""
父类的公有属性和方法
子类可以调用父类的公有属性和方法
子类对象也可以调用父类的公有属性和方法
可以通过父类的公有方法,在子类间接调用父类的私有属性和方法
"""
class A:
def __init__(self):
self.a = "父类公有属性"
self.__b = "父类的私有属性"
def test(self):
print("父类公有方法")
print("父类的公有方法中调用父类的私有属性和方法:")
print(self.__b)
self.__test2()
def __test2(self):
print("父类私有方法")
class B(A):
def demo(self):
# 子类调用父类的公有属性和方法
print(self.a)
self.test()
b = B()
b.demo()
# 子类对象调用父类的公有属性和方法
print(b.a)
b.test()
| false
|
5839e093920e86c0a2f9fa7449540a2552311a06
|
Three-Y/MyPythonLearning
|
/ibbie_36_多态.py
| 461
| 4.125
| 4
|
"""
多态
不同的子类对象,调用相同的父类方法,产生不同的结果(同java,略)
"""
class Animal:
def eat(self):
print("吃东西")
class Dog(Animal):
def eat(self):
print("狗狗吃骨头")
class Cat(Animal):
def eat(self):
print("猫猫吃鱼")
class Master:
def feed(self,animal):
animal.eat()
cat = Cat()
dog = Dog()
master = Master()
master.feed(cat)
master.feed(dog)
| false
|
7f4dd8521d12aa3d208fa4c51d507d84b304de6b
|
mtaziz/python_projects
|
/Basic Rock Paper Scissors Game (CLI).py
| 1,945
| 4.25
| 4
|
import random
# Welcome text
print("ROCK PAPER SCISSORS")
# Game variables
ties = 0
wins = 0
losses = 0
# Gameloop
while True:
# Displaying game data.
print("%s Wins, %s Loses, %s Ties" % (wins, losses, ties))
# Loop for player choice.
while True:
print("Enter any one: (r)ock (p)aper (s)cissor or (q)uit")
player_move = input('- ').lower()
if player_move == 'q':
exit()
elif player_move == 'r' or player_move == 'p' or player_move == 's':
break
print("Type one of: r, p, s or q")
# Printing text according to choice.
if player_move == 'r':
print("ROCK versus...")
elif player_move == 'p':
print("PAPER versus...")
elif player_move == 's':
print("SCISSORS versus...")
# Generating random number
num = random.randint(1, 3)
# Blank variable for computer move.
computer_move = ''
# Assigning values to computerMove accordingly.
if num == 1:
computer_move = 'r'
print("ROCK")
elif num == 2:
computer_move = 'p'
print("PAPER")
elif num == 3:
computer_move = 's'
print("SCISSORS")
# Condition for tie
if player_move == computer_move:
print("IT'S A TIE!")
ties += 1
# Conditions for wins
elif player_move == 'r' and computer_move == 's':
print("YOU WIN!")
wins += 1
elif player_move == 'p' and computer_move == 'r':
print("YOU WIN!")
wins += 1
elif player_move == 's' and computer_move == 'p':
print("YOU WIN!")
wins += 1
# Conditions for losses
elif computer_move == 'r' and player_move == 's':
print("YOU LOSE!")
losses += 1
elif computer_move == 'p' and player_move == 'r':
print("YOU LOSE!")
losses += 1
elif computer_move == 's' and player_move == 'p':
print("YOU LOSE!")
losses += 1
| true
|
5af7a4ac6b300fee0b1e86a4eb14378eb9243279
|
cgscreamer/UdemyProjects
|
/Python/dictionaries.py
| 671
| 4.1875
| 4
|
fruit = {"orange": "a sweet, orange, citrus fruit",
"apple": "good for making cider",
"lemon": "a sour, yellow citrus fruit",
"grape": "a small, sweet fruit growing in bunches",
"lime": "a sour, green citrus fruit"}
#To add to a dictionary
fruit["pear"] = "an odd shaped apple"
#To delete a dictionary entry
#del fruit["lime"]
for f in sorted(fruit.keys()):
print(f + " - " + fruit[f])
while True:
dict_key = raw_input("Please enter a fruit: ")
if dict_key == "quit":
break
description = fruit.get(dict_key, "We don't have a " + dict_key)
print(description)
#To clear/empty the dictionary
#fruit.clear
| true
|
fa82962cae016363dee794c962553a62b8a4fdc8
|
andyhou2000/exercises
|
/chapter-6/ex_6_5.py
| 1,129
| 4.125
| 4
|
# Programming Exercise 6-5
#
# Program to total the value of numbers in a text file.
# The program takes no user input, but requires a text file with numbers, one per line,
# which it opens, reads line by line, and totals the numbers in a variable,
# then displays the total on the screen.
# Define the main function.
# Declare a local string variable for line and two floats for total and current number
# Open numbers.txt file for reading
# iterate over the lines in the file
# get a number from the current line
# add it to total
# Close file
# Display the total of the numbers in the file
# Call the main function to start the program.
def main():
file = open("numbers.txt","r")
total = int(0)
count = int(0)
a = str("bob")
while a != "":
a = file.readline()
if a == "":
pass
else:
a = int(a)
total = total + a
count = count + 1
print("Total: ",total)
print("Count: ",count)
file.close()
main()
| true
|
5bd4a64c40de41eb21d95ec08c4ce5ba06d351b8
|
andyhou2000/exercises
|
/chapter-4/ex-4-5.py
| 2,173
| 4.46875
| 4
|
# Programming Exercise 4-5
#
# Program to compute total and average monthly rainfall over a span of years.
# This program gets a number of years from a user,
# then uses nested loops to prompt for rainfall for each month in each year
# and calculate the total and the average monthly rainfall,
# then displays the number of months, total rainfall and average monthly rainfall
# Create float variables for total rainfall, monthly rainfall, average monthly rainfall
# Create int variables for number of years and number of months.
# Get number of years from the user
# Nested loop logic to loop through the years and their months
#
# Outer for loop for the number of years
# Print the current year message
# Inner loop for 12 months
# Get monthly rainfall for current month from the user
# add monthly rainfall to total rainfall
# increment number of months
# Calculate the average rainfall using total rainfall and number of months
# print the results on the screen, including details for total months, total rainfall,
# and average monthly rainfall, formatting any floats to 2 decimal places.
startYear = input("Input starting year: ")
startYear = int(startYear)
years = input("Input amount of years: ")
years = int(years)
totalRain = 0
totalRain = float(totalRain)
yearRain = 0
yearRain = float(yearRain)
x = 0
x = int(x)
y = 1
y = int(y)
for x in range(0,years):
currentYear = startYear + x
print("Input rainfall data for year",currentYear)
for y in range(1,13):
print("Input inches of rain in month", y,": ", end="")
rain = input()
rain = float(rain)
yearRain = yearRain + rain
y = y + 1
averageRain = yearRain / 12.0
print("Rain in year ",currentYear,": ",format(yearRain,'.2f')," inches.")
print("Average rain per month in year ",currentYear,": ",format(averageRain,'.2f')," inches")
totalRain = totalRain + yearRain
yearRain = 0
x = x + 1
y = 1
averageTotalRain = totalRain / (12.0 * x)
print("Total rain in period: ",format(totalRain,'.2f')," inches")
print("Average rain per month in period:",format(averageTotalRain,'.2f')," inches")
| true
|
80c8bb6fa0068c40e7417af66c9230ec5945fcfc
|
andyhou2000/exercises
|
/chapter-2/ex-2-5.py
| 797
| 4.59375
| 5
|
# Programming Exercise 2-5
#
# Program to calculate distances traveled over time at a speed.
# This program uses no input.
# It will calculate the distance traveled for 6, 10 and 15 hours at a constant speed,
# then display all the results on the screen.
# Variables to hold the three distances.
# be sure to initialize these as floats.
# Constant for the speed.
# Calculate the distance the car will travel in
# 6, 10, and 15 hours.
# Print the results for all calculations.
speed = 40
speed = float(speed)
distSix = speed * 6
distTen = speed * 10
distFifteen = speed * 15
print("Distance after six hours: %.2f"%distSix, "miles")
print("Distance after ten hours: %.2f"%distTen, "miles")
print("Distance after fifteen hours: %.2f"%distFifteen, "miles")
| true
|
ddc8b5c1c688595eb24cdebc4d594fa50faa04c6
|
impradeeparya/python-getting-started
|
/tree/SymetricTree.py
| 2,042
| 4.21875
| 4
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_child_symmetric(self, children):
is_symmetric = True
left_index = 0
right_index = len(children) - 1
while left_index < right_index:
if children[left_index] is None and children[right_index] is None:
is_symmetric = True
elif (children[left_index] is None and children[right_index] is not None) or (
children[left_index] is not None and children[right_index] is None) or (
children[left_index].val != children[right_index].val):
is_symmetric = False
break
left_index += 1
right_index -= 1
if is_symmetric:
children_nodes = []
is_leaf_level = True
for index in range(len(children)):
children_nodes.append(children[index].left if children[index] is not None else None)
children_nodes.append(children[index].right if children[index] is not None else None)
if children[index] is not None:
is_leaf_level = False
if not is_leaf_level:
is_symmetric = self.is_child_symmetric(children_nodes)
return is_symmetric
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
is_symmetric = True
if root is not None:
if root.left is not None and root.right is not None and root.left.val == root.right.val:
is_symmetric = self.is_child_symmetric([root.left, root.right])
elif root.left != root.right:
is_symmetric = False
return is_symmetric
left = TreeNode(2, None, TreeNode(3))
right = TreeNode(2, None, TreeNode(3))
root = TreeNode(1, left, right)
print(Solution().isSymmetric(root))
| true
|
a145bda0848c345599343ef6abee82d44a11ba41
|
chanchalkumawat/Learn-Python-Hardway
|
/ex4of46.py
| 351
| 4.15625
| 4
|
#Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
def check(c):
if c=='a'or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u' or c=='U':
return True
else:
return False
z=raw_input("Enter the character :")
print check(z)
| true
|
40586a96dad88b27a9819cead81a91bb838a5442
|
liweichen8/Python
|
/104Reverse_reversed.py
| 363
| 4.28125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 22:59:19 2020
@author: liweichen
"""
def reverse_reversed(items):
for i in range(len(items)):
if type(items[i])==list:
#print(items[i])
item=reverse_reversed(items[i])
items[i]=item
#print(items[i], item)
return items[::-1]
| false
|
7278e5b16a928c6764dde79d296d30e063352e93
|
taylorperkins/foobar
|
/test/test_solar_doomsday.py
| 1,916
| 4.125
| 4
|
import unittest
from utils import print_time
from logic.solar_doomsday import answer
class TestSolarDoomsday(unittest.TestCase):
"""Challenge 1
Solar Doomsday
==============
Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's
quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels.
Due to the nature of the space station's outer paneling, all of its solar panels must be squares. Fortunately, you
have one very large and flat area of solar material, a pair of industrial-strength scissors, and enough MegaCorp
Solar Tape(TM) to piece together any excess panel material into more squares. For example, if you had a total area
of 12 square yards of solar material, you would be able to make one 3x3 square panel (with a total area of 9). That
would leave 3 square yards, so you can turn those into three 1x1 square solar panels.
Write a function answer(area) that takes as its input a single unit of measure representing the total area of solar
panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the largest squares you could
make out of those panels, starting with the largest squares first. So, following the example above, answer(12) would
return [9, 1, 1, 1].
Test Cases
==========
Inputs:
(int) area = 12
Output:
(int list) [9, 1, 1, 1]
Inputs:
(int) area = 15324
Output:
(int list) [15129, 169, 25, 1]
"""
def setUp(self):
pass
def tearDown(self):
pass
@print_time
def test_example_one(self):
response = answer(12)
self.assertEqual(response, [9, 1, 1, 1])
@print_time
def test_example_two(self):
response = answer(15324)
self.assertEqual(response, [15129, 169, 25, 1])
| true
|
f227f9eeb846c6faf3f4b36e0b7d0930837adf59
|
sahaj2005/pythonLearning
|
/pythonlearning2.py
| 379
| 4.25
| 4
|
#string
str1='hello world'
str2="this is good boy "
print(str1)
print(str2)
#index
my_str="My name is jhon"
print(my_str[0])
print(my_str[-1])
print(my_str[1:5])
print(len(my_str))
print(my_str.lower())
print(my_str.upper())
#replace
str2="My name is saju"
print(str2.replace('s','S'))
print(str2.count('a'))
str3="hello world"
print(str3.find('lo'))
print(str3.split(','))
| false
|
719d9d0e1b3548a2b791779d09693228e0824ab7
|
prof-paradox/project-euler
|
/7.py
| 520
| 4.125
| 4
|
'''
Calculates the 10001st prime number
'''
import math
def isPrime(num):
if num % 2 == 0:
return False
for i in range(3, round(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
natural_no = 3
prime_count = 1 # initial count for 2
max_prime = 2
while prime_count <= 10000:
if(isPrime(natural_no)):
prime_count += 1
max_prime = natural_no
natural_no += 2 # since 2 is the only even prime number
print(max_prime)
| true
|
db37990f15e0b9eaeab5dacf38b1adf87735b416
|
rawsashimi1604/Qns_Leetcode
|
/leetcode_py/valid-parentheses.py
| 834
| 4.125
| 4
|
class Solution:
def isValid(self, s: str) -> bool:
stack = []
lookup = {
"}": "{",
")": "(",
"]": "["
}
for p in s:
if p in lookup.values():
stack.append(p)
# Must make sure that stack exists, so that there will not be any index errors.
# Example input : "]" ...
# p will not be in lookup values, but cannot call stack[-1]
elif stack and lookup[p] == stack[-1]:
stack.pop() # Remove from top of stack
# If p not in lookup values, means not valid.
# And if the p did not exist in stack, means it is invalid
else:
return False
return stack == []
test = Solution()
output = test.isValid(']')
print(output)
| true
|
df38b1d404b01498a368916adb754a496f354c1e
|
callumr1/Programming_1_Pracs
|
/Prac 4/number_list.py
| 681
| 4.15625
| 4
|
def main():
numbers = []
print("Please input 5 numbers")
for count in range(1, 6):
num = int(input("Enter number {}: ".format(count)))
numbers.append(num)
average = calc_average(numbers)
print_numbers(numbers, average)
def calc_average(numbers):
average = sum(numbers) / len(numbers)
return average
def print_numbers(numbers, average):
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average of the number is {}".format(average))
main()
| true
|
c543270a6ffa5c251551c3cc3eb2082e013a2e0e
|
CRUZEAAKASH/PyCharmProjects
|
/section3_StringsAndPrint/String Methods.py
| 1,469
| 4.5
| 4
|
"""
len() and str() practice:
1.create a variable and assign it the string "Python"
2.create another variable and assign it the length of the string assigned to the variable in step 1
3.create a variable and use string slicing and len() to assign it the length of the slice "yth" from the string assigned
to the variable from step 1
4.create a variable and assign it the float 1.32
5.create a variable and assign it the string "2" from the float assigned to the variable from the last problem (use the
str() string method for this)
"""
# type your code for "len() and str() practice" below this single line comment and above the one below it --------------
# ----------------------------------------------------------------------------------------------------------------------
var1 = "Python"
var2 = len(var1)
var3 = len(var1[1:4])
var4 = 1.32
#var5 = 1.3(str(2))
print(var1)
print(var2)
print(var3)
print(var4)
#print(var5)
"""
.upper() and .lower() practice:
1.create a variable and assign it the string "upper" changed to "UPPER" using .upper()
2.create a variable and assign it the string "owe" from "LOWER" using string slicing and .lower()
"""
# type your code for ".upper() and .lower() practice" below this single line comment and above the one below it --------
# ----------------------------------------------------------------------------------------------------------------------
var6= "upper".upper()
var7 = "LOWER".lower()
print(var6)
print(var7)
| true
|
15d758afcd551443056c912accd5a639b0d150c2
|
CRUZEAAKASH/PyCharmProjects
|
/section4_ConditionalsAndFlowControl/BooleanOperatorProblems.py
| 1,605
| 4.625
| 5
|
"""
and, or, and not:
1.create a variable and set it equal to True using a statement containing an "and" Boolean operator
2.create a variable and set it equal to False using a statement containing an "and" Boolean operator
3.create a variable and set it equal to True using a statement containing an "or" Boolean operator
4.create a variable and set it equal to False using a statement containing an "or" Boolean operator
5.create a variable and set it equal to True using a statement containing an "not" Boolean operator
6.create a variable and set it equal to False using a statement containing an "not" Boolean operator
"""
# type your code for "and, or, and not" below this comment and above the one below it.---------------------------------
# ----------------------------------------------------------------------------------------------------------------------
print(True and True)
print(True and False)
print(True or True)
print(False or False)
print (not False)
print (not True)
"""
order of operations for Boolean operators:
1.make var1 evaluate to False by changing or removing a single Boolean operator
2.make var2 evaluate to True by changing or removing a single Boolean operator
"""
# type your code for "order of operations for Boolean operators" below this comment and above the one\below it. --------
var1 = not 3 > 1 and 5 != 2 or 6 == 6
var2 = 4 * 2 != 6 and not 7 % 6 == 1
# ----------------------------------------------------------------------------------------------------------------------
print(not 3 > 1 and 5 != 2 and 6 == 6)
print(4 * 2 != 6 and 7 % 6 == 1)
print("hello")
| true
|
cafc90b922a9c73f77e2ff2d3020c8563e93d60b
|
CRUZEAAKASH/PyCharmProjects
|
/section14_RegularExpressions/findAll.py
| 215
| 4.15625
| 4
|
import re
pattern = r"eggs"
String = "We have eggs in our string. eggs just eggstoeggs count the presence of eggs in the string"
print(re.findall(pattern, String))
print(re.findall(pattern, String).__len__())
| true
|
f5b2f41977280c6920d18c3736071647b38f0786
|
CRUZEAAKASH/PyCharmProjects
|
/section5_Functions/FunctionsProblems.py
| 2,525
| 4.875
| 5
|
"""
Single parameter and zero parameter functions:
1.define a function that takes no parameters and prints a string
2.create a variable and assign it the value 5
3.create a function that takes a single parameter and prints it
4.call the function you created in step 1
5.call the function you created in step 3 with the variable you made in step 2 as its input
"""
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def function1():
print("printing Method 1")
var1 = 5
def function2(a):
print(a)
function1()
function2(var1)
"""
multiple parameter functions:
1.create 3 variables and assign integer values to them
2.define a function that prints the difference of 2 parameters
3.define a function that prints the product of the 3 variables
4.call the function you made in step 2 using 2 of the variables you made for step 1
5.call the function you made in step 3 using the 3 variables you created for step 1
"""
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
var1 = 10
var2 = 20
var3 = 30
def function3(a,b):
print(abs(a-b))
def function4(a,b,c):
print(a * b * c)
function3(var1,var2)
function4(var1,var2,var3)
"""
Calling previously defined functions within functions:
1.create 3 variables and assign float values to them
2.create a function that returns the quotient of 2 parameters
3.create a function that returns the quotient of what is returned by the function from the second step and a
third
parameter
4.call the function you made in step 2 using 2 of the variables you created in step 1. Assign this to a
variable.
5.print the variable you made in step 4
6.print a call of the function you made in step 3 using the 3 variables you created in step 1
"""
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
flt1 = 10.0
flt2 = 20.0
flt3 = 30.0
def function5(a,b):
return a/b
def function6(a,b,c):
return((function5(a,b))/c)
flat4 = function5(flt1,flt2)
print(flat4)
print(function6(flt2,flt1,flt3))
| true
|
1a07035dcb4f3909b26f5b0aa1d1b4af20192866
|
CRUZEAAKASH/PyCharmProjects
|
/section15_Tkinter/TkinterMessageBox.py
| 340
| 4.125
| 4
|
from tkinter import Tk
from tkinter import messagebox
window = Tk()
messagebox.showinfo("title", "You are seeing message box")
response = messagebox.askquestion("Question 1", "Do you love Coffee?")
if (response == 'yes'):
print("Here are your coffee loverrr!!!!!!!!!!!!!!!!!")
else:
print("What do you love???")
window.mainloop()
| true
|
ef26690eccdd553f9a81cd1b9daa6f5c9e02cb93
|
chithracmenon/AutomateBoringStuff
|
/ch7_date_detection.py
| 1,743
| 4.71875
| 5
|
"""Date Detection
Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.
The regular expression doesn’t have to detect correct days for each month or for leap years; it will accept nonexistent dates like 31/02/2020 or 31/04/2021. Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date. April, June, September, and November have 30 days, February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date."""
#!python3
# Date Detection
import regex as re
import sys
regexobject = re.compile(r'([0-2]?[0-9]|31|30)/([0]?[0-9]|[1][0-2])/([1-2][0-9][0-9][0-9])')
date = '29/2/2020'
mo = regexobject.findall(date)
if len(mo):
date = int(mo[0][0])
month = int(mo[0][1])
year = int(mo[0][2])
else:
print("Not valid date")
sys.exit()
def leap_year(year):
return (~(year % 4) and (year % 100) or ~(year % 400)))
months_with30 = [4, 6, 9, 11]
if (month in months_with30) and (date <= 30):
print("Valid date1")
elif (month == 2) and ((date <= 28) or ((date <= 29) and (leap_year(year)))):
print("valid date2")
elif (month not in (months_with30 + [2])) and (date <= 31):
print("valid date4")
else:
print("invalid date")
print(date, month, year)
| true
|
4a891d4030805ca7bab9a9b2538d3c2084cd3114
|
JaneNjeri/python_crash_course
|
/factorial.py
| 235
| 4.3125
| 4
|
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print("Please enter a number to recieve its factorial.")
num = int(input() )
print (factorial(num))
# good recursion practice
| true
|
cde34a198a2699acfbae74f87e49c60b43fb85bd
|
annisa-nur/wintersnowhite
|
/exception.py
| 2,550
| 4.1875
| 4
|
# Program ini meminta pengguna memasukkan dua angka untuk operasi pembagian
# Program menampilkan pesan jika terjadi eksepsi
def main():
# [1] Tuliskan statement try/except
# Pada body klausa try:
# - Minta dua angka ke pengguna
# - Lakukan pembagian
# Pada body klausa except untuk ValueError
# - Tampilkan pesan: "Nilai yang diinput salah."
# Pada body klausa except untuk ZeroDivisionError
# - Tampilkan pesan: "Tidak dapat membagi dengan nol."
try:
Pembilang = int(input("Masukkan sebuah angka yang akan dibagi: "))
Penyebut = int(input("Masukkan sebuah angka pembagi: "))
pembagian = float(Pembilang / Penyebut)
print(f'{str(Pembilang)} dibagi dengan {str(Penyebut)} sama dengan {str(pembagian)}')
except ValueError:
print('Nilai yang diinput salah.')
except ZeroDivisionError:
print('Tidak dapat membagi dengan nol.')
## ANOTHER EXAMPLE OF EXCEPTION HANDLING
from statistics import mean
def main():
# List untuk menyimpan isi file
list_angka = []
# [1] Tuliskan statement yang meminta pengguna memasukkan nama file dengan prompt: Masukkan nama file: "
nama_file = input('Masukkan nama file: ')
# [2] Tuliskan exception handler dengan statement try/except
# Pada body klausa try: buka file, baca isinya, dan simpan isinya ke list_angka
try:
infile = open(nama_file, 'r')
list_angka = infile.readlines()
infile.close()
index = 0
while index < len(list_angka):
list_angka[index] = list_angka[index].rstrip('\n')
index += 1
list_angka = list(map(float, list_angka ))
rata2 = mean(list_angka )
highest = max(list_angka )
lowest = min(list_angka )
# Pada body klausa except untuk FileNoFoundError tampilkan pesan "File tidak ditemukan."
except FileNotFoundError:
print('File tidak ditemukan.')
# Pada body klausa except untuk ValueError tampilkan pesan "Terdapat data non numerik dalam file."
except ValueError:
print('Terdapat data non numerik dalam file.')
# Pada body klausa else: Cari rata-rata, nilai tertinggi, nilai terenda dan tampilkan hasilnya
else:
print(f'Rata-rata nilai:{rata2: .2f}')
print(f'Nilai tertinggi:{highest: .2f}')
print(f'Nilai terendah:{lowest: .2f}')
# Panggil fungsi main
main()
| false
|
da211a279fca121ab5531e59190dc9d0c4198a5c
|
annisa-nur/wintersnowhite
|
/processingrecord.py
| 1,698
| 4.25
| 4
|
# Program ini menambahkan record nilai mahasiswa
# ke file nilai_mahasiswa.txt
def main():
# [1] Minta pengguna berapa banyak record yang ingin dimasukkan
jmlRec = int(input("Berapa banyak record nilai mahasiswa yang ingin Anda tambahkan? "))
# [2] Buka file dengan statement with, minta input masing-masing record ke pengguna, dan tulis ke file
# nilai_mahasiswa.txt
with open('nilai_mahasiswa.txt', 'a') as rec:
for count in range(1, jmlRec + 1):
print(f'Masukkan record nilai mahasiswa ke {count}')
nama = input('Nama: ')
nilai = input('Nilai: ')
rec.write(nama + '\n')
rec.write(nilai + '\n')
print()
# Panggil fungsi main
main()
## ANOTHER EXAMPLE
# Program ini membaca record nilai mahasiswa
# dari file nilai_mahasiswa.txt
def main():
# [1] Buka file nilai_mahasiswa.txt dengan statement with untuk dibaca
# Pada body statement with:
# - Gunakan loop while untuk membaca field-field dari semua record
# - Tampilkan record dengan tampilan:
# Nama: <nama_mahasiswa>
# Nilai: <nilai_mahasiswa>
with open('nilai_mahasiswa.txt', 'r') as rec:
nama = rec.readline()
while nama != '':
nilai = rec.readline()
#Strip karakter baris baru dari field
nama = nama.rstrip('\n')
nilai = nilai.rstrip('\n')
print(f'Nama: {nama}')
print(f'Nilai: {nilai}')
print()
nama = rec.readline()
# Panggil fungsi main
main()
| false
|
ac74ba0fde939786aca05fff2648c368f46db4ef
|
miaha15/Programming-coursework
|
/Week 5 Question 1.py
| 974
| 4.34375
| 4
|
'''
Premade list is given to the function
A for loop is used to step through the list
As it steps through each value of the list, it appends the list called TempList
If the current element is GREATER than the next element of the list
then it will check if everything stored in the TempList upto current element
is longer than the sequence stored in LongestSequence
If it is then it will be overwritten, else it will ignore.
'''
import sys
def SubSequence(List):
TempList = []
LongestSequence = ("")
for element in range(0, len(List)-1):
TempList.append(List[element])
if List[element] > List[element+1]:
if len(TempList) > len(LongestSequence):
LongestSequence = []
LongestSequence = TempList
TempList = []
return LongestSequence
print('The Longest Sub-Sequence is:', SubSequence([1,2,3,4,1,2,3,4,5,0]))
sys.exit()
| true
|
9067db5d36f43f7d225c98628272ab067ac8dbd9
|
yerol89/100_Days_Of_Coding_With_Python
|
/1. Day_1_Working With Variables to Manage Data/Day1.py
| 861
| 4.1875
| 4
|
print("Day 1 - String Manipulation")
print("String Concatenation is done with the '+' sign.")
print("New lines can be created with a backslash.")
print("Hello" + " " + "Everyone")
print("Hello Python\nHello 100 Days of Coding")
print("Hello" + " " + input("What is your name?\n"))
name = input("What is your name? ")
print("Length of your name is " + str(len(name)))
#Swapping variables with each other
a = input("a: ")
b = input("b: ")
print("BEFORE SWAP")
print("a is equal to " + a)
print("b is equal to " + b)
c = a
a = b
b = c
print("AFTER SWAP")
print("a is equal to " + a)
print("b is equal to " + b)
# DAY1 PROJECT : BAND NAME GENERATOR
print("Welcome to Band Name Generator")
city = input("What is the name of city that you borned?\n")
pet = input("What is the name of your first pet?\n")
print("The name of the band is " + city +"_" + pet + " BAND")
| true
|
5e5d664cba8f82e045f025a763a3825d5342b0dd
|
msausville/ToolBox-Pickling
|
/counter.py
| 2,030
| 4.40625
| 4
|
""" A program that stores and updates a counter using a Python pickle file"""
from os.path import exists
import sys
from pickle import dump, load
def update_counter(file_name, reset=False):
""" Updates a counter stored in the file 'file_name'
A new counter will be created and initialized to 1 if none exists or if
the reset flag is True.
If the counter already exists and reset is False, the counter's value will
be incremented.
file_name: the file that stores the counter to be incremented. If the file
doesn't exist, a counter is created and initialized to 1.
reset: True if the counter in the file should be rest.
returns: the new counter value
>>> update_counter('blah.txt',True)
1
>>> update_counter('blah.txt')
2
>>> update_counter('blah2.txt',True)
1
>>> update_counter('blah.txt')
3
>>> update_counter('blah2.txt')
2
"""
# Note: Looked at classmates' code to help make this.
if exists(file_name) and not reset:
# The file has already been made and the reset button hasn't been pressed.
file = open(file_name, 'rb+')
# Open the file in reading mode
counter = load(file)
counter += 1
# Tell the counter to add one because the file was opened again.
file.close
return counter
# Close the file and tell us the number on the counter.
else:
file = open(file_name, 'wb')
# The file hasn't been declared or has been reset, rewrite it or make a new one.
counter = 1
# The file has been opened once so the count is one.
dump(counter, file)
# dumping it is what saves the pickle.
file.close
return counter
# pickle.load
# check if file exists
# if doesn't, create file
# initialize counter variable
if __name__ == '__main__':
if len(sys.argv) < 2:
import doctest
doctest.testmod()
else:
print("new value is " + str(update_counter(sys.argv[1])))
| true
|
737c4183d9b77db804165e51af24f8a051e31ec9
|
maumneto/IntroductionComputerScience
|
/CodeClasses/FunctionsCode/cod1.py
| 286
| 4.28125
| 4
|
# O módulo Math possui um conjunto de funções
import math
num1 = int(input('Digite um valor numérico: '))
res = math.sqrt(num1) # nesta linha o código principal irá parar para executar a função math no sistema de módulos do python!
print(f'A raiz quadrada de {num1} é {res}')
| false
|
4b2011ee272cdbf2b8b093786a392f0752a5a7cd
|
maumneto/IntroductionComputerScience
|
/CodeClasses/SequentialCodes/cod7.py
| 566
| 4.125
| 4
|
"""
Escreva um programa que pede os seguintes dados:
• Valor do salário de um funcionário
• Aumento em porcentagem
Depois mostre o valor do aumento e o salário com aumento arredondados para duas
casas decimais
"""
# entrada de dados
salario = float(input("Digite o salario: "))
aumento = float(input("Digite a porcentagem do aumento: "))
# processamento
aumento = salario * (aumento/100)
salario_total = salario + aumento
# saída de dados
# print("O aumento foi de: ", aumento)
print("O aumento foi de %.2f\nTotal é iqual a %.2f" % (aumento, salario_total))
| false
|
2b47b550001583c7a0f60d8b2022051796d39ad5
|
utkpython/utkpython.github.io
|
/session3/simulation.py
| 733
| 4.3125
| 4
|
# modeling the idea that "students getting ahead in life"
# some start off in a higher spot
# some have more skill, some less
from random import randint
import matplotlib.pyplot as plt
def rand_walk(numSteps, position, skill):
'''Returns a random walk list of size numSteps + 1.
position is the starting position.
skill is a measure of how far forward you are
able to walk per turn.'''
walk = [position]
numSteps = numSteps
for i in xrange(numSteps):
if randint(0,1):
step = 1 * skill #take a step forward
else:
step = -1 #take a step backward
position = position + step
walk.append(position)
return walk
| true
|
1ae5d1eb7c5408cedc29486dbe1ee36a2a0df77c
|
joyvai/Python-
|
/stopwatch.py
| 1,615
| 4.28125
| 4
|
# stopwatch.py - A simple stopwatch program.
# The stopwatch program will need to use the current time, so you will want to
# import the time module. Your program should also print some brief instruc-
# tions to the user before calling input() , so the timer can begin after the user
# presses enter . Then the code will start tracking lap times.
import time
# Display the program's instructions.
print ('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch.Press Ctrl-C to quit.')
raw_input() # press ENTER to begin
print 'Started.'
startTime = time.time() # get the first lap's start time.
lastTime = startTime
lapNum = 1
# TODO: Start tracking the lap times.
# Step 2: Track and Print Lap Times
try:
while True:
raw_input()
lapTime = round(time.time() - lastTime,2)
totalTime = round(time.time() - startTime, 2)
print 'Lap #%s: %s (%s)' % (lapNum, totalTime, lastTime)
lapNum += 1
lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
print '\nDone.'
# we use except because of KeyboardInterrupt error messages.
# It works when Ctrl-C press.
# Here while loop is a infinite loop.
# it calls the raw_input() and waits for enter
# to end a lap.when user press enter that means lap finished.
# when a lap ends we calculate the laptime.
# we subtract the start time of the lap from current time using time.time()
# We calculate the total time elapsed by subtracting
# the overall start time of the stopwatch, startTime ,from the current time
# setting lastTime to the current time, which
# is the start time of the next lap.
| true
|
4cb0e6419406286e87f84ece09c9baff8bd3cb5b
|
joyvai/Python-
|
/leapYear.py
| 590
| 4.15625
| 4
|
"""
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
"""
def is_leap_year2(year):
if year % 4 == 0:
return True
elif year % 100 == 1 :
return False
elif year % 400 == 0:
return True
else:
return False
def test_is_leap_year():
years = [1900, 2000, 2001, 2002, 2020, 2008, 2010,2016]
for year in years:
if is_leap_year2(year):
print year, 'is leap year.'
else:
print year, 'is not a leap year'
test_is_leap_year()
| false
|
530fe5b55fe23ad17ac63c31fd7ccba2c2371a27
|
aaronBurns59/3rd-year-functions-python
|
/printList.py
| 404
| 4.40625
| 4
|
def printList(l):
for x in l:
print(x)
list1 = [0,1,2,3,4,5,6,7,8,9,10]
list2 = ['apple', 'orange', 'banana', 'pear', 'kiwi']
list3 = [0.1,2.0,3.3,4.5,8.5]
choice = 0
while choice <= 0 or choice > 3:
choice = int(input("Enter which list you want 1, 2 or 3: "))
if choice == 1:
list = list1
elif choice == 2:
list = list2
elif choice == 3:
list = list3
printList(list)
| false
|
c643875b3f5b48f71f59b6b43c6ba0e4186aaa86
|
arrayatsabitah/mongga
|
/modul.py
| 1,620
| 4.1875
| 4
|
# suatu objek dikatakan class jika punya atribut __init__
class orang:
def __init__(self, nama, umur): #init tu ngejelasin tentang saya (self)
self.nama = nama
self.umur = umur # kayak buat ngenalin diri sendiri
def jalan(self):
print('orang jalan')
def makan(self):
print(self.nama + 'suka makan')
def umurs(self, namateman):
print('umur teman ' + namateman + ' ' + str(self.umur) + ' tahun')
#inheritance
#bikin class baru pake class yang udah ada, tapi isinya mau diganti-ganti
#mewarisi semua method yg ada di class parent (yg udah ada) (overwrite)
class orangtua(orang):
def __init__(self,nama,umur,waktumati):
#When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
#to keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function
self.nama=nama
self.umur=umur
self.waktumati=waktumati
def sakit(self):
print(self.nama+' suka sakit-sakitan')
def makan(self):
print(self.nama+'cuma bisa makna tidur')
class orangorang:
def __init__(self,*args):
self.arg=args
self.counter=0
def __iter__(self): #*args jumlah argumen tidak terbatas
self.a= self.arg[self.counter]
return self.a
def __next__(self):
self.counter += 1
x = self.arg[self.counter]
return x
def penjumlahan(a,b):
sum=a+b
return sum
def pengurangan(a,b):
kurang=b-a
return kurang
| false
|
7412acf2022c4a9509ddd22859ba8f85422abf57
|
fobbytommy/Algorithm-Practice
|
/10_week_2/nth_largest.py
| 386
| 4.34375
| 4
|
# Given an array, return the Nth-largest element
from python_modules import bubble_sort
def nth_largest(arr, n):
list_length = len(arr)
if n <= 0 or list_length < n:
return None
sorted_arr = arr
bubble_sort.bubble_sort(sorted_arr)
return sorted_arr[list_length - n]
arr = [23, 32, -2 , 6 ,2 ,7, 10, 3, 10, 22, 3, -1, 19, 24, 33]
result = nth_largest(arr, 3)
print(result)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.