blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
75a6883fb38db72e5775e46f6e94e49a3c4a9978
|
dimitardanailov/google-python-class
|
/python-dict-file.py
| 1,842
| 4.53125
| 5
|
# https://developers.google.com/edu/python/dict-files#dict-hash-table
## Can build up a dict by starting with the empty dict {}
## and storing key / value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
# Simple lookup, returns 'alpha'
print dict['a'] ## alpha
# Put new key / value into dict
dict['a'] = 6
print dict ## {'a': 6, 'o': 'omega', 'g': 'gamma'}
print 'a' in dict ## True
if 'z' in dict: print dict['z'] ## Avoid KeyError
## By default, iterating over a dict iterates over its keys
## Note that the keys are in a random order
for key in dict: print key ## prints a g o
## Exactly the same as above
for key in dict.keys(): print key
## Get the .keys list:
print dict.keys() ## ['a', 'o', 'g']
## Common case --loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]
## .items() is the dict expressed as (key, value) tuples
print dict.items() ## [('a', 6), ('o', 'omega'), ('g', 'gamma')]
## This loops syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print k, ' > ', v
## a > 6
## o > omega
## g > gamma
## Dic formatting
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
# %d for int, %s for string
s = 'I want %(count)d copies of %(word)s' % hash
print s # I want 42 copies of garfield
## Del
var = 6
del var # var no more!
list = ['a', 'b', 'c', 'd']
del list[0] ## Delete first element
del list[-2:] ## Delete last two elements
print list ## ['b']
dict = { 'a': 1, 'b': 2, 'c': 3}
del dict['b'] ## Delete 'b' entry
print dict ## {'a': 1, 'c': 3}
| true
|
c7668e86b91ed2fbcaa51d0d4811ae448d0f2a14
|
RobDBennett/DS-Unit-3-Sprint-1-Software-Engineering
|
/module4-software-testing-documentation-and-licensing/arithmetic.py
| 1,941
| 4.21875
| 4
|
#!/usr/bin/env python
# Create a class SimpleOperations which takes two arguements:
# 1. 'a' (an integer)
# 2. 'b' (an integer)
# Create methods for (a, b) which will:
# 1. Add
# 2. Subtract
# 3. Multiply
# 4. Divide
# Create a child class Complex which will inherit from SimpleOperations
# and take (a, b) as arguements (same as the former class).
# Create methods for (a, b) which will perform:
# 1. Exponentiation ('a' to the power of 'b')
# 2. Nth Root ('b'th root of 'a')
# Make sure each class/method includes a docstring
# Make sure entire script conforms to PEP8 guidelines
# Check your work by running the script
class SimpleOperations:
"""A constructor for simple math.
Parameters-
:var a: int
:var b: int
"""
def __init__(self, a, b) -> None:
self.a = a
self.b = b
def add(self):
return self.a + self.b
def subtract(self):
return self.a - self.b
def multiply(self):
return self.a * self.b
def divide(self):
if self.b == 0:
return f'Cannot divide by zero!'
else:
return self.a / self.b
class Complex(SimpleOperations):
"""A constructor for more complicated math.
:var a: int
:var b: int
"""
def __init__(self, a, b) -> None:
super().__init__(a, b)
def exponentiation(self):
return self.a ** self.b
def nth_root(self):
return round((self.a ** (1.0 / self.b)), 4)
if __name__ == "__main__":
print(SimpleOperations(3, 2).add())
print('-------------------')
print(SimpleOperations(3, 2).subtract())
print('-------------------')
print(SimpleOperations(3, 2).multiply())
print('-------------------')
print(SimpleOperations(3, 2).divide())
print('-------------------')
print(Complex(3, 2).exponentiation())
print('-------------------')
print(Complex(3, 2).nth_root())
print('-------------------')
| true
|
8a60d618f47ce9917bf2c8021b2863585af07672
|
sreesindhu-sabbineni/python-hackerrank
|
/TextWrap.py
| 511
| 4.21875
| 4
|
#You are given a string s and width w.
#Your task is to wrap the string into a paragraph of width w.
import textwrap
def wrap(string, max_width):
splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)]
returnstring = ""
for st in splittedstring:
returnstring += st
returnstring += '\n'
return returnstring
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| true
|
90d57fc0012c7370848d13f914790c03a9f10054
|
Nouw/Programming-class
|
/les-8/ns-kaartautomaat.py
| 2,035
| 4.1875
| 4
|
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "'s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
def inlezen_beginstation(stations):
running = True
while running:
station_input = input('Wat is uw begin station?')
if station_input in stations:
running = False
return stations.index(station_input)
else:
print('Het opgegeven station bestaat niet!')
def inlezen_eindstation(stations, beginstation):
running = True
while running:
station_input = input('Wat is uw eind station?')
if station_input in stations:
if beginstation < stations.index(station_input):
running = False
return stations.index(station_input)
else:
print("Het station is de verkeerde kant op!")
else:
print('Het opgegeven station bestaat niet!')
def omroepen_reis(stations, beginstation, eindstation):
nameBeginstation = stations[beginstation]
nameEndstation = stations[eindstation]
distance = eindstation - beginstation
price = distance * 5
print("Het beginstation " + nameBeginstation + " is het " + str(beginstation) + "e station in het traject \n" +
"Het eindstation " + nameEndstation + " is het " + str(eindstation) + "e station in het traject \n" +
"De afstand bedraagt " + str(distance) + " station(s) \n" +
"De prijs van het kaartje is " + str(price) + " euro")
print("Jij stapt in de trein in: " + nameBeginstation)
for stationIndex in range((len(stations))):
if eindstation > stationIndex > beginstation:
print("-" + stations[stationIndex])
print("Jij stapt uit in: " + nameEndstation)
beginstation = inlezen_beginstation(stations)
eindstation = inlezen_eindstation(stations, beginstation)
omroepen_reis(stations, beginstation, eindstation)
| false
|
25001af33ac7a663e5f20810c42d5cba3ac73242
|
AhmedElkhodary/Python-3-Programming-specialization
|
/1- Python Basics/FinalCourseAssignment/pro5.py
| 620
| 4.15625
| 4
|
#Provided is a list of data about a store’s inventory where each item
#in the list represents the name of an item, how much is in stock,
#and how much it costs. Print out each item in the list with the same
#formatting, using the .format method (not string concatenation).
#For example, the first print statment should read The store has 12 shoes, each for 29.99 USD.
inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
item =[]
for inv in inventory:
item = inv.split(", ")
print("The store has {} {}, each for {} USD.".format(item[1], item[0], item[2]))
| true
|
a53c2faa1c8da8d9f736720d2f653811898ea67a
|
AhmedElkhodary/Python-3-Programming-specialization
|
/1- Python Basics/Week4/pro3.py
| 256
| 4.3125
| 4
|
# For each character in the string already saved in
# the variable str1, add each character to a list called chars.
str1 = "I love python"
# HINT: what's the accumulator? That should go here.
chars = []
for ch in str1:
chars.append(ch)
print(chars)
| true
|
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b
|
DiegoCol93/holbertonschool-higher_level_programming
|
/0x0C-python-almost_a_circle/models/square.py
| 2,275
| 4.25
| 4
|
#!/usr/bin/python3
""" Module for storing the Square class. """
from models.rectangle import Rectangle
from collections import OrderedDict
class Square(Rectangle):
""" Por Esta no poner esta documentacion me cague el cuadrado :C """
# __init__ | Private | method |-------------------------------------------|
def __init__(self, size, x=0, y=0, id=None):
""" __init__:
Args:
size(int): Size of the Square object.
x(int): Value for the offset for display's x position.
y(int): Value for the offset for display's y position.
"""
super().__init__(size, size, x, y, id)
# __str__ | Private | method |--------------------------------------------|
def __str__(self):
""" Returns the string for the Rectangle object """
return "[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y,
self.width)
# update | Public | method |----------------------------------------------|
def update(self, *args, **kwargs):
""" Updates all attributes of the Rectangle object. """
if bool(args) is True and args is not None:
try:
self.id = args[0]
self.size = args[1]
self.x = args[2]
self.y = args[3]
except Exception as e:
pass
else:
for i in kwargs.keys():
if i in dir(self):
setattr(self, i, kwargs[i])
# to_dictionary | Public | method |---------------------------------------|
def to_dictionary(self):
""" Returns the dictionary representation of a Square object. """
ret_dict = OrderedDict()
ret_dict["id"] = self.id
ret_dict["size"] = self.width
ret_dict["x"] = self.x
ret_dict["y"] = self.y
return dict(ret_dict)
# Set & Get __width | Public | method |------------------------------------
@property
def size(self):
""" Getter of the Rectangle's width value. """
return self.width
@size.setter
def size(self, number):
""" Setter of the Rectangle's width value. """
self.width = number
self.height = number
| true
|
cf09393ec6a76c29cdd9ba6b187edc1121fe612b
|
CorSar5/Python-World2
|
/exercícios 36-71/ex052.py
| 220
| 4.15625
| 4
|
n = int(input('Escreva um número: '))
if n % 2 == 0 or n % 3 == 0 or n % 5== 0 or n % 7 == 0:
print('Esse número {} não é um número primo'.format(n))
else:
print('O número {} é um número primo'.format(n))
| false
|
971187848e721a42aec82fb6aa5d13f881d84ff4
|
johnmwalters/dsp
|
/python/q8_parsing.py
| 1,242
| 4.40625
| 4
|
# The football.csv file contains the results from the English Premier League.
# The colums labeled 'Goals and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in 'for' and 'against' goals.
import csv
def read_data(data):
with open(data) as csvfile:
reader = csv.DictReader(csvfile)
low_diff = 9999
club = ''
for row in reader:
print row['Team'], row['Games'], row['Wins'], row['Losses'], row['Draws'],row['Goals'], row['Goals Allowed'], row['Points']
goal_difference = int(row['Goals']) - int(row['Goals Allowed'])
abs_goal_difference = abs(int(row['Goals']) - int(row['Goals Allowed']))
print abs_goal_difference
if abs_goal_difference < low_diff:
club = row['Team']
print club
low_diff = abs_goal_difference
else:
low_diff = low_diff
print club
# COMPLETE THIS FUNCTION
#def get_min_score_difference(self, parsed_data):
# COMPLETE THIS FUNCTION
#def get_team(self, index_value, parsed_data):
# COMPLETE THIS FUNCTION
read_data('football.csv')
| true
|
714808135eb230b3fca687200a112a888a7809fd
|
dutraph/python_2021
|
/basic/while_calc.py
| 675
| 4.21875
| 4
|
while True:
print()
n1 = input("Enter 1st number: ")
n2 = input("Enter 2nd number: ")
oper = input("Enter the operator: ")
if not n1.isnumeric() or not n2.isnumeric():
print("Enter a valid number...")
continue
n1 = int(n1)
n2 = int(n2)
if oper == '+':
print(n1 + n2)
elif oper == '-':
print(n1 - n2)
elif oper == '*':
print(n1 * n2)
elif oper == '/':
div = n1 / n2
print(f'{div:.2f}')
else:
print("Must enter a valid operator..")
continue
print(end='\n\n')
exit = input("Exit? [y/n]: ")
if exit == 'y':
break
| false
|
c750ed33c5ec4069676685a31f4257f58055d9b0
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio023 - Separando digitos de um numero.py
| 811
| 4.1875
| 4
|
""" Desafio 023
Faça um programa que leia um número de 0 a 9999 e mostre na tela um dos dígitos separados.
Ex: Digite um número: 1834
Unidade: 4
Dezena: 3
Centena: 8
Milhar: 1 """
# Solução 1: com está solução só é possível obter o resulatdo esperado quando se coloca as quatro unidades
num = input('Digite um número entre 0 e 9999: ')
print('Unidade: {} \nDezena: {} \nCentena: {} \nMilhar: {}'.format(num[3], num[2], num[1], num[0]))
# Solução 2: com a lógica matematica é possível obter o resultado desejado independente de quantas unidades sejam usadas
n = int(input('Digite um número entre 0 e 9999: '))
u = n % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print('O número {} tem: \nUnidade(s): {} \nDezena(s): {} \nCentena(s): {} \nMilhar(es): {}'.format(n, u, d, c, m))
| false
|
6282e26c75b7c3673cdbbe6a5418af6232cfa647
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio035 - Analisando triangulos v1.0.py
| 574
| 4.21875
| 4
|
""" Desafio 035
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo
"""
reta1 = float(input('Informe o valor da primeira reta:'))
reta2 = float(input('Informe o valor da segunda reta:'))
reta3 = float(input('Informe o valor da terceira reta:'))
if (reta2 - reta3) < reta1 < reta2 + reta3 and (reta1 - reta3) < reta2 < reta1 + reta3 and (reta1 - reta2) < reta3 < \
reta1 + reta2:
print('Essas retas podem forma um triângulo')
else:
print('Essas retas não podem formam um triângulo')
| false
|
dd1ae1af46e3a860d227f51cc14f5270e6e4d66d
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio004 - Dissecando uma variavel.py
| 718
| 4.25
| 4
|
""" Desafio 004
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis
sobre ele """
msg = input(' Digite algo: ')
print('O valor {} e ele é do tipo primitivo desse valor é {}'.format(msg, type(msg)))
print('Esse valor é númerico? {}'.format(msg.isnumeric()))
print('Esse valor é alfabetico? {}'.format(msg.isalpha()))
print('Esse valor é alfanúmerico? {}'.format(msg.isalnum()))
print('Esse valor está todo em maiúsculo? {}'.format(msg.isupper()))
print('Esse valor está todo em minúsculo? {}'.format(msg.islower()))
print('Esse valor tem espaços? {}'.format(msg.isspace()))
print('Esse valor está capitalizado? {}'.format(msg.istitle()))
| false
|
1bc9ada8524c22e186391996992ee6458c992b98
|
nataliaqsoares/Curso-em-Video
|
/Mundo 03/desafio075 - Analise de dados em uma tupla.py
| 853
| 4.28125
| 4
|
""" Desafio 075
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: a) quantas vezes
apareceu o valor 9; b) em que posição foi digitado o primeiro valor 3; c) quais foram os números pares; """
conjunto = (int(input('Informe um número: ')), int(input('Informe um número: ')), int(input('Informe um número: ')),
int(input('Informe um número: ')),)
cont = 0
print(f'Foram informados os números: {conjunto}\nO 9 apareceu {conjunto.count(9)} vezes')
if conjunto.count(3) == 0:
print(f'O número 3 não foi informado')
else:
print(f'O 3 apareceu na {conjunto.index(3) + 1}º posição')
print(f'Os números pares digitados foram: ', end='')
for num in conjunto:
if num % 2 == 0:
print(num, end=' ')
else:
cont += 1
if cont == 4:
print('nenhum')
| false
|
0048caeb7b3546c1ae8cc917685d0df5242ad2b3
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio033 - Maior e menor valores.py
| 600
| 4.15625
| 4
|
""" Desafio 033
Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """
n1 = int(input('Informe um número: '))
n2 = int(input('Informe mais um número: '))
n3 = int(input('Informe mais um número: '))
maior = 0
menor = 0
if n1 > n2 and n1 > n3:
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n2:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
print('Dos três números informados o maior número é {} e o menor número é {}'.format(maior, menor))
| false
|
fccf2bdb5f6afe42e695468b8cefc57fedb19783
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio028 - Jogo de Adivinhacao v.1.0.py
| 526
| 4.25
| 4
|
""" Desafio 028
Escreva um programa que faça o computador 'pensar' em um número inteiro entre 0 e 5 e peça para o usuário tentar
descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu
"""
from random import randint
print('Estou pensando em um número entre 0 e 5...')
n1 = randint(0, 5)
n2 = int(input('Em qual número eu pensei? '))
if n1 == n2:
print('Você acertou!')
else:
print('Você errou! Eu estava pensando no número {}'.format(n1))
| false
|
693dd4620876b1525d56d4b03c47a34f032feb20
|
nataliaqsoares/Curso-em-Video
|
/Mundo 02/desafio036 - Aprovando emprestimo.py
| 842
| 4.1875
| 4
|
""" Desafio 036
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da
casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não
pode exceder 30% do salário ou então o empréstimo será negado """
valor_casa = float(input('Qual valor da casa que deseja financiar? R$'))
salario = float(input('Qual seu salário mensal? R$'))
anos = int(input('Em quantos anos deseja pagar a casa? '))
prestacao = valor_casa / (anos * 12)
if prestacao >= (salario * 0.3):
print('Infelizmente não foi possível financiar está casa no momento')
else:
print('Seu financiamento foi aprovado! As prestações mensais para pagar a casa de {:.2f} em {} anos são de {:.2f}'
.format(valor_casa, anos, prestacao))
| false
|
967aa21504999e6fd116ebd555c548bc26f6903c
|
nataliaqsoares/Curso-em-Video
|
/Mundo 01/desafio002.1 - Data de nascimento.py
| 514
| 4.125
| 4
|
""" Desafio002.1
Crie um programa que leia o dia, o mês e o ano de nascimento de uma pessoa e mostre uma mensagem com a data
formatada (mensagem de saida = Você nasceu no dia x de x de x. Correto?) """
# Solução 1
nasci = input('Quando você nasceu? ')
print('Você nasceu em', nasci, 'Correto?')
# Solução 2
dia = input('Em qual dia você nasceu? ')
mes = input('Em qual mês você nasceu? ')
ano = input('Em qual ano você nasceu? ')
print('Você nasceu no dia', dia, 'de', mes, 'de', ano, 'Correto?')
| false
|
499b850f68b05aceb843bcd4f6f94c9cb1077afc
|
thales-mro/python-cookbook
|
/2-strings/4-pattern-match-and-search.py
| 1,181
| 4.125
| 4
|
import re
def date_match(date):
if re.match(r'\d+/\d+/\d+', date):
print('yes')
else:
print('no')
def main():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.find('no'))
date1 = '02/01/2020'
date2 = '02 Jan, 2020'
date_match(date1)
date_match(date2)
print("For multiple uses, it is good to compile the regex")
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(date1):
print("yes")
else:
print("no")
if datepat.match(date2):
print("yes")
else:
print("no")
text = "Today is 02/01/2020. In a week it will be 09/01/2020."
print(datepat.findall(text))
print("Including capture groups (in parenthesis)")
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datepat.match('26/09/1998')
print(m)
print(m.group(0), m.group(1), m.group(2), m.group(3), m.groups())
print(datepat.findall(text))
for month, day, year in datepat.findall(text):
print('{}--{}--{}'.format(year, month, day))
print("With finditer:")
for m in datepat.finditer(text):
print(m.groups())
if __name__ == "__main__":
main()
| true
|
881166784fd6a82253a5b189f956582a7a8de5e0
|
firebirdrazer/CodingTests
|
/check_paren.py
| 1,952
| 4.40625
| 4
|
def check_bracket(Str):
stack = [] #make a empty check stack
while Str != "": #as long as the input is not empty
tChar = Str[0] #extract the first character as the test character
Str = Str[1:] #the rest characters would be the input in the next while loop
if tChar == "(" or tChar == "{": #as the test character is a left-bracket "(" or "{"
stack.append(tChar) #the character would be added into the stack
elif tChar == ")" or tChar == "}": #if the test character is a right-bracket ")" or "}"
if len(stack) == 0: #then we have to check the stack to see if there's a corresponding one
return False #if no or empty, the string would be invalid
else: #if yes, we can pop the corresponding character from the stack
if tChar == ")" and stack[-1] == "(":
stack.pop(-1)
elif tChar == "}" and stack[-1] == "{":
stack.pop(-1)
else:
return False
if stack == []: #which means if the string is valid, the stack would be empty
return True #after the process
else: #if there's anything left after the process
return False #the function would return False
#main program
Test=input() #input string
print(check_bracket(Test)) #return True if the input has valid brackets
| true
|
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7
|
ryanhgunn/learning
|
/unique.py
| 382
| 4.21875
| 4
|
# A script to determine if characters in a given string are unique.
import sys
string = input("Input a string here: ")
for i in range(0, len(string)):
for j in range(i + 1, len(string)):
if string[i] == string[j]:
print("The characters in the given string are not unique.")
sys.exit(0)
print("The characters in the given string are unique.")
| true
|
d279398b290a9f0320bacaa23864b3be614100c3
|
AndrewGreen96/Python
|
/math.py
| 1,217
| 4.28125
| 4
|
# 4.3 Counting to twenty
# Use a for loop to print the numbers from 1 to 20.
for number in range(1,21):
print(number)
# 4.4 One million
# Make a list from 1 to 1,000,000 and use a for loop to print it
big_list = list(range(1,1000001))
print(big_list)
# 4.5 Summing to one million
# Create a list from one to one million, use min() and max() to check that it starts at 1 and ends at 1000000 and then sum all of the elements from the list together.
onemillion = list(range(1,1000001))
print(min(onemillion))
print(max(onemillion))
print(sum(onemillion))
# 4.6 Odd numbers
# Make a list of the odd numbers from 1 to 20 and use a for loop to print each number.
odd_numbers = list(range(1,21,2))
for odd in odd_numbers:
print(odd)
print('\n')
# 4.7 Threes
# Make a list of the multiples of 3 from 3 to 30 and then print it.
threes =list(range(3,31,3))
for number in threes:
print(number)
# 4.8 Cubes
# Make a list of the first 10 cubes.
cubes = list(range(1,11))
for cube in cubes:
print(cube**3)
# 4.9 Cube comprehension
# Use a list comprehension to generate a list of the first 10 cubes.
cubes =[cube**3 for cube in range(1,11)]
| true
|
f003dd889cdce228f66dbad8f66955c9c32563c0
|
csgray/IPND_lesson_3
|
/media.py
| 1,388
| 4.625
| 5
|
# Lesson 3.4: Make Classes
# Mini-Project: Movies Website
# In this file, you will define the class Movie. You could do this
# directly in entertainment_center.py but many developers keep their
# class definitions separate from the rest of their code. This also
# gives you practice importing Python files.
# https://www.udacity.com/course/viewer#!/c-nd000/l-4185678656/m-1013629057
# class: a blueprint for objects that can include data and methods
# instance: multiple objects based on a class
# constructor: the __init__ inside the class to create the object
# self: Python common practice for referring back to the object
# instance methods: functions within a class that refers to itself
import webbrowser
class Movie():
"""This class provides a way to store movie related information."""
def __init__(self, movie_title, rating, duration, release_date, movie_storyline, poster_image, trailer_youtube):
# Initializes instance of class Movie
self.title = movie_title
self.rating = rating
self.duration = duration
self.release_date = release_date
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
# Opens a browser window with the movie trailer from YouTube
webbrowser.open(self.trailer_youtube_url)
| true
|
a6abf1f12cc09aeb393630d5c59219e9ae0c479b
|
chill133/BMI-calculator-
|
/BMI.py
| 310
| 4.25
| 4
|
height = input("What is your height?")
weight = input("What is your weight?")
BMI = 703 * (int(weight))/(int(height)**2)
print("Your BMI " + str(BMI))
if (BMI <= 18):
print("You are underweight")
elif (BMI >= 18) and (BMI <= 26):
print("You are normal weight")
else:
print("You are overweight")
| false
|
e8e71c47bd34a628562c9dfcd351bcd336a99d70
|
endar-firmansyah/belajar_python
|
/oddevennumber.py
| 334
| 4.375
| 4
|
# Python program to check if the input number is odd or even.
# A number is even if division by given 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number
# div = 79
div = int(input("Input a number: "))
if (div % 2) == 0:
print("{0} is even Number".format(div))
else:
print("{0} is Odd Number".format(div))
| true
|
b928d3b1b8bfac3efa68e1bccaa9347c16482bd8
|
JianHui1208/Code_File
|
/Python/Lists.py
| 291
| 4.15625
| 4
|
thislist = ["a", "b","c"]
print(thislist)
thislist = ["a", "b", "c"]
print(thislist[1])
# same the array start for 0
thislist = ["a", "b", "c"]
print(thislist[-1])
# -1 is same like the last itme
# -2 is second last itme
thislist = ["a", "b", "c", "d", "e", "f", "g"]
print(thislist[2:5])
| false
|
7a539c585cf9adca8dc788fea5295f99a65b5e92
|
wecchi/univesp_com110
|
/Sem2-Texto22.py
| 1,217
| 4.15625
| 4
|
'''
Texto de apoio - Python3 – Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin
Problema Prático 2.2
Traduza os comandos a seguir para expressões Booleanas em Python e avalie-as:
(a)A soma de 2 e 2 é menor que 4.
(b)O valor de 7 // 3 é igual a 1 + 1.
(c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25.
(d)A soma de 2, 4 e 6 é maior que 12.
(e)1387 é divisível por 19.
(f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?)
(g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.*
'''
a = (2 + 2) < 4
b = (7 // 3) == (1 + 1)
c = (3 ** 2 + 4 ** 2) == 25
d = (2 + 4 + 6 ) > 12
e = 1387 % 19 == 0
f = 31 % 2 == 0
g = min(34.99, 29.95, 31,50) < 30
print('(a)A soma de 2 e 2 é menor que 4.', a)
print('(b)O valor de 7 // 3 é igual a 1 + 1.', b)
print('(c)A soma de 3 ao quadrado e 4 ao quadrado é igual a 25.', c)
print('(d)A soma de 2, 4 e 6 é maior que 12.', d)
print('(e)1387 é divisível por 19.', e)
print('(f)31 é par. (Dica: o que o resto lhe diz quando você divide por 2?)', f)
print('(g)O preço mais baixo dentre R$ 34,99, R$ 29,95 e R$ 31,50 é menor que R$ 30,00.', g)
| false
|
2681542783b3751bd885d3f5d829d6bf2ccde4be
|
code-wiki/Data-Structure
|
/Array/(Manacher's Algoritm)Longest Palindromic Substring.py
| 1,046
| 4.125
| 4
|
# Hi, here's your problem today. This problem was asked by Twitter:
# A palindrome is a sequence of characters that reads the same backwards and forwards.
# Given a string, s, find the longest palindromic substring in s.
# Example:
# Input: "banana"
# Output: "anana"
# Input: "million"
# Output: "illi"
# class Solution:
# def longestPalindrome(self, s):
# # Fill this in.
# # Test program
# s = "tracecars"
# print(str(Solution().longestPalindrome(s)))
# # racecar
class Solution:
def checkPalindrome(str):
# reversing a string in python to get the reversed string
# This is extended slice syntax.
# It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1,
# it reverses a string.
reversedString = str[::-1]
if (str == reversedString):
return true
else:
return false
def longestPalindrome(str):
while (index > str.length):
while ():
pass
| true
|
f503e91072d0dd6c7402e8ae662b6139feed05e0
|
adykumar/Leeter
|
/python/104_maximum-depth-of-binary-tree.py
| 1,449
| 4.125
| 4
|
"""
WORKING....
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
"""
import Queue as queue
class TreeNode(object):
def __init__(self,x):
self.val= x
self.left= None
self.right= None
class Solution(object):
def createTree(self, treelist):
root= TreeNode(treelist[0])
q= queue.Queue(maxsize= len(treelist))
q.put(root)
i = 1
while True:
if i>= len(treelist): break
node= q.get()
if treelist[i] != "null":
node.left= TreeNode(treelist[i])
q.put(node.left)
i+=1
if i>= len(treelist): break
if treelist[i] != "null":
node.right= TreeNode(treelist[i])
q.put(node.right)
i+=1
return root
def maxDepth(self, root):
if root==None: return 0
return max( self.maxDepth(root.left)+1, self.maxDepth(root.right)+1 )
if __name__=="__main__":
testcases= [[3,9,20,"null","null",15,7, 1, 1, 3], [1], [1,"null", 3]]
obj= Solution()
for test in testcases:
root= obj.createTree(test)
print test, " -> ", obj.maxDepth(root)
| true
|
c5765011e3f9b07eae3a52995d20b45d0f462229
|
adykumar/Leeter
|
/python/429_n-ary-tree-level-order-traversal.py
| 1,083
| 4.1875
| 4
|
"""
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
1
/ | \
3 2 4
/ \
5 6
We should return its level order traversal:
[
[1],
[3,2,4],
[5,6]
]
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
"""
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children #list of nodes
class Solution(object):
def helper(self, root, res, level):
if root==None:
return
if len(res)<= level+1 and len(root.children)>0:
res.append([])
for eachNode in root.children:
res[level+1].append(eachNode.val)
self.helper(eachNode, res, level+1)
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root==None:
return []
res= [[root.val]]
self.helper(root, res, 0)
return res
| true
|
2b65c4cf9a9372262d2cc927904e36f69cec9cd4
|
mosabry/Python-Stepik-Challenge
|
/1.06 Compute the area of a rectangle.py
| 323
| 4.15625
| 4
|
width_string = input("Please enter width: ")
# you need to convert width_string to a NUMBER. If you don't know how to do that, look at step 1 again.
width_number = int(width_string)
height_string = input("Please enter height: ")
height_number = int(height_string)
print("The area is:")
print(width_number * height_number)
| true
|
b7b296552886fe0ca8d13d543770e0575361837c
|
joanamdsantos/world_happiness
|
/functions.py
| 1,018
| 4.125
| 4
|
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_countrybarplot(df, var, top_num):
'''
INPUT:
df - pandas dataframe with the data
var- variable to plot, not categorical
top_num - number of top countries to plot
OUTPUT:
plot with the top number of countries with the var scores
'''
# Initialize the matplotlib figure
f, ax = plt.subplots(figsize=(6, 15))
# Choose only the top 50 countries with higher score
y=df.sort_values(var, ascending=False)
y_top = y['Country or region'][:top_num]
# Plot the GDP per capita per country
sns.set_color_codes("pastel")
g=sns.barplot(x=var, y=y_top, data=df,
label=var, color="y")
# Add a legend and informative axis label
ax.legend(ncol=3, loc="lower right", frameon=True)
ax.set(xlim=(0, 10), ylabel="",
xlabel=var)
sns.despine(left=True, bottom=True)
return g
| true
|
54f0e746f3067e9c8f182de031b0711fd4033569
|
shinozaki1595/hacktoberfest2021-3
|
/Python/Algorithms/Sorting/heap_sort.py
| 884
| 4.34375
| 4
|
# Converting array to heap
def arr_heap(arr, s, i):
# To find the largest element among a root and children
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < s and arr[i] < arr[l]:
largest = l
if r < s and arr[largest] < arr[r]:
largest = r
# Replace the root if it is not the largest, then continue with the heap algorithm
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
arr_heap(arr, s, largest)
# Heap sort algorithm
def heapsort(arr):
s = len(arr)
# Making the Max heap
for i in range(s//2, -1, -1):
arr_heap(arr, s, i)
for i in range(s-1, 0, -1):
# replace
arr[i], arr[0] = arr[0], arr[i]
# Transform root element into Heap
arr_heap(arr, i, 0)
arr = [1, 12, 9, 5, 6, 10]
heapsort(arr)
n = len(arr)
print("Array after Heap Sort is:")
print(arr)
| false
|
70d87e6fe32ad1b0d647e85cf8a64c8f59c9398a
|
marcin-skurczynski/IPB2017
|
/Daria-ATM.py
| 568
| 4.125
| 4
|
balance = 542.31
pin = "1423"
inputPin = input("Please input your pin: ")
while pin != inputPin:
print ("Wrong password. Please try again.")
inputPin = input("Please input your pin: ")
withdrawSum = float(input("How much money do you need? "))
while withdrawSum > balance:
print ("The sum you are trying to withdraw exceeds your balance. Try again.")
withdrawSum = float(input("How much money do you need? "))
print ("You have successfully withdrawn " + str(withdrawSum) + "PLN. Your current balance is " + str(round((balance-withdrawSum), 2)) + "PLN.")
| true
|
296dd75cbc77a834515929bc0820794909fb9e54
|
sdaless/pyfiles
|
/CSI127/shift_left.py
| 414
| 4.3125
| 4
|
#Name: Sara D'Alessandro
#Date: September 12, 2018
#This program prompts the user to enter a word and then prints the word with each letter shifted left by 1.
word = input("Enter a lowercase word: ")
codedWord = ""
for ch in word:
offset = ord(ch) - ord('a') - 1
wrap = offset % 26
newChar = chr(ord('a') + wrap)
codedWord = codedWord + newChar
print("Your word in code is: ", codedWord)
| true
|
b3dbf8b4190548cd3787fbe0021ca46244b116af
|
sdaless/pyfiles
|
/CSI127/turtle_color.py
| 208
| 4.53125
| 5
|
#Sara D'Alessandro
#A program that changes the color of turtle
#September 26th, 2018
import turtle
tut = turtle.Turtle()
tut.shape("turtle")
hex = input("Enter a hex string starting with '#' sign: ")
tut.color(hex)
| false
|
5f7c7a681de3287b0e2c05bb05d18df626eb3b54
|
sudev/dsa
|
/graph/UsingAdjacencyList.py
| 1,677
| 4.15625
| 4
|
# A graph implementation using adjacency list
# Python 3
class Vertex():
def __init__(self, key):
self.id = key
# A dictionary to act as adjacency list.
self.connectedTo = {}
def addEdge(self, vert, w=0):
self.connectedTo[vert] = w
# Repr
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,vert):
return self.connectedTo[vert]
class Graph():
"""Graph"""
def __init__(self):
# A dictionary to map Vertex-keys and object vertex class.
self.vertlist = {}
self.vertexNum = 0
def addVertex(self, key):
self.vertlist[key] = Vertex(key)
self.vertexNum += 1
return self.vertlist[key]
def getVertex(self, key):
if key in self.vertlist:
return self.vertlist[key]
else:
return None
def addEdge(self, h, t, weight=0):
# If any of vertex not in list create them
if h not in self.vertlist:
nv = self.addVertex(h)
if t not in self.vertlist:
nv = self.addVertex(t)
# Add edge from head to tail
self.vertlist[h].addEdge(self.vertlist[t], weight)
def getVertices(self):
return self.vertlist.keys()
def __iter__(self):
return iter(self.vertlist.values())
# create a graph
g = Graph()
# add some vertex
for i in range(6):
g.addVertex(i)
print (g.vertlist)
# Some Egdes
g.addEdge(0,1,5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
# View them
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
| true
|
31d68d11fdc06c09e0721e6541024eb33b585c91
|
selimozen/Hackerrank
|
/Python/ifelse.py
| 546
| 4.3125
| 4
|
#ENG: if n is odd, print Weird , if n is even and in the inclusive range of 2 to 5, print Not Weird,
#if n is even and in the inclusive range of 6 to 20, print Weird, if is even and greater than 20, print Not Weird
#TR: Eğer n sayısı tekil ise, 'Weird' yazdır, eğer n sayısı 2 veya 5'e eşit veya arasında ise Not Weird yazdır, eğer n sayısı 6 ile 20'ye eşit veya arasında ise Weird yazdır.
#Eğer n sayısı 20'den büyük ise Not Weird yazdır.
if(n%2==1) or n in range (5,21):
print("Weird")
else:
print("Not Weird")
| false
|
a961f3be1e5d83fbd174bc21851b0753bec84c04
|
andersonresende/learning_python
|
/chapter_19/recursion.py
| 1,077
| 4.21875
| 4
|
#nao mudar o tipo de uma variavel e uma boa pratica
#nao usar globais dentro de funcoes, pois pode criar dependencias.
#durante a recursao o escopo das funcoes e mantido, por isso funciona.
#recursao exige que vc crie uma funcao, enquanto procedural nao.
#vc nao pode alterar os valores de variaveis a partir de fora da funcao.
def mysum_1(l):
''' Soma uma lista recursivamente.'''
if not l:
return 0
return l[0] + mysum(l[1:])
def mysum_2(l):
'''
Soma uma lista recursivamente
usando ternary expression.
Funciona tambem com strings.
'''
return 0 if not l else l[0] + mysum(l[1:])
def mysum_3(l):
'''
Soma uma lista com while.
'''
soma = 0
while l:
soma+=l[0]
l = l[1:] #essa tecnica dispensa o uso de contadores.Muito bom!!!
return soma
print mysum_3([1,2,3,4])
def sumtree(L):
'''
Funcao avancada de recursao que
soma listas aninhadas. Essa soma
so pode ser feita com recursao
'''
tot = 0
for x in L:
if not isinstance(x, list):
tot += x
else:
tot += sumtree(x)
return tot
L = [1, [2, [3, 4], 5], 6, [7, 8]]
print(sumtree(L))
| false
|
609add66f670ba8c7b3863bc12603b83e71c99af
|
andersonresende/learning_python
|
/chapter_18/min.py
| 723
| 4.125
| 4
|
def min1(*args):
'''
Retorna o menor valor, passado em uma tupla.
'''
res = args[0]
for arg in args[1:]:
if arg < res: res = arg
return res
print min1(10,2,3,4)
def min2(first, *rest):
'''
Retorna o menor valor, recebendo um argumento inicial
e outros em uma tupla.
'''
for arg in rest:
if arg < first: first = arg
return first
print min2('a','c','b')
def min3(*args):
'''
Recebe uma tupla e retorna o meno valor contido.
'''
tmp = list(args)
tmp.sort()
return tmp[0]
print min3([1,2],[3,4],[0,1])
#em python tuplas sao imutaveis logo, nao podemos trocar objetos ou
#reordena-las.
#lista.sort() ordena a lista
#strip()-tirar retira espacos, split('b')-divisao quebra por argumento, ou espaco.
| false
|
0406e3cc0d3d09c9bbaf400c2808ebf0737d31d4
|
bharathkkb/peer-tutor
|
/peer-tutor-api/timeBlock.py
| 1,230
| 4.25
| 4
|
import time
import datetime
class TimeBlock:
"""
Returns a ```Time Block``` object with the given startTime and endTime
"""
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
print("A time block object is created.")
def __str__(self):
"""
Prints the details of a time block.
"""
return self.start_time.strftime("%c") + " " + self.end_time.strftime("%c")
def get_json(self):
"""
returns a json format of a Time Block
"""
time_dict=dict()
time_dict["start"]=self.start_time
time_dict["end"] = self.end_time
return time_dict
def get_start_time(self):
"""
return TimeBlock's end_time
"""
return self.start_time
def get_end_time(self):
"""
return TimeBlock's end_time
"""
return self.end_time
def set_start_time(self, start_time):
"""
set start_time
"""
self.start_time = start_time
return True
def set_end_time(self, end_time):
"""
set end_time
"""
self.end_time = end_time
return True
| true
|
6edfeb4705a4f49b354ef9571029d19b9848f8e5
|
dani3l8200/100-days-of-python
|
/day1-printing-start/project1.py
| 454
| 4.28125
| 4
|
#1. Create a greeting for your program.
print('Welcome to Project1 of 100 Days of Code Python')
#2. Ask the user for the city that they grew up in.
city_grew_user = input('Whats is your country that grew up in?\n')
#3. Ask the user for the name of a pet.
pet_of_user = input('Whats is the name of any pet that having?\n')
#4. Combine the name of their city and pet and show them their band name.
print('Band Name: ' + city_grew_user + " " + pet_of_user)
| true
|
215ae22230731d3c486c7b652128fb1b212c78e0
|
islamrumon/PythonProblems
|
/Sets.py
| 2,058
| 4.40625
| 4
|
# Write a Python program to create a new empty set.
x =set()
print(x)
n = set([0, 1, 2, 3, 4])
print(n)
# Write a Python program to iteration over sets.
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
# Write a Python program to add member(s) in a set.
color_set = set()
color_set.add("Red")
print(color_set)
color_set.update(["Blue","Green"])
print(color_set)
# Write a Python program to remove item(s) from set.
num_set = set([0, 1, 3, 4, 5])
num_set.pop()
print(num_set)
num_set.pop()
print(num_set)
# Write a Python program to create an intersection of sets.
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
# Write a Python program to create a union of sets.
seta = setx | sety
print(seta)
# Write a Python program to create set difference.
setn = setx - sety
print(setn)
# Write a Python program to create a symmetric difference.
seto = setx^sety
print(setn)
# Write a Python program to test whether every element in s is in t and every element in t is in s.
setz = set(["mango"])
issubset = setx <= sety
print(issubset)
issuperset = setx >= sety
print(issuperset)
issubset = setz <= sety
print(issubset)
issuperset = sety >= setz
print(issuperset)
# Write a Python program to create a shallow copy of sets.
setp = set(["Red", "Green"])
setq = set(["Green", "Red"])
#A shallow copy
setr = setp.copy()
print(setr)
# Write a Python program to clear a set.
setq.clear()
print(setq)
# Write a Python program to use of frozensets.
x = frozenset([1, 2, 3, 4, 5])
y = frozenset([3, 4, 5, 6, 7])
#use isdisjoint(). Return True if the set has no elements in common with other.
print(x.isdisjoint(y))
#use difference(). Return a new set with elements in the set that are not in the others.
print(x.difference(y))
#new set with elements from both x and y
print(x | y)
# Write a Python program to find maximum and the minimum value in a set.
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
| true
|
aae16277602c86460bafa3df51c1eb258c7d85db
|
roxdsouza/PythonLessons
|
/Dictionaries.py
| 2,088
| 4.65625
| 5
|
# Dictionary is written as a series of key:value pairs seperated by commas, enclosed in curly braces{}.
# An empty dictionary is an empty {}.
# Dictionaries can be nested by writing one value inside another dictionary, or within a list or tuple.
print "--------------------------------"
# Defining dictionary
dic1 = {'c1':'Churchgate', 'c5':'Marine Drive', 'c4':'Vile Parle', 'c3':"Bandra", 'c2':'Dadar', 'c6':'Andheri'}
dic2 = {'w3':'Wadala', 'c5':'Chowpatty', 'w4':'Kurla', 'w5':"Thane", 'c2':'Dadar', 'w7':'Andheri'}
# Printing dictionary
print dic1
# Print all keys
print dic1.keys()
# Print all values
print dic1.values()
# Printing a particular value using key
print 'Value of key c4 is: ' + dic1["c4"]
print "Value of key c4 is: " + dic1.get("c4")
# Print all keys and values
print dic1.items()
print "--------------------------------"
# Add value in dictionalry
dic1['w1']='Victoria Terminus'
dic1['w2']=10001
dic1[20]='Byculla'
print dic1
print "--------------------------------"
# Finding data type of key
print [type(i) for i in dic1.keys()]
print "--------------------------------"
print "Length of dictionary is:",
print len(dic1)
print "--------------------------------"
# "in" used to test whether a key is present in the dictionary
print dic1
print 20 in dic1
print "c6" in dic1
print "c6" not in dic1
print "--------------------------------"
# Adding values in dictionary using another dictionary
# If same key exist in both the dictionaries then it will update the value of the key available from dic2 in dic1
# If both dictionaries have same key + value then it will only keep the original value from dic1
dic1.update(dic2)
print dic1
print "--------------------------------"
# Remove value from dictionary
dic1.pop('w4')
print dic1
print "--------------------------------"
# Looping through dictionary
for key, value in dic2.items():
print key, value
print "--------------------------------"
dic1.clear()
print "Total number of elements in dic1 after using the clear function: ",
print len(dic1)
print "-------------THE END-------------------"
| true
|
4fa1560b335f86dae73766c7f6b316e339d54671
|
roxdsouza/PythonLessons
|
/Classes04.py
| 964
| 4.125
| 4
|
# Program to understand class and instance variables
# class Edureka:
#
# # Defining a class variable
# domain = 'Big data analytics'
#
# def SetCourse(self, name): # name is an instance variable
# # Defining an instance variable
# self.name = name
#
#
# obj1 = Edureka() # Creating an instance of the class Edureka
# obj2 = Edureka()
#
# print obj1.domain
# print obj2.domain
#
# obj1.SetCourse('Python') # Calling the method
# obj2.SetCourse('Hadoop')
#
# print obj1.name
# print obj2.name
########################################################
# Program to understand more about constructor or distructor
class Edureka:
def __init__(self, name):
self.name = name
def __del__(self): # Called when an instance is about to be destroyed
print 'Destructor started'
obj1 = Edureka('Python')
obj2 = obj1
# Calling the __del__ function
del obj1
obj1 = obj2
print obj2.name
print obj1.name
del obj1, obj2
| true
|
4e7b02140879900cbbb4e3889789c8b3dcd15291
|
LewisT543/Notes
|
/Learning_Data_processing/3SQLite-update-delete.py
| 1,440
| 4.46875
| 4
|
#### SQLITE UPDATING AND DELETING ####
# UPDATING DATA #
# Each of the tasks created has its own priority, but what if we decide that one of them should be done earlier than the others.
# How can we increase its priority? We have to use the SQL statement called UPDATE.
# The UPDATE statement is used to modify existing records in the database. Its syntax is as follows:
'''
UPDATE table_name
SET column1 = value1, column2 = value2, column3 = value3, …, columnN = valueN
WHERE condition;
'''
# If we'd like to set the priority to 20 for a task with idequal to 1, we can use the following query:
'''
UPDATE tasks SET priority = 20 WHERE id = 1;
'''
# IMPORTANT NOTE: If you forget about the WHERE clause, all data in the table will be updated.
import sqlite3
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('UPDATE tasks SET priority = ? WHERE id = ?', (20, 1))
conn.commit()
conn.close()
# DELETING DATA #
# After completing a task, we would like to remove it from our database. To do this, we must use the SQL statement called DELETE
'''
DELETE FROM table_name WHERE condition;
DELETE FROM tasks WHERE id = 1;
'''
# NOTE: If you forget about the WHERE clause, all data in the table will be deleted.
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('DELETE FROM tasks WHERE id = ?', (1,)) # Tuple here? Not sure why, could be required...
conn.commit()
conn.close()
| true
|
100a33b667fa60386fabf26718b7bdf71d25d26c
|
satlawa/ucy_dsa_projects
|
/Project_0/Task2.py
| 1,759
| 4.25
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
def get_tel_num_max_time(calls):
"""
Function for finding the telephone number that spent the longest time on the phone.
Args:
calls(list): list containing call records
Return:
max_len(tuple): tuple containing the telephone number and the time spend on
the phone from the telephone number that spent the longest time on the phone.
"""
# dictionary for keeping track of the time of every tel number
tel_nums = {}
# loop all records
for record in calls:
# loop both columns
for i in range(2):
# if key already exists summ values
if record[i] in tel_nums:
tel_nums[record[i]] += int(record[3])
# key does not exist create key with value
else:
tel_nums[record[i]] = int(record[3])
# find tel number with max length
max_len = ("0",0)
for tel_num, length in tel_nums.items():
if length > max_len[1]:
max_len = (tel_num, length)
return max_len
tel_num, lenght = get_tel_num_max_time(calls)
print("{} spent the longest time, {} seconds, on the phone during September 2016."\
.format(tel_num, lenght))
| true
|
89309e6aa3917fee2427a1e16113a3de202994d5
|
achmielecki/AI_Project
|
/agent/agent.py
| 2,136
| 4.25
| 4
|
"""
File including Agent class which
implementing methods of moving around,
making decisions, storing the history of decisions.
"""
class Agent(object):
""" Class representing agent in game world.
Agent has to reach to destination point
in the shortest distance. World is random generated. """
def __init__(self):
""" Initialize the Agent """
self.__history = []
self.__x = -1
self.__y = -1
self.__destination_x = -1
self.__destination_y = -1
# ---------
# TO DO
# ---------
def make_decision(self):
""" make decision where agent have to go """
pass
# ---------
# TO DO
# ---------
def move(self, way: int):
""" Move the agent in a given direction """
pass
def add_to_history(self, env_vector: list[int], decision: int):
""" Add new pair of environment vector and decision to history """
self.__history.append((env_vector, decision))
def __str__(self):
""" define how agent should be shown as string """
string_agent = "{"
string_agent += "position: (" + str(self.__x) + ", " + str(self.__y) + ")"
string_agent += " | "
string_agent += "destination: (" + str(self.__destination_x) + ", " + str(self.__destination_y) + ")"
string_agent += "}"
return string_agent
def set_position(self, x: int, y: int):
""" Set new agent position """
self.__x = x
self.__y = y
def clear_history(self):
""" clear agent history """
self.__history.clear()
def get_history(self):
""" Return agent history """
return self.__history
def get_position(self):
""" Return agent position as a tuple (x, y) """
return self.__x, self.__y
if __name__ == '__main__':
agent = Agent()
print(agent)
agent.add_to_history([1, 0, 0, 1, 0, 1], 5)
agent.add_to_history([1, 0, 2, 3, 5, 6], 5)
agent.add_to_history([1, 1, 0, 3, 6, 5], 5)
print(agent.get_history())
agent.clear_history()
print(agent.get_history())
| true
|
b1e4492ff80874eeada53f05d6158fc3ce419297
|
lovepurple/leecode
|
/first_bad_version.py
| 1,574
| 4.1875
| 4
|
"""
278. 2018-8-16 18:15:47
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example:
Given n = 5, and version = 4 is the first bad version.
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
同样是二分法 这个例子带边界值
"""
def isBadVersion(version):
return True if version >= 6 else False
class first_bad_version:
def firstBadVersion(self, n):
return self.findBadVersion(0, n)
def findBadVersion(self, left, right):
if right - left == 1:
if not isBadVersion(left) and isBadVersion(right):
return right
else:
middleVersion = (right + left) // 2
if isBadVersion(middleVersion):
return self.findBadVersion(left, middleVersion)
else:
return self.findBadVersion(middleVersion, right)
instance = first_bad_version()
print(instance.firstBadVersion(7))
| true
|
29ef17e51ae29ba273a3b59e65419d73bacf6aa0
|
mathivananr1987/python-workouts
|
/dictionary-tuple-set.py
| 1,077
| 4.125
| 4
|
# Tuple is similar to list. But it is immutable.
# Data in a tuple is written using parenthesis and commas.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print("count of orange", fruits.count("orange"))
print('Index value of orange', fruits.index("orange"))
# Python Dictionary is an unordered sequence of data of key-value pair form.
# It is similar to Map or hash table type.
# Dictionaries are written within curly braces in the form key:value
countries = {"India": "New Delhi", "China": "Beijing", "USA": "Washington", "Australia": "Canberra"}
print(countries["India"])
# adding entry to dictionary
countries["UK"] = "London"
print(countries)
# A set is an unordered collection of items. Every element is unique (no duplicates).
# In Python sets are written with curly brackets.
set1 = {1, 2, 3, 3, 4, 5, 6, 7}
print(set1)
set1.add(10)
# remove & discard does the same thing. removes the element.
# difference is discard doesn't raise error while remove raise error if element doesn't exist in set
set1.remove(6)
set1.discard(7)
print(set1)
| true
|
7ca52317a28ac1a45a2a44b3d8d769def95493e5
|
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
|
/python_fundamentals/MakingDicts.py
| 329
| 4.34375
| 4
|
def print_dict(dict):
print "My name is", dict["name"]
print "My age is", dict["age"]
print "My country of birth is", dict["birthplace"]
print "My favorite language is", dict["language"]
myDict = {}
myDict["name"]="Mike"
myDict["age"]=34
myDict["birthplace"]="USA"
myDict["language"]="Python"
print_dict(myDict)
| false
|
63cd3250a2453bc5dcf1083a3f9010fd6496fe1f
|
BrandonCzaja/Sololearn
|
/Python/Control_Structures/Boolean_Logic.py
| 650
| 4.25
| 4
|
# Boolean logic operators are (and, or, not)
# And Operator
# print(1 == 1 and 2 == 2)
# print(1 == 1 and 2 == 3)
# print(1 != 1 and 2 == 2)
# print(2 < 1 and 3 > 6)
# Example of boolean logic with an if statement
# I can either leave the expressions unwrapped, wrap each individual statement or wrap the whole if condition in ()
if (1 == 1 and 2 + 2 > 3):
print('true')
else:
print('false')
# Or Operator
age = 15
money = 500
if age > 18 or money > 100:
print('Welcome')
# Not Operator
# print(not 1 == 1) # False
# print(not 1 > 7) # True
if not True:
print('1')
elif not (1 + 1 == 3):
print("2")
else:
print("3")
| true
|
674d9922f89514e4266c48ec91b98f223fdcf313
|
Ang3l1t0/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/4-append_write.py
| 410
| 4.1875
| 4
|
#!/usr/bin/python3
"""Append
"""
def append_write(filename="", text=""):
"""append_write method
Keyword Arguments:
filename {str} -- file name or path (default: {""})
text {str} -- text to append (default: {""})
Returns:
[str] -- text that will append
"""
with open(filename, 'a', encoding="UTF8") as f:
out = f.write(text)
f.closed
return (out)
| true
|
982c7852214a41e505052c5674006286fc26b4b9
|
Ang3l1t0/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/4-print_square.py
| 444
| 4.34375
| 4
|
#!/usr/bin/python3
"""print_square"""
def print_square(size):
"""print_square
Arguments:
size {int} -- square size
Raises:
TypeError: If size is not an integer
ValueError: If size is lower than 0
"""
if type(size) is not int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
for _i in range(size):
print('#' * size)
| true
|
af528387ea37e35a6f12b53b392f920087e5284b
|
Ang3l1t0/holbertonschool-higher_level_programming
|
/0x02-python-import_modules/2-args.py
| 596
| 4.375
| 4
|
#!/usr/bin/python3
import sys
from sys import argv
if __name__ == "__main__":
# leng argv starts in 1 with the name of the function
# 1 = function name
if len(argv) == 1:
print("{:d} arguments.".format(len(sys.argv) - 1))
# 2 = first argument if is equal to 2 it means just one arg
elif len(argv) == 2:
print("{:d} argument:".format(len(sys.argv) - 1))
else:
print("{:d} arguments:".format(len(sys.argv) - 1))
# range start in 1 because range start counting at 0
for i in range(1, len(argv)):
print("{:d}: {:s}".format(i, argv[i]))
| true
|
5253817eac722b8e72fa1eadb560f8b7c7d73250
|
weeksghost/snippets
|
/fizzbuzz/fizzbuzz.py
| 562
| 4.21875
| 4
|
"""Write a program that prints the numbers from 1 to 100.
But for multiples of three print 'Fizz' instead of the number.
For the multiples of five print 'Buzz'.
For numbers which are multiples of both three and five print 'FizzBuzz'."""
from random import randint
def fizzbuzz(num):
for x in range(1, 101):
if x % 3 == 0:
print '%d --> Fizz' % x
if x % 5 == 0:
print '%d --> Buzz' % x
if x % 3 == 0 and x % 5 == 0:
print '%d --> FizzBuzz' % x
def main():
fizzbuzz(randint(1, 100))
if __name__ == '__main__':
main()
| true
|
9a6e7b9ac1d4dceb8acf9e618cbe5dc63a92566e
|
roger1688/AdvancedPython_2019
|
/03_oop_init/hw1.py
| 1,039
| 4.125
| 4
|
class Node:
def __init__(self, val):
self.val = val
self.next = None
def print_linked_list(head):
now = head
while now:
print('{} > '.format(now.val),end='')
now = now.next
print() # print newline
# # Linked-list and print test
# n1 = Node(1)
# n2 = Node(3)
# n3 = Node(5)
# n1.next = n2
# n2.next = n3
#
# print_linked_list(n1)
# # expect 1 > 3 > 5 >
# Let's do a linked-list version stack
# Functions: push, pop, is_empty
class Stack:
def __init__(self):
self.head = None
def push(self, n):
# push n behind last one in self.head
pass
def pop(self):
# pop last one in self.head
return 0 # and return
def is_empty(self):
# check is linked-list empty
return True # return bool True or False
# # Stack test script
# l = [1, 3, 5]
# s = Stack()
# for n in l:
# s.push(n)
#
# s.pop()
# s.push('a')
# s.push('b')
# s.pop()
#
# while not s.is_empty():
# print(s.pop(), end='>')
# print()
# # ans is a > 3 > 1
| false
|
6305227ae30aa254fc14bbe65e646b3ecfc38224
|
guingomes/Linguagem_Python
|
/1.operadores_aritmeticos.py
| 385
| 4.125
| 4
|
#objetivo é criar um programa em que o usuário insere dois valores para a mensuração de operações diversas.
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
s = n1+n2
m = n1*n2
d = n1/n2
di = n1//n2
e = n1**n2
print('A soma é: {}, o produto é: {} e a divisão é: {:.3f}'.format(s, m, d))
print(f'A divisão inteira é: {di} e a potência: {e}')
| false
|
6724a08be69d5429e28bbf028f3cafe78337b8f2
|
zzfima/GrokkingAlgorithms
|
/Rec_sum_p81.py
| 357
| 4.125
| 4
|
def main():
print(SummArrayNumbers([3, 5, 2, 10]))
def SummArrayNumbers(arr):
"""Sum array of numbers in recursive way
Args:
arr (array): numerical array
Returns:
int: sum of numbers
"""
if len(arr) == 1:
return arr[0]
return arr[0] + SummArrayNumbers(arr[1:])
if __name__ == "__main__":
main()
| false
|
01af00a403187b6b3a2e68e0c1a3c82b475b8794
|
walleri18/Programming-tasks-Python-3.x
|
/Programming tasks/The first paragraph/Six tasks/Six tasks.py
| 1,177
| 4.21875
| 4
|
# Ипортирование мматематической библиотеки
import math
# Катеты прямоугольного треугольника
oneCathetus, twoCathetus = 1, 1
# Получение данных
oneCathetus = float(input("Введите первый катет прямоугольного треугольника: "))
twoCathetus = float(input("Введите второй катет прямоугольного треугольного: "))
oneCathetus = math.fabs(oneCathetus)
twoCathetus = math.fabs(twoCathetus)
# Вычисление гипотенузы прямоугольного треугольника
hypotenuse = math.sqrt((oneCathetus ** 2) + (twoCathetus ** 2))
# Вычисление площади прямоугольного треугольника
area = (oneCathetus * twoCathetus) / 2.0
# Вывод результата
print("\nГипотенуза прямоугольного треугольника: ", hypotenuse)
print("\nПлощадь прямоугольного треугольника: ", area)
input("\nДля завершения программы нажмите любую клавишу...")
| false
|
0077eae25b7f9731ffa985e5f7a8e079e417c27b
|
ScottBlaine/mycode
|
/fact/loopingch.py
| 808
| 4.28125
| 4
|
#!/usr/bin/env python3
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
Farm = farms[0]
for animals in Farm["agriculture"]:
print(animals)
InFarm = input("what farm are you interested in: NE Farm, W Farm, SE Farm?")
if InFarm == "W Farm":
Index = 1
elif InFarm == "NE Farm":
Index = 0
elif InFarm == "SE Farm":
Index = 2
else:
print("Invalid Value")
for animals in farms[Index]["agriculture"]:
print(animals)
print()
for animals in farms[Index]["agriculture"]:
if animals != "carrots" :
if animals != "celery":
print(animals)
| false
|
33d66808b44b182de3a9978dee9a8e88ce2d8b83
|
kranthikiranm67/TestWorkshop
|
/question_03.py
| 1,044
| 4.1875
| 4
|
#question_03 =
"""
An anagram I am
Given two strings s0 and s1, return whether they are anagrams of each other. Two words are anagrams when you can rearrange one to become the other. For example, “listen” and “silent” are anagrams.
Constraints:
- Length of s0 and s1 is at most 5000.
Example 1:
Input:
s0 = “listen”
s1 = “silent”
Output:
True
Example 2:
Input:
s0 = “bedroom”
s1 = “bathroom”
Output:
False
Write your code here
"""
# my own code with new functions
def isanagram(x,s1):
if(s1.find(x)==-1):
return 0
else:
return 1
def anagram(s0,s1):
length = len(s0)
count=0
for x in s0:
if(isanagram(x,s1)==1):
count = count+1
if(count==length):
print('TRUE')
else:
print('FALSE')
s0 = input()
s1 = input()
anagram(s0,s1)
#using counter
from collections import Counter
def anagram1(input1, input2):
return Counter(input1) == Counter(input2)
input1 = 'abcd'
input2 = 'dcab'
print(anagram1(input1, input2))
| true
|
26c06e9f868010768bdc7c7248cd1bf69032b1c4
|
AlenaRyzhkova/CS50
|
/pset6/sentimental/caesar.py
| 628
| 4.21875
| 4
|
from cs50 import get_string
import sys
# 1. get the key
if not len(sys.argv)==2:
print("Usage: python caesar.py <key>")
sys.exit(1)
key = int(sys.argv[1])
# 2. get plain text
plaintext = get_string("Please, enter a text for encryption: ")
print("Plaintext: " + plaintext)
# 3. encipter
ciphertext=""
for c in plaintext:
if c.isalpha()==True:
if c.isupper()==True:
p = chr((ord(c) - ord('A') + key)%26 + ord('A'))
else:
p = chr((ord(c) - ord('a') + key)%26 + ord('a'))
else:
p=c
ciphertext+=p
print()
# 4. print ciphertext
print("Ciphertext: " + ciphertext)
| true
|
17e7494fcbb225659e4e6add6d0f4874fdf87f59
|
dannslima/MundoPythonGuanabara
|
/MUNDO3/ex072.py
| 561
| 4.25
| 4
|
#Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso,
# de zero até vinte.
#Seu programa deverá ler um numero pelo teclado (entre 0 e 20) e motra-lo por extenso.
cont = ('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze','doze',
'treze','quatorze','quinze','dezesseis','dezessete','dezoito','dezenovo','vinte')
while True:
num = int(input('Digite um numero de 0 a 20 '))
if 0<= num <= 20:
break
print('Tente novamente')
print(f' Você digitou o número {cont[num]}')
| false
|
96e2e0d4ccfdb550673860199813c5467b83fe9f
|
rmedalla/5-2-18
|
/Calculator.py
| 429
| 4.1875
| 4
|
first_number = int(input("Enter first number: "))
math_operation = input("Choose an operand +, -, *, /: ")
second_number = int(input("Enter second number: "))
if math_operation == "+":
print(first_number + second_number)
if math_operation == "-":
print(first_number - second_number)
if math_operation == "*":
print(first_number * second_number)
if math_operation == "/":
print(first_number / second_number)
| false
|
df9a22117bd98acc6880792e5c3c0273f270067d
|
umasp11/PythonLearning
|
/polymerphism.py
| 1,482
| 4.3125
| 4
|
#polymorphism is the condition of occurrence in different forms. it uses two method overRiding & overLoading
# Overriding means having two method with same name but doing different tasks, it means one method overrides the other
#Methd overriding is used when programmer want to modify the existing behavior of a method
#Overriding
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,x,y):
print('multiplication', x*y)
obj= mult()
obj.result(5,6)
#Using superclass method we can modify the parent class method and call it in child class
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,a,b):
super().result(10,11)
print('multiplication', a*b)
obj= mult()
obj.result(10,20)
#Overloading: we can define a method in such a way that it can be called in different ways
class intro():
def greeting(self,name=None):
if name is not None:
print('Hello ', name)
if name is None:
print('no input given')
else:
print('Hello Alien')
obj1= intro()
obj1.greeting('Umasankar')
obj1.greeting(None)
#Ex2
class calculator:
def number(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
s=a+b+c
elif a!=None and b!= None:
s=a+b
else:
s= 'enter atlest two number'
return s
ob=calculator()
print(ob.number(10,))
| true
|
62c33ddc7ddc1daba876dd0422432686fcf361eb
|
umasp11/PythonLearning
|
/Threading.py
| 890
| 4.125
| 4
|
'''
Multitasking: Execute multiple task at the same time
Processed based multitasking: Executing multi task at same time where each task is a separate independent program(process)
Thread based multitasking: Executing multiple task at the same time where each task is a separate independent part of the same program(process). Each independent part is called thread.
Thread: is a separate flow of execution. Every thread has a task
Multithreading: Using multiple thread in a prhram
once a thread is created, it should be started by calling start method: t= Thread(target=fun, args=()) then t.start()
'''
from threading import Thread
def display(user):
print('hello', user)
th=Thread(target=display, args=('uma',))
th.start()
#Example: thread in loop
def show(a,b):
print('hello number', a,b)
for i in range(3):
t=Thread(target=show, args=(10,20))
print('hey')
t.start()
| true
|
24cda752498f51e747e869109f81da988089ca5a
|
developerhat/project-folder
|
/oop_practice.py
| 608
| 4.125
| 4
|
#OOP Practice 04/08/20
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@patgo.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('pat','go',300000)
emp_2 = Employee('xavier', 'braxis',15000)
#emp_1.first = "Pat"
#emp_1.last = "G"
#emp_1.email = 'pat.g@patrickgo.com'
#emp_1.pay = '300,000'
#emp_2.first = "Pet"
#emp_2.last = "f"
#emp_2.email = 'patooly'
#emp_2.pay = '20,000'
print(Employee.fullname(emp_2))
print(emp_2.fullname())
| false
|
116936cad73564abb9355199f5c8604d0b0bb8e7
|
girish75/PythonByGireeshP
|
/pycode/Quesetion1assignment.py
| 925
| 4.40625
| 4
|
# 1. Accept user input of two complex numbers (total 4 inputs, 2 for real and 2 for imaginary part).
# Perform complex number operations (c1 + c2, c1 - c2, c1 * c2)
a = int(input("For first complex number, enter real number"))
b = int(input("For first complex number, enter imaginary number"))
a1 = int(input("For second complex number, enter real number"))
b1 = int(input("For second complex number, enter imaginary number"))
c1 = complex(a,b)
print(c1)
c2 = complex(a1,b1)
print(c2)
print("Addition of two complex number =", c1 + c2)
#Subtraction
print("Subtraction of two complex number =", c1 - c2)
#Multiplication
print("Multiplication of two complex number =", c1 * c2)
#Division
print("Division of two complex number =", c1 / c2)
c = (3 + 6j)
print('Complex Number: Real Part is = ', c. real)
print('Complex Number: Imaginary Part is = ', c. imag)
print('Complex Number: conjugate Part = ', c. conjugate())
| true
|
ac235a932c259aac16a2a47fe0a45f9255e8a6f0
|
girish75/PythonByGireeshP
|
/pythonproject/FirstProject/jsong.py
| 1,813
| 4.3125
| 4
|
import json
'''
The Json module provides an easy way to encode and decode data in JSON
Convert from Python to JSON:
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
convert Python objects of the following types, into JSON strings: dict, list
tuple, string, int
float, True, False
None
'''
data = {"Name": "Girish",
"Shares": 100,
"Price": 540}
# convert into JSON:
json_str = json.dumps(data)
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
# the result is a JSON string:
print(json_str)
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann", "Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# Use the indent parameter to define the numbers of indents:
print(json.dumps(x, indent=4)) # Very useful.
# Use the separators parameter to change the default separator:
print(json.dumps(x, indent=4, separators=("|| ", " = ")))
# Order the Result
# Use the sort_keys parameter to specify if the result should be sorted or not:
print("New Dict = ", json.dumps(x, indent=4, sort_keys=True))
# ==============================================================
# Parse JSON - Convert from JSON to Python
# If you have a JSON string, you can parse it by using the json.loads() method.
# The result will be a Python dictionary.
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
| true
|
2196af2ef6617fbba8292dda5aed2649e1aac0a3
|
himal8848/Data-Structures-and-Algorithms-in-Python
|
/bubble_sort.py
| 315
| 4.1875
| 4
|
#Bubble Sort in Python
def bubble_sort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
list = [23,12,8,9,25,13,6]
result = bubble_sort(list)
print(list)
| false
|
75260678d000751037a56f69e517b253e7d82ad9
|
aasmith33/GPA-Calculator
|
/GPAsmith.py
| 647
| 4.1875
| 4
|
# This program allows a user to input their name, credit hours, and quality points. Then it calculates their GPA and outputs their name and GPA.
import time
name = str(input('What is your name? ')) # asks user for their name
hours = int(input('How many credit hours have you earned? ')) # asks user for credit hours earned
points = int(input('How many quality points do you have? ')) # asks user for amount of quality points
gpa = points / hours # calculates GPA
gpa = round(gpa, 2) #rounds gpa 2 decimal places
print ('Hi ' + str(name) + '. ' + 'Your grade point average is ' + str(gpa) + '.') # displays users name and GPA
time.sleep(5)
| true
|
eaa7fec6da4273925a0cb7b68c910a729bf26f3c
|
Yaguit/lab-code-simplicity-efficiency
|
/your-code/challenge-2.py
| 822
| 4.15625
| 4
|
"""
The code below generates a given number of random strings that consists of numbers and
lower case English letters. You can also define the range of the variable lengths of
the strings being generated.
The code is functional but has a lot of room for improvement. Use what you have learned
about simple and efficient code, refactor the code.
"""
import random
import string
def StringGenerator():
a = int(input('Minimum length: '))
b = int(input('Maximum length: '))
n = int(input('How many strings do you want? '))
list_of_strings = []
for i in range(0,n):
length = random.randrange(a,b)
char = string.ascii_lowercase + string.digits
list_of_strings.append(''.join(random.choice (char) for i in range(length)))
print(list_of_strings)
StringGenerator()
| true
|
59a5e4e86c2ccfd9b33ca254a220754fe981ebf7
|
newkstime/PythonLabs
|
/Lab07/Lab07P4.py
| 2,277
| 4.1875
| 4
|
def main():
numberOfLabs = int(input("How many labs are you entering?"))
while numberOfLabs <= 0:
print("Invalid input")
numberOfLabs = int(input("How many labs are you entering?"))
labScores = []
i = 0
while i < numberOfLabs:
score = float(input("Enter a lab score:"))
labScores.append(score)
i += 1
print("Lab scores:", labScores)
numberOfTests = int(input("How many tests are you entering?"))
while numberOfTests <= 0:
print("Invalid input")
numberOfTests = int(input("How many tests are you entering?"))
testScores = []
i = 0
while i < numberOfTests:
score = float(input("Enter a test score:"))
testScores.append(score)
i += 1
print("Test scores:", testScores)
print("The default weight for scores is 50% labs and 50% tests.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
while weightSelection != "c" and weightSelection != "d":
print("Invalid input.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
if weightSelection == "c":
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
while labWeight < 0:
print("Invalid input.")
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
while testWeight < 0:
print("Invalid input.")
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
grade_calculator(labScores, testScores, labWeight, testWeight)
else:
grade_calculator(labScores, testScores)
def grade_calculator(labScores, testScores, labWeight = 50, testWeight = 50):
labAverage = sum(labScores) / len(labScores)
print("Lab Average:", labAverage)
testAverage = sum(testScores) / len(testScores)
print("Test Average:", testAverage)
courseGrade = (labAverage * (labWeight/100)) + (testAverage * (testWeight/100))
print("Course Grade:", courseGrade)
main()
| true
|
842938b66f413e4a260395823d59a0a589bbdecf
|
newkstime/PythonLabs
|
/Lab03 - Selection Control Structures/Lab03P2.py
| 824
| 4.21875
| 4
|
secondsSinceMidnight = int(input("Please enter the number of seconds since midnight:"))
seconds = '{:02}'.format(secondsSinceMidnight % 60)
minutesSinceMidnight = secondsSinceMidnight // 60
minutes = '{:02}'.format(minutesSinceMidnight % 60)
hoursSinceMidnight = minutesSinceMidnight // 60
if hoursSinceMidnight < 24 and hoursSinceMidnight >= 12:
meridiem = "PM"
hours = hoursSinceMidnight - 12
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
elif hoursSinceMidnight < 12:
meridiem = "AM"
hours = hoursSinceMidnight
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
else:
print("The input seconds exceeds the number of seconds in a single day.")
| true
|
762f0115352b4b776ece45f8d5998b5ec06cd2ea
|
M-Karthik7/Numpy
|
/main.py
| 2,932
| 4.125
| 4
|
Numpy Notes
Numpy is faster than lists.
computers sees any number in binary fromat
it stores the int in 4 bytes ex : 5--> 00000000 00000000 00000000 00000101 (int32)
list is an built in int type for python it consists of 1) size -- 4 bytes
2) reference count -- 8 bytes
3) object type -- 8 bytes
4) object value -- 8 bytes
since numpy uses less bytes of memory it is faster than lists.
Another reason for numpy is faster than list is it uses contiguous memory. contiguous memory -- continues memory.
benefits :
->SIMD Vector processing
SIMD-Single Instruction Multiple Data.
->Effective cache utilization
lists | numpy
|
-> List can perform |-> Numpy can perforn insertion Deletion
insertion,delection | , appending , concatenation etc. we can perform lot more actions here.
appending,concatenation |
ex : | ex :
a=[1,3,5] | import numpy as np
b=[1,2,3] | a=np.array([1,3,5])
a*b = ERROR | b=np.array([1,2,3])
| c=a*b
| print(c)
|
| o/p : [1,6,15]
Applications of Numpy?
-> we can do maths with numpy. (MATLAB Replacement)
-> Plotting (Matplotlib)
-> Backend ( Pandas , Connect4 , Digital Photography)
-> Machine Learing.
Codes.
1) input
import numpy as np
a=np.array([1,2,3])
print(a)
1) o/p
[1 2 3] (one dimentional array)
2) input
b=np.array([[9.0,3.9,4],[6.0,5.0,4.0]])
print(b)
2) 0/p
[[9. 3.9 4. ] ( both the array inside must be equal or else it will give error )
[6. 5. 4. ]] --> Two dimentional array.
3) input
#To get dimension.
->print(a.ndim)
n-number,dim-dimention
3) o/p
1
4) input
# To get shape.
print(b.shape)
print(a.shape)
4) o/p
(2, 3) # { 2 rows and 3 columns }
(3,) # { 1 row and 3 columns }
5) input
# to get type.
print(a.dtype)
d-data,type
5) o/p
int32
6) input
to get size.
print(a.itemsize)
6) o/p
4 ( because 4 * 8 = 32 ) 8 - bytes
7) input
note :
we can specify the dtype in the beginning itself ex:
a=np.array([2,3,4],dtype='int16')
print(a.itemsize)
7) o/p
2 (because 2 * 8 = 16 ) 8 - bytes
8) input
# to get total size.
a=np.array([[2,5,4],[3,5,4]])
print(a.nbytes) # gets total size.
print(a.size * a.itemsize) # gets the total size.
8) o/p
24
24
9) input
#to get specific element [row,column]
print(a)
print(a[1,2]) or print(a[-1,-1]) '-' Refers to reverse indexing.
o/p
[[2 5 4]
[3 5 4]]
( indexing strats from 0 so a[1,2] means 2st row and 3rd column which is 4. )
4
input
#to get specific row only.
print(a[0:1])
o/p
[2 5 4]
input
#to get specific column.
print(a[:,2])
o/p
[4 4]
| true
|
9344dfc77da748a5bcfc5c2eac7a1cd0b0e810f3
|
Panda-ing/practice-py
|
/python_course/pentagram/pentagram_v3.0.py
| 573
| 4.25
| 4
|
"""
作者:xxx
功能:五角星绘制
版本:3.0
日期:17/6/2020
新增功能:加入循环操作绘制不同大小的图形
新增功能:使用迭代绘制不同大小的图形
"""
import turtle
def draw_pentagram(size):
count = 1
while count <= 5:
turtle.forward(size)
turtle.right(144)
count = count + 1
def main():
"""
主函数
"""
size = 50
while size <= 100:
draw_pentagram(size)
size += 10
turtle.exitonclick()
if __name__ == '__main__':
main()
| false
|
1ca0d3089cf33131b408c6f11ff4ec813a02f6f4
|
chengyin38/python_fundamentals
|
/Fizz Buzz Lab.py
| 2,092
| 4.53125
| 5
|
# Databricks notebook source
# MAGIC %md
# MAGIC # Fizz Buzz Lab
# MAGIC
# MAGIC * Write a function called `fizzBuzz` that takes in a number.
# MAGIC * If the number is divisible by 3 print `Fizz`. If the number is divisible by 5 print `Buzz`. If it is divisible by both 3 and 5 print `FizzBuzz` on one line.
# MAGIC * If the number is not divisible by 3 or 5, just print the number.
# MAGIC
# MAGIC HINT: Look at the modulo (`%`) operator.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def fizzBuzz(i):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
# COMMAND ----------
# MAGIC %md
# MAGIC This function expects a numeric type. If it receives a different type, it will throw an error.
# MAGIC
# MAGIC * Add a check so that if the input to the function is not numeric (either `float` or `int`) print `Not a number`.
# MAGIC
# MAGIC HINT: Use the `type()` function.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def typeCheckFizzBuzz(i):
if type(i) == int or type(i) == float:
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
# COMMAND ----------
# MAGIC %md But what if the argument passed to the function were a list of values? Write a function that accepts a list of inputs, and applies the function to each element in the list.
# MAGIC
# MAGIC A sample list is provided below to test your function.
# COMMAND ----------
my_list = [1, 1.56, 3, 5, 15, 30, 50, 77, "Hello"]
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def listFizzBuzz(my_list):
for i in my_list:
if (type(i) == int) or (type(i) == float):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
listFizzBuzz(my_list)
| true
|
a85d09e57b7a1e7fdaa8055003c922b494b7e437
|
angelfaraldo/intro_python_music
|
/1-01_crear-y-ejecutar-programas.py
| 1,424
| 4.46875
| 4
|
"""
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
"1-01_crear-y-ejecutar-programas"
contenidos: print(), comentarios, input(), variables, string concatenation
"""
# PRINT y CADENAS
print("hola, chicas y chicos!")
print("")
print('Estamos utilizando la función "print" para imprimir texto en la consola.')
# COMMENTS
# es bueno introducir comentarios para explicar vuestro código, documentar dudas, etc.
# el carácter "\n" es "newline", y crea una línea en blanco después de la cadena.
print("Espero que durante esta semana aprendáis cosas interesantes,\ny que os resulte entretenido.")
# INPUT
# aquí acabamos de concatenar dos strings ("cadenas", en castellano)
input("Hola, Cómo te llamas?")
print("Encantado")
# VARIABLES (almacenamiento)
# convenciones para llamar variables
mi_nombre = input("Hola, Cómo te llamas?")
# concatenación de cadenas
print("Mucho gusto, " + mi_nombre)
# tipos de data: int, float, strings, boolean
type(mi_nombre)
edad = 40
type(edad)
temperatura = 35.7
type(temperatura)
soltero = True
type(soltero)
# type casting
# nos sirve para convertir un tipo en otro
# esto es útil, por ejemplo para imprimir en la consola valores numéricos
edad = str(edad)
print("Hola, me llamo " + edad)
# o con una f-string
print("hola, me llamo {mi_nombre}, y tengo {edad} años.")
| false
|
d9a10876de3734ff92d0aa77aff01c8fe5f280f8
|
maslyankov/python-small-programs
|
/F87302_L3_T1.py
| 550
| 4.28125
| 4
|
# Encrypt a string using Cesar's cipher.
import sys
plain = sys.argv[1]
key = int(sys.argv[2])
translated = ''
for i in plain:
if i.isalpha():
num = ord(i)
num += key
if i.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif i.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += i
print translated
| false
|
78c81da0381174869334638036a3d11d5bb493a0
|
suntyneu/test
|
/test/类Class/6、析构函数.py
| 915
| 4.15625
| 4
|
"""
析构函数:__del__(): 释放对象时候自动调用
"""
class Person(object):
def run(self):
print("run")
def eat(self, food):
print("eat" + food)
def say(self):
print("Hello!my name is %s,I am %d years old" % (self.name, self.age))
def __init__(self, name, age, height, weight): # 可以有其他的参数列表
# print(name, age, height, weight)
self.name = name # self 表示要实例化对象的那个对象
self.age = age
self.height = height
self.weight = weight
def __del__(self):
print("这里是析构函数")
per = Person("tom", 20, 160, 70)
# 释放对象
# del per # 对象释放以后不能再访问
# print(per.age)
# 在函数里定义的对象,会在函数结束时自动释放,用来减少内存空间的浪费
def func():
per2 = Person("aa", 1, 1, 1)
func()
| false
|
065abbd254823c5bd5cfdcc7a14a5b66b36441fa
|
suntyneu/test
|
/for语句.py
| 733
| 4.1875
| 4
|
"""
for 语句
格式:
for 变量名 in 集合:
语句
逻辑:按顺序取 "集合" 中的每个元素,赋值给 "变量"
在执行语句。如此循环往复,直到取完“集合”中的元素截止。
range([start,]end[,step]) 函数 列表生成器 start 默认为0 step 步长默认为1
功能:生成数列
for i in [1, 2, 3, 4, 5]:
print(i)
"""
a = range(12)
print(a)
for x in range(12):
print(x)
for y in range(2, 20, 2):
print(y)
# enumerate 同时指定下标和元素
for index, m in enumerate([1, 2, 3, 4, 5]): # index, m = 下标,元素
print(index, m)
# for 实现1+2+3+...100的和
sum = 0
for n in range(1, 101):
sum += n
print(sum)
| false
|
634ec7c51e7db7cdc6a46c67478617c4f8d1748c
|
suntyneu/test
|
/面向对象/练习.py
| 916
| 4.1875
| 4
|
"""
公路(Road):
属性:公路名称,公路长度
车 (car):
属性:车名,时速
方法:1.求车名在那条公路上以多少时速行驶了都吃,
get_time(self,road)
2.初始化车属性信息__init__方法
3、打印显示车属性信息
"""
class Road(object):
def __init__(self, road_name, road_len):
self.road_name = road_name
self.road_len = road_len
print(self.road_name, self.road_len)
class Car(object):
def __init__(self, car_name, speed):
self.car_name = car_name
self.speed = speed
# print(self.car_name, self.speed)
def __str__(self):
return "%s-%d" % (self.car_name, self.speed)
def get_time(self):
pass
r = Road("泰山路", "2000") # r和road指向同一个地址空间
golf = Car("高尔夫", 50)
print(golf)
#Car.get_time(1000)
Road.road_len
Car.speed
| false
|
f93465e46e7201df11fcd754cf9bcffeb9fe17f1
|
suntyneu/test
|
/函数/装饰器.py
| 2,659
| 4.15625
| 4
|
"""
装饰器
概念:一个闭包,把一个函数当成参数,返回一个替代版的函数。
本质上就是一个返回函数的函数
"""
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("*******************")
func()
return inner
# f 是函数func1的加强版本
f = outer(func1)
f()
"""
那么,函数装饰器的工作原理是怎样的呢?假设用 funA() 函数装饰器去装饰 funB() 函数,如下所示:
纯文本复制
#funA 作为装饰器函数
def funA(fn):
#...
fn() # 执行传入的fn参数
#...
return '...'
@funA
def funB():
#...
实际上,上面程序完全等价于下面的程序:
def funA(fn):
#...
fn() # 执行传入的fn参数
#...
return '...'
def funB():
#...
funB = funA(funB)
通过比对以上 2 段程序不难发现,使用函数装饰器 A() 去装饰另一个函数 B(),其底层执行了如下 2 步操作:
将 B 作为参数传给 A() 函数;
将 A() 函数执行完成的返回值反馈回 B。
"""
# funA 作为装饰器函数
def funA(fn):
print("C语言中文网")
fn() # 执行传入的fn参数
print("http://c.biancheng.net")
return "装饰器函数的返回值"
@funA
def funB():
print("学习 Python")
print(funB)
"""
显然,被“@函数”修饰的函数不再是原来的函数,而是被替换成一个新的东西(取决于装饰器的返回值),
即如果装饰器函数的返回值为普通变量,那么被修饰的函数名就变成了变量名;
同样,如果装饰器返回的是一个函数的名称,那么被修饰的函数名依然表示一个函数。
实际上,所谓函数装饰器,就是通过装饰器函数,在不修改原函数的前提下,来对函数的功能进行合理的扩充。
"""
"""
带参数的函数装饰器
在分析 funA() 函数装饰器和 funB() 函数的关系时,细心的读者可能会发现一个问题,
即当 funB() 函数无参数时,可以直接将 funB 作为 funA() 的参数传入。
但是,如果被修饰的函数本身带有参数,那应该如何传值呢?
比较简单的解决方法就是在函数装饰器中嵌套一个函数,该函数带有的参数个数和被装饰器修饰的函数相同。例如:
"""
print("last")
def funA(fn):
# 定义一个嵌套函数
def say(arc):
print("Python教程:", arc)
say(arc)
return fn
@funA
def funB(arc):
print("funB():", arc)
funB("http://c.biancheng.net/python")
| false
|
77091f08b893364629e2d7170dbf1aeffe5fab5a
|
Gangamagadum98/Python-Programs
|
/sample/Calculator.py
| 451
| 4.15625
| 4
|
print("Enter the 1st number")
num1=int(input())
print("Enter the 2nd number")
num2=int(input())
print("Enter the Operation")
operation=input()
if operation=="+":
print("the addition of two numbers is",num1+num2)
elif operation == "-":
print("the addition of two numbers is", num1 - num2)
print("the asubstraction of two numbers is", num1 - num2)
print("enter the valid input")
| true
|
6f4786334da4a577e81d74ef1c58e7c0691b82b9
|
Obadha/andela-bootcamp
|
/control_structures.py
| 354
| 4.1875
| 4
|
# if False:
# print "it's true"
# else:
# print "it's false"
# if 2>6:
# print "You're awesome"
# elif 4<6:
# print "Yes sir!"
# else:
# print "Okay Maybe Not"
# for i in xrange (10):
# if i % 2:
# print i,
# find out if divisible by 3 and 5
# counter = 0
# while counter < 5:
# print "its true"
# print counter
# counter = counter + 1
| true
|
eb65ff92ef8086781e3657ca6f543dc2edadc228
|
ArielAyala/python-conceptos-basicos-y-avanzados
|
/Unidad 4/Listas.py
| 737
| 4.21875
| 4
|
numeros = [1, 2, 3, 4, 5]
datos = [5, "cadena", 5.5, "texto"]
print("Numeros", numeros)
print("Datos", datos)
# Mostramos datos de la lista por índice
print("Mostramos datos de la lista por índice :", datos[-1])
# Mostramos datos por Slicing
print("Mostramos datos por Slicing :", datos[0:2])
# Suma de Listas
listas = numeros + datos
print("La suma de las listas es :", listas)
# Mutabilidad
pares = [0, 2, 4, 5, 8, 10]
pares[3] = 6
print("Lista de pares, mutando un valor :", pares)
# Funciones o métodos de Listas
c = len(pares)
print("La función 'len' cuenta cuandos datos tiene la lista, ejemplo la lista pares :", c)
pares.append(12)
print("La función 'append' agregar un dato al final de la lista, ejemplo :", pares)
| false
|
e129e980c58a0c812c96d4d862404361765cbaa6
|
rafiqulislam21/python_codes
|
/serieWithValue.py
| 660
| 4.1875
| 4
|
n = int(input("Enter the last number : "))
sumVal = 0
#avoid builtin names, here sum is a built in name in python
for x in range(1, n+1, 1):
# here for x in range(1 = start value, n = end value, 1 = increasing value)
if x != n:
print(str(x)+" + ", end =" ") #this line will show 1+2+3+............
# end = " " means print will show with ount line break
sumVal = sumVal + x #this line will calculate sum 1+2+3+............
else:
print(str(x) + " = ", end=" ")#this line will show last value of series 5 = ............
sumVal = sumVal + x
print(sumVal) #this line will show final sum result of series............
| true
|
407ae0b9bd3004e0655b747f9f5ffda563ae8cae
|
anooptrivedi/workshops-python-level2
|
/list2.py
| 338
| 4.21875
| 4
|
# Slicing in List - more examples
example = [0,1,2,3,4,5,6,7,8,9]
print(example[:])
print(example[0:10:2])
print(example[1:10:2])
print(example[10:0:-1]) #counting from right to left
print(example[10:0:-2]) #counting from right to left
print(example[::-3]) #counting from right to left
print(example[:5:-1]) #counting from right to left
| true
|
ca7c8607e41db501f958a746028fb28040133d54
|
anooptrivedi/workshops-python-level2
|
/guessgame.py
| 460
| 4.125
| 4
|
# Number guessing game
import random
secret = random.randint(1,10)
guess = 0
attempts = 0
while secret != guess:
guess = int(input("Guess a number between 1 and 10: "))
attempts = attempts + 1;
if (guess == secret):
print("You found the secret number", secret, "in", attempts, "attempts")
quit()
elif (guess > secret):
print("Your guess is high, try again")
else:
print("Your guess is low, try again")
| true
|
8f8e8651d25ac8333692a5aa18bc26589f3fefe4
|
swaraj1999/python
|
/chap 8 set/set_intro.py
| 1,092
| 4.1875
| 4
|
# set data type
# unordered collection of unique items
s={1,2,3,2,'swaraj'}
print(s) # we cant do indexing here like:: s[1]>>wrong here,UNORDERED
L={1,2,4,4,8,7,0,9,8,8,0,9,7}
s2=set(L) # removes duplicate,unique items only
print(s2)
s3=list(set(L))
print(s3) # set to list
# add data
s.add(4)
s.add(10)
print(s)
# remove method
s.remove(1) #key not present in set,it will show error && IF ONE KEY IS PRESENT SEVERAL TIME,IT WILL NOT REMOVE
print(s)
# discard method
s.discard(4) # key not present in set,it will not set error
print(s)
# copy method
s1=s.copy()
print(s1)
#we cant store list tuple dictionary , we can store float,string
# we can use loop
for item in s:
print(item)
# we can use if else
if 'a' in s:
print('present')
else:
print('false')
# union && intersection
s1={1,2,3}
s2={4,5,6}
union_set=s1|s2 # union |
print(union_set)
intersection_set=s1&s2 # intersection using &
print(intersection_set)
| true
|
15c3309d2d94b809fccc1c1aaaa0cd66cdfd3954
|
swaraj1999/python
|
/chap 4 function/exercise11.py
| 317
| 4.375
| 4
|
# pallindrome function like madam,
def is_pallindrome(name):
return name == name[::-1]
#if name == reverse of name
# then true,otherwise false
# print(is_pallindrome(input("enter name"))) #not working for all words
print(is_pallindrome("horse")) #working for all words
| true
|
6d08454da7f8c3b15ec404505a6b77b9192e570e
|
breschdleng/Pracs
|
/fair_unfair_coin.py
| 1,307
| 4.28125
| 4
|
import random
"""
Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin
Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this
to a fair set of probabilities of 0.5 each
Solution: use bayes theorem flip the coins twice, if HH or TT then p(HH) == 0.49, p(TT) = 0.09, p(HT) = p(TH) = 0.21
1) flip two coins
2) if HH or TT repeat 1)
3) if different then heads if HT and tails if TH
Bayes' Theorem:
p(head on the first flip / diff results) = p(diff results / head on the first flip)*p(head on the first flip) / p(diff results)
p(diff results / head on the first flip) = p(tails/heads) = 0.3
p(heads on first flip) = 0.7
p(diff results) = p(HT)+p(TH) = 0.21*2
p(head on the first flip / diff results) = 0.3*0.7/0.42 = 0.5 ---answer for a fair coin flip!
"""
"""
1: heads
0: tails
"""
def unfair_coin():
p_heads = random.randint(0, 100)/100
if p_heads > 0.5:
return 1
else:
return 0
def unfair_to_fair(a,b):
p, q = unfair_coin()
print(b*p, a*q)
if __name__ == '__main__':
a = unfair_coin()
b = unfair_coin()
if a==b:
unfair_coin()
if a == 1:
print("heads")
else:
print("tails")
| true
|
5b6fc5dbfa1e7d85d4c80642ecb2822c23d5a6be
|
ShainaJordan/thinkful_lessons
|
/fibo.py
| 282
| 4.15625
| 4
|
#Define the function for the Fibonacci algorithm
def F(n):
if n < 2:
return n
else:
print "the function is iterating through the %d function" %(n)
return (F(n-2) + F(n-1))
n = 8
print "The %d number in the Fibonacci sequence is: %d" %(n, F(n))
| true
|
556ba64f9a8ac34fae4876547d44e2d990582742
|
DL-py/python-notebook
|
/001基础部分/015函数.py
| 1,548
| 4.34375
| 4
|
"""
函数:
"""
"""
函数定义:
def 函数名(参数):
代码
"""
"""
函数的说明文档:
1.定义函数说明文档的语法:
def 函数名(参数):
""" """内部写函数信息
代码
2.查看函数的说明文档方法:
help(函数名)
"""
# 函数说明文档的高级使用:
def sum_num3(a, b):
"""
求和函数sum_num3
:param a:参数1
:param b:函数2
:return:返回值
"""
return a + b
"""
返回值:可以返回多个值(默认是元组),也可以返回列表、字典、集合等
"""
"""
函数的参数:
1.位置参数:调用函数时根据函数定义的参数位置来传递参数
注意:传递和定义参数的顺序和个数必须一致
2.关键字参数:函数调用时,通过“键=值”形式加以指定,无先后顺序
注意:如果有位置参数时,位置参数必须在关键字参数的前面,但关键字参数之间不存在先后顺序
3.缺省参数(默认参数):用于定义函数,为参数提供默认值,调用时可不传入该默认参数的值。
注意:所有位置参数必须出现在默认参数前,包括函数定义和调用
"""
"""
不定长参数:
不定长参数也叫可变参数,用于不确定调用的时候会传递多少个参数(不传参数也可以)的场景,
此时可以用包裹位置参数,或包裹关键字参数,来进行参数传递,会显得非常方便。
包裹位置传递:*args
args是元组类型,则就是包裹位置传递
包裹关键字传递:**kwargs
"""
| false
|
8d852b9ba3fb4403dc783cc6c703c451ee0197f7
|
Pranav-Tumminkatti/Python-Turtle-Graphics
|
/Turtle Graphics Tutorial.py
| 979
| 4.40625
| 4
|
#Turtle Graphics in Pygame
#Reference: https://docs.python.org/2/library/turtle.html
#Reference: https://michael0x2a.com/blog/turtle-examples
#Very Important Reference: https://realpython.com/beginners-guide-python-turtle/
import turtle
tim = turtle.Turtle() #set item type
tim.color('red') #set colour
tim.pensize(5) #set thickness of line
tim.shape('turtle')
tim.forward(100) #turtle moves 100 pixels forward
tim.left(90) #turtle turns left 90 degrees
tim.forward(100)
tim.right(90)
tim.forward(100)
tim.penup() #lifts the pen up - turtle is moving but line is not drawn
tim.left(90)
tim.forward(100)
tim.right(90)
tim.pendown() #puts the pen back down
tim.forward(100)
tim.left(90)
tim.penup()
tim.forward(50)
tim.left(90)
tim.pendown()
tim.color('green') #changes the colour of the line to green
tim.forward(100)
#Making a new object named dave
dave = turtle.Turtle()
dave.color('blue')
dave.pensize(10)
dave.shape('arrow')
dave.backward(100)
dave.speed(1)
| true
|
b68c9db55ce6af793f0fc36505e12e741c497c31
|
sAnjali12/BsicasPythonProgrammas
|
/python/userInput_PrimeNum.py
| 339
| 4.1875
| 4
|
start_num = int(input("enter your start number"))
end_num = int(input("enter your end number"))
while (start_num<=end_num):
count = 0
i = 2
while (i<=start_num/2):
if (start_num):
print "number is not prime"
count = count+1
break
i = i+1
if (count==0 and start_num!=1):
print "prime number"
start_num = start_num+1
| true
|
3750e8f1fc7137dddda348c755655db99026922b
|
xilaluna/web1.1-homework-1-req-res-flask
|
/app.py
| 1,335
| 4.21875
| 4
|
# TODO: Follow the assignment instructions to complete the required routes!
# (And make sure to delete this TODO message when you're done!)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
"""Shows a greeting to the user."""
return f'Are you there, world? It\'s me, Ducky!'
@app.route('/frog')
def my_favorite_animal():
"""shows user my favorite animal"""
return f'Frogs are cute!'
@app.route('/dessert/<users_dessert>')
def favorite_dessert(users_dessert):
return f'How did you know I liked {users_dessert}'
@app.route('/madlibs/<adjective>/<noun>')
def mad_libs(adjective, noun):
return f'That is one {adjective} {noun}'
@app.route('/multiply/<number1>/<number2>')
def multiply(number1, number2):
if (number1.isdigit() == True) & (number2.isdigit() == True):
answer = int(number1) * int(number2)
return answer
else:
return "Invalid inputs. Please try again by entering 2 numbers!"
@app.route('/sayntimes/<word>/<number>')
def sayntimes(word, number):
if number.isdigit() == True:
string = ""
for word in range(int(number)):
string += str(word)
return
else:
return f"Invalid input. Please try again by entering a word and a number!"
if __name__ == '__main__':
app.run(debug=True)
| true
|
d4509f58c0d0721b86336e567946646df9431717
|
770847573/Python_learn
|
/Hello/错误和异常/抛出异常raise.py
| 391
| 4.15625
| 4
|
# 产生异常的形式
# 形式一:根据具体问题产生异常【异常对象】
try:
list1 = [12, 3, 43, 34]
print(list1[23])
except IndexError as e:
print(e)
#形式2:直接通过异常类创建异常对象,
# raise异常类(异常描述)表示在程序中跑出一个异常对象
try:
raise IndexError("下标越界~~~")
except IndexError as e:
print(e)
| false
|
7bbf2b2e59d035278ed1512201e70391af6c2e8a
|
770847573/Python_learn
|
/day19/4.多态的应用.py
| 1,664
| 4.4375
| 4
|
# 1.多态的概念
# a.
class Animal(object):
pass
class Cat(Animal):
pass
# 在继承的前提下,一个子类对象的类型可以是当前类,也可以是父类,也可以是祖先类
c = Cat()
# isinstance(对象,类型)判断对象是否是指定的类型
print(isinstance(c,object)) # True
print(isinstance(c,Animal)) # True
print(isinstance(c,Cat)) # True
a = Animal()
print(isinstance(a,Cat)) # False
# b.
class Animal(object):
def show(self):
print("父类")
class Cat(Animal):
def show(self):
print("cat")
class Dog(Animal):
def show(self):
print("dog")
class Pig(Animal):
def show(self):
print("pig")
# 定义a的时候不确定a的类型,所以不能确定a.show()调用的是哪个类中的函数
def func(a):
a.show()
c = Cat()
d = Dog()
p = Pig()
# 当运行程序的时候,才能确定a的类型
func(c)
func(d)
func(p)
# 2.多态的应用
# 好处:简化代码
# 需求:人喂养动物
class Animal(object):
def __init__(self,name):
self.name = name
def eat(self):
print("eating")
class Cat(Animal):
pass
class Dog(Animal):
pass
class Pig(Animal):
pass
class Person(object):
"""
def feed_cat(self,cat):
cat.eat()
def feed_dog(self,dog):
dog.eat()
def feed_pig(self,pig):
pig.eat()
"""
# 定义的时候ani的类型并不确定,只有当函数被调用,传参之后才能确定他的类型
def feed_animal(self,ani):
ani.eat()
per = Person()
c = Cat("小白")
d = Dog("旺财")
p = Pig("小黑")
per.feed_animal(c)
per.feed_animal(d)
per.feed_animal(p)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.