blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eacc9feb05e1b4aa4461200b11adddc39036eb3b | sdputurn/learn-python | /ex2.py | 2,344 | 4.1875 | 4 | def print_pattern(n):
for i in range(1,n+1):
for j in range(0,i):
print "* ",
for j in range(i,n):
print " ",
for j in range(i,n):
print " ",
for j in range(0,i):
print "* ",
print "\n"
n=int(raw_input("enter star pattern limit: "))
print_pattern(n)
def print_pattern_rev(n):
for i in range(1,n+1):
for j in range(i,n+1):
print "* ",
for j in range(1,i):
print " ",
for j in range(1,i):
print " ",
for j in range(i,n+1):
print "* ",
print "\n"
print_pattern_rev(n)
#String processing examples
#single quote and double quote are treated as same.
# print "my name is %s and weight is %d !!!" %('Zara', 21)
# print 'my name is %s and weight is %d !!!' %("Zara",21)
# e_string = '''this is a test string:\n
# - to test the string count
# - to check the length fo the string
# - replace a string with gven string eg - all ee to i
# - find some sting with in operator and by using program logic'''
e_string=raw_input("enter paragraph - ")
# print "string sount function syntax:\n",e_string.count.__doc__
# print e_string[0:20], "string" in e_string, e_string[0:20].capitalize(), "count - ", e_string.count("string",0, len(e_string))
pattern=raw_input("enter pattern to search - ").upper()
u_string=e_string.upper()
count=0
#below code is for fixed string length
# try:
# for i in range(0,len(e_string)):
# if u_string[i] ==pattern[0]:
# if u_string[i+1] == pattern[1]:
# if u_string[i+2] == pattern[2]:
# if u_string[i+3] == pattern[3]:
# if u_string[i+4] == pattern[4]:
# if u_string[i+5] == pattern[5]:
# count = count +1
# else:
# i = i +5
# else:
# i=i+4
# else:
# i = i+3
# else:
# i=i+2
# else:
# i=i+2
# except IndexError, e:
# print "looks like index error", e
# print "count of pattern - ", count
s_len = len(pattern)
# print u_string[10]
try:
for i in range(0,len(e_string)):
# print i
# print u_string[i:i+s_len], pattern
if u_string[i:i+s_len] == pattern:
count=count+1
i=i+s_len
if i+s_len > len(e_string):
break
else:
i=i+s_len
if i+s_len > len(e_string):
break
except IndexError,e:
print "looks like index error"
print "count of pattern - ",count
| false |
d0e9971af4674e0a7cb76be0b1d496c41f7bc799 | gonso1975/Ejercicios | /calculadora/calculadora.py | 1,359 | 4.15625 | 4 | import math
operacion=input("Introduce la operacion a realizar (suma,resta,multiplicacion,division,exponente,raiz): ")
def suma():
n1 = float(input("introduce un numero: "))
n2 = float(input("introduce el otro numero: "))
print("El resultado de la suma es:",n1+n2)
def resta():
n1 = float(input("introduce un numero: "))
n2 = float(input("introduce el otro numero: "))
print("El resultado de la resta es:",n1-n2)
def multiplicacion():
n1 = float(input("introduce numero: "))
n2 = float(input("introduce el otro numero: "))
print("El resultado de la multiplicacion es:",n1*n2)
def division():
n1 = float(input("introduce numero: "))
n2 = float(input("introduce numero: "))
print("El resultado de la division es:",n1/n2)
def exponente():
n1 = float(input("introduce numero: "))
n2 = float(input("introduce exponente: "))
print("El resultado del exponente es:",n1**n2)
def raiz():
n1 = float(input("introduce numero: "))
print("El resultado de la raiz es:",math.sqrt(n1))
if operacion=="suma":
suma()
if operacion=="resta":
resta()
if operacion=="multiplicacion":
multiplicacion()
if operacion=="division":
division()
if operacion=="exponente":
exponente()
if operacion=="raiz":
raiz()
| false |
df13ba743447e85d0d4a509d968a88a78e37ec7f | cce-bigdataintro-1160/winter2020-code | /3-python-notebook/13-writing-files-disk.py | 1,409 | 4.40625 | 4 | file_path = 'file_to_write.txt'
# To write a file using python we'll use the method `open`, here's the list of opening modes
# r Open text file for reading. The stream is positioned at the
# beginning of the file.
#
# r+ Open for reading and writing. The stream is positioned at the
# beginning of the file.
#
# w Truncate file to zero length or create text file for writing.
# The stream is positioned at the beginning of the file.
#
# w+ Open for reading and writing. The file is created if it does not
# exist, otherwise it is truncated. The stream is positioned at
# the beginning of the file.
#
# a Open for writing. The file is created if it does not exist. The
# stream is positioned at the end of the file. Subsequent writes
# to the file will always end up at the then current end of file,
# irrespective of any intervening fseek(3) or similar.
#
# a+ Open for reading and writing. The file is created if it does not
# exist. The stream is positioned at the end of the file. Subse-
# quent writes to the file will always end up at the then current
# end of file, irrespective of any intervening fseek(3) or similar.
my_file = open(file_path, 'w+')
my_file.write('Line1\n')
my_file.write('Line2\n')
my_file.write('Line3\n')
# It's important to close files after they've been used to avoid a `resources leak` on the os
my_file.close()
| true |
f5f613ecb20878537948001b3a67b1b83f1daab3 | andrewbowler/Programming-2018 | /fibonacci.py | 361 | 4.21875 | 4 | num = int(input('Enter #: '))
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci (n - 2)
print(str(fibonacci(num)))
#a(n) = a(n-1) + a(n-2)
""" I followed the recursion formula
I learned in discrete--did NOT expect
it to work, thought it would be MUCH harder
but I guess it works for a reason :^) """
| true |
b7d838d56a655db99740e0a015e3a3bab61343da | jawsnnn/python-pluralsight | /iterations/mapper.py | 1,219 | 4.21875 | 4 | from decimal import Decimal
from functools import reduce
# map() takes a function and runs it over a sequence(s) of inputs generating another sequence with the outputs of the function
color = ['blue', 'white', 'grey']
animal = ['whale', 'monkey', 'man']
place = ['asian', 'european', 'mythical']
def combine (color, animal, place):
return "{} colored {} {}".format(color, place, animal)
print(list(map(combine, color, animal, place)))
# filter() is similar to map in that it takes a single arg function and only returns those sequence numbers which are true (per the function)
def is_even(num):
if Decimal(str(num)) % Decimal('2') == 0:
return True
else:
return False
filtered = list(filter(is_even, [0, 1, 2, 3, 4, 5, 6]))
print(filtered)
# reduce takes a list/sequence and iterates over it, applying a single function to each value and accumulatiing the results
# ultimately returning a single accumulated values. The first argument to the function is always the accumulated result by default
# and the second is the next list entry
l = [x for x in range(1,6)]
print(l)
def fact(x, y):
print("{} into {}".format(x, y))
return x * y
ll = reduce(fact, l, 1)
print(ll)
| true |
4e1e679d21c1216c1b475657db166acdae9721f3 | StevenGaris/codingbat | /Warmup2/string_bits.py | 244 | 4.125 | 4 |
# Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
def string_bits(word):
return word[::2]
print(string_bits("Hello"))
print(string_bits("Hi"))
print(string_bits("Heeololeo")) | true |
c7aaed5ab4286eaeff8797d12fd45b5de719b95f | mahhets/algorithms-and-data-structures | /7.Алгоритмы сортировки/Разворот массива.py | 915 | 4.4375 | 4 | """
Разворот массива
"""
import random
size = 10
array = [i for i in range(size)]
random.shuffle(array)
print(array)
def revers(array):
for i in range(len(array) // 2):
array[i], array[len(array) -i - 1] = array[len(array) - i - 1], array[i]
revers(array)
print(array)
"""
Встроенная сортировка в Python позволяет отсортировать по порядку возростания .sort()
sort может принимать аргумент reverse = True, который выполнит разворот массива
"""
print('*'*50)
t = tuple(random.randint(0,100) for _ in range(10))
print(t)
"""
Кортежи неизменяемы, но для их сортировки тоже есть встроенная функция - sorted, которая так-же принимает reverse
"""
print('*'*50)
t = tuple(sorted(t))
print(t)
| false |
deb465f5ba74913dad810465fcd287baee47a4d6 | mahhets/algorithms-and-data-structures | /Задачи с кодом/7.py | 660 | 4.28125 | 4 | """
Напишите программу, которая принимает имя файла и выводит его расширение.
Если расширение у файла определить невозможно, выбросите исключение.
"""
def filename(file):
filename_parts = file.split('.')
if len(filename_parts) < 2:
raise ValueError('У файла нет расширения')
first, *middle, last = filename_parts
if not last or not first and not middle:
raise ValueError('У файла нет расширения')
return filename_parts[-1]
text = 'lalal.py'
print(filename(text)) | false |
38858ebcd8ced7c1bd9292a31029cfc7823db3cd | mahhets/algorithms-and-data-structures | /3.massives/1.py | 1,288 | 4.125 | 4 | # 1. Адекватное удаление итемов из списка (которые не пропускают элементы)
#list_1 = [1,2,3,4]
#for i , item in enumerate(list_1[:]):
# list_1.remove(item)
#print(list_1)
# Крестики-нолика, где Х побеждает с первой попытки
#row = [''] * 3
#board = [row]*3
#board = [['']*3 for _ in range(len(row))]
#board[0][0] = 'X'
#print(board)
# 4. Игла в стоке сена
#t = ('one','two')
#for i in t:
# print(i)
#c = ('one',)
#for i in c:
# print(i)
# 5. Сохранить только уникальне значения
#list_1 = [1,3,4,6,6,4,3,3,5,6]
#list_1 = list(set(list_1))
#print(list(set(list_1)))
# 6. Ключи словаря - изменяемый объект
set_x = {1,2,3}
list_x = [1,4,7]
# Мы не можем в кач-ве ключа словарю передавать изменяемые объекты
# В данном случае нам нужно представить что-то из исходных в кач-ве неизменяемых
# К примеру List предствить как tuple, а множество как frozenset
dict_x = {frozenset(set_x):list_x}
dict_y = {tuple(list_x):set_x}
print(dict_x)
print(dict_y) | false |
834b0aaf7e75123d54bcd3cd69a19afe33c390fa | OldDon/UdemyPythonCourse | /UdemyPythonCourse/2.37 Functions and Conditionals 3.py | 336 | 4.21875 | 4 | # Program to convert Celcius to Farenheit....
# Test for lowest possible temperature that physical matter can reach....
# That temperature is -273.15 degrees Celcius
def cel_to_fahr(c):
if c < -273.15:
return "That temperature doesn't make sense!"
else:
f = c * 9/5 + 32
return f
print(cel_to_fahr(-273.4)) | true |
acfe789899c1b5600c79416d88fe2216c16bbbdc | froland-git/Python | /ADV-IT_Lessons/For_beginners/Lesson-07-Loops.py | 570 | 4.15625 | 4 | for x in range(0,10): # 10 не входит в диапазон
print(x)
print("***********")
for x in range(-4,10,2): # 10 не входит в диапазон c шагом 2
print("Number x =" + str(x))
print("***********")
for x in range(-4,10,2): # 10 не входит в диапазон c шагом 2
print("Number x =" + str(x))
print("***********")
if x == 6:
break #Выход
print("#####EOF#####")
x = 0
while True: #Бесконечный цикл
print(x)
x = x + 1
if x == 5:
break #Выход | false |
5960c63c76d83cf3a0c149c90a10cad92333bd9b | Jiaxigu/pycogram | /pycogram/dijkstra.py | 1,700 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Single-source shortest path algorithm for non-negative graphs.
"""
import math
def dijkstra(graph, source):
"""
Given a graph and a source within the graph,
find shortest paths and distances for all nodes.
The edges in the graph must be non-negative.
Parameters
----------
- graph: Graph
a non-negative graph.
- source: node
a hashable object representing the source in graph.
Returns
-------
- dist: dict
shortest distance to source for each node.
- prev: dict
last node on the shortest path for each node.
Raises
------
- ValueError
if source is not in graph or negative edge exists.
Reference
---------
- https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#pseudocode
- Cormen T H. Introduction to algorithms[M]. MIT press, 2009.
"""
if source not in graph.nodes:
raise ValueError('The given source {} is not in the graph.'.format(source))
if not graph.is_nonnegative:
raise ValueError('There are non-positive edges in the graph.')
unvisited_nodes = graph.nodes
dist = {}
prev = {}
for node in graph.nodes:
dist[node] = math.inf
prev[node] = None
dist[source] = 0
while unvisited_nodes:
min_node = min(unvisited_nodes, key=(lambda x: dist[x]))
unvisited_nodes.remove(min_node)
for adj_node in graph.adjacent_nodes_of(min_node):
new_dist = dist[min_node] + graph.get_weight(min_node, adj_node)
if new_dist < dist[adj_node]:
dist[adj_node] = new_dist
prev[adj_node] = min_node
return dist, prev
| true |
6e13c17b6c4b1afc7b016b837ed9459a3a9a65ce | davidgoldcode/cs-guided-project-computer-memory-basics | /src/demonstration_2.py | 1,684 | 4.375 | 4 | """
Given an unsigned integer, write a function that returns the number of '1' bits
that the integer contains (the
[Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight))
Examples:
- `hamming_weight(n = 00000000000000000000001000000011) -> 3`
- `hamming_weight(n = 00000000000000000000000000001000) -> 1`
- `hamming_weight(n = 11111111111111111111111111111011) -> 31`
Notes:
- "Unsigned Integers (often called "uints") are just like integers (whole
numbers) but have the property that they don't have a + or - sign associated
with them. Thus they are always non-negative (zero or positive). We use uint's
when we know the value we are counting will always be non-negative."
"""
# you get normal number then convert it
def hamming_weight(n: int) -> int:
# return the number of 1s in the bitwise representation of the number
# if we're given a normal unsized integer, how do we convert it
# to a bitwise representation?
# bitwise logical operators: '&', '|'
# the left & right shift operations
# '<<' or '>>'
# the '>>' allows us to shift one over to the right
# using & we have a way to check the rightmost bit of n to see if it equals 1
# FIRST EXAMPLE
# count = 0
# while n != 0:
# if n & 1 == 1:
# count += 1
# n = n >> 1
# return count
# SECOND
# bin_representation = bin(n)
# counter = 0
# for i in range(len(bin_representation)):
# if bin_representation[i] == '1':
# counter += 1
# return counter
# THIRD
return bin(n).count('1')
print(hamming_weight(10))
print(hamming_weight(20))
print(hamming_weight(211))
print(hamming_weight(8))
| true |
1f350dc709c3aa29a440137a3616de38be1a4872 | Chu66y8unny/TP2e | /code/C02/ex2-2-1.py | 209 | 4.3125 | 4 | import math
def sphere_vol(r):
return 4.0 / 3.0 * math.pi * r**3
if __name__ == '__main__':
radius = 5
vol = sphere_vol(radius)
print(f"The volume of a sphere with radius {radius} is {vol}")
| true |
8822106518492def90adf59ca087c29ef3398846 | AlanRAN7/Course_PythonSinFronteras | /Python_Básico/identacion.py | 2,782 | 4.28125 | 4 | #Sirve para hacer comparaciones
#La identación sirve para que el programa
#sirva bien
if 5 > 3:
print("5 es mayor de 3")
#Los comentarios sirven para ayudarnos en un futuro a saber cómo funciona una línea de código
#VARIABLES
x = 5
y = "chanchito feliz"
print(x, y) #Imprime n argumentos separados por coma
#Valor primitivo = número, letra, frase [sin guardar en variables]
email = "chanchito@feliz.com"
print(email)
mi_var = "chanchito"
#MIVAR = constantes [TODO MAYUSCULA]
#MULTIPLES VARIABLES
a,b,c = "lala", "lele", "lili"
print(a,b,c)
valor1 = valor2 = valor3 = 'Chanchito Feliz'
print(valor1, valor2, valor3)
#CONCATENACIÓN
inicio = 'Hola ' #Sin separación, se juntan las palabras
final = 'mundo'
print(inicio + final)
#SECCIÓN 5: TIPOS DE DATOS
#Strings y Números
palabra = 'hola mundo' #string
oracion = "Hola mundo con comilla doble" #string
entero = 20 #integer
conDecimales = 20.2 #float
complejo = 1j #Números complejos
print(palabra, oracion, entero, conDecimales, complejo)
#INTRODUCCIÓN A LAS LISTAS
lista = [1,2,3] #Corchetes vacias = listas vacias
print(lista)
lista2 = lista.copy() #Copia una lista a otra
print('lista 2 [Copia de la lista 1]: ', lista2)
lista.append(4) #Agregar más elementos a la lista
print('lista 1 [Con nuevo elementos]: ', lista)
#lista.clear() #Elimianr todos los elementos de la lista
#CONTANDO ELEMENTOS Y CALCULANDO EL LARGO DE UNA LISTA
print (lista.count(1), lista2.count(5)) #Cuenta elementos repetidos que están dentro de "()"
print(len(lista)) #Imprime la longitud de una lista
print(len(lista), len(lista2))
largoLista = len(lista)
largoLista2 = len(lista2)
print(largoLista, largoLista2)
#ACCEDIENDO A ELEMENTOS DE LAS LISTAS
lista = ['Hola', 'Mundo', 'Chanchito feliz']
print(lista[0]) #Indice 0 = primer dato del arreglo
#ELIMINANDO ELEMENTOS DE UNA LISTA
lista.pop() #Elimina el último elemento de la lista
print(lista)
lista.append("Chanchito Feliz")
lista.remove('Hola') #lista.remover('string a eliminar')
print(lista)
#REVERSE Y SORT
lista.reverse() #Pone la lista al revés
print(lista)
#lista.sort() #Acomoda la lista de manera ordenada, sólo datos núméricos o sólo datos string, no juntos
#TUPLAS
#Las tuplas se declaran con () en lugar de []
#Las tuplas tienen pocos métodos
tupla = ('hola', 'mundo', 'somos', 'tupla')
print(tupla)
print(tupla.count('hola')) #Cuenta todos los elementos que contengan la palabra 'hola'
print(tupla.index('mundo')) #Busca la posición donde se encuentra ese elemento / dato que queramos encontrar
print(tupla[0]) #Regresa el primer valor de la tupla
# tupla.append('chanchito') #Las tuplas no son modificables, por lo tanto el append no sirve
listaDeTupla = list(tupla) #Transforma la tupla en lista
print(listaDeTupla)
listaDeTupla.append('chanchito')
#RANGE
rango = range(6) #RANGO DE (0,6)
print(rango) | false |
24ae58168838364e4ae98f88e63388a0ef93793d | fernandoreta/techdegree-project-1 | /guessing_game.py | 1,688 | 4.3125 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
--------------------------------
FERNANDO URIEL WERTT RETA
"""
import random
record = []
def start_game():
print("""
------------------------------------
Welcome to the Number Guessing Game!
------------------------------------
""")
while True:
answer = random.randint(1, 10)
guess = input("Pick a number 1 and 10: ")
attempts = 1
while guess != answer:
try:
guess = int(guess)
except ValueError:
print("Please only enter numbers ")
guess = input("Pick a number 1 and 10: ")
attempts += 1
else:
if guess < answer:
print("It's higher")
guess = input("Pick a number between 1 and 10: ")
attempts += 1
elif guess > answer:
print("It's lower")
guess = input("Pick a number between 1 and 10: ")
attempts += 1
print("NICE! You scored in {} attemps".format(attempts))
record.append(attempts)
print("Your scores is: {}".format(attempts))
score = print("The best record is : {} attempts".format(min(record)))
play_again = input("Do you want to play again? ([y]es, [n]o) ")
if play_again.lower() == 'y':
start_game()
else:
print("GOOD BYE!!")
print("The best record is : {} attempts".format(min(record)))
if __name__ == '__main__':
# Kick off the program by calling the start_game function.
start_game()
| false |
a59598e5251e5d48d4b26623dc23516aec27be73 | Mazama1980/FloweryJitteryLint | /guess.py | 801 | 4.15625 | 4 | """This is a Guess the Number Game"""
import random
number=random.randint(1,20)
max_guesses=6
#max_guesses=2
print("Hint:the number is: ", number)
player=input('Hello! What is your name? ')
print('Hello '+ player + '.')
print("I am thinking of a number between 1 and 20.")
print()
for guess_count in range(1, max_guesses):
print("Guess", guess_count, "of", max_guesses)
guess=input("Your guess:")
guess= int(guess)
if guess < number:
print("Your guess is too low")
elif guess > number:
print("Your guess is too high")
else:
break
print()
if guess==number:
guess_count=str(guess_count)
print("Good job, "+ player + "! You guessed my number in " + guess_count + " guesses!")
else:
number=str(number)
print("Nope! The number I was thinking of was " + number + ".") | true |
dfa69eebab5e0e970c27288a2b1233319546a4c0 | dogac00/Codewars | /mumbling.py | 1,244 | 4.28125 | 4 | # The problem is:
# This time no story, no theory. The examples below show you how to write function accum:
# Examples:
# accum("abcd") -> "A-Bb-Ccc-Dddd"
# accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
# accum("cwAt") -> "C-Ww-Aaa-Tttt"
# The parameter of accum is a string which includes only letters from a..z and A..Z.
# First I solve this problem with a for loop. This is to get the main idea behind the problem and see the tests and outputs
# on the screen. This is my first and more readable solution.
def accum(s):
st = ""
for i, letter in enumerate(s):
st += letter.upper()
st += letter.lower()*(i)
st += "-"
return st[:-1]
# The function creates an empty string and for each letter it adds every letter and dash. Returns without the last element.
# Then I tested a few samples on the compiler. I thought I can do this in a one-liner using list comprehension and join method.
# Then I came up with this beautiful one-liner.
def accum(s):
return "-".join([letter.upper()+letter.lower()*i for i, letter in enumerate(s)])
# I checked their execution time with time.time() method in time module. There is no significant time differences
# to execute for both functions.
| true |
99dd240e76e4fd3eeff66532c5133ee22ef01af0 | ArnoSonck/Python_practice | /square_integer_numbers.py | 801 | 4.25 | 4 | def run():
n = input("Up to what number do you want to know its squares: ")
print("You chosed: " + n)
my_list = []
for i in range(1,int(n)+1):
my_list.append(i*i)
print("Theirs squares are: \n", my_list, "\n")
# keeping only numbers divisible by 3
only_three = []
for i in range(0,int(n)):
if my_list[i] % 3 == 0:
only_three.append(my_list[i])
print("Theirs members that are only divisible by 3 are: \n", only_three, "\n")
# Avoiding divisors of 4, 6, and 9.
# Notice that the least common multiple is 36
# Using List Comprehisions
no_36_list = [i**2 for i in range(1,int(n)+1) if i**2 % 36 == 0]
print("Keeping only divisible by 4, 6, and 9 numbers: \n", no_36_list)
if __name__ == '__main__':
run() | false |
29f6bc0816c1f353680da3afea5cd88a92c1476d | ksairamteja01/module-2-assignment | /module2 assin3.py | 1,687 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#1 MAX OF THREE
# In[5]:
n1=float(input("enter he first number"))
n2=float(input("enter the second number"))
n3=float(input("enter the thrid number"))
if (n1>n2)and(n1>n1):
print("n1 is greater")
elif (n2>n1)and(n2>n3):
print("n2 is greater")
else:
print("n3 is greater")
# In[6]:
#2 REVERSE OF A STRING
# In[8]:
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('apple'))
# In[9]:
#3 PALINDROME
# In[5]:
def palindrome():
try:
num=int(input("enter a number :"))
rev=0
num1=num
while(num>0):
rem=num%10
rev=(rev*10)+rem
num=num//10
if(num1==rev):
print("YES ITS A PALINDROME..")
else:
print("NO ITS NOT A PALINDROME..")
except:
print("please enter valid input..")
finally:
print("done")
# In[7]:
palindrome()
# In[8]:
#4
# In[9]:
def prime():
a=int(input("enter a number:"))
for i in range(2,a):
if(a%i==0):
j=1
break
else:
j=0
if(j==1):
print("not a prime")
else:
print("yes its a prime")
# In[10]:
prime()
# In[11]:
#5
# In[7]:
def sumOfSquares():
a=int(input("enter an number :"))
sum=0
b=a+1
for i in range(1,b):
sum=sum+(i**2)
print("sum is ",sum)
# In[9]:
sumOfSquares()
# In[ ]:
| false |
93cd88a1dd73eb962548db859c39e767a77fee75 | TechTouhid/The_Modern_Python_3_Bootcamp | /dictionary.py | 400 | 4.28125 | 4 | # Dictionary comprehension
# Syntax {____:____ for___ in___}
# number = {"first": 1, "second": 2, "third": 3}
#
# squared_number = {key: value ** 2 for key, value in number.items()}
# print(squared_number)
# value = dict.fromkeys(range(1, 6), 'Touhid')
# print(value)
multi = [[1, 2, 3], [4, 5, 6]]
x = [1, 2, 3]
# print(multi[1][0])
# multi[1][0] = 5
#
# print(multi[1][0])
print(x.index(3))
| false |
53612dd6bfbd359d5c4f5a14d72d5ab8a30b6d42 | eevans01/development_python | /08-Stacks/stacks.py | 1,737 | 4.15625 | 4 | #Programmer: Eric Evans, M.Ed.
#Program Name: Introducton to Stacks
#Description: Working with LIFO Stacks, For Loops, and Conditional Statements
#
stack_ascending = [1, 2, 3, 4, 5] #Create ascending stack with integers 1, 2, 3, 4, & 5
stack_ascending.append(6) #Appends 6 to the top of the stack
stack_ascending.append(7) #Appends 7 to the top of the stack
stack_ascending.append(8) #Appends 8 to the top of the stack
print ("Ascending Stack: " + str(stack_ascending)) #Print the contents of the ascending stack
stack_descending = [] #Creates an empty stack named stack_descending to hold the descending integers
for x in range(0,8): #Opens a for loop that will run 8 times
stack_descending.append(stack_ascending.pop()) #Populates the descending stack with the top item of the ascending stack
print ("Descending Stack: " + str(stack_descending)) #Print the contents of the descending stack
stack_even = [] #Creates an empty stack named stack_even to hold even integers
stack_odd = [] #Creates an empty stack named stack_odd to hold odd integers
for x in range(0,8): #Opens a for loop that will run 8 times
top = stack_descending.pop() #Defines a variable named top that holds the value from the top of the descending stack
if top%2 == 0: #Determines if modulus 2 of the top variable is equal to zero
stack_even.append(top) #If modulus 2 of the top variable is equal to zero, the value is populated to the stack_even
else: #Catch all
stack_odd.append(top) #If modulus 2 of the top variable is NOT equal to zero, the value is populated to the stack_odd
print ("Even Integers Stack: " + str(stack_even)) #Print the contents of the even stack
print ("Odd Integers Stack: " + str(stack_odd)) #Print the contents of the odd stack | true |
9a4f02d7ce1ad6dd5558536323687e759983f58f | jprsurendra/core_python | /oops/aggregation_and_composition.py | 1,351 | 4.5 | 4 |
class Salary:
def __init__(self, pay):
self.pay = pay
def get_total(self):
return (self.pay * 12)
'''
Example of Aggregation in Python
Aggregation is a week form of composition. If you delete the container object contents objects can live without container object.
'''
class Employee:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
def annual_salary(self):
return "Total: " + str(self.pay.get_total() + self.bonus)
'''
Example of Composition in Python
In composition one of the classes is composed of one or more instance of other classes. In other words one class is container and other class is content and if you delete the container object then all of its contents objects are also deleted.
'''
class ComposedEmployee:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
self.obj_salary = Salary(self.pay)
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total() + self.bonus)
def main_aggregation():
obj_sal = Salary(600)
obj_emp = Employee(obj_sal, 500)
print(obj_emp.annual_salary())
def main_composition():
obj_emp = ComposedEmployee(600, 500)
print(obj_emp.annual_salary())
if __name__ == "__main__":
main_aggregation()
main_composition() | true |
5bc3826763bd156effca51adddbdf7b3e530f6f8 | cxvdy/shehacks2021 | /shehacks.py | 801 | 4.21875 | 4 | import random
#The user chooses the numbers for the range
print("Choose a range of numbers")
start = int(input("Enter first number: "))
end = int(input("Enter last number: "))
#Exit app if user inputs data format
if(start > end):
print("Incorrect range")
exit()
#generate random number
random = random.randint(start,end)
#run loop until number is correctly guessed
while True:
userguess = (input("Guess random number:"))
#checks if input number is of type integer
if (userguess.isdigit() is False):
print("Error. Only integers are allowed")
elif (int(userguess) < random):
print("Incorrect. The number is higher")
elif (int(userguess) > random):
print("Incorrect. The number is lower")
else:
print("Congratulations. You guessed the number!")
break
| true |
2709bea47e7e15ea3ef7096bea724532f168a251 | HetDaftary/Competitive-Coding-Solutions | /Geeks-For-Geeks/Practice/Array/Rotate-Array.py | 752 | 4.21875 | 4 | #User function Template for python3
class Solution:
#Function to rotate an array by d elements in counter-clockwise direction.
def rotateArr(self,A,D,N):
#Your code here
ls = A[D:] + A[:D]
for i in range(N):
A[i] = ls[i]
#{
# Driver Code Starts
#Initial Template for Python 3
import math
def main():
T=int(input())
while(T>0):
nd=[int(x) for x in input().strip().split()]
N=nd[0]
D=nd[1]
A=[int(x) for x in input().strip().split()]
ob=Solution()
ob.rotateArr(A,D,N)
for i in A:
print(i,end=" ")
print()
T-=1
if __name__=="__main__":
main()
# } Driver Code Ends | true |
91f8c8973e2594549e81c6e2a01f264309b91150 | umesh-gattem/Pyhton_matplotlib | /matplotlibExamples/SampleExample.py | 1,779 | 4.71875 | 5 | import matplotlib.pyplot as plt
import numpy as np
'''The following three lines will us used to draw a graph between two axis.
The Y axis label is some numbers and it takes the numbers from 1,2,3,4.
Here X axis values are not specified but it takes the same values as Y axis .
But x axis starts values from 0 and ends at 3.0 as axis length is 4.'''
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
'''The following three lines used to plot a graph between two axis.
Here X axis takes the values and Y axis takes the squares of the values taken in x axis.
the third parameter 'ro' is nothing but r means red color and 'o' means shape of the plotting.
This graph takes red circles to plot the values. plt.axis() gives the boundaries of the graph .
In the following graph X axis boundaries is 0-6 and Y axis boundaries is 0-20 .'''
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
''' Here we have taken the list of numbers by using arange function of the numpy.
arange functions takes the three parameters , first one is starting index,
second one is stopping index, third one is interval .
It means following statement takes the index from 0 to 5 with 0.2 interval .Y axis takes squares of the X axis.'''
list_numbers = np.arange(0.0, 5.0, 0.2)
plt.plot(list_numbers, list_numbers ** 2, 'ro', list_numbers, list_numbers ** 3, 'b^')
plt.axis([0, 6, 0, 130])
# The following statement mentions about the width of the line plotted.
line, = plt.plot(list_numbers, list_numbers + 5, linewidth=5.0)
plt.title("Line Width is 2.0")
plt.axis([0, 6, 0, 30])
'''The following statements use the keyword anti aliased which means line should me aliased or not.'''
plt.plot(list_numbers, list_numbers + 2, antialiased='False')
plt.axis([0, 6, 0, 30])
plt.show()
| true |
1ee1ac04d1eb09efabb44f80299bb866d4c558d6 | kyle-mccarthy/syrian-data-io | /src/hw1.py | 521 | 4.375 | 4 | # the list example, adding items the interating
list_example = []
list_example.append('one value')
list_example.append('another value')
list_example.append('the last value')
# iterate the list
for items in list_example:
print(items)
# the dict example
dict_example = {}
dict_example['key'] = 'value'
dict_example['another'] = 'item'
dict_example['the final'] = 'value in the list'
# iterate the values
for value in dict_example:
print(value)
# iterate the keys
for key in dict_example.keys():
print(key)
| true |
a1bbb1f93e4043c3acceb5ce1bdab21c9f377e9f | atishbits/101 | /numberEndingWith3.py | 1,537 | 4.34375 | 4 | import sys
import pdb
'''
Every number that ends with three follows a very interesting property:
"Any number ending with 3 will always have a multiple that has all 1's".
for eg, for,
3 : 111
13 : 111111
and so on.
Now the question is, given a number ending with 3, return this factor, or return the number of 1's in this divisor.
Now as can be seen from the examples given here, this number can be well beyond the range of normal data types like double or long long. Now the approach that immediately comes to mind is to use a user defined data structure like a linked list etc. to store this number. This could be a possible approach but would require tremendous amount of time and space. A very intelligent solution to this question comes by looking at how division works.
'''
last_digit_factors = {0:0, 1:7, 2:4, 3:1, 4:8, 5:5, 6:2, 7:9, 8:6, 9:3 } #for number 3
if __name__ == "__main__":
in_num = int(sys.argv[1])
if in_num % 10 != 3:
print "Wrong Input:", in_num, "input should end with 3"
sys.exit()
result = ""
next_factor = last_digit_factors[1]
result = str(next_factor)+result
curr_num = (in_num * next_factor)/10
#while (not is_num_1s(curr_num)):
while (True):
need_factor_for = abs((11 - curr_num)%10)
next_factor = last_digit_factors[need_factor_for]
result = str(next_factor)+result
curr_num = (in_num * next_factor + curr_num)/10
if curr_num == 0:
break
print result
print long(result)*in_num
| true |
2f5398d3d4396f3408afae6d677d6c6712b081d7 | arojit/data-structure-python | /Stack-Using-LinkedList.py | 1,348 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
node = Node(data)
if self.head is None:
self.head = node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = node
def pop(self):
if self.head is None:
print("Empty Stack")
elif self.head.next is None:
self.head = None
else:
current = self.head
while current.next.next is not None:
current = current.next
# del current
current.next = None
def show(self):
current = self.head
if current is None:
print("Stack empty")
else:
while current is not None:
print(current.data)
current = current.next
if __name__ == '__main__':
stack = Stack()
stack.show()
print("----------")
stack.push(3)
stack.push(5)
stack.push(7)
stack.show()
print("----------")
stack.pop()
stack.pop()
stack.pop()
stack.show()
print("----------")
stack.push(100)
stack.show()
print("----------") | false |
0102a37760a2c8e93ebaf911b966cf533b9950b3 | tcandzq/LeetCode | /String/ReverseWordsInAStringIII.py | 1,070 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/11 21:26
# @Author : tc
# @File : ReverseWordsInAStringIII.py
"""
题号 557 反转字符串中的单词 III
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
简洁版参考:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/solution/python-1xing-by-knifezhu-2/
"""
class Solution:
# 冗余版代码
def reverseWords(self, s: str) -> str:
res = []
for s in s.split(' '):
res.append(s[::-1])
return ' '.join(res)
# 简洁版
def reverseWords2(self, s: str) -> str:
return ' '.join(s.split(' ')[::-1])[::-1]
if __name__ == '__main__':
s = "Let's take LeetCode contest"
solution = Solution()
print(solution.reverseWords(s)) | false |
de6dcfb731ddb2111c783c79a83fea0a6a20df73 | tcandzq/LeetCode | /ReservoirSampling/RandomPickIndex.py | 1,176 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @File : RandomPickIndex.py
# @Date : 2020-02-16
# @Author : tc
"""
题号 398 随机数索引
给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
示例:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
# 蓄水池抽样
"""
from typing import List
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
import random
res = None
count = 0
for i,v in enumerate(self.nums):
if v == target:
if random.randint(0,count) == 0:
res = i
count += 1
return res
if __name__ == '__main__':
solution = Solution([1,2,3,3,3])
print(solution.pick(3))
| false |
f042671104853739d07d6f2781dcfab3f5e7f8d1 | tcandzq/LeetCode | /Brainteaser/NimGame.py | 1,058 | 4.125 | 4 | """
题号 292 Nim游戏
你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
示例:
输入: 4
输出: false
解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
参考:https://leetcode-cn.com/problems/nim-game/solution/nimyou-xi-by-leetcode/
"""
class Solution:
# 丑陋版
def canWinNim(self, n: int) -> bool:
if n <= 3:
return True
elif n % 4 == 0:
return False
else:
return True
# 优雅版
def canWinNim2(self, n: int) -> bool:
return n % 4 != 0
if __name__ == '__main__':
n = 4
solution = Solution()
print(solution.canWinNim(n)) | false |
064f356555ec799d71ae05c23225427f65adbd6b | tcandzq/LeetCode | /Design/ImplementStackUsingQueues.py | 1,933 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @File : ImplementStackUsingQueues.py
# @Date : 2021-06-28
# @Author : tc
"""
题号 225. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
"""
import collections
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = collections.deque()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
n = len(self.queue)
self.queue.append(x)
for _ in range(n):
self.queue.append(self.queue.popleft())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.queue[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not self.queue | false |
2724cd2b38e03ed916316ac7ff32e483b0516fbd | Alfred-Lau/PythonPractices | /4-1.py | 518 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
# 如何拆分含有多种分隔符的字符串
# python 2.x 的解决办法
# def mySplit(text, ds):
# res = [text]
# for d in ds:
# t = []
# map(lambda x: t.extend(x.split(d)), res)
# res = t
# print('ds')
# return [x for x in res if x]
#
#
# s = 'ab;cd|efg|hi,kl|mn\topq;rst,uvw\txyz'
# print(mySplit(s, ';,|\t'))
#
#
# python3.x的实现方法
import re
s = 'ab;cd|efg|hi,kl|mn\topq;rst,uvw\txyz'
res = re.split(r'[;,|\t]+', s)
print(res)
| false |
79602418e46aafda87bd9ed0bd900dc23f7ad40e | csaund/project-euler | /3and5.py | 556 | 4.28125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def find_and_add(limit):
sum = 0
for i in range(0, limit):
by_three = i % 3 == 0
by_five = i % 5 == 0
both = by_three == 0 and by_five == 0
if by_three or by_five and not both:
sum += i
return sum
if __name__ == "__main__":
# test
# sum = find_and_add(10)
sum = find_and_add(1000)
print sum
| true |
f30e7ea8bd88827e96094d2307d0fb9db0704864 | NethajiNallathambi/PYTHON_Programming | /Beginner_Level/alphabet.py | 201 | 4.1875 | 4 | A = input("Enter any character: ");
if A == '0':
exit();
else:
if((A>='a' and A<='z') or (A>='A' and A<='Z')):
print(A, "is an alphabet.");
else:
print(A, "is not an alphabet.");
| true |
b1d84a0b2993b545ebeeb25989cd8a3ae1a3e465 | victoriamreese/python-scripts | /kata_split_and_add.py | 1,034 | 4.15625 | 4 | #Split then add both sides of an array together
#completed 1/30/19
#https://www.codewars.com/kata/split-and-then-add-both-sides-of-an-array-together/train/python
import numpy as np
def split_and_add(numbers, n):
while len(numbers)>1 and n>0:
top = np.asarray(numbers[0:int(len(numbers)/2)])
bottom = np.asarray(numbers[int(len(numbers)/2):int(len(numbers))])
if len(top) == len(bottom):
numbers = np.add(top,bottom)
else:
top = np.insert(top, 0, 0)
numbers = np.add(top, bottom)
n-=1
if type(numbers) == list:
return numbers
else:
return numbers.tolist()
split_and_add([1,2,3,4,6],1)
#better solution
def split_and_add(numbers, n):
for _ in range(n):
middle = len(numbers) // 2
left = numbers[:middle]
right = numbers[middle:]
numbers = [a + b for a, b in zip((len(right) - len(left)) * [0] + left, right)]
if len(numbers) == 1:
return numbers
return numbers
| true |
ca905c1edb62859fe90cb39cdf796b984830a9f5 | Demoleas715/PythonWorkspace | /Notes/Lists.py | 338 | 4.21875 | 4 | '''
Created on Oct 20, 2015
@author: Evan
'''
names=[]
names=input("Give me a list of names on one line")
name_list=names.split()
for n in name_list:
print(n)
'''
print("Enter a list of names. Leave blank when done.")
n=input()
while n!="":
names.append(n)
n=input()
names.reverse()
for n in names:
print(n)
''' | true |
8ef4a8725f579b70954af40048ecaa50106c6051 | lyubadimitrova/ffpopularity | /scripts/visualization.py | 1,625 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def draw(to_plot, title, xlabel, ylabel, plot_type, rotation=0):
"""
Uses matplotlib to draw a diagram.
Args:
to_plot - dict - A dictionary in the form {<xtick label> : <y_value>}
title - str - The title of the plot.
xlabel - str - The title of the x axis.
ylabel - str - The title of the y axis.
plot_type - str - Either 'bar' or 'line'. Default: 'line'.
"""
sorted_to_plot = sorted(to_plot.items())
plt.figure(figsize=(10,5))
labels_vals = list(zip(*sorted_to_plot))
if plot_type == 'bar':
plt.bar(range(len(to_plot)), labels_vals[1])
else:
plt.plot(range(len(to_plot)), labels_vals[1])
plt.xticks(range(len(to_plot)), labels_vals[0], rotation=rotation)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
def draw_scatter_regline(x, y, title, xlabel, ylabel):
"""
Uses matplotlib to draw a scatter plot and the corresponding regression line.
Args:
x - np.array/pandas.Series - The first variable, plotted on the x axis.
y - np.array/pandas.Series - The second variable, plotted on the y axis.
to_plot - dict - A dictionary in the form {<xtick label> : <y_value>}
title - str - The title of the plot.
xlabel - str - The title of the x axis.
ylabel - str - The title of the y axis.
"""
print('Correlation coeffictient: ', np.corrcoef(x, y)[0][1])
plt.figure(figsize=(15,5))
plt.scatter(x, y)
a, b = np.polyfit(np.array(x), np.array(y), deg=1)
f = lambda point: a*point + b
line_x = np.array([min(x),max(x)])
plt.plot(line_x, f(x), c="orange")
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.show()
| true |
06b1dca2316277e19ade91653a391d8021633e96 | Aastha-520609/python_learning | /dictionarie.py | 576 | 4.25 | 4 | dict={}#creating a dictionary
dict['apple']= 150#assigning key to the dict and the value
dict['banana']=60
dict
print(dict)
#another way to create a dictionary
mail_adress={'aastha':'aastha@gmail.com','pasta':'pasta@gmail.com'}
print(mail_adress)
print(mail_adress.keys())#to print keys of dictionary
print(mail_adress.values())#to print values of dictionary
#creating dict with the help of list
a=[1,2,3,4]
b=['cat','dog','mouse','rat']
my_dict={}#empty dict
for i in range(len(a)):#here we can use any ones lenght because length is equal
my_dict[a[i]]=b[i]
print(my_dict)
| true |
2a38eeba2f76eccef675bc84603af4b178a6c0cb | aquman/mypy | /calculater.py | 910 | 4.21875 | 4 |
user_input = input('what you want to do:')
if user_input == 'quit':
print('calculator is closed')
elif user_input == 'add':
num1 = eval(input('enter a number:'))
num2 = eval(input('enter a number:'))
result =str(num1 + num2)
print('the answer is' ' ' + result)
elif user_input == 'subtract':
num1 = eval(input('enter a number:'))
num2 = eval(input('enter a number:'))
result = str(num1 - num2)
print('the answer is' ' ' + result)
elif user_input == 'multiply':
num1 = eval(input('enter a number:'))
num2 = eval(input('enter a number:'))
result = str(num1 * num2)
print('the answer is' ' ' + result)
elif user_input == 'divide':
num1 = eval(input('enter a number:'))
num2 = eval(input('enter a number:'))
result = str(num1 / num2)
print('the answer is' ' ' + result)
else:
print('unkown input')
| false |
e7035898fb2188f62776250ec069e67b9bfd1ea0 | michael-yanov/hillel | /lesson_12/task_2.py | 694 | 4.21875 | 4 | '''
Имеется строка вида: AABABBAABBBAB. Необходимо написать функцию которая заменит буквы A на Bб а B, соответственно, на A.
В результате применения функции к исходной строке, функция должна вернуть строку: BBABAABBAAABA
'''
def change_letters(string):
print('Origin is: ', string)
string_new = []
for i in range(len(string)):
if string[i] == 'A':
string_new.append('B')
else:
string_new.append('A')
return ''.join(string_new)
print('Modifaed is: ', change_letters('AABABBAABBBAB'))
| false |
1f08427b2c69fc702f6cdcbf78693ee3cd1c98ef | akoschnitzki/Module-6--Lab- | /Lab 6- Problem 6.py | 411 | 4.46875 | 4 | # Name- Alexander Koschnitzki
# Date- 11-4-21
# CSS - 225
# Number 6
# What this program does is that it calculates the factorial of a number
# when you input it. You can input any number and it can be able to
# find the factorial of it.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n)) | true |
9754b5adb22c5afb1401e887d65fae1d37d683b0 | ViktorKovinin/ds_python | /1.syntax/1.variables.py | 1,288 | 4.15625 | 4 | #print("hello world!")
# a = input("Введите число A: ")
# b = input("Введите число B: ")
# c = int(a) + int(b)
# print("Результат: ", c)
# int_num = 777 # целочисленный тип данных
# float_num - =3.14 # тип данных "числа с плавающей точкой"
# string = "Привет мир" # строковой тип данных
# boolean = True # False
# print(float_num)
# способ форматирования строк f-string
# name = "Viktor"
# age = 37
# s = f"Name: {name} Age: {age}"
# print(s)
# Арифметические операции
a = 100
b = 99
res_1 = a + b
res_2 = a * b
res_3 = a // b # a/b
res_4 = a % b # деление по модулю
res_5 = a ** b # a в степени b
print(res_5)
# Логические операции
x = 5
y = 3
res_6 = x != y # не равно !=
res_7 = x == y # равно ==
res_8 = x < y
res_9 = x > y
res_10 = x >= y
res_11 = x <= y
z = True
k = False
res_13 = z and k # логический оператор И
res_14 = z or k # логический оператор ИЛИ
print(res_14)
res_12 = not z # это логический оператор НЕ (инвертирующий оператор)
| false |
7dfe5989d5a473f38c03d43e76e9f169aa664eae | zypdominate/keepcoding | /books/book4 图解算法/code/demo2_select_sort.py | 622 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Description:选择排序
# Author:zhuyuping
# datetime:2020/8/11 22:31
import random
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def select_sort(arr):
res = []
for i in range(len(arr)):
smallest = find_smallest(arr)
res.append(arr.pop(smallest))
return res
if __name__ == '__main__':
arr = [random.randint(1, 100) for i in range(10)]
print(select_sort(arr))
| true |
499d1040d18da84ebb1fd28c492fbf3d17d86ad7 | AbhishekR25/cerner_2_5_2021 | /BreakTheName.py | 498 | 4.5 | 4 | #cerner_2tothe5th_2021
# Get all substrings of a given string using slicing of string
# initialize the string
input_string = "floccinaucinihilipilification"
# print the input string
print("The input string is : " + str(input_string))
# Get all substrings of the string
result = [input_string[i: j] for i in range(len(input_string))
for j in range(i + 1, len(input_string) + 1)]
# print the result
print("All substrings of the input string are : " + str(result))
| true |
f11be425bec8f1c9587b049d841663cb1b89cee7 | peterlewicki/pythonCrashCourseExercises | /strippingNames.py | 352 | 4.25 | 4 | # Use a variable to represent a person's name, and include some whitespace characters at the beginning and the end of the name. Print the name once, so the whitespace around the name is displayed. Then print the name using stripping functions
name = " Harold Ramis"
print(name)
print(name.lstrip())
name1 = "Bill Murray "
print(name1)
print(name1.rstrip()) | true |
27d2948a224fc4ffaf912fd0d84b6c4f8f2ba324 | zaghard/Aulas-Python | /projetosPython/aula05.py | 1,686 | 4.28125 | 4 | #Digitall Innovation One Aulas
#Lista e Tuplas
lista = [34, 12, 1 ,3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante', 'macaco', 'leão', 'tigre', 'boi', 'vaca']
tupla = (1, 10, 12, 14)
# len() é um contador que informa quantos elementos tem na lista ou tupla.
#tuple() faz a conversão de lista para tupla.
#list() converte as tuplas em lista númerica
print(tupla)
print(tupla[0])
print(len(tupla))
tupla_animal =tuple(lista_animal)
print(type(tupla_animal))
print(tupla_animal)
#<-------------------------------------------------------------------->
# nova_lista = lista_animal * 3
# lista_animal.sort() # sort() para ordenar a lista
# lista.sort()
#
# print(lista)
# print(lista_animal)
# lista_animal.reverse()
# print(lista_animal)
#<-------------------------------------------------------------------->
#lista_animal.pop(1) para remover um iten da lista
#lista animal.remove('elefante')
#<-------------------------------------------------------------------->
# print(lista_animal[1])
# print(nova_lista)
#
# soma = 0
# for x in lista:
# print(x)
# soma += x
# print(soma)
#
# print(sum(lista))
# print(max(lista))
#<-------------------------------------------------------------------->
# animal = str(input('Digite o nome de um tipo de animal: '))
#
# if animal in lista_animal:
# print('Existe um(a) "{}" na lista'.format(animal))
# else:
# print('Não existe um(a) "{}" na lista'.format(animal))
# print('O animal "{}" foi adcionado a lista'.format(animal))
# lista_animal.append(animal)
# print(lista_animal)
# print('<-----Fim do Programa!!!----->')
#<-------------------------------------------------------------------->
| false |
dcd6041ab962c2a0303e27f1433658a36356d44a | rlazcanoc/FindPair | /find_pair.py | 1,688 | 4.5 | 4 | # MedicoSoft 2020
# 1. Encuentra el par con la suma dada en el arreglo
# Lee el README.md antes de comenzar
# def find_pair(array, sum) -> [1,2]:
"""Arguents:
array -- unsorter array of integers
sum -- sum of pair of integers to find
Retorna:
array -- array of two elements with the integers of sum to find
"""
# Input
array = [1,5,6,7,3,5]
sum = 10
# Output
#[7,3] or [5,5]
def findPair(newArray,sum):
#clonamos nuestra lista para no afectar a la lista original
array = newArray[:]
for item in newArray:
#restamos el elemento actual al parametro suma
res = sum - item
#Ahora buscamos si el resultado de la resta existe en la lista
if res in array:
#Si existe entonces cremos una lista nueva
LIST = []
#obtenemos el indice que le corresponde al valor de la resta
position = array.index(res)
#agregamos a la lista nueva el item y su compelmento para formar la suma
LIST.append(item)
LIST.append(array[position])
#print(item,array[position])
#imprimimos la nueva lista
print(LIST)
#eliminamos el item y su complemento para no duplicar busquedas
array.pop(array.index(item))
array.pop(position)
findPair(array,sum)
"""
Big O notation
este algortimo cuenta con una O(n) (complejidad Lineal) ya que su nivel de complejidad se basa en dar
una recorrido completo solo una ves a lista que se le proporciona, y realizando las mismas operaciones solo una ves durante cada iteracion
"""
| false |
cc80f0669f274ebdd2e6e860d9f6f6b2e9fcf28f | VaishnaviMuley19/Coursera-Courses | /Google IT Automation with Python/Crash Course on Python/Assignment_7/Prog_1.py | 1,101 | 4.5625 | 5 | #The is_palindrome function checks if a string is a palindrome.
#A palindrome is a string that can be equally read from left to right or right to left,
#omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar,
#and phrases like "Never Odd or Even". Fill in the blanks in this function
#to return True if the passed string is a palindrome, False if not.
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = ""
reverse_string = ""
# Traverse through each letter of the input string
for letter in input_string:
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
#if ___:
new_string = new_string+letter.replace(" ","")
reverse_string = letter.replace(" ","")+reverse_string
# Compare the strings
if new_string.upper() == reverse_string.upper():
return True
return False
print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
| true |
baf951773998b1d9c20f478aa1567d1f8c58f2a2 | VaishnaviMuley19/Coursera-Courses | /Python 3 Programming/Python Basics/Week_1_Assignment.py | 862 | 4.3125 | 4 | # First Question
""" 1. There is a function we are providing in for you in this problem called square. It takes one integer and returns the square of
that integer value. Write code to assign a variable called xyz the value 5*5 (five squared). Use the square function, rather than
just multiplying with *. """
xyz = square(5)
# Second Question
""" 2. Write code to assign the number of characters in the string rv to a variable num_chars. """
rv = """Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore,
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
'Tis some visitor, I muttered, tapping at my chamber door;
Only this and nothing more."""
num_chars = len(rv)
| true |
84d3d9bc61bf679c555df9f7f8b929ea44babdcd | VaishnaviMuley19/Coursera-Courses | /Google IT Automation with Python/Crash Course on Python/Assignment_6/Prog_5.py | 244 | 4.375 | 4 | #The show_letters function should print out each letter of a word on a separate line.
#Fill in the blanks to make that happen.
def show_letters(word):
for x in word:
print(x)
show_letters("Hello")
# Should print one line per letter
| true |
56f7f14e82b4328d78962b9a817011edf9e2b909 | VaishnaviMuley19/Coursera-Courses | /Python 3 Programming/Python Basics/Week_2_Assignment_1.py | 774 | 4.375 | 4 | # First Question
""" 1. Write a program that extracts the last three items in the list sports and assigns it to the variable last. Make sure to write your
code so that it works no matter how many items are in the list. """
sports = ['cricket', 'football', 'volleyball', 'baseball',
'softball', 'track and field', 'curling', 'ping pong', 'hockey']
leng = len(sports)
last = sports[-3:]
print(last)
# Second Question
""" 2. Write code that combines the following variables so that the sentence “You are doing a great job, keep it up!” is assigned to the variable message.
Do not edit the values assigned to by, az, io, or qy. """
by = "You are"
az = "doing a great "
io = "job"
qy = "keep it up!"
message = by+" "+az+""+io+", "+qy
| true |
381f9e986365452846d254727ddb211ca248c657 | otaviohenrique1/python-projetos | /Calculadora 2.py | 1,518 | 4.1875 | 4 | import math
print("Calculadora 1")
print ("Adição - 1")
print ("Subtração - 2")
print ("Multiplicação - 3")
print ("Divisão- 4")
print ("Potenciação - 5")
print ("Radiciação - 6")
i = int(input("Escolha operação matematica"))
# Adição
if i == 1:
def adicao(x,y):
k = 0
k = x + y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , adicao(a,b))
# Subtração
elif i == 2:
def subtracao(x,y):
k = 0
k = x - y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , subtracao(a,b))
# Multiplicação
elif i == 3:
def multiplicacao(x,y):
k = 0
k = x * y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , multiplicacao(a,b))
# Divisão
elif i == 4:
def divisao(x,y):
k = 0
k = x / y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , divisao(a,b))
# Potencia
elif i == 5:
def potenciacao(x,y):
k = 0
k = x ** y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , potenciacao(a,b))
# Radiciação
elif i == 6:
def radiciacao(x,y):
k = 0
k = x ** 1/y
return k
a = int(input("Numero"))
b = int(input("Numero"))
print("Resultado: " , radiciacao(a,b))
| false |
162bc28a9b6461ad4675488bb8fa2b525fcac456 | rbo7nik/movie_trailer_website | /main.py | 2,849 | 4.21875 | 4 | from movie import Movie
from fresh_tomatoes import open_movies_page
# Application class that runs the program until the user quits
class MainApp():
# Method that gets user input one line at a time
# Returns the user_input as a string
def user_input():
usr_input = raw_input()
if usr_input == "":
print "Exiting program.."
exit(1)
return (usr_input)
# Method to initialize each movie object based on the Movie class
# returns the movie object
def initialize_movie(m):
movie = Movie(m[0], m[1], m[2])
return movie
# A list of possible prompts to cycle through in a loop
prompts = ['Please enter a movie title:',
'Please enter the url for movie poster for your movie',
'Please enter the url for a movie trailer for your movie']
# An empty array/list that will hold movie objects
movie_list = list()
# The main prompt for when the program starts
print "Please enter Movie information into the prompt."
print "(to exit the program, enter a blank line)"
# The program will run until the user enters a blank ""
while True:
# An array/list that gets re-initialized on every iteration
# of the while loop, stores each Movies (title,poster,trailer)
movie_raw = list()
# Cycling through each prompt to gather data for a movie object
for p in prompts:
print p
usr_input = user_input()
movie_raw.append(usr_input)
# Initializing movie object with the raw user data
# movie_raw array will always have 3 of some kind of values
movie = initialize_movie(movie_raw)
# Adding the movie object to a list of movies
movie_list.append(movie)
# Poll user to find out if they want to add more movies,
# or generate a webpage from the existing content.
print "Generate webpage from the content entered? Y/n"
print "(to exit the program, enter a blank line)"
usr_input = user_input()
# If the user enters y or Y for yes, a movie page will be generated
if usr_input.lower() == 'y':
print "Opening movie webpage.. "
open_movies_page(movie_list)
print "Exiting program.."
exit(1)
# If the user enters n or N, the program will continue to
# run until the user enters yes or quits
elif usr_input.lower() == 'n':
continue
# If the user enters an unknown choice the program will
# quit, letting the user known why
else:
print 'Choice does not match available options! "'+usr_input+'"'
print "Please start over!"
print "Exiting program.."
exit(1)
# Will run the
if __name__ == 'main':
MainApp().run()
| true |
caa4878683a850540fbcfe34db77e26a500475f1 | dbulgakov/inf_jet | /SimpleTasks/S5.py | 345 | 4.3125 | 4 | # Программа, выполняющая поиск подстроки в строке.
def main():
string_to_check = input('Enter string to check: ')
substring_to_find = input('Enter substring to find: ')
print('Input string contains substring: ', substring_to_find in string_to_check)
if __name__ == "__main__":
main()
| false |
397fd3bc37a5c7f8c9baec4c0ee91491a4502680 | MingHin-Cheung/python_review | /list.py | 758 | 4.25 | 4 | food = ["pizza", "sushi", "burger"]
nums = [1, 2, 3, 10, 20]
print(food) # print list
print(food[1]) # pizza
print(food[-1]) # burger
print(food[1:]) # start at position 1
print(food[1:2]) # start at position 1,up to 2 but not include
food[1] = "pasta"
print(food)
food.extend(nums) # combine 2 lists
print(food)
food.append("bacon")
print(food)
food.insert(1, "rice")
print(food)
food.remove(10)
print(food)
food.pop()
print(food) # remove the last element of the list
print(food.index("rice")) # check rice position
print(food.count("rice")) # check rice counts
food = ["pizza", "sushi", "burger"]
food.sort() # sort list
print(food)
nums.reverse()
print(nums)
num2 = nums.copy() #copy the list
food.clear() #delete everything in the list | true |
c90d14599963d087b7503a82e1c4b1cdaeba1c56 | CindyMacharia/Lab01 | /Project03RockPaperScissors.py | 2,359 | 4.28125 | 4 | import random
comp_points = 0
player_points = 0
def choose_option():
user_choice = input("Rock, Paper or Scissors: ")
if user_choice in ["Rock","rock"]:
user_choice = "Rock"
elif user_choice in ["Paper","paper"]:
user_choice = "Paper"
elif user_choice in ["Scissors", "scissors"]:
user_choice = "Scissors"
else:
print("Invalid choice, try again.")
choose_option()
return user_choice
def computer_option():
comp_guess = random.randint(0,2)
if comp_guess == 0:
comp_guess = "Rock"
elif comp_guess == 1:
comp_guess == "Paper"
else:
comp_guess == "Scissors"
return comp_guess
while True:
print("")
user_choice = choose_option()
comp_guess = computer_option()
print("")
if user_choice == "Rock":
if comp_guess == "Rock":
print("We have a tie!")
elif comp_guess == "Paper":
print("User chose Rock. Computer chose Paper. You lose!")
comp_points += 1
elif comp_guess == "Scissors":
print("User chose Rock. Computer chose Scissors. You win!")
player_points += 1
elif user_choice == "Paper":
if comp_guess == "Rock":
print("User chose paper. Computer chose Rock. You win")
player_points += 1
elif comp_guess == "Paper":
print("We have a tie!")
elif comp_guess == "Scissors":
print("User chose paper. Computer chose scissors.You lose!")
comp_points += 1
elif user_choice == "Scissors":
if comp_guess == "Rock":
print("User chose Scissors. Computer chose Rock. You lose!")
comp_points += 1
elif comp_guess == "Paper":
print("User chose Scissors. Computer chose Paper. you win!")
player_points += 1
elif comp_guess == "Scissors":
print("We have a tie!")
print("")
print("Player points: " + str(player_points))
print("Computer points: " + str(comp_points))
print("")
user_choice = input ("Do you want to play again? (y/n)")
if user_choice in ["y"]:
pass
elif user_choice in ["n"]:
break
else:
break
| true |
8ed095e93890ebbe6e3aba1e84284f3c0c61f534 | vduan/project-euler | /problem2.py | 1,127 | 4.125 | 4 | """
Problem Statement:
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""
import sys
def find_fibonacci(limit):
fib = [1, 2]
tail_index = 1
while fib[tail_index] <= limit:
tail_index += 1
fib.append(fib[tail_index - 1] + fib[tail_index - 2])
fib.pop()
return fib
def sum_evens(nums):
evens = [x for x in nums if x % 2 == 0]
return sum(evens)
def main():
args = sys.argv
if len(args) != 2:
print_usage()
return -1
try:
limit = int(args[1])
except:
print_usage
return -1
if limit < 2:
print 'limit must be greater than 2'
return -1
fibonacci = find_fibonacci(limit)
even_sum = sum_evens(fibonacci)
print 'The sum of fibonacci numbers not exceeding ' + str(limit) + ' is ' + str(even_sum)
def print_usage():
print 'Usage: python __file__ limit'
if __name__ == "__main__":
main()
| true |
13083bb815c5383af26d5366bdf33532162dcd9d | Htunn/code_practise | /python3/converter.py | 389 | 4.125 | 4 | '''
Input the temperature in degree Celsius( call celsius )
convert the fahrenheit as (9/5)celsius + 32
output fahrenheit
'''
# convert.py
# A program to convert celsius to fahrenheit
# by htunnthuthuu
def main():
celsius = eval(input("What is the Celsius Temperature? "))
fahrenheit = 9//5 * celsius + 32
print("The temperature is", fahrenheit, "degree Fahrenheit.")
main() | false |
a18557a658e1de0edc612f57d66ada58cc15c02e | RaySCS/Classical-Problems | /armstrongNumber.py | 523 | 4.125 | 4 | #An armstrong number, also known as a narcissistic number is the sum of cubes of each digit is equal to the number itself.
import math
def isArmstrong(number):
sum = 0
len_Num = len(str(number))
for digit in str(number):
num = int(digit)
sum += math.pow(num,len_Num)
if(math.trunc(sum) == number):
print(number, "is an armstrong number.")
else:
print(number, "is not an armstrong number.")
isArmstrong(153)#Valid, yes armstrong
isArmstrong(500)#Invalid, not armstrong | true |
27155bff9d1714fe6e4a7dc41c6efa899330e669 | imanshaterian/guess-game | /game.py | 1,177 | 4.125 | 4 | import random
# get a name for game
playerName = input('please enter your name:\n')
# saying hi to player
print('hi {} you have 100 chance to guess the number i choose between 1 and 100 :)\n'.format(playerName))
# the program chooses a number between 1 and 100
finalNumber = random.randrange(1, 101)
# get a number from player
guessedNumber = int(input('please enter your guess:\n'))
# a for loop to analyze the entered number
# with four steps
for i in range(0, 100):
# step one : if player guess the right number
if guessedNumber == finalNumber:
print('nice you guessed it . well played;)\n')
break
# step two : if the player guess a larger number than the answer
elif guessedNumber > finalNumber:
guessedNumber = int(input('please guess lower:\n'))
continue
# step three : if the player guess the smaller number than the answer
elif guessedNumber < finalNumber:
guessedNumber = int(input('please guess higher:\n'))
continue
# step four : if the player type a incorrect character
else:
guessedNumber = int(input('unknown character please type only integer numbers:\n'))
continue
| true |
e4d9720571c126b74b2d83a5db0e926324b7d2ab | Gasangit/primeros-pasos-python | /list.py | 2,931 | 4.46875 | 4 | demo_list=[1, "Hello", 1.34, True,[1, 2, 3] ]
colors=["red", "green", "blue"]
#numbers_list=list(1, 2, 3, 4)
# print(numbers_list)
#en el último caso la lista se escribió como un STRING. Para poder visualizarla en el interprete hay que escribirla como una TUPLA
# (revisar este termino, no entiendo la diferencia con lista) agregando un par mas de parentesis.
numbers_list=list((1, 2, 3, 4))
print(numbers_list)
r=list(range(1, 10))
print(r)
#la funcion range completa el rango entre dos números para poder crear listas instantaneas con gran cantidad de numeros
print(dir(colors))
#recordar que la funcion DIR permite ver las opciones de todo lo que se puede hacer(en este caso con una LISTA)
print(colors[1])
#con el número entre corchetes traigo el elemento de la LISTA COLORS que ocupa esa posición
print("green" in colors)
#con IN se puede comprobar si un elemento existe en una LISTA determinada devolviendo TRUE o FALSE
print(colors)
print(demo_list)
colors[1]="yellow"
print(colors)
#en la linea 27 se realizó una operación que permite cambiar uno de los componentes de la LISTA por el que figura luego del signo =
colors.append("violet")
print(colors)
#con la función APPEND agreganos un nuevo dato a la lista. Como en el caso anterior, primero se introduce la modificación y luego si se
#desea se hace ejecutar en pantalla mediante PRINT
colors.extend(["brown", "pink"])
print(colors)
#para agragar más de un elemento a la vez se debe usar la función EXTED, escribiendo los elemento en una LIST o TUPLE. De lo contrario
# funciona como APPEND
colors.insert(1, "black")
print(colors)
#con la función INSERT se puede ingresar un nuevo elemento a la LISTA en al posición deseada que esta dada por el número
colors.insert(len(colors), "white")
print(colors)
#combinando INSERT con LEN (funcion que cuenta los elemtos de la LISTA) puedo insertar un nuevo elemento al final de la lista
colors.pop()
print(colors)
#la funcion POP quita el último elemento de la LISTA. Si continuo ultilizandolo quitara uno a uno los elementos.
colors.remove("blue")
print(colors)
#para quitar un elemento puntual en base a su nombre se usa la funcion REMOVE
colors.pop(0)
print(colors)
#con la funcion POP también puedo quitar un ELEMENTO por su número de INDICE
colors.clear()
print(colors)
#CLEAR limpia completamente la LISTA
colors.extend(["blue","red","white","green","black","brown"])
print(colors)
colors.sort()
print(colors)
#SORT ordena alfabeticamente los elementos de la LISTA
colors.sort(reverse=True)
print(colors)
#utlizando REVERSE=TRUE junto con SORT ordenamos desde atras hacia adelante alfabeticamente
print(colors.index("black"))
#a traves de INDEX también se puede saber la posición de un elemento dentro de una LISTA (antes se había hecho en un STRING)
print(colors.count("white"))
#mediante la funcion COUNT se puede saber cuantas veces se repite un ELEMENTO de la LISTA
| false |
ade83772fcbb26d792bf4d17722fa905f96e87a0 | nagamiya/NLP100 | /Python/Chapter1/08_Cipher_Text.py | 598 | 4.125 | 4 | '''
Implement a function cipher that converts a given string with the specification:
Every alphabetical letter c is converted to a letter whose ASCII code is (219 - [the ASCII code of c])
Keep other letters unchanged
Use this function to cipher and decipher an English message.
'''
def clipher(text):
clipher_text = []
for t in text:
if str.islower(t):
clipher_text.append(chr(219 - ord(t)))
else:
clipher_text.append(t)
return "".join(clipher)
text = list(input())
encode = clipher(text)
print(encode)
decode = clipher(encode)
print(decode)
| true |
2b96baf9f2294a63f9f6b5af8a9f74311508a0dd | judDickey1/Codewars | /getMiddlechar.py | 489 | 4.1875 | 4 | def get_middle(s):
char = list(s)
indToPrint = int(len(char) / 2)
if len(char) % 2 == 0 :
return(char[indToPrint-1] + char[indToPrint])
else:
return(char[indToPrint])
"""
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
top Codewars solution
return s[(len(s)-1/2:len(s)/2+1
""" | true |
b440f90bc093f57c201b8fcfe81d41e67470229f | thebeanogamer/Classwork | /Python/Flight Check.py | 476 | 4.1875 | 4 | while True:
distance = int(input("How far is your journey in km?"))
if 40075 >= distance >= 500 :
canFly = input("Can you/do you want to fly?")
if canFly == "Yes" or canFly == "yes":
print ("Take a plane!")
else:
print ("Get on a boat or a coach!")
elif distance >= 40075:
print ("Hop on a space shuttle!")
else:
ownCar = input("Do you own a car?")
if ownCar == "yes" or ownCar == "Yes":
print ("Drive your car!")
else:
print ("Take the train")
| true |
0423c2f5ed7a6a7bda0da8e1699596b8b66db869 | KTyanScavenger/KTSPortfolio | /triviatest (1).py | 2,566 | 4.15625 | 4 | #Kyla Ryan
#1/19
#Trivia Challenge
#Trivia Game that reads a plain text file
import sys
##NAME THE FILE NAME
##ASSIGN MODE (PERMISSIONS TO THE FILE)
def open_file(file_name,mode):
"""OPEN A FILE"""
try:
the_file=open(file_name,mode)
except IOError as e:
print("Unable to open file",
file_name,"Ending the program.\n",e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""RETURN NEXT LINE FROM THE TRIVIA FILE, FORMATTED"""
line=the_file.readline()
line=line.replace("/","\n")
return line
##just a test
##file_name="test.txt"
##the_file=open_file(file_name,"r")
##line=next_line(the_file)
##print(line)
def next_block(the_file):
""" this moves to the next text block"""
category=next_line(the_file)
question=next_line(the_file)
answer=[]
for i in range(4):
answer.append(next_line(the_file))
correct=next_line(the_file)
if correct:
correct=correct[0]
explanation=next_line(the_file)
return category, question, answer, correct, explanation
def welcome(title):
""""welcome the player to their game"""
print("\t\tWelcome to Trivia Game!\n")
print("\t\t",title,"\n")
##just a test
##the_file=open_file("test.txt","r")
##title=next_line(the_file)
##category, question, answers, explanation=next_block(the_file)
##print(category)
##print(question)
##print(answers)
##print(explanation)
##print(title)
def main():
file_name="test.txt"
mode="r"
the_file=open_file(file_name,mode)
open_file(file_name, mode)
title=next_line(the_file)
welcome(title)
score=0
category, question, answer, correct, explanation=next_block(the_file)
while category:
print(category)
print(question)
for i in range(4):
print(i+1,":",answer[i])
user_answer=input("What is the correct answer?")
if user_answer in correct:
print("Congratulations! You chose the correct answer! ",end=" ")
score+=1
else:
print("Sorry that answer was incorrect.\n")
print(explanation)
print(score)
category, question, answer, correct, explanation=next_block(the_file)
the_file.close()
print("The game has been completed. Well done.")
print("Your final score was: ",score)
print("Press enter key to close.")
sys.exit()
main()
| true |
2afa1d26f765fb2f12e3a92ad964adfd61c44e6b | zoiaivanova/elementarytasks | /chessboard/fn_chessboard/fn_chessboard.py | 906 | 4.15625 | 4 | from errors import InvalidSideError
def validate_side(side: str) -> str:
"""
invalid -1, 0, adbc, ' '
valid 1, 5, 20
:param side: user input string for validation
:return: raise ValueError if side isn't a natural positive number otherwise return side in str format
"""
if not (side.isdigit() and int(side) >= 1):
raise InvalidSideError(f'\nYour value {side} is invalid, a side should a natural positive number')
return side
def building_board(height: str, width: str) -> str:
"""
:param height: height for building a chessboard
:param width: width for building a chessboard
:return: string representing the chessboard with given height and width
"""
result = ''
for row in range(int(height)):
for cell in range(int(width)):
result += '*' if row % 2 == cell % 2 else ' '
result += '\n'
return result
| true |
06b8092bde81d83faaacf205c8e8a3c8ec973bf0 | IvanicsSz/ivanics | /calc.py | 706 | 4.125 | 4 | #!/usr/bin/env python
import sys,io
start = "\033[1m"
end = "\033[0;0m"
def calc(num1,num2,op): #calculations
if (op=="+"):
return num1+num2
elif(op=="-"):
return num1-num2
elif (op=="*"):
return num1*num2
elif (op=="/"):
return num1/num2
else:
return "Not supported operator only: +,-,*,/"
while True: #repating
number1=input("Enter a number (or a letter to "+start+"exit"+end+"):")
try:
nbr1=float(number1)
except ValueError:
exit()
operator=input("Enter an operator:")
number2=input("Enter another number:")
nbr2=float(number2)
print("Result:"+str(calc(nbr1,nbr2,operator))) #result
| true |
cb500e781798fb1cdfd0c5c6ac66976da202d0bc | TayExp/pythonDemo | /05DataStructure/01thread.py | 1,238 | 4.125 | 4 | # 并发:指的是任务数多余cpu核数,通过操作系统的各种任务调度算法,实现用多个任务“一起”执行(实际上总有一些任务不在执行,因为切换任务的速度相当快,看上去一起执行而已)
# 并行:指的是任务数小于等于cpu核数,即任务真的是一起执行的
import time
import threading
# threading模块能完成多任务的程序开发
def task1():
for i in range(3):
print("run task1...")
time.sleep(1)
def task2():
for i in range(3):
print("run task2...")
time.sleep(1)
def task3():
for i in range(3):
print("run task3...|")
time.sleep(1)
if __name__ == '__main__':
print("start--%s" %time.ctime())
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t3 = threading.Thread(target=task3)
t1.start()
t2.start()
t3.start()
# 查看线程数量
while True:
length = len(threading.enumerate())
print("the number of threadings is %d" %length)
if length<=1:
break
time.sleep(0.5)
# 主线程会等待所有的子线程结束后才结束
time.sleep(5)
print("over--%s" % time.ctime())
| false |
2669454eac140274f36a7ca3c9b12ef018aa4ac2 | AlexandrovSergei/2019-fall-polytech-cs | /1.2.2.The_Internetional.py | 967 | 4.125 | 4 | def main():
print('Количество команд: ', end='')
n_str = input()
n = int(n_str) if n_str else 0
while 1:
print('Напишите 1, чтобы узнать, сколько есть вариантов распределить первые три места. Напишите 2, чтобы узнать, сколько вариантов есть распределить все места : ')
x = input()
if x == '1':
f3(n)
return
if x == '2':
all(n)
return
if x != '1' and x != '2':
print('Ошибка ввода, выберите пожалуйста "1" или "2"')
def f3(n):
n = factorial(n) / factorial(n - 3)
print(str(n))
def all(n):
n = factorial(n)
print(str(n))
def factorial(n):
fac = 1
while n > 1:
fac *= n
n -= 1
return int(fac)
main() | false |
40bc31bea557c39567ea77a964d2ac314df8d7b2 | NicolasKujo/Lista-3-TPA | /Ex 10.py | 230 | 4.1875 | 4 | print ("olá eu sou um programa que desenha triangulos")
print()
a = int(input("insira o tamanho do triangulo:"))
print()
print()
b = 0
while b < a:
b = b + 1
print(" #" * b )
print()
print("fim do programa") | false |
3f92a6656495dcd1c95cc56949fd6b1856223b6b | Dia-cpu/Prework | /TKH_Prework/assignment_3.py | 217 | 4.125 | 4 | names_list = ["Sam","Rebecca","Sally","Cardi B","Michelle","Khadjat"]
longest_name = ""
for name in names_list :
if len(name) > len(longest_name) :
longest_name = name
print(longest_name) | false |
850227aab194e38c3f01803bfec31e56e96f3129 | wisdom2018/pythonLearn | /IteratorVSIterable.py | 1,571 | 4.25 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/23 8:34 AM
# @Author: zhangzhihui.wisdom
# @File:IteratorVSIterable.py
from collections import Iterable, Iterator
# Collection data type: list、tuple、dict、set、str
# can use isinstance() to judge a object whether is iterable
# Iterator not only can use for loop,but also can call by next() method,
# until return StopIteration error which indicates can not return next value
if __name__ == '__main__':
isinstance({}, Iterable)
isinstance('abc', Iterable)
print(isinstance({}, Iterable))
print(isinstance('abc', Iterable))
print(isinstance('abc', Iterator))
# also can change a iterable object to iterator object by iter() method
isinstance(iter('abc'), Iterator)
print(isinstance(iter('abc'), Iterator))
# the difference of iterator and iterable in python
# in python, Iterator object represents a data stream, iterator object can be called by next()
# method and return next value gradually, util has no next value and return StopIteration error.
# we can think that this data stream is a sorted sequence, while we can not know the length of data beforehand.
# only be next() compute next value, So the computation of Iterator is lazy computation.
# Only calculate next value when needed
# Iterator even can represents a infinite data stream, while list can not.
it = iter([1, 2, 3, 4, 5])
while True:
try:
x = next(it)
print(x, "this is %d" % x)
except StopIteration:
break
| true |
a277f82a839763513ebc15b31fb646d0f041f770 | wisdom2018/pythonLearn | /venv/findMaxAndMin.py | 692 | 4.1875 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/19 12:21 PM
# @Author: zhangzhihui.wisdom
# @File:findMaxAndMin.py
# using iterable implement to find max value and min value of list, and return type is tuple
def findMax(number):
if not number:
return [None, None]
else:
min_value = number[0]
max_value = number[0]
for i in number:
if i < min_value:
min_value = i
elif i > max_value:
max_value = i
return [min_value, max_value]
if __name__ == '__main__':
listOne = [2, 3, 6, 9, 1, 4]
print(listOne[:1], listOne[-1:])
findMax(listOne)
print(findMax(listOne))
| true |
b6a0f20b24ec91b1cbdf811ffbb68ca12145a5fc | diogoamvieira/DSBA-Data-Mining-Ex | /Ex1.py | 381 | 4.28125 | 4 | '''gives the volume of the cylinder and the surface area of that cylinder'''
import numpy as np
pi = np.pi
r = int(input('Choose a Radius for a Cylinder: '))
h = int(input('Choose a Height for a Cylinder: '))
totalvolume = pi * r ** 2 * h
surface = 2 * pi * r * 2 + 2 * pi * r * h
print('The cylinder has a volume of: ', totalvolume)
print('... and the surface is: ', surface) | true |
6e66e173d709c54c95d8126add279871e172b02e | angelofallars/sandwich-maker | /sandwich_maker.py | 2,342 | 4.28125 | 4 | #! python3
# sandwich_maker.py - Ask the user for a sandwich preference.
import pyinputplus as pyip
# Cost of the ingredients
prices = {'wheat': 10,
'white': 7,
'sourdough': 15,
'chicken': 40,
'turkey': 55,
'ham': 45,
'tofu': 40,
'cheddar': 15,
'Swiss': 25,
'mozzarella': 30,
'mayo': 5,
'mustard': 6,
'lettuce': 8,
'tomato': 7,
'none': 0,
}
print('====SANDWICH MAKER====')
print("Hi mam'sir, welcome to our restaurant. What's your order?")
while True:
# Ask the customer for their sandwich choices.
bread = pyip.inputMenu(['wheat', 'white', 'sourdough'],
'What type of bread do you want?\n')
protein = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'],
'What type of protein do you want?\n')
cheese_choice = pyip.inputYesNo('Do you want cheese?\n')
if cheese_choice == 'yes':
cheese = pyip.inputMenu(['cheddar', 'Swiss', 'mozzarella'],
'What type of cheese do you want?\n')
else:
cheese = 'none'
condiments = pyip.inputMenu(['mayo', 'mustard', 'lettuce', 'tomato'],
'What condiments do you want?\n')
amount = pyip.inputInt('How many sandwiches?\n', min=1)
# Calculate the total cost.
total_cost = (prices[bread] + prices[protein] + prices[cheese]
+ prices[condiments]) * amount
# Different depending on if customer wanted cheese.
if not cheese == 'none':
print(f"""To recount your order:
{amount} {bread} sandwiches with {protein},
topped with {cheese} cheese and {condiments}.
Total cost: {total_cost}.00 pesos.""")
else:
print(f"""To recount your order:
{amount} {bread} sandwiches with {protein},
topped with {condiments}.
Total cost: {total_cost}.00 pesos.\n""")
# Ask the customer if their order is right.
right_order = pyip.inputYesNo('Is this the right order?\n')
if right_order == 'no':
print("Mam'sir, please restate your order...")
continue
else:
print('Enjoy your meal!')
break
| true |
0c0594f330d1f31fc67b00d055725a2a865e428d | dannyhollman/holbertonschool-interview | /0x19-making_change/0-making_change.py | 500 | 4.28125 | 4 | #!/usr/bin/python3
"""
function that determine the fewest number of coins
needed to meet a given total
"""
def makeChange(coins, total):
""" Determine fewest number of coins to meet total """
count = 0
coin_total = 0
if total <= 0:
return 0
coins = sorted(coins, reverse=True)
for coin in coins:
while coin_total + coin <= total:
coin_total += coin
count += 1
if coin_total == total:
return count
return -1
| true |
3e2a7276439b8450e3e89d0f9bdd70c198d859d5 | gaddiss3651/cti110 | /P3T1_AreasOfRectangles_ShannonGaddis.py | 831 | 4.25 | 4 | # P3T1
# Areas Of Rectangles
# Shannon Gaddis
# March 6, 2018
# Get the dimensions of rectange 1
recLength1 = int(input('Enter the length of the first rectangle: '))
recWidth1 = int(input('Enter the width of the first rectangle: '))
# Get the dimensions of rectangle 2
recLength2 = int(input('Enter the length of the second rectangle: '))
recWidth2 = int(input('Enter the width of the second rectangle: '))
# Calculate the areas of the rectangles
recArea1 = recLength1 * recWidth1
recArea2 = recLength2 * recWidth2
# Determine the greater area
if recArea1 > recArea2:
print('The first rectangle you entered has the greater area.')
else:
if recArea2 > recArea1:
print ('The second rectangle you entered has the greater area.')
else:
print ('Both rectangles have the same area.')
| true |
99b2882520ac7afa090acc358da7f2997fd6b04e | phuclinh9802/ds_and_a | /Week 1/Day 1/main.py | 1,447 | 4.40625 | 4 | # python Data Structures & Algorithm study
# iterate with index
y = [3,5,6]
for index, item in enumerate(y):
print(index, item)
# sort by 2nd letter
x = ['hello', 'hi', 'xin chao', 'gc']
print(sorted(x, key=lambda k : k[1]))
# find the index of first occurence of an item
letter = 'djeqnakocie'
print(letter.index('q'))
# unpack and assign each item in an array to n variables
arr = [2,34,6]
a,b,c = arr
print(a,b,c)
# list comprehension - create a for loop inside a list
loop_list = [i**2 for i in range(5)]
print(loop_list)
# delete an item or a list
a_list = [3,5,6,1]
del(a_list[1])
print(a_list)
# del(a_list) -> a_list does not exist anymore
# append, extend, pop, remove, reverse, sort
# tuple
# several ways to initialize tuple:
# x = (), x = (1,2,3), x = 1,2,3 , x = 1,
x = 1,2,3
print(x)
# tuples are immutable, but its member objects are mutable
x = ([1,3], 4)
del(x[0][1])
print(x)
# concatenate with tuples
x += (6,)
print(x)
# Sets:
# Non-duplicate
# Very fast access vs. List
# Can be used for math sets (union, intersect)
# Unordered (cannot sort)
x = set() # empty set
x = {6,3,3}
print(x)
# functions: add(), remove(), clear(), pop() - pop a random item
# Dictionaries
# Ways to initialize
x = {'pork': 20, 'beef': 23, 'chicken': 30}
y = dict([('pork', 20), ('beef', 23), ('chicken', 30)]) # list of tuples passed through dictionaries function
z = dict(pork=20, beef=23, chicken=30)
print(x)
print(y)
print(z)
| true |
7d8b3637c1ceeb1f1d6f7bf9f5d72a8544cf7658 | frankroque/simple-python | /Desktop/GitPython/SimplePython.py | 517 | 4.3125 | 4 | print("Simple Python Progam")
print("Let us descend:")
def reverseArray(array):
beg = 0
last = len(array) - 1
temp = 0
for i in range(0, len(array)):
temp = array[beg]
array[beg] = array[last]
array[last] = temp
beg += 1
last -= 1
print(array)
orderArray = [1,2,3,4,5,6,7,8,9,10]
print(orderArray)
print("Descending using the built in python .sort(reverse = True) function:")
orderArray.sort(reverse = True)
print(orderArray)
print("Descending using our own function:")
reverseArray(orderArray)
| true |
36d88f0620981c38f4df7747e2d796db181c7362 | BlacknallW/Python-Practice-2 | /greater_than_zero.py | 209 | 4.21875 | 4 | #Print list of numbers greater than 0.
number_list = [5,19,5,20,-1,-5,-9,-23,10,11,51,-17]
empty_list = []
for numbers in number_list:
if numbers > 0:
empty_list.append(numbers)
print(empty_list) | true |
1ee103914a1b0956561a72cd0d00b233f13d5c0d | cassianasb/python_studies | /fiap-on/2-1 - Variables.py | 1,143 | 4.15625 | 4 | name = input("Digite o nome do funcionário: ")
enterprise = input("Digite o nome da empresa: ")
employeesAmount = int(input("Digite a quantidade de funcionários: "))
monthlyPayment = float(input("Digite a média da mensalidade: "))
print(name + " trabalha na empresa " + enterprise)
print("Possui ", employeesAmount, " funcionários")
print("A média da mensalidade é " + str(monthlyPayment))
print("=============== Verifique os Tipos de Dados Abaixo: ===============")
print("O tipo de dado de [name] é: ", type(name))
print("O tipo de dado de [enterprise] é: ", type(enterprise))
print("O tipo de dado de [employeesAmount] é: ", type(employeesAmount))
print("O tipo de dado de [monthlyPayment] é: ", type(monthlyPayment))
responsible = input("Digite o nome do responsável: ")
employee = input("Digite o nome do funcionário: ")
event = input("Digite o nome do evento: ")
reimbursedAmount = float(input("Digite ao valor a ser ressarcido: "))
print("Declaaro para o senhor " + responsible + " que o senhor " + employee + "s esteve presente no evento " + event + " e gastou o valor R$ " + str(reimbursedAmount) + " com a entrada.") | false |
be06b76e68aa53fd34d6c535801af7579c3ba3df | havenshi/leetcode | /549. Binary Tree Longest Consecutive Sequence II.py | 1,424 | 4.21875 | 4 | # Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.
#
# Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
#
# Example 1:
#
# Input:
# 1
# / \
# 2 3
# Output: 2
# Explanation: The longest consecutive path is [1, 2] or [2, 1].
# Example 2:
#
# Input:
# 2
# / \
# 1 3
# Output: 3
# Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.ans = 0
self.helper(root)
return self.ans
def helper(self, root):
left, right = 0, 0
if root.left and root.val == root.left.val+1:
left = self.helper(root.left)
if root.right and root.val == root.right.val-1:
right = self.helper(root.right)
self.ans = max(self.ans, left + right + 1)
return 1 + max(left, right)
| true |
eb03991f844f476e6225bbbc476f6175a974b75a | herbeeg/hg-project-euler | /1-10/problem_3.py | 1,684 | 4.21875 | 4 | from math import sqrt
class LargestPrimeFactor:
"""
A very crude way of calculating prime
numbers. While checking factors is
a single operation, I feel there
is a simpler more 'mathematical'
way of doing this.
Execution time increases exponentially
as the passed number increases in
size.
"""
def __init__(self, number):
self.number = number
self.largest = 0
def isPrime(self, value):
for n in range(2, value-1):
if 0 == value % n:
return False
return True
def isFactor(self, value):
if 0 == self.number % value:
return True
else:
return False
def largestPrime(self):
"""
Attempted to reduce execution time by halving
the number to check prime factors for as we
can assume we will find no factors larger
than itself/2.
The number needs to be cast as an integer
as division returns a float but the
range function only accepts
integer values.
"""
for n in range(3, int(sqrt(self.number))):
"""
After further research, we are able to use
'proof by contradiction' to confirm
any prime factors.
A good explanation for reference here:
http://mathandmultimedia.com/2012/06/02/determining-primes-through-square-root/
"""
if 0 != n % 2:
if self.isFactor(n):
if self.isPrime(n):
self.largest = n
return self.largest
print(LargestPrimeFactor(600851475143).largestPrime()) | true |
7af1eac6f6e0b64c50e09b3f790a8ee307402f7f | Sabbir2809/Python-For-Beginners | /Week1-Introduction/getting_input_from_theUser.py | 944 | 4.21875 | 4 | # The built-in input function requests and obtains user input:
name = input("What's your name?")
print(name)
#python takes input as a string we have to type cast the input
value1 = input("Enter first number: ")
value2 = input("Enter second number: ")
total = value1 + value2
print(total)
print(type(total))
#type casting to int format
total = int(value1) + int(value2)
print(total)
# Getting an Integer from the User by casting the input format
another_value = int(input("Enter another integer: "))
print(another_value)
# Taking multiple input from the user
a, b = input().split()
print(a, b)
print(type(a))
##########Solving Problem##########
# Determining the Minimum and Maximum with Built-In Functions min and max
number1 = int(input("Enter first intefer: "))
number2 = int(input("Enter second intefer: "))
number3 = int(input("Enter third intefer: "))
print(min(number1, number2, number3))
print(max(number1, number2, number3))
| true |
053c642f0a9c475c06acc05fdd26e1632ce70803 | Sabbir2809/Python-For-Beginners | /Week2-Control-Statements/conditional.py | 490 | 4.1875 | 4 | # IF statement
grade = 85
if grade >= 60:
print("Passed")
print("\n")
# If else statement
grade = 55
if grade >= 60:
print("Passed")
else:
print("Fail")
print("\n")
# Conditional expression
result = ("Passed" if grade >= 60 else "Failed")
print(result)
print("\n")
# IF...elif....else statement
grade = 77
if grade >= 90:
print('A')
elif grade >= 80:
print('B')
elif grade >= 70:
print('C')
elif grade >= 60:
print('D')
else:
print('F') | false |
8f5b7de0d5d0f0e6aff534852a645577e176740b | MFTI-winter-20-21/LebedevDanya | /02 хав олд р ю.py | 439 | 4.125 | 4 | print('Привет, парень!')
name = input('Как тебя зовут? ')
print('Привет, ', name, 'а в твоём имени ', len(name), " буков")
year = int(input('В каком году ты родил(ся/ась)? '))
if len(str(year)) ==4:
print('А ',year,' неплохой год')
print('Но получается вам ',2020-year,' лет')
else:
print ('ты блин ошибся')
| false |
1af9f8ec3150d5b6a1fc9a49f5a550eaa68b0b74 | Lmineor/Sword-to-Offer | /bin/balanced-binary-tree.py | 943 | 4.125 | 4 | __doc__ = """
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x, left=None, right=None):
# self.val = x
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
leftH = self.height(root.left)
rightH = self.height(root.right)
if abs(leftH - rightH) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def height(self, root:TreeNode) -> int:
if not root:
return 0
leftH = self.height(root.left)
rightH = self.height(root.right)
return max(leftH, rightH) + 1 | false |
4b2c490a94fca02d4c08e8d7910cc68e8bf5b35b | Lmineor/Sword-to-Offer | /bin/16.py | 348 | 4.15625 | 4 | def Power(base,exponent):
result = 1
if base == 0:
return 0
if exponent == 0:
return 1
elif exponent < 0:
for i in range(-exponent):
result = result*base
return 1/result
else:
for i in range(exponent):
result = result*base
return result
print(Power(2,3))
| true |
7b5872330598e20ff4fdb4819b45416809daf7e4 | 29furkhan/Programs | /Spiral.py | 1,032 | 4.25 | 4 |
matrix = []
tmp = []
m = int(input("Enter Number of Rows of Matrix\n"))
n = int(input("Enter Number of Columns of Matrix\n"))
print("Enter Matrix Values")
for i in range(m):
for j in range(n):
print("Enter matrix[",i,"][",j,"]")
tmp.append(int(input()))
matrix.append(tmp)
tmp = []
for i in matrix:
print(i)
print("Spiral Pattern for Above Matrix is\n")
row = 0
col = 0
while (row < m and col < n) :
for i in range(col, n) :
print(matrix[row][i], end = " ")
row += 1
for i in range(row, m) :
print(matrix[i][n - 1], end = " ")
n -= 1
if ( row < m) :
for i in range(n - 1, (col - 1), -1) :
print(matrix[m - 1][i], end = " ")
m -= 1
if (col < n) :
for i in range(m - 1, row - 1, -1) :
print(matrix[i][col], end = " ")
col += 1
| false |
1bb36406d02d23e554d352a12903b829eb15000e | SimaSheibani/Assignments_Northeastern_University | /stars/christmas_tree.py | 558 | 4.21875 | 4 | def main():
height = int(input("Please enter an odd number:"))
while (height < 3) or (height % 2 == 0):
height = int(input("It was not an odd number, pick another one:"))
widt = height
for row in range(height):
if (row == 0):
print(' '*int(widt/2), '*')
elif (row == height - 1):
print('/', '_' * (widt-1), '\\')
else:
if (row % 2 != 0):
print(' ')
else:
print(' '*((int(widt/2))-(int(row/2))), '/', ' '*(row-2), '\\')
main()
| true |
514408a731d619ede7edf4689b6067b94c96ba83 | SimaSheibani/Assignments_Northeastern_University | /numbers/magic_squre_validator.py | 1,169 | 4.15625 | 4 | '''This program take the input as three separate lines.
Each line consist of three numerical characters.
The program evaluate whether or not the sum of any 3 digits
horizontally, vertically, or diagonally equals 15.
'''
def main():
row_1 = (input("Enter a magic number:\n"))
row_2 = (input())
row_3 = input()
row_1_list = [int(d) for d in str(row_1)]
row_2_list = [int(d) for d in str(row_2)]
row_3_list = [int(d) for d in str(row_3)]
check = True
lsit_of_rows = [row_1_list, row_2_list, row_3_list]
for row in lsit_of_rows:
if(row[0] + row[1] + row[2] != 15):
print(row[0], row[1], row[2])
check = False
for i in range(len(lsit_of_rows)):
if(row_1_list[i] + row_2_list[i] + row_3_list[i] != 15):
print("self", row_1_list[i], row_2_list[i], row_3_list[i])
check = False
if (row_1_list[0] + row_2_list[1] + row_3_list[2] != 15):
check = False
elif (row_1_list[2] + row_2_list[1] + row_3_list[0] != 15):
check = False
if(check):
print("This is a magic number!")
else:
print("This is not a magic square!")
main()
| true |
77c82b9a06720c11a08639e7554714d22b3cb5e1 | suthirakprom/Python_BootcampKIT | /week02/ex/ex/projects/01_dice.py | 682 | 4.1875 | 4 | import random
welcome_message = "Welcome to the dices game!"
warning_message = "USAGE: The number must be between 1 and 8"
flag = True
sum = 0
print(welcome_message)
while flag:
try:
n = int(input("Enter the number of dices you want to roll: "))
if n<1 or n>8:
n = 10/0
else:
flag = False
except:
print(warning_message)
flag = True
if n>1:
for i in range(1,n+1):
random_number = random.randint(1,6)
sum += random_number
print(f"Dice {i} : {random_number}")
print("="*10)
print(f"RESULT: {sum}")
print("="*10)
else:
print(f"RESULT: {random.randint(1,6)}")
| true |
dd6c8f0ab35288b6b45d7662a4a33fb3edaf86ed | suthirakprom/Python_BootcampKIT | /week03/ex/projects/01_stringreplace_minproj_01.py | 1,950 | 4.15625 | 4 | choice = True
while choice:
paragraph = input("Please input a paragraph:\n")
searchStr = input("Please input a String search:\n")
splitParagraph = paragraph.split()
# count the number of searchStr that contained in the paragraph
count = paragraph.count(searchStr)
# the amount of words need to be replaced
countReplacedWord = splitParagraph.count(searchStr)
# print to the console
print(f"There are {count} occurrences.")
choice2 = True
# second while loop
while choice2:
choose = input("Do you want to replace the text [Y/N]?\n")
if choose == 'Y' or choose == 'N' or choose == 'y' or choose == 'n':
if choose == 'Y' or choose == 'y':
replace = input("Please input replacement string:\n")
# after_replace = paragraph.replace(searchStr, replace)
# print(after_replace)
print(f"{countReplacedWord} words has been replaced from the paragraph")
splitParagraph = paragraph.split()
for i in splitParagraph:
if i == searchStr:
i = replace
else:
i = i
# print the paragraph with replaced words
print(i, end=' ')
choice = False
elif choose == 'N' or choose == 'n':
recheck = input("Oh! you don't like to replace, Do you want to check again?[Y/N]\n")
# if yes
if recheck == 'Y' or recheck == 'y':
choice = True
# if no
if recheck == 'N' or recheck == 'n':
choice = False
# out of the second while loop
choice2 = False
else:
print("Please give a proper input")
# get back the the second while loop
choice2 = True
| true |
b63b2742f854d0e731be3536cffc3439ec6fd544 | suthirakprom/Python_BootcampKIT | /week02/ex/ex/03_vote.py | 220 | 4.21875 | 4 | age = int(input('Input your age: '))
if age > 0 and age < 18:
print("You aren't adult yet... Sorry can't vote")
elif age >= 18:
print("You are eligible to vote")
else:
print("Age must be a positive digit") | true |
792699922d74f9e67a6052678d9de45d043e240c | zfyazyzlh/hello-python | /3.1.2多分枝结构.py | 835 | 4.25 | 4 | 多分支结构(Chained)
将考试分数转换名为等级
例题
分数>=90 打印A
分数>=80 打印B
分数>=70 打印C
分数>=60 打印D
分数<60 打印E
score =78
#gender = 'lady'
if score>=90:
print 'A'
else:
if score>=80:
print 'B'
else:
if score>=70:
print 'C'
else:
if score>=60:
print 'D'
else:
if score<60:
print 'E'
由于基本if嵌套格式缩进容易出错
所以使用 if elif 语句 达到同样的效果
if score>=90:
print 'A'
elif score>=80:
print 'B'
elif score>=70:
print 'C'
elif score>=60:
print 'D'
else:
print 'E'
if-elif-else 语句中有else条件时候 else 条件放到最后 否则出错
例题
求解二元一次方程
示例文件夹 下
| false |
1cf95499837804e17cc1abfccd87fa2dc2b97b07 | sraaphorst/daily-coding-problem | /dcp_py/day062/day062.py | 806 | 4.28125 | 4 | #!/usr/bin/env python3
# day062.py
# By Sebastian Raaphorst, 2019.
from math import factorial
def num_paths(n: int, m: int) -> int:
"""
Calculate the number of paths in a rectangle of dimensions n x m from the top left to the bottom right.
This is incredibly easy: we have to make n - 1 moves to the right, and m - 1 moves down.
Thus, we must make a total of n - 1 + m - 1 moves, and choose n - 1 of them to be to the right.
The remaining ones will be down.
:param n: one dimension of the matrix (doesn't really matter which, due to symmetry)
:param m: the other dimension of the matrix
:return: the number of possible paths through the matrix
>>> num_paths(2, 2)
2
>>> num_paths(5, 5)
70
"""
return factorial(n - 1 + m - 1)//factorial(n-1)//factorial(m-1)
| true |
d9a3ddf6ecc082c06d34ca28c450f4488ce548b9 | WarmisharrowPy/Bill-Creator | /Code.py | 1,745 | 4.3125 | 4 | product1_name, product1_price = input("Product1 Name : "), input("Product1 price : ")
product2_name, product2_price = input("Product2 Name : "), input("Product2 price : ")
product3_name, product3_price = input("Product3 Name : "), input("Product3 price : ")
company_name = input("Enter your Company name : ")
company_address = input("Enter your Company Address : ")
company_city = input("Enter your Company City : ")
# declare ending message
message = 'Thanks for shopping with us today!'
# create a top border
print('*' * 50)
# print company information first using format
print('\t\t{}'.format(company_name.title()))
print('\t\t{}'.format(company_address.title()))
print('\t\t{}'.format(company_city.title()))
# print a line between sections
print('=' * 50)
# print out header for section of items
print('\tProduct Name\tProduct Price')
# create a print statement for each item
print('\t{}\t\t${}'.format(product1_name.title(), product1_price))
print('\t{}\t\t${}'.format(product2_name.title(), product2_price))
print('\t{}\t\t${}'.format(product3_name.title(), product3_price))
# print a line between sections
print('=' * 50)
# print out header for section of total
print('\t\t\tTotal')
# calculate total price and print out
total = sum(product1_price + product2_price + product3_price)
print('\t\t\t${}'.format(total))
# print a line between sections
print('=' * 50)
# output thank you message
print('\n\t{}\n'.format(message))
# create a bottom border
print('*' * 50)
| true |
01ff50c872e6dab70fdbac06c4672556d68e50eb | sa3mlk/projecteuler | /python/euler145.py | 1,250 | 4.21875 | 4 | #!/usr/bin/env python
"""
Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n).
There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10^(9))?
"""
from utils import reverse
def is_all_odd(n):
while n > 0:
if n & 1 == 0:
return False
n /= 10
return True
def is_reversible(n):
if n % 10 == 0:
return False
r = reverse(n)
if r % 10 == 0:
return False
else:
if r + n & 1 == 0:
return False
else:
return is_all_odd(n + r)
i, num_reversible = 0, 0
while i < 1000000:
num_reversible += is_reversible(i)
i += 1
print "Answer is", num_reversible
"""
num_reversible = sum([is_reversible(i) for i in xrange(10**9)])
print "Answer is", num_reversible
givez
Macintosh:projecteuler jonasg$ time ./euler145.py
Traceback (most recent call last):
File "./euler145.py", line 32, in <module>
num_reversible = sum([is_reversible(i) for i in xrange(10**9)])
MemoryError
real 78m0.968s
user 73m39.828s
sys 0m15.685s
"""
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.