blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b76db936d110914c8a3cfa76411014253d940222 | YingZi18/1 | /rpsls.py | 2,048 | 4.1875 | 4 | #coding:gbk
"""
һСĿRock-paper-scissors-lizard-Spock
ߣӢ
ڣ2020.4.9
"""
import random
print("ӭʹRPSLSϷ")
print("ѡ:")
choice_name=input()
print("----------------")
def name_to_number(choice_name): #ѡתΪ
if choice_name=="":
return 4
elif choice_name=="ʯͷ":
return choice_name==0
elif choice_name=="ʷ":
return 1
elif choice_name=="ֽ":
return 2
elif choice_name=="":
return 3
else:
return "Error: No Correct Name"
player_choice_number=name_to_number(choice_name)
print("ѡΪ"+choice_name)
comp_number=int(random.randint(0,5) )#0,1,2,3,4
def number_to_name(comp_number):#תΪ
if comp_number==0:
return "ʯͷ"
elif comp_number==1:
return "ʷ"
elif comp_number==2:
return "ֽ"
elif comp_number==3:
return ""
elif comp_number==4:
return ""
print("ѡ"+str(number_to_name(comp_number)))
def rpsls(player_choice_number,comp_number):#ݹжӮ
if (player_choice_number==comp_number):
return"ͼһ"
elif (player_choice_number==2 and (comp_number==1 or 0)) or (player_choice_number==3 and (comp_number==1 or 2)):
return "Ӯ!"
elif (player_choice_number==0 and (comp_number==3 or 4)) or (player_choice_number==1 and (comp_number==4 or 0)) or (player_choice_number==4 and (comp_number==2 or 3)) :
return "Ӯ!"
elif (comp_number==2 and (player_choice_number==1 or 0)) or (comp_number==3 and (player_choice_number==1 or 2)):
return "Ӯ"
elif (comp_number==0 and (player_choice_number==3 or 4)) or (comp_number==1 and (player_choice_number==4 or 0)) or (comp_number==4 and (player_choice_number==2 or 3)):
return "Ӯ"
else:
return "Error: No Correct Name"
print (rpsls(player_choice_number,comp_number))#
| false |
cd8dbf34d866708f6f1953a387bc3519ac4bc05b | jmuguerza/adventofcode | /2017/day17.py | 1,976 | 4.15625 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PART 1
There's a spinlock with the following algorithm:
* starts with a circular buffer filled with zeros.
* steps forward some number, and inserts a 1 after the number
it stopped on. The inserted value becomes the current position.
* Idem, but inserts a 2. Rinse and repeat.
The algorithm is repeated 2017 times. What's the value after the
last inserted 2017 ?
PART 2
Get the value after 0, after the 50000000th insertion
"""
INPUT = 343
N_INSERTIONS_1 = 2017
N_INSERTIONS_2 = 50000000
def get_one_after(steps):
""" Get what's the number after the last insertion """
vector = [0]
inserting_pos = 0
for inserting in range(1, N_INSERTIONS_1+1):
initial_pos = inserting_pos + 1
inserting_pos = (initial_pos + steps) % inserting
vector = vector[:inserting_pos + 1] + [inserting] + vector[inserting_pos + 1:]
return vector[inserting_pos + 2]
def get_after_zero(steps):
""" Get what's the number after 0 after the last insertion """
vector = [0]
inserting_pos = 0
after_zero = -1
for inserting in range(1, N_INSERTIONS_2+1):
initial_pos = inserting_pos + 1
inserting_pos = (initial_pos + steps) % inserting
if not inserting_pos:
after_zero = inserting
return after_zero
def test(truth, check_function, *args):
for test_input, result in truth:
try:
my_result = check_function(test_input, *args)
assert(my_result == result)
except AssertionError:
print("Error trying to assert {}({}) == {} != {}".format(
check_function.__name__, test_input, my_result, result))
if __name__ == "__main__":
# Test for PART 1
GROUND_TRUTH = (
(3, 638),
)
test(GROUND_TRUTH, get_one_after)
# RUN
print('PART 1 result: {}'.format(get_one_after(INPUT)))
print('PART 2 result: {}'.format(get_after_zero(INPUT)))
| true |
fa2f83e4a96be139adcfa59660ebc96dd120a6fe | nihalgaurav/pythonprep | /MixedSeries.py | 1,203 | 4.4375 | 4 | """Consider the below series:
1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, ...
This series is a mixture of 2 series - all the odd terms in this series form a Fibonacci series
and all the even terms are the prime numbers in ascending order.
Write a program to find the Nth term in this series.
The value N is a Positive integer that should be read from STDIN.
The Nth term that is calculated by the program should be written to STDOUT.
Other than the value of Nth term, no other characters/strings or message should be written to STDOUT.
For example, when N = 14, the 14th term in the series is 17.
So only the value 17 should be printed to STDOUT."""
def FindNextPrime(prev):
prev += 1
while True:
for x in range(2, prev):
if prev % x == 0:
break
elif x == prev-1:
return(prev)
prev += 1
def FindNextFib(p1,p2):
return(p1+p2)
list = [1, 2, 1, 3]
N = int(input())
if N > 4:
for i in range(4, N):
# even = prime , odd = fibonacci
if (i+1)%2 == 0:
list.append(FindNextPrime(list[i-2]))
else:
list.append( FindNextFib(list[i-2],list[i-4]))
print(list[N-1])
| true |
c80b92dfa26817fc051fd4609230815fe1cfc8be | Dylandk10/fun_challenges | /python/palindrome_number.py | 632 | 4.25 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is palindrome while 123 is not.
examples
Input: x = 121
Output: true
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
xStr = str(x)
xStrReverse = xStr[::-1]
return xStr == xStrReverse
| true |
7d6065d6e222eaec66ef5c383e7442303b265a8b | zerolinux5/Python-Tutorials | /chapter1.py | 1,310 | 4.15625 | 4 | movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"]
print(movies[1])
"""
cast = ["Cleese", 'Palin', 'Jones', "Idle"]
print(cast)
print(len(cast))
print(cast[1])
cast.append("Gilliam")
print(cast)
cast.pop()
print(cast)
cast.extend(["Gilliam", "Chapman"])
print(cast)
cast.remove("Chapman")
print(cast)
cast.insert(0, "Chapman")
print(cast)
"""
movies.insert(1, 1975)
movies.insert(3, 1979)
movies.insert(5, 1983)
#print(movies)
fav_movies= ["The Holy Grail", "The Life of Brian"]
for each_flick in fav_movies:
print(each_flick)
movies2 = ["The Holy Grail", 1975, "Terry Jones & Terry Filliam", 91, ["Graham Chapman", ["Michael Palin", "John Cleese", "Terry Filliam", "Eric Idle", "Terry Jones"]]]
print(movies2[4][1][3])
print(movies2)
for each_item in movies2:
print(each_item)
"""
names = ['Michael', 'Terry']
print(isinstance(names, list))
num_names= len(names)
print(isinstance(num_names, list))
"""
for each_item in movies2:
if(isinstance(each_item, list)):
for nested_item in each_item:
if(isinstance(nested_item, list)):
for deeper_item in nested_item:
print(deeper_item)
else:
print(nested_item)
else:
print(each_item)
print("\n");
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)
print_lol(movies2)
| false |
8b0e54cf78a1a82c8ae92655723fc3b313e18185 | DauntlessDev/py-compilation | /Prime or not.py | 412 | 4.21875 | 4 | # Python program to check if the input number is prime or not
number = 123
if number > 1:
# check for factors
for i in range(2,number):
if (number % i) == 0:
print(number,"is not a prime number")
print(i,"times",number//i,"is",number)
break
else:
print(number,"is a prime number")
else:
print(number,"is not a prime number")
| true |
6b982842a841b71f48d49b9af48e75f4066ca224 | juriemaeac/Data-Structure-and-Algorithm | /Lab Exercise 1/DecimalToBinary.py | 414 | 4.3125 | 4 | num = int(input("Enter a decimal number: "))
#Empty string to hold the binary form of the number
b = ""
while num != 0:
if (num % 2) == 1:
b += "1"
else:
b += "0"
#this is equivalent to num = num // 2 ----- num/=2 results to decimal
#use double slash to result in integer
num//=2
#b[::-1] is used to reverse all the elements
b = b[::-1]
print("Binary equivalent: "+str(b))
| true |
959d40e7949962c427e5edb64a366133c119faf8 | juriemaeac/Data-Structure-and-Algorithm | /Lab Exercise 1/Palindrome.py | 556 | 4.40625 | 4 | '''
by Jurie Mae Castronuevo
from BSCOE 2-6
[November 22, 2020]
'''
import re
z = input("Enter a word: ")
x = z.lower()
#x[::-1] is used to reverse all the elements
#source lesson: https://jakevdp.github.io/PythonDataScienceHandbook/02.02-the-basics-of-numpy-arrays.html
#library that accepts word with some symbols and spaces only
# since some of names/ words are with symbols
if re.match(r"^[A-Za-z -.]+$", x):
y = x[::-1]
if x == y:
print(z, "is a palindrome")
else:
print(z, "is not a palindrome")
else:
print ("This is not a word")
| true |
8b2a5bed4207d1f5c8f63e857148d1faf7d92a59 | kg55555/pypractice | /Part 1/Chapter 6/exercise_6.6.py | 341 | 4.1875 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
'bob': '',
'joe': ''
}
for name, language in favorite_languages.items():
if language != '':
print(f"{name}, your favourite language is {language}")
else:
print(f"Please take our language poll, {name}!")
| false |
af63ebe4e641ab2b8ce18f8602a7a89a3ace4b27 | kg55555/pypractice | /Part 1/Chapter 6/exercise_6.11.py | 518 | 4.375 | 4 | tokyo = {'country': 'japan', 'population': 12338734, 'fact': 'Tokyo is beautiful!'}
vancouver = {'country': 'canada', 'population': 4829453, 'fact': 'Vancouver is cold!'}
new_york = {'country': 'usa', 'population': 7943854, 'fact': 'New York is busy!'}
cities = {'tokyo': tokyo, 'vancouver': vancouver, "new york": new_york}
for city, info in cities.items():
print(f"{city.title()} is located in the country of {info['country']}, and has a population of {info['population']}. A fun fact is that {info['fact']}")
| false |
241c25f337622ce86f3c8a246a7384869e025ad6 | kg55555/pypractice | /Part 1/Chapter 3/exercise_3.5.py | 487 | 4.125 | 4 | famous = ['steve jobs','bill gates', 'gandhi']
print(f"Hello {famous[0].title()}, I'd like to invite you to dinner with me!")
print(f"Hello {famous[1].title()}, I'd like to invite you to dinner with me!")
print(f"Hello {famous[2].title()}, I'd like to invite you to dinner with me!")
print(f"Oh no! {famous.pop().title()} is dead, so he can't make it to dinner, I'll invite Elon Musk instead")
famous.append("elon musk")
print(f"Hello {famous[2].title()}, I'd like to invite you to dinner with me!")
| true |
9fae3d11dd9fa50aeafba53bb0a5c1bb44861a21 | PAJADK/myPythonLektioner | /lektion5/chapter8-2.py | 975 | 4.1875 | 4 | def make_album(name, title, number_of_tracks=''):
if number_of_tracks:
album = {'artist_name': name, 'album_titel': title, 'tracks':number_of_tracks}
else:
album ={'artist_name': name, 'album_titel': title}
return album
albums = make_album('jime', 'henrikx')
print(albums)
albums = make_album('jime', 'henrikx', number_of_tracks=6)
print(albums)
def make_album(name, title, number_of_tracks=''):
if number_of_tracks:
album = {'artist_name': name, 'album_titel': title, 'tracks':number_of_tracks}
else:
album ={'artist_name': name, 'album_titel': title}
return album
while True:
print("(enter 'q' at any time to quit)")
artist_name = input("Name: ")
if artist_name == 'q':
break
album_name = input("Album name: ")
if artist_name == 'q':
break
albums = make_album(artist_name, album_name)
print(albums)
albums = make_album('jime', 'henrikx', number_of_tracks=6)
print(albums) | false |
e80b8a5f48ebca0f07d57f823bb6374c9d6baae3 | valemescudero/Python-Practice | /Class 1/04. Primality Test.py | 658 | 4.21875 | 4 | # Write a function that recieves a number and returns True when it's a prime number and False when it's not.
# Through a for loop check for the primality of numbers 1 to 20.
def is_prime(num):
if num == 1:
primality = False
else:
primality = True
if num > 2:
rang = (num ** 0.5)
rang = int(rang)
for i in range(rang):
if num % (i + 2) == 0:
print(num, "is divisible by", i + 2)
primality = False;
break
return primality
for i in range(20):
num = i + 1
primality = is_prime(num)
if primality == True:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
| true |
6262980f0a0d1083a33767d9efdb2cd7bc695cc4 | adarshrao007/Python_Assignment | /18.py | 971 | 4.125 | 4 | #Implement a calculator program for above using getopt.
import sys
import getopt
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a,b):
return a*b
def division(a,b):
return a/b
opts,args=getopt.getopt(sys.argv[1:],"a:o:b:",["num1=","operator=","num2="])
for key,value in opts:
if (key=='-a' or key=='--num1'):
num1=int(value)
print("first number is:",num1)
elif(key=='-o' or key=='--operator'):
operator=value
print("entered operator is :",operator)
elif(key=='-b' or key=='--num2'):
num2=int(value)
print("second number is:",num2)
else:
sys.exit();
if num1 and num2 and operator:
if(operator=='+'):
print("addition:",add(num1,num2))
elif(operator=='-'):
print("sub:",subtract(num1,num2))
elif(operator=='*'):
print("mul:",multiply(num1,num2))
elif(operator=='/'):
print("div:",division(num1,num2))
else:
print("enter valid operator")
| false |
79f798b37cf5b8e4af75ffdf6e6049a0bd247294 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo2/ex062.py | 2,704 | 4.125 | 4 | # Aula 14 - Estrutura de repetição while (Estrutura de repetição com teste lógico)
# Desafio 061 - Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos da
# progessão usando a estrutura while.
print('\nDesafio 062 - Super Progressão Aritmética v3.0\n')
numeroValido = 0
while numeroValido < 2:
numeroValido = 0
a1 = str(input('Primeiro termo da PA: ')).strip()
r = str(input('Razão da PA: ')).strip()
if a1.isnumeric():
numeroValido += 1
elif a1[0] == '-' and a1[1:].isnumeric():
numeroValido += 1
elif a1[0] == '-' and a1[1:a1.find('.')].isnumeric() and a1[(a1.find('.') + 1):].isnumeric():
numeroValido += 1
elif a1[0] == '-' and a1[1:a1.find('.')].isnumeric() and len(a1) == a1.find('.') + 1:
numeroValido += 1
elif a1[:a1.find('.')].isnumeric() and a1[(a1.find('.') + 1):].isnumeric():
numeroValido += 1
elif a1[:a1.find('.')].isnumeric() and len(a1) == a1.find('.') + 1:
numeroValido += 1
else:
print('\033[4;31mVOCÊ DIGITOU UM VALOR INVÁLIDO PARA O 1º TERMO DA PA. TENTE NOVAMENTE.\033[m\n')
if numeroValido == 1:
if r.isnumeric():
numeroValido += 1
elif r[0] == '-' and r[1:].isnumeric():
numeroValido += 1
elif r[0] == '-' and r[1:r.find('.')].isnumeric() and r[(r.find('.') + 1):].isnumeric():
numeroValido += 1
elif r[0] == '-' and r[1:r.find('.')].isnumeric() and len(r) == r.find('.') + 1:
numeroValido += 1
elif r[:r.find('.')].isnumeric() and r[(r.find('.') + 1):].isnumeric():
numeroValido += 1
elif r[:r.find('.')].isnumeric() and len(r) == r.find('.') + 1:
numeroValido += 1
else:
print('\033[4;31mVOCÊ DIGITOU UM VALOR INVÁLIDO PARA A RAZÃO DA PA. TENTE NOVAMENTE.\033[m\n')
a1 = float(a1)
r = float(r)
an = a1
i = 1
print('\nProgressão aritmética: ', end='')
while i < 11:
print('{}'.format(an), end=' ')
an += r
i += 1
maisTermos = '1'
while int(maisTermos) > 0:
maisTermos = str(input('\n\nQuantos outros termos a partir do último você deseja ver (Digite 0 para encerrar): '))
if maisTermos.isnumeric() and int(maisTermos) > 0:
print('\nContinuação da PA:', end=' ')
auxI = i
while i < (auxI + int(maisTermos)):
print('{}'.format(an), end=' ')
an += r
i += 1
elif not(maisTermos.isnumeric()):
print('\n\033[4;31mVOCÊ DIGITOU UMA LETRA OU UM NÚMERO NEGATIVO. TENTE NOVAMENTE.\033[m')
maisTermos = '1'
else:
print('\nObrigado por utilizar o programa :)')
| false |
15ed653c0cc88186fd582d9f4a4ae007e6bda8f3 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex028.py | 1,178 | 4.34375 | 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 ven-
# ceu ou perdeu.
from random import randint
from time import sleep
print('\nDesafio 028 - Jogo da Advinhação v.1.0')
numeroComputador = randint(0, 5)
print('\nVou pensar em um número entre 0 e 5...')
sleep(3)
numeroUsuario = str(input('\nEm qual número pensei: ')).strip()
if not(numeroUsuario.isnumeric()):
print('Você não digitou um valor numérico! Reinicie o programa e tente novamente.')
else:
numeroUsuario = int(numeroUsuario)
if not((numeroUsuario >= 0) and (numeroUsuario <= 5)):
print('Você não digitou um número entre 0 e 5! Reinicie o programa e tente novamente.')
else:
sleep(1)
print('\nPROCESSANDO...')
sleep(3)
if numeroUsuario == numeroComputador:
print('Parabéns, você venceu! Eu pensei no mesmo número que você.')
else:
print('Me desculpe, você perdeu! Eu pensei no número {}.'.format(numeroComputador))
| false |
b4dcf36c8a25b01cc3ab83a92919cfe7c82748f6 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex022.py | 842 | 4.46875 | 4 | # Desafio 022 - Crie um programa que leia o nome completo de uma pessoa e mostre:
# - O nome com todas as letras maiúsculas
# - O nome com todas as letras minúsculas
# - Quantas letras ao todo (sem considerar espaços)
# - Quantas letras têm o primeiro nome
print('Desafio 022 - Analisador de textos')
nome = str(input('\nQual é o seu nome? '))
print('\nNome com todas as letras maiúsculas: {}'.format(nome.strip().upper()))
print('Nome com todas as letras minúsculas: {}'.format(nome.strip().lower()))
print('Quantidade de letras que o nome possui (sem considerar espaços): {}'.format(len(nome.replace(' ', ''))))
nomeDividido = nome.split()
print('Quantidade de letras no primeiro nome ({}): {}'.format(nomeDividido[0], len(nomeDividido[0])))
# print('Quantidade de letras no primeiro nome: {}'.format(nome.strip().find(' ')))
| false |
3be6bb6b703becc5424664dc8bee033f932cfd70 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex005.py | 1,004 | 4.125 | 4 | # Desafio 005 - Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor
coresLetra = {
'padrao': '\033[m',
'vermelho': '\033[31m',
'verde': '\033[32m',
'azul': '\033[34m'
}
print('Desafio 005 - Antecessor e sucessor')
n = int(input('Digite um número inteiro: '))
print('\n')
print('O antecessor de ', end=''
'{}{}{} é {}{}{}.\n'.format(coresLetra['azul'],
n,
coresLetra['padrao'],
coresLetra['vermelho'],
n - 1,
coresLetra['padrao']))
print('O sucessor de ', end=''
'{}{}{} é {}{}{}.'.format(coresLetra['azul'],
n, coresLetra['padrao'],
coresLetra['verde'],
n + 1,
coresLetra['padrao']))
| false |
54d83e81f6d7eadc7ec2f6528e99eea296a2992b | NatanLisboa/python | /exercicios-cursoemvideo/Mundo2/ex037.py | 1,049 | 4.21875 | 4 | # Mundo 2 - Aula 12 - Condições Aninhadas
# Desafio 037 - Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base
# de conversão:
# - 1 para binário
# - 2 para octal
# - 3 para hexadecimal
print('\nDesafio 037 - Conversor de Bases Numéricas')
numeroInteiro = int(input('Digite um número inteiro: '))
print('\n1 para binário')
print('2 para octal')
print('3 para hexadecimal')
opcaoEscolhida = int(input('\nSelecione a base de conversão: '))
print('\n')
if opcaoEscolhida == 1:
numeroInteiroEmBinario = (bin(numeroInteiro))[2:]
print('{} = {}'.format(numeroInteiro, numeroInteiroEmBinario))
elif opcaoEscolhida == 2:
numeroInteiroEmOctal = (oct(numeroInteiro))[2:]
print('{} = {}'.format(numeroInteiro, numeroInteiroEmOctal))
elif opcaoEscolhida == 3:
numeroInteiroEmHexadecimal = (hex(numeroInteiro))[2:]
print('{} = {}'.format(numeroInteiro, numeroInteiroEmHexadecimal))
else:
print('Opção inválida inserida! Reinicie o programa e tente novamente.')
| false |
f7dfcf2fefc9d23c7487cf368d1858759f603265 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo3/ex080.py | 1,903 | 4.59375 | 5 | # Mundo 3 - Aula 17 - Variáveis Compostas - Listas
# Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma
# lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
print('\nExercício 80 – Lista ordenada sem repetições\n')
listaNumeros = []
for i in range(0, 5):
while True:
num = str(input(f'{i+1}º número: ')).strip()
if num == '':
print('\n\033[31mVALOR INVÁLIDO INSERIDO! POR FAVOR, DIGITE UM NÚMERO VÁLIDO.\033[m\n')
elif (num.isnumeric()) or \
(num[0] == '-' and num[1:].isnumeric()) or \
(num[0] == '-' and num[1:num.find('.')].isnumeric() and len(num) == num.find('.') + 1) or \
(num[0] == '-' and num[1:num.find('.')].isnumeric() and num[num.find('.') + 1:].isnumeric()) or \
(num[0:num.find('.')].isnumeric() and len(num) == num.find('.') + 1) or \
(num[0:num.find('.')].isnumeric() and num[num.find('.') + 1:].isnumeric()):
num = float(num)
break
else:
print('\n\033[31mVALOR INVÁLIDO INSERIDO! POR FAVOR, DIGITE UM NÚMERO VÁLIDO.\033[m\n')
if len(listaNumeros) == 0:
listaNumeros.append(num)
print(f'Elemento {listaNumeros[0]} adicionado no final da lista')
else:
for j in range(0, len(listaNumeros)):
if num <= listaNumeros[j]:
break
if num > listaNumeros[j] and j == len(listaNumeros) - 1:
listaNumeros.append(num)
print(f'Elemento {listaNumeros[len(listaNumeros) - 1]} adicionado no final da lista')
else:
listaNumeros.insert(j, num)
print(f'Elemento {listaNumeros[j]} adicionado na posição {j} da lista')
print(f'\n\nLista em ordem crescente: {listaNumeros}')
| false |
24bee83c3dc3cce9a72e336d3c7a5bb5867fd442 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex016.py | 456 | 4.15625 | 4 | # Desafio 016 - Crie um programa que leia um número real qualquer pelo teclado e mostre na tela a sua porção inteira.
# from math import trunc
print('Desafio 016 - Quebrando um número')
numeroReal = float(input('Digite um número real (com casas decimais): '))
print('\n', end='')
# print('O número {} tem a parte inteira {}'.format(numeroReal, trunc(numeroReal)))
print('O número {} tem a parte inteira {}'.format(numeroReal, int(numeroReal)))
| false |
1291f99844e533f595854aeeeef5c29e71fd8c8c | mazhewitt/python-training | /Day 3/week2_Lists_2.py | 736 | 4.53125 | 5 | ### Excercise 2 ###
# 2. Let's plan some shopping. We want to get some fruits, vegies and diary products:
fruits = ['Banana', 'Apple', 'Lemon', 'Orange']
vegies = ['Carrot', 'Pumpkin']
diary = ['Milk', 'Cheese', 'Butter']
# 2.1 Check how many product from each category we want to buy
# 2.2 Create one shopping list called basket with all the products
# 2.3 We forgot about cucumber - can you add it to the list of vegies?
# 2.4 Let's check what is in our basket now:
print(basket)
# Is cucumber in the basket? Can you explain why?
# We create one more list called sweets:
sweets = ['Chocolate', 'Biscuits']
# 2.5 Try to add sweets to the basket using append() and extend() methods. Do you see the difference?
| true |
a279637aee7839aa7c13a020144d76a47b92631d | anhnguyendepocen/Mphil | /POPE/func.py | 1,690 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
func.py
Purpose:
Playing with functions
Version:
1 First start
Date:
2019/08/27
Author:
Aishameriane Venes Schmidt
"""
###########################################################
### Imports
import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
###########################################################
### dY= emptyfunc(vX)
def fnPrint(argX, *args):
"""
Purpose:
Prints an argument and returns it to main()
Inputs:
argX argX is something
args (optional) args can be something or a list of somethings
Return value:
[argX, args] something, exactly the input
"""
#####################################################
# Question
# The argument in here is not a known thing, could be anything in fact.
#So how do I concile with the hungarian notation?
#####################################################
dRes= argX
for dA in args:
# dRes= dRes + dA
dRes = [dRes, dA]
return np.array(dRes)
###########################################################
### main
def main():
# Magic numbers
argX = 8.2
argY = [[8.2], ["a"]]
argA = 8.5
argB = 7.5
argC = 9.5
# Initialisation
resX = fnPrint(argX)
resY = fnPrint(argY)
resAB = fnPrint(argA, argB, argC)
# Output
print ("The argument is given by argX = ", resX)
print ("The argument is given by argY = ", resY)
print ("The argument is given by argAB = ", resAB)
###########################################################
### start main
if __name__ == "__main__":
main()
| true |
73097d41a3939d867dc82f3e1563e140bef10873 | ParthG-Gulati/Python-Day3 | /average.py | 340 | 4.15625 | 4 | # Average of five numbers
print("Enter five numbers to find average:")
a = int(input("Enter number1:"))
b = int(input("Enter number2:"))
c = int(input("Enter number3:"))
d = int(input("Enter number4:"))
e = int(input("Enter number5:"))
total = a + b + c + d + e
average = total / 5
print("Average of five numbers is:", average)
| false |
421c5d172261beb8aa1fa56fc237d13fb8672e3b | Anoosha16798/Python-Programs | /Binary-HexaDec-Converter.py | 939 | 4.15625 | 4 | print("Welcome to Binary-HexaDecimal Converter App!")
max_val = int(input("\n Compute the Binary and Hexa-Decimal values upto the following decimal numbers: "))
decimal = list(range(1,max_val+1))
binary = []
hexaDec = []
for num in decimal:
binary.append(bin(num))
hexaDec.append(hex(num))
print("The portion of the list you would like to access?")
low_range = int(input("Starting value? "))
max_range = int(input("End value? "))
print("\nDecimal Values")
for num in decimal[low_range+1:max_range]:
print(num)
print("\nBinary Values")
for num in binary[low_range+1:max_range]:
print(num)
print("\nHexa-Decimal Values")
for num in hexaDec[low_range+1:max_range]:
print(num)
input("\nPress Enter to print all the values from 1 to "+str(max_val)+".")
#print(f"{decimal} \t {binary} \t {hexaDec}")
for d,b,h in zip(decimal,binary,hexaDec):
print("Decimal \t Binary \t HexaDecimal")
print(d,"\t\t",b,"\t\t",h)
| false |
679f659f2cb83e2c9b4e2c33324c5e9afe16a692 | Anoosha16798/Python-Programs | /Favourite-Teacher-Program.py | 661 | 4.15625 | 4 | print("Welcome")
rank = []
rank.append(input("Enter the list of Teachers\n"))
rank.append(input("Enter the list of Teachers\n"))
rank.append(input("Enter the list of Teachers\n"))
rank.append(input("Enter the list of Teachers\n"))
rank.append(input("Enter the list of Teachers\n"))
print("This is your present rank of teachers:\n", rank)
print("This is your sorted list of teachers: \n", sorted(rank))
print("Your first two fav teachers: ", rank[:2])
print("Your first next two fav teachers: ", rank[2:4])
print("Your last fav teachers: ", rank[-1])
rank.insert(0,input("\nOpps"+rank[0]+"is no longer you fav teacher, Who is your fav teacher??"))
print(rank)
| false |
869fe2e3779ac48cd64c1deb595eaa1886929441 | MrCodemaker/python_work | /while/age.py | 814 | 4.28125 | 4 | """
Функция int() преобразует строковое представление числа в само число:
"""
age = input("How old are you? ")
# How old are you? 21
age = int(age)
age >= 18
# True
"""
В этом примере введенный текст 21 интерпретируется как строка,
но затем он преобразуется в числовое представление вызовом int().
Теперь Python может проверить условие:
сравнить переменную age (которая теперь содержит числовое значение 21) с 18.
Условие «значение age больше или равно 18» выполняется, и результат
проверки равен True.
"""
| false |
da03b97692eb1ec784171938e339fa68b2ca3a24 | JLL32/MBCP | /Python - fundamentals/UNIT 4: Functions/countchoice.py | 673 | 4.21875 | 4 | # Defining a countdown method
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
# Testing an input
countdown(5)
# Defining a countup method
def countup(n):
if n == 0:
print('Blastoff!')
elif n < 0:
print(n)
countup(n+1)
# Testing an input
countup(-5)
# Defining a countchoice method
def countchoice():
# takes user's input and cast it to an integer
n = int(input("please enter a number: "))
if n > 0:
countdown(n)
elif n < 0 :
countup(n)
else:
countdown(n)
# Calling the function countchoice
countchoice() | false |
146b1e0937b0b3decc261b8170024c8a9c44525a | JLL32/MBCP | /Python - fundamentals/UNIT 8: Dictionaries and Files/inverse.py | 1,012 | 4.4375 | 4 | ##### Create a dictionary where values are lists #####
people = {"names":["noura","amine"],"ages":[22,28],"profession":["Software Engineer", "Red Hat"]}
print(people)
# From Section 11.5 of:
# Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press.
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
##### Function after edits #####
def invert_dict_edited(d):
inverse = dict()
for key in d:
val = d[key]
for value in val: # iterate through values
if value not in inverse:
inverse[value] = [key]
else:
inverse[value].append(key)
return inverse
##### Test Functions #####
print(invert_dict(people)) # TypeError: unhashable type: 'list'
print(invert_dict_edited(people))
| true |
2bb0d8834b23146dbb2e204026452cb3e3f380e7 | joshua-scott/python | /ch9 Advanced datastructures.py | 1,630 | 4.3125 | 4 | # Task 1
# Basic lists
myList = [ "Blue", "Red", "Yellow", "Green" ]
print("The first item in the list is:", myList[0])
print("The entire list printed one at a time:")
for i in myList: print(i)
# Task 2
# Use lists to allow the user to:
# (1) add products, (2) remove items and (3) print the list and quit.
def main():
shoppingList = []
while True:
selection = getSelection()
if selection == 1:
addItem(shoppingList)
elif selection == 2:
removeItem(shoppingList)
elif selection == 3:
gracefulExit(shoppingList)
else:
print("Incorrect selection.")
def getSelection():
return int(input("""
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: """))
def addItem(list):
newItem = input("What will be added?: ")
list.append(newItem)
def removeItem(list):
print("There are {} items in the list.".format(len(list)))
deleteIndex = int(input("Which item is deleted?: "))
try:
list.pop(deleteIndex)
except Exception:
print("Incorrect selection.")
def gracefulExit(list):
print("The following items remain in the list: ")
for i in list: print(i)
quit()
if __name__ == "__main__":
main()
# Task 3
# Reading a list from a file and sort it
with open("words.txt") as sourcefile: # read each line into a list
content = sourcefile.readlines()
content = [word.strip() for word in content] # strip newline chars
content.sort() # sort to alphabetical order
print("Words in an alphabetical order:")
for i in content: print(i)
| true |
9b4d6e1e4a4a67f47fc74397890841fdd4061624 | SakibKhan1/most_frequent_word | /most_frequent_word.py | 1,301 | 4.40625 | 4 | def most_frequently_occuring_word(strings):
word_counts = {}
most_word = ""
most_word_count = 0
for s in strings:
words = s.split()
# We can then iterate over each word in that string.
for word in words:
# If the word isn't yet in the count dictionary, add it with a starting count of 1. Otherwise, increase the count.
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
# If the newly updated word is now the most frequently occuring, update the return value.
if word_counts[word] > most_word_count:
most_word = word
most_word_count = word_counts[word]
# This occurs after all strings and words have been iterated over. Return the most frequently occuring word.
return most_word
test1 = [
"hi hello how are you", "i promise this works", "seriously give it a try",
"it should return the word it", "and if it didn't then I messed up",
"feel free to flame me"
]
test2 = ["something simpler", "much simpler", "nonsense words"]
print(most_frequently_occuring_word(test1)) # "it"
print(most_frequently_occuring_word(test2)) # "simpler"
| true |
3318e928ef6cd5e68563e3fdc20a6fd77204be63 | districtem/ProjectEuler | /euler4.py | 815 | 4.375 | 4 | '''
def the_function():
get all 3 digit numbers between 900 and 999, store those numbers
for numbers in range
start with highest number and multiply by each number less than that number
test if product is palindrome
if palindrome store in something
compare all palindromes stored to find largest palindrome
'''
def is_palindrome(num):
reverse_num = str(num)[::-1]
if num == int(reverse_num):
return True
else:
return False
def get_max_palindrome():
products = []
for num1 in range(999, 900, -1):
for num2 in range(num1, 900, -1):
product = num1 * num2
if is_palindrome(product) is True:
products.append(product)
return max(products)
| true |
38044d199f319874a0611493b8e997bdbe685a97 | jRobinson33/Python | /map_filter_reduce.py | 2,029 | 4.4375 | 4 | #examples of mapping filtering and reducing
#6/18/2019
import math
def area(r):
"""Area of a circle with radius 'r'."""
return math.pi * (r**2)
radii = [2, 5, 7.1, 0.3, 10]
# Method 1: Direct method
areas = []
for r in radii:
a = area(r)
areas.append(a)
print("Direct method areas: ", areas)
# Method 2: use 'map' function
# map takes in a function and a list map(function, list)
print(map(area, radii)) #returns an iterater according to output
print(list(map(area, radii)))
# temps is a list of tuples of form (city, temp in celcius)
temps = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19),
("Los Angeles", 26), ("Tokyo",27), ("New York", 28),
("London", 22), ("Beijing", 32)]
# We want ot convert celcius to farenheit
c_to_f = lambda data: (data[0], (9/5)*data[1]+32)
print("Temps from C to F: ", list(map(c_to_f, temps)))
# filtering
import statistics
import decimal
data = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1]
avg = statistics.mean(data)
print(data," average amounts of fuel: ", avg)
# filter(function, list) which returns a filter object, an iterator over the results
print("Data above average: ", list(filter(lambda x: x > avg, data)))
print("Data below average: ", list(filter(lambda x: x < avg, data)))
# Remove missing data
countries = ["", "Argentina", "", "Brazil", "Chile", "", "Colombia", "", "Ecuador", "", "", "Venezuela"]
# we want to filter out the missing data
# some things you can use in the function for empty data
# "", 0, 0.0, 0j, [], (), {}, False, None, instances which signal they are empty
print("Countries in South America: ",list(filter(None, countries)))
# Reduce function
# data: [a1, a2, a3...]
# Function: f(x,y)
# reduce(f, data)
# Step 1: val1 = f(a1, a2)
# Step 2: val2 = f(val1, a3)
# Step 3: val3 = f(val2, a4)
# ...
# Return val(n-1)
from functools import reduce
# Multiply all numbers in a list
data = [2,3,5,7,11,13,17,19,23,29]
multiplier = lambda x, y: x*y
print("Product of prime numbers data list: ", reduce(multiplier, data)) | true |
7d0c5941f30b676d12ebaec45512e9a676649044 | vaaishalijain/Leetcode | /May-LeetCode-Challenge-Solutions/29_Course_Schedule.py | 2,081 | 4.125 | 4 | """
Course Schedule
Q. There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1,
which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all
courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Constraints:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how
a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
1 <= numCourses <= 10^5
"""
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
self.graph = collections.defaultdict(set)
for i, j in prerequisites:
self.graph[i].add(j)
n = numCourses
self.visited = [0] * n
self.flag = 0
def dfs(s):
if self.flag == 1:
return
if self.visited[s] == 1:
self.flag = 1
if self.visited[s] == 0:
self.visited[s] = 1
for each in self.graph[s]:
dfs(each)
self.visited[s] = 2
for i in range(n):
if self.flag == 1:
break
if self.visited[i] == 0:
dfs(i)
return self.flag == 0
| true |
e95bb74e1ee878076d8803977922c595b7d1f4b3 | Empow-PAT/fall2020game | /pickle_func.py | 1,248 | 4.15625 | 4 | import os
import pickle
import platform
# Use this to create a pickle file
def create_file(filename: str):
# Checks if the file doesn't exist
if not os.path.isfile(filename):
# Creates the file
open(filename, 'xb')
# Checks whether the person is using Windows or MacOS(Darwin) and according to that, decides how to hide the file
if platform.system() == 'Windows':
os.system(f'attrib +h {filename}')
elif platform.system() == 'Darwin':
os.rename(filename, f'.{filename}')
# Use this to write to a pickle file
def write(filename: str, data):
# Opens the file in writing mode
if not os.path.isfile(filename):
create_file(filename)
with open(filename, 'wb') as f:
# Dumps data into the file using pickle
pickle.dump(data, f)
# Closes the file
f.close()
# Use this to read from a pickle file
def read(filename: str):
# Opens the file in reading mode
with open(filename, 'rb') as f:
# Creates a variable with the value of the data in the file
loaded_data = pickle.load(f)
# Closes the file
f.close()
# Returns the variable with the contents of the file
return loaded_data | true |
744ef4cf2fbd4f37c8bac9e8184bd0a7d21f3716 | ccoo/Multiprocessing-and-Multithreading | /Multi-processing and Multi-threading in Python/Multi-threading/Race Condition Demo by Raymond Hettinger/race_condition.py | 1,405 | 4.28125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple demo of race condition, amplified by fuzzing technique.
"""
import random
import time
from threading import Thread
# Fizzing is a technique for amplifying race condition to make them more
# visible.
# Basically, define a fuzz() function, which simply sleeps a random amount of
# time if instructed, and then call the fuzz() function before each operation
# Fuzzing setup
FUZZ = True
def fuzz() -> None:
"""
Fuzzes the program for a random amount of time, if instructed.
:return: None
"""
if FUZZ:
time.sleep(random.random())
# Shared global variable
counter = 0
def worker() -> None:
"""
:return: None
"""
global counter
fuzz()
old_val = counter # Read from the global variable
fuzz()
counter = old_val + 1 # Write to the global variable
# Whenever there is read from/write to global variables, there could be race
# condition.
# To amplify this race condition to make it more visible, we utilize fuzzing
# technique as mentioned above.
fuzz()
# Note that the built-in print() function is also a "global" resource, and
# thus could lead to race condition as well
print(f'The counter is {counter}')
fuzz()
print('----------')
print('Starting up')
for _ in range(10):
Thread(target=worker).start()
fuzz()
print('Finishing up')
| true |
aef7c9805f73bf47454ee4bfa666ab5a0f12a856 | M-Jawad-Malik/Python | /Python_Fundamentals/11.if-elif-else.py | 214 | 4.375 | 4 | # This is program of checking a no whether it is even or odd using if and else keywords #
x=eval(input('Enter Number'))
if x%2==0:
print('Entered number is Even')
else:
print('Entered number is odd')
| true |
6e16d5f3d0cb07695b68a48025b2ee6090c95100 | M-Jawad-Malik/Python | /Python_Fundamentals/16.list_append().py | 224 | 4.21875 | 4 | #this is way of adding single element at the end of list#
list=['1',2,'Jawad']
list.append('Muhammad')
#this is way of adding one list to other#
list2=[3,4,5,]
list.append(list2)
print('List after modification: ',list) | true |
0e75e6d92b7aefb4ff3cc69a24681ac462e3316b | M-Jawad-Malik/Python | /Python_Fundamentals/36.Python_function.py | 540 | 4.15625 | 4 | # Here a function for checking a number either it is odd or even is defied#
def even_odd(number):
if number%2==0:
return True
else:
return False
# _________________________________#
# Here main function is defined#
def main():
number=[1,2,3,4,5,6,7]
for i in number:
if even_odd(i):
print(i,' is even number.')
else:
print(i,' is odd number')
#__________________________________#
# here main function is called#
main()
#_____________________________# | true |
685fe33ac4fd79dc861d605c01694e1489ec2ee4 | herysantos/cursos-em-video-python | /desafios/desafio59.py | 992 | 4.1875 | 4 | #
# Crie um programa que leia dois valores e mostre um menu na tela.
#
# [1] somar
# [2] multiplicar
# [3] maior
# [4] novos numeros
# [5] sair
#
# Seu programa deverá realizar a operação em cada caso.
#
n1 = float(input('Informe um valor'))
n2 = float(input('Informe outro valor'))
menu = -1
while menu != 5:
menu = int(input('''
O que você deseja fazer com esses números?
# [1] somar
# [2] multiplicar
# [3] maior
# [4] novos numeros
# [5] sair '''))
if menu == 1:
print('A soma dos números é {}'.format(n1 + n2))
elif menu == 2:
print('A multiplicação dos números é {}'.format(n1 * n2))
elif menu == 3:
print('O maior número é {}'.format(n1 if n1 > n2 else n2))
elif menu == 4:
n1 = float(input('Informe um valor'))
n2 = float(input('Informe outro valor'))
elif menu == 5:
print('Good bye!!!')
else:
print('O valor informação não é válido, por favor informe um número entre 1 e 5')
| false |
30927c7b556233523f1c9ef68b55dd0ea9665a47 | herysantos/cursos-em-video-python | /desafios/desafio11.py | 283 | 4.15625 | 4 | l = float(input('Say me how largest is the wall:'))
a = float(input('Say me how higher is the wall'))
print('Ok! your wall have the dimension {:.2f}x{:.2f} e your area is {}m²'.format(l, a, (a*l)))
print('To paint this wall you will need {:.2f} liters of paint.'.format(((a*l)/2)))
| true |
f3f9a1b622820c093d39e210684f9250da820fd6 | elliottqian/DataStructure | /tree/huffman_tree.py | 1,947 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
用Python来定义一个Huffman树
输入例子:
A:13,B:11,C:4,D:22
"""
class Node(object):
"""
The Huffman Tree's Node Structure.
"""
weight = None
left = None
right = None
def __init__(self, left=None, right=None, weight=None, name=None):
self.left = left
self.right = right
self.weight = weight
self.name = name
@staticmethod
def sort_list(node_list):
"""
Need to study the sorted function.
:param node_list:
:return:排好的列表
"""
return sorted(node_list, key=lambda node: node.weight)
class HuffmanTree(object):
def __init__(self, node_list):
self.node_list = node_list
def make_huffman_tree(self):
while len(self.node_list) > 1:
self.node_list = Node.sort_list(self.node_list)
print("debug: before make node")
for x in self.node_list:
print(x.weight)
temp_weight = self.node_list[0].weight + self.node_list[1].weight
new_node = Node(weight=temp_weight)
new_node.left = self.node_list[0]
new_node.right = self.node_list[1]
self.node_list.append(new_node)
self.node_list = self.node_list[2:]
print("debug: one time")
for x in self.node_list:
print(x.weight)
print("debug: the loop is over!")
return self.node_list[0]
if __name__ == "__main__":
node_1 = Node(weight=7, name='A')
node_2 = Node(weight=5, name='B')
node_3 = Node(weight=2, name='C')
node_4 = Node(weight=4, name='D')
in_node = [node_1, node_2, node_3, node_4]
huffman_tree = HuffmanTree(in_node)
root = huffman_tree.make_huffman_tree()
print(root.left.name)
print(root.right.left.name)
print(root.right.right.left.name)
print(root.right.right.right.name)
pass
| true |
62410bff55419e32fada6c28270e5ff83fc52913 | JCMolin/hw8Project2 | /main.py | 865 | 4.21875 | 4 | #! /usr/bin/python
# Exercise No. 2
# File Name: hw8Project2.py
# Programmer: James Molin
# Date: July 16, 2020
#
# Problem Statement: make a picture grayscale
#
#
# Overall Plan:
# 1. import the picture
# 2. calculate a way to turn the picture grayscale
# 3. print the result
#
#
# import the necessary python libraries
from graphics import *
import math
def main():
flower = Image(Point(110, 83), "flower.gif")
width = flower.getWidth()
height = flower.getHeight()
win = GraphWin("Grayscale", width, height)
flower.draw(win)
i = 0
j = 0
for i in range(0, width):
for j in range(0, height):
r, g, b = flower.getPixel(i, j)
brightness = int(round(0.299*r + 0.587*g + 0.114*b))
flower.setPixel(i, j, color_rgb(brightness, brightness, brightness))
j = j + 1
i = i + 1
main() | true |
a7f85a8a4ed7affe287449bd085c7bd10509149f | IrisDyr/demo | /Week 1/H1 Exercise 1.py | 813 | 4.1875 | 4 |
def adding(x,y): #sum
return x + y
def substracting(x,y): #substraction
return x - y
def divide(x,y): #division
return x / y
def multiplication(x, y): #multiplication
return x * y
num1 = int(input("Input the first number ")) #inputing values
num2 = int(input("Input the second number "))
acti = int(input("What would you like to do? 1.Add 2.Substract 3.Divide 4. Multiplication ")) # choosing what to do with the numbers inputed
if acti == 1: #telling the calculator which function to execute
print(num1,"+",num2,"=", adding(num1,num2))
elif acti == 2:
print(num1,"-",num2,"=", substracting(num1,num2))
elif acti == 3:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print(num1,"*",num2,"=", multiplication(num1,num2))
| true |
4d47678a12fb82c3f98dc59bfd2a6d69b6b423e0 | ZoltanSzeman/python-bootcamp-projects | /fibonacci_sequence.py | 540 | 4.25 | 4 | # Created by Zoltan Szeman
# 2020-09-09
# Task: Print the fibonacci sequence to the nth digit
while True:
try:
seq_no = int(input('Enter the length of the fibonacci sequence '
'you would like to print: '))
break
except ValueError:
print('\nPlease enter a valid whole number!\n')
count = 2
i = 0
j = 1
fibonacci_list = [i, j]
while count != seq_no:
k = i + j
i = j
j = k
fibonacci_list.append(k)
count += 1
print(f'Fibonacci sequence of {seq_no} length is:\n{fibonacci_list}')
| true |
418cece77b7fc1ed8397623ade04a0d4247000d9 | Mannizhang/learn | /笨方法学python/练习3.py | 485 | 4.1875 | 4 | print('I Will now count my chickens:')
print('Hens')
print(25+30/6)
print("Roosters")
print(100-25*3%4)
print('now i whil count the eggs:')
print(int(3+2+1-5+4%2-1/4+6))
print('is it true that 3+2<5-7?')
print(3+2<5-7)
print('what is 3+2?')
print(3+2)
print('what is 5-7?')
print(5-7)
print("oh no that's why it's false")
print("how about about some more")
print("is it greater?"),print(5>-2)
print("is it greater or equal?"),print(5>=-2)
print("is it less or equal"),print(5<=-2) | true |
5aeee69ab4be5e023c37f452e30d8e334807b2b3 | gongtian1234/-offer | /test58_翻转字符串.py | 1,276 | 4.15625 | 4 | '''
题目一:翻转单词顺序。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如,输入字符串
"I am a student.",则输出"student. a am I"
思路:
先切分开,翻转后再用空格链接回去
题目二:左旋转字符串。字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。例如,输入字符串'abcdefg'和数字2,该函数将返回左旋转两位
得到的结果'cdefgab'
思路:将前面的n个字符串移动到后面即可/
'''
class Solution1:
def reverseSentence(self, sentence):
if sentence is None:
return
return (' ').join(sentence.split(' ')[::-1])
class Solution2:
def leftRotateString(self, chars, n):
if chars is None:
return
charsLen = len(chars)
if charsLen<n:
n = n%charsLen
return chars[n:]+chars[:n]
if __name__ == '__main__':
s1 = Solution1()
print(s1.reverseSentence('I am a student, but I will graduate after ten months.'))
print(s1.reverseSentence(None))
s2 = Solution2()
print(s2.leftRotateString('acsadad', 8))
| false |
c0ad3d9f12b00aad6a6080edac90d54a422d075b | Minhaj9800/BasicPython | /print_frmt.py | 1,362 | 4.1875 | 4 | another_quote = "He said \"You are amazing\", Yesterday"
print(another_quote)
#or do below
second_quote = "I am doing Okay, 'Man'"
print(second_quote)
multilines="""" Hello This is Minhajur Rahman I am a 4th year student at UPEI. I am planing start my Hnours Thesis at the end of this year.
I am originally from Moulvibazar, Sylhet, Bangladesh."""
print(multilines)
#concatnation
first_name = "Minhajur"
last_name = "Rahman"
full_name = first_name +" "+last_name
print(" Full Name of Mine: "+full_name)
#Note You cannot add integer and String
#together in python.
#age = 21
#print("My Age is "+ age) This is an error in python.
#Do one of Following:
age = "21"
print("My Age: "+age) # or
print("Age: "+str(age))
print (int("5"))
#String Formatting starts from here
print(f"Age: {age}")
print(f"Value of PI: {3.14159}")
greeting = (f"How are you {first_name}")
print(greeting)
first_name = "Allan"
print(greeting) # Still Minhajur,Greetings
#will not be effect by name change.
#Let's see another Approach to solve above
"""
This will solve the above probelm
which does not affected by expression change.
"""
final_greeting = "How are you {name}"
first_name = "Minhajur"
print(" ")
f_name = final_greeting.format(name=first_name)
print(f_name)
print(" ")
first_name = "Allan"
another_name = final_greeting.format(name=first_name)
print(another_name)
| true |
cdb1afe5559a5c3c9f9bc45d9f504bd79064a960 | Minhaj9800/BasicPython | /destructuring.py | 340 | 4.4375 | 4 | currencies = 0.8, 1.2 # Making a tuple.
usd,euro = currencies # usd = 0.8, euro = 1.2. This is called desturturing. Taking a tuple and make it two different variables.
friends_age = [("Rolf",25),("John",30),("Anne",23)] # List of tuples
for name, age in friends_age: #destructuring inside a for loop.
print(f"{name} is {age} years old.")
| true |
9636799164bddc7a2f408bd42ac69772cef007a4 | zvovov/goodrich | /C-4.17.py | 562 | 4.375 | 4 | # Write a short recursive Python function that determines if a string s is a
# palindrome, that is, it is equal to its reverse. For example, racecar and
# gohangasalamiimalasagnahog are palindromes.
def is_palindrome(s):
"""
Returns True if s is palindrome
False otherwise
:param s: input string
:return: True or False
"""
if len(s)<=1:
return True
if s[0] == s[-1]:
is_palindrome(s[1:-1])
return True
else:
return False
if __name__ == "__main__":
s = input()
print(is_palindrome(s))
| true |
dace58879101e50ee872a8ffa3838a52477cf309 | MosheBakshi/HANGMAN | /Conditions/4.3.1.py | 692 | 4.15625 | 4 | user_input = input("Guess a letter: ")
ENGLISH_FLAG = user_input.isascii()
LENGTH_FLAG = len(user_input) < 2
SIGNS_FLAG = user_input.isalpha()
if (LENGTH_FLAG is False and # IN CASE MORE THAN 1 LETTER BUT ELSE IS FINE
ENGLISH_FLAG is True and
SIGNS_FLAG is True):
print("E1")
elif (LENGTH_FLAG is True and # NOT IN ENGLISH AND SIGNS BUT IN LENGTH
SIGNS_FLAG is False):
print("E2")
elif (ENGLISH_FLAG is False or # SAME AS UP BUT LONG STRING
(SIGNS_FLAG is False and
LENGTH_FLAG is False)):
print("E3")
else:
print(user_input)
"""
CHECKS THE USER'S INPUT IF LEGAL OR ILLEGAL -> IF LEGAL PRINTS THE INPUT ELSE PRINT THE RELEVANT ERROR
""" | true |
329dd32bb3263ebcfccdffc0ccbd701e4544e1f7 | mxor111/Play-ROCK-Paper-Scissor | /rps-starter-code12.py | 2,989 | 4.25 | 4 | #!/usr/bin/env python3
# ROCK PAPER SCISSOR - MICHELE
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
import random
moves = ['rock', 'paper', 'scissors']
p1 = input("Player 1 Whats's your name?")
p2 = input("Player 2 What's your name?")
"""The Player class is the parent class for all of the Players
in this game"""
# Remember the Rules: Rock beats scissor, Scissor beats paper, paper
# beats rock
class Player(): # play always Rock!
my_move = None
thier_move = None
def move(self):
return 'rock'
def learn(self, my_move, their_move):
pass
class RandomPlayer(Player): # player chooses random moves
def move(RandomPlayer):
return (random.choice(moves))
class HumanPlayer(Player):
def move(self):
while True: # addng validator
user = input("Rock, Paper or Scissors? ")
if user.lower() not in moves:
print("Invalid input choose Rock, Paper or Scissors")
else:
return user.lower() # not sure
class ReflectPlayer(Player): # Remembers and imitates what human player did
def move(self):
if self.their_move is None:
return 'HumanPlayer'
def learn(self, my_move, their_move):
self.my_move = their_move
class CyclePlayer(Player): # cycles through three moves
def move(self):
if self.my_move is None:
return random.choice(moves)
elif self.my_move == "rock":
return "paper"
elif self.move == "paper":
return "scissors"
else:
return "rocK"
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
p1_score = 0
p2_score = 0
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
if beats(move1, move2) is True:
self.p1_score += 1
print('Player 1 You Win!')
else:
if move1 == move2:
print('Tie Game')
else:
self.p2_score += 1
print('Player 2 You Win!')
print(f"Player 1: Score: {self.p1_score}")
print(f"Player 2: Score: {self.p2_score}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def play_game(self):
print("Let's Play! and Welcome")
for round in range(7):
print(f"Round {round}:")
self.play_round()
print("Game over Pay Again!")
if __name__ == '__main__':
game = Game(HumanPlayer(), CyclePlayer())
game.play_game()
| true |
a7515e51deac103a155dca3b88f04f68631f3e70 | mlassoff/PFAB52014 | /greetings.py | 301 | 4.125 | 4 | #raw_input is for strings-- does not attempt conversion
name = raw_input("What is your name?")
print "Hello and greetings", name
#input is for integers or floating point numbers
age = input("How old are you?")
print "You are", age, "years old."
print "In dog years you are ", (age*7) , "years old"
| true |
eb370baa70a807d3f9fa050712235bd94503b7f1 | manitghogar/lpthw | /3/ex3.py | 968 | 4.3125 | 4 | #start of the task, will start counting chickens
print "I will now count my chickens:"
#counts number of hens
print "Hens", 25.0 + 30.0 / 6.0
#counts number of Roosters
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
#will start counting eggs
print "Now I will count the eggs:"
#counting eggs
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
#question - boolean
print "Is it true that 3 + 2 < 5 - 7?"
#answer to the boolean questions
print 3.0 + 2.0 < 5.0 - 7.0
#clarifying first question - answers with 5
print "What is 3 + 2?" , 3.0 + 2.0
#clarifying first question - answers with -2
print "What is 5 - 7?" , 5.0 - 7.0
#realizes why the first question was false
print "Oh, that's why it's False."
#asks for more
print "How about some more."
#question 2 - boolean
print "Is it greater?" , 5 > -2
#proof to question 2 - answers with True
print "Is it greater or equal?" , 5>= -2
#proof to question 2 - answers with False
print "Is it less or equal?" , 5 <= -2
| true |
2bbb70dfaa362bf182e2d0a314b2bf5895195a45 | manitghogar/lpthw | /14/ex14.py | 1,020 | 4.1875 | 4 |
#importing argv from sys
from sys import argv
#unpacking argv into three variables v0, v1 and v2
script, user_name, birth_country = argv
#setting a consistent prompt that shows up everytime a question is asked
prompt = '>>'
#strings that use the argv arguments
print "Hi %s of %s, I'm the %s script." % (user_name, birth_country, script)
#string
print "I'd like to ask you a few questions."
#string questions using argv argument
print "Do you like me %s?" % user_name
#prompt to answer the question
likes = raw_input(prompt)
#string questions using argv variable
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
#string question
print "What kind of computer do you have?"
computer = raw_input(prompt)
#string question
print "What is your favourite food"
food = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
But what I do know is that you like %r just like me.
And you have a %r computer. Nice.
""" % (likes, lives, food, computer)
| true |
b8caa7819abc898dc5fcc1335d302ff94dceffe6 | nivb52/python-basics | /05- Classes/06- Magic-Methods.py | 1,133 | 4.34375 | 4 | # rszalski.github.io/megicmethods
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ( {self.x} , {self.y} )" )
point = MyPoint(1,2)
print(point)
# // <__main__.MyPoint object at 0x00C191D8>
# __str__ ^ give us the above which is magic methods
print(" __str__ gave us the ^ above which is magic methods")
# ===============
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# // magic method
def __str__(self):
return f"({self.x},{self.y})"
def draw(self):
print(f"Point ( {self.x} , {self.y} )" )
point = Point(1,2)
print("===========CHANGING MAGIC METHODS======================")
print(point)
print(str(point))
# __str__ ^ give us the above which is magic methods
print(" ^ CHANGED __str__ ^ ")
# ================ CANT CHANGE LIKE THIS : =======================
point2 = Point(0,0)
print(" # YOU CAN'T CHANGE IT BY ClassName.__str__ = some code ... ")
# YOU CANT CHANGE IT LIKE THIS
def someStr():
print('haha')
point.__str__ = someStr
print(point)
print(point2)
| false |
397660a71a23fa37977b5db7842b53721c42bb23 | barankurtulusozan/Algorithms-and-Data-Structures | /Python/PY_01_List_Tuple_Dictionary.py | 1,178 | 4.40625 | 4 | #PY_List_Tuple_Dictionary
#Lists
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
#This will create a list made by characters
print(alphabet[0:6])
#will print characters till g
#Lets create a list of names
names = ["John","Erica","Stephen"]
#If we want to append names to this list
names += ["Joseph","Aysha"]
#Dictionary
country_capitals = {"Denmark":"Copenhagen","Spain":"Madrid"}
#Add Item to dictionary
country_capitals["Turkey"] = "Ankara"
#Delete Item
del country_capitals["Denmark"]
print(country_capitals)
#Prints whole list
print(country_capitals["Spain"])
#Prints capital of Spain
print(country_capitals.values())
#will print all the values of the dictionary
print("Turkey" in country_capitals.keys())
#will print if Turkey is in the dictionary
fruits = ["apple","banana","pear"]
fruits_dictionary = {"apple":1,"banana":2,"pear":3}
print(fruits) #will print list of fruits
print(fruits_dictionary.keys())
#will print dictionary of fruit dictionary
print("pear" in fruits_dictionary.keys())
print(3 in fruits_dictionary.values())
#will print true if dictionary has a value of 3
#keys and values are differ from eachother significantly, beware
| true |
2277a6705349b81f2918382f2ed72313bd9c4af3 | renchao7060/studynotebook | /数图游戏/打印菱形.py | 1,479 | 4.25 | 4 | '''
# rhombus /ˈrɑːmbəs/ 菱形
*
***
*****
*******
*****
***
*
行 *数量 空格数量--->行转换为---->推算空格数量---->推算每行*数量
1 1 3 -(7//2)=-3 abs(-3) 7-2*abs(-3)=1
2 3 2 -2 abs(-2) 7-2*abs(-2)=3
3 5 1 -1 abs(-1) 7-2*abs(-1)=5
4 7 0 0 0 7-2*abs(0) =7
5 5 1 1 1 7-2*abs(1) =5
6 3 2 2 2 7-2*abs(2) =3
7 1 3 7//2=3 3 7-2*abs(3) =1
行起始数值 =-(7//2) =-3
行结束数值 = (7//2)+1 = 4
每行空格值 = ' '.abs(i) #i为当前处于哪一行
每行星号值 = '*' *(n-2*abs(i)) #n为菱形最长一行*的数量,需为奇数odd,本例中的7即为n
代码实现:
for i in range(-3,4):
print(' '*abs(i)+'*'*(7-2*abs(i)))
'''
def rhombusg(n):
# if not n%2:
# n=n+1
start=-(n//2)
stop=(n//2)+1
for i in range(start,stop):
print(' '*abs(i)+'*'*(n-2*abs(i)))
if __name__=='__main__':
while True:
try:
n=int(input('Please input the odd:'))
if n%2==1:
rhombusg(n)
break
else:
print('The input is even,it need odd')
continue
except:
print('The input is invalid')
continue | false |
73a63f4440793041849743e30a02a5a6cd388a10 | renchao7060/studynotebook | /基础学习/p64.py | 547 | 4.25 | 4 |
#如何进行反向迭代以及如何实现反向迭代
class FloatRange(object):
def __init__(self,start,end,step):
self.start=start
self.end=end
self.step=step
def __iter__(self):
t=self.start
while t<=self.end:
yield t
t+=self.step
def __reversed__(self):
t=self.end
while t>=self.start:
yield t
t-=self.step
for i in FloatRange(1.0,4.0,0.5):
print(i)
for i in reversed(FloatRange(1.0,4.0,0.5)):
print(i)
| false |
bf0e35adb8b9fc6ec55a21837105cc864b5fadfd | renchao7060/studynotebook | /基础学习/py94.py | 1,222 | 4.1875 | 4 | # 模拟购物车流程
product_list=[
('Iphone',5800),
('Mac Pro',9800),
('Bike',800),
('Coffee',30),
('Alex python',120)
]
shopping_list=[]
salary=input("Input your salary:")
if salary.isdigit():
salary=int(salary)
while True:
for index,item in enumerate(product_list):
print(index,item)
user_choice=input("请选择商品编号>>:")
if user_choice.isdigit():
user_choice=int(user_choice)
if user_choice<len(product_list) and user_choice>=0:
p_item=product_list[user_choice]
if p_item[1]<=salary:
shopping_list.append(p_item)
salary-=p_item[1]
print("Added %s into shopping list"%p_item[0])
else:
print("你的余额只剩%s,无法购买,请充值"%salary)
else:
print("producd code %s is not exits"%user_choice)
elif user_choice=='q':
print('shooping list'.center(20,'*'))
for p in shopping_list:
print(p)
print("Your current balance:",salary)
exit()
else:
print("invalid option")
| true |
3f8e44a1c120f3b725d64c83f6b51726ff4830f6 | Codeology/LessonPlans | /Spring2017/Week1/searchInsertPosition.py | 909 | 4.1875 | 4 | #!/usr/local/bin/python
# coding: latin-1
# https://leetcode.com/problems/search-insert-position
#
# Given a sorted array and a target value, return the index if
# the target is found. If not, return the index where it would
# be if it were inserted in order.
#
# You may assume no duplicates in the array.
#
# Here are few examples.
# [1,3,5,6], 5 → 2
# [1,3,5,6], 2 → 1
# [1,3,5,6], 7 → 4
# [1,3,5,6], 0 → 0
def searchInsert(nums, target):
for i, num in enumerate(nums):
if num == target:
return i
elif num > target:
return i
return len(nums)
def tests():
print(searchInsert([1,3,5,6], 5) == 2)
print(searchInsert([1,3,5,6], 2) == 1)
print(searchInsert([1,3,5,6], 7) == 4)
print(searchInsert([1,3,5,6], 0) == 0)
print(searchInsert([], 0) == 0)
print(searchInsert([1], 0) == 0)
print(searchInsert([1], 2) == 1)
tests()
| true |
9cfdfab5ed7eea89812de216b4e4fa9e39ea0647 | Akash21-art/solidprinciple | /Inheritance.py | 897 | 4.125 | 4 | # A Python program to demonstrate inheritance
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Inherited or Sub class
class Child(parent):
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
# To get name
def getAge(self):
return self.age
# Inherited or Sub class
class GrandChild(Child):
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
# To get address
def getAddress(self):
return self.address
# Driver code
obj1 = GrandChild("Akash", 23, "Hyderabad")
print(obj1.getName(), obj1.getAge(), obj1.getAddress()) | true |
26e5cdb0e2c2e9b88bfd438d584d78743faa796c | themarcelor/perfectTheCraft | /coding_questions/matrix/matrix.py | 809 | 4.40625 | 4 | # --- Directions
# Write a function that accepts an integer N
# and returns a NxN spiral matrix.
# --- Examples
# matrix(2)
# [[1, 2],
# [4, 3]]
# matrix(3)
# [[1, 2, 3],
# [8, 9, 4],
# [7, 6, 5]]
# matrix(4)
# [[1, 2, 3, 4],
# [12, 13, 14, 5],
# [11, 16, 15, 6],
# [10, 9, 8, 7]]
def matrix(n):
inner_array = []
outer_array = []
counter = 0
for i in range(n):
for j in range(n):
if i > 0 and j == 0:
# resume counter from the last element of the previous inner array
counter = outer_array[i-1][n-1]
counter = counter + 1
inner_array.append(counter)
print(f'counter: {counter}')
outer_array.append(inner_array)
inner_array = []
return outer_array
if __name__ == '__main__':
print(matrix(4))
| true |
b6fc02ea30e11d9feee4ba57487c7cf62c4cb890 | Guithublherme/Python | /Primeiros Passos/Aulas/Aula1.py | 697 | 4.3125 | 4 | #aula 1 váriaveis, tipos, entradas e saídas, operadores matemáticos
#saídas
print("Olá mundo!");
print('Segundo print\noutra linha\t Usando o tab');
#variáveis
Nome = "Guilherme";
idade = 27;
altura = 1.75;
print(Nome);
print("Nome:"+ Nome); #concatena Strings apenas
print("Nome:",Nome,"tem",idade,"anos");
tipoNome= type(Nome);
tipoIdade= type(idade);
tipoAltura= type(altura);
print(tipoNome,tipoIdade,tipoAltura); #str , int, float
#entradas
Nome = input("Escreva seu nome: ");
idade = input("Digite sua idade: ");
print("Nome:",Nome,"tem",idade,"anos");
#Operações matemáticas
num1 = 42;
num2 = 2;
num3 = 3.0;
resultado = num2 + num1 / (num3**num2)**(1/2);
print(resultado); | false |
5c231792e7a9bf0578182618690a4df7efcd706b | claireyegian/unit4 | /functionDemo.py | 396 | 4.1875 | 4 | #Claire Yegian
#10/17/17
#functionDemo.py - learning functions
def hw():
print('Hello, world!')
def bigger(num1,num2): #prints which number is bigger
if num1>num2:
print(num1)
else:
print(num2)
def slope(x1,y1,x2,y2): #calculates slope
print((y2-y1)/(x2-x1))
#tests for the various functions
hw()
bigger(13,27)
bigger(-10,-15)
bigger('Smeds','Yegian')
slope(1,2,2,4)
| true |
be0d6748fc3267953041330cdfc66e6cb76a8d95 | claireyegian/unit4 | /stringUnion.py | 325 | 4.25 | 4 | #Claire Yegian
#10/26/17
#stringUnion.py - takes two strings and returns all letters that appear in either word
def stringUnion(word1,word2):
string = ''
for ch in word1 + word2:
if not ch.lower() in string:
string = string+ch.lower()
return string
print(stringUnion('Mississippi','Pensylvania'))
| true |
9a6b2c668b70d8d6e3b52babd32fe8fd94eaa904 | yanehi/student_management_python | /student/student.py | 2,757 | 4.21875 | 4 | class Student():
def __init__(self, first_name, last_name, matriculation_number, language, term, average_grade, username, state, street_name, street_number):
self.first_name = first_name
self.last_name = last_name
self.matriculation_number = matriculation_number
self.language = language
self.term = term
self.average_grade = average_grade
self.username = username
self.state = state
self.street_name = street_name
self.street_number = street_number
def print_student(self, student, counter):
first_name, last_name, matriculation_number, language, term, average_grade, username, state, street_name, street_number = student
print("Student Nr: " + str(counter))
print("Firstname: " + first_name)
print("Lastname: " + last_name)
print("Matriculation Number: " + matriculation_number)
print("Language: " + language)
print("Term: " + term)
print("Average Grade: " + average_grade)
print("Username: " + username)
print("State: " + state)
print("Street: " + street_name + " Nr. " + street_number)
print("")
def print_all_students(self,students):
counter = 1
for student in students:
self.print_student(student, counter)
counter += 1
def add_student(self):
first_name = input('Firstname: ')
last_name = input('Lastname: ')
matriculation_number = input('Matriculation Number: ')
language = input('Language: ')
term = input('Term: ')
average_grade = input('Average Grade: ')
username = input('Username: ')
state = input('State: ')
street_name = input('Street: ')
street_number = input('Nr: ')
new_student = (first_name, last_name, matriculation_number, language, term, average_grade, username, state, street_name, street_number)
return new_student
def search_student(self, students, matriculation_number):
found = False
student_firstname = ""
student_lastname = ""
index = 0
for student in students:
if matriculation_number == student[2]:
found = True
student_firstname = student[0]
student_lastname = student[1]
break
index = index +1
if found == True:
print("Student: " + student_firstname + " " + student_lastname + " found on position " + str(index))
else:
print("Student not in list!")
return index
# s = Student("","","","","","","","","","")
# s.print_all_students(students) | false |
44cfa8fa73162bc9618bc6fb2b30f26458c0b0ae | maryclareok/python | /list_class.py | 2,542 | 4.3125 | 4 | # lst=[1,2,3,4,5]
# list=["jane","kemi","obi","mose"]
# print(len(lst))
# print(lst [0 : 3])
# print(list)
# num=lst[0]*lst[1]#using list for mathematical operation
# print(num)
# print(list[1:])
# print(list[1::2])
# print(lst[-1])
# print(lst[:-1])
# list3=["david","john",2,"ben",7,9,"germany"]
# print(list3[1])
# #changing values
# list3[1]= "wed"
# print(list3)
# #changing values of a specific index
# list3.insert(0,10)
# print(list3)
# #removing element
# list3.remove("wed")
# print(list3)
# list3.pop()
# print(list3) #deletes the last element the list
# del list3[2] #deletes the specified index
# print (list3)
# list3.clear()
# print(list3)#clears all the list content
# del list3
# print(list3)#deletes the list
# number=["jenny","bunny","55"]
# list2=[9,8,6,1,2,3,4,5]
# lst3=["m","y","z","b"]
# print(lst3)
# number.append("56")#adds to the list
# print (number)
# print(type(number))
# list2.extend(number)
# print(list2)#adds number to list2
# lst3=number.copy()
# print (lst3)#copys numbeer into lst3 and replaces it completly
# lst3.sort()
# print(lst3)#arranges the list
# lst10=["ben","jen","9","3"]#put numbers in double quote for integer and string combination
# lst10.sort()
# print(lst10)
# list5=["jamie",3,"davie",8,0]
# list5.pop(0)#used to remove a specific index
# list5.pop()
# print(list5)
# list6=[0,9,8,7,6,5]
# list6.sort()
# print(list6[-1])#to show the largest number in the list
# lst7=[3,6,9]
# newlist=[]
# mul=lst7[0]*lst7[1]*lst7[2]
# newlist.append(mul)
# print(newlist)#multiiplys the list
# list9=[1,4,0,7]
# list9.sort()
# print (list9[0])#returns the smallest number in the list
# list11=[1,3,5,7,9]
# print ("The list is : " + str(list11))
# counter = 0
# for i in list11:
# counter=counter+1
# if counter == ind:
# print ("Length of list without using len is : " + str(counter))
#CORRECTION
#1 a function to delete the first and last element in the list
# lst=["chucks","ada","henry","benita"]
# def remv(param):
# param.pop(0)
# param.pop()
# return param
# remv(lst)
# print(lst)
#2 a function to print the largest value in the list
list6=[0,9,8,7,6,5]
def large(param: list):
largest=0
for x in list6:
if x > largest:
largest = x
return largest
a = large(list6)
print(a)
#3 a function to print smallest value in the list
list6=[0,9,8,7,6,5]
def small(param: list):
smallest=sum(list6)
for x in list6:
if x < smallest:
smallest = x
return smallest
b= small(list6)
print(b)
| true |
0d136d5f6e1d4086d232f60c24f92f43abad5949 | ravikuril/DesignPatterns | /facade.py | 1,914 | 4.28125 | 4 | class Washing:
'''Subsystem # 1'''
def wash(self):
print("Washing...")
class Rinsing:
'''Subsystem # 2'''
def rinse(self):
print("Rinsing...")
class Spinning:
'''Subsystem # 3'''
def spin(self):
print("Spinning...")
class WashingMachine:
'''Facade'''
def __init__(self):
self.washing = Washing()
self.rinsing = Rinsing()
self.spinning = Spinning()
def startWashing(self):
self.washing.wash()
self.rinsing.rinse()
self.spinning.spin()
""" main method """
if __name__ == "__main__":
washingMachine = WashingMachine()
washingMachine.startWashing()
"""
Advantages
Isolation: We can easily isolate our code from the complexity of a subsystem.
Testine Process: Using Facade Method makes the process of testing comparitively easy since it has convenient methods for commmon testing tasks.
Loose Coupling: Availability of loose coupling between the clients and the Subsytems.
Disadvantages
Changes in Methods: As we know that in Facade method, subsequent methods are attached to Facade layer and any change in subsequent method may brings change in Facade layer which is not favourable.
Costly process: It is not cheap to establish the Facade method in out application for the system reliability.
Violation of rules: There is always the fear of violation of the construction of the facade layer.
Applicability
Providing simple Interface: One of the most important application of Facade Method is that it is used whenever you want to provide the simple interface to the complex sub-system
Division into layers: It is used when we want to provide a unique structure to a sub-system by dividing them into layers. It also leads to loose coupling between the clients and the subsystem.
"""
| true |
e1c8a88572cd610ac68ba546ff5b701974931b4a | papunmohanty/password-encryption | /encryptedPassword.py | 1,921 | 4.125 | 4 | def encryption():
count = 0
print "========================================================="
password = raw_input("Enter your Password between 6 to 8 Characters: ")
tempPassword = []
if len(password) < 7 or len(password) > 8:
print "Your Password Must be 7 - 8 Characters Long --- Try Again"
encryption()
for e in password:
if e == 'a':
temp = '@'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('a')
elif e == 'e':
temp = '3'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('e')
elif e == 'i':
temp = '1'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('i')
elif e == 'o':
temp = '0'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('o')
elif e == 'r':
temp = '4'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('r')
elif e == 's':
temp = '5'
count += 1
if count <=2:
tempPassword.append(temp)
else:
tempPassword.append('s')
else:
tempPassword.append(e)
temp = ''
for i in tempPassword:
temp += i
print "=====================================", password, ":", temp
press = raw_input("\nDo You Need More? Y or N? ")
if press == 'y':
encryption()
print "========================================================="
encryption()
| false |
6a132dc98dde7afabeaed73e31954944eb37f06c | billypriv05/bit-calculater | /image_bit_calc.py | 1,276 | 4.125 | 4 | # checks imput is a number more than
def num_check(question, low):
valid = False
while not valid:
error = "please enter a interger that is more or than "
"(or equal to) {}".format(low)
try:
# ask the user to enter a number
response = int(input(question))
# checks if number is more than zero
if response >= low:
return response
# outputs error if imput is invalid
else:
print(error)
print()
except ValueError:
print(error)
# finds # of bits for 24 bit colour
def image_bits():
# get width and height
image_width = num_check("image width? ", 1)
image_height = num_check("image height? ", 1)
# calculate # of pixels
num_pixels = image_width * image_height
# calculate # of bits ( 24 * num of pixels)
num_bits = num_pixels * 24
# output the answer with working
print()
print("# of pixels = {} x {} = {}".format(image_height,
image_width, num_pixels)
print("# of bits = {} x 24 = {}".format(num_pixels, num_bits)
print()
return ""
# main routine goes here
image_bits()
| true |
3ef8781a23a3139f9055129e6c8774a9bbe0de90 | Gaurav812/Learn-Python-the-hard-way | /Ex3.py | 580 | 4.34375 | 4 | #Ex3
# <= less-than-equal
# >= greater-than-equal
#print("I will now count my chickens:")
#print("Hens", 25 + 30 / 6)
#print("Roosters", 100 - 25 * 3 % 4)
#print ("Now I will count the eggs:")
#print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
#print ("Is it true that 3 + 2 < 5 - 7?")
#print(3+2<5-7)
#print ("Oh, that's why it's False.")
#print ("How about some more.")
#print ("Is it greater?", 5 > -2)
#print ("Is it greater or equal?", 5 >= -2)
#print ("Is it less or equal?", 5 <= -2)
print(2*3)
print(10/5)
print(5%7.75)
print (56%77)
print (11%5)
print (2 - 1 / 4 + 6)
| true |
753cca8c21a22551ecbe3b70e767c638a7a0147e | nyangeDix/automate-the-boring-stuff-with-python | /automate_the_boring_stuff/dictionaries and structuring data/dict_setDefault.py | 419 | 4.40625 | 4 | #Adds a default dictionary item to an already existing dictionary
#This only applies when the key and value are not available in the dictionary
food = {'fruits':'apples',
'vegetables':'kales',
'cereals':'maize',
'drinks':'vodka'
}
"""
if 'drugs' not in food:
food['drugs'] = 'weed'
"""
#this can also be done as shown below
food.setdefault('drugs', 'weed')
print(food) | true |
c8c77d1cc9a83234eb5fa2152b931d05a73de0d8 | nyangeDix/automate-the-boring-stuff-with-python | /automate_the_boring_stuff/pattern_matching_with_regex/regex_pipe.py | 2,080 | 4.125 | 4 | #The character "|" is called the pipe key
import re
findName = re.compile(r'Dickson | Nyange')
mo = findName.search('Dickson is Nyange')
print(mo.group())
#note the difference between the two set of codes
findName2 = re.compile(r'Nyange | Dickson')
mo2 = findName2.search('Nyange is Dickson')
print(mo2.group())
#The pipe key can also be used to match several patterns
findBat = re.compile(r'Bat(man|mobile|plate|plane|copter)')
mo3 = findBat.search('Yesterday i saw a Batcopter on the hills')
print(mo3.group())
print(mo3.group(1))
#optional matching with question mark
findBat2 = re.compile(r'Bat(wo)?man') #the part (wo)? is optional
mo4 = findBat2.search('I saw Batman')
print(mo4.group())
#Second set of code to test optional
mo5 = findBat2.search('I am a Batwoman')
print(mo5.group())
findNumber = re.compile(r'(\d\d\d)?\d\d\d-\d\d\d\d')
moNumber = findNumber.search('My number is 120-4542')
print(moNumber.group())
#Matching zero or more with the start
find_name = re.compile(r'Bat(wo)*man')
search_name = find_name.search('I am a Batman')
print(search_name.group())
search_name2 = find_name.search('Flora is a Batwoman')
print(search_name2.group())
search_name3 = find_name.search('Wakio is a Batwowowowowowoman')
print(search_name3.group())
#matching one or more with the the plus
findPlus = re.compile(r'Bat(wo)+man')
search_more = findPlus.search('I am a Batwoman')
print(search_more.group())
search_more2 = findPlus.search('I killed a Batman')
if search_more2 == None:
print ("The pattern didn't find a match")
search_more3 = findPlus.search('I am Batwowowowoman')
print(search_more3.group())
#matching with curly braces
find_new_regex = re.compile(r'(Ho){4}')
more_search = find_new_regex.search('HoHoHoHo')
print(more_search.group())
#Greedy and none greedy matching
find_laugh = re.compile(r'(ha){3,5}?')
search_laugh = find_laugh.search('He laughed so hahahaha')
print(search_laugh.group())
search_laugh2 = find_laugh.search('She laughed so nicely, hahahaha')
print(search_laugh2.group())
| true |
c827732bd723bd387ddeccc1a4b4ed48135831a4 | jamalamar/Python-function-challenges | /challenges.py | 1,182 | 4.28125 | 4 |
#Function that takes a number "n" and returns the sum of the numbers from 1 to "n".
# def sum_to(n):
# x = list(range(n))
# y = sum(x) + n
# print(y)
def sum_to(num):
sum = 0
for i in range(num + 1):
sum += i
print("The sum from 1 to "+ str(num) + ": " + str(sum))
sum_to(10)
#Function that takes a list parameter and returns the largest element in that list.
#You can assume the list contents are all positive numbers.
def largest(list):
largest = 0
for i in list:
if(i>largest):
largest = i
print("Largest on list: " + str(largest))
largest([1,2,34,5,6])
#Function that counts the number of occurrances of the second string inside the first string.
def occurances(one, two):
occur = 0
for i in one:
if(i == two):
occur += 1
print("Number of " + "'" + two + "'" + " occurances: " + str(occur))
occurances('fleeeeep floop', 'e')
#Function that takes an arbitrary number of parameters, multiplies them all together, and returns the product.
#Only need "*", args is just a convention:
def multi(*args):
product = 1
for i in args:
product *= i
print("The product of this numbers is: " + str(product))
multi(2, 2, 2, 2)
| true |
7e6f5908a6be5ba6d574ba51da9ffe4dc75750de | Chibizov96/project | /Lesson 6-3.py | 1,526 | 4.3125 | 4 | """
Реализовать базовый класс Worker (работник),
в котором определить атрибуты: name, surname, position (должность), income (доход).
Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы:
оклад и премия, например, {"wage": wage, "bonus": bonus}.
Создать класс Position (должность) на базе класса Worker.
В классе Position реализовать методы получения полного имени сотрудника (get_full_name) и
дохода с учетом премии (get_total_income).
Проверить работу примера на реальных данных (создать экземпляры класса Position, передать данные,
проверить значения атрибутов, вызвать методы экземпляров).
"""
class Worker:
name = ""
lastname = ""
position = ""
_income = {}
class Position(Worker):
def get_full_name(self):
print(f"Полное имя сотрудника {self.name}, {self.lastname}")
def get_total_income(self):
print(f"Зарплата сотрудника {self._income['wage'] + self._income['bonus']}")
a = Position()
a.name = "Yakov"
a.lastname = "Chibizov"
a._income = {"wage": 30000, "bonus": 10000}
a.get_full_name()
a.get_total_income() | false |
f5402726633ba15c54c8ad1867c16188dcdbb4fb | GauPippo/C4E9-Son | /ss1/ss1.py | 866 | 4.125 | 4 | #1.
'''
- How to check a variable's type?
type()
- Three difference examples of invalid name.
1992abc = 10
abc$ = "name"
True = 'hahaha'
'''
#2.
from math import *
from turtle import *
import turtle
##pi = 3.14
##radius = int(input("Radius?"))
##print ("Area =", radius * pi)
##print ("hihihi")
###3.
##
##doC = int(input("Enter the temperature in Celsius?"))
##doF = 9.0/5.0 * doC + 32
##print(doC, "C = ", doF, "F")
# TURTLE EXERCISE
shape("turtle")
speed(-1)
##for n in range(3, 5):
## for i in range(n):
## forward(100)
## left(360/n)
size=36
bgcolor("black")
pensize(5)
pencolor("white")
speed(400)
for i in range(size):
rt(90);pencolor("pink")
circle(60,360)
lt(120);pencolor("yellow")
circle(90,360)
lt(120);pencolor("green")
circle(120,360)
circle(150)
print("Toi da sua file nay")
| true |
88ab14671d8ceda24786eb76c012c2f33f077258 | BattenfE8799/CSC121 | /dictionary example from instructor.py | 763 | 4.15625 | 4 | #example via instructor
petNum = int(input("How many pets do you have? "))
pets = {}
for num in range(1, petNum+1): # always add 1 to userinput # to end there
name = input("Enter name for pet "+str(num)+":") #input only takes one arguement and str(num) converts num into a string
age = input("How old is "+name+":")
print()
petType = input("What is "+name+": ")
pets.update({name: age})
print(pets)
print(f'{"Name":<10}{"Age"}{"Type"}')
print("---------------------------")
for k, v in pets.items():
# was print(f'{k:<10}{v}')
print(f'{k:<10}', end="") #seperates this and next print statement by nothing
for item in v:
print(f'{item:<10}', end="")
print()
| true |
3d50d7392672c8fc3080eeb4e1ccfa88210567a2 | burnhamup/facebook-hacker-cup | /2013/pretty.py | 1,821 | 4.125 | 4 | '''
Created on Jan 25, 2013
@author: Chris
'''
"""
The algorithim is to take the string. Make everything lowercase, strip out any thing that isn't a letter.
Calculate frequency of each letter.
Maybe create an array with each index being a different letter and the value is the frequency. Sort this.
The letter with the highest frequency is 26. This continues on down to 0.
Sum this. Return.
"""
letters = "abcdefghijklmnopqrstuvwxyz"
def countPretty(prettyString):
prettyString = ''.join(e for e in prettyString if e.isalpha())
prettyString = prettyString.lower()
frequency = {}
for letter in letters:
frequency[letter] = 0
for letter in prettyString:
frequency[letter] +=1
prettyValue = 1
result = 0
for freq in sorted(frequency.values()):
result += freq * prettyValue
prettyValue +=1
return result
def testStrings():
assert(countPretty("ABbCcc") == 152)
assert(countPretty("Good luck in the Facebook Hacker Cup this year!") ==754)
assert(countPretty("Ignore punctuation, please :)") == 491)
assert(countPretty("Sometimes test cases are hard to make up.") == 729)
assert(countPretty("So I just go consult Professor Dalves") == 646)
assert(countPretty("abcdefghijklmnopqrstuvwxyz") == 351)
baseString = ''
count = 1
expectedValue = 0
for x in letters:
baseString += (x * count)
expectedValue += (count * count)
count += 1
print baseString
assert(countPretty(baseString) == expectedValue)
def parseFile(filename):
f = open(filename)
numberOfTests = int(f.readline())
for test in range(numberOfTests):
result = countPretty(f.readline())
print "Case #"+str(test+1) + ": " + str(result)
testStrings()
#parseFile('input.txt') | true |
badf867dca7ad2e09d8b9f19c99daca10f56327f | hebertca18/tddAsgn | /Greeting_Kata.py | 1,181 | 4.125 | 4 | def greet(name):
if name is None:
name = 'my friend'
if isinstance(name, str):
if name.isupper():
string = 'HELLO ' + name + '!'
else:
string = 'Hello, ' + str(name) + '.'
else:
string = 'Hello, '
upperName = ''
sepNames = []
for n in name:
if n.isupper():
upperName = n
name.remove(n)
if n.find('\"') != -1:
newString = n.replace('\"', '')
name.remove(n)
name.append(newString)
elif n.find(',') != -1:
sepNames = n.split(', ')
name.remove(n)
for s in sepNames:
name.append(s)
for i in range(len(name)):
if i == len(name)-1:
string = string + 'and ' + name[i]
elif len(name) < 3 and i != len(name)-1:
string = string + name[i] + ' '
else:
string = string + name[i] + ', '
string = string + '.'
if upperName is not '':
string = string + ' AND HELLO ' + upperName + '!'
return string | false |
d49e21ed77380072e925dd1ff07735d96a2f0594 | nehamehta2110/LeetCode-August-Challenge | /Day2-DesignHashSet.py | 1,649 | 4.125 | 4 | """
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
"""
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.my_hash = []
def add(self, key: int) -> None:
"""
Function to add item to hash set
:param key: item
"""
if key not in self.my_hash:
self.my_hash.append(key)
print("--{} inserted in hashset".format(key))
return
print("--{} in hashset".format(key))
def remove(self, key: int) -> None:
"""
Function to remove item from hash set
:param key: item
"""
if key not in self.my_hash:
print("--{} not in hashset".format(key))
return False
else:
self.my_hash.remove(key)
print("--{} removed from hashset".format(key))
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
if key in self.my_hash:
return True
else:
return False
def main():
obj = MyHashSet()
obj.add(1)
obj.add(2)
print(obj.contains(1))
print(obj.contains(3))
obj.add(2)
print(obj.contains(2))
obj.remove(2)
print(obj.contains(2))
if __name__ == '__main__':
main()
| true |
a133dd7c5093c6bf9180947048551ef4992c2ee6 | Ranimru/Mycode | /palindrome.py | 251 | 4.15625 | 4 | def isPalindrome(String):
#this is a method to check whether a string is a Palindrome
for s in range(0,len(String)//2):
if String[s]!=String[(len(String)-1)-s]:
return False
return True
print(isPalindrome('foolloof'))
| true |
ce1f2c1d619358a2f36f790838c02addca9f15a0 | Rashmiii-00/Python-programs | /Check for palindrome and factorial of a number.py | 941 | 4.28125 | 4 | option=''
while True:
print("Enter 1 for pallindrome \n2 for factorial \n3 for Exit")
op = int(input("Enter Your choice:"))
#while op<3:
if op==1:
s2=input("Enter any String or integer ")
print()
n = len(s2)
#s1=s1.split()
s1 = list(s2)
for i in range(int(n/2)+1):
if s1[i]!=s1[n-1-i]:
break;
if i is(int(n/2)):
#if i <int(n/2):
print("Entered String is a pallindrome")
print()
else:
print("Entered String is not a pallindrome")
print()
elif op == 2:
print()
n1=int(input("Enter any number:"))
fac=1
i=1
while i<=n1:
fac = fac*i
i = i+1
print()
print("Factorial of ", n1 ," is " ,fac)
if op==3 :
break;
| false |
6a4130acf82fb745bc6688f177afc57c04c9b7ae | Ianwanarua/Password-locker | /user.py | 1,266 | 4.125 | 4 | class Users:
"""
class that generates new instances of users
"""
user_list = []
def __init__ (self,username,first_name,last_name,password):
'''
This is a blueprint that every user instance must conform to
'''
self.username = username
self.first_name = first_name
self.last_name = last_name
self.password = password
def save_users(self):
"""Method to save new account to the user_list
"""
Users.user_list.append(self)
@classmethod
def user_exist(cls, username, password):
'''
Method that checks if a user exists from the user list.
Returns :
Boolean: True or false if the user exists
'''
for user in cls.user_list:
if user.username == username and user.password == password:
return True
return False
@classmethod
def findby_username(cls, username):
""" Method to find user by searching their username
"""
for user in cls.user_list:
if user.username == username:
return user
| true |
78833a4cb9fb94c912be389f227cdf7aa85aa310 | DanielMalheiros/geekuniversity_logica_de_programacao | /Python/secao06/exercicio10.py | 768 | 4.15625 | 4 | """Seção 06 - Exercício 10
Elabore um algoritmo que dada a idade de um nadador classifique-o em uma das seguintes categorias:
Infantil-a = 5 a 7 anos
Infantil-b = a 11 anos
Juvenil-a = 12 a 13 anos
Juvenil-b = 14 a 17 anos
Adultos = Maiores de 18 anos
"""
# entrada
idade = int(input("Qual a idade do nadador? "))
# processamento e saída
if idade < 5:
print("A idade minima para competir é de 5 anos.")
elif idade >= 5 and idade <= 7:
print("Categoria Infantil-A.")
elif idade >= 8 and idade <= 11:
print("Categoria Infantil-B.")
elif idade >= 12 and idade <= 13:
print("Categoria Juvenil-A.")
elif idade >= 14 and idade <= 17:
print("Categoria Juvenil-B.")
elif idade > 18:
print("Categoria Adultos.")
| false |
fa232e5df4a0bdb2e99b702b953ba73e3acbd353 | chenyongda2018/PythonShortTerm | /课件/example/example_05.py | 442 | 4.15625 | 4 | #string
char_1 = 'A'
print(ord(char_1))
char_1 = 'Z'
print(ord(char_1))
char_1 = 'a'
print(ord(char_1))
char_1 = 'z'
print(ord(char_1))
#--------------------------------
number_1 = 65
print(chr(number_1))
#---------------------------------
str1 = 'hello'
print(len(str1))
str2 = '你好'
print(len(str2))
#------------------------------------
#二进制
data = str2.encode('utf-8')
print(data)
str3 = data.decode('utf-8')
print(str3)
| false |
cb8b44720c634935d9c2337af1f9d1d4d401d5fb | chenyongda2018/PythonShortTerm | /day03/demo03_python_dict.py | 690 | 4.40625 | 4 | # 定义词典
dict1 = {'no1' :{'name':'zhangsan', 'age' :20, 'sex' : 'male'}, 'no2':{'name' :'list', 'age' :30, 'sex' :'male'}}
# 访问字典,也是用类似数组下标索引的方式
print(dict1['no1'])
print(dict1['no1']['name'])
# 怎么来得到字典里所有的key
for key in dict1.keys():
print(key)
# 怎样来得到所有的value
print(dict1.values())
# 通过get key来得到key对应的value
print(dict1.get('key'))
# items返回以key和value自称的一个元祖列表
print(dict1.items())
# updata
dict2 = {'no2' : 11111, 'no3' :22222}
dict1.update(dict2)
print(dict1)
# pop会删除元素而且会返回对应key的value
value = dict1.pop('no1')
print(value)
| false |
7bdb3cbdd71b2b342270621c08dfb68c7e58f448 | chenyongda2018/PythonShortTerm | /day03/demo01_python_list.py | 1,089 | 4.34375 | 4 | # 定义list
lista = [1, 'xiaojiejie', 20, 'female']
print(type(lista))
print(lista)
# 遍历列表
for element in lista:
print(element)
pass
# 下标取列表元素
print(lista[1])
# 使用range来生成list
listb = list(range(10))
print(listb)
# 生成0到10的偶数
listc = list(range(0, 10, 2))
print(listc)
print(range(10))
# list切片
listd = list(range(20))
print(listd)
print(listd[0:10])
print(listd[0:20:2])
# list是可变数据类型
listd.append(20)
print(listd)
listd.insert(5, 20000)
print(listd)
listd.remove(listd[5])
print(listd)
# + *
print(listd+listd)
print(listd * 10)
# list嵌套
liste = [1, 2, 3, 4, 5]
liste.append(list(range(6, 11)))
print(liste)
print(liste[5][0])
# 打散插入
listf = list("abcdefg")
print(listf)
print(len(listf))
print(max(listf))
print(min(liste))
# list排序
listg = [4, 1, 2, 6, 3, 5, 0]
listg.reverse()
print(listg)
listg.sort(reverse = True)
print(listg)
# [:]深复制
listh = list(range(20))
listi = listh
listi[0] = 200
print(listh)
listj = listh[:] # 深复制
listj[0] = 20000
print(listj)
print(listh) | false |
83b774feafd4887d086285205a027c660d36d86f | MarkParenti/intermediate-python-course | /dice_roller.py | 569 | 4.15625 | 4 | import random
def main():
dice_sum = 0
dice_rolls = int(input("How many dice would you like to roll?"))
sides = int(input("How many sides should the die have?"))
for i in range(0, dice_rolls):
roll = random.randint(1,sides)
if roll == 1:
print(f'You rolled a {roll}! Critical Fail')
elif roll == sides:
print(f'You rolled a {roll}! Critical Success!')
else:
print(f'You rolled a {roll}')
dice_sum = dice_sum + roll
if dice_rolls != 1:
print(f"Your total is {dice_sum}!")
if __name__== "__main__":
main() | true |
ec9786119c231f6a43b75cbae4b2bf33318bf701 | MinwooRhee/unit_two | /d4_unit_two_warmups.py | 237 | 4.15625 | 4 | print(9 * 5)
print(2 / 5)
# // sign is integer division
print(12 // 5)
print(27 // 4)
print(2 // 5)
# % sign gives the remainder
# very useful when telling odd or even number
print(5 % 2)
print(9 % 5)
print(6 % 6)
print(2 % 7)
| true |
2253395f3a5f76f00452f3bf03067af3d1d95d7b | amogh-dongre/dotfiles | /python_projects/Binary_search.py | 729 | 4.21875 | 4 | #!/usr/bin/env python3
# This is the python implementation of Binary search
def Binary_searcher(arr, l, f, num):
while f <= l:
mid_index = (l + f) / 2
if num == arr[mid_index]:
return mid_index
elif num < arr[mid_index]:
f = mid_index + 1
else:
l = mid_index - 1
return -1
arr = []
print("Enter 10 number to be added into the array")
for i in range(0, 9, 1):
ele = int(input())
arr.append(ele)
print("Enter a number to be searched in the array")
num = int(input())
result = Binary_searcher(arr, 0, len(arr) - 1, num)
if result != -1:
print(f"the value is present at index {result}")
else:
print("the value you entered is not present")
| true |
644e2b5ae4e9dce423e812d548f9a3999fd42ae2 | ihuei801/leetcode | /MyLeetCode/python/Merge k Sorted Lists.py | 2,446 | 4.1875 | 4 | #######################################################################
# Priority Queue
# Time Complexity: O(nk*log k) k:num of lists n: num of elements
# Heap implementation: http://algorithms.tutorialhorizon.com/binary-min-max-heap/
# A binary heap is a heap data structure created using a binary tree.
# Two rules -
# 1) Shape property: Binary heap has to be omplete binary tree at all levels except the last level.
# 2) Heap property: All nodes are either greater than equal to (Max-Heap) or less than equal to (Min-Heap) to each of its child nodes.
# Heap insert/delete: O(log n)
#
# Python heappop, heappush
# You can use tuples, and it will sort by the first element of the tuple
#######################################################################
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
if not lists:
return None
pq = []
for lst in lists:
if lst:
heapq.heappush(pq, (lst.val, lst))
dummy = cur = ListNode(None)
while pq:
v, nd = heapq.heappop(pq)
cur.next = nd
cur = cur.next
if nd.next:
heapq.heappush(pq, (nd.next.val, nd.next))
return dummy.next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
from Queue import PriorityQueue
if not lists:
return None
pq = PriorityQueue()
for lst in lists:
if lst:
pq.put((lst.val, lst))
dummy = cur = ListNode(None)
while not pq.empty():
v, nd = pq.pop()
cur.next = nd
cur = cur.next
if nd.next:
pq.put((nd.next.val, nd.next))
return dummy.next
| true |
a5cc6bdbd44719c30639f8bf040f1ac3fa2d7066 | jdlambright/Hello-World | /100 Days/day 20-29/24 notes/read_write.py | 1,464 | 4.25 | 4 | #these are notes on how to open write and read files
#the first way. this is less efficient because you have to remember to close it
#open is a built in keyword
# file = open("my_file.txt")
#
# #read method returns contents of file as a string
# #we save it into a variable
# contents = file.read()
#
# print(contents)
#
# #we always need to close the file to not waste computers resources
# file.close()
#________________________Better way_________________
#this is a much more efficient way "file" is a variable
# with open("my_file.txt") as file:
# contents = file.read()
# print(contents)
#writing to a file
#the open method defaults to read only
#mode= "w" puts it in writing mode which replaces all text
#mode= "a" allows you to append to end of file
# with open("my_file.txt", mode="a") as file:
# file.write("\nnew text")
#you can create a brand new file by putting it in writing mode
#and by giving the file a name in the string example:
# with open("new_file.txt", mode = "w") as file:
# file.write("\nNew Text")
#in the snake scoreboard on lines 11-12 we wrote this to retrieve the data
#and set high score as a variable to that data
with open("data.txt") as quote:
self.high_score = int(quote.read())
#in lines 26-28 we wrote this to erase and rewrite the current data if a new high score was acheived
new_score = str(self.high_score)
with open("data.txt", mode="w") as file:
file.write(new_score) | true |
0ed789707b311da154308a4c38bca69fe5e72024 | Naouali/Leetcode_Python | /climbing_stairs.py | 213 | 4.15625 | 4 | #!/usr/bin/python3
def staire(n):
step = n
value = 0
while n > 0:
n = n - 2
if n < 0:
break
value += 1
return value + step
print(staire(3))
print(staire(3))
| false |
622dad3a18f2f2acd6614d81702ca71370b7b98b | pyl135/Introduction-to-Computing-using-Python | /Unit 4- Data Structures/Ch 4.4- File Input and Output/Reading Files in Python 1.py | 942 | 4.3125 | 4 | #Write a function called "find_coffee" that expects a
#filename as a parameter. The function should open the
#given file and return True if the file contains the word
#"coffee". Otherwise, the function should return False.
#
#Hint: the file.read() method will return the entire
#contents of the file as one big string. You can use that
#to make this simpler instead of using readline().
#Write your function here!
def find_coffee(name):
output = open(name, "r")
word = output.read()
if not word.find("coffee")== -1:
return True
else:
return False
#You can test your function with the provided files named
#"coffee.txt" and "nocoffee.txt". With their original
#text, the lines below should print True, then False. You
#may also edit the files by selecting them in the drop
#down in the top left to try your code with different
#input.
print(find_coffee("coffee.txt"))
print(find_coffee("nocoffee.txt"))
| true |
122f50f5a0e6298094df98172406ed300afd6690 | pyl135/Introduction-to-Computing-using-Python | /Unit 5- Objects and Algorithms/Ch 5.2- Algorithms/Coding Problem 5.2.5.py | 1,321 | 4.375 | 4 | #Write a function called string_search() that takes two
#parameters, a list of strings, and a string. This function
#should return a list of all the indices at which the
#string is found within the list.
#
#You may assume that you do not need to search inside the
#items in the list; for examples:
#
# string_search(["bob", "burgers", "tina", "bob"], "bob")
# -> [0,3]
# string_search(["bob", "burgers", "tina", "bob"], "bae")
# -> []
# string_search(["bob", "bobby", "bob"])
# -> [0, 2]
#
#Use a linear search algorithm to achieve this. Do not
#use the list method index.
#
#Recall also that one benefit of Python's general leniency
#with types is that algorithms written for integers easily
#work for strings. In writing string_search(), make sure
#it will work on integers as well -- we'll test it on
#both.
#Write your code here!
def string_search(aList,aStr):
index = 0
result =[]
for i in aList:
if i == aStr:
result.append(index)
index +=1
elif index > len(aList)-1:
return []
else:
index += 1
return result
#Feel free to add code below to test your function. You
#can, for example, copy and print the test cases from
#the instructions.
print(string_search(["bob", "burgers", "tina", "bob"], "bob"))
| true |
bd3c39f51cf2831fa120921591769c1699e4208f | TytarenkoVictor/Travel_planner_project | /date_estimation.py | 2,342 | 4.15625 | 4 | import datetime
class CheckDate:
"""This class checks users input dates."""
def __init__(self, d1, d2):
"""This method initializes."""
self.day1 = d1.split('/')[0]
self.day2 = d2.split('/')[0]
self.month1 = d1.split('/')[1]
self.month2 = d2.split('/')[1]
self.year1 = d1.split('/')[2]
self.year2 = d2.split('/')[2]
def check_date(self):
"""This method checks is user input is date or in correct format
dd/mm/yy"."""
correct = True
try:
datetime.datetime(int(self.year1), int(self.month1), int(self.day1))
datetime.datetime(int(self.year2), int(self.month2), int(self.day2))
except ValueError:
correct = False
if correct:
return True
else:
return False
def check_two(self):
"""This method checks if two date are relevant and not too long
or too short period between them."""
if not self.check_date():
return "Incorrect date format. Please, try again."
curr_year = str(datetime.date.today()).split()[0].replace("-", "/")[2:4]
curr_month = str(datetime.date.today()).split()[0].\
replace("-", "/")[5:7]
curr_date = str(datetime.date.today()).split()[0].\
replace("-", "/")[8:10]
if self.year1 != curr_year or self.year2 != curr_year:
return "You can plan your trip by the end of this year. \
Aviaticket for next year will be avaible later"
time1 = datetime.date(year = int("20" + self.year1), \
month = int(self.month1), day = int(self.day1))
time2 = datetime.date(year = int("20" + self.year2), \
month = int(self.month2), day = int(self.day2))
if time1 <= datetime.date.today() or time2 <= datetime.date.today():
return "Your date Incorrect. Please, try again."
final_time = time2 - time1
total_days = int(str(final_time).split()[0])
if 0 < total_days < 3:
return "Interval between date too short."
if total_days <= 0:
return "Incorrect date. Please, try again."
elif total_days > 21:
return "Interval between your date too large."
else:
return True
| true |
a3f2ac2183a06475c23408002fdef2f8cbec0e1c | GarethOLeary/GraphTheory_WeeklyExercises | /basics.py | 535 | 4.125 | 4 | #Gareth O'Leary
#Python Basics
#print("Hello World")
a = 1
b = 1.0
s = "Hello, world from a string!"
t = 'Hello, from a different string'
#print (a,b,s,t)
#print(s[3:10:2])
x = [1,2,3,"Hello",1.0]
#print(x)
#print(x[0])
#print(x[2])
#print(x[-1])
#for i in x[::2]:
# print(i)
# print(i + i)
#for i in range(10):
# print(i)
d = {"no_wheels": 4, "make": "Skoda"}
print(d["no_wheels"])
d["model"] = "Superb"
print(d["model"])
r = [1,2,3,4]
print(r)
s = [i*i for i in r]
print(s) | false |
dcd775541280e0ed58433e8cb652c745e87484c7 | Zhamshid2121/2.7 | /hw.py | 457 | 4.375 | 4 | #Создайте класс. Добавьте к классу 3 параметра. Напишите
# 1 метод, который будет выводить
# на экран все 3 параметра. Создайте экземпляр класса.
# Вызовите его метод
class Jon:
born = 15
height = 50
step = 25
def men(self):
return self.born + self.height +self.step
c = Jon()
c.men()
print(c.men()) | false |
0e7d762c83a93f480cf1494236eaacd04d6aa92f | flores-jacob/exercism | /python/meetup/meetup.py | 748 | 4.15625 | 4 | from datetime import date
import calendar
def meetup_day(year, month, day_of_the_week, which):
if which == "teenth":
date_range = range(13, 20)
elif which == "last":
last_day_of_month = calendar.monthrange(year, month)[1]
date_range = range(last_day_of_month, 1, -1)
else:
date_range = range(1, 31)
count_req_dict = {"1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "5th": 5, "last": 1, "teenth": 1}
day_count = 0
count_req = count_req_dict[which]
for day in date_range:
desired_date = date(year, month, day)
if calendar.day_name[desired_date.weekday()] == day_of_the_week:
day_count += 1
if day_count == count_req:
return desired_date
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.