blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2544b449da6fc448b0708853e51969866388488a | insaanehacker/Learn_Python | /Getting input.py | 939 | 4.65625 | 5 | # Here we are going to get input from user
# sometimes you need to enter your data or value to the console....In order to achieve your private things.....
# To tell that in a simple manner, It is not possible to change name again and again after coding a web or any interface
# So here comes our input....to solve the problem
# To get input from user, you need to use input() .......and inside brackets you many specify anything in form of string
# Example
input("What is your name? :") # This will prompt in console, So you should enter your name, This is an idea
# Now lets assign a variable and will get input from user
my_name = input("Hello, What is your name buddy :")
print("My name is " + my_name + "!")
# Similarly we can get the age or any data we want
my_name = input("Hello, What is your name buddy :")
my_age = input("What is your age :")
print("My name is " + my_name + ", I am " + my_age + " years old") | true |
4d0a732ea2327066c06479dc824e80436b36425b | insaanehacker/Learn_Python | /If statements and comparision.py | 2,314 | 4.71875 | 5 | # We already learnt the basics of if else statements, where to use it......etc
# Now lets use the same if statements inside our function to do our task using comparision operators
# >= ...........greater than equal to
# <= ...........less than equal to
# == ...........This checks whether the assigned function is equal or not
# != ...........not equal to
# Now lets check the maximum number using if statements using our function
def f_max(data1, data2, data3): # Here i have defined function and passed three parameters
if data1 >= data2 and data1 >= data3: # This checks whether data1 is greater than all or not
return data1 # This will return data1 value to console if the condition matches
elif data2 >= data1 and data2 >= data3: # This checks whether data2 is greater than all or not
return data2 # This will return data1 value to console if the condition matches
else: # This is else condition if no condition matches, use the else condition as output
return data3 # This will return data1 value to console if the condition matches
print(f_max(37,12,37.7)) # We use return statements in our function, inorder to print our output we need to specify print statements and the call our function with our parameters
# We should get output as 37.7, because 3.5 is the maximum value.
# Now lets check the minimum number using if statements using our function
def f_max(data1, data2, data3): # Here i have defined function and passed three parameters
if data1 <= data2 and data1 <= data3: # This checks whether data1 is lesser than all or not
return data1 # This will return data1 value to console if the condition matches
elif data2 <= data1 and data2 <= data3: # This checks whether data2 is lesser than all or not
return data2 # This will return data1 value to console if the condition matches
else: # This is else condition if no condition matches, use the else condition as output
return data3 # This will return data1 value to console if the condition matches
print(f_max(37,12,37.7)) # We use return statements in our function, inorder to print our output we need to specify print statements and the call our function with our parameters
# We should get output as 12, because 3.5 is the minimum value. | true |
f617ea9ac98446ef3e0328955f412ebacd2b26ba | insaanehacker/Learn_Python | /MCQ_Objects.py | 1,274 | 4.125 | 4 | # To use class in our object we must import it
from MCQ import Question_Parameters
# We need to assign questions to a variable, so lets use lists or array to assign questions
questions_prompt = [
"What is the color of Rose?\n(a) Red\n(b) Green\n(c) Violet\n\n",
"What is the color of Sky?\n(a) Red\n(b) Green\n(c) Blue\n\n",
"What is the color of Apple?\n(a) Grey\n(b) Red\n(c) Violet\n\n",
]
# Now we need to assign correct answers associated with questions_prompt
C_Answer = [
Question_Parameters(questions_prompt[0], "a"),
Question_Parameters(questions_prompt[1], "c"),
Question_Parameters(questions_prompt[2], "b"),
]
# Now lets define function ask lists of question we wanna ask with user
def Mcq_test(C_Answer):
print("Enter your choice: ")
Score = 0
for test in C_Answer:
U_Answer = input(test.Questions_Prompt)
if U_Answer == test.U_Answer:
Score += 1
if Score == 3:
print("Congrats you are brilliant")
elif Score == 2:
print("Try hard next time")
else:
print("You loose, Try again")
print("You have scored " + str(Score) + "/" + str(len(questions_prompt)) + " Correct")
Mcq_test(C_Answer)
| true |
0c1e2d657585c92c98aa190a4aa80ec15344f32c | Cainuriel/Training-Python- | /funcion iter().py | 500 | 4.1875 | 4 | # funcion iter()
# vamos a convertir listas y cadenas en algo iterable.
lista = [1,2,3,4,5,6,7,8,9]
cadena = "Deletreame por favor"
listaiterada = iter(lista)
cadenaiterada = iter(cadena)
print("primera iteracion")
print(next(listaiterada))
print(next(cadenaiterada))
print("segunda, tercera y cuarta iteracion")
print(next(listaiterada))
print(next(cadenaiterada))
print(next(listaiterada))
print(next(cadenaiterada))
print(next(listaiterada))
print(next(cadenaiterada))
| false |
674dfdbcb3dd9210bf1392dc528dfc58168a68d7 | Cainuriel/Training-Python- | /bucles 2.py | 1,081 | 4.125 | 4 | import math
# el tipo range es muy versatil en el uso de rangos numericos. algunos ejemplos:
# de un numero a un numero, el primero inclusive:
for i in range(5,10):
print(f"valor de la variable: {i}")
#introduciendo un tercer numero, determinamos la distancia de rango en el conteo:
# por ejemplo, para ir de dos en dos, desde el numero 50 al 70 lo definimos asi:
for i in range(50,71,2):
print(f"valor de la variable: {i}")
# bucles con while
i=1
while i<=10:
#otra forma de concatenar texto con variables
print("valor de la variable: "+ str(i))
i = i + 1
print("Fin de la impresion")
print("Programa que calcula la raiz cuadrada")
numero=int(input("Introduce un numero: "))
intentos = 0
while numero< 0:
if intentos==2:
print("Te estas pitorreando de mi. cerramos el programa")
break
print("Numero negativo no operable. por favor, introduce uno correcto")
numero=int(input("aqui: "))
intentos = intentos + 1
if (intentos<2):
resultado = math.sqrt(numero)
print("La raiz cuadrada de "+str(numero)+" es:"+str(resultado))
| false |
29aa70af60a39c8c50e10eed97e263e9d6ef6a5a | sallysy8/pythonLearningUdemy | /myexp.py | 1,103 | 4.1875 | 4 | # ''' fibonacci series'''
# def fib(n):
# if n < 2:
# return n
# else:
# nums[0,1]
# new_num = nums[-1] +nums[-2]
# nums.append(new_num)
# return nums[-1]
# def fibonacci(n):
# """ compute the nth Fibonacci number """
# if n < 2:
# return n
# a, b = 0, 1
# for _ in range(n):
# a, b = b, a + b
# return a
# def fibonacci(n):
# if n < 2:
# return n
# else:
# return fibonacci(n-1) +fibonacci(n-2)
# assert fibonacci(5) == 5
# def pig_latin(word):
# first_letter = word[0]
# # check if vowel
# if first_letter in 'aeiou':
# pig_word = word + 'ay'
# else:
# pig_word = word[1:] + first_letter + 'ay'
# return pig_word
# print(pig_latin('word'))
def even_num(*args):
even_num = []
for num in args:
if num % 2 != 0:
pass
else:
even_num.append(num)
return even_num
print(even_num(2,3,4,5,6))
def skyline(mystring):
newstring = ''
for i in range(len(mystring)):
if i%2 ==0:
newstring += mystring[i].upper()
else:
newstring += mystring[i].lower()
return newstring
print(skyline('AHgbjekjhd'))
| false |
e375437e52ec23b83fa51b4cb3880daac9698a5f | sallysy8/pythonLearningUdemy | /GeneratorsHomework.py | 653 | 4.25 | 4 | '''
Create a generator that generates the squares of numbers up to some number N.
'''
import random
def gensquare(N):
for number in range(N):
yield number**2
for x in gensquare(10):
print(x)
'''
Create a generator that yields "n" random numbers between a low and high number (that are inputs).
'''
def rand_num(low, high, n):
for number in range(n):
number = random.randint(low, high)
yield number
for num in rand_num(1,10,12):
print(num)
'''
Use the iter() function to convert the string below into an iterator:
'''
s = 'hello'
s_iter = iter(s)
print(next(s_iter))
print(next(s_iter))
| true |
46bc79112a33c7aa766eecd9b135c0def861250b | TA-Engineer/Python_Interview_Practice | /Dynamic Programming/DP_canConstruct.py | 1,287 | 4.1875 | 4 | '''
Write a function canConstruct(target, wordBank) that accepts a target
string and an array of strings.
The function should returna boolean indicating whether or not the 'target'
can be constructed by concatenating elements of the 'wordBank' array.
You may reuse elements of 'wordBank' as many times as needed.
'''
def canConstruct(target, wordBank, memo = {}):
if target in memo: return memo[target]
if target == '': return True
for word in wordBank:
if target.find(word) == 0:
suffix = target[len(word):]
if canConstruct(suffix, wordBank, memo) == True:
memo[suffix] = True
return True
memo[target] = False
return False
memo= {}
print( canConstruct("abcdef", ["ab","abc", "cd", "def", "abcd" ]))
# True
print( canConstruct( " skatebaord", ['bo', 'rd', 'ate', "t","ska", "sk", "boar"]))
# False
memo= {}
print(canConstruct("enterapotentpot", ['a', 'p', 'ent', 'enter', 'ot', 'o', 't' ] ))
# True
memo= {}
print(canConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeef", [
"e",
"ee",
"eee",
"eeeee",
"eeeeee"
])) # False
''''
Output:
Time complexity
m = target.length
n = wordBank.length
Brute Force
Time O(n^m * m)
Space O(m^2)
Memoized:
Time: O(n*m^2)
Space: O(m^2)
''' | true |
4a5d07ca64b26f33c5214c86ef5aa5a9bb2a1642 | doronma/pyton_study | /scopes.py | 757 | 4.15625 | 4 | def fact(n):
""" calculatee n! iteratively """
result = 1
if n > 1:
for f in range(2,n+1):
result*= f
return result
def factorial(n):
# n can be defiend as n * (n-1)
""" calculate n recursively """
if n<=1 :
return 1
else :
return n * factorial(n-1)
def fib(n):
if n<2:
return n
else:
return fib(n-1) + fib(n-2)
def fibonacci(n):
if n == 0:
result = 0
elif n ==1:
result = 1
else:
n_minus1 = 1
n_minus2 = 0
for f in range(1,n):
result = n_minus1 + n_minus2
n_minus2 = n_minus1
n_minus1 = result
return result
for i in range(36):
print(i,fibonacci(i)) | false |
237da88d9e7e8551f9cf84b17e814042fe9104a0 | afizs/pythonhomework | /COMSC11/multiplicationtable_7.py | 445 | 4.34375 | 4 | # This program print multiplication table in the below format.
# =================
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# 1 x 4 = 4
# 1 x 5 = 5
# 1 x 6 = 6
# 1 x 7 = 7
# 1 x 8 = 8
# 1 x 9 = 9
# 1 x 10 = 10
# =================
till = int(input("enter the number[till which you want to pring multiplication table]: "))
for i in range(1, till+1):
print("=================")
for j in range(1, 11):
print("%d x %d = %d"%(i, j, i*j))
| true |
80f69e7a2f542cd7ff7357d936b6e9fdd3782b35 | justin-ho/security-tools | /crypto/vigenere.py | 2,479 | 4.21875 | 4 | #!/usr/bin/python
"""Python script to decrypt a vigenere cipher
Uses the given key to shift the letters in the given message.
-m,
The message to encrypt using the key
-k,
The key to encrypt the message with
-a,
enumerate vigenere using keys in the dictionary
-f,
dictionary file
-e,
encrypt the message
-d,
decrypt the message
Example:
python vigenere.py -m 'This is my secret message' -k 'mykey'
"""
import sys
import getopt
from substitution import vigenere
from util import mquit
def enumerate_vigenere(message, filename, encrypt):
"""Enumerates the filename file performing a vigenere shift
on the message using each line from the file as the key"""
fileobj = open(filename, 'r')
iterator = 0
user = ''
viewnumber = 10
# print the enumeration 10 entries at a time
while iterator != viewnumber or user != 'q':
temp = fileobj.readline().rstrip()
if temp == '':
break
print vigenere(message, temp, encrypt)
iterator += 1
# When the enumeration pauses ask the user if they want to continue
if iterator == viewnumber:
user = raw_input('Press Enter to continue or q to quit: ')
if user != 'q':
iterator = 0
fileobj.close()
def main():
"""Main function to run the script"""
argv = sys.argv[1:]
qmessage = 'vigenere.py -m <message> -k <key to use for shifting> ' \
'[-a -f -d -e]'
try:
opts, args = getopt.getopt(argv, "m:k:f:aed")
except getopt.GetoptError:
mquit(qmessage)
# All options must be specified
if len(opts) < 2:
mquit(qmessage)
# get and set all the user defined options
message = ''
key = ''
dictionary = ''
enum = False
encrypt = True
for opt, arg in opts:
if opt == '-m':
message = arg
elif opt == '-k':
key = arg
elif opt == '-f':
dictionary = arg
elif opt == '-a':
enum = True
elif opt == '-e':
encrypt = True
elif opt == '-d':
encrypt = False
# quit if the user did not define a mandatory option
if message == '' or (not enum and key == '') or (enum and dictionary == ''):
mquit(qmessage)
if enum:
enumerate_vigenere(message, dictionary, encrypt)
else:
print vigenere(message, key)
if __name__ == "__main__":
main()
| true |
3e8495ec897ae9b2563b8388a9e38538f2521b18 | marwansalama94/eecs-6.001 | /ps0/ps0.py | 245 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 23:22:34 2018
@author: marwansalama
"""
import math
x = int(input("Enter Number x:"))
y = int(input("Enter Number y:"))
power = x**y
print("log(x) ="+str(math.log(x,2))) | false |
8e6bda09e96190611cafa4bce049d8f3259f1444 | sonyasha/exercises | /rocket.py | 1,214 | 4.375 | 4 | from math import sqrt
class Rocket():
'''Define a Rocket object'''
def __init__(self, name, cap, x=0, y=0):
self.x = x
self.y = y
self.name = name
self.cap = cap
def moving(self, x_move=0, y_move=1):
self.x += x_move
self.y += y_move
def distance(self, other_rocket):
dist = sqrt((self.x-other_rocket.x)**2 + (self.y-other_rocket.y)**2)
return round(int(dist))
def launch(self):
return f'captain {self.cap} starts launching of rocket {self.name}'
def landing(self):
print(f'before: rocket x: {self.x}, y: {self.y}')
self.x = 0
self.y = 0
print(f'after: rocket x: {self.x}, y: {self.y}')
def secure_check(self, other_rocket):
if self.distance(other_rocket) == 0:
return f'Rockets crashed!!'
elif self.distance(other_rocket) < 5:
return f'Alarm! Too close'
else:
return f'All good!'
class Shuttle(Rocket):
'''Define a Shuttle object with parent class - Rocket'''
def __init__(self, name, cap, x=0, y=0, flights = 0):
super().__init__(name, cap, x,y)
self.flights = flights | false |
ee7a89f928271ef038133bcaf8fb213b60b86f5a | halukkorkmaz/T3-Python-Egitimi | /VariableTypes.py | 1,928 | 4.1875 | 4 | # coding=utf-8
print("Hello, World!")
#Numbers
sayac = 100 # An integer assignment
kilometre = 1000.0 # A floating point
print(sayac)
print kilometre
#Bool
x = True
y = not x
print
print x
print y
print(10 > 9) #True
print(10 == 9) #False
print(10 < 9) #False
#Strings
str = 'Hello World!'
print
print(len(str))
print str # String yazdırır
print str[0] # String ilk elemanını yazdırır
print str[2:5] # 3. karakterden 5. karaktere kadar olan elemanları yazdırır
print str[2:] # 3. karakterden itibaren tum elemanlari yazdirir.
print str * 2 # Stringi iki defa basar
print str + "TEST" # Stringi yeni ifade ile birleştirir.
print(str.split(",")) # returns ['Hello', ' World!']
print
m = "awesome"
print("Python " + m)
txt = "T3 IOT Egitimi Gungoren"
x = "ungor" in txt
print(x)
#Lists
list = [ 'Ece', 786 , 2.23, 'Can', 70.2 ]
tinylist = [123, 'Can']
print
print list # Tüm listeyi yazdırır.
print list[0] # Listenin ilk elemanını yazdırır.
print list[1:4] # 2. elemandan 4. elemana kadar listeyi yazdırır.
print list[2:] # Listenin 3. elemanından itibaren yazdırır.
print tinylist * 2 # Listeyi iki defa yazdırır.
print list + tinylist # İki listeyi birleştirir.
#tuple[2] = 1000 # Invalid syntax with tuple
#list[2] = 1000 # Valid syntax with list
#Dictionaries (Key - Value Types)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
"""
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print
print dict
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
"""
#Casting
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
print
print type(kilometre)
| false |
9c71cdba2e16924932065786b44f0799c6fb8077 | adilgereev/python_training | /calculator.py | 1,508 | 4.15625 | 4 | print('Приветствую на своем супер-мощном калькуляторе!')
def calculator():
while True:
x1 = int(input('Вацок, введи первое число: '))
print('Красиго!')
operator = input('А теперь введи один из знаков операции (+, -, *, /): ')
x2 = int(input('И второе число для операции: '))
if operator == '+':
print('Шикардос!')
print(f'{x1} + {x2} = {x1 + x2}')
break
elif operator == '-':
print('Четко!')
print(f'{x1} - {x2} = {x1 - x2}')
break
elif operator == '*':
print('Мощно!')
print(f'{x1} * {x2} = {x1 * x2}')
break
elif operator == '/':
print('Зачет!...')
print(f'{x1} / {x2} = {x1 / x2}')
break
else:
print('Будь по проще, уци! Вводи символы соответствующие функционалу калькулятора!')
calculator()
while True:
restart = input(
'Если хочешь еще раз провести какую нибудь опасную операцию введи "Да", если не хочешь введи "Нет": ')
if restart == 'Да':
calculator()
elif restart == 'Нет':
print('До встречи, вацок...')
break
| false |
71c276bddb8be41a3f431ee6448eb5f3dbabe763 | emdre/first-steps | /fly nerd/modifying strings.py | 708 | 4.21875 | 4 | """Do zmiennej sentence przypisz zdanie: „Kurs Pythona jest prosty i przyjemny.”, a następnie:
Policz wszystkie znaki w napisie
Nie modyfikując zmiennej sentence wyświetl słowo „prosty”
Wyświetl znak o indeksie (czy za każdym razem rozumiesz co się dzieje?):
7
12
-4
37
Wprowadź do zdania 2 błędy ortograficzne. """
sentence = "Kurs Pythona jest prosty i przyjemny."
print(len(sentence))
print(sentence[18:24])
print(sentence[7]) # prints t
print(sentence[12]) # prints a space
print(sentence[-4]) # prints m
print(sentence[37]) # out of range
sentence = sentence[0] + "ó" + sentence[2:22] + "s" + sentence[23:]
print(sentence)
| false |
36ef832efbda11ddf55459cdf4f58e9f35e18505 | benalloway/practicepython | /list-ends.py | 636 | 4.25 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
# [ expression for item in list if conditional ]
# First Attempt:
import random
# generate random list of random numbers with random length between 5 and 30 items long.
a = [random.randint(1,100) for x in range(0, random.randint(5,30))]
# function that returns list of two items: first and last item in given list.
def bookEnd(i):
return [i[0], i[-1]]
# print list, and print first/last item
print(a)
print(bookEnd(a)) | true |
69c387ccff018cb75f732d5b26113974446e7404 | riddhisharma2019/PYTHON-EXAMPLES | /array1.py | 697 | 4.21875 | 4 | from array import *
arr = array('i',{}) # this is for the forming a array by given values to by user.
n = int(input("enter the length of the array"))
for i in range(n): # range goes upto a given n no
x= int(input("enter the next value"))
arr.append(x)
print(arr)
vals = int(input("enter the search no: ")) # this for finding the given search index value of a given input no
k=0 # given counter value; this is for generating index value
for e in arr:
if e==vals:
print(k)
break
k+=1 | true |
07e4d8140c77f7af9caf65edb3c5f7839a6fa848 | luid95/python-course | /07-ejercicios/ejercicio3.py | 943 | 4.15625 | 4 | """
Ejercicio 3
- Escribir un script que nos muestra los cuadrados
de los 60 primeros numeros naturales.
- Una primera version con uso del bucle for
- Una segunda version con uso del bucle while
"""
# Generar los numeros mediente un bucle for
print("Lista de los primeros 60 numeros naturales y sus cuadrados")
for numero in range(0, 61):
# Realizar los cuadrados de cada numero
cuadrado = numero * numero
# Imprimir los numeros naturales y sus cuadrados
print(f"{numero} - {cuadrado}")
print("\n Fin de la lista de numeros con bucle for")
# Generar los numeros mediente un bucle while
contador = 0
while contador <= 60:
# Realizar los cuadrados de cada numero
cuadrado = contador * contador
# Imprimir los numeros naturales y sus cuadrados
print(f"{contador} - {cuadrado}")
contador += 1
print("\n Fin de la lista de numeros con bucle while")
print("\n Y de todos los cuadrados") | false |
d6d10367ded7efe26ed0123ffd5d196671f34d83 | luid95/python-course | /12-modulos/main.py | 1,281 | 4.34375 | 4 | """
MODULOS:
Son funcionalidades ya hechas para reutilizar.
Podemos consseguir modulos que ya se vienen en el lenguaje,
modulos en internet, y tambien podemos usar nuestros modulos.
"""
# Importar modulo propio
# import mimodulo
## o importar una funcion del modulo
## from mimodulo import holamundo
### o importar todas las funciones del modulo para llamarlo por nombre
from mimodulo import *
# print(mimodulo.holamundo("Luis David"))
# print(mimodulo.calculadora(3,5,True))
## print(holamundo("Luis"))
print(holamundo("Luis"))
print(calculadora(10, 5, True))
# MODULO DE FECHA POR DEFECTO
import datetime
print(datetime.date.today())
fecha_completa = datetime.datetime.now()
print(fecha_completa)
print(fecha_completa.year)
print(fecha_completa.month)
print(fecha_completa.day)
fecha_personaliada = fecha_completa.strftime("%d/%m/%Y, %H:%M:%S")
print(f"Fecha personalizada {fecha_personaliada}")
print(datetime.datetime.now().timestamp())
# MODULO MATEMATICAS
import math
# Operaciones basicas
print(f"Raiz cuadrada de 10: {math.sqrt(10)}")
print(f"Numero PI: {math.pi}")
print(f"Redondear: {math.ceil(6.5678)}")
print(f"Redondear floor: {math.floor(6.5678)}")
# Modulo Random
import random
print(f"Numero aleatorio entre 15 y 65: {random.randint(15, 65)}") | false |
16b8f300979a41f738fff63664ccaaf924f6a2e5 | luid95/python-course | /07-ejercicios/ejercicio1.py | 517 | 4.1875 | 4 | """
Ejercicio 1
- Crear 2 varibles uno para 'pais' y otra para 'continente'
- Mostrar su valor por pantalla (imprimir)
- Mostrar un comentario diciendo el tipo de dato
"""
# Crear las variables
pais = 'Mexico'
continente = 'Americano'
# Mostrar el valor de cada variable
print(f"El pais de {pais} se encuentra en el continente {continente}")
# Mostrar su tipo de dato
tipoP = type(pais)
tipoC = type(continente)
print("tipo de dato de pais es: ", tipoP)
print("tipo de dato de continente es: ", tipoC) | false |
01804ef8ebf98728f86f0cc9c5d8bd43984fbc0b | luid95/python-course | /10-sets-diccionarios/diccionarios.py | 929 | 4.21875 | 4 | """
DICCIONARIO
Es un tipo de dato que almacena un conjunto de datos.
En formato clave > valor.
Es parecido a un array asociativo o un objeto json.
"""
persona ={
"nombre": "Luis",
"apellido": "Morales",
"email": "example@gmail.com"
}
print(type(persona))
print(persona)
print(persona['apellido'])
# LISTA CON DICCIONARIOS
contactos = [
{
'nombre': 'Antonio',
'email': 'antonio@gmail.com'
},
{
'nombre': 'Luis',
'email': 'luis@gmail.com'
},
{
'nombre': 'Salvador',
'email': 'salvador@gmail.com'
},
]
print(contactos)
print(contactos[0]['nombre'])
contactos[0]['nombre'] = 'Antony'
print(contactos[0]['nombre'])
print('\n --------------------------------------------')
for contacto in contactos:
print(f"Nombre del contacto {contacto['nombre'] }")
print(f"Email del contacto {contacto['email'] }")
print('\n ###########################################') | false |
dda039bbbe361d4d846a79b164df6a8a8c2e3c81 | tabboud/code-problems | /problems/interview_cake/24_reverse_linked_list/reverse_linked_list.py | 971 | 4.59375 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Reverse a linked list in-place
"""
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
def print_list(root):
while root is not None:
print "Data: ", root.value
root = root.next
def reverse_list(root):
""" Reverse a linked list in-place
Complexity:
Time -> O(n): Iterate the list once
Space -> O(1): In-place reversal
"""
if root is None:
return
cur = root
tail = None
while cur is not None:
tmp = cur.next
cur.next = tail
tail = cur
cur = tmp
if __name__ == "__main__":
a = LinkedListNode(1)
b = LinkedListNode(2)
c = LinkedListNode(3)
d = LinkedListNode(4)
e = LinkedListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
print_list(a)
reverse_list(a)
print "Reversed:"
print_list(e)
| true |
3d2fd1a2bad67544441b1c3dd992608d0f9e9b06 | tabboud/code-problems | /problems/interview_cake/43_merge_sorted_arrays/merge_sorted_arrays.py | 1,228 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Merge Sorted Arrays
"""
def merge_lists(l1, l2):
""" Merge two sorted lists
Complexity:
Time -> O(n): Iterate both lists once
Space -> O(n): Create a new list with n values
"""
# check empty lists
if len(l1) == 0 and len(l2) == 0:
raise Exception("Both lists are empty")
merged_lists = []
start1 = 0
start2 = 0
while start1 < len(l1) or start2 < len(l2):
# compare both
if start1 < len(l1) and start2 < len(l2):
if l1[start1] < l2[start2]:
merged_lists.append(l1[start1])
start1 += 1
else:
merged_lists.append(l2[start2])
start2 += 1
elif start1 < len(l1):
# append the rest of l1
merged_lists += l1[start1:]
break
elif start2 < len(l2):
# append the rest of l2
merged_lists += l2[start2:]
break
return merged_lists
if __name__ == "__main__":
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
print merge_lists(my_list, alices_list) # [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
| true |
9226d5b26c85a70391cf33f14f66228e24041112 | tabboud/code-problems | /problems/interview_cake/01_apple_stocks/max_profits.py | 1,599 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_max_profit(yesterdays_stocks):
"""
Keep a running max_profit and min_price as we iterate through the list
Runtime:
Time -> O(n): iterate the list once
Space -> O(1):
"""
if len(yesterdays_stocks) < 2:
raise IndexError("Getting a profit requires atleast 2 prices!")
min_price = yesterdays_stocks[0]
max_profit = yesterdays_stocks[1] - yesterdays_stocks[0]
for index, current_price in enumerate(yesterdays_stocks):
# We can't sell at the first stock, since we have to buy first
if index == 0:
continue
potential_profit = current_price - min_price
max_profit = max(max_profit, potential_profit)
min_price = min(min_price, current_price)
return max_profit
def get_max_profit_brute(yesterdays_stocks):
"""
Brute Force
Calculate the max profit for every value in the list and return the largest
Runtime:
O(n^2): Comparing numbers to all numbers
"""
# Set to a random small number
max_profit = -1000
for earlier_time, buy_price in enumerate(yesterdays_stocks):
for sell_price in yesterdays_stocks[earlier_time+1:]:
# compare all values
max_profit = max(max_profit, (sell_price - buy_price))
return max_profit
if __name__ == "__main__":
stock_prices_yesterday = [10, 7, 5, 8, 11, 9] # 6
print get_max_profit(stock_prices_yesterday)
stock_prices_yesterday = [10, 7, 5, 4, 3, 2] # -1
print get_max_profit(stock_prices_yesterday)
| true |
17b301732e3345e950b3b58a910ad1c9de42714b | tabboud/code-problems | /problems/interview_cake/03_highest_product/highest_product.py | 1,906 | 4.46875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def highest_product_of_3_brute(list_of_ints):
""" Find the highest product of 3 integers in an array
Args:
Returns:
Runtime:
Time -> O(n^3)
Space -> O()
"""
highest_product = 1
for i, elem1 in enumerate(list_of_ints[0:-2]):
for j, elem2 in enumerate(list_of_ints[i+1:-1]):
for k, elem3 in enumerate(list_of_ints[j+1:]):
highest_product = max(highest_product, elem1*elem2*elem3)
return highest_product
def highest_product_greedy(arr):
""" Return the highest product by using a greedy algorithm
Runtime:
Time -> O(n): Traverse the list in 1 pass
Space -> O(1):
"""
highest = max(arr[0], arr[1])
lowest = min(arr[0], arr[1])
highest_product_of_two = arr[0] * arr[1]
lowest_product_of_two = arr[0] * arr[1]
highest_product_of_three = arr[0] * arr[1] * arr[2]
for num in arr[2:]:
# update highest product of three
highest_product_of_three = max(highest_product_of_three, highest_product_of_two*num, lowest_product_of_two*num)
# update highest and lowest product of two
highest_product_of_two = max(highest_product_of_two, highest*num, lowest*num)
lowest_product_of_two = min(lowest_product_of_two, highest*num, lowest*num)
# update the highest and lowest value
highest = max(highest, num)
lowest = min(lowest, num)
return highest_product_of_three
if __name__ == "__main__":
arr = [4,1,2,3] # 24
arr2 = [-10, -10, 1, 12, 10] # 1200
arr3 = [1, 10, -5, 1, -100] # 5000
list_of_ints = [-10,-10,1,3,2] # 300
print(highest_product_greedy(arr))
print "---"
print(highest_product_greedy(arr2))
print "---"
print(highest_product_greedy(arr3))
print "---"
print(highest_product_greedy(list_of_ints))
| true |
46623976002261e3dfd0ad46729eebe000f0b9b2 | tabboud/code-problems | /problems/interview_cake/25_kth_to_last_node/kth_to_last_node.py | 1,375 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Reverse a linked list in-place
"""
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
def print_list(root):
while root is not None:
print "Data: ", root.value
root = root.next
def kth_to_last_node(k, root):
""" Return the kth to last node in a linked list
Complexity:
Time -> O(n): Iterate the list once
Space -> O(1): No extra space
"""
if root is None:
return
# Use two pointers to traverse the list
first = second = root
# Move second pointer k positions
for _ in xrange(k):
if second.next is None:
raise Exception("k is out of range!")
second = second.next
# Now move first and second one at a time until second reaches the end
while second != None:
second = second.next
first = first.next
# Return the value under first
return first.value
if __name__ == "__main__":
a = LinkedListNode("Angel Food")
b = LinkedListNode("Bundt")
c = LinkedListNode("Cheese")
d = LinkedListNode("Devil's Food")
e = LinkedListNode("Eccles")
a.next = b
b.next = c
c.next = d
d.next = e
# returns the node with value "Devil's Food" (the 2nd to last node)
print kth_to_last_node(2, a)
| true |
b24663ae5678eccb0e66ad91a1b9cb5e6e66cbc1 | wojciechbielecki/py4e-exercises | /3-5.py | 231 | 4.15625 | 4 | x = float(input('Enter x: '))
y = float(input('Enter y: '))
if x > y:
print(str(x) + ' is greater than ' + str(y))
elif x < y:
print(str(x) + ' is smaller than ' +str(y))
else:
print(str(x) + ' is equal to ' + str(y))
| false |
c2f3e8b77e8524dc8cc7ee47230c91cab79d40a3 | kungfumanda/30DaysOfPython | /exercises/day23.py | 698 | 4.15625 | 4 | # Write a generator that generates prime numbers in a specified range.
def prime_range(n, m):
for number in range(n, m+1):
for i in range(2, number):
if number % i == 0:
break
else:
yield number
n = int(input("Please enter your start number: "))
m = int(input("Please enter your ending number: "))
prime = prime_range(n, m)
print(f"The prime numbers between {n} and {m} are:")
print(*prime, sep="\n")
# Rewrite this code using a generator expression
# map(lambda name: name.strip().title(), names)
names = [" rick", " MORTY ", "beth ", "Summer", "jerRy "]
names = (name.strip().title() for name in names)
print(*names, sep=", ")
| true |
7a93768a85b3b6eca4f7a9727203d8875a4d458c | kungfumanda/30DaysOfPython | /exercises/day7.py | 755 | 4.125 | 4 | complete_name = input("Please enter your name and last name: ")
first_name = complete_name.split()[0]
surname = complete_name.split()[1]
#------------------------------------#
n = [str(i) for i in range(1,6)]
a = " | ".join(n)
print(a)
#---------------------------------#
quotes = [
"'What a waste my life would be without all the beautiful mistakes I've made.'",
"'A bend in the road is not the end of the road... Unless you fail to make the turn.'",
"'The very essence of romance is uncertainty.'",
"'We are not here to do what has already been done.'"
]
for quote in quotes:
print(quote[1:-1].strip())
#---------------------------------------#
word = input("please enter a word").strip()
print(f"your word has {len(word)} letters.")
| true |
65567d984024710cfdc8346e6817b0709f6bd407 | kungfumanda/30DaysOfPython | /exercises/day19.py | 837 | 4.53125 | 5 | # Create a short program that prompts the user for a list of grades
# separated by commas. Split the string into individual grades and
# use a list comprehension to convert each string to an integer.
# You should use a try statement to inform the user when the values
# they entered cannot be converted.
grades = input("Please enter your grades, separated by commas: ")
try:
grades = grades.split(",")
grades = [int(grade) for grade in grades]
except ValueError:
print("Your values cannot be converted.")
# Imagine you have a file named data.txt. Open it for reading using Python,
# but make sure to use a try block to catch an exception that arises if
# the file doesn't exist.
try:
with open("data.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("There's no such file.")
| true |
0d4505f3333e617aac44ffd985a32a1808e86548 | alina-molnar/Python3-Projects | /2. Intro to Python/Intro to Python - Classes/Rocket2_class.py | 2,717 | 4.4375 | 4 | from math import sqrt
class Rocket2():
"""Class to store coordinates, move rocket in all directions, calculate distance between all rockets."""
def __init__(self, x=0, y=0):
"""Set initial coordinates."""
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=0):
"""Move rocket left, right, up and down."""
self.x += x_increment
self.y += y_increment
def get_distance(self, other_rocket):
"""Calculate distance between two rockets."""
distance = sqrt((self.x - other_rocket.x)**2 +
(self.y - other_rocket.y)**2)
if self != other_rocket:
print("Distance between %s and %s is %d." %
(self, other_rocket, distance))
return distance
# Create object, move it, then print new coordinates.
rocket_2 = Rocket2()
rocket_2.move_rocket(-1, 3)
print(rocket_2.x)
print(rocket_2.y)
print("\n")
# Create list of 5 rockets.
improved_rockets = [Rocket2() for x in range(0, 5)]
# Move all rockets.
improved_rockets[0].move_rocket(-2, 1)
improved_rockets[1].move_rocket(2, 4)
improved_rockets[2].move_rocket(1, -2)
improved_rockets[3].move_rocket(3, 2)
improved_rockets[4].move_rocket(5, 3)
# Print coordinates of each rocket
for index, rocket in enumerate(improved_rockets):
print("Coordinates of rocket %d: %d, %d" % (index, rocket.x, rocket.y))
# ??????Maybe use **kwargs when defining get_distance function, then use pop method to calculate distance between one element in the list and all others???????????????????????????
# Print distance between rockets using for loops, problem is they are shown both ways (like A to B, and B to A).
for index, rocket in enumerate(improved_rockets):
improved_rockets[0].get_distance(rocket)
improved_rockets[1].get_distance(rocket)
improved_rockets[2].get_distance(rocket)
improved_rockets[3].get_distance(rocket)
improved_rockets[4].get_distance(rocket)
# Print distance between rockets using for loops, problem is I have to write them by hand.
print("\nDistances between rockets:")
improved_rockets[0].get_distance(improved_rockets[1])
improved_rockets[0].get_distance(improved_rockets[2])
improved_rockets[0].get_distance(improved_rockets[3])
improved_rockets[0].get_distance(improved_rockets[4])
improved_rockets[1].get_distance(improved_rockets[2])
improved_rockets[1].get_distance(improved_rockets[3])
improved_rockets[1].get_distance(improved_rockets[4])
improved_rockets[2].get_distance(improved_rockets[3])
improved_rockets[2].get_distance(improved_rockets[4])
improved_rockets[3].get_distance(improved_rockets[4])
| true |
83dbd68397af54767d4a28801d34985c9bb9e539 | Eleni21K/python_scripts | /average_variance_deviation_example.py | 1,391 | 4.375 | 4 | # Find how the grades varied against the average. This is called computing the variance.
# Listof grades:
grades_input = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades_input):
"""Print the list of grades.
Args:
grades_input (list): list of grades
"""
for grade in grades_input:
print grade
def grades_sum(grades_input):
"""Get sum of grades.
Args:
grades_input (list): list or grades
Returns:
total (float): sum of the grades
"""
total = 0
for score in scores:
total += score
return total
def grades_average(grades_input):
"""Get average of grades.
Args:
grades_input (list): list or grades
Returns:
average (float): average of the grades
"""
sum_of_grades = grades_sum(grades_input)
average = sum_of_grades / float(len(grades_input))
return average
def grades_variance(scores):
"""
Args:
Returns:
result ():
"""
average = grades_average(scores)
variance = 0
for score in scores:
variance += (average-score)**2
result = variance/len(scores)
return result
def grades_std_deviation(variance):
result = variance**0.5
return result
variance = grades_variance(grades)
print grades_std_deviation(variance)
print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance)
| true |
90cb024d32333492f8ecc97ea730549381910ba8 | rajeshjaga/Python-Log | /func.py | 325 | 4.25 | 4 | def area(Radius):
return 3.14*Radius**2
def Volume(area,length):
print(area*length)
Radius=int(input('Enter the radius of the circle :\n'))
length=int(input('Enter the Length of the circle :\n'))
area1=area(Radius)
print('The area of the cicle is ',area1)
print('The volume of the cicle is ')
Volume(area1,length)
| true |
f41f3e261ac5369d4d1eb9244759bfb912bedaae | scperkins/46-python-exercises | /VerySimpleExercises/make_ing_form.py | 1,894 | 4.625 | 5 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
In English, the present participle is formed by adding the suffix -ing to the
infinite form: go -> going. A simple set of heuristic rules can be given as
follows:
If the verb ends in e, drop the e and add ing (if not exception: be, see,
flee, knee, etc.)
If the verb ends in ie, change ie to y and add ing
For words consisting of consonant-vowel-consonant, double the final letter
before adding ing
By default just add ing
Your task in this exercise is to define a function make_ing_form() which
given a verb in infinitive form returns its present participle form. Test
your function with words such as lie, see, move and hug. However, you must
not expect such simple rules to work for all cases.
"""
import unittest
def is_vowel(char):
vowels = 'aieou'
if char in vowels:
return True
else: return False
def make_ing_form(infinitive):
exceptions = ('be', 'see', 'flee', 'knee')
if infinitive.endswith('ie'):
infinitive = infinitive[:-2]
return infinitive + 'ying'
elif infinitive.endswith('e') and infinitive not in exceptions:
infinitive = infinitive[:-1]
return infinitive + 'ing'
elif not is_vowel(infinitive[-1]) and is_vowel(infinitive[-2]) and not is_vowel(infinitive[-3]):
return infinitive + infinitive[-1] + 'ing'
else:
return infinitive + 'ing'
class TestMakeIngForm(unittest.TestCase):
def test_is_vowel(self):
self.assertTrue(is_vowel('a'))
self.assertFalse(is_vowel('z'))
def test_make_ing_form(self):
self.assertEqual(make_ing_form('lie'), 'lying')
self.assertEqual(make_ing_form('see'), 'seeing')
self.assertEqual(make_ing_form('move'), 'moving')
self.assertEqual(make_ing_form('hug'), 'hugging')
if __name__ == "__main__":
unittest.main()
| true |
6c910a9ca06e2751b264a6169b3207bbd80cc0f1 | scperkins/46-python-exercises | /VerySimpleExercises/caesar_cipher.py | 2,176 | 4.5625 | 5 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
In cryptography, a Caesar cipher is a very simple encryption techniques in
which each letter in the plain text is replaced by a letter some fixed number
of positions down the alphabet. For example, with a shift of 3, A would be
replaced by D, B would become E, and so on. The method is named after Julius
Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13
places") is a widely used example of a Caesar cipher where the shift is
13. In Python, the key for ROT-13 may be represented by means of the following
dictionary:
Your task in this exercise is to implement an encoder/decoder of ROT-13. Once
you're done, you will be able to read the following secret message:
Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
Note that since English has 26 characters, your ROT-13 program will be
able to both encode and decode texts written in English.
"""
import unittest
alphabet = {
'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s','g':'t',
'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a',
'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h',
'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O',
'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V',
'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 'O':'B', 'P':'C',
'Q':'D', 'R':'E', 'S':'F','T':'G', 'U':'H', 'V':'I', 'W':'J',
'X':'K', 'Y':'L', 'Z':'M'
}
def encode_rot_13(string):
encoded = ''
for char in string:
for k, v in alphabet.items():
if k == char:
encoded += v
return encoded
def decode_rot_13(string):
decoded = ''
for char in string:
for k, v in alphabet.items():
if v == char:
decoded += k
return decoded
class TestEncodeDecode(unittest.TestCase):
def test_encode(self):
self.assertEqual(encode_rot_13('hello'), 'uryyb')
def test_decode(self):
self.assertEqual(decode_rot_13('uryyb'), 'hello')
if __name__ == "__main__":
print(decode_rot_13('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!'))
unittest.main()
| true |
2de015e65be35324f733b72e96fd1a577bea6923 | scperkins/46-python-exercises | /VerySimpleExercises/string_length.py | 596 | 4.3125 | 4 | #-*- coding: utf-8 -*-
#! /usr/bin/env python
"""
Define a function that computes the length of a given list or string. (It is
true that Python has the len() function built in, but writing it yourself is
nevertheless a good exercise.)
"""
import string
import random
def string_length(my_string):
return sum(1 for l in my_string)
if __name__ == "__main__":
rand = random.randint(0,100)
random_string =''.join(random.choice(string.ascii_lowercase) for _ in range(rand))
print('Standard len method:', len(random_string))
print('My len method:', string_length(random_string))
| true |
26001d673621c0765dda9939776398409e442409 | scperkins/46-python-exercises | /VerySimpleExercises/is_member.py | 716 | 4.1875 | 4 | #-*- coding: utf-8 -*-
#! /usr/bin/env python
"""
Write a function is_member() that takes a value (i.e. a number, string, etc) x
and a list of values a, and returns True if x is a member of a, False
otherwise. (Note that this is exactly what the in operator does, but for the
sake of the exercise you should pretend Python did not have this operator.)
"""
def is_member(elem, seq):
#We're going to try this without using the 'in' operator at all.
i = 0
while i < len(seq):
if elem == seq[i]:
return True
i += 1
if __name__ == "__main__":
print('Should return True:', is_member('a', ['b','c','d','a']))
print('Should return None:', is_member('a', ['z','x','f','c']))
| true |
76829f1ce1e61b772e4e17a54cc65c08a7c952e6 | xpgeng/leetcode | /Python/Reverse_Bits.py | 637 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
"""
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
bin_n = '{0:032b}'.format(n)
revese_num = int(bin_n[::-1], 2)
print (revese_num)
if __name__ == '__main__':
Solution().reverseBits(43261596) | true |
18ba7316d6c7f6a644e9e32aca18cd2320e019e1 | Igor-Felipy/Exercises | /CursoEmVideo/aula10a.py | 214 | 4.125 | 4 | tempo = int(input('Quantos anos te seu carro? '))
print('Carro novo' if tempo<=3 else 'Carro velho')
if tempo<=3:
print('Carro novo')
else:
print('Carro velho')
print('___________FIM____________')
| false |
4a59bdefc580f8a567726a6ffb6d680144e4bd31 | rurata/python_practice | /pythagorean.py | 397 | 4.34375 | 4 |
print "Please enter the triangle side lengths to check if a right triangle."
sides=[0,0,0]
for x in range(3):
while True:
try:
num=str(x+1)
side=raw_input("Side "+num+": ")
s=float(side)
break
except ValueError:
print "Enter a number!"
sides[x]=s
sides.sort()
if (sides[2]**2==sides[0]**2+sides[1]**2):
print "Yes! It is a right triangle!"
else:
print "This isn't right!" | true |
72b3a792572f66e326950e5a970f7f0232fc461a | serggukov/learn-python-adv-it | /Lesson-8-Lists1.py | 679 | 4.3125 | 4 | cities = ['Moscow','Washington','Beijing','Paris','Berlin']
print(cities)
print(len(cities))
print("#update")
print("city №3 is\t", cities[2])
print("last city is\t", cities[-1])
cities[2] = 'Tokyo'
print(cities)
print("#add")
cities.append('Madrid')
cities.insert(1, 'Saint-Petersburg')
print(cities)
print(len(cities))
print("#delete")
del cities[-1]
print(cities)
cities.remove('Washington')
print(cities)
deleted_city = cities.pop()
print("deleted city is\t", deleted_city)
print("#reverse")
cities.reverse()
print(cities)
print("#sort")
cities.sort()
print(cities)
cities.sort(reverse=True)
print(cities)
print("#output")
for item in cities:
print(item) | false |
3cc3b97488bc18b5b0d717a4da8bec4aa527a775 | lukasmyth96/nuvox-mobile-backend | /nuvox_algorithm/utils/string_funcs.py | 776 | 4.125 | 4 | from typing import List
from nuvox_algorithm.utils.list_funcs import all_subsequences
def all_char_subsequences(a_str: str) -> List[str]:
"""Returns all subsequences of characters in a string.
Notes
------
- This is not the same as all sub-strings because the
returned list includes strings where the characters are
not adjacent in the original string.
- The only requirement on the subsequences of characters
is that the characters are in the same order as they
appear in the original string.
Examples
--------
- 'aba' --> ['a', 'b', 'a', 'ab', 'aa', 'ba', 'aba']
- 'abc' --> ['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
"""
return [''.join(char_subsequence) for char_subsequence in all_subsequences(list(a_str))]
| true |
62af3c4295d04ada8594e9dc1b04a3f331854928 | Emily-chiu/Kata | /Convert_a_String_to_a_Number.py | 571 | 4.3125 | 4 | # Description
# We need a function that can transform a string into a number. What ways of achieving this do you know?
# Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.
# test.assert_equals( string_to_number("1234"), 1234)
# test.assert_equals( string_to_number("605"), 605)
# test.assert_equals( string_to_number("1405"), 1405)
# test.assert_equals( string_to_number("1234"), 1234)
def string_to_number(s):
# ... your code here
s = int(s)
return s
print(string_to_number("1234")) | true |
454ee581a62031a81e208d6040a431da69a1a1ae | devscheffer/SenacRS-Algoritmos-Programacao-3 | /Task_6/Sorts/selection.py | 408 | 4.125 | 4 | def selection_sort(arr):
n=len(arr)
for i in range(n):
## to store the index of the minimum element
min_element_index = i
for j in range(i + 1, n):
## checking and replacing the minimum element index
if arr[j] < arr[min_element_index]:
min_element_index = j
## swaping the current element with minimum element
arr[i], arr[min_element_index] = arr[min_element_index], arr[i]
return arr
| true |
1d2778d8e9c7f5942c3cfacd84c3c3c6e0177131 | jjcrab/code-every-day | /day6.py | 519 | 4.25 | 4 | # Remember the triangle of balls in billiards? To build a classic triangle(5 levels) you need 15 balls. With 3 balls you can build a 2-level triangle, etc.
# For more examples,
# pyramid(1) == 1
# pyramid(3) == 2
# pyramid(6) == 3
# pyramid(10) == 4
# pyramid(15) == 5
# Write a function that takes number of balls(≥ 1) and calculates how many levels you can build a triangle.
def pyramid(balls):
level = 0
while level < balls:
level += 1
balls -= level
return level
print(pyramid(21))
| true |
ad08f0fc94429890a0138641f8a2ec324ef5cd90 | jjcrab/code-every-day | /day48_mergeSort.py | 1,942 | 4.15625 | 4 | # Sort Integers II
'''
Description
Given an integer array, sort it in ascending order in place. Use quick sort, merge sort, heap sort or any O(nlogn) algorithm.
Example
Example1:
Input: [3, 2, 1, 4, 5],
Output: [1, 2, 3, 4, 5].
Example2:
Input: [2, 3, 1],
Output: [1, 2, 3].
'''
class Solution:
"""
@param A: an integer array
@return: nothing
"""
def sortIntegers2(self, A):
temp = [0 for _ in range(len(A))]
self.merge_helper(0, len(A) - 1, A, temp)
def merge_helper(self, start, end, A, temp):
# end case
if start >= end:
return
mid = (start + end)//2
self.merge_helper(start, mid, A, temp)
self.merge_helper(mid + 1, end, A, temp)
self.merge(start, mid, end, A, temp)
def merge(self, start, mid, end, A, temp):
# merge two sides, left side start from start, right side start from mid + 1
left, right = start, mid + 1
# record the index of element
index = start
# compare left side each element to right side each element (both are from thier most left position since already sorted)
while left <= mid and right <= end:
if A[left] < A[right]:
temp[index] = A[left]
left += 1
else:
temp[index] = A[right]
right += 1
index += 1
# after comparing, if left side still have elements not put in temp list, put them into temp list
while left <= mid:
temp[index] = A[left]
left += 1
index += 1
# after comparing, if right side still have elements not put in temp list, put them into temp list
while right <= end:
temp[index] = A[right]
right += 1
index += 1
# copy temp list to original list
for index in range(start, end + 1):
A[index] = temp[index]
| true |
858e5bcce31dbcafaa377295c79e03c328915a0e | Dmytro9/python | /udemy_lessons/if_statement.py | 282 | 4.1875 | 4 | if True:
print("Something")
if 3 > 2:
print("Yes")
num1 = 100
num2 = 50
if num1 > num2:
print("num1 > num2")
else:
print("num2 > num1")
num1 = 100
num2 = 100
if num1 > num2:
print("num1 > num2")
elif num2 > num1:
print("num2 > num1")
else:
print("num2 = num1")
| false |
44b1541d0374a524dd87d7e7d7a3150d10bff5dc | Torrespan/python3 | /examples/9.6.type.py | 966 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Hello(object):
def hello(self, name='World'):
print('Hello, %s.' % name)
h = Hello()
h.hello()
# 类, 它的类型是 'type'
print(type(Hello)) # <class 'type'>
# 对象, 它的类型就是 Hello
print(type(h)) # <class '__main__.Hello'>
# 通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义
# 先定义函数
def fn(self, name="world"):
print('hello, %s. ' % name)
# 创建 Hello class
Hello = type('Hello', (object,), dict(hello=fn))
h = Hello()
h.hello()
print(type(Hello)) # <class 'type'>
print(type(h)) # <class '__main__.Hello'>
"""
要创建一个class对象,type()函数依次传入3个参数:
1.class的名称;
2.继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上
"""
| false |
9f21ef4623e9d533173870c3ed4428e156b518fc | Shiji-Shajahan/Python-Programs | /Lesson 5 Strings and lists Homework.py | 2,078 | 4.59375 | 5 | #Lesson 5 Homework
print('Homeork Execise1')
#Create a string a = “hello world”.
a1="hello"
a2="world"
a= a1+' '+a2
print(a)
#Find out what a.endswith("world") is doing. Formulate generally what string1.endswith(string2) is doing
print(a.endswith("world"))
a3="shiji"
print(a.endswith(a3))
#.endswith check whether the string named a ends with string world, since its correct the code output shows "True" otherwise the output is "False"
string1= "Good Morning"
print(string1)
string2="Morning"
print(string2)
print(string1.endswith(string2))
string3="Evening"
string4="Good"
print(string1.endswith(string3))
#string1.endswith(string2) checks the ending word of string 1 is string 2, and if it is correct the ouput is "True" otherwise it will give a output as "False"
#Find out what a.startswith("world") is doing. Formulate generally what string1.startswith(string2) is doing.
print(a.startswith("world"))
print(string1.startswith(string2))
#string1.startswith(string2) is used to check whether the string 1 starts with string 2 if its correct it shows True otherwise "Fasle"
print(a.startswith(a1))
print(string1.startswith(string4))
print('\n')
print('\n')
print('Homeork Execise2')
#Create a string str1 = "I love Python"
#a) Find out what str1.lower() is doing. Formulate generally what str.lower() is doing.
str_1="I"
str_2="love"
str_3="Python"
str1= str_1+" "+str_2+" "+str_3
print(str1)
print(str1.lower())
str4= "I"
str5="am"
str6="from"
str7="India"
str8= str4+" "+str5+" "+str6+" "+str7
print(str8)
print(str8.lower())
#str.lower() is used to change all capital letters in the string to small letters.
#b) Find out what str1.upper() is doing. Formulate generally what str.upper() is doing.
print(str1.upper())
print(str8.upper())
#str.upper() is used to change all small letters in the string to capital letters.
#c) Find out what str1.swapcase() is doing. Formulate generally what str.swapcase() is doing.
print(str1.swapcase())
print(str8.swapcase())
#str.swapcase() is used to change all capital letters in the string to small letters and vice versa
| true |
a6993cad9f87e3c828345c5404817dd3c8bc6803 | Shiji-Shajahan/Python-Programs | /Lesson 4 strings and inputs exercises.py | 948 | 4.46875 | 4 | #Exercise 1 – String Operation
#Write a program that prints a shopping list as following:
print("shopping list:\n\t*bread\n\t*milk\n\t*coffee\n\t*bananas")
print()
#Exercise 2 – Input
"""
1) Ask the user of your program to enter following information:
- Name
- Month of birth
- Year of birth
Once the information is provided, print following message:
"Hello {user_name}, by the next {birth_month} you will be {user_age} years old!"
2) Write a small program (2 lines of code :)) that asks the user to enter a text and prints the length of the input text.
"""
user_name= input('please enter your name:')
birth_month= input('please enter your month of birth:')
year_of_birth= input('please enter your year of birth:')
user_age= (int(2020) - int(year_of_birth))
print(user_age)
print(f'Hello {user_name},by the next {birth_month}, you will be {user_age} years old!')
your_name= input('please enter your official name')
print(len(your_name)) | true |
7254aab3b5ca24c0bc049be782b16596abe8d8f0 | HzDmS/algorithm_python | /merge_sort/merge_sort.py | 1,380 | 4.1875 | 4 | """ Python implementation of mergeSort. """
import random
import time
def merge(arr, low, mid, high):
""" in-place merge
Parameters
----------
arr: list
low: int, index of the first element.
mid: int, index of the middle element.
high: int, index of the last element.
"""
left = arr[low: mid + 1]
right = arr[mid + 1: high + 1]
i, j, k = 0, 0, low
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
k += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
def merge_sort(arr, low, high):
""" in-place merge sort
Parameters
----------
arr: list
low: int, index of the first element.
high: int, index of the last element.
"""
if low >= high:
return
mid = low + (high - low) // 2
merge_sort(arr, low, mid)
merge_sort(arr, mid + 1, high)
merge(arr, low, mid, high)
if __name__ == "__main__":
arr = [random.randint(0, 1000) for _ in range(int(1e4))]
start = time.time()
merge_sort(arr, 0, len(arr) - 1)
end = time.time()
print("total time: {:3f}".format(end - start))
| false |
de27ad231168d56b2f9fda3566f73ccd631a82b3 | ahephner/pythonUdemy | /Python basics/scoping.py | 1,734 | 4.6875 | 5 | #calling global will update the global value from inside a fungtion
#function reference local then global
#
# num = 5
# def func1():
# num = 3
# print(num)
# def func2():
# global num
# double_num = num * 2
# num = 6
# print(double_num)
# func1() => 3
# func2() => 10 but value of global num is 6
# Create a string: team
team = "teen titans"
# Define change_team()
def change_team():
"""Change the value of the global variable team."""
# Use team in global scope
global team
# Change the value of team in global: team
team = 'justice league'
#call function without calling team still equals team titans
change_team()
# Print team
print(team) #-> justice league
# Nested functions
# Define three_shouts
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings have to pass it to the inner function!!
return (inner(word1), inner(word2), inner(word3))
# Call three_shouts() and print
print(three_shouts('a', 'b', 'c'))
#closure notice how inner function has the ability to go to the outter function and get a value in this case n
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
# Call echo: twice
twice = echo(2)
# Call echo: thrice
thrice = echo(3)
# Call twice() and thrice() then print
print(twice('hello'), thrice('hello'))
| true |
02d37bbfef4d098b8faff1b40f0f013a015cdad1 | knitdance/Beginner-python-projects | /diceroll.py | 528 | 4.15625 | 4 | import random
print("Your first roll is", random.randint(1,6))
roll_again = input("Would you like to roll again?:")
while roll_again.lower() == ("y" or "yes"):
print("Your dice says", random.randint(1,6))
roll_again = input("Would you like to roll again?:")
if roll_again.lower() != ("y" or "yes"):
print("Goodbye")
#Learning point - the key thing here is if there are
#two conditions after == THERE MUST BE BRACKETS AROUND THEM
#OR EVERYTHING FUCKS UP.
#There is no need to add the if bit - just seems more polite.
| true |
bd075e6d4f5b045b75c9610c14ae1b16f2b669a1 | gabecagnazzi/BIS-397-497-CagnazziGabe | /Assignment 2 - 3.6.py | 662 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 15:03:20 2020
@author: gabecagnazzi
"""
#Assignment 2-3.6: Turing Test
input("What is your problem? ")
userInput = str(input("Have you had this problem before (yes or no)? "))
if userInput == 'yes':
print("Well, you have it again.")
else:
print("Well, you have it now.")
# answer to the follow up question: this conversation would most likely not
#convince the user that the entity on the other end exhibited intelligent behavior
# because it did not help them with their problem merely gave scripted responses
# with zero artificial thinking done by the computer
| true |
5325f6872d2a94c3b66ce092df0275d80a6ee9c7 | prasad01dalavi/python_basics | /04.Dictionary.py | 1,606 | 4.75 | 5 | dictVariable = {'Name': 'Prasad', 'Age': 23, 'Class': 'First'} # declaring a dictionary
# 'Name','Age','Class' are called keys of dictionary which holds the value
# Accessing values of dictionary using key
print "dictVariable['Name'] =", dictVariable['Name'] # Prasad
print "dictVariable['Age'] =", dictVariable['Age'] # 23
# if we try to access the data which is not in the dictionary it will produce error
# e.g if we write print dictVariable['Education']
# because Education key is not present in the dictionary
print "Length of Dictionary =", len(dictVariable) # 3
# Returns a list of dictionary's (key,value) tuple pairs
print 'List of Dictionary Items =', dictVariable.items()
# [('Age', 23), ('Name', 'Prasad'), ('Class', 'First')]
print 'Keys of Dictionary =', dictVariable.keys() # ['Age', 'Name', 'Class']
print 'Values of Dictionary =', dictVariable.values() # [23, 'Prasad', 'First']
# Updating Dictionary
dictVariable['Age'] = 24
print 'My Dictionary =', dictVariable # [23, 'Prasad', 'First']
dictVariable['Degree'] = 'B.Tech' # Adding new key-value
print dictVariable
# {'Age': 24, 'Name': 'Prasad', 'Degree': 'B.Tech', 'Class': 'First'}
del dictVariable['Degree'] # Deleting dictionary elements
print 'After deleting key Degree =', dictVariable
# {'Age': 24, 'Name': 'Prasad', 'Class': 'First'}
dictVariable.clear() # Remove all the entries but do not delete it
print 'cleared Dictionary =', dictVariable # {}
del dictVariable # Delete entire dictionary
print dictVariable # Shows error because we have deleted it
| true |
7e287166b7b430ab49534cdfffbebc862c9caa96 | prasad01dalavi/python_basics | /11.isAndin.py | 502 | 4.15625 | 4 | string = "abcde"
if 'a' in string: # a is in string or not. if it is present then true
print 'yes! a in string'
if 'ab' in string:
print 'yes! ab in string'
myList1 = [1, 2, 3]
myList2 = [1, 2, 3]
if myList1 is myList2: # it is not similar to == so this if will not execute
print 'Yes! my two list are having same contents'
anotherlist1 = anotherlist2 = [1, 2, 3]
if anotherlist1 is anotherlist2: # but it is similar to ==
print 'This works actually!'
| true |
f5bca5b45eabf2a69140bca2d073ddc8fc571cb8 | prasad01dalavi/python_basics | /21.overriding.py | 512 | 4.125 | 4 | class Parent:
def my_method_1(self):
print 'This is parent class method 1'
def my_method_2(self):
print 'This is parent class method 2'
class Child(Parent): # Child class inheriting the properties from parent class
def my_method_2(self):
print 'This is child class method 2'
child_object = Child()
child_object.my_method_1() # Child class using Parent class properties (methods)
child_object.my_method_2() # Parent class method has been overrided by Child class
| true |
e91f83a0047fa87d5431dc60d002497079da2309 | miguelabragonz/functions | /functionDrills.py | 2,811 | 4.53125 | 5 | '''
@author: amayamunoz
'''
'''
For this assignment you should read the task, then below the task do what it asks you to do.
For tasks with return statements, you can test out if you are correct by
calling the function and printing what is returned
EXAMPLE TASK:
'''
#EX) Define a function that adds two numbers and returns the result
def add_two_numbers(num1, num2):
sumOfTwoNumbers = num1 + num2
return sumOfTwoNumbers
'''
END OF EXAMPLE
'''
'''
START HERE
'''
#1) Define a function that subtracts the second number from the first number. Return the result.
def subtractions(num1,num2):
diOfNumbers = num2 - num2
return diOfNumbers
#2) Define a function that divides a number by 2, multiplies it by 77, and then adds 10000. Return the result.
def division(num):
finalNumber = ((num/2)*77) + 10000
return finalNumber
#3) Define a function that checks if two numbers are equal. If they are equal, return true. If they are not equal, return false.
def equalCheck(num1, num2):
if num1 == num2:
return"True"
else:
return"False"
#4) Define a function that takes in two numbers and returns the larger number. If they are the same, it should just return that number.
def checkGreater(num1, num2):
if num1> num2:
return num1
elif num1 == num2:
return num1
else:
return num2
#5) Define a function that takes in two words and returns a string that contains both words combined.
str1 = ""
str2 = ""
def combineString(str1, str2):
finalString = str(str1 + "" + str2)
return finalString
#6) Define a function that takes in three numbers. If the first number is equal to the second OR the third number, return true. Else, return false.
def coolNum(num1, num2, num3):
if num1 == num2 or num1 == num3:
finalAnswer = "True"
else:
finalAnswer = "False"
return finalAnswer
#7) Define a function that prints your name.
def myName(name):
return name
name = ""
#8) Define a function that takes in a string that is the name of a color. If that string is equal to your favorite color, it prints "That's my favorite color!" If it is not, it prints "That is not my favorite color. Try again."
favoriteColor = "blue"
def checkColor(newColor):
if newColor == favoriteColor:
answer = ("That's my fovorite color")
else:
answer = ("That's not my favorite color. Try Again")
return answer
#9) Define a function that takes in a number. If the number is not equal to zero, the function runs a loop until the number reaches 0. HINT: Within the loop, keep subtracting 1 from the number.
'''YOUR OWN FUNCTION'''
#10) Create your own function that solves any problem you can think of.
def subtraction(num1,num2):
difference = num1 - num2
return difference
| true |
2f95226f032a8a7d6ff2838eec8992991132383d | Eshwar-n-kumar/Eshwar-n-kumar | /Mypractice/CompositionInheritance.py | 1,524 | 4.78125 | 5 | # class Engine:
# '''THis is a program to demonstrate the concept of composition in Inheritance (HAS-A relationship)'''
# a = 10
# def __init__(self):
# self.b = 20
# def m1(self):
# print("Engine specific funcitonality")
# class Car:
# def __init__(self):
# self.engine = Engine()
# def m2(self):
# print("Class Car using Engine Functionality")
# print(self.engine.a)
# print(Engine().a)
# print(self.engine.b)
# self.engine.m1()
# c = Car()
# c.m2()
class Car:
"""Employee HAS - A Car relationship"""
def __init__(self, name, model, colour):
self.name = name
self.model = model
self.colour = colour
def getInfo(self):
print("\tCar name:", self.name)
print("\tCar model:", self.model)
print("\tCar colour:", self.colour)
class Employee:
def __init__(self, empName, empId, empCar ):
self.empName = empName
self.empId = empId
self.empCar = empCar # A method of one class can access other class functionality by simply creating object. This is HAS - A relationship
def empInfo(self):
print("Emp name:",self.empName)
print("Emp ID:",self.empId)
print("Emp Car Information....")
self.empCar.getInfo() # By using car..it accesses getinfo(). Therefore, Employee class using car class functionality.
car = Car("Innova", "2011", "Grey")
emp = Employee("Shiva", "112233", car) # We pass car object here
emp.empInfo() | false |
4ac0e42e181e28b87bb5755b0aa88690e6151a2d | ldonlytest/learnPython3 | /ex16.py | 761 | 4.15625 | 4 | # -*- coding:utf-8 -*-
from sys import argv
"""
open
"""
script,filename=argv
print("We're going to erase %r."%(filename))
print("If you don't eant that ,hit CTR-C(^C)")
print("If you do want that,hit RETURN")
input("?")
print("Opening the file...")
target=open(filename,"w")
print("Truncating the file,Goodbye")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input("line1: ")
line2 = input("line2: ")
line3 = input("line3: ")
print("I'm going to write these to the file")
target.write("%s\n%s\n%s"%(line1,line2,line3))
print("And finally,we close it.")
target.close()
print("Openging the file")
file=open(filename,"r")#访问模式 r w a,修饰符+,表示可同时读写
print(file.read())
print("Closing the file")
file.close()
| true |
43bb9bbc4a87445a1837d3a7b09964a0d8a53b1c | HaleSmith/corey-schafer-youtube-tutorials | /object_oriented/3_class_and_static_methods.py | 2,495 | 4.15625 | 4 | # References https://www.youtube.com/watch?v=rq8cL2XMM5M
# Regular methods in a class default take instance as first argument
# Class methods in a class default take class as first argument
# Static methods take neither as first argument, and don't operate on
# instance or on class
class Employee:
num_of_emps = 0 # Tracker used to count number instances
raise_amt = 1.04 # Class variable
# self refers to the instance of the class
def __init__(self, first, last, pay): # Creates an instance
self.first = first
self.last = last
self.pay = pay
self.email = f'{first}.{last}@company.com'
Employee.num_of_emps += 1
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
# Need to access class variable via instance/class
# Could also use Employee.raise_amount
self.pay = int(self.pay * self.raise_amount)
@classmethod # Decorator for defining a class method
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod # Alternative constructor via class method
# 'from' is common convention for naming - from_array, etc.
# See datetime.py (common library) for examples
def from_string(cls, emp_str):
# Data is in string form
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
@staticmethod # Decorator for defining static method
# Doesn't access instance or class anywhere in function
def is_workday(day):
if day.weekday() == 5 or day.weekday == 6:
return False
return True
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
print(Employee.raise_amt)
print(emp_1.raise_amt)
print(emp_2.raise_amt)
Employee.set_raise_amt(1.05) # Same as Employee.raise_amt = 1.05
print("Raise amount set via class method")
print(Employee.raise_amt) # Could be run on an instance too
print(emp_1.raise_amt)
print(emp_2.raise_amt)
print("\n------ String parsing below\n")
emp_str_1 = 'John-Doe-70000'
emp_str_2 = 'Steve-Smith-30000'
emp_str_3 = 'Jane-Doe-90000'
first, last, pay = emp_str_1.split('-')
new_emp_1 = Employee(first, last, pay)
print(new_emp_1.email, new_emp_1.pay) # From manual parsing
new_emp_2 = Employee.from_string(emp_str_2)
print(new_emp_2.email, new_emp_2.pay) # From alternative constructor
print("\n------ Static methods below\n")
import datetime
my_date = datetime.date(2016, 7, 9)
print(Employee.is_workday(my_date))
| true |
842b317fb918a28d0834b886349a77ad8ffceaa1 | HaleSmith/corey-schafer-youtube-tutorials | /function_control/else_clause_in_loops.py | 1,532 | 4.125 | 4 | # References https://www.youtube.com/watch?v=Dh-0lAyc3Bc
# In a for loop, should think of else as "no-break"
# Separator for print output
def new_section(message):
print(f"\n--- {message} ---\n")
new_section("Else in a for loop without break")
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
else: # Think of this as a no-break
print("Hit the for/else statement")
new_section("Else in a for loop with break")
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
if i == 3:
break
else: # Think of this as a no-break
print("Hit the for/else statement")
new_section("Else in a while loop without break")
i = 1
while i <= 5:
print(i)
i += 1
else: # Think of this as a no-break
print("Hit the for/else statement")
new_section("Else in a while loop with break")
i = 1
while i <= 5:
print(i)
i += 1
if i == 4:
break
else: # Think of this as a no-break
print("Hit the for/else statement")
new_section("Example: finding an index success")
def find_index(to_search, target):
for i, value in enumerate(to_search):
if value == target:
break
else:
return -1
return i
my_list = ['Corey', 'Rick', 'John']
index_location = find_index(my_list, 'Rick')
print(f"Location of target is index: {index_location}")
new_section("Example: finding an index fail")
# Went through whole list and found nothing, so did else statement
index_location = find_index(my_list, 'Steve')
print(f"Location of target is index: {index_location}") | true |
1d583aa145a173284e32157065d4699f761d7750 | HaleSmith/corey-schafer-youtube-tutorials | /data_structures/comprehensions.py | 2,757 | 4.40625 | 4 | # References https://www.youtube.com/watch?v=3dt4OGnU5sM
# Separator for print output
def new_section(message):
print(f"\n---{message}---\n")
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("\nExample 1: Give 'n' for each 'n' in nums\n")
my_list = []
for n in nums:
my_list.append(n)
print(my_list)
print("\nExample 2: Each n in nums with less syntax\n")
my_list = [n for n in nums]
print(my_list)
print("\nExample 3: 'n*n' for each n in nums\n")
my_list = []
for n in nums:
my_list.append(n*n)
print(my_list)
new_section("Example 4: n^2 via comprehension syntax")
my_list = [n*n for n in nums]
print(my_list)
new_section("Maps and lambdas")
# Runs through an anonymous function lambda
my_list = map(lambda num: num*num, nums) # Doesn't work that well
print(my_list)
new_section("n in nums if n is even")
my_list = []
for n in nums:
if n % 2 == 0:
my_list.append(n)
print(my_list)
new_section("n in nums if n is even via comprehensions")
my_list = [n for n in nums if n % 2 == 0]
print(my_list)
new_section("filter and lambda function for n if even")
# Tutorial does not return an address, but rather same as above
my_list = filter(lambda n: n % 2 == 0, nums) # Returns an address
print(my_list)
new_section("Multi list comprehensions via loop")
# A letter number pair for each letter in abcd and num in 0123
my_list = []
for letter in 'abcd':
for num in range(4):
my_list.append((letter, num))
print(my_list)
new_section("Multi list comprehensions without loop")
my_list = [(letter, num) for letter in 'abcd' for num in range(4)]
print(my_list)
new_section("Dictionary comprehension with loop")
names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heroes = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
# Prints object address, but in tutorial printed a list of tuples
print(str(zip(names, heroes)))
my_dict = {}
# Zip merges lists together into tuples
for name, hero in zip(names, heroes):
my_dict[name] = hero
print(my_dict)
new_section("Dictionary comprehension without loop and not including Peter")
my_dict = {name: hero for name, hero in zip(names, heroes) if name != 'Peter'}
print(my_dict)
new_section("Set comprehensions via loop")
nums = [1, 1, 2, 1, 3, 4, 3, 4, 5, 5, 6, 7, 8, 7, 9, 9]
my_set = set()
for n in nums:
my_set.add(n)
print(my_set)
new_section("Set comprehensions without loop")
my_set = {n for n in nums}
print(my_set)
new_section("Generator expressions via loop")
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def gen_func(nums):
for n in nums:
yield n*n
my_gen = gen_func(nums)
for i in my_gen:
print(i)
del gen_func, my_gen
new_section("Generator expression via reduced syntax")
my_gen = (n*n for n in nums)
for i in my_gen:
print(i) | false |
867007c9b87141a4bb0d50f8d37b364c0df07e23 | HaleSmith/corey-schafer-youtube-tutorials | /beginner_intro/conditionals_and_control_statements.py | 1,378 | 4.25 | 4 | # Comparisons:
# Equal: ==
# Not Equal: !=
# Greater Than: >
# Less Than: <
# Greater or Equal: >=
# Less or Equal: <=
# Object Identity: is
# False Values:
# False
# None
# Zero of any numeric type
# Any empty sequence. For example, '', (), [].
# Any empty mapping. For example, {}.
language = 'Python'
if language == 'Python':
print("Language is Python")
elif language == 'Java':
print("Language is Java")
elif language == 'JavaScript': # No switch/case in Python
print("Language is JavaScript")
else:
print("No match")
# and, or, not are boolean operators
user = 'Admin'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page')
else:
print('Bad credentials')
if not logged_in:
print("Please log in")
else:
print("Welcome")
# Object type testing
# 'is' is the same as id(a) == id(b)
a = [1, 2, 3]
b = [1, 2, 3]
c = b
print(a == b)
print(a is b)
print(b is c)
print(id(a), id(b), id(c))
condition = None
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
condition = 0
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
condition = 0.00001
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
condition = {}
if condition:
print('Evaluated to True')
else:
print('Evaluated to False')
| true |
0c1026d33e114b4575aeaf29b53924ac3344f71d | doohinkus/rockPaperScissorsPython | /rps.py | 1,862 | 4.125 | 4 | # import random number specifically integers
from random import randint
#create a list of computer choice options, list starts at 0. 0=Rock, 1=Paper...
choices = ["Rock", "Paper", "Scissors"]
#assign a random number that corresponds to one of the above choices
computerChoice = choices[randint(0,2)]
#set playing to true
playing = True
while playing == True:
#Use raw_input for 2.7 just input for later versions of python
playerChoice = raw_input("Rock, Paper, Scissors? (Type 'q' to quit)\n")
# if player chooses "q" break out the loop
if playerChoice == "q":
playing = False
# player choice is the same as the computer's choice
elif playerChoice == computerChoice:
print("Tie!")
# player choice is rock
elif playerChoice == "Rock" and computerChoice == "Scissors":
print("You win! " + playerChoice + " smashes " + computerChoice)
elif playerChoice == "Rock" and computerChoice == "Paper":
print("You lose! " + computerChoice + " covers " + playerChoice)
# player choice is paper
elif playerChoice == "Paper" and computerChoice == "Rock":
print("You win! " + playerChoice + " covers " + computerChoice)
elif playerChoice == "Paper" and computerChoice == "Scissors":
print("You lose! " + computerChoice + " covers " + playerChoice)
# player choice is scissors
elif playerChoice == "Scissors" and computerChoice == "Paper":
print("You win! " + playerChoice + " cut " + computerChoice)
elif playerChoice == "Scissors" and computerChoice == "Rock":
print("You lose! " + computerChoice + " crushes " + playerChoice)
# player entered something other than a valid choice
else:
print("That's not a valid play. Check your spelling!")
# make another random choice for the computer
computerChoice = choices[randint(0,2)]
| true |
3768fbb9fe453c92aa516d5a77fa2a7c1c5b4c41 | prashanthhn25/git_basics | /for_loop.py | 623 | 4.1875 | 4 | a="Hello World"
'''
for i in a:
print (i)
for i in a:
print (i)
else:
print("Else executed")
#track the index of for loop using enumerate
#works with integers
for x,y in enumerate(a): #x is index and y is value
print(x,y)
#reverse the string
for x in a[::-1]:
print(x)
#range function
for i in range(0, 100):
print(i)
#same as above value
for i in range(100):
print(i)
#print the value in increment of 2
for i in range(0, 100, 2):
print(i)
'''
#using enumerator in for loop
for i,j in enumerate(range(0, 100,5)):
print(i,j)
| true |
985b549464efca2c86427bd73d3fa4711de1a670 | MRS88/python_basics | /week_4_functions/is_point_in_circle.py | 860 | 4.25 | 4 | '''Даны пять действительных чисел: x, y, xc, yc, r.
Проверьте, принадлежит ли точка (x,y) кругу с центром (xc, yc) и радиусом r.
Если точка принадлежит кругу, выведите слово YES, иначе выведите слово NO.
Решение должно содержать функцию IsPointInCircle(x, y, xc, yc, r),
возвращающую True, если точка принадлежит кругу и False, если не принадлежит.
'''
from math import sqrt
def IsPointInCircle(x, y, xc, yc, r):
section = sqrt((xc - x)**2 + (yc - y)**2)
return 'YES' if section <= r else 'NO'
x, y = float(input()), float(input())
xc, yc, r = float(input()), float(input()), float(input())
print(IsPointInCircle(x, y, xc, yc, r))
| false |
d4c400484052aab847bc8de4f2117d6216bcc041 | MRS88/python_basics | /week_5_tuples_cycles_lists/wonderful_numbers.py | 436 | 4.21875 | 4 | '''Найдите и выведите все двузначные числа, которые равны удвоенному
произведению своих цифр.
Формат ввода
Программа не требует ввода данных с клавиатуры,
просто выводит список искомых чисел.'''
for i in range(10, 100):
if 2 * (i // 10) * (i % 10) == i:
print(i)
| false |
764f7fa14b9cdc9852bedefe7ca8995be0e82442 | abhimishra01/DeepLearningForAudio | /basic/mlp_forwardProp.py | 1,451 | 4.21875 | 4 | # implementing a multi layer perceptron
import numpy as np
class MLP:
def __init__(self, n_inputs=3, n_hidden=[3,3], n_outputs=2):
self.n_inputs = n_inputs
self.n_hidden = n_hidden
self.n_outputs = n_outputs
# total layers present in a this MLP
# LOL - List of lists
layers = [self.n_inputs] + self.n_hidden + [self.n_outputs]
# initiating random weights matrix
weights = []
for i in range(len(layers)-1):
curr_weights = np.random.rand(layers[i],layers[i+1])
weights.append(curr_weights)
self.weights = (weights)
# forward propagation method
def forward_prop(self, inputs):
# calculating net inputs / weighted sum
for w in self.weights:
net_inputs = np.dot(inputs,w)
# calculating activation
activations = self._sigmoid(net_inputs)
return activations
def _sigmoid(self, net_inputs):
return 1 / 1 + np.exp(net_inputs)
if __name__ == "__main__":
# creating MLP network / Neural network
mlp = MLP() # using default values of MLP for now
# creating random inputs
inputs = np.random.rand(mlp.n_inputs) # n_inputs = n_neurons
# forward propagation
output = mlp.forward_prop(inputs)
print("The inputs given to MLP are {}\n", format(inputs))
print("The output given from the MLP layer is {}\n", format(output)) | true |
a2f4a8f4fa36f43a3625d1709c75ebeffb5b394b | RoseGreene/Homework | /about_user.py | 277 | 4.34375 | 4 | my_dict = {}
name = input("Enter you name: ")
age = int(input("Enter your age: "))
city = input("Where do you live? ")
month = input("Enter the month you were born: ")
my_dict["name"]=name
my_dict["age"]=age
my_dict["city"]=city
my_dict["month"]=month
print(my_dict) | false |
c874a697e28816c1584dfabebc9820002c347646 | fafafariba/coding_challenges | /python/two_characters.py | 1,638 | 4.4375 | 4 | # String t always consists of two distinct alternating characters. For example, if string t's two distinct characters are x and y, then t could be 'xyxyx' or 'yxyxy' but not 'xxyy' or 'xyyx'.
# You can convert some string s to string t by deleting characters from s. When you delete a character from s, you must delete all occurrences of it in s. For example, if s = 'abaacdabd' and you delete the character 'a', then the string becomes 'bcdbd'.
# Given s, convert it to the longest possible string t. Then print the length of string t on a new line; if no string t can be formed from s, print 0 instead.
def two_characters(s):
length = 0
explored1 = []
for letter1 in s:
if letter1 not in explored1:
explored1.append(letter1)
explored2 = []
for letter2 in s:
if letter2 not in explored2 and letter2 not in explored1:
explored2.append(letter2)
t = two_char_str(s, letter1, letter2)
t_length = valid_t(t)
if t_length > 0 and t_length > length:
length = t_length
return length
def two_char_str(s, x, y):
new_str = ""
for l in s:
if l == x or l == y:
new_str += l
return new_str
def valid_t(t):
if len(t) < 2:
return 0
else:
for i in range(1, len(t)):
if t[i] == t[i - 1]:
return 0
return len(t)
s1 = 'cobmjdczpffbxputsaqrwnfcweuothoygvlzugazulgjdbdbarnlffzpogdprjxvtvbmxjujeubiofecvmjmxvofejdvovtjulhhfyadr'
print(two_characters(s1) == 8)
s2 = ''
print(two_characters(s2) == 0)
s3 = 'a'
print(two_characters(s3) == 0)
s4 = 'fd'
print(two_characters(s4) == 2) | true |
e3f7711eb38e6d215072bfb98b358cca05209211 | margaridav27/feup-mnum | /5. optimization/unidimensional.py | 1,520 | 4.125 | 4 | import math
# o método de trisecção baseia-se na constatação que,
# num intervalo contendo um mínimo e subdividido em três subintervalos,
# um dos subintervalos extremos não pode conter o mínimo sem violar a condição de unimodalidade
# definir intervalo do tipo [a, b, c, d] que contenha o mínimo da função
def trisection_method(a, b, c, d, f, iterations):
for i in range(iterations):
if f(b) > f(c):
a = b
else:
d = c
print("a = {} f(a) = {}\nb = {} f(b) = {}\nc = {} f(c) = {}\nd= {} f(d) = {}".format(a, f(a), b, f(b), c, f(c), d, f(d)))
# definir intervalo do tipo [a, d] que contenha o mínimo da função
def thirds_method(a, d, f, iterations):
for i in range(iterations):
b = a + (d - a) / 3
c = d - (d - a) / 3
if f(b) > f(c):
a = b
else:
d = c
print("a = {} f(a) = {}\nb = {} f(b) = {}\nc = {} f(c) = {}\nd= {} f(d) = {}".format(a, f(a), d, f(d), b, f(b), c, f(c)))
# definir intervalo do tipo [a, d] que contenha o mínimo da função
def aurea_method(a, d, f, iterations):
B = (math.sqrt(5) - 1) / 2
A = B ** 2
b = A * (d - a) + a
c = B * (d - a) + a
for i in range(iterations):
if f(b) < f(c):
d = c
c = B * (d - a) + a
else:
a = b
b = A * (d - a) + a
print("a = {} f(a) = {}\nb = {} f(b) = {}\nc = {} f(c) = {}\nd= {} f(d) = {}".format(a, f(a), d, f(d), b, f(b), c, f(c)))
| false |
f38b16680ab0b5e280a24aa68a5203bce3726417 | ekurpie/ekurpie.github.io | /Selection and Palindrome/Selection_Palindrome.py | 1,074 | 4.1875 | 4 | import random
def SelectionSort(a):
"""
Selection sort algorithm.
:param a:
:return:
"""
position = 0
for i in range(len(a)):
smallest = a[i]
for b in range(len(a)-1,i,-1):
if a[b] < smallest:
smallest = a[b]
position = b
if smallest < a[i]:
a[i],a[position] = a[position],a[i]
## these are for creating a list to sort
b = random.sample(range(-10000,10000),10)
print(b)
#sorting b and reprinting it to show that it is sorted
SelectionSort(b)
print(b)
#
def palindrome(n,lst=[],current_string = ""):
"""
This function PRODUCES palindromes via recursion.
:param n:
:param lst:
:param current_string:
:return:
"""
if len(current_string) == n:
if current_string == current_string[::-1]:
lst.append(current_string)
else:
palindrome(n,lst,current_string + "a")
palindrome(n, lst, current_string + "b")
palindrome(n, lst, current_string + "c")
return lst
print(palindrome(5)) | false |
0fad453246b0465c681e3f76bba3688d41e1b9c3 | tauanybueno/cursoemvideo-python-mundo1 | /desafios-python/python-mundo1/ex004.py | 584 | 4.15625 | 4 | #faça um programa que leia algo pelo teclado e mostre na tela
#seu tipo primitivo e todas as possiveis informações sobre aquilo
a = input('Digite algo: ')
print('O tipo primitivo desse valor é', type(a))
#será str porque todo input retorna string a não ser
#que coloque antes int, bool, float
print('Só tem espaços?', a.isspace())
print('É um número?', a.isnumeric())
print('É alfabético?', a.isalpha())
print('É alfanúmerico?', a.isalnum())
print('Esta em maiúcula?', a.isupper())
print('Esta em minúscula?', a.islower())
print('Está capitalizada?', a.istitle())
| false |
221585f8d8c38f6f12850b063398bddfc06c8939 | Junsu/Tutorial | /Python/learning_python_to_korean_developer_tutorial_1_data_structure.py | 1,425 | 4.21875 | 4 | #!/usr/bin/python
# Learning Python
# by Junsu Ko
import os
import sys
def sort_by_custom(one,other) :
if isinstance(one,str) and not isinstance(other,str) :
return -1
if not isinstance(one,str) and isinstance(other,str) :
return 1
if one>other :
return 1
if one<other :
return -1
return 0
def tutorial_1_data_type() :
# Boolean
val_0=True
# Integer
val_a=1
# Float
val_b=2.56
# String
val_c='Single quat. is string.'
val_d="Double quat. is string, too"
val_e='''Triple quat. is multi-line string.
For triple, single, and double is sample feature.'''
# List
print "List"
val_l=['1st',4,3,2,3.5]
print val_l
val_l.append("test")
print val_l
val_l.sort() # Sorting
print val_l
val_l.sort(sort_by_custom) # Custom Sorting
print val_l
val_l.reverse() # Reverse
print val_l
val_l_2=val_l[1:4] # Slicing
print val_l_2
print ""
# Diction
print "Diction (Hashing)"
val_l={"1st":1, "2nd":"string data"}
print val_l
val_l["3rd"]="hi, yo"
print val_l
print val_l["2nd"]
print ""
# Set
print "Set (Unique Set)"
val_s=set(["hi","wow"])
print val_s
val_s.add("wow")
print val_s
val_s.add("wow2")
print val_s
if __name__=='__main__' :
tutorial_1_data_type()
| false |
7e6ccda3495bd579eb9d6baf1cddb58d4532aa7d | tlming16/Project_Euler | /python/p001.py | 538 | 4.25 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# @author: mathm
# @email :tlming16@fudan.edu.cn
class solution:
'''
given n ,find the sum of all number from 1 to n which is the
multiples of three or five
'''
__slots__=('n')
def __init__(self,n:int):
self.n=n
def sum_of_multiples(self):
res=0
for value in range(1,self.n):
if value%3==0 or value%5==0:
res+=value
return res
if __name__ == '__main__':
s=solution(1000)
print(s.sum_of_multiples())
| false |
72f808403f3c685381a0caecd51022d9f9b874bd | eduardoramosdev/python-learning | /list_functions.py | 811 | 4.28125 | 4 | # extend = appending to a list
lucky_numbers = [1, 2, 3, 4, 5, 6]
friends = ['Karl', 'Karen', 'Jim', 'Oscar', 'Tamia']
#friends.extend(lucky_numbers)
# adding individual elements to list via append
friends.append('Gago')
print(friends)
# adding an individual element to a specific index of a list via insert pushing other elements like a wisdom tooth
friends.insert(1, 'Tangina')
print(friends)
print('===========')
# removal of friends via remove
friends.remove('Jim')
print(friends)
# resetting the list via clear
#friends.clear()
#print(friends)
print('==============')
# pop == removes the last element inside the list
friends.pop()
print(friends)
# index asking python where is the position of our element == also good for looking up if a specific element is in our array
print(friends.index('Oscar'))
| true |
3385b15970493950a6cd06f2ff4fb51ed9a4c3c5 | Navneeth-7/Python-Programs | /demo2_web.py | 800 | 4.125 | 4 | '''
Create a python script called googlesearch that provides a command line utility to
perform google search. It gives you the top links (search results) of whatever you want to
search on google
Input:-
python demo2_web.py 'Edureka'
'''
# Performing google search using Python code
import sys
class Gsearch_python:
def __init__(self,name_search):
self.name = name_search
def Gsearch(self):
count = 0
try :
from googlesearch import search
except ImportError:
print("No Module named 'google' Found")
for i in search(query=self.name,tld='co.in',lang='en',num=10,stop=5,pause=2):
count += 1
print (count)
print(i + '\n')
if __name__=='__main__':
gs = Gsearch_python(str(sys.argv))
gs.Gsearch() | true |
aec2374461d24389479cde809858e82ec59acc54 | nickBes/crypto_ml | /main.py | 2,415 | 4.125 | 4 | import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
FORCAST_DAYS = 1
TEST_SIZE = 0.9
TEST_DAYS = 5 * FORCAST_DAYS
df = pd.read_csv('./bitcoin_clean.csv')
# Creating a label column for the prediction by moving the Close column
# backwards by the desired amount of forcast days. In this way the feature columns will
# point to the close price in the future.
df['Label'] = df['Close'].shift(-FORCAST_DAYS)
df.dropna(inplace=True)
# We're creating a features array that doesn't include the time and
# label and then we're seperating it into the rows that we want to train
# and into the rows that we'll use for prediction.
FEATURES = preprocessing.scale(np.array(df.drop(['Label', 'Timestamp'], axis=1)))
features = FEATURES[:-TEST_DAYS]
features_after = FEATURES[-TEST_DAYS:]
# Creating a label array for training without the days that will be predicted.
label = np.array(df['Label'])
label = label[:-TEST_DAYS]
# The previous data is being prepared for training and testing.
x_train, x_test, y_train, y_test = train_test_split(features, label, test_size=TEST_SIZE)
# Creating a linear regression classifier, training and testing it.
clf = LinearRegression(n_jobs=-1)
clf.fit(x_train, y_train)
accuracy = clf.score(x_test, y_test)
print(f'Accuracy: {accuracy}.')
# Using the classifier to predict the data and comparing it to the real data.
forcast_set = clf.predict(features_after)
end = df[-TEST_DAYS:]
# Getting from the user how much money he wants to trade, then we're checking for every day
# if the person should buy or sell by the prediction.
money = int(input('Money (in usd): '))
pm = money
print('')
btc = 0
si = 0
for index, row in end.iterrows():
if money > 0:
if row['Close'] < forcast_set[si]:
print(f"Day {si + 1}, profit expected. Buying.")
btc = money / row['Close']
money = 0
elif money == 0 and btc > 0:
if row['Close'] < forcast_set[si]:
print(f"Day {si + 1}, profit expected. Selling.")
money = btc * row['Close']
btc = 0
si += 1
if si == TEST_DAYS:
last = row['Label']
# If there's some btc left sell on the next day and print the income
if btc > 0:
money = last * btc
print("\nProfit: ", money - pm) | true |
b532c006fc057329c47b7df3aace9a8291235b65 | deepyes02/creditcardvalidator | /static/credit.py | 2,344 | 4.21875 | 4 | #using luhn's algorithm to solve this credit card validation
#let's go now
creditCard = int(input("Enter a card Number: "))
sum = 0
workingDigits = creditCard
while (workingDigits > 0):
lastDigit = workingDigits %10
sum = sum + lastDigit
workingDigits = workingDigits // 100
print("sum of odd digits", sum)
#odd number multiplied by 2
#if two digits, is factored to one by adding the two digits
ridLastDigit = creditCard//10
workingDigits = ridLastDigit
while (workingDigits > 0):
lastDigit = workingDigits % 10
lastDigit *= 2
digitValue = 0
if (lastDigit < 10):
sum = sum + lastDigit
else:
digitValue = (lastDigit % 10) + (lastDigit // 10)
sum = sum + digitValue
workingDigits = workingDigits // 100 #get rid of last two digits to get the third one
print('sum of all digits after adjustment', sum)
#finding the first digit and first two digits of the numbers
workingDigits = creditCard
count =0
while (workingDigits != 0):
workingDigits = workingDigits//10
count= count+1
print("Digit count: ", count)
firstDigit = creditCard//10**(count-1)
firstTwoDigits = creditCard//10**(count-2)
print("first Digit :", firstDigit)
print("firstTwoDigits: ", firstTwoDigits)
"""
since the validity is now confirmed, classify the credit card according to company and console log the fuck out.
American express starts with 34 or 37 >> 15 digit number
Mastercard starts with 22, 51, 52, 53, 54 or 55 -> 16 digit
Visa starts with a 4 -> 13 or 16 digits
"""
cardProvider = ['Visa', 'MasterCard', 'American Express']
#Check if the card is valid at all, after that, check which card it is, return cardname, valid/invalid
if (sum % 10 == 0):
print("The Credit Card ", creditCard, " is valid.")
#since valid, check and return the make of card
if ((count == 13 or count == 16) and firstDigit ==4):
print("It's a ", cardProvider[0], ".")
elif ((count ==16) and (firstTwoDigits == 22 or (firstTwoDigits > 50 and firstTwoDigits < 56))):
print("It's a ", cardProvider[1], ".")
elif ((count == 15) and (firstTwoDigits == 34 or firstTwoDigits == 37)):
print("It's a ", cardProvider[2], ".")
else :
print("Card's provider not available")
else:
print("Card is invalid")
| true |
979c72204f709059945906eacd18b4bc1069594b | nikita-choudhary/Python-files | /practice_ques1.py | 204 | 4.15625 | 4 | my_dict = { "pankha" : "fan", "sabzi":"vegetable" ,"ankh":"eyes"
}
print("the options are" ,my_dict.keys())
a = input("Enter the hindi words\n")
print("The meaning of the word is :",my_dict.get(a)) | false |
d3aa455b778c415e7aefc839816bc03ce67e37e0 | KirillGukov/edu_epam | /hw2/tasks/task_2.py | 1,034 | 4.21875 | 4 | """
Given an array of size n, find the most common and the
least common elements.
The most common element is the element that appears
more than n // 2 times.
The least common element is the element that appears fewer than other.
You may assume that the array is non-empty and the most common element
always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3, 2
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2, 1
"""
from typing import Dict, List, Tuple
def major_and_minor_elem(inp: List[int]) -> Tuple[int, int]:
"""
:param inp: array is non-empty and the most common element
always exist in the array
:return: Tuple(least_common_elem, most_common_elem)
"""
value_count_dict: Dict[int, int] = {}
for value in inp:
if value in value_count_dict:
value_count_dict[value] += 1
else:
value_count_dict[value] = 1
return (
max(value_count_dict.items(), key=lambda item: item[1])[0],
min(value_count_dict.items(), key=lambda item: item[1])[0],
)
| true |
6ccbbfe7e5fff8f3bc6f328199193abbe8b0b6db | vaishalicooner/Strings-Practice | /strings/URLify.py | 278 | 4.21875 | 4 | # Write a method to replace all spaces in a string with '%20'.
def replace(string):
str = ""
for word in string:
if word == " ":
str += "%20"
else:
str += word
return str
result = replace("hello how are you?")
print(result) | true |
e230348a66e0f62c3865e0c76f233af408f127eb | vivaana/PythonTrg | /homework.py | 2,922 | 4.46875 | 4 | # 1) Write a program to check the temperature of a room.
# The requirements are simple:
# Prompt the user to enter the room temperature (it could be -100 to +100 including 0).
# Should the temperature of the room is below zero, shout out "It's freezing out here!".
# If the temperature is above zero, say "Ok, at least we aren't freezing".
# If the temperature is 0, say "Hmm, it's cold".
the_temperature = eval(input("please enter a temperature"))
if the_temperature <0:
print("it is freezing in here")
if the_temperature == 0:
print("hmm it is cold")
if the_temperature > 0:
print("at least it isn't cold ")
# If the user enters any number over 100 or below 100 degrees, alert him saying
# "I refuse to work with people who wouldn't follow instructions:)" 5 marks
user_degrees = eval(input("please enter 100 degrees"))
if user_degrees == 100:
print("your fine to work with me")
else:
print("I refuse to work with people who wouldn't follow instructions:)")
# 2) Write a program to find out if the given number is a positive or negative or zero number. 5 marks
users_number = eval(input("please enter a number"))
if users_number == 0:
print("it is a zero number")
elif users_number >0:
print(users_number,"is a positive number")
else:
print(users_number,"is a negative number")
# 3) Write a program to find out if the number is an even or odd number. 5 marks
users_number = eval(input("please enter a number\n"))
if users_number % 2 == 0:
print("even")
else:
print("odd")
# 4) Given a range of numbers from 0 to 29, write a program as per the requirements mentioned below:
# - if the number is a multiple of 3, print "Fizz"
# - if the number is a multiple of 5, print "Buzz"
# - if the number is a multiple of 3 and multiple of 5, print "FizzBuzz"
# - if the number is neither of the above, print the number (10 marks)
my_numbers = range(1,30)
for numbers in my_numbers:
if numbers %3 == 0 and numbers %5 == 0:
print("Fizzbuzz")
elif numbers % 3 == 0:
print("fizz")
elif numbers % 5 == 0:
print("buzz")
else:
print(numbers)
# 5) My mum sent me to Pizza Hut to pick up a pizza.
# There were quite a few toppings to select from.
# I was told to keep a note of these toppings so when she calls me I need to tell her.
#
# Write a program with a list of toppings.
# Make sure you have at least 10 toppings in your pizza (use your imagination).
# After noting down the toppings, I'll usually wait for my mum's call.
# When I receive her call I'll run through the toppings list shouting
# "Topping one is _______", "Topping two is ______".
#
# Write a program depicting this requirement. 10 marks.
pizza_toppings = ["cheese","mushroom","onion","pepper","olive","tomato","corn","feta cheese","jalapeno","chili"]
print("mum's call time to tell the toppings")
for toppings in pizza_toppings:
print(f"this is a ,{toppings} topping") | true |
21b3920cabe42167ad58753390ec62100e6bd0aa | vivaana/PythonTrg | /lesson1/lesson 1/lesson 1/CalculateNumbers.py | 292 | 4.25 | 4 | # These are the two numbers
number1 = 8
number2 = 8
sum_of_numbers = number1 * number2
print("Sum of numbers is ", sum_of_numbers)
# 1. Find out product of two numbers and print out
# 2. Find out division of two numbers and print out
# 3. Find out subtraction of two numbers and print out | true |
417bdf993278518b5e68f5dbd3e50f60c5368611 | vivaana/PythonTrg | /lesson1/your birthday.py | 340 | 4.34375 | 4 | yourName = input("what is your name")
u_Birthday = (input("when is your birthday"))
print(u_Birthday)
Birthday_date = "8th of June"
if u_Birthday == Birthday_date:
print(f"""happy birthday to you
happy birthday to you
happy birthday to {yourName}
happy birthday to you.""")
else:
print("ok come back on your birthday") | false |
998c7e47d5e658298fcf3ebabd2d281041e8be53 | gayathrisd28/HBEX | /dicts-restaurant-ratings/ratings.py | 1,034 | 4.15625 | 4 | def restaurant_ratings(file):
"""Restaurant rating lister."""
restaurant_file = open(file)
restaurant_dictionary = {}
for line in restaurant_file:
restaurant_list = line.rstrip().split(":")
restaurant_dictionary[restaurant_list[0]] = restaurant_list[1]
restaurant_name = input("enter the restaurant name: ").title()
restaurant_score = input("enter ur score: ")
restaurant_dictionary[restaurant_name] = restaurant_score
for key,value in sorted(restaurant_dictionary.items()):
print(f'{key} is rated at {value}.')
#file.close()
restaurant_ratings("scores.txt")
# pseudocode
# define our function
# create a blank dictionary
# pass in our file & open it
# for each line in the file:
# rstrip and split using ":"
# store each restaurant & rating in the dictionary
# use .items() to get a list of dictionary entries
# call sorted() on the list to get alphabetical order
# return/print sorted() dictionary
# call the function (print it if we use a return)
| true |
e7298e0781337a75caf4c7a19879be74a32c07bd | HotDogfinba11/Python | /Calculator - Text/calculator.py | 2,803 | 4.3125 | 4 | from time import sleep #imports library sleep to add delays for running code
def add(x, y): #creates the 'add' function, asks for num1 and num2 and renames them to 'x' and 'y'
return x + y #result of adding x (num1) and y (num2) will be sent to the print of where it was used
def subtract(x, y): #creates the 'subtract' function, asks for num1 and num2 and renames them to 'x' and 'y'
return x - y #result of subtracting x (num1) and y (num2) will be sent to the print of where it was used
def multiply(x, y): #creates the 'multiply' function, asks for num1 and num2 and renames them to 'x' and 'y'
return x * y #result of multiplying x (num1) and y (num2) will be sent to the print of where it was used
def divide(x, y): #creates the 'divide' function, asks for num1 and num2 and renames them to 'x' and 'y'
return x / y #result of dividing x (num1) and y (num2) will be sent to the print of where it was used
def calculator(): #main caluclator function, when this is called everything beneath will run line by line
sleep(0.7) #using imported sleep library, 700ms delay
print("Select operation.") #prints to user, "select operaton"
print("1.Add") #prints to user, "add"
print("2.Subtract") #prints to user, "subtract"
print("3.Multiply") #prints to user, "multiply"
print("4.Divide") #prints to user, "divide"
choice = input("Enter choice(1/2/3/4):\n") #what user writes will be set to choice
sleep(0.3) #delay of 300ms
num1 = float(input("Enter first number: ")) #inputted number by user is set to 'num1'
sleep(0.3) #delay of 300ms
num2 = float(input("Enter second number: ")) #inputted number by user is set to 'num2'
if choice == '1': #the value set to choice a few lines up is compared against each if and elif statement until it is true
print(num1,"+",num2,"=", add(num1,num2)) #outputs to user the sum that they did and then calls the add function giving the values of 'num1' and num2'
elif choice == '2': #is choice 2
print(num1,"-",num2,"=", subtract(num1,num2)) #outputs to user the sum that they did and then calls the subtract function giving the values of 'num1' and num2'
elif choice == '3': #is choice 3
print(num1,"*",num2,"=", multiply(num1,num2)) #outputs to user the sum that they did and then calls the multiply function giving the values of 'num1' and num2'
elif choice == '4': #is choice 4
print(num1,"/",num2,"=", divide(num1,num2)) #outputs to user the sum that they did and then calls the divide function giving the values of 'num1' and num2'
else: #if what the user inputted when asked for choice doesn't match any of the above, they inputted wrongly
print("Invalid input") #tells user they entered wrong
calculator() #calls/runs the calculator function | true |
050d42d361749759b6196dd529918cba53277299 | SOFTWARE-ANALYSTS/CircleObjectPyth | /main.py | 951 | 4.21875 | 4 | import math
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def input_attributes(self):
self.x = int(input("Faka ikho-odineyithi ka x"))
self.y = int(input("Faka ikho-odineyithi ka y"))
self.radius = int(input("Faka irediyasi"))
def perimeter(self):
d = 2 * (3.14 * self.radius)
print("Ipherimitha yesekile", d)
def area(self):
a = (3.14) * (self.radius * self.radius)
print (" ieriya yesekile ngu", a)
def outsideinsidecircle(self):
distance = math.sqrt((self.x-0) * (self.x-0) + (self.y-0) * (self.y-0))
if distance < self.radius:
print("ipoyinti ingaphakthi kwesekile")
else:
print("ipoyinti ingaphandle kwesekile")
if __name__ == '__main__':
c = Circle(4, 5, 6)
c.input_attributes()
c.perimeter()
c.area()
c.outsideinsidecircle()
| false |
2a6c98d1ea0994c90a163545082cb982b2d7442e | naestevez/python-practice | /practice8.py | 1,150 | 4.15625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 19:04:29 2018
@author: Alex
"""
import random
import time
print("Let's play a round of rock, paper, scissors!, Ya ready?")
time.sleep(2) #2 second delay for more spoken feel
choices = ["rock", "paper", "scissors"]
compChoice = random.choice(choices) #randomly selects from choices list
userChoice = raw_input("What will it be? rock, paper or scissors?")
userChoice = userChoice.lower()
if userChoice in choices: #checks for correct selection of options
if userChoice == compChoice:
print("There is a tie!")
elif userChoice == "rock":
if compChoice == "paper":
print("I win.")
elif compChoice == "scissors":
print("You win.")
elif userChoice == "paper":
if compChoice == "rock":
print("You win.")
elif compChoice == "scissors":
print("I win.")
elif userChoice == "scissors":
if compChoice == "paper":
print("You win.")
elif compChoice == "rock":
print("I win.")
else:
print("That is not a valid selection. Please try again.")
| true |
5e101b296825007a2e4e52b07066c00339ba72f9 | quamejnr/bazaar | /main.py | 1,872 | 4.1875 | 4 | from abc import ABC, abstractmethod
class Order:
def __init__(self, product: str, price: int, quantity: int, paid=False):
self.product = product
self.price = price
self.quantity = quantity
self.paid = paid
def total_cost(self) -> int:
return self.price * self.quantity
class PaymentMethod(ABC):
def __init__(self, money):
self.money = money
@abstractmethod
def connect(self):
pass
class VisaCard(PaymentMethod):
def __init__(self, money):
super().__init__(money)
def connect(self):
print('Connected to Visa Card...')
class Momo(PaymentMethod):
def __init__(self, money):
super().__init__(money)
def connect(self):
print('Connected to Momo...')
class DebitCard(PaymentMethod):
def __init__(self, money):
super().__init__(money)
def connect(self):
print('Connected to debit Card...')
class CheckoutCounter:
@staticmethod
def has_enough_money(order: Order, payment_method: PaymentMethod) -> bool:
return payment_method.money >= order.total_cost()
def receive_payment(self, order: Order, payment_method: PaymentMethod):
print('Verifying payment method...')
payment_method.connect()
if self.has_enough_money(order, payment_method):
payment_method.money -= order.total_cost()
print(f"Payment for {order.product} received\tBalance: {payment_method.money}\n")
else:
raise Exception(f'Payment for {order.product} rejected: Not enough funds')
if __name__ == '__main__':
order1 = Order('Corn', 3200, 1)
order2 = Order('Burger', 3000, 1)
visa_card = VisaCard(4000)
momo = Momo(50000)
counter = CheckoutCounter()
counter.receive_payment(order1, visa_card)
counter.receive_payment(order2, momo)
| true |
14176840ab8fad9bf4ff40b72bb59f70445c2e83 | mlyangyue/leetcode | /array/longest_substring_norepeate.py | 1,032 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_len = 0
start = 0
temp_dict = {}
for i in range(len(s)):
if s[i] in temp_dict and start <= temp_dict[s[i]]: #如果在字典里并且start小于等于上一次重复的字符下标
start = temp_dict[s[i]] + 1 # 找到上次重复的下标
else:
max_len = max(max_len, i - start + 1) # 最大值 和 当前下标到上次重复的距离 做比较
temp_dict[s[i]] = i
return max_len
if __name__ == "__main__":
print Solution().lengthOfLongestSubstring('dvdfe') | true |
f01dd1f2f968dc1a39249f924ef9c0235d10c793 | mlyangyue/leetcode | /array/search_insert.py | 1,031 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
有序数组查找用用二分法查找
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
if nums[-1] < target:
return len(nums)
l = 0
r = len(nums) - 1
while l <= r:
m = (l + r)/2
if nums[m] == target:
return m
if nums[m] > target:
r = m - 1
if r >= 0:
if nums[r] < target:
return r + 1
else:
return 0
else:
l = m + 1
if l < len(nums):
if nums[l] > target:
return l
else:
return len(nums)
if __name__ == "__main__":
print Solution().searchInsert([1,3,5,6],7)
| true |
c701cc2e3eec1bfa32815eb71cca041ea37ee10b | bayoishola20/Python-All | /D.I.P/11_DP_Minimum_Removals_Valid_Parenthesis.py | 1,209 | 4.53125 | 5 | # You are given a string of parenthesis. Return the minimum number of
# parenthesis that would need to be removed in order to make the string valid.
# "Valid" means that each open parenthesis has a matching closed parenthesis.
def count_invalid_parenthesis(string):
left_paren, right_paren = 0, 0 # store count of left and right parenthesis
for i in string: # loop through the string input
if i == '(': # check for left parenthesis and then increase count
left_paren += 1
# print "left_paren,", left_paren
else: # else i is ')'
if left_paren > 0: # if left is greater than 0, then decrease count
left_paren -= 1
# print "left_paren,", left_paren
else:
right_paren += 1 # else increase count of right
# print "right_paren,", right_paren
return left_paren + right_paren # return what is remaining of left and right.
print count_invalid_parenthesis("()())()")
# 1
print count_invalid_parenthesis("((()()()")
# 2 | true |
e6dab7c7325a490f195944e18e2452981c148810 | bayoishola20/Python-All | /D.I.P/08_DP_Primes.py | 882 | 4.1875 | 4 | """
Given a positive integer n, find all primes less than n.
"""
def find_primes(n):
# initialize empty array to store primes
result = []
for i in range(2, n): # loop through starting from 2 which is the smallest prime number to n
isPrime = True # a truthy for prime numbers
for j in range(2, i): # loop through starting from 2 to i: So, from loop from 2 to 2, from 2 to 3, then from 2 to 4
if i % j == 0: # check if each number divided by each has a remainder of zero(0).
isPrime = False # then isPrime is False
if isPrime: # all other values, that is, that isPrime
result.append(i) # append to empty list
return result #return result
# list comprehension alternative
# return [x for x in range(2, n) if all(x % y != 0 for y in range(2, x))]
print find_primes(14)
# [2, 3, 5, 7, 11, 13] | true |
a5e4f97b2b88d3dfcfd5afdca2608cb57ce36411 | bayoishola20/Python-All | /D.I.P/03_DP_Sum_Squares.py | 694 | 4.21875 | 4 | # Given a number n, find the least number of squares needed to sum up to the number.
def square_sum(n):
# minimum squares for 3, 2 and 1 is same as the number itself. Check by solving.
if n <= 3:
return n
# check if number is a perfect square return 1
elif n == int( pow(n,1/2) ):
return 1
ans = n # store maximum squares needed
for i in range(1, n+1):
tmp = i * i
if tmp > n:
break
elif tmp == n:
ans = 1
else:
ans = min( ans, 1 + square_sum(n - tmp) ) # recursion
return ans
print square_sum(100)
# Min sum is 3^2 + 2^2
# 2
#PS: This solution works for small values of n. | true |
e888b1717bad12297883b990924001714307f399 | omcairoli/Fizz-Buzz | /FizzBuzz.py | 624 | 4.21875 | 4 | # Program: FizzBuzz
# Created by Oscar Cairoli
# Prints the numbers from 1 to 100.
# For multiples of three, print "Fizz"
# For multiples of five, print "Buzz"
# For numbers which are multiples of both three and five, print "FizzBuzz"
def fizzBuzz():
for num in range(1, 100 + 1):
if ((num % 3 == 0) and (num % 5 == 0)):
print("Num: {} FizzBuzz".format(num))
elif (num % 5 == 0 and num % 3 != 0):
print("Num: {} Buzz".format(num))
elif (num % 3 == 0 and num % 5 != 0):
print("Num: {} Fizz".format(num))
else:
print("Num: {} ".format(num))
def main():
fizzBuzz()
if __name__ == '__main__':
main() | true |
f979326be748bcfbb075232dd259df7c261e1e75 | shilpavijay/Algorithms-Problems-Techniques | /Puzzles/paranthesis.py | 858 | 4.125 | 4 | '''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
'''
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pairs = {')':'(',']':'[','}':'{'}
opening_brackets = ['(','[','{']
bstack=[]
for each in s:
if each in opening_brackets:
bstack.append(each)
else: #closing
if len(bstack) == 0:
return False
if pairs[each] != bstack.pop():
return False
if len(bstack)==0:
return True
return False
| true |
e3a6d868c5d380255382ef31fa93e965b06ad599 | shilpavijay/Algorithms-Problems-Techniques | /DataStructures/BST.py | 1,277 | 4.125 | 4 | # Binary Search Tree with Pre-order, In-order, Post-order traversals
# Elements: Key, Prev, Next
# Operations: insert, inOrder, preOrder, postOrder
class BST:
def __init__(self,key,left,right):
self.key = key
self.left = left
self.right = right
def insert(self,el):
n = BST(el,None,None)
if self.key:
if el < self.key:
if self.left is None:
self.left = n
else:
self.left.insert(el)
elif el > self.key:
if self.right is None:
self.right = n
else:
self.right.insert(el)
else:
self.key = el
def inOrder(self):
if self.left:
self.left.inOrder()
print(self.key)
if self.right:
self.right.inOrder()
def preOrder(self):
print(self.key)
if self.left:
self.left.preOrder()
if self.right:
self.right.preOrder()
def postOrder(self):
if self.left:
self.left.postOrder()
if self.right:
self.right.postOrder()
print(self.key)
#Usage:
tree = BST(12,None,None)
tree.insert(10)
tree.insert(20)
tree.insert(4)
print("In-order Traversal: ")
tree.inOrder()
print("Pre-order Traversal: ")
tree.preOrder()
print("Post-order Traversal: ")
tree.postOrder()
#Output:
# In-order Traversal:
# 4
# 10
# 12
# 20
# Pre-order Traversal:
# 12
# 10
# 4
# 20
# Post-order Traversal:
# 4
# 10
# 20
# 12 | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.