blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
300a518ca7f1ffb6f6e1cbda05508feffbe3a0c7 | joeiv1220/Joei | /Joei Vargas Dictionary CS10.py | 891 | 4.15625 | 4 | def a_def():
return 'adds an element to a list'
def d_def():
return 'digit; used to call digit variables'
def r_def():
return 'answer to a variable that makes the user input information'
def e_def():
return 'concatenates the first list with another list\
(or another iterable not necessarily a list.)'
def o_def():
return 'Using this on the beginning of a line with comment out the rest\
of the line'
def d():
AP = 'Append-',a_def()
DIGITS = '%d-', d_def()
RI = 'raw_input()-', r_def()
# CON = "CON",three_best_d6()
#INT = "INT",three_best_d8()
EX = 'Extend-', e_def()
OCT = 'Octothorpe (#)-',o_def()
#CHA = "CHA",three_best_d8()
d = [AP, DIGITS, EX, OCT, RI]
return (d)
print " Find the definition to words associated with Python by inputing\
'd()'."
| true |
4fb739170b82330391f311a4077e3f69a574003e | akkuzu/dictionary-example-python | /dictionaries.py | 951 | 4.125 | 4 |
'''
A data type in Python.
Dictionaries are indexed by keys and these keys can be a String and integer type.
Shown as key:value pairs and keys are the unique values.
'''
d={}
print(d)
print(type(d))
d={"python":1 , "course":2}
print(d)
d2= {"machine":"learning","artificial":"intelligence"}
print(d2)
print(d2["artificial"])
d2["java"]= "programming"
print(d2)
d2["ruby"] = "language"
print(d2)
print(d)
print(d["course"])
print(d.keys())
print(d2.keys())
for k in d2.keys():
print(k)
for v in d2.values():
print(v)
for k,v in d.items():
if v == 2:
print(k)
d["a"]=[3,4,5]
print(d)
d.pop("python")
print(d)
print(len(d))
d2.get("artificial")
d4 = {"human":2,
"cat":4,
"spider":8
}
for i in d4:
leg = d4[i]
print("%s has %d legs " % (i,leg))
print(str(i) + " has " + str(leg) +" legs.")
d4 = {"human":2, "cat":4, "spider":8}
for i,leg in d4.items():
print(str(i) + " has " + str(leg) +" legs.")
| false |
351320cb7113cd525f19715d4d5c814450078160 | gutovianna88/learning_python | /ListaDeExercicios/ExerciciosFuncoes/4.py | 549 | 4.125 | 4 | """
Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’,
se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
"""
def verification_number(number):
if type(number) is float:
if number > 0:
return "P"
else:
return "N"
else:
return False
n = input("Informe um numero: ")
n1 = n.replace("-","")
if n1.isnumeric():
n = float(n)
print(verification_number(n))
else:
print("Caractere invalido! ") | false |
f84e469386cacb8bab91526fc8b2a2c212d49eb1 | gutovianna88/learning_python | /ListaDeExercicios/EstruturaDeRepeticao/21.py | 334 | 4.125 | 4 | """
Faça um programa que peça um número inteiro e determine se ele é ou não um número primo. Um número primo é aquele que é divisível somente por ele mesmo e por 1.
"""
number = int(input("Digite um numero para verificar se este numero é primo: "))
if number % 2 >= 1:
print("Primo ")
else:
print("Não é primo ")
| false |
b150d2e3c838b03750c32988186fb7ab20971906 | gutovianna88/learning_python | /tests/testse.py | 546 | 4.1875 | 4 | print("1- soma");
print("2- multiplicacao");
print("3- divisao");
print("4- subtrai");
primeiro_numero = float(input("primeiro_numero?"));
segundo_numero = float(input("Qual segundo numero?"));
operacao = input("O que quer meu rei?");
if (operacao =="1"):
print(primeiro_numero + segundo_numero);
elif (operacao =="2"):
print(primeiro_numero * segundo_numero);
elif (operacao =="3"):
print(primeiro_numero / segundo_numero);
elif (operacao =="4"):
print(primeiro_numero - segundo_numero);
else:
print("Operação invalida"); | false |
a0dd40a2a67fd82c7b9a92260cd96f00ae93a684 | gutovianna88/learning_python | /ListaDeExercicios/EstruturaDeRepeticao/27.py | 725 | 4.15625 | 4 | """
Faça um programa que calcule o número médio de alunos por turma.
Para isto, peça a quantidade de turmas e a quantidade de alunos para cada turma.
As turmas não podem ter mais de 40 alunos.
"""
classes = int(input("Informar a quantidade de turmas a serem consideradas: "))
total_classes = 0
students_grids = []
while total_classes < classes:
class_by_class = int(input("Informe a quantidade de alunos a considerar para esta turma: "))
if class_by_class <= 40:
students_grids.append(class_by_class)
total_classes = total_classes +1
else:
print("Quantidade acima da permitida! ")
student_media = sum(students_grids)/ classes
print(" Média de alunos por turma ", student_media)
| false |
70cfb001a2351ffe2c5e7413b40b7f3dd56cc2ff | fyfmbs/stanCode_Project | /weather_master/quadratic_solver.py | 1,263 | 4.625 | 5 | """
File: quadratic_solver.py
Name: Shawn Chan
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation:
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
def main():
"""
This is a calculator to help user finding out the roots of the quadratic equation.
"""
print('stanCode Quadratic Solver!')
a = float(input("What's the coefficient of x^2? "))
b = float(input("What's the coefficient of x? "))
c = float(input("What's the constant of the equation? "))
discriminant = b*b - 4*a*c
if discriminant == 0:
# The variable "root" stands for the only root of the quadratic equation.
root = -b/(2*a)
print('One root: ' + str(root))
elif discriminant > 0:
# The variable "sq_rt" stands for the square root of discriminant.
sq_rt = math.sqrt(discriminant)
# The variables "root1" & "root2" stand for the two real roots of the quadratic equation.
root1 = (-b + sq_rt) / (2*a)
root2 = (-b - sq_rt) / (2*a)
print('Two roots: ' + str(root1) + " , " + str(root2))
else:
print('No real roots')
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
1d18d074ab4a1c086d49a365164cb6b6c5df000f | pragmatizt/coffee_challenges | /simple_recursion.py | 727 | 4.21875 | 4 | # Simple summation of a given integer
# 4: 4 + 3 + 2 + 1 = 10
# 3: 3 + 2 + 1 = 6
# First, let's see the iterative solution
def iterative_sum_integer(n):
sum = 0
for i in range(n + 1):
sum = sum + i
return sum
print('Iterative Solutin:', iterative_sum_integer(2))
print('Iterative Solutin:', iterative_sum_integer(3))
print('Iterative Solutin:', iterative_sum_integer(4))
# Now let's check out the recursive solution
def recursive_sum_integer(n):
if n == 0:
return 0
else:
return recursive_sum_integer(n-1) + n
print('Recursive Solution:', recursive_sum_integer(2))
print('Recursive Solution:', recursive_sum_integer(3))
print('Recursive Solution:', recursive_sum_integer(4))
| false |
b17097bfcfa1e6897f03fc163d4802dcbb38ee33 | fabiosabariego/curso-python | /pacote-download/Python/modulo01/python01ex/ex009.py | 824 | 4.25 | 4 | # ------------------------- DESAFIO 009 -------------------------
# Programa para ler um numero inteiro, e mostrar a sua tabuada
num = int(input('Digite um numero: '))
x1 = num * 1
x2 = num * 2
x3 = num * 3
x4 = num * 4
x5 = num * 5
x6 = num * 6
x7 = num * 7
x8 = num * 8
x9 = num * 9
x10 = num * 10
print('A Tabela de tabuada do numero {} é:'.format(num))
print('-' * 20)
print('{} x {:2} = {}'.format(num, 1, x1))
print('{} x {:2} = {}'.format(num, 2, x2))
print('{} x {:2} = {}'.format(num, 3, x3))
print('{} x {:2} = {}'.format(num, 4, x4))
print('{} x {:2} = {}'.format(num, 5, x5))
print('{} x {:2} = {}'.format(num, 6, x6))
print('{} x {:2} = {}'.format(num, 7, x7))
print('{} x {:2} = {}'.format(num, 8, x8))
print('{} x {:2} = {}'.format(num, 9, x9))
print('{} x {:2} = {}'.format(num, 10, x10))
print('-' * 20) | false |
f1a9211db0fc47d610e8c7373192dadb78914723 | fabiosabariego/curso-python | /pacote-download/Python/modulo01/python01ex/ex059.py | 1,180 | 4.34375 | 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 do Programa
Seu programa deverá realizar a opção solicitada em cada caso
"""
print('-=' *20)
num1 = float(input('Digite um Valor: '))
num2 = float(input('Digite outro Valor: '))
menu = 1
while 1 <= menu <= 4:
menu = int(input("""\n========== MENU ==========
[1] Somar
[2] Multiplicar
[3] Maior Numero
[4] Novos Numeros
[5] Sair do Programa
Digite sua Opção: """))
if menu == 1:
print('\nOpção [1] - SOMA!!')
print('{:.1f} + {:.1f} = {:.1f}\n'.format(num1, num2, num1 + num2))
elif menu == 2:
print('\nOpção [2] - Multiplicação!!')
print('{:.1f} x {:.1f} = {:.1f}\n'.format(num1, num2, num1 * num2))
elif menu == 3:
if num1 > num2:
print('\nO maior número é o {:.1f}'.format(num1))
else:
print(('\nO menor número é o {:.1f}'.format(num2)))
elif menu == 4:
print('\n')
print('-=' *20)
num1 = float(input('Digite um Valor: '))
num2 = float(input('Digite outro Valor: '))
print('\nObrigado Por usar o Programa!!!') | false |
c3bf88dc9410aed318e722c582c8ebf857abfc0c | fabiosabariego/curso-python | /pacote-download/Python/modulo01/python01ex/ex036.py | 853 | 4.25 | 4 | # Escreva um programa para aprovar o emprestimo bancario de uma Casa. O programa deve perguntar o VALOR DA CASA, o
# SALARIO do comprador e em QUANTOS ANOS ele vai pagar. Calcular o valor da prestacao mensal, sabendo que ela nao
# pode exceder 30% do salario ou entao o emprestimo sera negado
valor = float(input('Diga o Valor do Imovel: '))
sal = float(input('Diga seu Salario: '))
prazo = int(input('Quantos anos para Pagar: '))
parcela = valor / prazo
print('O valor da casa de R${:.2f}, divido em {}x, resultara em uma parcela de R${:.2f}.'.format(valor, prazo, parcela))
if parcela > (sal * 0.30):
print('O valor da parcela excede a 30% do valor do comprador (R${:.2f}), emprestimo negado!'.format(sal * 0.30))
elif parcela <= (sal * 0.30):
print('O valor e inferior a 30% do salario (R#{:.2f}), emprestimo liberado!'.format(sal * 0.30))
| false |
f4b6213419d4a1e8ac1fd2ede3c2c8c8f590ffea | Rajan-Chaurasiya/Python-Practice | /swapping_of_two.py | 610 | 4.34375 | 4 | #using temp variable
#num1 = input("enter a first number:")
#num2 = input("enter a second number:")
#print("value of num1 before swap:", num1)
#print("value of num2 before swap:", num2)
#temp = num1
#num1 = num2
#num2 = temp
#print("value of num1 after swap:",num1)
#print("value of num2 after swap:",num2)
#without using temp variable
num1 = input("enter a first number:")
num2 = input("enter a second number:")
print("value of num1 before swap:", num1)
print("value of num2 before swap:", num2)
num1, num2 = num2, num1
print("value of num1 after swap:",num1)
print("value of num2 after swap:",num2) | true |
ed04da1fb0887b4829cd5d1a022cd8c874bb295c | amirholyanasabn/Python | /Session-04/infinitySecond.py | 538 | 4.125 | 4 | numbers = []
main_flag = True
while main_flag is True :
in_string = input('Enter number : ')
numbers.append(float(in_string))
second_flag = False
while second_flag is False :
temp = input('Do you want to continue(y/n) ? ')
if temp == 'n':
second_flag = True
main_flag = False
elif temp == 'y':
second_flag =True
main_flag =True
else :
print('Only answer y or n ...')
numbers.sort()
print('list of number {} '.format(numbers))
| true |
7c92022173bb8694329160edf15e6bbb24a46a75 | rogerchang910/stanCode-projects | /stanCode projects/weather_master/weather_master.py | 1,049 | 4.1875 | 4 | """
File: weather_master.py
Name: Roger(Yu-Ming) Chang
-----------------------------------------------
This program should implement a console program
that asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
Output format should match what is shown in the sample
run in the Assignment Handout.
"""
# Constant
EXIT = -100 # Controls when to end the program.
def main():
t_lst = []
cold_day = 0
print('stanCode \"Weather Master 4.0\" !')
t = int(input('Next Temperature: ' + '(or ' + str(EXIT) + ' to quit?) '))
if t == EXIT:
print('No temperature were entered.')
else:
t_lst.append(t)
while True:
t = int(input('Next Temperature: ' + '(or ' + str(EXIT) + ' to quit?) '))
if t == EXIT:
break
t_lst.append(t)
for t in range(len(t_lst)):
if t < 16:
cold_day += 1
print('Highest Temperature:', max(t_lst))
print('Lowest Temperature:', min(t_lst))
print('Average:', sum(t_lst)/len(t_lst))
print(str(cold_day) + ' cold day(s).')
if __name__ == "__main__":
main()
| true |
88ca49f83727e5268bbeb833a757f3b03da564d6 | LoriWhite24/Tic-Tac-Toe | /player.py | 1,466 | 4.125 | 4 | """
Author: Lori White
"""
class Player:
"""
This represents a player in the game.
"""
def __init__(self):
"""
Intializes the player
"""
self.is_first = False
self.game_token = "O"
self.is_winner = False
self.player_name = "name"
self.num_placed_tokens = 0
def player_reset(self):
"""
Resets the player
"""
self.is_first = False
self.is_winner = False
self.num_placed_tokens = 0
def place_game_token(self):
"""
Updates the number of game tokens that player has placed
"""
self.num_placed_tokens += 1
if self.is_first:
assert (self.num_placed_tokens <= 5), f"Player 1, " \
+ f"{self.player_name}, has exceded the number of " \
+ "game token placement."
else:
assert (self.num_placed_tokens <= 4), f"Player 2, " \
+ f"{self.player_name}, has exceded the number of " \
+ "game token placement."
def get_name(self, is_player_one):
"""
Prompts player for name based on if they are player one or player two
"""
if is_player_one:
self.player_name = input("Player 1, what is your name? ")
self.is_first = True
self.game_token = "X"
else:
self.player_name = input("Player 2, what is your name? ")
| true |
adfa06eadcf3bc456f384cdd49d28ba07a8ed1e3 | arsezzy/python_base | /lesson4/lesson4_2.py | 1,302 | 4.28125 | 4 | #!/usr/bin/python3
digit_list = [1, 6, 1, 3, 6, 2, 2, 6, 5, 7, 10, 4]
print(f"Initial list is \n{digit_list}")
#First variant - maybe not a generator ?
#Next element is bigger than previous in final list
print("First variant, next element is bigger than previous in final list")
new_list = []
for el in digit_list:
try: #for including first element from initial list
if el > new_list[-1]:
new_list.append(el)
except IndexError:
new_list.append(el)
print(new_list)
#second variant
#Next element is bigger than previous in final list
print("Second variant, next element is bigger than previous in final list")
def generator(my_list):
max = my_list[0] - 1 # for including first element from initial list
for el in (my_list):
if el > max:
max = el
yield el
print(list(generator(digit_list)))
#Third variant
#Next element is bigger than previous in initial list
print("Third variant, next element is bigger than previous in initial list")
def generator(my_list):
previous = my_list[0] - 1 # for including first element from initial list
for el in (my_list):
if el > previous:
previous = el
yield el
previous = el
print(list(generator(digit_list)))
| true |
dba7cad9a4105cff1c98c8a125043ba1aea38307 | arsezzy/python_base | /lesson1/lesson1_6.py | 305 | 4.15625 | 4 | #!/usr/bin/python3
km = int(input("Please enter how many kilometers"
"runner can do on the first day: "))
target_km =int(input("Please enter target kilometers per day: "))
days = 1
while km < target_km:
km *= 1.1
days += 1
print(f"Runner is needed to train for {days} days")
| true |
3c1e311de55210a9f715b464dc358082a13a5f20 | densaiko/coding-challenge | /sort number from ascending.py | 1,146 | 4.34375 | 4 | # sort number from ascending is the simple coding challenge. However, it will be useful to sort the number to get
# the structured data
# This solution is a solution that you pretend to code. But no problem about that, lets we pretend to code :)
# OR, if you think you don't need to pretend, you can simply use the 'sorted' function to sort number from ascending :(
# I pretend to code :)
# I consider time and space complexity down below:
# - Time complexity O(n) because I only use one variable i to loop the entire number in list
# - Space complexity O(1) because I don't need an empty list to keep the number
# Lets find the solution
class solution():
def sort_num_ascending(self, nums):
nums_one = 0
nums_two = 0
nums_three = 0
for n in nums:
if n == 1:
nums_one = 1 + nums_one
elif n == 2:
nums_two = 1 + nums_two
elif n == 3:
nums_three = 1 + nums_three
return [1]*nums_one + [2]*nums_two + [3]*nums_three
nums = [3, 3, 2, 1, 3, 2, 1]
solution().sort_num_ascending(nums)
| true |
564c4a2b21c171fef4de6f7f8f4046abba92da9d | marmiod1/pythonowe_przygody | /09_Czas na pracę ze stringami/zmiana_znaków_dodatkowe_funkcje.py | 2,462 | 4.21875 | 4 | """Napisz program, który dla podanego łańcucha znaków zamieni podaną pozycję na jakiś znak (też podany przez użytkownika).
Funkcja, która dokona zamiany znaku z podanej pozycji musi sprawdzić, czy wskazana pozycja jest prawidłowa
(nie możemy zmienić szóstego znaku, podczas gdy łańcuch ma tylko 5 znaków).
Funkcja powinna przyjmować 3 parametry (łańcuch do analizy, pozycję, którą należy podmienid i znak, który ma służyć do podmiany).
Niech program wyświetla łańcuch przed i po zamianie.
"""
def new_word():
origin_word = get_input_origin_word()
swap_letters_location = get_input_swap_letters_location()
swap_letters = get_input_swap_letters()
begging_swap_letters_location = swap_letters_location - 1
swap_letters_length = len(swap_letters)
end_swap_letters_location = begging_swap_letters_location + swap_letters_length
first_part_new_word = origin_word[:begging_swap_letters_location]
last_part_new_word = origin_word[end_swap_letters_location:]
if swap_letters_location > len(origin_word):
print("Origin word is too short")
elif swap_letters_length <= len(origin_word) and swap_letters_location > 0 \
and swap_letters_length <= len(origin_word[begging_swap_letters_location:]):
new_word = [first_part_new_word, swap_letters, last_part_new_word]
new_word = ''.join(new_word)
print("The origin word was: {}".format(origin_word))
print("The word word is: {}".format(new_word))
else:
print("There are too many letters to swap")
def get_input_origin_word():
while True:
origin_word = input("Please enter the word we will modify: ")
if origin_word.isalpha():
return origin_word
else:
print("You need to enter correct word.")
def get_input_swap_letters_location():
while True:
swap_letters_location = input("Please give the position of the letter from which we will start to change: ")
try:
swap_letters_location = int(swap_letters_location)
return swap_letters_location
except ValueError:
print("Enter correct value")
def get_input_swap_letters():
while True:
swap_letters = input("Please enter the new letters you want to insert: ")
if swap_letters.isalpha():
return swap_letters
else:
print("You need to enter correct word.")
new_word()
| false |
e8cc25014c75678bd04de5ef52878429d5450692 | AngelRamos99/AprendaPython | /Palindromo.py | 335 | 4.125 | 4 | palabraOriginal = input('Ingrese una palabra: ')
palabraOriginal = palabraOriginal.replace(' ', '')
palabraAlRevez = palabraOriginal[::-1]
if palabraOriginal == palabraAlRevez:
print(f'La palabra {palabraOriginal} es una palabra palíndroma')
else:
print(f'La palabra {palabraOriginal} NO es una palabra palíndroma')
| false |
f6ef8f821d942ecebc1cd7b5bf9e9f7485ef41bb | hawaiianpizzaguy/MIT-OCW-6.00SC-Problem-Sets | /hangman/ps2_hangman.py | 2,681 | 4.125 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# Name : Connor Wyandt
# Collaborators : <your collaborators>
# Time spent : <total time>
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print ("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print (" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
wordlist = load_words()
def hangman():
incorrect_guesses = 0
found_secret_word = ''
print('Welcome to the game, Hangman')
secret_word = choose_word(wordlist).lower()
print('I am thinking of a word that is %d letters long' %(len(secret_word)))
num_guesses = 8
guessed_letters = {}
while(True):
print("___________")
print("You have %d guesses left" %(num_guesses))
print("Available Letters: " + get_available_letters(guessed_letters))
new_letter = request_letter(secret_word, guessed_letters)
if new_letter in secret_word:
print("Good guess: " + get_secret_word(secret_word, guessed_letters))
else:
print("Oops! That letter is not in my word " \
+ get_secret_word(secret_word, guessed_letters))
incorrect_guesses -= 1
if incorrect_guesses == 0:
print("Sorry, you ran out of guesses. The word was " \
+ secret_word + ". Play again!")
break
if found_secret_word(secret_word, guessed_letters):
print("Congratulations, you won!")
break
def get_secret_word(secret_word, guessed_letters):
visible_word = ""
for letter in secret_word:
if letter in guessed_letters:
visible_word += letter
else:
if len(visible_word) > 0 and visible_word[-1] == '_':
visible_word += " "
visible_word += "_"
return visible_word
def found_hidden_word(secret_word, guessed_letters):
for letter in secret_word:
if letter not in guessed_letters:
return False
return True
def get_available_letters(guessed_letters):
available_letters = ""
for letter in string.lowercase:
if letter not in guessed_letters:
available_letters += letter
return available_letters
def request_letter(secret_word, guessed_letters):
used_letters = ''
new_letter = input("Please guess a letter: ").lower()
used_letters[new_letter] = 1
return new_letter
hangman()
| true |
6d2aadc191526bcf0f87ca35d3b57f1147c467c2 | wangyibin/bioway | /NumParse/ordnum.py | 835 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class ordnum:
"""
Return the corresponding ordinal number of a number.
Such as 21>21st; 11>11th; 3>3rd.
"""
def __init__(self,num):
self.num = num
def __str__(self):
if not self.num.isnum:
print('Please input a number!')
last2bits = int(str(self.num)[-2:])
if (last2bits < 10) or (last2bits > 20):
if last2bits % 10 == 1:
suffix = 'st'
elif last2bits % 10 == 2:
suffix = 'nd'
elif last2bits % 10 == 3:
suffix = 'rd'
else :
suffix = 'th'
else:
suffix = 'th'
ordnum = '%d%s'%(self.num,suffix)
return ordnum
__repr__ = __str__
| true |
0b1872c7b7a29d41aaec9cde9e506d37f4379396 | sammyjankins/python_skillbox | /lesson_003/01_days_in_month.py | 909 | 4.25 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input("Введите, пожалуйста, номер месяца: ")
month = int(user_input)
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = {28: 'дней', 30: 'дней', 31: 'день'}
print('Вы ввели', month)
if 1 <= month <= 12:
print(months[month-1], days[months[month-1]])
else:
print('Введенный номер месяца некорректен')
# зачет! | false |
f9a627fa6b6246448ffb307b06bbc68ef3150fdc | ysei/project-euler | /pr042.py | 1,439 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The nth term of the sequence of triangle numbers is given by, t(n) = 1/2 * n(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical
position and adding these values we form a word value. For example, the word
value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number
then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file
containing nearly two-thousand common English words, how many are triangle words?
"""
def get_words_from_file(fname):
"""get word list from text file"""
f = open(fname, 'r')
buf = f.readline()
f.close
words = map(lambda x: x[1:-1], buf.split(','))
return words
def is_triangle_num(num):
"""check whether num is trianble number or not"""
triangle = lambda n: (n * (n + 1)) / 2
idx = 1
val = triangle(idx)
while val < num:
idx += 1
val = triangle(idx)
return val == num
def is_triangle_word(word):
"""check whether word is triangle or not"""
num = sum(map(lambda c: ord(c) - ord('A') + 1, word))
return is_triangle_num(num)
def main():
"""main function"""
words = get_words_from_file('pr042_words.txt')
n_triangle = len(filter(is_triangle_word, words))
print n_triangle
if __name__ == "__main__":
main()
| true |
d0c0394aa17d776d342c199b9898e1e692e15124 | ysei/project-euler | /pr020.py | 679 | 4.34375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
n! means n *(n 1) * ... * 3 * 2 * 1
For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
INPUT_NUM = 100
def factrial(num):
"""factorial of number"""
if num == 1:
return 1
else:
return num * factrial(num - 1)
def digits_sum(val):
"""sum of digits of number"""
lst = list(str(val)) # convert number to list of digits char
return sum(map(int, lst))
def main(num):
"""main function"""
print digits_sum(factrial(num))
if __name__ == "__main__":
main(INPUT_NUM)
| true |
ed72809dd33d0e8fdaebca3af4507829a4866caa | ysei/project-euler | /pr023.py | 2,810 | 4.15625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors
of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than
n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
number that can be written as the sum of two abundant numbers is 24.
By mathematical analysis, it can be shown that all integers greater than 28123
can be written as the sum of two abundant numbers. However, this upper limit
cannot be reduced any further by analysis even though it is known that the
greatest number that cannot be expressed as the sum of two abundant numbers is
less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of
two abundant numbers.
"""
# all integer greater than 28123 can be written as a sum of two abundant
# numbers. so consider number limit is 28123 at this problem.
NUM_LIMIT = 28123
def divisors(num):
"""return divisors of num"""
return [x for x in range(1,num) if num % x == 0]
def get_abundants(limit):
"""abundant number list under limit."""
return [n for n in range(1, limit) if n < sum(divisors(n))]
def search(num, lst, length):
"""binary search for sorted list; loop version."""
start = 0
end = length # len(lst)
while start <= end:
idx = start + (end - start) / 2
if lst[idx] == num:
return idx # found num in lst.
if lst[idx] < num:
start = idx + 1
else: # lst[idx] > num
end = idx - 1
return None # num is not found in lst. return None object.
# binary search; recursive call version.
# XXX: I not use this version for optimization
def search_rec(num, lst, start, end):
"""binary search for sorted list: recursive version."""
if start > end:
return None # num is not found in lst, return None object.
idx = start + (end - start) / 2
if lst[idx] == num:
return idx # found num in lst.
elif lst[idx] < num:
return search(num, lst, idx+1, end)
else: # lst[idx] > num
return search(num, lst, start, idx-1)
def can_sum(num, abundants):
"""num can written as the sum of two abundant numbers"""
length = len(abundants) # XXX: calclulate length on each the func call...
for i in abundants:
if i >= num:
return False
if search(num-i, abundants, length) is not None: # found in abundants
return True
return False
def main():
"""main function"""
abundants = get_abundants(NUM_LIMIT+1)
lst = [n for n in range(1, NUM_LIMIT+1) if not can_sum(n, abundants)]
print sum(lst)
if __name__ == "__main__":
main()
| true |
b7f56f54b9154b00b465c0b061ebe759a819e48a | amandafrois/hackerrank | /python/qualis_unittest_circle2.py | 1,483 | 4.375 | 4 | # Unit Testing using unittest in Python
# Circle
class Circle:
def __init__(self, radius):
# Define initialization method:
self.radius=radius
if not isinstance(self.radius,(int,float)):
raise TypeError("radius must be a number")
elif(self.radius >1000 or self.radius <0):
raise ValueError("radius must be between 0 and 1000 inclusive")
else:
pass
def area(self):
# Define area functionality:
return round(math.pi*(self.radius**2),2)
def circumference(self):
# Define circumference functionality:
return round(2*math.pi*self.radius,2)
class TestCircleArea(unittest.TestCase):
def test_circlearea_with_random_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# its area is 19.63.
c1 = Circle(2.5)
self.assertEqual(c1.area(),19.63)
def test_circlearea_with_min_radius(self):
# Define a circle 'c2' with radius 0, and check if
# its area is 0.
c2 = Circle(0.0)
self.assertEqual(c2.area(),0)
def test_circlearea_with_max_radius(self):
# Define a circle 'c3' with radius 1000.1. and check if
# its area is 3141592.65.
with self.assertRaises(ValueError) as e:
c3 = Circle(1000.1)
self.assertEqual(str(e.exception), "radius must be between 0 and 1000 inclusive")
| true |
2ad4781323a4b97db558f27d45799e80a03a871e | maxicool/PredictStock | /tutorial_12.py | 1,495 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 06:56:52 2017
https://pythonprogramming.net/how-to-program-r-squared-machine-learning-tutorial/?completed=/r-squared-coefficient-of-determination-machine-learning-tutorial/
@author: justin
random data generation
"""
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import random
def best_fit_linear(xs, ys):
m = (mean(xs)*mean(ys) - mean(xs*ys))/(mean(xs)**2 - mean(xs**2))
b = mean(ys) - m * mean(xs)
# coefficient determination using two different ways to calculate squared error
r = 1 - np.sum((m*xs+b -ys)**2)/np.dot((ys-mean(ys)),(ys-mean(ys)))
return m, b, r
def create_random_data(num, variance, step = 2, correlation = False):
val = 1
ys = []
for i in range(num):
y = val + random.randrange(-variance,variance)
ys.append(y)
# add some correlation
if correlation and correlation == 'pos':
val+=step
elif correlation and correlation == 'neg':
val-=step
xs = np.arange(num)
return np.array(xs, dtype=np.float64),np.array(ys,dtype=np.float64)
for variance in [40, 20, 10]:
xs, ys = create_random_data(100, variance, 2, 'neg')
m,b,r = best_fit_linear(xs, ys)
print(m,b,r)
regression_line = m * xs + b
plt.scatter(xs,ys,color='#003F72')
plt.plot(xs, regression_line)
plt.show()
| true |
d5b0b2bb8e3d1d826d3f7f68901834c358350cc4 | rmmcosta/Introduction-to-Computer-Science-and-Programming | /Lesson 15 - Abstract data types, classes and methods/points.py | 980 | 4.125 | 4 | import math
from abc import ABC, abstractmethod
class Point(ABC):
# common method
def __eq__(self, other):
print('from abstract eq')
return self.x-other.x < 0.01 and self.y-other.y < 0.01
# common method
def cartesian(self):
return 'x:{}, y:{}'.format(self.x, self.y)
# common method
def polar(self):
return 'radius:{}, angle:{}'.format(self.radius, self.angle)
class CartesianPoint(Point):
def __init__(self,x,y):
self.x = x
self.y = y
self.radius = math.sqrt(x*x+y*y)
self.angle = math.atan(y/x)
# def __eq__(self,other):
# return self.x-other.x < 0.01 and self.y-other.y < 0.01
class PolarPoint(Point):
def __init__(self,r,a):
self.radius = r
self.angle = a
self.x = math.cos(a)*r
self.y = math.sin(a)*r
# def __eq__(self,other):
# return self.radius-other.radius < 0.01 and self.angle-other.angle < 0.01 | false |
89f0c76eea85a02d480daacec5c1c76e607b0aa7 | manjunathhegdebalgar/assignment | /question2.py | 1,324 | 4.34375 | 4 | """ Program to calculate the number of days between two dates"""
from datetime import date
import sys
max_date = str(input("Enter the maximum date in YYYYMMDD format"))
min_date = str(input("Enter the minimum date in YYYYMMDD format"))
# Following lines split the dates at proper positions to fetch year, month and day.
max_year = int(max_date[:4])
max_month = int(max_date[4:6])
# Checking for the error in month
if max_month == 0 or max_month > 12:
print("Error in the month of maximum date")
sys.exit(0)
max_day = int(max_date[6:8])
# Checking for error in day
if max_day == 0 or max_day > 31:
print("Error in the day of maximum date")
sys.exit(0)
min_year = int(min_date[:4])
min_month = int(min_date[4:6])
# Checking for error in month
if min_month == 0 or min_month > 12:
print("Error in the month of minimum date")
sys.exit(0)
# Checking for error in day
min_day = int(min_date[6:8])
if min_day == 0 or min_day > 31:
print("Error in the day minimum date")
sys.exit(0)
max_date = date(
max_year, max_month, max_day
) # Preparing max_date for inbuilt date function
min_date = date(
min_year, min_month, min_day
) # Feeding min_date for inbuilt date function
difference_in_days = max_date - min_date
print("The number of days between given two dates are", difference_in_days)
| true |
cc89d04534abca19a8dc3437a99e571949b1a64f | khang-le/ICS3U-UNIT-03 | /recreate.py | 512 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Khang Le
# Created on: Sep 2019
# This program checks if there is over 30 students
import constants
def main():
# this function checks if there is over 30 students
# input
number_of_students = int(input("Enter the number of studetns: "))
print("")
# process and output
if number_of_students == constants.MAX_STUDENT_NUMBER1:
print("EXACTLY 30 STUDENTS!")
else:
print("Not 30 students!")
if __name__ == "__main__":
main()
| true |
f777ea2a2c0809772d0b333b48d0d7c23ee4e39d | SusanMorton/CP1404_Practicals | /prac_03/password_check.py | 500 | 4.15625 | 4 | def main():
minimum_length = 6
password = get_password(minimum_length)
print_asterisks(password)
def print_asterisks(password):
for char in password:
print("*", end='')
def get_password(minimum_length):
password = input("Enter a password")
valid_password = False
while not valid_password:
if len(password) < minimum_length:
password = input("Enter a password")
else:
valid_password = True
return password
main()
| false |
678b849d37e00bb693dab1223b575c3e2469c1cb | m3tr0x/World_Of_Games | /venv/Live.py | 2,875 | 4.375 | 4 | # welcome(name) - This function gets a person name as an input and returns a welcome string.
# load_game() - This function:
# 1. Will print out the game selection text
# 2. Will get an input from the user about the game he chose – 1/2.
# 3. After receiving the game number from the user, the function will get the level of difficulty from 1 to 5
# 4. Will start a new function of the corresponding game with the given difficulty.
# The function will check the input of the chosen game (the input supposed to be a number
# between 1 to 2), also will check the input of level of difficulty (input should be a number between
# 1 to 5).
# In case of an invalid choice, return the ERROR_MESSAGE (Utils.py).
# In case the user won the game, the function will call the function called add_score() (in score.py
# module) to add the new score the user won to the score saved in the Scores.txt function.
# In case the user lost, call load_game() again.
from Utils import error, screen_cleaner
from Score import add_score
def welcome(name):
print("Hello", name, "and welcome to the World of Games (WoG) \n")
print("Here you can find many cool games to play")
def load_game():
print("Please choose a game to play:")
print("1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back \n")
print("2. Guess Game - guess a number and see if you chose like the computer \n")
while True:
selection = input("Select which game you'd like to play: ")
try: #Checking value is an integer
if int(selection) == 1:
from MemoryGame import play
diff = input("Please choose game difficulty from 1 to 5: ")
if int(diff) > 5 or int(diff) < 1: #Checking value not crossing 1-5
screen_cleaner()
print(error)
result = 0
else:
result = play(int(diff))
elif int(selection) == 2:
from GuessGame import play
diff = input("Please choose game difficulty from 1 to 5: ")
if int(diff) > 5 or int(diff) < 1: #Checking value not crossing 1-5
screen_cleaner()
print(error)
result = 0
else:
result = play(int(diff))
else:
screen_cleaner()
print(error)
result = 0
except ValueError:
print("You've inserted a non integer value, please try again \n")
continue
else:
break
# Selected game will return 1 in order to update score. else will return 0 to intiate the reload game.
if result == 1:
add_score(int(diff))
return 1 # Will return 1 to finish the game w/o reload.
else:
return 0
| true |
d842b3fcd4daded33c0b72472a0978a35ad6fcc8 | KonekoTJ/Level-3_Python | /Homework6/Fenrir/Homework4_3.py | 1,575 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 18:29:01 2020
@author: Fenrir
Description :
ユーザーに数字(西暦)を入力させ、
閏年「leap year」であるかを判断することが出来るプログラムを作成してください。
1. 数字が4の倍数であればその年は閏年「leap year」と表示
2. 但し数字が100の倍数であれば2.よりも優先されその年は平年「Normal year」と表示
3. 更に数字が400の倍数であれば3.よりも優先されその年は閏年「leap year」と表示
Variable:
year
"""
# Code Example(if else):
year = int(input('Please input year:'))
if(year % 400 == 0):
# 数字が4の倍数であればその年は閏年「leap year」と表示
print('{} is a leap year.'.format(year))
else:
if(year % 100 == 0):
# 但し数字が100の倍数であれば2.よりも優先されその年は平年「Normal year」と表示
print('{} is a normal year.'.format(year))
else:
if(year % 4 == 0):
# 更に数字が400の倍数であれば3.よりも優先されその年は閏年「leap year」と表示
print('{} is a leap year.'.format(year))
else:
print('{} is a normal year.'.format(year))
# Code Example(elif)):
'''
if( year % 400 == 0):
print('{} is a leap year.'.format(year))
elif( year % 100 == 0):
print('{} is a normal year.'.format(year))
elif( year % 4 == 0):
print('{} is a leap year.'.format(year))
else:
print('{} is a normal year.'.format(year))
''' | false |
42c7240e4fe65c71bf60fcb03cd924dada8a8044 | bluescience/pythonCode3 | /Problem 7.py | 843 | 4.15625 | 4 | import math
def primeCheck(num):
primeCheck = True
for number in range(2, int(math.floor(num/2))+1): #range in which a num can be checked if prime or not
if num % number == 0:
primeCheck = False
break
if primeCheck == True:
return(num)
#Takes in a number and finds which prime it corresponds to if all nums before it were prime
def primeCalc(num):
currentNum = 2 # number we are checking as prime
primeCounter = 0 # counts how many primes have been found
while primeCounter < num:
primeCheckVar = primeCheck(currentNum)
if type(primeCheckVar) == int:
primeCounter += 1
biggestKnownPrime = primeCheckVar
currentNum += 1
print(biggestKnownPrime)
print(primeCounter)
primeCalc(10001)
| true |
316d6d735db8ee2aceb877a16b127ba0a88b491e | wh-yenny-choi/pythonstudy | /07_string/string_trans.py | 1,122 | 4.28125 | 4 | #replace()
text = 'Java Programming'
#print(text.replace('Java','Python'))
text = text.replace('Java','Python') #text.replace('원래문자' , '바꿀문자')
print(text) # <Python Programming>
#대문자/소문자 변환
#upper() : 대문자로 변경
#Lower() : 소문자로 변경
#capitalize() : 첫 문자를 대문자로 변경
#title() : 각 단어의 첫글자를 대문자로 변경
#swapcase() : 대문자는 소문자로, 소문자는 대문자로 변경
text = 'java programming is Fun'
print(text.upper()) #<JAVA PROGRAMMING IS FUN>
print(text.lower()) #<java programming is fun>
print(text.title()) #<Java Programming Is Fun>
print(text.capitalize()) #<Java programming is fun>
print(text.swapcase()) #<JAVA PROGRAMMING IS fUN>
#공백문자 제거 strip(), Lstrip(), Rstrip()
text = ' java programming is Fun '
print(text + '---') #< java programming is Fun --->
print(text.strip()) #<java programming is Fun>
print(text.lstrip()) #<java programming is Fun >
print(text.rstrip() + '---') #< java programming is Fun--->
| false |
c019e0b6bb1fa9302f68af1791cc5b9a9ead0aaf | DanielTuttos/PYTHON-FundamentosEnPython | /POOAritmeticaClass.py | 1,336 | 4.34375 | 4 | class Aritmetica:
"""Clase Artimetica para realizar las operaciones de sumar, restar, etc"""
def __init__(self, operando1, operando2):
self.operando1 = operando1
self.operando2 = operando2
"""Se realiza la operación con los atributos de la clase"""
def sumar(self):
return self.operando1 + self.operando2
def restar(self):
return self.operando1 - self.operando2
def multiplicar(self):
return self.operando1 * self.operando2
def dividir(self):
return self.operando1 / self.operando2
# creamos un nuevo objeto
numero1 = int(input('Ingrese el primer numero para las operaciones: '))
numero2 = int(input('Ingrese el segundo numero para las operaciones: '))
aritmetica = Aritmetica(numero1, numero2)
print('Resultado de la suma:', aritmetica.sumar())
print('Resultado de la resta:', aritmetica.restar())
print('Resultado de la multiplicacion:', aritmetica.multiplicar())
print('Resultado de la division:', aritmetica.dividir())
# creamos un nuevo objeto
# aritmetica2 = Aritmetica(10, 50)
# print('El resultado de la suma es:', aritmetica2.sumar())
# print('El resultado de la resta es:', aritmetica2.restar())
# print('El resultado de la multiplicacion es:', aritmetica2.multiplicar())
# print('el resultado de la division es:', aritmetica2.dividir())
| false |
e966af3a59a2b2d3adaf27b137d8ca5b3e25fb18 | holywar20/PythonSandbox | /dictionaries.py | 572 | 4.125 | 4 | # A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
person = {
'first' : 'Justice' ,
'last' : 'Destroyer',
'age' : '9 million 1'
}
print( person['first'] )
# Add / Remove
person['phone'] = '555-555-5555'
del( person['age'] )
person.pop('phone')
person.clear()
print( len(person) )
# Keys
print( person.keys() )
# Values
print( person.values() )
# Copy
person2 = person.copy()
# List of dictionaries
people = [
{'name' : 'justice' , 'age': '44'} , { 'name' : '23423' , 'age' : 'Justice'}
]
print( people[1]['name'] ) | false |
84668346b10c4028270bf421c6b5d45965624a7d | CVinegoni/Course_Python_MIT6001x | /Week01_PythonBasics/PS01_02.py | 585 | 4.21875 | 4 | # Assume s is a string of lower case characters.
# Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
# Number of times bob occurs is: 2
s = 'azcbobobegghakl'
string_to_search = 'bob'
occurring_number = 0
for position in range(len(s)-len(string_to_search)+1):
print(s[position:position+len(string_to_search)])
if s[position:position+len(string_to_search)] == string_to_search:
occurring_number += 1
print('Number of times bob occurs is: {}'.format(occurring_number))
| true |
9ed9dc7da3111be4f47b87b8392337b6a81cdd23 | donotbesad/algorithm-s | /subsets/subsets.py | 623 | 4.34375 | 4 | # -------------------------------------------------------------
# Subsets (easy)
# Given a set with distinct elements, find all of its distinct subsets.
#
# Time Complexity: O(N*2^N)
# Space Complexity: O(N*2^N)
# -------------------------------------------------------------
def find_subsets(nums):
subsets = [[]]
for curr in nums:
n = len(subsets)
for i in range(n):
subset = list(subsets[i])
subset.append(curr)
subsets.append(subset)
return subsets
if __name__ == '__main__':
print(find_subsets([1, 3]))
print(find_subsets([1, 5, 3]))
| true |
da7722143bbb4d83497b32c9780bb7076e73d01a | donotbesad/algorithm-s | /cyclicsort/cyclic_sort.py | 715 | 4.21875 | 4 | # -------------------------------------------------------------
# Cyclic Sort (easy)
# Write a function to sort the objects in-place on their creation
# sequence number in O(n)O(n) and without any extra space.
#
# Time Complexity: O(n)
# Space Complexity: O(1)
# -------------------------------------------------------------
def cyclic_sort(nums):
i = 0
while i < len(nums):
j = nums[i] - 1
if nums[i] != nums[j]:
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
return nums
if __name__ == '__main__':
print(cyclic_sort(nums=[3, 1, 5, 4, 2]))
print(cyclic_sort(nums=[2, 6, 4, 3, 1, 5]))
print(cyclic_sort(nums=[1, 5, 6, 4, 3, 2]))
| true |
99008469db1ea5275f8220e6fc5a315f8a1c3173 | donotbesad/algorithm-s | /mergeintervals/intervals_merge.py | 1,757 | 4.125 | 4 | # -------------------------------------------------------------
# Merge Intervals (medium)
# Given a list of intervals, merge all the overlapping intervals
# to produce a list that has only mutually exclusive intervals.
#
# Time Complexity: O(nlogn)
# Space Complexity: O(n)
# -------------------------------------------------------------
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def print_interval(self):
print("[" + str(self.start) + ", " + str(self.end) + "]", end='')
def merge(intervals):
if not intervals:
return []
if len(intervals) == 1:
return intervals
merged = []
intervals.sort(key=lambda x: x.start)
start = intervals[0].start
end = intervals[0].end
for il in range(1, len(intervals)):
interval = intervals[il]
if interval.start <= end:
end = max(end, interval.end)
else:
merged.append(Interval(start, end))
start = interval.start
end = interval.end
merged.append(Interval(start, end))
return merged
if __name__ == '__main__':
print("Merged intervals: ", end='')
for i in merge([Interval(1, 4), Interval(2, 5), Interval(7, 9)]):
i.print_interval()
print()
print("Merged intervals: ", end='')
for i in merge([Interval(6, 7), Interval(2, 4), Interval(5, 9)]):
i.print_interval()
print()
print("Merged intervals: ", end='')
for i in merge([Interval(1, 4), Interval(2, 6), Interval(3, 5)]):
i.print_interval()
print()
print("Merged intervals: ", end='')
for i in merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)]):
i.print_interval() | true |
1c22e3f67858296e2cfecebee993e65079f4fa72 | richdon/Data-Structures-Algorithms | /merge_sort.py | 2,017 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 19:53:58 2021
@author: richa
"""
def merge_sort(lst):
"""
Sorts a list in ascending order.
Returns a new sorted list.
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
"""
# stopping condition
if len(lst) <= 1:
return lst
# divide using a helper function split()
left_half, right_half = split(lst)
# conquer step
left = merge_sort(left_half)
right = merge_sort(right_half)
# combine step
return merge(left, right)
def split(lst):
"""
Divide the unsorted list at midpoint into sublists
Returns two sublists - left and right.
"""
mid_index = len(lst)//2
left_lst = lst[:mid_index]
right_lst = lst[mid_index:]
return left_lst, right_lst
def merge(left, right):
"""
This function merges two lists (arrays) , sorting them in the process.
Return a new merged list.
"""
# merged list
l = []
# index in left list
i = 0
# index in right list
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
l.append(left[i])
i += 1
else:
l.append(right[j])
j += 1
while i < len(left):
l.append(left[i])
i += 1
while j < len(right):
l.append(right[j])
j += 1
return l
def verify_sorted(lst):
n = len(lst)
if n == 0 or n == 1:
return True
return lst[0] < lst[1] and verify_sorted(lst[1:])
my_list = [54, 78, 97, 5, 16, 43, 9, 12, 4]
l = merge_sort(my_list)
print(l)
print(verify_sorted(my_list))
print(verify_sorted(l))
| true |
c2b16ea3fffa57ace7df375c63d2a370dcea52ca | linuxheels/linuxheels | /udemy_learning/fun_with_strings.py | 612 | 4.1875 | 4 |
#https://docs.python.org/3/tutorial/datastructures.html
states_of_america = ["NC", "SC", "TN", "FL", "VA", "PA"]
#states_of_america.clear() # this will clear your list out to nothing
#states_of_america.append("KY") #to add a new item to the list
#states_of_america.extend(["AZ", "CA", "NM", "TX", "AL", "AL"])
#states_of_america.insert(0, "WV") #TO INSERT AN ITEM AT A CERTAIN POSITION IN THE LIST#
# to change an item in the list.
#states_of_america[0] = "CN" #this will change NC to CN
if states_of_america.count("TX") == 0:
print(states_of_america)
else:
print("this country needs a TX!") | false |
95a0ac72fed47e57277ee56b67e018c2a334f7ac | linuxheels/linuxheels | /udemy_learning/odd_or_even.py | 388 | 4.3125 | 4 | number = int(input("Which number do you want to check? "))
number_type = number % 2
if number_type == 0:
print("This is an even number.")
else:
print("This is an odd number.")
#or you can do it this way as well
# number = int(input("Whis number do you want to check? "))
# if number % 2 == 0:
#print("This is an even number.")
# else:
# #print("This is an odd number.") | true |
19b0d8307e78d431b37a3d1b903230071d47f599 | belargej/PythonProjects | /NPTut/FibSeq.py | 246 | 4.1875 | 4 | print("Fibonacci Sequence!")
a=0
b=1
count=0
max_count=int(input("How far do you want to go?? "))
while count < max_count:
count = count+1
print(a,end=" ") #end keeps from printing a new line.
old_a = a
a=b
b= old_a+b
print()
| true |
ee855305ad87b144b39a69a5b7333217f84382c3 | matheb/trial-exam-python | /3.py | 764 | 4.28125 | 4 | # Create a class that represents a cuboid:
# It should take its three sizes as constructor parameters (numbers)
# It should have a method called `getSurface` that returns the cuboid's surface
# It should have a method called `getVolume` that returns the cuboid's volume
class Cuboid():
def __init__(self, edge1, edge2, edge3):
self.a = edge1
self.b = edge2
self.c = edge3
def getSurface(self):
surface = 2*(self.a*self.b + self.a*self.c + self.b*self.c)
return surface
def getVolume(self):
volume = self.a*self.b*self.c
return volume
cube = Cuboid(2, 2, 2)
print(cube.getSurface())
print(cube.getVolume())
"""cuboid = Cuboid(1, 2, 3)
print(cuboid.getSurface())
print(cuboid.getVolume())"""
| true |
28867f7dbc7d37fe4038a2e5ef78e74c7bbc0dae | nishantranaa/Python_Uni_Projects | /prac_2/Strings.py | 1,226 | 4.25 | 4 | s = ord("N") # used to find the unicode dec value of a single character and not a string value.
print(s)
s = chr(78) # this function is used to find the char value using a unicode dec value.
print(s)
s = "My God name is HariKrishna and I believe in Him entirely"
t = s[:]
print(t)
s = "I believe in Hari Krishna"
reversed=s[::-1]
print(reversed)
for char in "Test":
print(char, type(char))
# the operator is overloaded means that an operator does diffent task based off the datatype.
print("Nishant" + "HariKrishna")
word = "Transport"
t = "r" in word
print(t)
t = "z" in word
print(t)
compare = "Transport"
if word == compare:
print('Yes')
print(compare[1])
compare = 'CARS'
print(compare)
# updating a character in a word
word = 'Nishant'
updated_word = word[:2] + 'z' + word[3:] + " pronounced by Shila kaki"
print(updated_word)
"""This is a docstring. It describes the how the function works."""
# A function algorithm is encapsulated within it, we only need to know the name of the function to call it and operate it .
# A method is applied on a object using a dot notation invocation. Invocation means the action of invoking someone or something.
for num in range(00, 13, 3):
print(num, end=' ')
| true |
d60c653b0569ea06fefc515d9ea97bfccb682b8d | ELLowe/CodeWars | /8_findTheOddInt_101719.py | 1,641 | 4.3125 | 4 | # Given an array, find the int that appears an odd number of times.
# There will always be only one integer that appears an odd number of times.
# Solution 1:
# This method isn't the greatest because it requires adding to the list, but it is nice if you are only seeking one number,
# because you don't need to process the entire list to find that single number.
def oddInt(a):
sortedArray = sorted(a)
sortedArray.append(0)
counter = 1
for index,item in enumerate(sortedArray):
if index == (len(sortedArray)-1):
break
if sortedArray[index] == sortedArray[index+1]:
counter = counter+1
else:
if counter % 2 != 0:
return sortedArray[index]
else:
counter = 1
print(oddInt([9,1,5,9,3,8,6,1,5,3,8,6,9]))
# Solution 2:
# This method is great because it can be adapted to find all numbers listed an odd number of times
# Unfortunately it will take longer to come up with the same answer in the case where only a single number is desired,
# because it will go through the entire array before returning an answer.
# Credit for this solution goes to my teacher, Steve Kain:
def oddInt2(a):
counter = {}
for item in a:
if item in counter:
counter[item] += 1
else:
counter[item] = 1
for key in counter:
if counter[key] % 2 != 0:
return key
return None
print(oddInt2([9,1,5,9,3,8,6,1,5,3,8,6,9]))
# Best Practice solution by cerealdinner:
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i | true |
65088c32fdc73cae60de00b146b72174f22f4363 | songweishuai/python_test | /class/constructor.py | 740 | 4.15625 | 4 | # /usr/bin/python3
# -*- coding:utf-8 -*-
# 如果子类需要调用父类的构造方法就需要显示的调用,或者子类不重写父类的构造方法
class Father(object):
def __init__(self, name):
self.name = name
print("name: %s" % (self.name))
def getName(self):
return 'Father ' + self.name
class Son(Father):
# 复写构造函数
def __init__(self, name):
print("hi")
# 需要主动调用父类的构造方法
# super().__init__(name)
# Father.__init__(self, name)
self.name = name
def getName(self):
return "son " + self.name
if __name__ == "__main__":
son = Son('runoob')
# print(son.getName())
print(repr(son))
| false |
2b94d4b0285976037bb72990605eb6fa2891085b | gavincn/mypy100 | /day6/Day6_Practise1.py | 1,198 | 4.1875 | 4 | """
练习1:实现计算求最大公约数和最小公倍数的函数。
"""
# 最大公约数,能同时被两个数整除
def gcd(x, y):
(x, y) = (y, x) if (x > y) else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor
# 最小公倍数, 如4 和6 的最小公倍数是 12
# x 和 y 乘以某数后能得到的最小的相同的值
def lcm(x, y):
return x * y // gcd(x, y)
print(gcd(4, 6))
print(lcm(4, 6))
"""
判断一个数是不是会问数的函数
"""
def is_palindrome(num):
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
return total == num
print(is_palindrome(151))
"""
判断一个数是不是素数
"""
from math import sqrt
def is_prime(num):
tmp = int(sqrt(num))
for i in range(2, tmp+1):
if num % i == 0:
return False
return True
print()
print(is_prime(3))
print(is_prime(8))
print(is_prime(7))
print(is_prime(16))
print(is_prime(31))
if __name__ == "__main__":
num = int(input("input a number please :"))
if is_palindrome(num) and is_prime(num):
print("%d是回文素数")
| false |
cb0dc2deaa72f4c300bebf438fd2373425897c1a | guivecchi/PythonCrashCourse | /chapter11_examples.py | 2,861 | 4.21875 | 4 | ## Chapter about testing
def get_formatted_name(first, last, middle=''):
"""Generate a neatly formatted full name."""
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
print("Enter 'q' at any time to quit.")
while True:
first = input("\nPlease give me a first name: ")
if first == 'q':
break
last = input("Please give me a last name: ")
if last == 'q':
break
formatted_name = get_formatted_name(first, last)
print("\tNeatly formatted name: " + formatted_name + '.')
import unittest
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'."""
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self):
"""Do names like 'Wolfgang Amadeus Mozart' work?"""
formatted_name = get_formatted_name(
'wolfgang', 'mozart', 'amadeus')
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
# unittest.main()
print('\n\n')
## TESTING A CLASS
class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
def __init__(self, question):
"""Store a question, and prepare to store responses."""
self.question = question
self.responses = []
def show_question(self):
"""Show the survey question."""
print(self.question)
def store_response(self, new_response):
"""Store a single response to the survey."""
self.responses.append(new_response)
def show_results(self):
"""Show all the responses that have been given."""
print("Survey results:")
for response in self.responses:
print('- ' + response)
# Define a question, and make a survey.
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# Show the question, and store responses to the question.
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
# Show the survey results.
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
class TestAnonmyousSurvey(unittest.TestCase):
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
unittest.main() | true |
24ed9176635f7f71e7f7c38210c5f2d28f7b49bb | Daria-Ras/praktikum | /current_hour.py | 504 | 4.125 | 4 | for current_hour in range(0, 24):
print("На часах " + str(current_hour) + ":00.")
if current_hour < 6:
print ('Доброй ночи!')# напишите код здесь
elif current_hour < 12:
print('Доброе утро!')
elif current_hour < 18:
print('Добрый день!')
elif current_hour < 23:
print('Добрый вечер!')
else:
print('Доброй ночи!')
current_hour=17
| false |
444b360701f01dbcd13049a66dfeb6b39e3be399 | KingOzma/Python-Homework-1 | /Python Homework 1.py | 2,145 | 4.625 | 5 | #NUMBERS:
#Answer these 3 questions without typing code. Then type code to check your answer.
#What is the value of the expression 4 * (6 + 5)
print(4 * (6 + 5)) #44
#What is the value of the expression 4 * 6 + 5
print( 4 * 6 + 5) #29
#What is the value of the expression 4 + 6 * 5
print(4 + 6 * 5 ) #33
#What is the type of the result of the expression 3 + 1.5 + 4?
float
#What would you use to find a number’s square root, as well as its square?
print(3**0.5)
print(3*3)
#STRINGS:
#Given the string 'hello' give an index command that returns 'e'.
s = 'hello'
print(s[1])
#Reverse the string 'hello' using slicing:
s ='hello'
print(s[::-1])
#Given the string hello, give two methods of producing the letter 'o' using indexing.
s ='hello'
print(s[-1])
print(s[4])
#LISTS:
#Build this list [0,0,0] two separate ways.
example1=[0,0,0]
print(example1)
#Reassign 'hello' in this nested list to say 'goodbye' instead:
list3 = [1,2,[3,4,'hello']]
list3[2][2] = 'goodbye'
print(list3)
#Sort the list below:
list4 = [5,3,4,6,1]
list4.sort()
print(list4)
#DICTIONARIES
# Grab 'hello'
d = {'simple_key':'hello'}
print(d['simple_key'])
d = {'k1':{'k2':'hello'}}
print(d['k1']['k2'])
d = {'k1':[{'nest_key':['this is deep',['hello']]}]}
print(d['nest_key'][1])
d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}
print(d['tough'][2])
#TUPLES
#What is the major difference between tuples and lists?
#Tuples are unchangeable
#How do you create a tuple?
#Use () instead of []
#SETS
#What is unique about a set?
#Sets can't have repeated objects
#Use a set to find the unique values of the list below:
list5 = [1,2,2,33,4,4,11,22,3,3,2]
print(set(list5))
#BOOLEANS
# Answer before running cell
2 > 3 #False
# Answer before running cell
3 <= 2 #False
# Answer before running cell
3 == 2.0 # False
# Answer before running cell
3.0 == 3 #True
# Answer before running cell
4**0.5 != 2 #False
# two nested lists
l_one = [1,2,[3,4]]
l_two = [1,2,{'k1':4}]
# True or False?
l_one[2][0] >= l_two[2]['k1'] #False
| true |
1969a554ede68b7dcc4500543dc987cb87793fef | Alepan789/Py111 | /Tasks/b1_binary_search.py | 1,599 | 4.15625 | 4 | from typing import Any, Sequence, Optional
def binary_search(elem: Any, arr: Sequence) -> Optional[int]:
"""
Performs binary search of given element inside of array
:param elem: element to be found
:param arr: array where element is to be found
:return: Index of element if it's presented in the arr, None otherwise
"""
# print(f'На входе arr:{arr} Len:{len(arr)}')
if len(arr) == 0:
return
start_index = 0
if len(arr) > 1:
end_index = len(arr)
else:
end_index = 0
res_index = 0
i = 1
mdl_index = 0
while True:
# print(f"EndIndex:{end_index}; \tstart_index:{start_index}; \tarr:{arr[start_index:end_index]}")
mdl_index = (end_index - start_index) // 2 + start_index
if elem == arr[mdl_index]:
# res_index = (end_index - start_index)//2
# print(f'res = {elem} за {i+1} шагов index:{mdl_index}')
return mdl_index
if elem < arr[mdl_index]:
end_index = mdl_index
# arr2 = arr2[0:end_index]
else:
start_index = mdl_index + 1
# arr2 = arr2[end_index + 1:]
i += 1
if start_index >= end_index:
# print(f'Result end_index:{end_index}; start_index:{start_index}; arr:{arr[start_index:end_index]}; искали:{elem} index:{res_index}')
return
# print(elem, arr)
return None
#
# a = 7
#
# b = [1, 3, 5, 7, 9, 5, 17, 19, 23, 99]
#
# b = [1, 2, 3, 4, 5, 6, 7]
# b = [1, 7, 9]
# # b = [1]
# # print(b)
#
# print(binary_search(9, b))
| true |
db6edf54df6acaeb6d436e008cbd317a54b85345 | luhanhan/leetcode | /maxArea_11.py | 1,250 | 4.125 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
############################
#File Name: maxArea_11.py
#Author: luhan
#Created Time: 2019-06-27 14:47:20
############################
"""
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
"""
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
res = 0
left, right = 0, len(height)-1
while left<right:
res = max(min(height[left],height[right])*(right-left), res)
if height[left]<height[right]:
left += 1
else:
right -= 1
return res
s = Solution()
height = [1,8,6,2,5,4,8,3,7]
print s.maxArea(height)
| true |
06aa3b4948650dd97ad0d1a8a805af6450376b31 | luhanhan/leetcode | /findRadius_475.py | 2,495 | 4.15625 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
############################
#File Name: findRadius_475.py
#Author: luhan
#Created Time: 2019-06-18 15:19:11
############################
"""
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
As long as a house is in the heaters' warm radius range, it can be warmed.
All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
解题思路:
排序(Sort) + 二分查找(Binary Search)
升序排列加热器的坐标heaters
遍历房屋houses,记当前房屋坐标为house:
利用二分查找,分别找到不大于house的最大加热器坐标left,以及不小于house的最小加热器坐标right
则当前房屋所需的最小加热器半径radius = min(house - left, right - house)
利用radius更新最终答案ans
"""
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
import bisect
ans = 0
heaters.sort()
for house in houses:
radius = 0x7FFFFFFF
le = bisect.bisect_right(heaters, house)
if le > 0:
radius = min(radius, house - heaters[le - 1])
ge = bisect.bisect_left(heaters, house)
if ge < len(heaters):
radius = min(radius, heaters[ge] - house)
ans = max(ans, radius)
return ans
s = Solution()
houses = [1,2,3]
heaters = [2]
print s.findRadius(houses, heaters)
| true |
768715c17addd4146bea89e953ed4a6ca33e84ab | Kitakarsh/pythonworkshop | /r2.py | 760 | 4.21875 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> float(input("Enter the number:") + float(input("Enter the number:")
3 4
SyntaxError: invalid syntax
>>> float(input("Enter the number:") + float(input("Enter the number:")
3 4
SyntaxError: invalid syntax
>>> float(input("Enter the number:")) + float(input("Enter the number:"))
Enter the number:3
Enter the number:5
8.0
>>> a=[1,2,3]
>>> b=[3,4,5]
>>> a[0]+b[1]
5
>>> for 1 in a:
print(a)
SyntaxError: can't assign to literal
>>>
>>> for a[1]<3:
print(a)
SyntaxError: invalid syntax
>>> for a:
SyntaxError: invalid syntax
>>> x=
| true |
94b34d4f235cf96dfc6be89fbe3102e8ef53f96b | Madhavpawar600/acadview | /discount.py | 213 | 4.125 | 4 | quantity=int(input("enter the quantity"))
cost=quantity*100
if cost >1000:
print("total cost=",cost)
a=cost * 90/100
print("you get 10 % discount total cost=",a)
else:
print("total cost=",cost)
| true |
61e0f88e3e51e2346b62cefeec9fc6509da672c9 | gustavoramos82/opera-o-fra-o | /ope fra.py | 2,136 | 4.125 | 4 | from fractions import Fraction
from termcolor import colored
#colocando os números correspondente ao numerador e ao denominador.
a1 = Fraction(input('Digite o numerador da primeira fração:'))
d1 = Fraction(input('Digite o denominador da primeira fração:'))
a2 = Fraction(input('Digite o numerador da segunda fração:'))
d2 = Fraction(input('Digite o denominador da primeira fração:'))
#caso os denominadores forem diferentes de zero.
if d1 == 0 or d2 == 0:
print(colored('O denominador de uma fração tem que ser diferente de zero, por favor tente novamente e mude o valor do denominador.','red'))
ope = int(input("insira 0 para adição, 1 para subtração, 2 para multiplicação e 3 para divisão:"))
if ope > 3 or ope < 0:
print(colored('Só aceitamos como valor de 0 a 3 representando as respectivas operações, por favor, tente novamente.', 'red'))
# definindo as varáveis pra ficar mais fácil.
adi = a1*d2+a2*d1
dif = a1*d2-a2*d1
prode = d1*d2
mutn = a1*a2
proddn = a1*d2
prodnu = a2*d1
#Operação da adição
if ope == 0:
if d1 != d2:
print('O resultado é {}/{}'.format(adi,prode))
print('A sua forma irredutivel é:')
print(colored(Fraction(adi,prode),'green'))
else:
print('O resultado é {}/{}'.format(a1+a2,d1))
print('Sua forma irredutivel é:')
print(colored(Fraction(a1+a2,d1),'green'))
#Operação da subtração
if ope == 1:
if d1 != d2:
print('O resultado é {}/{}'.format(dif,prode))
print('A sua forma irredutível é')
print(colored(Fraction(dif,prode),'green'))
else:
print('O resultado é {}/{}'.format(a1-a2,d1))
print('A sua forma irredutivel é:')
print(colored(Fraction(a1-a2,d1),'green'))
#Operação da multiplicação
if ope == 2:
print('O resultado é {}/{}'.format(mutn,prode))
print('Sua forma irredutivel é:')
print(colored(Fraction(mutn,prode)))
#Operação da divisão
if ope == 3:
print('O resultado será {}/{}'.format(proddn,prodnu))
print('Sua forma irredutivel é:')
print(colored(Fraction(proddn,prodnu),'green'))
| false |
1078556fa7a9039e9399382b2be4c01805a8ac32 | flores9698/pythonExcercises | /ex2.py | 759 | 4.4375 | 4 | #!/usr/bin/env python3
"""Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
Hint: how does an even / odd number react differently when divided by 2? """
import sys
def isEven(number):
""" Returns True when the number entered is even False otherwise"""
if number%2 == 0:
return True
return False
if len(sys.argv)==2:
number= float(sys.argv[1])
if isEven(number):
print("The number {} is even.".format(number))
else:
print("The number {} is odd.".format(number))
else:
number= float(input("Enter a number you want to know if its even or odd"))
if isEven(number):
print("The number {} is even.".format(number))
else:
print("The number {} is odd.".format(number))
| true |
ed666d6b400fabd4bb0ab68c568fdaca30179eeb | ecalzavarini/python-at-polytech-lille | /script2.py | 1,353 | 4.3125 | 4 | # script for conversion
print("Conversion of pressure measurements")
unit_in = input("Please insert pressure units, choosing among [ pa, bar , atm , psi , torr ] ")
print("chosen unit is %s" % unit_in )
val_in = input("Please insert pressure value = ")
val_in = float(val_in)
print("given value is " + str(val_in) + " " + str(unit_in) )
unit_out = input("Please insert pressure output units, choosing among [ pa , bar , atm , psi , torr ] ")
print("chosen output unit is %s" % unit_out )
# first we convert the in value to Pascal
if unit_in == 'psi' :
val_pa = val_in * 6.8948e+3
elif unit_in == 'atm' :
val_pa = val_in * 1.01325e+5
elif unit_in == 'bar' :
val_pa = val_in * 1.e+5
elif unit_in == 'torr' :
val_pa = val_in * 133.3224
elif unit_in == 'pa' :
val_pa = val_in
else :
print("unknown given unit")
# then we convert the Pascal to the desired value
if unit_out == 'psi' :
print("converted to psi")
val_out = val_pa * 1.450377e-4
elif unit_out == 'atm' :
val_out = val_pa * 9.8692e-6
print("converted to atm")
elif unit_out == 'bar' :
val_out = val_pa * 1.e-5
print("converted to bar")
elif unit_out == 'pa' :
val_out = val_pa
print("converted to pa")
elif unit_out == 'torr' :
val_out = val_pa * 7.5006e-3
print("converted to torr")
print(val_out)
| true |
b6a2f73b7849574a827ad7cf99ef27b70dbe1c5c | Joeydelarago/tetrisneuralnetwork | /helpful_functions.py | 1,837 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def basic_plot_time(title, x, color='blue'):
""" Plots a vector x where the index represents time and the value represents the value at that time"""
plt.figure()
plt.title(title)
plt.plot(range(len(x)), x, color=color)
d = np.zeros(len(x))
plt.fill_between(range(len(x)), x, color=color)
plt.show()
def bar_plot_time(title, x, color='red'):
""" Plots a vector x where the index represents time and the value represents the value at that time"""
plt.figure()
plt.title(title)
plt.bar(range(len(x)), x, color=color)
plt.show()
def reward_stats(rewards):
""" Prints statistics about vector rewards where the index represents
that episode and the value represents the value at the end of that episode
"""
print("\n *** Reward Stats *** ")
print("Average Reward: {}".format(sum(rewards)/len(rewards)))
if len(rewards) >= 100:
print("Average Reward Last 100 Episodes: {}".format(sum(rewards[-100:])/100))
print("Total Reward: {}".format(sum(rewards)))
def step_stats(steps):
""" Prints statistics about vector steps where the index represents
the episode and the value represents the steps at the end of that episode
"""
print("\n *** Step Stats *** ")
print("Average Steps: {}".format(sum(steps)/len(steps)))
if len(steps) >= 100:
print("Average Steps Last 100 Episodes: {}".format(sum(steps[-100:])/100))
def episodes_until_reward_above_mean(reward):
""" Prints the amount of steps it took until the reward was always above the total mean reward"""
mean = np.mean(reward)
for i in range(len(reward) - 1):
if reward[len(reward) - i - 1] < mean:
print("Episodes Until Reward Above Average Reward: {}".format(i))
return
| true |
2108b8769f0a4b50bd56417986d306bf11279177 | alendina/Coffee_Machine | /Topics/Operations with dictionary/Upper and lower/main.py | 223 | 4.21875 | 4 | # the list with words from string
# please, do not modify it
some_iterable = input().split()
new_dict = {x.upper(): x.lower() for x in some_iterable}
print(new_dict)
# use dictionary comprehension to create a new dictionary | true |
06d2cedea31bc3dd55e1be0df7f224bc463a3738 | modulus100/advanced-algorithms-udacity | /graph-algorithms/prims_algorithms_connecting_islands/heapq_playground.py | 1,194 | 4.34375 | 4 | import heapq
# initialize an empty list
#heappush
minHeap = list()
# insert 5 into heap
heapq.heappush(minHeap, 6)
# insert 6 into heap
heapq.heappush(minHeap, 6)
# insert 2 into heap
heapq.heappush(minHeap, 2)
# insert 1 into heap
heapq.heappush(minHeap, 1)
# insert 9 into heap
heapq.heappush(minHeap, 9)
print("After pushing, heap looks like: {}".format(minHeap))
#heappop
# pop and return smallest element from the heap
smallest = heapq.heappop(minHeap)
print("Smallest element in the original list was: {}".format(smallest))
print("After popping, heap looks like: {}".format(minHeap))
# heappush and heappop for items with multiple entries
# Note: If you insert a tuple inside the heap, the element at 0th index of the tuple is used for comparision
minHeap = list()
heapq.heappush(minHeap, (0, 1))
heapq.heappush(minHeap, (-1, 5))
heapq.heappush(minHeap, (2, 0))
heapq.heappush(minHeap, (5, -1))
print("After pushing, now heap looks like: {}".format(minHeap))
# pop and return smallest element from the heap
smallest = heapq.heappop(minHeap)
print("Smallest element in the original list was: {}".format(smallest))
print("After popping, heap looks like: {}".format(minHeap))
| true |
d092c71ad5e2de4a9c363dd3cd9d7a831d3f0c4c | MrSxky/Math | /vowel.py | 270 | 4.25 | 4 | def anti_vowel(text):
new = ""
for n in text:
if n == "A" or n =="a" or n == "E" or n =="e" or n == "I" or n =="i" or n == "O" or n =="o" or n == "U" or n =="u":
new = new
else:
new = new + n
print (new)
anti_vowel("Hey look Words!") | false |
accd88583ea72460aa19246724995060e26d9538 | ymuratsimsek/pythonSolutions | /Q3.py | 1,598 | 4.21875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 11:32:38 2016
@author: ymuratsimsek
"""
"""
3. You are given a list of names below. You should be counting and printing the number of items that includes the letter “a” regardless of its occurrences in an item. For instance: the list including ‘Utku’, ‘Aynur’, ‘Tarık’, and ‘Aktan’ includes 4 a’s but 3 items in the list include a. Thus, you need to report both of these cases.
nameList = ["Utku", "Aynur", "Tarik", "Aktan", "Asli", "Ahmet", "Metin", "Funda", "Kemal", "Hayko", "Zelal", "Kenan", "Asli", "Atakan", "Umut"]
You need to be careful about the case-sensitive feature of python. If you count a’s in Aktan, there will be one and for A’s the result will be the same. However, the output for the occurence of a is 2. You can make use of for-loops to go over the whole list quickly. You should print both the total number of a’s and the total number of names including the target letter, a.
"""
###start python code for question 3
nameList = ["Utku", "Aynur", "Tarik", "Aktan", "Asli", "Ahmet", "Metin", "Funda", "Kemal", "Hayko", "Zelal", "Kenan", "Asli", "Atakan", "Umut"]
total_a_count = 0
total_a_in_name_count = 0
for letter in nameList :
if "a" in letter.lower() :
total_a_count = total_a_count + letter.lower().count("a")
total_a_in_name_count = total_a_in_name_count + 1
print "The Total Number of a’s: " + str(total_a_count)
print "The Total number of names including the target letter, a: "+ str(total_a_in_name_count)
###end python code for question 3
| true |
6a727d537c35e06945f833122aa5f07e61f22b75 | TyrusK/Snowflake | /koch_snowflake2.py | 1,116 | 4.28125 | 4 | import turtle
# turtle settings
turtle.speed(0)
turtle.hideturtle()
# get the order
try:
order = int(input("What should the order be?(0 is a triangle) "))
except:
print("The order must be an integer.")
# make sure the order is in the right form
if order < 0:
print("The order must be positive.")
elif order > 5:
print("That order is too high")
# initialize variable
side_length = 500 / (3 ** order)
def main():
# get the turtle in position
turtle.left(90)
turtle.penup()
turtle.forward(500 / (3 ** 0.5))
turtle.pendown()
turtle.right(150)
# draw the base triangle
for count in range(3):
line(0)
turtle.right(120)
# line either draws a line or calls bump depending on the order
def line(current_order):
if current_order < order:
bump(current_order + 1)
else:
turtle.forward(side_length)
# bump goes one level deeper
def bump(current_order):
line(current_order)
turtle.left(60)
line(current_order)
turtle.right(120)
line(current_order)
turtle.left(60)
line(current_order)
# Call main
main()
| true |
f514ce9bf593ac6bea2ea2e5fa5051833f65367e | kjgaetjens/DigitalCrafts-Assignments | /Week1/Add-Two-Numbers.py | 283 | 4.4375 | 4 | #Create an app which takes two numbers as input from the user and then prints out the results of addition on the screen.
def add_two_nums(num1,num2):
print(num1+num2)
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
add_two_nums(num1, num2) | true |
54d406fbcb033fded57db5815bafaafd62a925a0 | poojagupta18/Python_Tryouts | /tryout8_tryExcept.py | 1,148 | 4.21875 | 4 | #try except in python is used to handle the exception
#Lets consider the code
#Before exception handling
#Here program causes crash after print(divide(0))
def divide(number):
return 24/number;
print(divide(12));
print(divide(3));
print(divide(5));
#print(divide(0)); commented for working of after part
print(divide(2));
"""Output:
2.0
8.0
4.8
Traceback (most recent call last):
File "G:/pooja_tryouts/python_tryout/tryout8_tryExcept.py", line 12, in <module>
print(divide(0));
File "G:/pooja_tryouts/python_tryout/tryout8_tryExcept.py", line 7, in divide
return 24/number;
ZeroDivisionError: division by zero"""
#As it will print for 3 function calls,for fourth it will throw error 'ZeroDivisionError' as computer dont know to handle divide by zero.
#After try except
def divide(number):
try:
return 24/number
except ZeroDivisionError: #you can also write as except: if you dont know exception type
print('You have entered zero...')
print(divide(12));
print(divide(3));
print(divide(5));
print(divide(0));
print(divide(2));
"""Output:
2.0
8.0
4.8
You have entered zero...
None
12.0"""
| true |
cf8dbd8af771bfb2bf8990b043068b2803c3f456 | poojagupta18/Python_Tryouts | /tryout_18_more_on_string.py | 1,285 | 4.34375 | 4 | #More about string:
#String can begin and end with double quotes.
>>> 'Hello'
'Hello'
>>> 'That is Alice's cat.'
SyntaxError: invalid syntax
>>> "That is Alice's cat."
"That is Alice's cat."
>>> 'That is Alic\'s cat'
"That is Alic's cat"
>>>
#Escape character let you put quotes and other character that are hard to type inside strings.
-------------------------------------------
#Escape character | print as
-------------------------------------------
\' | Single quote
\" | Double quote
\t | Tab
\n | Newline (line break)
\\ | Backslash
--------------------------------------------
>>> print('Hello there!\nHow are you?\nI\'m fine.')
Hello there!
How are you?
I'm fine.
>>>
#Strings within ''' or """ is considered as multiline string
>>> print("""Dear friends,
we are celebrating b\'dy today.
we will be having yummy snaks as well.
""")
Dear friends,
we are celebrating b'dy today.
we will be having yummy snaks as well.
>>>
>>> 'Hello world!'
'Hello world!'
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[1:5]
'ello'
>>> spam[-1]
'!'
#in and not in are used to check whether specific string is present or not
>>> 'Hello' in spam
True
>>> 'X' in spam
False
>>> 'HELLO' in spam
False
>>>
| true |
e66b218ab5100ac8dbfe55ea981483e42122a616 | shaadomanthra/cbpython | /batch1/day2/functions_completed.py | 776 | 4.21875 | 4 | # # Functions in Python
# Basic function
def basic_func():
print("This is a basic function")
# basic_func()
# function with arguments
def arg_func(arg1,arg2):
print(arg1,arg2)
# arg_func(2,3)
# print(arg_func(4,3))
# print(arg_func)
# function with return value
def add(a,b):
s = a+b
return s
# print(add(4,3))
# function with default value
def power(n,x=1):
result = 1;
for i in range(x):
result = result * n
return result
# print(power(2,3))
# print(power(2))
# print(power(x=3,n=2))
# function with varaible arguments
def var_args_func(*args):
s = 0;
for a in args:
s = s + a
return s
# print(var_args_func(4,2,4,5))
# print(var_args_func(4,2,4,5,10))
# global & local variables
a = 10
print(a)
def func():
global a
a=12
print(a)
func()
print(a) | true |
851d714a2dc7c07f8df598a550f31eecbbc1a7c9 | BrainLiang703/Python- | /List | 1,305 | 4.625 | 5 | #!/usr/bin/env python
#coding:utf-8
#list 的重要几个函数用法
a = [1,2,3]
c = [1,2,3]
b = [4,5,6]
a.extend(b) #把b列表的元素追加到a列表中
c.append(b) #把b列表当作一个元素追加到c列表中
b.insert(1,7) #在b列表中的索引为1的地方,增加元素7
print("List a is " + str(a))
print("List c is " + str(c))
print("List b is " + str(b))
print("a.index(2) 的索引 is " + str(a.index(2))) #index读取a列表中元素2的索引是多少
a.pop(1)#pop是根据索引来删除列表元素,但是如果函数中没填写索引号,那么就会默认删除所有的,剩下列表最后一个元素
print("a.pop(1) 后list a 为" + str(a))
c.remove(1)#remove是根据元素值来删除列表元素。要注意找不到值异常问题,需要捕捉异常。
print("c.remove(1) 后List c is " + str(c))
a.reverse() # reverse是把列表反转排列
print("a.reverse() 后list a 为" + str(a))
a.sort()#把列表的元素进行排列。
print("a.sort() 后list a 为" + str(a))
运行结果:
List a is [1, 2, 3, 4, 5, 6]
List c is [1, 2, 3, [4, 7, 5, 6]]
List b is [4, 7, 5, 6]
a.index(2) 的索引 is 1
a.pop(1) 后list a 为[1, 3, 4, 5, 6]
c.remove(1) 后List c is [2, 3, [4, 7, 5, 6]]
a.reverse() 后list a 为[6, 5, 4, 3, 1]
a.sort() 后list a 为[1, 3, 4, 5, 6]
| false |
2e32c0376565970135210d46b92e8c3812501ec4 | imtom4/try-python | /task38.py | 669 | 4.125 | 4 | # We're going to make our own rock-paper-python game, where paper beats rock, rock beats python, and python beats paper.
computer_choice= 'rock'
user_choice= input('enter rock, paper, or python:\n')
if computer_choice == user_choice :
print('TIE')
# IMPROVE on the code we just wrote to add some cases where a user can win.
# else:
# print('you lose :( computer wins :D)')
if computer_choice == user_choice:
print('TIE')
elif user_choice == 'rock' and computer_choice == 'python':
print('WIN')
elif user_choice == 'paper' and computer_choice == 'rock':
print('WIN')
elif user_choice == 'python' and computer_choice == 'paper':
print('WIN')
| true |
aad53cb789267d730efab4a2c1209171064daef9 | kofi/mlinterview | /linkedlist.py | 2,457 | 4.125 | 4 | class LLNode(object):
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str((self.data, 'next:', self.next))
__repr__ = __str__
# # add a new node as the next node
# def insert_next(node):
# self.next = next
class LinkedList(object):
def __init__(self, head = None):
self.head = None
# add a node to the LinkedList.
# this becomes the new head
def insert_node(self, data):
node = LLNode(data)
node.next = self.head
self.head = node
# returns the number of elements in the linked list
# starting the count from the head LLNode till we reach None
# def size(self):
# curr_node = self.head()
# count = 0
# while curr_node:
# count = count+ 1
# curr_node = curr_node.next
# return count
def question5(head,n):
if head is None:
return None
# counter for tracking the size of the sliding window
count = 0
# set both start and end nodes to the head
window_start = head
window_end = head
if window_end is None:
return None
while count < n:
# create a sliding window of length n and find the node at the window end. Remember the window will be size n
if window_end is None:
return None
window_end = window_end.next
count = count + 1
# start moving the window start till window_end becomes None
# then window start will be size n from the end of the LinkedList
while window_end is not None:
window_start = window_start.next
window_end = window_end.next
return window_start.data
def main():
print("Question 5, Test 1:")
# Test 1
ll = LinkedList()
ll.insert_node(50)
ll.insert_node(40)
ll.insert_node(30)
ll.insert_node(20)
ll.insert_node(10)
#print(ll .head)
print(question5(ll.head,4))
#output: 20
# Test 2
print("Question 5, Test 2:")
ll = LinkedList()
ll.insert_node(50)
print(question5(ll.head,4))
#output: None
# Test 3
print("Question 5, Test 3:")
ll = LinkedList()
print(question5(ll.head,4))
#output: None
# Test 4
print("Question 5, Test 4:")
for i in range(50):
ll.insert_node(i)
print(question5(ll.head,14))
#output : 13
if __name__ == '__main__':
main() | true |
a25bb8b35ca3727f573b974ca3e9888b8c38f0b4 | kuldeeprishi/Reversing_String | /reversing_string.py | 1,280 | 4.59375 | 5 | #-------------------------------------------------------------------------------
# Name: Reversing a String
# Purpose: Different ways to reverse a string in python
#
# Author: Kuldeep Rishi
#
# Created: 22-07-2013
#-------------------------------------------------------------------------------
string = "Hello, World!"
print "Original String","\t"*6,"==> ", string
print "="*59
# Method 1 : Define a function
# =================================
def reverse(string):
result = ""
for i in xrange(len(string), 0, -1):
result = result+string[i-1] # i-1 so as to avoid out of index error
return result
print "Method 1 : (Defining reverse function)","\t"*1,"==> ", reverse(string)
# Method 2 : Using Join
# =================================
print "Method 2 : (Using join)","\t"*4,"==> ", "".join([string[i-1] for i in xrange(len(string), 0, -1)])
# Method 3 : Using Join
# =================================
print "Method 3 : (Using join with reversed)","\t"*1,"==> ", "".join(reversed(string))
# Method 4 : Using Extended Slice
# =================================
print "Method 4 : (Using Extended Slice)","\t"*2,"==> ", string[::-1]
# Timings for these methods can be found at
# https://gist.github.com/IlianIliev/6056557
| true |
28dce1388d4d4987fd1da9f214f148a4c0d0f419 | subedisapana/python-fundamentals | /Python Datatypes/Dictionary.py | 2,160 | 4.34375 | 4 | #Storing and accessing data in dictionaries...
'''
-Data is stored in a key and value pair
-Mutable data structure
-unordered data structure
-key should be unique
-key should be immutable
-When we create a dict it will create a hash table using key and the value so retrival of value
using dict is much faster than list
-from hash table it will fetch data
-key only allows data structure-(int,strings,tuple,float); Dictionary only allows immutable data type as a key
-mutable data structure is not hashable
-There should be unique key; if key is same then it just update value.
'''
d={"emp_id":101,
"name":"ABC",
"email":"abc@gmail",
"name":"CDE"
}
#There must be unique key
print(d,type(d))
d["contact_no"] = 8888
print(d )
d["contact_no"] = 12345
print(d)
print(d["email"])
#get
#setdefault function
print(d.get("name"))
print(d.get("age",-1)) # Since there is no age as a key, it returns given value
print(d.get("age","key doesnot exist"))
print(d.setdefault("age"))
print(d)
d1={"emp_id":101,
"name":"CDE"
}
print(d1.setdefault("emp_id")) #101
print(d1.setdefault("age")) #None
print(d1)
print(d1.setdefault("Roll",50))
print(d1)
#Incase of set default if there doesn't exist a key then it provides default value as None
for v in d1:
print(v, d1[v])
#1:1, 2:4, 3:9, 4:16....10:100
d={} #empty dict
for value in range(1,11):
d[value] = value*value
print(d)
'''
Functions
keys
value
Items
'''
#If you want all the keys, value and items
print(d.keys())
print(d.values())
print(d.items())
for t in d.items():
print(t)
#Add, Update and Delete Operations
l1=[1,2,3,4,5] #key
l2=[1,2,9,16,25] #value
di=dict(zip(l1,l2)) #combines elements having same index
print(di)
l= [1,2,3,4,5]
d=dict.fromkeys(l,0) #it assigns none value in value
print(d)
d1 = {1:1,2:4, 3:9}
d2 = {4:16,5:25, 6:36}
d1.update(d2)
print(d1)
'''Delete items in dict
we have pop,popitems,del,clear'''
d3 = {1:1,2:4, 3:9}
r=d3.pop(2)# takes key as an argument
print(d3, r) #1: 1, 3: 9} 4
d4 = {1:1,2:4, 3:9}
r1= d4.popitem() #you are not specifying any key value
print(d4, r1) #{1: 1, 2: 4} (3, 9)
d4 = {1:1,2:4, 3:9}
d4.clear()
print(d4) | true |
fedc59177acdbf475be8a448ad6d010ccb25e406 | HainesR11/Python-Projects | /calulator.py | 1,501 | 4.1875 | 4 | while True:
input ("***********Welcome To The Calculator*********")
input ("for your infomation you cant use words or letters")
while True:
while True:
numb_1 = int(input("what is your first number: "))
if numb_1 >=0:
break
elif numb_1 <=0:
break
else:
print ("invalid number")
while True:
numb_2 = int(input("What is your second number: "))
if numb_2 >=0:
break
elif numb_2 <=0:
break
else:
print ("invalid number")
while True:
action = input("What is the fuction you wish to use: ")
if action == "+" :
answer = numb_1 + numb_2
print (answer)
break
elif action == "-" :
answer = numb_1 - numb_2
print (answer)
break
elif action == "*" :
answer = numb_1 * numb_2
print (answer)
break
elif action == "/" :
answer = numb_1 / numb_2
print (answer)
break
else:
print ("invalid function")
repeat = input ("would you like to restart: ").upper()
if repeat == "N" or "NO"
break
| true |
a7010cdaa7105351140354d7fa7374c455762570 | praatibhsurana/Competitive-Coding | /Strings/MakingAnagrams.py | 2,036 | 4.5625 | 5 | """
A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters
can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency.
For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. The student decides on an encryption scheme that involves two large strings.
The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number.
Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams.
Any characters can be deleted from either of the strings.
Example
a = 'cde'
b = 'dcf'
Delete 'e' from a and 'f' from b so that the remaining strings are cd and dc which are anagrams. This takes 2 character deletions.
Sample Input
cde
abc
Sample Output
4
Explanation
Delete the following characters from the strings make them anagrams:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
It takes 4 deletions to make both strings anagrams.
"""
# !/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'makeAnagram' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING a
# 2. STRING b
#
def makeAnagram(a, b):
# Write your code here
count = 0
counta = [0 for i in range(26)]
countb = [0 for i in range(26)]
for i in a:
counta[ord(i)-97] += 1
for i in b:
countb[ord(i)-97] += 1
print(counta, countb)
for i in range(26):
count += max(abs(counta[i]-countb[i]), 0)
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
| true |
86d1d9fcf8c5edfd54f2ec257b95bcc3087e70da | lxz0503/study_20190608 | /01_Python_Basics/hm_13_异常.py | 642 | 4.25 | 4 | # 利用下面的方法可以捕获任何未知错误
# except Exception as result
# 尽量少用异常处理,因为会降低代码的可读性
# 只有在有些异常无法预知的情况下,才会用异常处理
# !usr/bin/env python
try:
num = int(input("input a integer:"))
result = 8/num
print("the result is %s" % result)
except ValueError:
print("value error")
except ZeroDivisionError:
print("zero value error")
except Exception as result:
print("未知错误:%s" % result)
else:
print("尝试成功,无异常,就执行此处代码")
finally:
print("无论成功与否,都执行此处代码")
| false |
19660b4d071231b0958bc788332653cafcd9422c | lxz0503/study_20190608 | /string_process/9-map-function.py | 1,069 | 4.125 | 4 | # map()它接收一个函数 f 和一个可迭代对象(这里理解成 list),
# 并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回
# map()函数不改变原有的 list,而是返回一个新的 list
# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表
def square(x): # 计算平方
return x ** 2
res = map(square, [1, 2, 3, 4, 5]) # 计算列表各个元素的平方
# [1, 4, 9, 16, 25]
# TODO:use comprehensions 列表表达式
res = [x**2 for x in [1, 2, 3, 4, 5] if x > 1 and x < 5]
print(res)
# TODO:map function return an address,you must use a list to show it.
res = map(lambda x: x ** 2, filter(lambda x: x > 1 and x < 5, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数
# [4, 9, 16]
print(list(res))
# 提供了两个列表,对相同位置的列表数据进行相加
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
# [3, 7, 11, 15, 19]
| false |
588e316b20ecdb5d065298919a4ede092c0d7180 | fuppl/python | /course/ls_01_python_基础/l_13_字符串.py | 261 | 4.1875 | 4 | hello_str = "hello hello"
# 1.统计字符串长度
print(len(hello_str))
# 2.统计某个子字符串出现的次数
# 若不存在显示0
print(hello_str.count("hello"))
# 3.某个子字符串出现的位置
# 若不存在报错
print(hello_str.index(" "))
| false |
a0448832fb40d4368e86c3dbba826461c83b468b | tjhunkin/learnpython | /numbersStuff.py | 1,073 | 4.28125 | 4 | x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
# int : Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
# float : Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
# Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
# complex: Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
# conversion / casting
x = 1 # int
y = 2.8 # float
z = 1j # complex
# convert from int to float:
a = float(x)
# convert from float to int:
b = int(y)
# convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
| true |
89a9cdd7442e968f0dcaf0e54779880b8a1810c7 | tjhunkin/learnpython | /functions.py | 1,617 | 4.34375 | 4 | # global variable
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
def myfuncglobal():
global x
x = "fantastic"
myfunc()
myfuncglobal()
print("Python is " + x)
# unlimited arguments
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# named arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1="Emil", child2="Tobias", child3="Linus")
# unlimited named parameters
def my_function(**kid): # **kwargs
print("His last name is " + kid["lname"])
my_function(fname="Tobias", lname="Refsnes")
# default parameter value
def my_function(country="Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
# return values
def my_function(g):
return 5 * g
print(my_function(3))
print(my_function(5))
print(my_function(9))
# recursion
def tri_recursion(k):
print("k:" + str(k))
if k > 0:
output = tri_recursion(k - 1)
print("output:" + str(output))
result = k + output
print("result:" + str(result))
else:
result = 0
print("result:" + str(result))
return result
print("\n\nRecursion Example Results")
tri_recursion(2)
# scope for nested functions
def myfunc():
x = 300 # The local variable can be accessed from a function within the function:
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
| false |
8bceba7dd4b3bae18fb3b6331301cc5c06d04f21 | tjhunkin/learnpython | /print.py | 218 | 4.125 | 4 | x = "awesome"
print("Python is " + x)
# concatenates strings
x = "Python is "
y = "awesome"
z = x + y
print(z)
# works as a mathematical operator
x = 5
y = 10
print(x + y)
x = 5
y = "John"
print(x + y) # cannot mix
| false |
cee094f381ea8c16e3af68a1a737a2430aa654f5 | yeli7289/Algorithms | /sort/selectionsort.py | 478 | 4.21875 | 4 | # Selection Sort
# the left array is the sorted, and the right array is the unsorted,
# in each iteration, find the smallest one in the right and swap it with the leftmost element
def SelectionSort(A):
for i in range(len(A)):
samllest = A[i]
index = i
for j in range(i+1,len(A)):
if A[j]<samllest:
index = j
samllest = A[j]
swap(A,i,index)
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
list = [6,5,3,7,8,4,1,2,3,5]
SelectionSort(list)
print list | true |
aa0a0cdaef852744d3304b20c1b76db5329d4162 | khangnngo12/astr-119-section-2 | /operators.py | 798 | 4.125 | 4 | x = 9
y = 3
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponential
x = 9.191823
print(x//y) #floor division
#assignment operators
x = 9 #set x = 9
x += 3 #x = x + 3
print(x)
x = 9
x -= 3 #x = x - 3
print(x)
x *= 3 #x = x * 3
print(x)
x /= 3 # x = x / 3
print(x)
x **= 3 # x = x ** 3
print(x)
#comparison operators
x = 9
y = 3
print(x==y) #True if x equal to y, False otherwise
print(x!=y) #True if x is NOT equal to y, False otherwise
print(x>y) #True if x is greater than y, False otherwise
print(x<y) #true if x is lesser than y, False otherwise
print(x>=y) #True if x is greater than or equal to y, False otherwise
print(x<=y) #True if x is lesser than or equal to y, False otherwise
| true |
94599168b6af5181b885b55e96680f8660036ac1 | umoqnier/Python-challanges | /Level_3/level3_ex2.py | 551 | 4.125 | 4 | """
Each cell in a 2D grid contains either a wall ('W') or an enemy ('E'),
or is empty ('0'). Bombs can destroy enemies, but walls are too strong to be destroyed.
A bomb placed in an empty cell destroys all enemies in the same row and column, but the destruction stops once it hits a wall.
field = [["0", "0", "E", "0"],
["W", "0", "W", "E"],
["0", "E", "0", "W"],
["0", "W", "0", "E"]]
the output should be
bomber(field) = 2.
Placing a bomb at (0, 1) or at (0, 3) destroys 2 enemies.
"""
def bomber(field):
pass | true |
60bbe43837f8f56fd46c2b9d03d4eed270294f90 | georgeuwagbale/georgeCSC102 | /Abstraction.py | 721 | 4.1875 | 4 | from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Rectangle(Shape):
length = 3
breadth = 5
def calculate_area(self):
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle()
cir = Circle()
print("Area of a rectangle:", rec.calculate_area())
print("Area od a circle:", cir.calculate_area())
class Animal:
def move(self):
return "Moving"
class Dog(Animal):
name = "Dog"
def move(self):
print(self.name)
return "running"
d1 = Dog()
print(Dog.move(d1))
#print(Dog.name) | true |
e1f03912f27f81c6f8a351266708178b9c9fb9ad | TAleja0202/Taller-1-2-3 | /project2.py | 1,766 | 4.1875 | 4 | # ejercicio 1 pasado a python / calcular valor en dolares
dolar = 0.00027
pesos = float(input("Digite la cantidad de pesos a comvertir "))
comvercion: float = pesos * dolar
print(f"El valor en dolares es: {comvercion:.2f}")
# ejercicio 2 / mostrar numero en pantalla
numero = int(input("Ingrese un numero Entero: "))
print(type(numero))
print(f"El Numero Igresado es: ", numero)
# ejercicio 3 / calcular la masa del aire
presion = float(input("Ingrese la cantidad de la Precion: "))
volumen = float(input("Ingrese la cantidad de la volumen: "))
temperatura = float(input("Ingrese la cantidad de la temperatura: "))
masaAire = (presion * volumen)/(0.37*(temperatura + 460))
print(f"La masa de Aire es de: ", masaAire)
# ejercicio 4 / cantidad de pulsaciones cada 10 segundos
numPulsacion = 220
Edad = int(input("Ingrese su edad: "))
totalPulso = (220 - Edad)/10
print(f"Su pulso por el Ejercicio es: ", totalPulso)
# ejercicio 5 salario con aumento
salario = int(input("Ingrese su Salario Actual: "))
nuevoSal = salario + (salario * 0.25)
print(f"Su nuevo Salario es: ", nuevoSal)
# ejercicio 6 / presupuesto por areas de trabajo
presupuesto = float(input("Ingrese el Valor del Presupuesto Anual "))
ginecologia = presupuesto * 0.40
traumatologia = presupuesto * 0.30
pediatria = presupuesto * 0.30
print(f"El presupuesto para Ginecologia es de: {ginecologia:.2f}")
print(f"El presupuesto para Traumatologia es de: {traumatologia:.2f}")
print(f"El presupuesto para Pediatria es de: {pediatria:.2f}")
# ejercicio 7 / sacar ganancia del 30%
compra = float(input("Ingrese el Valor de la Compra "))
nuevoVal = compra + 3500
ganancia = nuevoVal * 0.30
print(f"Valor al cual lo debe Vender: {nuevoVal:.2f}")
print(f"y la ganancia es de: {ganancia:.2f}")
| false |
6ade23addc688f3ca256623a3883efc99d2ff5bf | PetersonDePaula/peterphy | /TerceiraAula.py | 2,100 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
horario = int(input('Qual horario é agora? '))
#Acabei de aprender como registrar um comentário
#Laço de repetição irá executar enquanto o horário for maior que zero e menor que seis.
#Caso a condição seja satisfeita o algorítimo irá repetir que horário está na madrugada até que este seja maior que seis.
while 0 < horario < 6:
print('Você está no horario da madrugada')
horario = horario + 1
else:
print('Você nao está no horario da madrugada')
# In[10]:
#O algorítimo vai imprimir o número de pipocas informado de maneira decrescente enquanto for maior que zero.
num_pipocas = int(input('Digite o numero de pipocas: '))
while num_pipocas > 0:
print('O numero de pipocas é: ', num_pipocas)
num_pipocas = num_pipocas - 1
else:
print("Não tem pipoca!Bora comprar mais!")
# In[11]:
# O algorítimo só sai do loop quando o usuário digitar a senha correta:
resposta = input('Informe sua senha: ')
while resposta != '102030':
resposta = input('SENHA INVÁLIDA! TENTE NOVAMENTE ')
else:
print("BEM VINDO, MESTRE.")
# In[12]:
nome_paises = ['Brasil','Canadá','Ítalia','Japão']
print(nome_paises)
# In[13]:
print('Tamanho da lista: ', len(nome_paises))
# In[14]:
print('Japão: ', nome_paises(4))
# In[15]:
print('Japão: ', nome_paises[4])
# In[16]:
nome_paises = ['Brasil','Canadá','Ítalia','Japão']
print('Quarto país é o:', nome_paises[4])
# In[17]:
nome_paises = ['Brasil','Canadá','Ítalia','Japão']
print('Quarto país é o:', nome_paises[3])
# In[18]:
print('Primeiro país é o: HUEHUE', nome_paises[0])
# In[19]:
#Slice remove o último elemento informado, no caso o elemento da posição 3.
print(nome_paises[0:3])
# In[20]:
print(nome_paises[1:])
# In[21]:
print (nome_paises[::2])
# In[23]:
print(nome_paises[::-1])
# In[32]:
champions = []
champions.append('Ahri')
champions.append('Ashe')
champions.append('Dr.Mundo')
champions.append('Master Yi')
champions.append('Annie & Chimbres')
print(champions)
# In[ ]:
| false |
84324066d7b62145c3377cc1255d0c7927d7c8dd | akshaynagpal/python_snippets | /code snippets/is_int.py | 612 | 4.25 | 4 | """
Problem:
An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not).
For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0.
This means that, for this lesson, you can't just test the input to see if it's of type int.
Hint: If the difference between a number and that same number rounded down is greater than zero, what does that say about that
particular number?
"""
#SOLUTION
def is_int(x):
if x==round(x,0):
return True
else:
return False
| true |
4801f8ed6ffb7a1c856b4cd80002230c7c314fb0 | akshaynagpal/python_snippets | /code snippets/censor.py | 457 | 4.15625 | 4 | #censor takes two strings, text and word, as input.
#It returns the text with the word you chose replaced with asterisks.
def censor(text,word):
result = ""
count = 0
no_of_stars = 0
split_list = text.split()
for i in split_list:
count += 1
if(i==word):
result += "*" * len(i)
else:
result +=i
if(count != len(split_list)):
result += " "
return result
| true |
6716134b88d7db94674c502b2cf14ebb4714b103 | mhiyer/ML-Helper-Codes | /Sigmoid Function/sigmoid_function.py | 1,369 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 15:41:39 2019
@author: mh iyer
Description: Code to:
1) Define sigmoid function
2) Plot it
3) Get sigmoid function value for an input x
"""
import numpy as np
import math
import matplotlib.pyplot as plt
# create sigmoid class
class Sigmoid:
# initialize
def __init__(self):
pass
# define sigmoid function
def sigmoid_function(self,x):
return (1./(1+math.exp(-x)))
# plot sigmoid curve
def visualize_sigmoid(self):
# initialize list to store x
x = []
# initialize list to store sigmoid(x)
sigmoid_fcn = []
# loop through a set of values
for i in np.arange(-20,20,0.1):
sigmoid_fcn.append(self.sigmoid_function(i))
x.append(i)
# plot
plt.scatter(x, sigmoid_fcn, color='blue')
plt.title('Sigmoid Function')
plt.xlabel('x')
plt.ylabel('Sigmoid(x)')
# example usage
if __name__ == "__main__":
# initialize Sigmoid object
s=Sigmoid()
# visualize sigmoid function
s.visualize_sigmoid()
# calculate sigmoid for a value
val=0.2
print('Sigmoid output for',val,' is :',s.sigmoid_function(val)) | true |
f2e8ea3e855bcbb6e2891ddb00605d54b256b56c | jessemcastro/resposta_estrutura_de_repeticao | /03.py | 1,088 | 4.125 | 4 | #Faça um programa que leia e valide as seguintes informações:
#Nome: maior que 3 caracteres;
#Idade: entre 0 e 150;
#Salário: maior que zero;
#Sexo: 'f' ou 'm';
#Estado Civil: 's', 'c', 'v', 'd';
nome = ""
while len(nome)<=3:
nome = str(input("Digite seu nome"))
if len(nome)<=3:
print("Nome inválido")
idade = -1
while idade<0 or idade>150:
idade = int(input("Digite sua idade"))
if idade<0 or idade >150:
print("Idade inválida")
salario = -1
while salario <= 0:
salario = float(input("Digite seu salario"))
if salario<=0:
print("Salário inválido")
sexo = ""
while sexo!="m" and sexo!="f":
sexo = str(input("Digite o sexo"))
if sexo!="m" and sexo!="f":
print("Sexo inválido")
estado_civil = ""
while estado_civil!="s" and estado_civil!="c" and estado_civil != "v" and estado_civil !="d":
estado_civil = str(input("Digite o estado civil"))
if estado_civil!="s" and estado_civil!="c" and estado_civil != "v" and estado_civil !="d":
print("Estado civil inválido") | false |
d057c6883feded817ebe0fd8042e5da371d6116e | bpham2018/powerFunction | /powerFunctionMain.py | 1,214 | 4.40625 | 4 | # float_input function -------------------------------------------------------------------
def float_input( question ):
try:
baseNumber = float( raw_input( question ) ) # terminating case
return baseNumber
except ValueError: # if input is not a real number
float_input( "\nThats not a valid input, try again: " ) # recursive call
# int_input function -----------------------------------------------------------------------
def int_input( question ):
try:
exponent = int( raw_input( "\nEnter the integer exponent: " ) ) # terminating case
return exponent
except ValueError: # if input is not a positive integer
int_input( "\nThats not a valid input, try again: " ) # recursive call
# Main Program ---------------------------------------------------------------------------
import powerFunctionFunction # import file so I can call the function in it
baseNumber = float_input( "\nEnter the base number: " ) # argument is the string you want function to ask
exponent = int_input( "\nEnter the a positive integer exponent number: " ) # --
print ( "\n" + str( powerFunctionFunction.power_function( baseNumber, exponent ) ) + "\n" ) # prints answer as a formatted string | true |
26581d4db51f08067c054c90116fa6e18170bd37 | jonnythebard/algorithms | /exercise/sorting/merge_sort.py | 488 | 4.25 | 4 | def merge_sort(S):
"""Sort the elements of Python list S using the merge sort algorithm"""
n = len(S)
if n < 2:
return
# devide
mid = n//2
S1 = S[0:mid]
S2 = S[mid:n]
# conquer
merge_sort(S1)
merge_sort(S2)
# merge results
i = j = 0
while i + j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i + j] = S1[i]
i += 1
else:
S[i + j] = S2[j]
j += 1
| false |
c363ee3e99dd36bc241b4cf9cb1c96edfad6b8ef | jonnythebard/algorithms | /exercise/linked_list/linked_stack.py | 1,231 | 4.125 | 4 | class Stack:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
def __init__(self):
self.n = 0
self.head = None
def is_empty(self):
return self.n == 0
def push(self, value):
node = self.Node(value)
if self.n == 0:
self.head = node
else:
node.next = self.head
self.head = node
self.n += 1
def pop(self):
node = self.head
self.head = node.next
self.n -= 1
return node
def peek(self):
if self.n > 0:
return self.head.value
else:
print("no item")
def size(self):
return self.n
def __str__(self):
arr = []
cursor = self.head
while cursor is not None:
arr.append(cursor.value)
cursor = cursor.next
return str(arr)
if __name__ == "__main__":
stack = Stack()
for n in range(6):
stack.push(n)
print(stack)
for _ in range(3):
stack.pop()
print(stack)
print(stack.size())
print(stack.peek())
| false |
f4f3882cb80b7140629e6fb644f2c018302eabe4 | NarcomFelix/python_lessons_p1 | /Lesson 3/P3.6.py | 1,206 | 4.15625 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов,
# разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре.
# Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
# Необходимо использовать написанную ранее функцию int_func()
def int_func(a):
a = a.title()
return a
word = input("Введите слово, состоящее из маленьких латинских букв: ")
print(int_func(word))
sentence = input("Введите предложение через пробел: ")
new_sent = sentence.split()
for el in new_sent:
el = int_func(el)
print(el, end=' ') | false |
2c18c50367bc99084c1cabfb0b1567f555caded7 | Sam-Garcon/ICS3U-Unit-2-02-phyton | /perimeter_of_rectangle.py | 611 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by:Sam. Garcon
# Created on:April 2021
# This program calculates the area and perimeter of a circle
# with radius inputted from the user
def main():
# this function calculates area and perimeter
# input
length = float(input("Enter length of the rectangle: "))
width = float(input("Enter width of the rectangle: "))
# process
perimeter = 2 * (length + width)
area = width * length
# output
print("")
print("Area is {0} mm².".format(area))
print("Perimeter is {0} mm.".format(perimeter))
if __name__ == "__main__":
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.