blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
22f684c1ea3a1f78b58f9b8db35238d5041091ce | suneeshms96/python-password-validator | /python-password-validator.py | 795 | 4.28125 | 4 | digit_count = 0
alpha_count = 0
char_count = 0
lower_count = 0
#we can change password strength requirement here..!
required_digit_count = 5
required_alpha_count = 2
required_char_count = 4
required_lower_count = 2
uname = input('Enter your username: ')
word = input('Enter a password : ')
for w in str(word):
if w.isdigit():
digit_count = digit_count + 1
elif w.isalpha():
alpha_count = alpha_count + 1
if w.islower():
lower_count = lower_count + 1
else:
char_count = char_count + 1
if digit_count >= required_digit_count and alpha_count >= required_alpha_count and char_count >= required_char_count and lower_count >= required_lower_count :
print ('The password is successfully added for',uname)
else:
print('The password is not valid')
| true |
321abe804a7ce7b47ee132886559168e3b52d640 | wojlas/Guess-the-number | /guess_the_number.py | 909 | 4.1875 | 4 | import random
def guess_the_number():
try:
"""function checks if the given number is equal
to the drawn number and displays an appropriate message"""
user_number = int(input("Guess the number: "))
index = 0
while user_number != random_number:
if user_number < random_number:
print("Too small!")
user_number = int(input("Guess the number: "))
index += 1
else:
print("Too big!")
user_number = int(input("Guess the number: "))
index += 1
print(f"You win in {index + 1} steps")
except ValueError:
"""when given value is not a number function print message
"It's not a number" """
print("It's not a number!")
if __name__ == '__main__':
random_number = random.randint(1, 100)
print(guess_the_number())
| true |
29ab376394ff53ed3542e6f22877b23d5d115e72 | dchtexas1/pythonFiles | /division.py | 233 | 4.4375 | 4 | """Gives quotient and remainder of two numbers."""
a = input("Enter the first number: ")
b = input("Enter the second number: ")
print("The quotient of {} divided by {} is {} with a remainder of {}.".format(
a, b, a / b, a % b))
| true |
88cb18925a67570cc548a039b40ea70fcf473889 | Woutah/AutoConvert | /timer.py | 2,290 | 4.25 | 4 | """Simple timer which can be used to get the wall/cpu time of a process.
Implements the "with x:" to measure timings more easily.
"""
from time import process_time
import time
class CpuTimer:
def __init__(self):
self._start_time = process_time()
self._paused = True
self._pause_time = process_time()
self._paused_time = 0
def start_timer(self):
if self._paused:
self._paused = False
self._paused_time = process_time() - self._pause_time
else:
print("Warning: timer has already started")
def __enter__(self):
self.start_timer()
def __exit__(self, exc_type, exc_value, tb):
self.pause_timer()
def pause_timer(self):
if self._paused:
print("Warning: timer already paused")
else:
self._paused = True
self._pause_time = process_time()
def get_time(self) -> float:
if self._paused: #If current paused time needs to be subtracted as well
return process_time() - self._start_time - self._paused_time - (process_time() - self._pause_time)
else: #If only total paused time needs to be subtracted
return process_time() - self._start_time - self._paused_time
class WallTimer:
def __init__(self):
self._start_time = time.time()
self._paused = True
self._pause_time = time.time()
self._paused_time = 0
def __enter__(self):
self.start_timer()
def __exit__(self, exc_type, exc_value, tb):
self.pause_timer()
def start_timer(self):
if self._paused:
self._paused = False
self._paused_time = time.time() - self._pause_time
else:
print("Warning: timer has already started")
def pause_timer(self):
if self._paused:
print("Warning: timer already paused")
else:
self._paused = True
self._pause_time = time.time()
def get_time(self) -> float:
if self._paused: #If current paused time needs to be subtracted as well
return time.time() - self._start_time - self._paused_time - (time.time() - self._pause_time)
else: #If only total paused time needs to be subtracted
return time.time() - self._start_time - self._paused_time
if __name__ == "__main__":
print("Now testing timer")
thetimer = CpuTimer()
print(thetimer.get_time())
thetimer.start_timer()
time.sleep(1.0)
thetimer.pause_timer()
for i in range(100000):
print("kaas")
print(thetimer.get_time())
print("Done")
| true |
8c25a31f8dd7dba671150a51ef052880bdc5c402 | Garce09/ShirleysMentees | /logic_recursion.py | 1,856 | 4.375 | 4 | ############ Q1. Ask the user for an integer, multiply it by itself + 1, and print the result
# Topic: user input
############ Q2. Ask the user for an integer
# If it is an even number, print "even"
# If it is an odd number, print "odd"
# Topic: conditionals, user input
############# Q3. Iterate through each element in the list USING A FOR LOOP, add 5 to it, and print them
# Topic: loops + lists
numbers = [1, 2, 3, 4, 5]
# Code here
# ############# Q4. Iterate through the list and only print values that are divisible by 3 ############
# Topic: lists, loops, conditions, comparison operators
numbers = list(range(0, 500))
# Code Here
counter = 0
for number in numbers:
if number %2 == 0:
counter +=1
print(counter)
# ############# Q5. Iterate through the list and count the number of even numbers within the list ############
# Topic: lists, loops, conditions, comparison operators
numbers = list(range(0, 500))
# Code Here
############# Q6. Iterate through each element in the list, add 5 to it, and print them
# MUST USE A WHILE LOOP
# Topic: loops + lists
# Hint: You can use len() function
numbers = [1, 2, 3, 4, 5]
# Code here
i = 0
#run this for total # of elements in a list
while i < len(numbers):
print(numbers[i] + 5)
print("ran", i + 1, "time(s)")
i += 1
############# Q7. For the following list:
# Print ALL numbers divisible by 7 and label them like so: "Divisible by 7: 70"
# Print ALL numbers divisible by 3 and label them like so: "Divisible by 3: 6"
# Print ALL numbers divisible by 3 and 7 and label them like so: "Divisible by 3 and 7: 21"
############
# Topic: lists, loops, conditions, string concatenation
numbers = list(range(0, 500))
# Code here
| true |
b4eddaa8ceada22cdf3d2c3f12e441752cfb6425 | larlyssa/checkio | /home/house_password.py | 1,648 | 4.1875 | 4 | """
DIFFICULTY: ELEMENTARY
Stephan and Sophia forget about security and use simple passwords for everything. Help Nikola develop a password security check module. The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least one digit, as well as containing one uppercase letter and one lowercase letter in it. The password contains only ASCII latin letters or digits.
Input: A password as a string (Unicode for python 2.7).
Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean. In the results you will see the converted results.
Precondition:
re.match("[a-zA-Z0-9]+", password)
0 < len(password) ≤ 64
"""
def checkio(data):
length = len(data) >= 10
upper = False
lower = False
number = False
for character in data:
if character in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
upper = True
elif character in "abcdefghijklmnopqrstuvwxyz":
lower = True
elif character in "0123456789":
number = True
return upper and lower and number and length
#Some hints
#Just check all conditions
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio('A1213pokl') == False, "1st example"
assert checkio('bAse730onE4') == True, "2nd example"
assert checkio('asasasasasasasaas') == False, "3rd example"
assert checkio('QWERTYqwerty') == False, "4th example"
assert checkio('123456123456') == False, "5th example"
assert checkio('QwErTy911poqqqq') == True, "6th example"
| true |
f1053a896ab4d62501f8f1930514e2d0e2e08dde | RodrigoAk/exercises | /solutions/ex13.py | 545 | 4.3125 | 4 | '''
You are given a positive integer N which represents the number of steps
in a staircase. You can either climb 1 or 2 steps at a time. Write a function
that returns the number of unique ways to climb the stairs
'''
import math
def staircase(n):
spaces = n//2 + n % 2
num2 = n//2
answer = 0
while(spaces <= n):
answer += math.factorial(spaces) / \
(math.factorial(spaces-num2)*math.factorial(num2))
num2 -= 1
spaces += 1
return answer
print(staircase(4))
# 5
print(staircase(5))
# 8
| true |
74ec0c3112aea6992d54a59e2cec323143085df8 | hitanshkadakia/Python_Tutorial | /function.py | 1,419 | 4.75 | 5 | # Creating a Function
# In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
# Calling a Function
# To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
# Arguments
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
# Number of Arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
# Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# Keyword Arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
# Default Parameter Value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
# Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
# Passing a List as an Argument
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
# The pass Statement
def myfunction():
pass | true |
5f2b869fad97bd52b0381a4f95ebce15c54c6568 | hitanshkadakia/Python_Tutorial | /if-elsestatement.py | 711 | 4.21875 | 4 | #If statement
a = 33
b = 200
if b > a:
print("b is greater than a")
#elif
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
#One line if statement:
if a > b: print("a is greater than b")
#One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
#pass statement
#if statements cannot be empty
#but if you for some reason have an if statement with no content
#put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass | true |
17aeb081b24147badad1e1945acae197fe287d43 | BawangGoh-zz/ELEC0088-Lab | /Exercise2.py | 1,122 | 4.125 | 4 | ## Part 1) Implement a DNS querying program that stores the mapping between the names
## into IP addresses. Explicitly define the name of the network into the databases
## Part 2) Allow for the user to query several types of NS record (NS, MX, etc).
# IP addresses query
def IPquery(dct, string):
return dct.get(string)
def NS_MX(dct, string):
if(string.find('NS') == True):
print(str(dct.get(string)))
else:
print(str(dct.get(string)))
def main():
## Part 1) Defining DNS query name and IP addresses databases
IPdatabase = {"www.ee.ucl.ac.uk": '144.82.8.143',
"www.google.com": '8.8.8.8'}
website = str(input("Enter a website: "))
print("Requested IP address: " + IPquery(IPdatabase, website))
print("Print all records: ")
print (IPdatabase)
## Part 2) Defining DNS query name and IP addresses for NS and MX databases
lookup = {'NS': {"www.bbc.co.uk": '212.58.244.26'},
'MX': {"www.google.com": '173.194.202.27'}}
dnstype = str(input("Enter type of lookup: "))
NS_MX(lookup, dnstype)
if __name__ == "__main__":
main() | true |
0ac9ea93dd1a9cc31946535c2b6982052f6e7c60 | moosuchot/handyscripts | /pyscript/add_list.py | 473 | 4.25 | 4 | #!/usr/bin/env python
#coding:utf-8
'''
得到n个相同长度list的对应位置的和后的list.
比如:
a = [1,2,3,4]
b = [5,6,7,8]
求两个list的和.
结果为:
c = [6,8,10,12]
'''
def add_list(*lsts):
merged_list = []
for i in xrange(len(lsts[0])):
merged_list.append(sum([lst[i] for lst in lsts]))
return merged_list
if __name__ == '__main__':
a = [1,2,3,4]
b = [5,6,7,8]
print add_list(a,b)
c = [a,b]
print add_list(*c)
| false |
ff746957eac224baeb7c47522ea4eb4edb576f0e | Ahisanz/luizacode | /python/ana_sanz_adivinha2.py | 1,331 | 4.125 | 4 | import random
print("Seja bem vindo! Qual é o seu nome?")
user_name = input()
print(f"Prazer, {user_name}, vou te explicar as regras do jogo, primeiro eu vou pensar em um número de 1 a 20.")
random_number = random.randint(1, 21)
print()
print("Pronto, pensei! Agora eu vou te dar 6 chances para acertar qual é o número que eu pensei. Valendo!")
for chances in range(1,7):
user_guess = int(input())
if random_number == user_guess:
print("GANHOOUUU!!!!")
print(f"{user_name} você acertou!")
if chances == 1:
print(f"Sim, o numero é {random_number} você acertou de primera!")
else:
print(f"Sim, o numero é {random_number} e você acertou na {chances}ª vez")
break
elif random_number != user_guess and chances <= 5:
try_left = 6 - chances
if user_guess > 20:
print(f"ôôôôÔôôÔÔ {user_name}!! O número tem que ser menor ou igual a 20. Tente outra vez!")
elif user_guess < random_number:
print("O numero que eu pensei é maior que esse!")
else:
print("O numero que eu pensei é menor que esse!")
print(f"Tente outra vez, te faltam {try_left} chances!")
if user_guess != random_number:
print(f"Ah, que pena... O número era {random_number}. Jogue outra vez.")
| false |
222ff971a2cd98b5e876a9b3d9c9e4c7ec891793 | Ahisanz/luizacode | /python/exercio1_dia1.py | 577 | 4.25 | 4 | '''
Crie um programa que peça o nome do usuário, diga que é um prazer conhecê-lo e pergunte a idade dele.
O programa se apresentará como um robô - pode inventar o nome - e dirá quantos anos mais velhos que o usuário ele é.
O robô tem 107 anos
Não se preocupar se o usuário já fez aniversário ou não
'''
print("Olá, qual o seu nome?")
user_name = input()
print(f"Prazer te conhecer, {user_name}. Qual é a sua idade?")
user_years = input()
years_difference = 107 - int(user_years)
print(f"Eu sou a MaluRobo, e eu sou {years_difference} mais velha que você!") | false |
a48867d01dbbd259e0cddf2a0349d9a10b4b99fa | guilherme-witkosky/MI66-T5 | /Lista 2/L2E02.py | 258 | 4.15625 | 4 | #Faça um Programa que peça um valor e mostre
#na tela se o valor é positivo ou negativo.
#Exercício 2
num = float(input("Informe um numero: "))
if num >=0:
print("O numero digitado e positivo")
else:
print("O numero digitado e negativo") | false |
7df8038be3cbd4f3d80a266420efa8ff3ebd258f | guilherme-witkosky/MI66-T5 | /Lista 2/L2E10.py | 711 | 4.15625 | 4 | #Exercício 10
print("Informe o período em que você estuda:")
print("(M) Matutino")
print("(V) Vespertino")
print("(N) Noturno")
print("------------------------------------------")
p = input("Seu Período = ")
print("------------------------------------------")
periodo = p.upper()
print("==========================================")
if periodo == "M":
print("Bom Dia!")
print("==========================================")
elif periodo == "V":
print("Boa Tarde!")
print("==========================================")
elif periodo == "N":
print("Boa Noite!")
print("==========================================")
else:
print("Valor Inválido!")
print("==========================================")
| false |
242f4e0d36978026ba5458e18defc7cb67668422 | guilherme-witkosky/MI66-T5 | /Lista 1/L1E11.py | 627 | 4.40625 | 4 | #Exercício 11
#Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# A) o produto do dobro do primeiro com metade do segundo.
# B) a soma do triplo do primeiro com o terceiro.
# C) o terceiro elevado ao cubo.
int1 = int(input('Informe um numero inteiro: '))
int2 = int(input('Informe outro numero inteiro: '))
real = int(input('Informe um numero real: '))
a = ((int1 * 2) * (int2 / 2))
b = ((int1 * 3) + real)
c = real**3
print("o produto do dobro do primeiro com metade do segundo: ", a)
print("a soma do triplo do primeiro com o terceiro: ", b)
print("o terceiro elevado ao cubo: ", c)
| false |
b2c8d209db76afe3959cb2a10117366c133f5008 | guilherme-witkosky/MI66-T5 | /Lista 2/L2E16.py | 1,214 | 4.1875 | 4 | #Exercicio 16
#Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e
#fazer as consistências, informando ao usuário nas seguintes situações: Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o
#programa não deve fazer pedir os demais valores, sendo encerrado; Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o
#programa; Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário; Se o delta for positivo, a equação possui duas raiz reais;
#informe-as ao usuário;
a = int(input("Informe o valor de A: "))
if a == 0:
print("A = 0, a equação não é do segundo grau")
quit()
else:
b = int(input("Informe o valor de B: "))
c = int(input("Informe o valor de C: "))
delta = (b**2) - (4 * a * c)
print(delta)
if delta < 0:
print("Delta é negativo, a equacao nao possui raizes reais")
quit()
elif delta == 0:
print("Delta = 0, a equacao possui apenas uma raiz real")
else:
print("Delta maior que 0, a equacao possui duas raizes reais")
| false |
8c180b5c53bc9a211ec88c7a4477987a307f0ed9 | guilherme-witkosky/MI66-T5 | /Lista 8/L8E05.py | 1,310 | 4.125 | 4 | #Classe Conta Corrente: Crie uma classe para implementar uma conta corrente.
#A classe deve possuir os seguintes atributos: número da conta, nome do correntista e saldo.
# Os métodos são os seguintes: alterarNome, depósito e saque; No construtor, saldo é opcional,
# com valor default zero e os demais atributos são obrigatórios.
class ContaCorrente:
def __init__(self, nrConta, nomeDono, saldo):
self.nrConta = nrConta
self.nomeDono = nomeDono
self.saldo = saldo
def saque(self, valorSaque):
if valorSaque > self.saldo:
print("Valor execede o saldo existente!")
else:
self.saldo -= valorSaque
def verificarSaldo(self):
print("Seu saldo é de: ", self.saldo)
def verificarInfo(self):
print("Seu nome é : ", self.nomeDono)
def deposito(self, valorDep):
self.saldo += valorDep
def alterarNome(self, novoNome):
if novoNome == "" or novoNome == " ":
print("Caractere inválido")
else:
self.nomeDono = novoNome
conta01 = ContaCorrente(1,"Leonardo", 100)
conta01.saque(50)
conta01.deposito(1050)
conta01.alterarNome("Leonardo Pio")
conta01.verificarSaldo()
conta01.verificarInfo()
| false |
8a0a9d68892f0dbac3b8e55eb69e82f1788cc05e | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-4-Partition.py | 1,801 | 4.3125 | 4 | # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "right partition"; it does not need to appear between the left and right partitions.
# EXAMPLE
# Input:
# Output:
# 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition= 5]
# 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def append(self, x):
n = self
while n.next:
n = n.next
n.next = ListNode(x)
# recursion, time O(n), unstable
def partition1(n,x):
if not n.next:
return n,n
first, end = partition(n.next, x)
if n.val < x:
n.next = first
first = n
else:
end.next = n
n.next = None
end = n
return first, end
# maintain two lists and combine, O(n), stable
def partition2(n,x):
small = None
big = None
first = None
mid = None
while n:
if n.val < x:
if small:
small.next = n
small = small.next
else:
small = n
first = n
else:
if big:
big.next = n
big = big.next
else:
big = n
mid = n
n = n.next
small.next = mid
big.next = None
return first, big
# n = ListNode(3)
# n.append(5)
# n.append(8)
# n.append(5)
# n.append(10)
# n.append(2)
# n.append(1)
# n,_ = partition2(n,5)
# while n:
# print(n.val)
# n = n.next
| true |
6c3b5c12c863b87a0c1d0cdb3ddc164caafb5862 | jimsun25/python_practice | /turtle_race/main.py | 927 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_pos = [-75, -45, -15, 15, 45, 75]
turtles = []
for i in range(6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[i])
new_turtle.penup()
new_turtle.goto(x=-235, y=y_pos[i])
turtles.append(new_turtle)
if user_bet:
race_on = True
while race_on:
cur_turtle = random.choice(turtles)
cur_turtle.forward(random.randint(0, 5))
if cur_turtle.xcor() > 230:
race_on = False
win = cur_turtle.pencolor()
if win == user_bet:
print("You've won the bet!!!")
else:
print(f"You've lost. The {win} turtle is the winner.")
screen.exitonclick() | true |
f5f9dc8646c6e16b68dfed9ec46ef70328964ecd | jorge800/pythonLanguage | /arithmetic.py | 564 | 4.1875 | 4 | # Python Arithmetic Operators.
# Let x = 34 and y = 78, then find z;
x = 34 # Let x = 34
y = 78 # y = 78
z = (x + y) # Addition Operator
print("Addition:\n"+str(z))
z = (x - y) # Substraction Operator
print("Substraction:\n"+str(z))
z = (x * y) # Multiplication Operator
print("Multiplication:\n"+str(z))
z = (x / y) # Division Operator
print("Division:\n"+str(z))
z = (x % y) # Modulus Operator
print("Modulus:\n"+str(z))
z = (x ** y) # Exponential Operator
print("Exponential:\n"+str(z))
z = (x // y) # Floor Division Operator
print("Floor Division:\n"+str(z))
| false |
b8ee4804c73a956a36f4b00d94d50551149a2ad5 | sdahal1/pythonoctober | /fundamentals/python_fun/bootleg_functionsbasic2.py | 1,213 | 4.65625 | 5 | # CountUP - Create a function that accepts a number as an input. Return a new list that counts up by 1, from 1 (as the 0th element) up to num (as the last element).
# Example: countup(5) should return [1,2,3,4,5]
# Print and Return - Create a function that will receive a list with three numbers. Print the second value and return the third.
# Example: print_and_return([1,2,3]) should print 2 and return 3
# Second times Length - Create a function that accepts a list and returns the product of the second value in the list times the list's length.
# Values less than third - Write a function that accepts a list and creates a new list containing only the values from the original list that are smaller than its 3rd value. Print how many values this is and then return the new list. If the list has less than 3 elements, have the function return False
# This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
| true |
1a03184e8ca72e019f6afc71915f90837ecf2c34 | spacecase123/cracking_the_code_interview_v5_python | /array_strings/1.2_reverse_string.py | 788 | 4.3125 | 4 | '''
Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string.
'''
def reverse(string):
'''reverse in place'''
string_len = len(string)
if string_len <= 1 : return string
last = string_len - 1
string = list(string)
for i in range(string_len / 2):
string[i], string[last - i] = string[last -i], string[i]
return "".join(string)
def reverse_words(string):
'''reverse words in a string'''
r = []
for words in string.split():
r.insert(0, words)
return [r for r in reversed(string.split())]
if __name__ == "__main__":
print reverse_words("see the dog jump")
print reverse('abcdefghijk')
print reverse('abcdefghij')
print reverse('ab')
print reverse('aaaabbb')
| true |
05b4df401f64144d9147a616b5ff5ac94d0b0eac | Howardman2/Hello-World | /13.py | 485 | 4.125 | 4 | print('Welcome to TRUE or FALSE')
print ('Please answer with yes or no')
Truth = input('Mr Gallo is the best: ')
if Truth !='yes':
print('wrong')
if Truth =='yes':
print('Correct!')
Falth = input('Coding is dumb: ')
if Falth =='yes':
print('WRONG')
if Falth !='yes':
print('Correct!')
Truce = input('Technology is the future: ')
if Truce !='yes':
print('WRONGGGG')
if Truce =='yes':
print('CORRRECTTT')
print('Thanks for playing!!!!!!')
| false |
1077da31c67125636c41d22aed5e7359d13ce82d | bobbybabra/codeGuild | /basics/dictIterate.py | 1,016 | 4.1875 | 4 | people = {}
people['Bob'] = 22
people['Carol'] = 47
people['Justin'] = 14
for i, k in people.items():
print (i,k)
#for i in people.keys():
# print (i)
list(people.keys())
print people.keys()
# print(people)
people = {}
########### from quiz solution, this dict is not formatted
#### correctly, but the point is down below on iterating through
### the dict when there is a dict w/in the dict
## see kevin long's script
people['Bob'] = {age:22}
people['Carol'] = {age:47}
people['Justin'] = {age:14}
# for (i, k) in (people.keys(), people):
# print (i + people.get(k))
for i, j in people.values():
print i + j
#for i in people.keys():
# print (i)
list(people.keys())
print people.keys()
# print(people)
for index, person in people.items():
print index, person['age']
people = {}
people['Bob'] = 22
people['Carol'] = 47
people['Justin'] = 14
for i, k in people.items():
print (i,k)
#for i in people.keys():
# print (i)
list(people.keys())
print people.keys()
# print(people)
| false |
acf1238f2f25e2ba32b1c0086b1a75bcc0c6905a | gauravbachani/Fortran-MPI | /Matplotlib/tutorial021_plotColourFills.py | 1,484 | 4.15625 | 4 | # Plotting tutorials in Python
# Fill colours inside plots
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('default')
x = np.linspace(-2.0*np.pi, 2.0*np.pi, 201)
C, S = np.cos(x), np.sin(x)
plt.plot(x, C, color='g', label='Cosine')
plt.plot(x, S, color='r', label='Sine')
# Upper value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# curves can be in any order
# Simply: area above the curve from a reference above the curve
# plt.fill_between(x, S, 1)
# mid value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# Simply: area under the curve with the reference intersecting the curve
# plt.fill_between(x, 0, S)
# lower value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# Simply: area below the curve from a reference below the curve
# plt.fill_between(x, -1, S)
# Area between curves
# Simply: Area between the curves
# plt.fill_between(x, S, C, color='orange', alpha=0.3)
# Area between curves
# Limited regions
# plt.fill_between(x[20:41], C[20:41], S[20:41], color='red', alpha=0.7)
# Using where option
# plt.fill_between(x, C, S, where=C>=S, color='green', alpha=0.3)
# plt.fill_between(x, C, S, where=C<=S, color='red', alpha=0.3)
# using interpoldiff = C-S
plt.fill_between(x, C, S, where=(C>=S), color='green', alpha=0.3, interpolate=True)
plt.fill_between(x, C, S, where=(C<=S), color='red', alpha=0.3, interpolate=True)
plt.grid()
plt.legend()
plt.title('Sample Sine and Cosine curves')
plt.show() | true |
60a97cefda9fa31dda0b46740b8dc5de42bc17fe | StephenH69/CodeWars-Python | /8-total-amount-of-points.py | 1,606 | 4.25 | 4 | # Our football team finished the championship. The result of each match look like "x:y".
# Results of all matches are recorded in the collection.
# For example: ["3:1", "2:2", "0:1", ...]
# Write a function that takes such collection and counts the points of our team in the championship.
# Rules for counting points for each match:
# if x>y - 3 points
# if x<y - 0 point
# if x=y - 1 point
# Notes:
# there are 10 matches in the championship
# 0 <= x <= 4
# 0 <= y <= 4
def points(games):
total = 0
for x in games:
if x[0] > x[2]:
total += 3
elif x[0] == x[2]:
total += 1
return total
print(points(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']))
print(points(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']))
print(points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']))
print(points(['1:0', '2:0', '3:0', '4:0', '2:1', '1:3', '1:4', '2:3', '2:4', '3:4']))
print(points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']))
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']), 30)
# Test.assert_equals(points(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']), 10)
# Test.assert_equals(points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']), 0)
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:0', '2:1', '1:3', '1:4', '2:3', '2:4', '3:4']), 15)
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']), 12)
| true |
57f3618fc797fa6bec6c896585f94685b2265337 | StephenH69/CodeWars-Python | /8-blue-and-red-marbles.py | 1,517 | 4.1875 | 4 | # You and a friend have decided to play a game to drill your
# statistical intuitions. The game works like this:
# You have a bunch of red and blue marbles. To start the game you
# grab a handful of marbles of each color and put them into the bag,
# keeping track of how many of each color go in. You take turns reaching
# into the bag, guessing a color, and then pulling one marble out. You
# get a point if you guessed correctly. The trick is you only have three
# seconds to make your guess, so you have to think quickly.
# You've decided to write a function, guessBlue() to help automatically
# calculate whether you should guess "blue" or "red". The function should take four arguments:
# the number of blue marbles you put in the bag to start
# the number of red marbles you put in the bag to start
# the number of blue marbles pulled out so far (always lower than the starting number of blue marbles)
# the number of red marbles pulled out so far (always lower than the starting number of red marbles)
# guessBlue() should return the probability of drawing a blue marble, expressed as a float.
# For example, guessBlue(5, 5, 2, 3) should return 0.6.
def guess_blue(blue_start, red_start, blue_pulled, red_pulled):
return((blue_start - blue_pulled)/((blue_start + red_start) - (blue_pulled + red_pulled)))
print(guess_blue(5, 5, 2, 3))
print(guess_blue(5, 7, 4, 3))
print(guess_blue(12, 18, 4, 6))
# guess_blue(5, 5, 2, 3), 0.6)
# guess_blue(5, 7, 4, 3), 0.2)
# guess_blue(12, 18, 4, 6), 0.4) | true |
7c86e26e0bea599be21bc9a00c788f2e9e63cef4 | VaishnaviBandi/6063_CSPP1 | /m4/p3/longest_substring.py | 1,431 | 4.3125 | 4 | '''Assume s is a string of lower case characters.
Write a program that prints the longest
substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring.
For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Note: This problem may be challenging.
We encourage you to work smart.
If you've spent more than a few hours on
this problem, we suggest that you move on
to a different part of the course.
If you have time, come back to this problem
after you've had a break and cleared your head.'''
def main():
"""This program prints the longest sequence of alphabets"""
STRING_INPUT = input()
STRING_A = STRING_INPUT + "!"
TEMP = ''
TEMP_1 = ''
BEG_VAL = 0
MOV_VAL = 1
LEN = len(STRING_A)
COUNT = 1
LENGTH = 1
while MOV_VAL <= LEN-1:
COUNT = 1
TEMP = STRING_A[BEG_VAL]
while STRING_A[BEG_VAL] <= STRING_A[MOV_VAL] and MOV_VAL < LEN:
COUNT = COUNT + 1
TEMP = TEMP+STRING_A[MOV_VAL]
BEG_VAL = MOV_VAL
MOV_VAL = MOV_VAL + 1
BEG_VAL = MOV_VAL
MOV_VAL = MOV_VAL + 1
if COUNT == LENGTH:
TEMP_1 = TEMP_1
if COUNT > LENGTH:
LENGTH = COUNT
TEMP_1 = ""
TEMP_1 = TEMP
print(TEMP_1)
if __name__ == "__main__":
main()
| true |
b61b666855df35a0968802a9018d3baf29187cc2 | VaishnaviBandi/6063_CSPP1 | /m22/assignment1/read_input.py | 426 | 4.375 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
"""python program to read multiple lines of text
input and store the input into a string."""
string = ''
no_of_lines = int(input())
for each_line in range(no_of_lines):
string = string + (input()) + "\n"
each_line += 1
print(string)
if __name__ == '__main__':
main()
| true |
264245a0748c7c261abf311076a164b9cd1f4379 | aaronspindler-archive/CSCI1030U | /Labs/lab04.py | 1,453 | 4.375 | 4 | #Date: October 8th 2015
#Practising printing the statment testing 1 2 3...
print("testing 1 2 3...")
#Printing numbers, variables, and num equations
x=8
print(x)
print(x*2)
#Defining other variable types
name = "Carla Rodriguez Mendoza"
length = 14.5
width = 7.25
#Printing statments
print("X: ")
print(x)
print("Name:", name)
#Printing nums attached to words
print("length:" + str(length))
print("width:",)
#Defining more variables
firstName = "Maya"
lastName = "Pandit"
age = 20
birthMonth = "December"
#Printing longer statments with multiple data types
print(firstName, lastName, "is", age, "years old. Her next birthday is in",birthMonth + ".")
#Inputing a number and then using if statments to determine what to print
num = int(input("Enter a number:"))
secretNum = 6
if(num > secretNum):
print("Lower")
elif(num < secretNum):
print("Higher")
elif(num == secretNum):
print("You got it!")
num = int(input("Enter a number:"))
if num >= 5 and num <= 10:
print "This number is between 5 and 10"
elif num < 5 or num >10:
print "This number is not between 5 and 10"
#Inputing a grade number and determining what grade letter is corresponds to
#using if statements
gradeNum = int(input("Enter a grade number:"))
if(gradeNum < 50):
print("F")
elif(gradeNum > 49 and gradeNum < 60):
print("D")
elif(gradeNum > 59 and gradeNum < 70):
print("C")
elif(gradeNum > 69 and gradeNum < 80):
print("B")
elif(gradeNum > 79):
print("A")
| true |
fcf797b741b31215d44684056807336655a29638 | artbb/gb_python | /hw2_2.py | 642 | 4.21875 | 4 | # 2) Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются
# элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить
# на своем месте. Для заполнения списка элементов необходимо использовать функцию input().
data = input('Введите не менее 3 символов: ')
for i in range(0, len(data), 2):
print((data[i:i + 2][::-1]), end='')
| false |
7007ff4c5d4cd9ae59ba9642bf27f5b38c6af4d1 | artbb/gb_python | /hw3_2.py | 1,048 | 4.25 | 4 | """
2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
def user_data(name, surname, birth, city, email, phone):
return (
f'Добрый день {name} {surname}! Проверьте ваши данные: вы родились {birth}, проживаете в {city}, ваш email {email}, телефон {phone}')
print(user_data(name=input('Ваше имя: '), surname=input('Ваша фамилия: '), birth=input('Год рождения: '),
city=input('Город проживания: '), email=input('email: '), phone=input('Телефон: ')))
| false |
8e1997b194cd3c70b844333b9a91b1a8ffee002b | fergatica/python | /triangle.py | 578 | 4.21875 | 4 | from math import sqrt
def area(first, second, third):
total = (first + second + third) / 2
final = sqrt(total*(total-first)*(total-second)*(total-third))
return final
def main():
first = input("Enter the length of the first side: ")
first = float(first)
second = input("Enter the length of the second side: ")
second = float(second)
third = input("Enter the length of the third side: ")
third = float(third)
final = area(first, second, third)
print("The triangle's area is ", end="")
print("{:.1f}".format(final))
main()
| true |
9514caf7bef250e2917c6444326ed88f4d03886d | alexfreed23/OleksiiHorbachevskyi-PythonCore | /Python/PythonCore/HomeWork/HomeWork_8_20200703/Task3.py | 609 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 4 11:28:04 2020
@author: oleksiy
"""
def checkDate(day, month, year):
dayInMonth = [31,28,31,30,31,30,30,31,31,30,31,30,31]
if month < 1 or month > 12: return False
elif day < 1 or day > 31: return False
elif month > dayInMonth[month]:
print(month, dayInMonth[month-1])
return False
elif len(year) > 4 or len(year) < 4: return False
else:
print(month, dayInMonth[month-1])
return True
print(checkDate(int(input("Enter day: ")),int(input("Enter month: ")), input("Enter year: "))) | false |
a8ad09b9e8ba85067526a6eb731e58908559ca59 | LukasSilvaSantos/python_solutions | /curso_em_video/atvidades de manipulação de textos/desafio22.py | 562 | 4.21875 | 4 | #Crie um programa que leia o nome completo de uma pessoa e mostre:
#O nome com todas as letras maiúsculas.
#O nome com todas as letras minúsculas.
#Quantas letras ao todo (sem considerar os espaços.)
#Quantas letras tem o primeiro nome.
MeuNome = str(input(' digite seu nome!: ')).strip()
print(f' Analisando seu nome...\n O seu nome é {MeuNome}.\n Todo em maiúsculo é {MeuNome.upper()}.\n Todo em minúsculo é {MeuNome.lower()}.\n O seu nome tem {len(MeuNome) - MeuNome.count(" ")} ')
print(f' Seu primeiro nome tem {MeuNome.find(" ")} letras.')
| false |
63f3824ef398440e8cc1950da02441b0b677670f | LukasSilvaSantos/python_solutions | /faculdade/exercicio5.py | 1,018 | 4.3125 | 4 | print('CAlCULANDO... \n + = ADIÇÃO \n - = Subtração \n * = Multiplicação \n / = Divisão.')
operação = input('qual operação deseja fazer?: ').lower()
while (operação != 'sair'):
numero1 = float(input('digite um valor: '))
numero2 = float(input('digite um valor: '))
if (operação == '+'):
soma = numero1 + numero2
print(f'A soma de {numero1} + {numero2} é {soma}.')
elif (operação == '-'):
soma = numero1 - numero2
print(f'A subtração de {numero1} - {numero2} é {soma}.')
elif (operação == '*'):
soma = numero1 * numero2
print(f'A multiplicação de {numero1} * {numero2} é {soma}.')
elif (operação == '/'):
soma = numero1 / numero2
print(f'A divisão de {numero1} / {numero2} é {soma}.')
print('CAlCULANDO... \n + = ADIÇÃO \n - = Subtração \n * = Multiplicação \n / = Divisão.')
operação = input('qual operação deseja fazer?: ').lower()
print('Encerrando o programa...')
input()
| false |
b024afabdd981863e78cf8be0aaeaf2a5736725b | drozol/python01 | /workhome/Day_03_01.py | 945 | 4.15625 | 4 | # 1. Napisz program do przeliczania stopni Celsjusza na Fahrenheita i odwrotnie (wyświetlając wzór i kolejne obliczenia)
rodzaj = input ("Jakie stopnie będziesz podqwał do przeliczenia Fahrenheit / Celsjusz wpisz F lub C - ")
temperatura = float(input ("Podaj liczbę stopni: "))
if rodzaj == 'F' or rodzaj =='f':
print("Przeliczamy stopnie Farenhaita na Celsjusza")
print("Konwersja z Fahrenheita do Celsjusza ℃ = ((℉ - 32) / 1.8) ")
wynik = float ((temperatura - 32) /1.8)
print (str(temperatura) + " stopni Farenhaita to " + str(wynik) + " stopni Celsjusza")
elif rodzaj == 'C' or rodzaj =='c':
print("Przeliczamy stopnie Celsjusza na Farenhaita")
print("Konwersja z Celsjusza do ℉ =((℃ *1.8) + 32)")
wynik = float ((temperatura * 1.8) + 32)
print(str(temperatura) + " stopni Celsjusza to " + str(wynik) + " stopni Farenhaita")
else:
print ("Podałeś błędnie parametry") | false |
4683537ce9b8565c779407bca07abe00992279a9 | franciscomelov/Apuntes | /reto_dataAcademy/21_listas.py | 631 | 4.125 | 4 | # Nos permite guardar varios valores en una sola variable
numero = 3
otro_numero = 4
numeros = [1, 2, 3, 4, 5, 5, 6, 1]
print(numeros)
# [1, 2, 3, 4, 5, 5, 6, 1]
objetos = ["hola", 2, True, "a", 2.5]
# Accediendo a los elementos
lista = ["a", "b", "c"]
lista[0]
# a
lista[1]
# b
lista[3]
# IndexError
# AÑADIENDO A UNA LISTA
lista = ["a", "b", "c"]
objetos.append(1)
lista
["a", "b", "c", 1]
lista[3]
# 1
# BORRANDO DE LA LISTA
objetos = ["a", "b", "c", 1]
objetos.pop(1)
lista
# ["a", "c", 1]
# RECORRIENDO LA LISTA
for elemento in objetos:
print(elemento)
# a
# c
# 1
elemento[::-1]
# invierte la lista
| false |
e63094b8a8351924742363fd1e2517272fd2a7e2 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/114_flatten_binary_tree_to_linked_list.py | 1,223 | 4.40625 | 4 | # Given a binary tree, flatten it to a linked list in -place.
# For example, given the following tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None
stack = [root]
while stack:
curr = stack.pop()
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
if stack:
curr.right = stack[-1]
curr.left = None
"""
create stack with root in stack
traverse through the tree inorder (append right, append left)
if there's anything in the stack, then set curr.right to last element in stack
set curr.left to None
"""
| true |
e34f79a5dbe72d7e8fff2f46b5f89f9de50f673a | hjungj21o/Interview-DS-A | /lc_88_merge_sorted_arr.py | 959 | 4.21875 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space(size that is equal to m + n) to hold additional elements from nums2.
# Example:
# Input:
# nums1 = [1, 2, 3, 0, 0, 0], m = 3
# nums2 = [2, 5, 6], n = 3
# Output: [1, 2, 2, 3, 5, 6]
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
p = n + m - 1
p1 = m - 1
p2 = n - 1
while p1 >= 0 and p2 >= 0:
if nums2[p2] > nums1[p1]:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
if p2 >= 0:
nums1[:p+1] = nums2[:p2+1]
| true |
d647fc1babadb96e9d4268d9cd97255efa479bc1 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/21_merge_sorted_list.py | 913 | 4.15625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l2.val > l1.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
"""
two pointers
create a dummy node
curr point to dummy
create a loop to iterate through both l1 and l2
if l2.val > l1.val:
dummy.next = l1
move l1 along
vice versa for l2
if there's any left over in l1 or l2, attach it to curr.next
return dummy.next
"""
| true |
a8242252ac207c8121d7f75859a97bcd9b873875 | orsnes-privatskole/python-oppgaver | /calculator-deluxe.py | 2,869 | 4.125 | 4 | import time
# Calculator - Deluxe Edition
# Name and version info
version_info = "MyCalculator - Deluxe Edition v0.3"
# Function for getting menu choice
def get_menu_choice():
# Variable used to align the menu to a common width
menu_width = 30
# List of available menu options
valid_menu_choice = ['+', '-', '*', '/', 'e']
# Loop until valid choice is made. If illegal input, ask the user again
while True:
print('\n')
print('*' * menu_width)
print("Welcome to " + version_info)
print('*' * menu_width)
print("Choose type of calculation or exit")
print('*' * menu_width)
print("* Addition: +")
print("* Subtraction: -")
print("* Multiplication: *")
print("* Division: /")
print("* Exit: e")
print('*' * menu_width)
choice = input("Please choose your option: ")
# If the user input is valid, exit the loop by returning from the function with the user choice
if choice in valid_menu_choice:
return choice
# If the user did not input a valid choice, inform about valid options, and ask again
else:
print(f"\n\t** Illegal menu option, please use one of {valid_menu_choice}")
time.sleep(1)
# Function for reading in a number, and ensuring that the input is valid
def read_input_number():
while True:
input_number = input("Please input number: ")
if input_number.isdigit():
return int(input_number)
else:
print(f"\n\t** {input_number} is not valid, try again")
time.sleep(1)
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
def calculate(a, b, operator):
if operator == '+':
return addition(a, b)
elif operator == '-':
return subtraction(a, b)
elif operator == '*':
return multiplication(a, b)
elif operator == '/':
return division(a, b)
# Variable for storing the user menu choice
menu_choice = get_menu_choice()
# Loop the whole program until the user choice is 'e' (exit)
while menu_choice != 'e':
# Get the two numbers from the user
number_a = read_input_number()
number_b = read_input_number()
# Calculate based on chosen operator and input numbers
result = calculate(number_a, number_b, menu_choice)
# Print results of calculation
print(f"\n** Calculation {number_a} {menu_choice} {number_b} = {result}\n")
time.sleep(1)
menu_choice = get_menu_choice()
# The loop is finished and we exit the program
print(f"\nThank you for using {version_info}")
print("Goodbye")
| true |
deab4c799195b9bd5b92f3052f10a7ec2c1f1826 | MarcosRS/python_practice | /01_strings.py | 1,548 | 4.21875 | 4 | #escaping characters \' , \" , \t, \n, \\
alison = 'That is Alison\'s cat'
print(alison)
#you can also use raw string and everythig will be interpreted as a string
rawStr = r'nice \' \n \" dfsfsf '
print(rawStr)
# multiline strings. this iincludes new lines as tab directly. Useful when you have a large string
mul = '''
Once Upon a time
Little red hidding hood
was walking in the forrest.
And you know the rest :D
'''
print(mul)
# You can use lists/array list in strings too:
print(alison[0])
print(alison[1:])
print(alison[-1])
print('al' in alison)
print('123' not in alison)
# String Methods
strText = 'once upon! SHREK! donkey'
print(strText.upper())
print(strText.lower())
print(strText.title())
print(strText.isupper()) #boolean
print(strText.islower()) # boolean
print(strText.upper().isupper())
# Other methods : isalpha, isalnum, isdecimal,
# isspace, istitle, startswith, endswith,
# ljust, rjust (second argument specifies the fill character)
# center (second argument specifies the fill character)
# strip, rstrip, lstrip (removes spaces)
# replace (same :D)
#join example:
print (','.join(['cat', 'rat', 'bat']))
#split example
print('bat,mat,fat'.split(','))
#Additional: pyperclip (needs to be installed)
#pyperclip is used to grab
#pyperclip.copy() , copies to the clipboard
#pyperclip.paste() , brings back the text from the clipboard
# STING FORMATTING - Similar to templating
stingTest = 'nice' + 'coding'
name = 'Alice'
time = '10:00:'
print('%s You are invited to a party at %s' % (name, time))
| true |
c899ae39957dc75221110be441670016040002d4 | Rachelami/Pyton_day-1 | /ex 03.py | 291 | 4.125 | 4 |
num = 3
def is_even(number):
if isinstance(number, int) == True:
if number == num:
print("True")
return True
else:
print("False")
return False
else:
print ("This is NOT an integer")
exit()
is_even(5)
| true |
376c45f4b21df79d6505234d5d14f4e1e61411c7 | Akansha0211/PythonPrograms | /Assignment4.6.py | 1,295 | 4.40625 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation.
# The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
def computepay(h,r):
try:
h = float(hrs)
r = float(rate)
except:
print("Error . please enter numeric input")
quit() # if we don't use quit it will again give us traceback instead of placing it inside except block
if (h > 40): # once got appropriate value (without traceback error)
grossPay = h * r + (h - 40) * 1.5 * r;
else:
grossPay = h * r
return grossPay
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
p = computepay(10,20) # invoke function
print("Pay",p) | true |
258d58764350aab386c1fd047b0d72ef47906114 | WangsirCode/leetcode | /Python/valid-parenthesis-string.py | 1,892 | 4.375 | 4 | # Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must have a corresponding left parenthesis '('.
# Left parenthesis '(' must go before the corresponding right parenthesis ')'.
# '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
# An empty string is also valid.
# Example 1:
# Input: "()"
# Output: True
# Example 2:
# Input: "(*)"
# Output: True
# Example 3:
# Input: "(*))"
# Output: True
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
left = []
star = []
if not s:
return True
for index, value in enumerate(s):
if value == '(':
left.append(index)
elif value == '*':
star.append(index)
else:
if left:
left.pop()
elif star:
star.pop()
else:
return False
if not left:
return True
elif len(left) > len(star):
return False
else:
index = -1
for i in left:
index +=1
if index == len(star):
return False
while(star[index] < i) :
index += 1
if index == len(star):
return False
return True
if __name__ == "__main__":
print(Solution().checkValidString("()*()**()(())(()()(())*)()((()**))()()()(((*(((*)))(**(())))*()*))()(()()(()))()((())(*()())())()(*")) | true |
327adc7432d621c66865248250a20d233671e2b9 | MuhammadAzizShobari/praxis-academy | /novice/02-01/latihan/kekekalan.py | 552 | 4.1875 | 4 | mutable_collection = ['Tim', 10, [4, 5]]
immutable_collection = ('Tim', 10, [4, 5])
# Reading from data types are essentially the same:
print(mutable_collection[2]) # [4, 5]
print(immutable_collection[2]) # [4, 5]
# Let's change the 2nd value from 10 to 15
mutable_collection[1] = 15
# This fails with the tuple
immutable_collection[1] = 15
immutable_collection[2].append(6)
print(immutable_collection[2]) # [4, 5, 6]
immutable_collection[2] = [4, 5]
# This throws a familiar error:
# TypeError: 'tuple' object does not support item assignment | true |
3c40edcb6143bd3a72febcac7c4e0f891e571e51 | roopi7760/WebServer | /Client.py | 2,797 | 4.125 | 4 | '''
Author: Roopesh Kumar Krishna Kumar
UTA ID: 1001231753
This is the Client program which sends the request to the server and displays the response
*This code is compilable only with python 3.x
Naming convention: camel case
Ref: https://docs.python.org/3/library/socket.html and https://docs.python.org/3/tutorial/index.html '''
import sys
import socket
import time
import datetime
#Method to print socket details
def PrintServerDetails(ServerAddress, ServerPort):
ServerDetails = socket.getaddrinfo(ServerAddress, ServerPort, proto=0) #This function returns a list of 5-tuples(family, type, proto, canonname, sockaddr)
print("Server socket family:", ServerDetails[0][0])
print("Server socket type:", ServerDetails[0][1])
print("Server name: " , socket.gethostbyaddr(ServerAddress)[0])
#End of method PrintServerDetails
#Main program starts here
try:
print("Client Started. . .\n")
ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket to connect to server
if(len(sys.argv) < 3): #Check whether the command line argument is less than 3. [argv[0]:File Name]
print("No or insufficient parameters recieved! \n")
ServerAddress = input("Enter the Server address: ") #Take the input from the user if the arguments are not sufficient.
ServerPort = int(input("Enter the port: "))
FileName = input("Enter the file you want request: ")
else: #if the command line argument is sufficient, then assign them to respective variables.
ServerAddress = (sys.argv[1])
ServerPort = int(sys.argv[2])
FileName = (sys.argv[3])
SendMsg = 'GET /'+FileName+ ' HTTP/1.1' #Prepare the header for the request
StartTime = datetime.datetime.now() #Mark the start time of the connection to calculate RTT
ClientSocket.connect((ServerAddress, ServerPort)) #Connect to the server
ClientSocket.sendall(SendMsg.encode()) #send the request to the server
ReplyFromServer = ClientSocket.recv(1024) #Recieve the request from the server
EndTime=datetime.datetime.now() #Mark the end time of the connection to calculate RTT
PrintServerDetails(ServerAddress,ServerPort)
print("Peer name: " , ClientSocket.getpeername() , "\n")
print("\nReply from the server: \n============\n")
print(ReplyFromServer.decode())
RTT = (EndTime - StartTime) #calculate the RTT
print("\nThe RTT is ", (RTT.total_seconds()) , " seconds or %.2f" %((RTT.total_seconds())*1000) , " milliseconds.") #print the RTT in seconds and milliseconds format
ClientSocket.close() #close the client socket
k = input("\nPress any key to exit") #close the program
except Exception as e:
print("Client encountered an error! Client is closing!\n",e)
'''End of the program'''
| true |
87a51c978d8891d80b1f1eafadbd0e7654e04237 | viseth89/nbapython | /trial.py | 1,042 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 19:06:19 2016
@author: visethsen
"""
import matplotlib.pyplot as plt
# Importing matplotlib general way that it is used
x1 = [1,2,3]
y1 = [4,7,5]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x1, y1, label = "first line")
plt.plot(x2, y2, label = 'second line')
plt.xlabel('this is the x label')
plt.ylabel('this is the y label')
plt.title('this is how we put the title')
plt.legend()
plt.show()
a1 = [1,2,3]
b1 = [4,7,5]
a2 = [1,2,3]
b2 = [10,14,12]
plt.plot(a1, b1, label = "third line")
plt.plot(a2, b2, label = 'fourth line')
plt.xlabel('this is the x label')
plt.ylabel('this is the y label')
plt.title('this is how we put the title')
plt.legend()
plt.show()
'''
plt.bar([1,3,5,7,9], [5,2,7,8,2], label='example numero 1')
plt.bar([2,4,6,8,10], [4,6,8,4,10], label='part 2', color='g')
plt.legend
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('bar graph title\nAnother Line Whoa')
plt.show()
# Plotting x and y which would be the data
'''
| true |
bc330656519ec96a211e305cc5abd9099952d649 | LordEldak/Vampy-2017-CS | /CanChickinsFly.py | 1,586 | 4.1875 | 4 | answer = input ("Am I an object or a place? YES/NO:")
if answer == "YES":
answer = input("Am i bigger than a PC? YES/NO:")
if answer == "YES":
answer = input("Am I a building? YES/NO:")
if answer == "YES":
answer = input("Am I a Salon? YES/NO:")
if answer == "YES":
print("I am a salon")
else:
print("I am bowling ally")
else:
answer = input("Am I NY? YES/NO:")
if answer == "YES":
print("I am NY")
else:
print("I am an Umbrella")
else:
answer = input("Am I a consumable? YES/NO:")
if answer == "YES":
answer == input("Am I a Pizza? YES/NO:")
if answer == "YES":
print("I am a Pizza")
else:
print("I am soap")
else:
answer = input("Am I a hat? YES/NO:")
if answer == "YES":
print("I am a hat")
else:
print("I am a computer")
else:
answer = input("Am I human? YES/NO:")
if answer == "YES":
answer = input("Am I fictional? YES/NO:")
if answer == "YES":
answer = input("Am I Santa Clause? YES/NO:")
if answer == "YES":
print("I am Santa Clause")
else:
print("I am James Bond")
else:
answer = input("Am I Micheal Jackson? YES/NO:")
if answer == "YES":
print("I am Micheal Jackson")
else:
print("I am Brittany Spears")
else:
answer = input("Can I fly? YES/NO:")
if answer == "NO":
answer = input("Am I a rat? YES/NO?:")
if answer == "YES":
print("I am a rat")
else:
print("I am a frog")
else:
answer = input("Am I Dracula? YES/NO:")
if answer == "YES":
print("I am Dracula")
else:
print("I am a chicken")
| false |
4b93a00e1ca8e27e19d5c723af42b9b2604d61f4 | NUbivek/PythonBootcamp | /Module6/ex1.py | 1,175 | 4.28125 | 4 | # Exercise 1.
# Write your Binary Search function.
# Start at the middle of your dataset. If the number you are searching for is lower,
#stop searching the greater half of the dataset. Find the middle of the lower half
#and repeat.
# Similarly if it is greater, stop searching the smaller half and repeat
# the process on that half. By continuing to cut the dataset in half,
#eventually you get your index number.
# Number to search for - 3 alist = [1,2,3,4,5,6,7]
def binary_search (user_input,x):
# user_input_lefthalf = 0
# user_input_righthalf = 0
mid = round(len(user_input)//2)
#print (mid)
#print (user_input[mid-1])
while len(user_input) > 1:
if x == user_input[mid-1]:
value = x
print("The value is {}", x)
return x
elif x < user_input[mid-1]:
start_point = user_input[0]
end_point = user_input[mid-1]
value = len(range(user_input[start_point:end_point]))//2
print (value)
return value
elif x > user_input[mid-1]:
start_point = user_input[mid-1]
end_point = user_input[:]
value = len(range(user_input[start_point:end_point]))//2
print (value)
return value
binary_search([1,2,3,4,5,6,7],6)
| true |
09fdf09fb3393d7081c02d4fb9fbf3efb81e14b0 | NUbivek/PythonBootcamp | /Module1/ex6.py | 748 | 4.28125 | 4 | ##Exercise 6: Write Python program to construct the following pattern, using a nested for loop.
def triangle():
temp_var = ""
for num in range(5):
temp_var += "*"
print(temp_var)
for num in range(5,0,-1):
temp_var = "*"
print(num * "*")
triangle()
##(optimized code below)
def triangle(number):
for num in range (1, number+1):
print (num*"*")
for num in range (number-1,0,-1):
print (num*"*")
triangle(6)
####
def triangle(number,character):
character_str = str(character)
for num in range (1, number+1):
print (num*character_str)
for num in range (number-1,0,-1):
print (num*character_str)
triangle(6,"$")
| true |
075507eb146a94e556b9fe135191c904a4e479ed | 4320-Team-2/endDateValidator | /endDateValidator.py | 1,352 | 4.34375 | 4 | import datetime
class dateValidator:
#passing in the start date provided by user
def __init__(self, startDate):
self.startDate = startDate
def endDate(self):
#loop until user provides valid input
while True:
#try block to catch value errors
try:
endDate = input("Enter the end Date (YYYY-MM-DD): ")
#splitting input to use with datetime module
d1 = self.startDate.split(('-'))
d2 = endDate.split('-')
#creating datetime objects
start = datetime.datetime(int(d1[0]),int(d1[1]),int(d1[2]))
end = datetime.datetime(int(d2[0]),int(d2[1]),int(d2[2]))
#error handling for end date before start date
if start == end:
print("[ERROR] Start date cannot be the same as end date\n")
elif start > end:
print("[ERROR] Start date cannot be after end date\n")
else:
print("Valid date input")
return end.date()
break
except ValueError:
print("[ERROR] Invalid date provided.\n")
#Error checking and example use
#date = dateValidator("1999-06-29")
#endDate = date.endDate() | true |
c72f07976c3d40c88fbef5a39d3bdab8f0a5f202 | divyashree-dal/PythonExercises | /Exercise22.py | 673 | 4.625 | 5 | '''Question 54
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with the same name in the super class.'''
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self,length):
Shape.__init__(self)
self.length = length
def area(self):
return self.length * self.length
asquare = Square(int(raw_input()))
print asquare.area() | true |
8fd1d34b6a98d4f171c8b7bd138f892a3861800e | deepakmethalayil/PythonCrash | /list_study.py | 785 | 4.125 | 4 | members = ['uthay', 'prsanna', 'karthick']
members_master = members
print(members) # print the entire list
print(members[0]) # print list items one by one
print(members[1])
print(members[2])
msg = "Hello!"
print(f"{msg},{members[0].title()}")
print(f"{msg},{members[1].title()}")
print(f"{msg},{members[2].title()}")
# Adding an element to the list
members.append('ratheesh')
print(members)
# Define an empty list
Grade = []
# removing items using del statement
del members[0]
print(members)
# Removing an Item Using the pop() Method
members.pop()
print(members)
members1 = members.pop(0)
print(members1)
# we can remove the items by value by remove command
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
| true |
0c885c721e116d2ed482bf53bae8590df0db711e | gauvansantiago/Practicals | /Prac_02/exceptions_demo.py | 1,020 | 4.46875 | 4 | # Gauvan Santiago Prac_02 Task_04 exceptions_demo
try:
# asks to input numerator and denominator
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
# while loop will prevent ZeroDivisionError and ask for a valid denominator
while denominator == 0:
print(print("Cannot divide by zero!"))
denominator = int(input("Enter the denominator: "))
# calculates the fraction and changes it to a number
fraction = numerator / denominator
print(fraction)
# Valid numbers meaning whole numbers without decimal points
except ValueError:
print("Numerator and denominator must be valid numbers!")
print("Finished.")
# When will a ValueError occur?
# A ValueError will occur if you put in a number with a decimal as an input
# When will a ZeroDivisionError occur?
# ZeroDivisionError occurs when you input 0 in either denominator and numerator as well as on both
# Could you change the code to avoid the possibility of a ZeroDivisionError?
# Yes
| true |
a26da98cd7f927a76810f2b9f97a60e896cbd5ee | Anjalibhardwaj1/GuessingGame | /GuessingGame.py | 2,370 | 4.28125 | 4 | #December 30 2020
#Guessing Game
#This program will pick a random number from 1 to 100, and
#it will ask the user to guess the number.
from random import randint
#Welcome Message and Rules
print("\n---------------------- Guessing Game ------------------------------")
print("Welcome!")
print("In this game I will think of a number, and you will try to guess it!\n")
#Start Game
ready = input("Are you ready to play? (Y/N)")
#If 'y' then start game otherwise, prompt and exit.
if ready.lower() == 'y':
print("\nGenerating a random number...")
#Randomly chose a number from 1 to 100
random_num = randint(1, 100)
#Initialize user Guess List
guess_list = [0]
#While True this code will loop and prompt the user for guesses
while True:
#Prompt user for their guess and convert to integer
user_guess = int(input('Enter Your Guess! \n'))
#If the user's guess is out of bounds, ask the user again.
if user_guess < 1 or user_guess > 100:
print('Please Enter a Number Between 1 and 100. \n')
continue
#If the user's guess is correct then prompt user, tell them their amount of tries and break out of loop
if user_guess == random_num:
print('Correct! It took you {} tries!'.format(len(guess_list)))
print("Play again next time!")
exit()
break
#Add user's guesses to guess_list
guess_list.append(user_guess)
#If there exists 3 values in the list compare the current value to the previous value
if guess_list[-2]:
#if the current value is closer to the random number prompt "WAMER!"
if abs(random_num-user_guess) < abs(random_num-guess_list[-2]):
print('WARMER!\n')
#Otherwise, print "COLDER!"
else:
print('COLDER!\n')
#otherwise check if user's guess is within 10 digits of the random number
else:
if abs(random_num - user_guess) <= 10:
print("WARM!\n")
else:
print("COLD!\n")
else:
print("...Come back next time")
exit()
| true |
ed294c0d77434c644a4805c6f7a04b1789e1019d | nbrown273/du-python-fundamentals | /modules/module11_list_comprehensions/exercise11.py | 1,384 | 4.34375 | 4 | # List Comprehension Example
def getListPowN(x, n):
"""
Parmaeters: x -> int: x > 0
n -> int: n >= 0
Generate a list of integers, 1 to x, raised to a power n
Returns: list(int)
"""
return [i**n for i in range(1, x) if i % 2 == 0]
# Dictionary Comprehension Example
def getDictComprehension(keys, vals):
"""
Parameters: keys -> list(str)
vals -> tuple(int)
Generate a dictionary comprehension based on a list and tuple
Returns: dict
"""
return {key: val for key, val in zip(keys, vals)}
################################################################################
"""
TODO: Write a function that follows the criteria listed below
The purpose of this function is to generate a dictionary object whose
keys and values follow the criteria below:
* Function should take in a parameter "letters", where "letters" is a
list of strings of length 1
* Function should take in a parameter "lengths", where "lengths" is a
list of ints >= 0
* The length of "letters" and "lengths" have to be equal
* If the lengths of "letters" and "lengths" are not equal, return the
an error message
Example:
letters=["a", "b", "c", "d"]
lengths=[0, 1, 2, 3]
returns {"a0": "", "b1": "b", "c2": "cc", "d3": "ddd"}
""" | true |
2cad47a5a9905de6a6dfc562e71db4f8a6e66ac9 | manmodesanket/hackerrank | /problem_solving/string.py | 683 | 4.34375 | 4 | # You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
#
# For Example:
#
# Www.HackerRank.com → wWW.hACKERrANK.COM
# Pythonist 2 → pYTHONIST 2
# Input Format
#
# A single line containing a string .
#
# Constraints
#0<=len(s)<=1000
#
# Output Format
#
# Print the modified string .
#
# Sample Input 0
#
# HackerRank.com presents "Pythonist 2".
# Sample Output 0
#
# hACKERrANK.COM PRESENTS "pYTHONIST 2".
def swap_case(s):
a=""
for i in s:
if i.islower()==True:
a+=(i.upper())
else :
a+=(i.lower())
return a
s=input()
a=swap_case(s)
print(a) | true |
4d97da83215734d677dd6b7bc15c527b9e6ee262 | srs0447/Basics | /8-calculator.py | 817 | 4.15625 | 4 | # Basic calculator that do the basic calculations like addition, subtraction, multification etc
# declaring the global variables
print("This is the basic calculator")
print("\n********************************************\n")
print("$$$$$$^^^^^^********^^^^^^^$$$$$$$$$$")
number1 = float(input('Please Enter the first number \n'))
operator = str(input("Please select the operator \n"))
number2 = float(input("Please enter the second number \n"))
def add():
print(number1 + number2)
def sub():
print(number1 - number2)
def mult():
print(number1 * number2)
def devide():
print(number1 / number2)
if(operator == "+"):
add()
elif(operator == "-"):
sub()
elif(operator == "*"):
mult()
elif(operator == "/"):
devide()
else:
print("Wrong operator !. Please select the currect operator..") | true |
b7341f228d1fc848f24326a63a4659ed93ff2078 | DaniilAnichin/for_TA | /merge.py | 863 | 4.125 | 4 | #!usr/bin/python
# -*- coding: utf-8 -*-#
from math import log
def merge_sort(num_list):
half_len = len(num_list) / 2
if len(num_list) > 2:
return merge(merge_sort(num_list[:half_len]),
merge_sort(num_list[half_len:]))
elif len(num_list) == 2:
return merge(num_list[:1], num_list[1:])
else:
return num_list
def merge(list_a, list_b):
result_list = []
for i in range(len(list_a) + len(list_b)):
if len(list_a) == 0:
result_list.append(list_b.pop(0))
elif len(list_b) == 0:
result_list.append(list_a.pop(0))
elif list_a[0] < list_b[0]:
result_list.append(list_a.pop(0))
else:
result_list.append(list_b.pop(0))
return result_list
if __name__ == '__main__':
print merge_sort([1, 5, 6, 2, 7, 1, 8, 5, 3])
| false |
e3ca668d88674d2934ac7994f959d526b392cc59 | dimasiklrnd/python | /highlighting numbers, if, for, while/The number of even elements.py | 610 | 4.28125 | 4 | '''Посчитать количество четных элементов в массиве целых чисел, заканчивающихся нулём. Сам ноль учитывать не надо.
Формат входных данных
Массив чисел, заканчивающийся нулём (каждое число с новой строки, ноль не входит в массив)
Формат выходных данных
Одно число — результат.'''
n = int(input())
x = 0
while n != 0:
if n % 2 == 0:
x += 1
n = int(input())
print(x)
| false |
d0ad5dd7e1e3fcb6555e8573b7802d23dc345e9f | si7eka/XiaoXiang-python | /案例7--模拟之掷骰子/模拟掷骰子1.0.py | 2,571 | 4.15625 | 4 | """
案例描述:
通过计算机程序模拟投掷骰子,并显示各种点数的出现次数及频率
比如,投掷2个骰子50次,出现点数为7的次数是8,频率是0.16
案例分析:
如何通过Python模拟随机事件?或者生成随机数?
random模块
遍历列表时,如何同时获取每个元素的索引号及其元素值?
enumerate() 函数
知识点:
random模块
用于生成随机数
常用函数
函数 含义
random() 生成一个[0, 1.0)之间的随机浮点数
uniform(a, b) 生成一个a到b之间的随机腐恶点数
randint(a, b) 生成一个a到b之间的随机整数
choice(<list>) 从列表中随机返回一个元素
shuffle(<list>) 将列表中元素随机打乱
sample(<list>, k) 从指定列表中随机获取k个元素
更多random模块的方法请参考
https://docs.python.org/3/library/random.html
enumerate()
enumerate()函数用于将可遍历的组合转换为一个索引序列
一般用于for循环中,同时列出元素和元素的索引号
例子:
l = ['a', 'b', 'c']
for x in l:
print(x)
输出:
a
b
c
l = ['a', 'b', 'c']
for i, x in enumerate(l):
print('{}--{}'.format(i, x))
输出:
0--a
1--b
2--c
作者:si7eklz
功能:模拟掷骰子
版本:1.0
日期:20190120
"""
import random
def roll_dice():
"""
模拟掷骰子
"""
roll = random.randint(1, 6) # 生成随机数1-6
return roll # 输出roll
def main():
"""
主函数
"""
# 初始化次数
total_times = 1000
# 初始化列表 [0, 0, 0, 0, 0, 0],用于记录每次掷骰子的数
result_list = [0] * 6
# 循环total_times次
for i in range(total_times):
# roll 接收roll_dice函数的输出值
roll = roll_dice()
for j in range(1, 7): # 遍历是1-6的数字
if roll == j: # 如果 roll的数字==j
result_list[j - 1] += 1 # 在列表result_list对应的位置+1 来记录不通骰子每次得数的次数
for i, result in enumerate(result_list): # i索引号 result元素值
print('点数{}的次数:{},频率:{}'.format(i + 1, result, result / total_times))
if __name__ == '__main__':
main()
| false |
bbbac97db52c79674684601e12be34092c6d3f8f | si7eka/XiaoXiang-python | /案例2--分形树的绘画/五角星2.py | 1,369 | 4.3125 | 4 | """
作者:李征
功能:五角星绘图
版本:2.0
新增:循环操作
turtle库说明:
形状绘制函数
turtle.forward(distance)
画笔向前移动distance距离
turtle.backward(distance)
笔画向后移动distance距离
turtle.right(degree)
绘制方向向右旋转degree度
turtle.exitonclick()
点击关闭图形窗口
(左)
|
(后)--中心点--(前)
|
(右)
更多查询 https://docs.python.org/3/library/turtle.html#module-turtle
"""
import turtle
def huizhi_wujiaoxing(size):
# 绘制五角星
count = 1 # 计数器
while count <= 5: # 计数器小于等于5的时候执行循环
turtle.forward(size) # 绘图向前size的长度
turtle.right(144) # 右转144度
count += 1 # 计数器+1 相当于 count = count + 1
def main():
"""
主函数
"""
size = 50 # 星星边长初始尺寸
while size <= 170: # 边长小于等于200的执行循环
# 调用函数
huizhi_wujiaoxing(size)
size += 30 # 执行完绘制五星之后边长+30
turtle.exitonclick() # 点击关闭图形
if __name__ == "__main__":
main()
| false |
ffb5acfef7395967bfc3a8d62fb981768ef6bae4 | anish-lakkapragada/libmaths | /libmaths/trig.py | 2,884 | 4.28125 | 4 | #Developer : Vinay Venkatesh
#Date : 2/20/2021
import matplotlib.pyplot as plt
import numpy as np
def trigsin(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.sin(b * x)
yint = z * np.sin(b * 0)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}sin({b}x)')
plt.title('Sine Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
def trigcos(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.cos(b * x)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}cos({b}x)')
plt.title('Cosine Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
def trigtan(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.tan(b * x)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}tan({b}x)')
plt.title('Tangent Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
| true |
9d59edf273a76e409ca5ba7a6898c50d130d43c7 | khanmaster/python_modules | /exception_handling.py | 1,246 | 4.1875 | 4 | # We will have a look at the practical use cases and implementation of try, except, raise and finally
we will create a variable to store a file data using open()
Iteration 1
try: # let's use try block for a 1 line of code where we know this will throw an error
file = open("orders.text")
except:
print(" Panic Alert!!!! ")
# Iteration 2
try:
file = open("orders.text")
except FileNotFoundError as errmsg: # creating an alais for FileNotFound Error in except block
print("Alert something sent wrong" + str(errmsg))
# if we still wanted them to see the actual exception together with our customised message
raise # raise will send back the actual exception
finally: # finally will execute regardless of the above conditions
print(" Hope you had a good Customer experience, please visit again")
# import json
#
# car_data = {"name": "tesla", "engine": "electric"} # dic
#
# print(type(car_data))
#
#
# car_data_json_string = json.dumps(car_data) #
# print(type(car_data_json_string))
#
# with open("new_json_file.json", "w") as jsonfile:
# json.dump(car_data, jsonfile)
#
# with open("new_json_file.json") as jsonfile:
# car = json.load(jsonfile)
# print(car['name'])
# print(car['engine'])
| true |
a89ea893b8f11bf22fc437b1b43ef3cc1e7a19a2 | themoat/Codeforces-problems | /Advanced_Recursion.py | 902 | 4.125 | 4 | a=[[1,1,0],[1,2,1],[1,0,2]]
def floodfill(a,r,c,tofill,prevfill): # yahaan pe, r and c denote the row and column we are at, or in paint we will click at.
#Let's mention out how many rows and columns are there
rows = len(a)
col = len(a[0])
#Since we are applyng recursion over here, so let's start with our base condition.
if rows<0 or r>rows or c<0 or c>col:
return
# We check if the new cell in which we are, that it is the cell, jisko
#hum update karnaa chahte hain, i.e see if [r][c]==prevfill, agar nahi hai toh return kar jaao
# kyuki uss cell ko mujhe chhednaa hiii nahi hai.
if a[r][c]!=prevfill:
return
#now we fill our color
a[r][c]=tofill
floodfill(a,r-1,c,tofill,prevfill)
floodfill(a,r,c-1,tofill,prevfill)
floodfill(a,r+1,c,tofill,prevfill)
floodfill(a,r,c+1,tofill,prevfill)
floodfill(a,1,1,8,2)
print(a)
| false |
60e0fa3af1eca5fbd52590f7622545097db1a8be | jxhangithub/lintcode | /Tree/480.Binary Tree Paths/Solution.py | 1,853 | 4.15625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
self.result = []
if not root:
return self.result
self.dfs(root, "")
return self.result
def dfs(self, root, path):
# dfs has reached the leaf node, add path to result
if root.left is None and root.right is None:
path = path + str(root.val)
self.result.append(path)
return
# turn left
if root.left:
self.dfs(root.left, path + str(root.val) + "->")
# turn right
if root.right:
self.dfs(root.right, path + str(root.val) + "->")
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Traverse
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
result = []
if not root:
return result
self._traverse(root, result, [str(root.val)])
return result
def _traverse(self, root, result, path):
if root.left is None and root.right is None:
result.append("->".join(path))
return
if root.left:
path.append(str(root.left.val))
self._traverse(root.left, result, path)
path.pop()
if root.right:
path.append(str(root.right.val))
self._traverse(root.right, result, path)
path.pop()
| true |
b6c43d8e05c2c06879abe86a53a1d919a75b5fa9 | KellyOllos/STRUCTURES | /STRUCTURE.py | 416 | 4.1875 | 4 | #BRIANNE KELLY R. OLLOS
#STRUCTURES
letters = ['s','l','l','o','s','s','o','l',
's','o','o','l','o','l','s','s',
'o','s','s','o','l','l','l',
's','l','s','l','l','o','o','s',
'l','l','s','o','s','s','o']
from collections import Counter
letters_counts = Counter(letters)
repeat = letters_counts.most_common(3)
print ("letters repeated")
print(repeat)
| false |
1708d66404362fb9a0e18008e6e500453235a49e | chandnipatel881/201 | /chap3.py | 407 | 4.25 | 4 | print "This program illustrates average of numbers"
# total_num = input ("How many numbers you want to average : ")
# sum = 0.0
#
# for i in xrange(total_num):
# sum = sum + input("Enter: " )
# average = sum/total_num
# print average
avg = 0.0
count = 0
while True:
total = avg * count
num = input("Enter : ")
count = count + 1
total = total + num
avg = total/count
print avg
| true |
d4b2cdb089e531181f30b6130d915878bd5744ef | Aiswarya333/Python_programs | /const5.py | 1,595 | 4.1875 | 4 | '''CELL PHONE BILL - A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs
$0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill
(including the 911 charge) is subject to 5 percent sales tax.
Write a program that reads the number of minutes and text messages used in a month from the user. Display
the base charge, additional minutes charge (if any), additional text message charge (if any), the 911 fee, tax and total bill amount. Only display the additional
minute and text message charges if the user incurred costs in these categories. Ensure that all of the charges are displayed using 2 decimal places.'''
min=int(input('ENTER THE NUMBER OF MINUTES :'))
msg=int(input('ENTER THE NUMBER OF MESSAGES :'))
BASE_COST=15.00
MSG_COST=0.15
CALL_COST=0.25
accost=0.0
amcost=0.0
if min>50:
accost=(min-50)*CALL_COST
if msg>50:
amcost=(msg-50)*MSG_COST
center=amcost+accost+BASE_COST+0.44
tax=(BASE_COST+amcost+accost+center)*5/100
total=tax+BASE_COST+amcost+accost+center
print('''
BASE CHARGE : %.2f
ADDITIONAL MINUTES CHARGE : %.2f
ADDITIONAL TEXT CHARGE : %.2f
911 FEE : %.2f
TAX : %.2f
------------------------------------------
TOTAL BILL AMOUNT : %.2f
''' %(BASE_COST,accost,amcost,center,tax,total))
| true |
38f3243733f0a36e5c2ca109f986f9fdc94cd9f0 | ed4m4s/learn_python_the_hard_way | /Exercise18.py | 569 | 4.1875 | 4 | #!/usr/bin/python
# Exercise on Names, Variables, Code, Functions
# this one is like the scripts we did with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Take out the *args as you do not need it
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Takes one argument only
def print_one(arg1):
print "arg1: %r" % arg1
# No arguments at all.
def print_none():
print "I got no arguments"
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
| true |
81190be06991bf9d7d942ccc7962d7a0b1881c61 | deepak7514/Venturesity-Need_For_Hack | /need25.py | 1,225 | 4.1875 | 4 | import datetime
while True:
date=raw_input("Enter date in format dd-mm-yyyy: ")
if not date:
print 'Please provide input'
continue
date=date.strip().split('-')
if len(date)!=3:
print 'Day, Month and Year should be separated by \'-\'.'
continue
d,m,y=date
if y.isdigit() and len(y)==4:
y=int(y)
else:
print 'Year should be 4-digit.'
continue
if m.isdigit() and 1<=int(m)<=12:
m=int(m)
else:
print 'Month should be between 1 and 12.'
continue
days = [31,28,31,30,31,30,31,31,30,31,30,31]
# Check for leap year
if (y%4 ==0 and y%100 !=0) or (y%400 ==0):
days[1] = 29
if d.isdigit() and 1<=int(d)<=days[m-1]:
d=int(d)
else:
print 'Day should be between 1 and %d'%days[m-1]
continue
break
Month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
WeekDay = ['Monday', 'Tuesday', 'Wednesday', 'Thhursday', 'Friday', 'Saturday', 'Sunday']
print 'Day Of the year:',WeekDay[datetime.date(y,m,d).weekday()]
print 'Date: %s,%d %s %d'%(WeekDay[datetime.date(y,m,d).weekday()],d,Month[m-1],y)
| false |
1f024b3de44ee95d07ab6b44a2c3fcf22079ba09 | pioziela/programming-learning | /Hacker_Rank_Exceptions.py | 965 | 4.25 | 4 | import sys
def divide_exceptions():
"""
divide_exceptions function trying to divide two values.
The user provides data in the following format:
- in the first line the number of divisions to be carried out,
- in the following lines, the user provides two values to divide, the values should be separated by a space.
The function returns a division result or a corresponding error.
"""
line_number = 0
number_of_lines = int(sys.stdin.readline())
while line_number < number_of_lines:
numbers_to_divide = list(map(str, sys.stdin.readline().rstrip().split()))
try:
print(int(numbers_to_divide[0]) / int(numbers_to_divide[1]))
except ZeroDivisionError:
print("Error Code: integer division or modulo by zero")
except ValueError as invalid_literal:
error = f"Error Code: {invalid_literal}"
print(error)
line_number += 1
divide_exceptions()
| true |
a1b191446e960f38e7e6621275d85ac7629d0368 | geetha10/GeeksForGeeks | /basic/factorial.py | 317 | 4.25 | 4 | def factorial(num):
result = 1
for x in range(1, num+1):
result = result*x
return result
num = input("Enter a number for finding factorial")
if num.isdigit():
num = int(num)
fact = factorial(num)
print(f"Factorial of {num} is {fact}")
else:
print("Please enter a valid Integer")
| true |
cc8d3b1b5d12299494d897fc24e6173b0a407aca | ricamos/study_code | /Programming _Foundations_with_Python/aula3_Use_classes_Draw_Turtles/a3c5_mindstorms_v2.py | 1,009 | 4.625 | 5 | """
Versão otimizada: Uso de funções em codigos repetido.
Estudo do uso de classes. No caso a classe turtle.
Usamos varias instancias da classe turtle. instancia como brad e angie.
Podemos pensar em uma classe como uma planta de um edificio. E em seus objetos (Edificios criado a partir da planta)
como exemplos ou instancias dessa planta.
"""
import turtle #Usando a classe turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("red")
#Create the turtle brad - Draws a square
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(5)
draw_square(brad)
for i in range(1,37):
draw_square(brad)
brad.right(10)
#Create the turtle Angie - Draw a circle
#angie = turtle.Turtle()
# angie.shape("arrow")
# angie.color("blue")
# angie.circle(100)
window.exitonclick()
draw_art()
| false |
721b2651ffb8c02d09a2130810f3baf3294c48ec | jayantpranjal0/ITW1-Lab | /python-assignments/3/4.py | 219 | 4.375 | 4 | '''
Python program to read last n lines of a file.
'''
with open("test.txt", "r") as f:
n = int(input("Enter number of lines from last to read: "))
for i in f.readlines()[-n:]:
print(i, end = "") | true |
4bc1c71828f44dda49523303fa15adc3ba9ed9d3 | jayantpranjal0/ITW1-Lab | /python-assignments/1/14.py | 213 | 4.21875 | 4 | '''
Python program to get the number of occurrences of a specified element in an array.
'''
l = input("Enter the array: ").split()
e = input("Enter the element: ")
print("No of occurence: "+str(l.count(e))) | true |
eecf3b4c3635d6de005320cc22de378334d64723 | jayantpranjal0/ITW1-Lab | /python-assignments/2/15.py | 342 | 4.1875 | 4 | '''
Python program to sort a list of elements using the selection sort algorithm
'''
a = list(map(int, input("Enter the list: ").split()))
n = len(a)
for i in range(0,n-1):
m = a[i]
pos = i
for j in range(i+1,n):
if m > a[j]:
m = a[j]
pos = j
a[i], a[pos] = a[pos], a[i]
print(a) | false |
01fe18819e29ae6806c6392f384ce6cbc39c81b7 | KarnolPL/python-unittest | /06_functions/04_tax/tax.py | 511 | 4.25 | 4 | def calc_tax(amount, tax_rate):
"""The function returns the amount of income tax"""
if not isinstance(amount, (int, float)):
raise TypeError('The amount value must be int or float type')
if not amount >= 0:
raise ValueError('The amount value must be positive.')
if not isinstance(tax_rate, float):
raise TypeError('The tax_rate must be float')
if not 0 < tax_rate < 1:
raise ValueError('The tax_rate must be between 0 and 1')
return amount * tax_rate
| true |
5588dad39ce8b2d00d77f4497371df468016e4fe | Parzha/Assingment3 | /assi3project6.py | 583 | 4.125 | 4 |
flag=True
number_list = []
while flag:
user_input=int(input("Please enter the numbers you want? "))
number_list.append(user_input)
user_input_2=input("If you wanna continue type yes or 1 if you want to stop type anything= ").lower()
if user_input_2=="1" or user_input_2=="yes":
flag=True
else:
print("created list is ",number_list)
flag=False
sorted_list = sorted(number_list)
if sorted_list == number_list:
print("This list array is sorted ",number_list)
else:
print("This array is not sorted ",number_list) | true |
e68ce6ed23b536195d51f4d71f3e91521f133c68 | AaryanGoel/Homework-1 | /main.py | 1,684 | 4.25 | 4 | # author: Aaryan Goel apg5720@psu.edu
letter = input("Enter your course 1 letter grade: ")
credit1 = float(input("Enter your course 1 credit: "))
GradeP = 0
if letter == "A":
GradeP = 4.0
elif letter == "A-":
GradeP = 3.67
elif letter == "B+":
GradeP = 3.33
elif letter == "B":
GradeP = 3.00
elif letter == "B-":
GradeP = 2.67
elif letter == "C+":
GradeP = 2.33
elif letter == "C":
GradeP = 2.0
elif letter == "D":
GradeP = 1.0
elif letter == "F":
GradeP = 0
GPA1 = float(GradeP)
print(f"Grade point for course 1 is: {GPA1}")
# 2
letter = input("Enter your course 2 letter grade: ")
credit2 = float(input("Enter your course 2 credit: "))
GradeP = 0
if letter == "A":
GradeP = 4.0
elif letter == "A-":
GradeP = 3.67
elif letter == "B+":
GradeP = 3.33
elif letter == "B":
GradeP = 3.00
elif letter == "B-":
GradeP = 2.67
elif letter == "C+":
GradeP = 2.33
elif letter == "C":
GradeP = 2.0
elif letter == "D":
GradeP = 1.0
elif letter == "F":
GradeP = 0
GPA2 = float(GradeP)
print(f"Grade point for course 2 is: {GPA2}")
#3
letter = input("Enter your course 3 letter grade: ")
credit3 = float(input("Enter your course 3 credit: "))
GradeP = 0
if letter == "A":
GradeP = 4.0
elif letter == "A-":
GradeP = 3.67
elif letter == "B+":
GradeP = 3.33
elif letter == "B":
GradeP = 3.00
elif letter == "B-":
GradeP = 2.67
elif letter == "C+":
GradeP = 2.33
elif letter == "C":
GradeP = 2.0
elif letter == "D":
GradeP = 1.0
elif letter == "F":
GradeP = 0
GPA3 = float(GradeP)
print(f"Grade point for course 3 is: {GPA3}")
GPAt = ((GPA1 * credit1) + (GPA2 * credit2) + (GPA3 * credit3)) / (credit1 + credit2 + credit3)
print(f"Your GPA is: {GPAt}")
| false |
e42748ed030e92c694657695e48fdc29a3dafed8 | ConnorHoughton97/selections | /Water_Temp.py | 337 | 4.34375 | 4 | #Connor Houghton
#30/09/14
#telling the user whether ater is frozen, boiling or neither
water_temp = int(input("please enter the temperature of the water: "))
if water_temp >= 100:
print ("The water is boiling.")
elif water_temp <= 0:
print("The water is frozen.")
else:
print("The water is neither boiling or frozen.")
| true |
a9dd7f6698194127322ccb3430435f8bb70ce01f | WhiteLie1/PycharmProjects | /alex_python/day6/继承实例.py | 1,774 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/8 19:58
# @Author : chenxin
# @Site :
# @File : 继承实例.py
# @Software: PyCharm
class SchoolMember(object):
members = 0; #初始学校人数为0
def __init__(self,name,age):
self.name = name
self.age = age
def tell(self):
pass
def enroll(self):
#注册
SchoolMember.members +=1;
print("\033[32;1mnew member [%s] is enrolled,now there are[%s] members.\033[0m"%(self.name,SchoolMember.members))
def __del__(self):
#析构方法
print("\033[32;1mmember[%s] is dead!\033[0m"%self.name)
class Teacher(SchoolMember):
def __init__(self,name,age,course,salary):
super(Teacher,self).__init__(name,age)
self.course = course
self.salary = salary
self.enroll()
def teaching(self):
#讲课方法
print("Teacher[%s] is teaching [%s] for class [%s]"%(self.name,self.course,'S12'))
def tell(self):
#自我介绍方法
msg = '''Hi, my name is [%s],works for [%s] as a [%s] teacher !'''%(self.name,'Oldboy',self.course)
print(msg)
class Student(SchoolMember):
def __init__(self,name,age,grade,sid):
super(Student,self).__init__(name,age)
self.grade = grade
self.sid = sid
self.enroll()
def tell(self):
#自我介绍
msg = '''Hi ,my name is [%s],I am studing [%s] in [%s]!'''%(self.name,self.grade,'Oldboy')
print(msg)
if __name__ == '__main__':
t1 = Teacher('Alex',22,'python',20000)
t2 = Teacher('Toney',29,'Linux',3000)
s1 = Student('Qinghua',24,'python s12',1483)
a2 = Student('sanjiang',26,'python s12',1484)
t1.teaching()
t2.teaching()
t1.tell()
| false |
ed1ad13442cde6d47dba6ea1ac955ad157929c16 | shreethi29/Python-for-Everybody-Specialization | /assignment6.py | 375 | 4.1875 | 4 | largest = -1
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n=float(num)
except:
print("Invalid input")
if smallest is None:
smallest=n
elif n>largest:
largest=n
elif n<smallest:
smallest=n
print("Maximum is",int(largest))
print("Minimum is",int(smallest)) | false |
fbf00374688203f1feacec0636e2f1d385439be0 | zhanshi06/DataStructure | /Project_1/Problem_2.py | 1,375 | 4.375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
if len(suffix) == 0:
return []
files_list = list()
if os.path.exists(path):
dir_to_walk = [path]
while dir_to_walk:
cur_folder = dir_to_walk.pop() + '/' # get the first folder
sub_items = os.listdir(cur_folder)
for item in sub_items:
item = cur_folder + item
if os.path.isdir(item):
dir_to_walk.append(item)
elif str(item).endswith(suffix):
files_list.append(item)
return files_list
# tets
### Test Case one ###
print(find_files('.h', 'testdir'))
'''
output: ['testdir/t1.h', 'testdir/subdir1/a.h', 'testdir/subdir5/a.h', 'testdir/subdir3/subsubdir1/b.h']
'''
### Test Case two ###
print(find_files('.c', ''))
'''
output: []
'''
### Test Case three ###
print(find_files('.c', 'testdir/subdir1'))
'''
output: ['testdir/subdir1/a.c']
'''
| true |
8456392830bb561c6f4156b270e445f10b0e67c4 | 0xphk/python_tutorial1 | /07_if_conditions_1.py | 241 | 4.28125 | 4 | age = int(input("age: "))
if age == 18:
print("age is 18!")
elif age < 21 > 18:
print("age over 18 but not yet 21!")
elif age == 21:
print("age is 21!")
elif age >= 21:
print("age over 21!")
else:
print("age under 18!")
| false |
32e95aacf766b380faaa2b8dc64d13b7bb062f24 | fffelix-jan/Python-Tips | /3a-map-those-ints.py | 239 | 4.15625 | 4 | print("Enter space-separated integers:")
my_ints = list(map(int, input().split())) # collect the input, split it into a list of strings, and then turn all the strings into ints
print("I turned it into a list of integers!")
print(my_ints) | true |
0ff46aa541476ec73d8dbe2de099a11048d0f560 | SS1908/30_days_of_python | /Day 16/properties_of_match.py | 342 | 4.21875 | 4 | """"
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function.
.group() returns the part of the string where there was a match.
"""
import re
str = "The train in Spain"
x = re.search("train",str)
print(x.span())
print(x.string)
print(x.group()) | true |
d62363750fa06239f769f4490b7c8dea0eeb06eb | SS1908/30_days_of_python | /Day 12/LIst_comprehension.py | 466 | 4.34375 | 4 | """
List Comprehension is defined as an elegant way to define, create a list in Python.
It consists of brackets that contains an expression followed by for clause.
SIGNATURE:
[ expression 'for' item 'in' list 'if' condition]
"""
letters = []
for letter in 'Python':
letters.append(letter)
print(letters)
print()
#You can also do using list comprehension.
letters = [letter for letter in 'Python']
print(letters)
| true |
c07614f370a9f5b625593569cf89f2e98f15e01a | SS1908/30_days_of_python | /Day 17/type_of_variable_in_class.py | 940 | 4.34375 | 4 | """
we have a two type of variable in class :- 1) instance variable
2)class variable
instance variable is changes object to object.
class variable is same for all the instance/object of the class.
"""
class car:
#this is a class variable
#class variable define outside the __init__ method.
wheels = 4
#this is a instance variable
def __init__(self):
self.comp = "BMW"
self.mile = 10
c1 = car()
c2 = car()
# you can access class variable using object_name or class_name.
print(c1.comp,c1.mile,c1.wheels)
print(c2.comp,c2.mile,car.wheels)
print()
#you can change the value of an instance variable.
c1.mile = 8
#we can also change the value of class variable.
car.wheels = 5
print("After changing value of instance and class variable")
print(c1.comp,c1.mile,car.wheels)
print(c2.comp,c2.mile,c2.wheels) | true |
9d6e28084ff70545db5ed473b6ca361806566481 | SS1908/30_days_of_python | /Day 6/Comparisons_of_set.py | 406 | 4.25 | 4 | # <, >, <=, >= , == operators
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
# Days1 is the superset of Days2 hence it will print true.
print(Days1 > Days2)
# prints false since Days1 is not the subset of Days2
print(Days1 < Days2)
# prints false since Days2 and Days3 are not equivalent
print(Days2 == Days3) | true |
6a1f01bccda41e9216fc389162eaa758f241ac7d | SS1908/30_days_of_python | /Week 1/Day 1/Logical_operator.py | 761 | 4.5625 | 5 | #Logical operators are use to combine conditional statements.
# Operator Description
# and Returns True if both statements are true
# or Returns True if one of the statements is true
# not Reverse the result, returns False if the result is true
print("and operator")
x=6
print(x)
if x>0 and x<10:
print("number is between 0 to 10")
else:
print("numer is not is between 0 to 10")
print()
print(" or opreator")
x=11
if x>0 or x<10:
print("one or both conditons are true")
else:
print("both the conditions are false")
print()
print("not operator")
x = True
print("before use of not operator x is",x)
print("after using not operator x is become",not x)
| true |
34133a627a028c0b89086bd79ab2928cdd85aa36 | leoweller7139/111-Lab-1 | /calc.py | 1,299 | 4.15625 | 4 | # Method on the top
def seperator():
print(30 * '-')
def menu():
print('\n') #\n is like pressing enter
seperator()
print(" Welcome to PyCalc")
seperator()
print('[1] - Add')
print('[2] - Subtract')
print('[3] - Multiply')
print('[4] - Divide')
print('[x] - Exit')
# instructions on the bottom
opc = ''
while(opc != 'x'):
menu() # Display Menu
# Select an option
opc = input('Select an option: ')
if(opc == 'x'):
break # Finish with the loop
num1 = float(input('First Number: '))
num2 = float(input('Second Number: '))
if(opc == '1'):
res = num1 + num2
print('Result: ' + str(res))
if(opc == '2'):
res = num1 - num2
print('Result: ' + str(res))
if(opc == '3'):
res = num1 * num2
print('Result: ' + str(res))
elif(opc == '4'):
if(num1 == 0) or (num2 == 0): # After the if is the condition of the loop
print("Can not put zero when dividing")
# elif also requires a condition COMMENTS EFFECT IF LOOPS
else: #Else do not have a condition
res = num1 / num2
print('Result: ' + str(res))
input('Press Enter to continue...')
print('Thank you!!') | true |
684a6f6049359c0f77b8d6e13e7780570a71f845 | gabe01feng/trinket | /Python Quiz/dayAndWeekOfYear.py | 959 | 4.1875 | 4 | number = int(input("Pick a number from 1-365. "))
week = ((number + 4) // 7) + 1
day = (number + 3) % 7
ending = ''
if day % 10 == 1 and day != 11:
ending = 'st'
elif day % 10 == 2 and day != 12:
ending = 'nd'
elif day % 10 == 3 and day != 13:
ending = 'rd'
else:
ending = 'th'
if week % 10 == 1 and week != 11:
print("That day on the year 2019 was during the " + str(week) + "st week of the year and " + str(day) + ending + " day of the week.")
elif week % 10 == 2 and week != 12:
print("That day on the year 2019 was during the " + str(week) + "nd week of the year and " + str(day) + ending + " day of the week.")
elif week % 10 == 3 and week != 13:
print("That day on the year 2019 was during the " + str(week) + "rd week of the year and " + str(day) + ending + " day of the week.")
else:
print("That day on the year 2019 was during the " + str(week) + "th week of the year and " + str(day) + ending + " day of the week.") | false |
c3b4e2f580b13b04739c2b47b7dd47def850947e | gabe01feng/trinket | /Python Quiz/poolVolume.py | 1,108 | 4.1875 | 4 | import math
name = input("What is your name? ")
pool = input("What shape is your pool, " + name + "? (Use RP for rectangular prism, C for cube, or CY for a cylindrical pool) ")
if pool == "RP":
length = float(input("What is the length of the pool in feet? "))
width = float(input("What is the width of the pool in feet? "))
depth = float(input("What is the depth of the pool in feet? "))
volume = length * depth * width * 7.5
print("The volume of your pool, " + name + ", is " + str(volume) + " gallons.")
elif pool == "C":
length = float(input("What is the side length of the pool? "))
volume = (length ** 3) * 7.5
print("The volume of your pool, " + name + ", is " + str(volume) + " gallons.")
elif pool == "CY":
radius = float(input("What is the radius of the pool? "))
depth = float(input("What is the depth of the pool in feet? "))
volume = (((((math.pi * (radius ** 2)) * depth * 7.5) * 100) // 1) / 100)
print("The volume of your pool, " + name + ", is ~" + str(volume) + " gallons.")
else:
print(name + ", you didn't give me a valid pool shape.") | true |
29b59615adf2069988a4e84989840118886faf05 | TushinIE/cource-work | /Курсовая работа по программированию/31 Задача (2 часть курсовой)/example_29.py | 1,119 | 4.1875 | 4 | #имя проекта: numpy-example
#номер версии: 1.0
#имя файла: example_29.py
#автор и его учебная группа: И.Тушин, ЭУ-142
#дата создания: 20.05.2019
# дата последней модификации: 20.05.2019
#связанные файлы: пакеты numpy, matplotlib
# описание: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со
# случайными элементами. Добавить к матрице столбец чисел и вставить его
# под номером K.
#версия Python: 3.6
import numpy as np
import random
N= random.randint (1,10)
M= random.randint (1,10)
K=1
print(N,M)
matrix = np.random.randint(low=-9, high=10, size=(N, M))
print("Матрица:\r\n{}".format(matrix))
col = np.random.randint(low=-9, high=10, size=N)
print("Столбец для вставки: {}".format(col))
matrix = np.insert(matrix, K, col, axis=1)
print("Полученная матрица:\r\n {}".format(matrix)) | false |
726edd78dab141ca239759642d86a4312b7c92af | TushinIE/cource-work | /Курсовая работа по программированию/31 Задача (2 часть курсовой)/example_17.py | 1,110 | 4.28125 | 4 | #имя проекта: numpy-example
#номер версии: 1.0
#имя файла: example_17.py
#автор и его учебная группа: И.Тушин, ЭУ-142
#дата создания: 11.05.2019
# дата последней модификации: 11.05.2019
#связанные файлы: пакеты numpy, matplotlib
# описание: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со
# случайными элементами. Добавить к матрице строку и вставить ее под
# номером L.
#версия Python: 3.6
import numpy as np
import random
N = np.random.randint(2,10)
M = np.random.randint(2,10)
L = 1
print(N,M)
matrix = np.random.randint(low=-9, high=10, size=(N, M))
print("Матрица:\r\n{}".format(matrix))
row = np.random.randint(low=-9, high=10, size=M)
print("Строка для вставки: {}".format(row))
matrix = np.insert(matrix, L, row, axis=0)
print("Полученная матрица:\r\n {}".format(matrix)) | false |
d68f4b523b209f3a42cea58cafd8b153eeba6ba2 | Mukosame/learn_python_the_hard_way | /ex25.py | 1,380 | 4.4375 | 4 | def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
stuff = "A quick brown fox jumps over a lazy dog"
words = break_words(stuff)
print (words)
sorted_words = sort_words(words)
print (sorted_words)
print_first_word(words)
print (words)
print_last_word(words)
print (words)
sentence = "Ich habe eine kleine Katze."
sorted_sentence = sort_sentence(sentence)
print (sorted_sentence)
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.