blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a2e100b7e3a53939b40d2bddcc82942096484e7c | aga-moj-nick/Python-String | /Exercise 021.py | 545 | 4.1875 | 4 | # 21. Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters.
def zwiększanie_liter (string):
duże_litery = 0
for litery in string [:4]:
if litery.upper () == litery:
duże_litery += 1
if duże_litery >= 2:
return string.upper ()
else:
return string
return string
print (zwiększanie_liter ("PyThon"))
print (zwiększanie_liter ("PytHon"))
print (zwiększanie_liter ("Python"))
| false |
acab86a65d7c1dda4c21ac45f31b872e19990270 | 1496rajeev/Timesys_Assignment | /python/string_palindrome.py | 318 | 4.125 | 4 | string = input('enter string ')
filtered_string=''
# filter the alphabets
for i in string:
if i.isalpha():
filtered_string += i
#reverse the string
reverse_string = filtered_string[::-1]
# checking palindrome
if filtered_string.upper() == reverse_string.upper():
print("YES")
else:
print("NO") | true |
86ea1e848fd40a4de0ca55681b39224e738385eb | ezileo/Rohit_Scripts | /Daily_Python_Programming/Practice Python Problems/PracticePython_Problem_12_01_09_2017.py | 723 | 4.21875 | 4 | # URL: http://www.practicepython.org/
# Author: Rohit Gupta
# Date Scheduled: September 01, 2017
# Date Written: October 23, 2017
# Version 1.0
# Problem Exercise: 12
import datetime
import random
user_name = input("Please enter your name: ")
print("This programme was run on: " + str(datetime.datetime.today()))
user_input = int(input("Enter the length of the list"))
a = []
b = []
for _ in range(0, user_input):
a.append(random.randint(0, 100))
print(a)
print("The length of the list is: ", len(a))
#def ListIteration():
first = a[0]
last = a[user_input-1]
print("The first number on the list is: ", first)
print("The last number on the list is: ", last)
b.append(first), b.append(last)
print("The new list is: ", b) | true |
8af0390293bf7ce94d6222b57c5ab10493e46f64 | notbasic/linked_list | /linklist.py | 1,893 | 4.125 | 4 | class node:
def __init__(self, data=None): # did not work if data was not set to None here
self.data= data # didn't work if this was set to None
self.next = None
class linked_list:
def __init__(self):
self.head = node() # creating access to a new node to use
def append(self, data):
new_node = node(data) # creating a new node
now = self.head # setting the start point
while now.next!= None: # stepping through the nodes to find the end
now = now.next
now.next = new_node # adding the new data to the end of the list
def length(self):
now = self.head
count = 0 #initialinging to counter
while now.next!= None: # checking if the is a next node
count += 1 # adding 1 for each iteration that go by
now = now.next
return print(count) # displaying the ccount as the length of the list
def show(self):
lst = [] # creating a empty list
current_node = self.head # setting the starting point for the nodes
while current_node.next!= None: # checking if there is a next node
current_node = current_node.next # setting current node to the next node.
lst.append(current_node.data) # adding the current node data to the list
return print(lst) # printing the list
def __str__(self): # i dont get this
str_repr= ""
for el in self.data:
str_repr += str(el)+ "\n"
str_repr = "".join(reversed(str_repr.strip()))
return str_repr # printing the list
my_list = linked_list() # created a new instance of a linked_list
my_list.append(12)
my_list.append('how')
my_list.length()
my_list.show()
| true |
6513c644756310d9d7199252290c2a26d6c6ec54 | dariazac/hello-world | /python-basics.py | 770 | 4.1875 | 4 |
# some python basics
# for i in range(1, 11):
# print i
# i = 1
# while i <= 10:
# print i
# i += 1
# a = 10
# b = 20
# if a < b:
# print "{} is less than {}".format(a, b)
# elif a == 20:
# print "{} is equal to {}".format(a, b)
# else:
# print "{} is greater than {}".format(a, b)
import sys
print(sys.executable)
print(sys.version)
class Employee:
"""A sample Employee class"""
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
| false |
edcb0b731c4aa683021141791e1a0d9019080cbb | GabrielFierro/Python-Exercises | /Estructuras de datos/Sets/ConjuntoDeFrutas2.py | 547 | 4.15625 | 4 | # Algoritmo que dada una estructura de tipo set cargada con elementos de tipo 'str', recorre el conjunto mediante la estructura for y muestra todos sus elementos.
"Zona de declaración e inicialización de variable"
fruits = {"apple", "banana", "cherry", "orange", "watermelon", "pear"}
# Los conjuntos no tienen índice, por lo que para acceder a sus elementos puedo usar la estructura for.
# "in" es una palabra reservada denominada "keyword", que pregunta si un valor específico se encuentra en el conjunto.
for x in fruits:
print(x)
| false |
c73ee78cdaf74adab580fff49300416088ed1301 | GabrielFierro/Python-Exercises | /Funciones/CantidadDeNumerosDeLista.py | 1,056 | 4.125 | 4 | # Algoritmo que dada una lista con valores precargados, llama a la función 'mi_funcion' pasándole como argumento una lista y suma sus valores, retornando el resultado
def my_function(mi_lista):
# Función que recibe por parámetro una lista, suma los elementos que posee y muestra el resultado por consola
"Zona de inicialización de variable"
cont = 0
for cant in mi_lista:
cont = cont + cant
print('El resultado es:',cont)
def cant_elementos(my_list):
# Función que recibe por parámetro una lista, y cuenta la cantidad de elementos que la misma posee. Retorna el resultado.
"Zona de inicialización de variable"
cont = 0
for cant in my_list:
cont = cont + 1
return cont
"Zona de declaración e inicialización de variables"
lista1 = [2,13,11,6,0,7]
lista2 = [-1,5]
# Se le envía como argumento una lista
my_function(lista1)
# Se imprime por consola a la vez, que se llama a la función
print('La cantidad de números que posee la lista es:',cant_elementos(lista2)) | false |
32462411e20cc3dba9217052ddb85d889e165484 | Manuel-illidge/Python_Basico | /Menu_Programas.py | 1,626 | 4.1875 | 4 |
opcion_menu = int(input("""
Bienvenido a Programas Integrados de Python 💸
1- numero menos o mayor
2 - Conversor Monedas
3 -
4 -
Elige una opcion:
"""))
if opcion_menu == 1:
numero = int(input('Escribe un numero: ')) # convertir caracter a entero en una sola linea de codigo
if numero > 5:
print('Su numero es mayor a 5')
elif numero == 5:
print('Su numero es igual a 5')
else:
print('Su numero es menor que 5')
if opcion_menu == 2:
menu = """
Bienvenido al conversor de monedas 💸
1 - Pesos Colombianos
2 - Pesos Argentinos
3 - Pesos Mexicanos
Elige una opcion:
"""
opcion = float(input(menu))
if opcion == 1:
pesos_col = input('Ingresa valor en pesos colombianos: ')
pesos_col = float(pesos_col)
dolar_valor = 3555
dolar = pesos_col / dolar_valor
dolar = round(dolar, 3)
dolar = str(dolar)
print('Tienes $' + dolar + ' dolares')
elif opcion == 2:
pesos_arg = input('Ingresa valor en pesos argentinos: ')
pesos_arg = float(pesos_arg)
dolar_valor = 87
dolar = pesos_arg / dolar_valor
dolar = round(dolar, 4)
dolar = str(dolar)
print('Tienes $' + dolar + ' dolares')
elif opcion == 3:
pesos_mex = input('Ingresa valor en pesos mexicanos: ')
pesos_mex = float(pesos_mex)
dolar_valor = 20
dolar = pesos_mex / dolar_valor
dolar = round(dolar, 4)
dolar = str(dolar)
print('Tienes $' + dolar + ' dolares')
else:
print('Ingresa una opcion porfavor: ')
def run():
pass
if __name__ == '__main__':
run () | false |
1de10452eb2f9aec0d25628ceb2dd6cf0acab42a | bpachev/acme_homework | /vol1_ta/calculator.py | 651 | 4.15625 | 4 | def add(a,b):
"""
Add two numbers and return the result.
Parameters:
a (float) -- the first number
b (float) -- the second number
Returns:
The sum of a and b.
"""
return a + b
def multiply(a,b):
"""
Add two numbers and return the result.
Parameters:
a (float) -- the first number
b (float) -- the second number
Returns:
The product of a and b.
"""
return a*b
def sqrt(a):
"""
Return the square root of a real number.
Parameters:
a (float) -- the input number
Returns:
The square root of a.
"""
return a**.5
| true |
e19dd77f959bee903b8e415eb2dfffc599420793 | tahirm1/CodeQuestions- | /TahirMariaLab02a.py.py | 565 | 4.125 | 4 | #first python program
#you will be able to enter the temperature in F and see what that converts to in C
def main():
#Enter your first and last name
firstName= input("Type your first name")
lastName= input("Type your last name")
#Enter the temperature in F
farenheit= (int)(input("What is the current temperature in farenheit?"))
#equation to convert Farenheit to Celsius
celsius=(farenheit-32)*(5/9)
for x in range (0, 10):
print(firstName," ", lastName, "The temperature in celsius is", celsius+x,"degrees")
| true |
be31889ddbd84220be5b85b242074f624921ad9e | l3va/algo-tasks | /task_554.py | 1,649 | 4.4375 | 4 | import sys
print("Task 554: find all pythagorean triples that lower than input number n")
def continue_or_not():
"""
Asks a user whether he/she wants to continue using program or not,
if not program is terminated, else program continues its work
"""
print("Do you want to continue?(yes/no)")
answer = input()
if answer == "yes":
main()
else:
print("Thank you! Program has ended its work")
sys.exit()
def input_natural_number():
"""
Asks user to enter natural number, if input is wrong, output alert message
and asks user whether he wants to try again
"""
print("Enter natural number: ")
try:
number = int(input())
except ValueError:
print("Wrong input! Enter natural numbers(1, 2, 3, 4...)")
return continue_or_not()
else:
if number < 1:
print("Wrong input! Natural number must be greater than zero(1, 2, 3, 4...)")
return continue_or_not()
return number
def count_pythagorean_triples(number):
"""
Takes an integer as arguments and returns all pythagorean triples
lower than given number
"""
pythagorean_triples = []
for c in range(number):
for b in range(c):
for a in range(b):
if a ** 2 + b ** 2 == c ** 2:
pythagorean_triples.append((a, b, c))
return pythagorean_triples
def main():
number = input_natural_number()
pythagorean_triples = count_pythagorean_triples(number)
print(f"List of all pythagorean triples lower than {number}:\n{pythagorean_triples} ")
continue_or_not()
main() | true |
3aa8c7bdd2591d35cc6976e5660e3c04cd8a94b7 | obltrn/CS-Labs | /Edit_Distance.py | 1,378 | 4.25 | 4 | # finds min number of operations to convert str1 to str2
def edit_distance(str1, str2, str1_len, str2_len):
# base case 1:
# checks if 1st string is empty
if str1_len == 0:
return str2_len
# base case 2:
# checks if 2nd string is empty
if str2_len == 0:
return str1_len
# checks last char of strings
# if similar, edit count is not updated and check edits for remaining characters
if str1[str1_len - 1] == str2[str2_len - 1]:
return edit_distance(str1, str2, str1_len - 1, str2_len - 1)
# else last char of strings differ
# performs all 3 possible options and gets edit count : 1) insert, 2) remove, 3) replace
# return the min edit count of the three plus 1
return 1 + min(edit_distance(str1, str2, str1_len, str2_len - 1), # Insert
edit_distance(str1, str2, str1_len - 1, str2_len), # Remove
edit_distance(str1, str2, str1_len - 1, str2_len - 1) # Replace
)
def main():
# asks user for 2 words to compare
str1 = input("Enter first word: ")
str2 = input("Enter second word: ")
# prints number of edits needed for conversion
print("The minimum number of operations needed to convert word one into word two is: ", end="", flush=True)
print(edit_distance(str1.lower(), str2.lower(), len(str1), len(str2)))
main()
| true |
d2e999c4447cb752b264e8bb2ab8b67198188daf | vishalkumar95/HackerRank- | /Staircase.py | 682 | 4.59375 | 5 | # Your teacher has given you the task of drawing a staircase structure.
# Being an expert programmer, you decided to make a program to draw it for you instead.
# Given the required height, can you print a staircase as shown in the example?
# Input
# You are given an integer depicting the height of the staircase.
# Output
# Print a staircase of height that consists of # symbols and spaces. For example for , here's a staircase of that height:
def printStairs(num):
# Keep track of the number of spaces to add
spaces = num - 1
# Run the loop to print the stairs
for i in range(num):
print (' ' * spaces + '#' * (i + 1))
spaces = spaces - 1
| true |
1ffdd57a18cf7ce45f9b2ed982da00a8c3dc9b0d | kashyapa/interview-prep | /revise-daily/educative.io/medium-subsets/4_permutations_by_changing_case.py | 683 | 4.21875 | 4 | # Input: "ad52"
# Output: "ad52", "Ad52", "aD52", "AD52"
def find_letter_case_string_permutations(str):
permutations = []
permutations.append(str)
for i in range(len(str)):
if str[i].isalpha():
for j in range(len(permutations)):
chs = list(permutations[j])
chs[i] = chs[i].swapcase()
permutations.append(''.join(chs))
return permutations
def main():
print("String permutations are: " +
str(find_letter_case_string_permutations("abc")))
print("String permutations are: " +
str(find_letter_case_string_permutations("ab7c")))
if __name__ == "__main__":
main()
| false |
d4631d1752c42e6c1b7b2b9b34c4d5438f21ec61 | kashyapa/interview-prep | /revise-daily/educative.io/medium-dp/fibonacci/5_minimum_jumps_with_fee.py | 1,295 | 4.15625 | 4 | # Given a staircase with ‘n’ steps and an array of ‘n’ numbers representing the fee that you have to pay if you take the step.
# Implement a method to calculate the minimum fee required to reach the top of the staircase (beyond the top-most step).
# At every step, you have an option to take either 1 step, 2 steps, or 3 steps. You should assume that you are standing at the first step.
def find_min_fee(fee):
dp = [0 for x in range(len(fee))]
return find_min_fee_recursive(dp, fee, 0)
def find_min_fee_recursive(dp, fee, currentIndex):
n = len(fee)
if currentIndex > n - 1:
return 0
if dp[currentIndex] == 0:
# if we take 1 step, we are left with 'n-1' steps
take1Step = find_min_fee_recursive(dp, fee, currentIndex + 1)
# similarly, if we took 2 steps, we are left with 'n-2' steps
take2Step = find_min_fee_recursive(dp, fee, currentIndex + 2)
# if we took 3 steps, we are left with 'n-3' steps
take3Step = find_min_fee_recursive(dp, fee, currentIndex + 3)
dp[currentIndex] = fee[currentIndex] + \
min(take1Step, take2Step, take3Step)
return dp[currentIndex]
def main():
print(find_min_fee([1, 2, 5, 2, 1, 2]))
print(find_min_fee([2, 3, 4, 5]))
main()
| true |
ecabe2c8ecdf73db189da164451bbc5daa6230df | kashyapa/interview-prep | /revise-daily/educative.io/1-sliding-window/1_maximum_sum_subarray.py | 623 | 4.125 | 4 | import math
# Given an array of positive numbers and a positive number ‘k,’
# find the maximum sum of any contiguous subarray of size ‘k’.
def max_sub_array_of_size_k(k, arr):
sum = 0
max_sum = -math.inf
for i in range(len(arr)):
sum += arr[i]
if i >= k-1:
max_sum = max(max_sum, sum)
sum -= arr[i+1-k]
return max_sum
if __name__ == "__main__":
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])))
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])))
| true |
7a74c4729d3dad108f20c04f13080ab783b85a49 | byrondover/python-practice | /palindromes.py | 704 | 4.1875 | 4 | #!/usr/bin/env python3
#
# palindromes.py
# Given string input, return all possible palindromes.
#
DEFAULT_TEXT = "racecarenterelephantmalayalam"
def is_palindrome(word):
return all(word[i] == word[-1 * (i + 1)] for i in range(len(word) // 2))
def substrings(string):
for i in range(len(string)):
for j in range(i, len(string)):
substring = string[i:j + 1]
if len(substring) > 1:
yield substring
def palindrome_substrings(string):
return (i for i in substrings(string) if is_palindrome(i))
if __name__ == '__main__':
palindromes = palindrome_substrings(DEFAULT_TEXT)
for palindrome in palindromes:
print(palindrome)
| false |
6692cbdea99028091a3549d29d2429d3a4f63397 | ulcsf/IGCSE-CS-validationTasks | /TKinter/myFirstGUI.py | 455 | 4.15625 | 4 | # ***********************************************
# My First GUI project
# ***********************************************
from tkinter import *
window = Tk()
window.title("Welcome to my 1st GUI app")
lbl = Label(window, text="Hello")
#lbl.grid(column=0, row=0)
lbl.pack()
def clicked():
lbl.configure(text="Button was clicked !!")
btn = Button(window, text="Click Me", command=clicked)
#btn.grid(column=1, row=1)
#
window.mainloop()
| true |
52ef69f872a6d1a73400461abc2a4936d95d4ebb | ulcsf/IGCSE-CS-validationTasks | /PizzaOrderingService/Task1-outline_A.py | 1,686 | 4.5625 | 5 | '''
TASK 1 – Design your pizza.
Part A:
The customer is given choices of size, base and additional toppings (number and type) as stated above.
Only valid choices can be accepted.
Part B:
The customer is asked to confirm their order or alter their
choices or not proceed. If the customer confirms their order they are given a unique order number.
--------------------------------------
'''
#Lists containing the options for the customer
toppings = ["Pepperoni","Chicken","Extra cheese","Mushrooms","Spinach","Olives"]
baseSizes = ["Small","Medium","Large"]
baseTypes = ["Thin","Thick"]
#NOTE: No other variable have been created. You may require more than this!!
#**START**
#TODO: 1. Display a 'welcome' message to the user
print("""
Hi, welcome to the Pizza Ordering Service.
Please follow the on-screen prompts to place your order.
Press return/enter to continue...
""")
input()
orderComplete = "N" #Flag to allow repetiton of the process
while orderComplete == "N":
#TODO: 2. Ask the user what size base they want and store the answer.
#HINT: Show the user the options they have available and ask them to repond. Are there any problems that could happen?
#TODO: 3. Ask the user to choose a type of pizza base and store the answer
#TODO: 4. Show the customer the extra toppings available. Ask the user to select their toppings and store the answer
#TODO: 5. Output the order so the user can check their choices.
#TODO: 6. Ask the user if their order is correct. If it isn't...let them choose again. Otherwise...give them an order number.
print("""
Thank you!
Your order number is: """)
| true |
fcab25823684621f56a715d6204d5a32076c6e07 | keryl/NBO-Bootcamp16 | /data_types.py | 595 | 4.40625 | 4 | def data_type(m):
""" Takes an input and returns the corresponding value"""
m_type = type(m)
if m_type == str:
return len(m)
elif m_type == bool:
return m
elif m_type == int:
if m < 100:
return "less than 100"
elif m_type == 100:
return "equal to 100"
else:
return "more than 100"
elif m_type == list:
if len(m) >= 3: # length should be equal or greater than 3 in order to access the 3rd item
return m[2]
else:
return None
else:
return "no value"
| true |
888bca09bd3c5d00d2ac4fc22dc33b65ecc1e741 | bptfreitas/Project-Euler | /problema4.py | 757 | 4.15625 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
a=999
b=999
def is_pal(a,b):
s_num=str(a*b)
siz=len(s_num)
left=s_num[0:(siz/2)]
if (siz%2==0):
right=s_num[-1:(-siz/2)-1:-1]
else:
right=s_num[-1:(-siz/2):-1]
print s_num +": size "+ str(siz) +", left " + left +", right " + right
if (left==right):
print "Found:" + str(s_num) + "=" + str(a) + "*" + str(b)
return True
else:
return False
pals=list()
while (a>499):
if (is_pal(a,b)==True):
pals.append(a*b)
print pals
b-=1
if (b==99):
a,b=a-1,999
print "Complete list:"
for i in sorted(pals):
print i
| true |
7e70dd5ae7f06b8084c5eebab7b79c8bb9b417ab | Maretzky85/pbwp-3rd-si-code-comprehension | /comprehension.py | 2,196 | 4.1875 | 4 | #program runs a guess game. Firstly choosing random number from 1 to 20, and ask for quess. You can guess up to 6 times.
import random #import random library
guesses_taken = 0 #Assign 0 to guesses_taken variable
print('Hello! What is your name?') #Print text to console
myName = input() #Ask user for input, waits for enter and assign input as str to variable myName
number = random.randint(1, 20) #assigning to variable a randomly choosed integer from range 1-20
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #prints a string in variable name inside
while guesses_taken < 6: #creates loop that compares guesses_taken var to 6 integer, and runs until var reaches 6, than stops. 6 loop will not be executed
print('Take a guess.') #prints a string
guess = input() #asks for user keyboard input, waits for enter and assigning inpupt as str to var guess
guess = int(guess) #changes var guess to int
guesses_taken += 1 #adds +1 to var guesses taken
if guess < number: #creates if condition that takes inputed guess variable and compares to number variable, checking if guess var is lower than number var
print('Your guess is too low.') #if condition is met, prints a str to console
if guess > number: #creates if condition that takes inputed guess variable and compares to number variable, checking if guess var is higher than number var
print('Your guess is too high.') #if condition is met, prints a str to console
if guess == number:#creates if condition that takes inputed guess variable and compares to number variable, checking if guess var equals number var
break #exits loop
if guess == number: #after loop, if guess var equals number var execute code bolew
guesses_taken = str(guesses_taken) #changes var guesses_taken from var to str
print('Good job, ' + myName + '! You guessed my number in ' + guesses_taken + ' guesses!') #prints str +2 variables in
if guess != number: #another check, if var guess differs from var number execute code below
number = str(number) #changes var number to str
print('Nope. The number I was thinking of was ' + number) #print str and var number at end
| true |
b0f6104efe96d3cfe27ea8f413c045215498089f | vrautela/ciphers | /affine.py | 1,169 | 4.25 | 4 | #Affine Cipher Encoder/Decoder
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
punctuation = " .?!:;,'\"\\"
print("Welcome to the Affine Cipher Encoder/Decoder.")
use_default_alphabet = input("Would you like to use the standard English alphabet (ABCDEFGHIJKLMNOPQRSTUVWXYZ)?\nEnter (y/n): ").upper()
while use_default_alphabet != 'Y' and use_default_alphabet != 'N':
use_default_alphabet = input("Unrecognized option. Please enter either y or n to indicate whether you would like to use the Standard English Alphabet: ").upper()
if use_default_alphabet == 'N':
alphabet = input("Please enter your custom alphabet (in uppercase letters): ").upper()
# TODO: check for duplicates(?)
encrypt_decrypt = input("Would you like to encrypt or decrypt your text?\nEnter (e/d): ").upper()
while encrypt_decrypt != 'E' and encrypt_decrypt != 'D':
encrypt_decrypt = input("Unrecognized option. Please enter either e or d to indicate whether you would like to encrypt or decrypt your text: ").upper()
if encrypt_decrypt == 'E':
ciphertext = input("Enter your text to be encrypted: ").upper()
else:
ciphertext = input("Enter your text to be decrypted: ").upper()
| false |
7a1bb1dd7f4a542af31212b3e1f8cab22bd73323 | mcceTest/leetcode_py | /src/X152_MaximumProductSubarray.py | 1,784 | 4.125 | 4 | '''
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
neg = None
pos = None
res = nums[0]
for num in nums:
if num == 0:
neg = pos = None
elif num > 0:
if pos is None:
pos = num
else:
pos *= num
if neg is not None:
neg *= num
else:
if neg is None:
if pos is None:
neg = num
else:
neg = num * pos
pos = None
else:
newPos = neg * num
if pos is None:
neg = num
else:
neg = num * pos
pos = newPos
if pos is not None:
if pos > res:
res = pos
elif neg is not None:
if neg > res:
res = neg
else:
if res < 0:
res = 0
return res
@staticmethod
def main():
sol = Solution()
nums = [2,3,-2,4]
print(sol.maxProduct(nums))
if __name__ == "__main__":
Solution.main()
| true |
45b6f74a31ee1a54328524c6d9e01793f1bba663 | mcceTest/leetcode_py | /src/X38_CountandSay.py | 1,505 | 4.125 | 4 | '''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for _ in range(n - 1):
curChar = None
startIdx = None
newRes = ''
for i, c in enumerate(res):
if curChar is None:
curChar = c
startIdx = i
elif curChar != c:
preLength = i - startIdx
newRes += str(preLength)
newRes += curChar
startIdx = i
curChar = c
preLength = len(res) - startIdx
newRes += str(preLength)
newRes += curChar
res = newRes
return res
@staticmethod
def main():
sol = Solution()
print(sol.countAndSay(5))
if __name__ == "__main__":
Solution.main()
| true |
6972edbd88eeecbd9a0b5d1db32bc4c6b5308ba0 | mcceTest/leetcode_py | /src/X114_FlattenBinaryTreetoLinkedList.py | 1,418 | 4.375 | 4 | '''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
from treeNode import TreeNode
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
self.flattenHelper(root)
return root
def flattenHelper(self, root):
if root is None:
return (None, None)
cur = root
lstart, lend = self.flattenHelper(root.left)
rstart, rend = self.flattenHelper(root.right)
if lstart is not None:
cur.right = lstart
cur = lend
root.left = None
if rstart is not None:
cur.right = rstart
cur = rend
return (root, cur)
@staticmethod
def main():
sol = Solution()
root = TreeNode.constructFromLevelList([1, 2, 5, 3, 4, None, 6])
root = sol.flatten(root)
print(TreeNode.toList(root))
if __name__ == "__main__":
Solution.main() | true |
6feddf7bbd79dca5edf3531477f8bdab3d8b11dd | mcceTest/leetcode_py | /src/X208_ImplementTrie.py | 2,452 | 4.25 | 4 | '''
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
'''
class TrieNode(object):
def __init__(self, val='', wordEnd=False):
self.val = val
self.wordEnd = wordEnd
self.children = {}
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
# self._insertChar(self.root, word, 0)
idx = 0
node = self.root
while idx < len(word):
c = word[idx]
if c not in node.children:
node.children[c] = TrieNode(c)
idx += 1
node = node.children[c]
node.wordEnd = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
idx = 0
node = self.root
while idx < len(word):
c = word[idx]
if c not in node.children:
return False
else:
idx += 1
node = node.children[c]
return node.wordEnd
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
idx = 0
node = self.root
while idx < len(prefix):
c = prefix[idx]
if c not in node.children:
return False
else:
idx += 1
node = node.children[c]
return True
@staticmethod
def main():
obj = Trie()
obj.insert("apple")
print(obj.search('apple'))
print(obj.search('app'))
if __name__ == "__main__":
Trie.main()
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) | true |
253fc2a3b97c2cf4fddf3a059d8d550e05ffb890 | mcceTest/leetcode_py | /src/X125_ValidPalindrome.py | 1,326 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
sLen = len(s)
s = s.lower()
start = 0
end = sLen - 1
while start < end:
while start < sLen and not self.shouldConsider(s[start]):
start += 1
if start >= sLen:
return True
while end >= 0 and not self.shouldConsider(s[end]):
end -= 1
if end < 0:
return True
if start < end and s[start] != s[end]:
return False
start += 1
end -= 1
return True
def shouldConsider(self, c):
return (c >= 'a' and c <= 'z') or (c >= '0' and c <= '9')
@staticmethod
def main():
sol = Solution()
s = "A man, a plan, a canal: Panama"
print(sol.isPalindrome(s))
if __name__ == "__main__":
Solution.main()
| true |
2fa40c02fadcd988d2869f08802d6bbfffa637b6 | mcceTest/leetcode_py | /src/X166_FractiontoRecurringDecimal.py | 1,945 | 4.25 | 4 | '''
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
'''
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return '0'
isNeg = (numerator < 0) ^ (denominator < 0)
res = ""
if isNeg:
res += '-'
if numerator < 0:
numerator *= -1
if denominator < 0:
denominator *= -1
d = numerator // denominator
res += str(d)
numerator -= d * denominator
if numerator == 0:
return res
res += '.'
numerator *= 10
startIdxMap = {}
while numerator != 0:
if numerator < denominator:
res += '0'
numerator *= 10
else:
if numerator in startIdxMap:
# found repeats
idx = startIdxMap[numerator]
res = res[:idx] + '(' + str(res[idx:]) + ')'
break
else:
startIdxMap[numerator] = len(res)
cur = numerator // denominator
res += str(cur)
numerator -= cur * denominator
numerator *= 10
return res
@staticmethod
def main():
sol = Solution()
numerator = 1
denominator = 2
print(sol.fractionToDecimal(numerator, denominator))
if __name__ == "__main__":
Solution.main() | true |
ed491d076a9365eb0d635ba8b8211766923b50dc | picwell/pyboretum | /pyboretum/tree/base.py | 2,969 | 4.21875 | 4 | import abc
class Tree(object):
"""
A class to manage the storage for binary decision trees. Binary decision trees always
insert both children nodes if a parent node is split. As a result, there is a relation
between the number of leave nodes and the number of internal nodes:
(number of leave nodes) = (number of internal nodes) + 1
"""
@abc.abstractmethod
def get_root_id(self):
"""
Returns the root node ID. In many cases, this is used to start a recursion.
:return: a node ID
"""
pass
@abc.abstractmethod
def get_iterator(self):
"""
Returns a TreeIterator object that starts at the root node and traverses the tree.
:return: a TreeIterator object
"""
pass
@abc.abstractmethod
def get_node(self, node_id):
"""
Returns the corresponding Node object and its depth in a tree when a node ID is
given. If the ID is not found, it returns None.
:param node_id: a node ID
:return: (a Node object or None, int or None)
"""
pass
@abc.abstractmethod
def get_children_ids(self, node_id):
"""
Returns the two child IDs of a node. Two Nones are returned if
(a) the node itself is not found; or
(b) the found node is a leaf node.
:param node_id: a node ID
:return: a pair of node IDs or Nones
"""
pass
@abc.abstractmethod
def insert_children(self, node_id, left_node, right_node):
"""
Insert two nodes as children nodes of the given parent node. Insertion fails if the
parent node already has children.
:param node_id: a node ID for the parent
:param left_node, right_node: Node objects to insert
:return: a pair of child node IDs if successful
"""
pass
class TreeIterator(object):
"""
An iterator used to traverse a tree. It maintains a state to make the traversal efficient.
"""
@abc.abstractmethod
def left_child(self):
"""
Update the iterator to move to the left child. An exception is raised if the current
node is a leaf node.
"""
pass
@abc.abstractmethod
def right_child(self):
"""
Update the iterator to move to the right child. An exception is raised if the current
node is a leaf node.
"""
pass
@abc.abstractmethod
def is_leaf(self):
"""
Check whether the current node is a leaf node.
:return: True or False.
"""
pass
@abc.abstractmethod
def get_node(self):
"""
Returns the corresponding Node object and its depth.
:return: (a Node object, int)
"""
pass
@abc.abstractmethod
def get_id(self):
"""
Returns the ID of the corresponding Node.
:return: a node ID
"""
pass
| true |
29a10496aa24a289aaeb40cf33554791dfe9747c | alexanderahn/python-projects | /Project 8.py | 1,428 | 4.4375 | 4 | #Final Project
#Takes a directory as an argument, and then finds the extension of each file. Then, for each extension found, it prints the number of files with that extension and the minimum, average, and maximum size for files with that extension in the selected directory.
import os, sys
directory = input("Please enter a directory to learn more about the file types it contains: ")
print("\n")
if not os.path.isdir(directory):
print("Sorry, I cannot find your directory", directory, ".")
sys.exit()
files_dict = {}
for root, dirs, files in os.walk(directory):
for file in files:
if not files_dict.get(os.path.splitext(file)[1]):
files_dict[os.path.splitext(file)[1]] = []
files_dict[(os.path.splitext(file)[1])] += [(file, os.path.getsize(os.path.join(root, file)))]
for type in files_dict.keys():
count = 0
average = 0
for file,size in files_dict[type]:
count += size
average = count/len(files_dict[type])
print("The number of files with {} is {}.".format(type, len(files_dict[type])))
print("The minimum file size with {} is {}.".format(type, sorted(files_dict[type], key=lambda x: x[1])[0][1]))
print("The average file size with {} is {}.".format(type, average))
print("The maximum file size with {} is {}.".format(type, sorted(files_dict[type], key=lambda x: x[1])[-1][1]))
print("\n")
#Tested with /Users/alex.ahn/Documents
| true |
5fb776d22857f8ec419edad5d5d713ad743de7bf | Escartin85/scriptsPy | /standar_library/datetimes.py | 888 | 4.125 | 4 | from datetime import datetime, timedelta
import calendar
import time
now = datetime.now()
print(now.date())
print(now.time())
print(now.year)
print(now.month)
print(now.hour)
print(now.minute)
print(now.second)
print(now.strftime("%a %A %d"))
print(now.strftime("%b %B %m"))
print(now.strftime("%a %B %d"))
print(now.strftime("%H : %M : %S %p"))
print(now.strftime("%y %Y"))
# Work with before and after times from a time
testDateAfter = now + timedelta(days=2)
testDateBefore = now - timedelta(weeks=3)
print(testDateAfter.date())
print(testDateBefore.date())
if testDateAfter > testDateBefore:
print("Comparision works")
cal = calendar.month(2001, 10)
print(cal)
cal2 = calendar.weekday(2001, 10, 11)
print(cal2)
print(calendar.isleap(2000))
run = input("Start¿")
seconds = 1
if run == "yes":
while seconds != 10:
print(">", seconds)
time.sleep(1)
seconds += 1 | true |
3d95bc43165a9520979b76f1a4d226b2560a9f44 | Escartin85/scriptsPy | /exam_tests/example_test_1.py | 665 | 4.3125 | 4 | # A palindrome is a word that reads the same backward of forward
# Write a function that checks if a given word is a palindrome. Character case should be ignored.
# Fro example, is_palindrome("Deleveled") should return True as character case should be ignored, resulting in
# "deleveled", which is a palindrome since it reads the same backward and forward.
class Palindrome:
@staticmethod
def is_palindrome(word):
wordTmp = ""
word = word.lower()
for letter in word:
wordTmp = letter + wordTmp
if wordTmp == word:return True
return False
print(Palindrome.is_palindrome("Deleveled"))
| true |
8cdfbcb457ef1580121906d582bf36042ebdb624 | LaercioMSJ/Logic-and-Programming-I | /InClass/Lab8/Solution1.py | 1,010 | 4.34375 | 4 | ###########################################
# Desc: 1. Using a list of integers, build a function called
# FirstOrLast7 which returns True if a 7 appears as either
# the first or last element in the list. The list will be
# length 1 or more.
#
# Sample function calls & results:
# FirstOrLast7 ([1, 3, 7]) → True
# FirstOrLast7 ([7, 8, 2, 4]) → True
# FirstOrLast7 ([13, 7, 1, 5, 9]) → False
#
# Date: 23 October 2019
#
# Author: Laercio M da Silva Junior - W0433181.
###########################################
def FirstOrLast7(valueList):
return "7" in str(valueList[0]) or "7" in str(valueList[len(valueList)-1])
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# INPUT
numberList = [2,4,5,6,7,5,7]
# PROCESS
result = FirstOrLast7(numberList)
# OUTPUT
print("\n7 appears as either the first or last element in the list? " + str(result))
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
ed03de09c931dc6c903ddfe93595a1b7d2e6e0cf | LaercioMSJ/Logic-and-Programming-I | /LoopsAndListsExercises/Solution7.py | 654 | 4.21875 | 4 | ###########################################
# Desc: Write a program that reads a word and prints each
# character of the word on a separate lt "Harry",
# the program prints:
#
# H
# a
# r
# r
# y
#
# Date: 30 October 2019
#
# Author: Laercio M da Silva Junior - W0433181.
###########################################
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# INPUT
chosenWord = str(input("\nPlease, enter the a word: "))
# PROCESS
# OUTPUT
for char in chosenWord:
print("\n" + char)
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
7fbeb715742572020783136a4466f92b7017e8b8 | LaercioMSJ/Logic-and-Programming-I | /InClass/Lab8/Solution7.py | 773 | 4.40625 | 4 | ###########################################
# Desc: Given an integer list of length 2, return True if it contains a 2 or a 3.
#
# Sample function calls & results:
# Has2Or3 ([2, 5]) → True
# Has2Or3 ([4, 3]) → True
# Has2Or3 ([4, 5]) → False
#
# Date: 27 October 2019
#
# Author: Laercio M da Silva Junior - W0433181.
###########################################
def has2Or3(valueList):
return (2 in valueList or 3 in valueList)
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# INPUT
numberList = [7,2]
# PROCESS
result = has2Or3(numberList)
# OUTPUT
print("\nThe list contains a 2 or a 3: " + str(result))
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
77ebdc54a8ea30bdd1a20e9c3bb93b9b11846f43 | LaercioMSJ/Logic-and-Programming-I | /LoopsAndListsExercises/Solution9.py | 984 | 4.21875 | 4 | ###########################################
# Desc: Write a program that reads numbers and adds them to a
# list if they aren’t already contained in the list.
# When the list contains ten numbers, the program
# displays the contents and quits.
#
# Date: 01 November 2019
#
# Author: Laercio M da Silva Junior - W0433181.
###########################################
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# INPUT
listOfNumbers = []
while 10 > len(listOfNumbers):
inputedValue = input("\nPlease, enter a number: ")
if inputedValue.isnumeric():
valueCounter = listOfNumbers.count (int(inputedValue))
if valueCounter == 0:
listOfNumbers.append (int(inputedValue))
# PROCESS
# OUTPUT
print("\nThe list contains ten different numbers: " + str(listOfNumbers))
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
dc06935a771408dc7679c2da4d6a527a042f2e83 | LaercioMSJ/Logic-and-Programming-I | /Demo/Oct2Demo.py | 1,194 | 4.375 | 4 | ###########################################
# Desc: .
#
# Author: Laercio M da Silva Junior - W0433181.
###########################################
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# INPUT
country = input('Where are you from? ')
# PROCESS
if country == 'CANADA':
print('Hello')
elif country == 'GERMANY':
print ('Guten Tag')
elif country == 'FRANCE':
print('Bonjour')
country = 'VIETNAM'
pet = 'BEAVER'
if country == 'CANADA' and \
(pet == 'MOOSE' or pet == 'BEAVER'):
print('Do you play hockey too?')
monday = True
fresh_coffee = False
if monday:
#you could have code here to check for fresh coffee
# the if statement is nested, so this if statement
# is only executed if the other if statement is true
if fresh_coffee:
print('go buy a coffee!')
print('I hate Mondays')
print('now you can start work')
# OUTPUT
# print("Hello World")
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
162028189346fec1feafb0dc6200c1df181a355b | ehtashamp/python-projects | /oops_programs/inheritMultilevel.py | 1,429 | 4.34375 | 4 | """
Multilevel inheritance program
"""
class Car(object):
def moveCar(self, direction):
print('Car is moving towards: {} direction' . format(direction))
self.dir = direction
def brandCar(self, brand):
print('All car brand {}' . format(brand))
class EuroCar(Car):
def moveCar(self, direction):
print('Euro Car is moving towards: {} direction' . format(direction))
self.dir = direction
super(EuroCar, self).moveCar('random') #invoking parent or super class function
#if brandCar method doesn't exsit here then the control from indiaCar class
# will go to the super parent class Car and will execute its method.
def brandCar(self, brand):
if (brand == 'Audi'):
print('Euro car brand {}' . format(brand))
else:
print('{} is not euro car' . format(brand))
super(EuroCar, self).brandCar('Mustang')
class IndianCar(EuroCar):
def moveCar(self, direction):
print('Indian Car is moving towards: {} direction' . format(direction))
self.dir = direction
super(IndianCar, self).moveCar('right') #invoking parent or super class function
def brandCar(self, brand):
print('Indian car brand {}' . format(brand))
super(IndianCar, self).brandCar(brand)
audi = IndianCar()
audi.moveCar('left') #it looked for the moveCar method in the parent class
audi.brandCar('Audi')
| false |
4908caec54faffb8412df8282de2568111344a8a | ehtashamp/python-projects | /vehicle_num_combinations/vehiclenum.py | 1,858 | 4.28125 | 4 | """
Documentation interlude
Program to accept a lucky number from the end user and return
all possible combinations of vehicle numbers he can opt for.
This is based on the logic that the final sum of the digits of the vehicle
should be equal to the user's lucky number.
"""
def calc_lucky_number(number,lucky_num):
'''
Called recursively
Accepts int and int as parameters, iterated number and lucky number input by the end user
Returns 'int' , the number(single digit value)
'''
temp_list = list()
if(len(str(number)) != 1):
for i in str(number):
temp_list.append(int(i))
return calc_lucky_number(sum(temp_list),lucky_num)
elif len(str(number)) == 1:
return number
def getLuckyNum(lucky_num):
'''
Accepts int as parameter, lucky number input by the end user
Returns list, final list to the getInput function for displaying the output
'''
lucky_list = list()
for number in range(1,10000):
final_val = calc_lucky_number(number,lucky_num)
if final_val == lucky_num:
lucky_list.append(str(number).rjust(4,'0'))
return lucky_list
def getInput():
'''
Recursive, till a correct value is entered by the end user.
Accpets no parameters
Returns no parameters
Calls getLuckyNum function and prints the return value from it as a result to the end user.
'''
lucky_num = input('Enter your lucky number(0-9) for vehicle number generation:- ')
if len(lucky_num) == 1 and ord(lucky_num) in range(48,58):
list_num = getLuckyNum(int(lucky_num))
print(list_num)
del list_num
else:
print('Invalid input. Please provide a single digit numner between 0-9)')
#recursion added to prompt user to enter correct input
getInput()
# Execution begins!!!
getInput()
| true |
cde3dabf0dd06b72a382051a3daa74ca352af821 | ykzw/data_structures_and_algorithms | /python/sorting/selection.py | 1,017 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Sorting by selection"""
import heapq
def selection_sort(A):
n = len(A)
for i in range(n):
# Invariant: A[:i] is sorted
# "Select" the smallest element among A[i:]
_, j = min((A[j], j) for j in range(i, n))
# And swap A[i] and A[j]
A[i], A[j] = A[j], A[i]
def _siftdown_max(heap, i, end):
x = heap[i]
child = 2 * i + 1
while child < end:
right = child + 1
if right < end and not heap[right] < heap[child]:
child = right
if x > heap[child]:
break
heap[i] = heap[child]
i = child
child = 2 * i + 1
heap[i] = x
def heapsort(A):
n = len(A)
heapq._heapify_max(A)
for i in range(n - 1, 0, -1):
# Invariants:
# - A[:i+1] is a max-heap
# - A[i+1:] is sorted
# - Elements in A[:i+1] are less than or equal to those in A[i+1:]
A[0], A[i] = A[i], A[0]
_siftdown_max(A, 0, i)
| false |
9a541c535cf3698f0533a8723a89b8d99c5079d1 | jaredparmer/ThinkPythonRepo | /triangle.py | 490 | 4.28125 | 4 | def is_triangle(a, b, c):
if a > (b + c):
return False
if b > (a + c):
return False
if c > (a + b):
return False
return True
def check_triangle():
a = int(input("Length of side a: "))
b = int(input("Length of side b: "))
c = int(input("length of side c: "))
if is_triangle(a, b, c):
print("A triangle can be made out of those sides!")
else:
print("No triangle can be made out of those sides!")
check_triangle()
| true |
a41bb66df2488763b5e294c32e1fcf4bd77d708f | MaliciousFiles/Python-Projects | /Little_Projects/guess_the_number.py | 1,813 | 4.3125 | 4 | '''
The classic guess the number game
Author: MaliciousFiles (https://github.com/MaliciousFiles)
Contributor(s): mrmaxguns (https://github.com/mrmaxguns)
'''
# Imports
from random import randint
# Main function
def num_game(range=50, num_of_tries=5):
# Choose the random number
num = randint(1, range)
# Set the number of tries to the specified parameter
tries = num_of_tries
# The main game loop runs until there are no tries left
while tries > 0:
# Get the user's guess
guess = input('\nGuess a number from 1 to %s. You have %s try/tries left.\n' % (range, tries))
# Try to turn the guess into an integer
try:
guess = int(guess)
except ValueError:
# If a ValueError is raised, alert the user to enter an integer
print('%s is not an integer! Try again' % guess)
continue
# Check if the guess is in the guessing range
if guess < range and guess > 0:
# Excecute if the guess is the random number
if guess == num:
print('You WIN!!!')
break
# Excecute if the guess is too high
elif guess > num:
print('%s is too high. Try again.' % guess)
tries-=1
# Excecute if the guess is too low
elif guess < num :
print('%s is too low. Try again.' % guess)
tries-=1
# Excecute if the number is not in the guessing range
else:
print('%s is not in range! Try again.' % guess)
# Tell the player they lost if tries have run out
if tries == 0:
print('Oh no, you ran out of tries. I WIN!!!!!!!!!!!')
# Run the function if this module is run
if __name__ == "__main__":
num_game()
| true |
8e4b1f028034fa19c655f2256c4738948753444d | shihuaguo/python_study | /basic/list_tuple.py | 501 | 4.125 | 4 | # list
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
print(classmates[0])
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
print(classmates[0])
single_tuple = ('single',)
print(single_tuple)
# if
age = 18
if age <= 6:
print("age=", age)
elif age >= 12:
print("age=", age)
# 循环
for name in classmates:
print(name)
# dict and set
dict1 = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(dict1['Michael'])
set1 = {1, 2, 3}
set1.add(4)
for s in set1:
print(s)
| false |
82b74185c2288a74f9acc677a240d00a7162d5ae | hamsa125/lab1 | /lab1/camelcase.py | 1,090 | 4.28125 | 4 |
def main():
#intro
print('Camel case converter ')
# Getting a sentence from user, set all to lower case
sent = input("Enter the sentence you want to convert \n").lower().strip()
# Split the sentence into words
words = sent.split(' ')
# Create an array and Capitalize all words
sentArray = Capitalize(words)
# for Lab 1 the first word should be lowercase
camelcase = ''.join(Lab1Edit(sentArray))
print(camelcase)
def Capitalize(words):
capWords = []
# loop each word and capitalize it
for eashWord in words:
# Converting each word first letter to upper and appending it with remaining letters
final_words = eashWord[0].upper() + eashWord[1:].strip()
# Put all words into array
capWords.append(final_words)
return capWords
def Lab1Edit (sentArray):
#Change the first word to a lowercase
change = sentArray[0].lower()
sentArray[0]= change
#After the edit send back
return sentArray
if __name__ == '__main__':
main()
| true |
928ba695cf66024dd454e2b226531daf961e913b | jarelleboac/checkPermutation | /main.py | 570 | 4.125 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
def checkPermutation(string1, string2):
#sort them
#print("testing1")
string1sorted = sorted(string1)
string2sorted = sorted(string2)
#print("test")
#need to account spaces
length1 = len(string1)
length2 = len(string2)
if(length1 != length2):
#print("no")
return False
if(string1sorted == string2sorted):
#print("no")
return True
input1= "banana"
input2= "bna aan"
if(checkPermutation(input1, input2)):
print("yes")
else:
print("no") | true |
2efca34f92e8eba02a565e0b907de4ba6ae706b3 | d4libor/egjak-info-python | /priklad 3/zadanie-1.py | 492 | 4.375 | 4 | #To get current date and time we need to use the datetime library
from datetime import datetime, timedelta
# The now function returns current date and time
today = datetime.now()
print('Today is: ' + str(today))
#You can use timedelta to add or remove days, or weeks to a date
one_day = timedelta(days=1)
yesterday = today - one_day
print('Yesterday was: ' + str(yesterday))
one_week = timedelta(weeks=1)
last_week = today - one_week
print('Last week was: ' + str(last_week))
| true |
2a056ca4401009971c54254f3e8526f7e6e33582 | jokosystems/LearnPython | /ClassOps2.py | 983 | 4.125 | 4 | # Define a Class Called Cart that Contains Data Attributes Apples
# and Oranges. Write Methods that Return Appropriate Messages If the Number of
# Apples is Greater than 5 or When the Number of Oranges are Greater than 10.
class Cart:
def __init__(self, apples, oranges):
self.apples = apples
self.oranges = oranges
def apple_quantity_check(self):
if self.apples > 5:
return 'Sufficient Quantity'
else:
return 'Insufficient Quantity'
def orange_quantity_check(self):
if self.oranges > 10:
return 'Sufficient Quantity'
else:
return 'Insufficient Quantity'
def main():
fruits = Cart(oranges=3, apples=11)
returned_apple_message = fruits.apple_quantity_check()
returned_orange_message = fruits.orange_quantity_check()
print(f"Apple is in {returned_apple_message}")
print(f"Orange is in {returned_orange_message}")
if __name__ == "__main__":
main()
| true |
d9529fd4bb6a65250bbb6e3fbc539b90216425ac | kwadjooe/Learning_Python | /if_program_flow.py | 464 | 4.34375 | 4 | name = input("Please enter your name: ")
age = int(input("How old are you, {0} ? ".format(name)))
# Making decision base on the age
if (age >= 18):
print("Congratulation! {0}, you are old enough to vote".format(name))
print("Did you register to vote? it's important!")
else:
print("Sorry! {0}, Please wait until you turn 18 to register to vote. ".format(name))
print("Friendly reminder: you can register to vote in {0} years".format(18 - age))
| true |
f5e902aa61a7d8a26b032274f6ca58728adb45c3 | Matt-Girman/Projects | /matt_girman_pig_latin.py | 451 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Matt Girman
Pig Latin
11/8/19
"""
sentence = input("Type a sentence that you want converted to Pig Latin: ")
sentence = sentence.upper()
sentence = sentence.split(' ')
pig_latin = []
for x in sentence:
if x[-1].isalpha():
pig_latin.append(x[1:]+x[0]+'AY')
else:
pig_latin.append(x[1:-1] + x[0] + 'AY' + x[-1])
pig_sentence = ' '.join(pig_latin)
print(pig_sentence) | false |
4144704459a5ed1496c25b604b2ced2f999c56fe | Anson008/Think_Python_Exercise | /C16_Exercise.py | 2,110 | 4.25 | 4 | class Time:
""" Represents time of the day.
Attributes: hour, minute, second
"""
def valid_time(time):
if time.hour < 0 or time.minute < 0 or time.second < 0:
return False
if time.minute >= 60 or time.second >= 60:
return False
return True
def print_time(time):
print("{:02d}:{:02d}:{:02d}".format(time.hour, time.minute, time.second))
def is_after(t1, t2):
return (t1.hour, t1.minute, t1.second) < (t2.hour, t2.minute, t2.second)
def increment(time, seconds):
assert valid_time(time)
time.second += seconds
if time.second > 60:
time.minute += time.second // 60
time.second = time.second % 60
if time.minute > 60:
time.hour += time.minute // 60
time.minute = time.minute % 60
def increment_2(time, seconds):
""" A pure version of "increment" that creates and returns an new object."""
assert valid_time(time)
t2 = Time()
t2.second = time.second + seconds
t2.minute = time.minute
t2.hour = time.hour
if t2.second > 60:
t2.minute += t2.second // 60
t2.second = t2.second % 60
if t2.minute > 60:
t2.hour += t2.minute // 60
t2.minute = t2.minute % 60
return t2
def time_to_int(time):
assert valid_time(time)
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def increment_3(time, seconds):
assert valid_time(time)
seconds += time_to_int(time)
return int_to_time(seconds)
t1 = Time()
t1.hour = 14
t1.minute = 35
t1.second = 54
t2 = Time()
t2.hour = 14
t2.minute = 25
t2.second = 36
print_time(t1)
print(is_after(t1, t2))
increment(t1, 68)
print("{:02d}:{:02d}:{:02d}".format(t1.hour, t1.minute, t1.second))
t3 = increment_2(t1, 68)
print("{:02d}:{:02d}:{:02d}".format(t3.hour, t3.minute, t3.second))
t4 = increment_3(t2, 68)
print("{:02d}:{:02d}:{:02d}".format(t4.hour, t4.minute, t4.second))
| true |
85a3da62e01305d81ce8637be147a8bc93bd7896 | Anson008/Think_Python_Exercise | /Exercise_7_2.py | 531 | 4.34375 | 4 | import math
def eval_loop():
""" Iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated.
"""
while True:
s = str(input("Enter a string:\n"))
if s == "done":
print("Done!")
print("Last result:", res)
break
else:
res = eval(s)
print("Result:", res)
eval_loop()
| true |
98258f8e0cc658b4d9eaa682deae00aa9f787fd0 | Anson008/Think_Python_Exercise | /Exercise_9_4.py | 644 | 4.15625 | 4 | def has_letter(word, letter):
return letter in word
def find_letter(word, letters):
for letter in letters:
if has_letter(word, letter):
continue
else:
return False
return True
def use_only(word, letters):
""" Take a word and a string of letters, and that
returns True if the word contains only letters in the list.
"""
letters_in_word = list(word)
letters_in_string = list(letters)
print("Letters in word:", letters_in_word)
print("Letters in string:", letters_in_string)
return find_letter(letters, letters_in_word)
print(use_only("apple", "apue"))
| true |
e57df49fdbd10ef23f99f1e58b014ab309f236ea | Anson008/Think_Python_Exercise | /Exercise_15_2.py | 1,670 | 4.6875 | 5 | import turtle
import math
class Point:
""" Represents a point in 2D space.
Attributes: x, y
"""
class Rectangle:
""" Represents a rectangle in 2D space.
Attributes: width, height, corner
"""
class Circle:
""" Represents a circle in 2D space.
Attributes: center, radius
"""
def polygon(t, length, sides):
degree = 360/sides
for i in range(sides):
t.fd(length)
t.lt(degree)
def turtle_circle(t, r):
circumference = 2 * math.pi * r
sides = int(circumference / 3) + 1
length = circumference / sides
polygon(t, length, sides)
def draw_rect(t, rect):
""" Takes a turtle object and rectangle object as parameters.
Use the turtle to draw the rectangle.
t: turtle
rect: rectangle
"""
t.pu()
t.goto(rect.corner.x, rect.corner.y)
t.setheading(0)
t.pd()
for length in rect.width, rect.height, rect.width, rect.height:
t.fd(length)
t.lt(90)
def draw_circle(t, circle):
t.pu()
t.goto(circle.center.x, circle.center.y)
t.fd(circle.radius)
t.lt(90)
t.pd()
turtle_circle(t, circle.radius)
anson = turtle.Turtle()
# Draw the axes
length = 200
anson.fd(length)
anson.bk(length)
anson.lt(90)
anson.fd(length)
anson.bk(length)
# Draw a rectangle
rect = Rectangle()
rect.width = 60
rect.height = 90
rect.corner = Point()
rect.corner.x = 10
rect.corner.y = 30
draw_rect(anson, rect)
# Draw a circle
circle = Circle()
circle.center = Point()
circle.center.x = 70
circle.center.y = 80
circle.radius = 60
draw_circle(anson, circle)
# wait for the user to close window
turtle.mainloop()
| true |
f16740de2e4abe600108749a0340bdf464463147 | iSelickiy/GeekBrainsHW | /1quarter/igor_selickiy_dz_11/task_11_4.py | 1,169 | 4.28125 | 4 |
# 4. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число».
# Реализуйте перегрузку методов сложения и умножения комплексных чисел.
# Проверьте работу проекта. Для этого создаёте экземпляры класса (комплексные числа), выполните сложение и умножение созданных экземпляров.
# Проверьте корректность полученного результата.
class ComplexNum:
def __init__(self, num: int):
self.__num = complex(num)
def __str__(self):
return str(self.__num)
def __add__(self, num: int):
num.num = complex(str(num))
return self.__num + num.num
def __mul__(self, num: int):
num.num = complex(str(num))
return self.__num * num.num
#test
a = complex(2)
b = complex(3)
print(f'{a+b}/{a*b}')
a = ComplexNum(2)
b = ComplexNum(3)
print(f'{a+b}/{a*b}') | false |
2908fe4c019cc3b37e6599a731330b365661697d | ssavann/Python-Logical-Operators | /OrderPizza.py | 522 | 4.125 | 4 | #Take a pizza order and calculate the price
print("Welcome to Python Pizza Deliveries!")
size = input("What pizza size do you want? S, M or L? ")
addPepperoni = input("Do you want pepperoni? Y or N ")
extraCheese = input("Do you want extra cheese? Y or N ")
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
elif size == "L":
bill += 25
if addPepperoni == "Y":
if size == "S":
bill += 2
else:
bill += 3
if extraCheese == "Y":
bill += 1
print(f"Your final bill is: ${bill}")
| true |
9daf1d116d9e7fe751f5f86d3f0471029ec558f5 | wanghaoListening/python-study-demo | /day-exe/day10-6.py | 1,782 | 4.28125 | 4 | """
因为多个线程可以共享进程的内存空间,因此要实现多个线程间的通信相对简单,大家能想到的最直接的办法就是设置一个全局变量,
多个线程共享这个全局变量即可。但是当多个线程共享同一个变量(我们通常称之为“资源”)的时候,很有可能产生不可控的结果从
而导致程序失效甚至崩溃。如果一个资源被多个线程竞争使用,那么我们通常称之为“临界资源”,对“临界资源”的访问需要加上保护,
否则资源会处于“混乱”的状态。下面的例子演示了100个线程向同一个银行账户转账(转入1元钱)的场景,在这个例子中,银行账户
就是一个临界资源,在没有保护的情况下我们很有可能会得到错误的结果。
"""
from time import sleep
from threading import Thread
class Account(object):
def __init__(self):
self._balance = 0
def deposit(self,money):
# 计算存款后的余额
new_balance = self._balance + money
# 模拟受理存款业务需要0.01秒的时间
sleep(0.01)
# 修改账户余额
self._balance = new_balance
@property
def balance(self):
return self._balance
class AddMoney(Thread):
def __init__(self,account,money):
super().__init__()
self._account = account
self._money = money
def run(self):
self._account.deposit(self._money)
def main():
account = Account()
threads = []
for _ in range(100):
t = AddMoney(account,1)
threads.append(t)
t.start()
for t in threads:
t.join()
print('账户余额为: ¥%d元' % account.balance)
if __name__ == '__main__':
main() | false |
7a7fa2bd4627dfacade6626346e31bc71c3cc86b | wanghaoListening/python-study-demo | /object-oriented/access_permission.py | 1,752 | 4.15625 | 4 |
#访问限制
'''
让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,
就变成了一个私有变量(private),只有内部可以访问,外部不能访问
'''
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_score(self):
print('%s ,%s'%(self.__name,self.__score))
def get_name(self):
return self.__name
def get_scor(self):
return self.__score
def set_name(self,name):
self.__name=name
def set_score(self,score):
self.__score = score
class Person(object):
def __init__(self,name,gender):
self.__name = name
self.__gender = gender
def get_name(self):
return self.__name
def get_gender(self):
return self.__gender
'''
需要注意的是,在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。
有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量:
''' | false |
b0c002d2072bf7a8bec408fea9c92733665c8bcf | wanghaoListening/python-study-demo | /build-in-module/use_itertools.py | 1,598 | 4.1875 | 4 |
'''
Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数
'''
import itertools
natuals = itertools.count(1)
for n in natuals:
print(n)
'''
count()会创建一个无限的迭代器,上述代码会打印出自然数序列
'''
cs = itertools.cycle('abc')
for c in cs:
print(c)
'''
cycle()会把传入的一个序列无限重复下去
'''
ns = itertools.repeat('a',5)
for n in ns:
print(n)
'''
无限序列只有在for迭代时才会无限地迭代下去,如果只是创建了一个迭代对象,它不会事先把无限个元素生成出来,
事实上也不可能在内存中创建无限多个元素。
无限序列虽然可以无限迭代下去,但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列
'''
natuals = itertools.count(1)
nss = itertools.takewhile(lambda x:x<=20,natuals)
list(nss)
#chain()
'''
chain()可以把一组迭代对象串联起来,形成一个更大的迭代器:
'''
for c in itertools.chain('abc','xyz'):
print(c)
'''
groupby()把迭代器中相邻的重复元素挑出来放在一起
'''
for key,group in itertools.groupby('aaabbbcssaabbssdd'):
print(key,list(group))
'''
实际上挑选规则是通过函数完成的,只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,
而函数返回值作为组的key。如果我们要忽略大小写分组,就可以让元素'A'和'a'都返回相同的key
'''
for key,group in itertools.groupby('aaAbBbcSsaabbssDd',lambda c:c.upper()):
print(key,list(group))
| false |
db53d1e4ca5d2d212561076de85e7c0238def204 | OCWProject/OCWProject | /OCWProject/MIT6_0001F16/Lectures/lec5_tuples_lists.py | 2,307 | 4.21875 | 4 | # MIT6.0001- LECTURE 5: TUPLES, LISTS, ALIASING, MUTABILITY, CLONING
#############################
# Mutable: List #
# Immutable: Tuple, String #
#############################
# Tuples
# t1 = ()
# t2 = (1, "two", 3.0)
# print(t1)
# print(t2)
#
# # Returns multiple values with tuples
# def findDivisor(n1, n2):
# divisor = ()
# for i in range(1, min(n1, n2)):
# if n1 % i == 0 and n2 % i == 0:
# divisor += (i, )
# return divisor
#
# divisor = findDivisor(12, 16)
# print(divisor)
# Lists, Mutability
# Create empty list
# L = []
# L = ['I dit it all', 4, 'love']
# for i in range(len(L)):
# print(L[i])
##############################################################
# List operators #
# L.append(e): adds the object e to the end of L #
# L.count(e): returns numbers of time object e occurs in L #
# L.insert(i, e): insert object e into L at index i #
# L.extend(L2): adds items in L2 at the end of L #
# L.remove(e): deletes the first occurrence of e in L #
# L.index(e): returns the index of the #
# # first occurrence of e in L -> Raise EXCEPTION #
# L.pop(i): remove and return item at index i, #
# # otherwise return -1 #
# L.sort() sort elements of L (default: ASC order) #
# L.reverse(): reverse elements order in L #
##############################################################
# L1 = [1, 2, 3, 4]
# L1.reverse()
# print(L1)
# L1.extend(L)
# print(L1)
# print(L1)
# Cloning
# Reference L1 = L
# Cloning L1 = L[:]
# L2 = [-1, 1, -3, 0]
# Aliasing: L2 = L1
# <=> L1 & L2 are referenced to the same object
# L3 = L2
# L3.remove(-1)
# L3.remove(0)
# print('L2: ', L2)
# print('L3: ', L3)
# Cloning L2 = L1[:]
# L2 is copy all elements of L1
# but L1 and L2 are referenced 2 different objects
# L4 = [23, 6, 1994]
# L5 = L4[:]
# L5.remove(6)
# print('L4: ', L4)
# print('L5: ', L5)
# sort vs sorted
# sort: mutates list returns nothing
# sorted: does not mutates list
# L6 = [23, 6, 1994, 5, 11, 1995]
# L7 = L6[:]
# print('L6: ', L6)
# L6.sort()
# print('L6.sort(): ', L6)
# print()
# print('L7: ', L7)
# sorted(L7)
# print('sorted(L7): ', L7)
| false |
d168d90eb299aa21829edf3e901bb0b66e7e2732 | avimunk1/py4a | /3.3_score.py | 873 | 4.4375 | 4 | #3.3 Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range, print an error.
#If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit.
#For the test, enter a score of 0.85.
myscore='Invlid Input'
score=input('enter score: ')
try:
float(score)*1
except:
print('enter valid score between 0.0 and 1.0')
exit()
score=float(score)
if 0.9<=score<=1.0: myscore='A'
elif 0.8<=score<0.9: myscore='B'
elif 0.7<=score<0.8: myscore='C'
elif 0.6<=score<0.7: myscore='D'
elif 0.0<=score<0.6: myscore='F'
elif score > 1.0: myscore='invlid score score should be less than 1.0'
elif score < 0.0: myscore='invlid score score should be more than 0.0'
print(myscore)
| true |
c980ee0950dbb6fb35e84cde9ad85553e1f0f2a0 | avimunk1/py4a | /EX-8.4-files.py | 648 | 4.4375 | 4 | #8.4 Open the file romeo.txt and read it line by line. For each line,
#split the line into a list of words using the split() method.
#The program should build a list of words. For each word on each line
#check to see if the word is already in the list and if not append it to the list. When the program completes,
#sort and print the resulting words in alphabetical order.
fileH=open('inputs/'+"romeo.txt")
word=list()
for line in fileH:
line=line.strip()
mywords=line.split()
for Aword in mywords:
if Aword not in word:
word.append(Aword)
else:
continue
word.sort()
print(word)
#print('===')
| true |
09c0eae459be511df1ca0a01e74df0f2c68545da | CarolineShiphrah/Python-programs | /Reversing Numbers.py | 254 | 4.15625 | 4 | """ Reversing the given number by using while loop"""
N = int(input("Enter any Number to reverse: "))
rev = 0
number = N
while (N > 0):
rem = N % 10
rev = (rev * 10) + rem
N = N // 10
print("Reverse of number", number,"is", rev) | true |
7c75d326c4b127754a3109b929d895f949d7d449 | harryseong/Algorithms | /pythagorean_triples.py | 902 | 4.15625 | 4 | def py_trip(arr):
# Edge case #1: check to ensure that the array is at least 3 members.
if len(arr) < 3:
print('False: array is not at least 3 members.')
return False
# Edge case #2: check to ensure that all members of the array are non-zero, positives
for x in arr:
if x < 1 or x % 1 != 0:
print('False: mot a positive int.')
return False
# Sort array first in ascending order.
arr.sort()
# Convert all array members into squares of themselves.
arrsq = [x**2 for x in arr]
# Leave 2 for nested for loop.
for x in range(0, len(arrsq) - 2):
for y in range(0, len(arrsq) - x - 1):
if arrsq[len(arrsq) - 1 - x] == arrsq[len(arrsq) - 2 - x] + arrsq[y]:
print('True!')
return True
print('False: array does not contain pythagorean triples.')
return False | true |
bf2656ff43416a58ca1c5d52caad144f95534401 | bogdan71/python_playing | /pyDataScienceNumpy3.py | 1,250 | 4.21875 | 4 | import numpy as np
def makeTwoDim(x):
if len(x.shape)==1:
x = x.reshape(len(x) // 2, 2)
return x
# apple stock prices (May 2018)
prices = [189, 186, 186, 188,
187, 188, 188, 186,
188, 188, 187, 186]
data = np.array(prices)
data = makeTwoDim(data)
print(np.average(data[-1]))
Solution
186.5
Explanation
Numpy is a popular Python library for data science focusing on linear algebra.
This advanced puzzle combines multiple language concepts and numpy features. The topic is a miniature stock analysis of the Apple stock.
The puzzle creates a one-dimensional numpy array from raw price data. Note that the shape property of an n-dimensional numpy array is a tuple with n elements. Thus, a one-dimensional numpy array has a shape property of length one.
The function makeTwoDim(x) uses this to detect one-dimensional numpy arrays. Then, it transforms these into two-dimensional arrays using the reshape function. For each of the two dimensions, the reshape function needs the number of elements of this dimension. In particular, it creates a numpy array with two columns and half the number of rows.
Finally, we access the last row of this numpy array that contains the two numbers 187 and 186 and average them. | true |
6290d053ca00e80baa57f20a06e46851fa2fa59f | bogdan71/python_playing | /pyBinarySearchAlgorithm.py | 2,108 | 4.3125 | 4 | def bsearch(l, value):
lo, hi = 0, len(l)-1
while lo <= hi:
mid = (lo + hi) // 2
if l[mid] < value:
lo = mid + 1
elif value < l[mid]:
hi = mid - 1
else:
return mid
return -1
l = [0,1,2,3,4,5,6]
x = 6
print(bsearch(l,x))
# how?? to go to this puzzle? https://app.finxter.com/learn/computer/science/159
Solution
6
Explanation
How to find a value in a sorted list?
A naive algorithm compares each element in the list against the searched value. For example, consider a list of 1024 elements. The naive algorithm performs in the order of 1024 comparisons in the worst-case. In computer science, the worst-case runtime complexity can be expressed via the Big-O notation. We say, for n elements in a list, the naive algorithm needs O(n) comparisons. The function O defines the asymptotical worst-case growth.
The function bsearch is a more effective way to find a value in a sorted list. For n elements in the list, it needs to perform only O(log(n)) comparisons. In the same example, Bsearch requires only up to log(1024)=10 comparisons. Hence, Bsearch is much faster.
Why is Bsearch so fast?
The naive algorithm compares all elements with the searched value. Instead, Bsearch uses the property that the list is sorted in an ascending manner. It checks only the element in the middle position between two indices lo and hi.
If this middle element is smaller than the searched value, all left-hand elements will be smaller as well because of the sorted list. Hence, we set the lower index lo to the position right of the middle element.
If this middle element is larger than the searched value, all right-hand elements will be larger as well. Hence, we set the upper index hi to the position left of the middle element.
Only if the middle element is exactly the same as the searched value, we return the index of this position.
This procedure is repeated until we find the searched value or there are no values left. In each loop iteration, we reduce the search space, i.e., the number of elements between lo and hi, by half. | true |
10b11697edc6a2fc62f653d94fa6853cfe4bf422 | blessingayo/NewPythonExercises | /cartesian_plane.py | 353 | 4.25 | 4 | x = float(input("Enter any positive or negative number"))
y = float(input("Enter another positive or negative number"))
if x == 0 and y == 0:
print("it's the origin")
elif x == 0 or y == 0:
print("One of the coordinate is equal to zero")
elif x >= 0 or y >= 0:
print("I")
elif x <= 0 or y <= 0:
print("III")
else:
print("II")
| true |
29e3f15be01d2354ba899f6a2329c85cf37ae05e | blessingayo/NewPythonExercises | /venv/OptionalClause.py | 217 | 4.21875 | 4 | for i in range(2):
value = int(input('Enter a number (press -1 to break): '))
print('You entered:' , value)
if value == -1:
break
else:
print('Theloop terminated without executing the break') | true |
1bb3cdb1b0631ea1232f9829cabb6ffc1595c7df | jauvariah/RandomCode | /CareerCupQuestions/ch1q6.py | 217 | 4.28125 | 4 | #Write a function that adds two numbers without using + or arithmetic operators
def addition(a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
print addition(1, 5)
| true |
d9b9b283dd3ba48731cd8267208a9aef9f7ea265 | stevebtang/coderdojo-beginner-python-week-1 | /multiplication game.py | 1,304 | 4.34375 | 4 | import random
# Finish the Game
# 1. Ask the user for his name
# 2. Print a welcome message introducing the game and a goodbye message when user leaves
# 3. Use random so it doesn't ask 1 x 1 every time (look at the number guessing game for an example)
# 4. How can you repeat the code so it asks 10 questions in a row?
# You could use a for loop that repeats code a specific number of times. This line will repeat the indented code 10 times:
# for num in range(0,10):
# Bonus 1. Can you count how many times they got questions wrong and tell them at the end of the game?
# Bonus 2. Can you add another level with a harder num range?
# Bonus 3. Can you add addition and subtraction problems as well?
# Bonus 4. Can you ask to multiply/add/subtract 3 numbers instead of 2?
# Bonus 5. What other games can you do with user input?
# Bonus 6. Can you build a calculator ?
# ---- code below this line ------------
#print your welcome message here
for num in range(0,1):
#pick the numbers to multiply
number1 = 1
number2 = 1
answer = number1 * number2
guess = 0
print ("What is", number1, "x", number2, "?")
while guess != answer:
guess = int(input("Answer: "))
if guess != answer:
print ("No, try again")
print ("You got it!")
| true |
2ea56d01a6a69ad826af1fc43bc4c1bdbc57ceda | victorsilva-ibmec/datamining-2020-1 | /ola_mundo.py | 2,355 | 4.25 | 4 | # Precedencia de operacoes:
# ** (potencia)
# * / (multiplicacao e divisao)
# + - (soma e subtracao)
def faz_conta():
return 0
def oi():
print('oi')
print('oi')
def soma_dois_valores(valor1, valor2):
return valor1 + valor2
def raiz(valor, base):
return valor ** (1 / base)
def e_par(valor):
return (valor % 2) == 0
def div_por_seis(valor):
return ((valor % 2) == 0) and ((valor % 3) == 0)
def testa_par():
"""Le um valor inserido pelo usuario, verifica se o valor e par e retorna uma mensagem."""
parada = False
while parada == False:
valor = input('Insira um valor numérico, ou aperte ENTER para encerrar...\n')
if valor == '':
parada = True
elif e_par(int(valor)) == True:
print('O valor inserido é par.')
else:
print('O valor inserido é ímpar.')
def dez_mult_tres():
"""Imprime os primeiros 10 numeros nao negativos multiplos de 3."""
cont = 0
numero = 1
while cont < 10:
if numero % 3 == 0:
print(numero)
cont += 1
numero += 1 # numero = numero + 1
def ordena_tres_numeros(valor1, valor2, valor3):
if valor1 > valor2:
valor1, valor2 = valor2, valor1
if valor2 > valor3:
valor2, valor3 = valor3, valor2
if valor1 > valor2:
valor1, valor2 = valor2, valor1
print(valor1, valor2, valor3)
def decompoe_numero(valor):
print(valor % 10)
print((valor // 10) % 10)
print(valor // 100)
def e_multiplo(valor, divisor):
if valor % divisor == 0:
print('É múltiplo de', divisor)
else:
print('Não é múltiplo de', divisor)
def informa_pares():
for i in range(3):
valor = int(input('Insira um número.\n'))
e_multiplo(valor, 2)
def informa_maior():
maximo = 0
for i in range(3):
valor = int(input('Insira um número.\n'))
if valor > maximo:
maximo = valor
print('O maior valor inserido é', maximo)
def informa_maior_alt():
numeros = []
for i in range(3):
numeros.append(int(input('Informe um valor.\n')))
print(max(numeros))
def main():
informa_maior_alt()
if __name__ == '__main__':
main()
| false |
3bcf808fb20fc020313d03892b62cd880b0fa973 | JASURALTA17/jasmine2828 | /Python/Suralta.py | 672 | 4.125 | 4 | #v1 = "Jasmine"
#v1 = v1.strip()
#String Functions
#print(len(v1))
#print(v1.upper())
#print(v1.lower())
#print(v1.replace('i', 'ea'))
#v2 = input("Name: ")
#v2 = input("Course and Section: ")
#v2 = input("Contact Number: ")
#v2 = input("Email Address: ")
#print("First character: %s" %(v2[0]))
#print("First 3 character: %s" %(v2[0:3]))
#print("Last 3 character: %s" %(v2[len(v2)-3]))
v5 = "xxxxxxxxxxxxxxxx"
print(v5)
v5 = "x _ _ x"
print(v5)
v5 = "x O O x"
print(v5)
v5 = "x ^ x"
print(v5)
v5 = "x \_______/ x"
print(v5)
v5 = "x x"
print(v5)
v5 = "xxxxxxxxxxxxxxxx"
print(v5)
v5 = v5.strip()
| false |
0b4b5ddbe484f5ed909e1049f8793d2d4fe3a754 | tanishq-dubey/personalprojects | /Pi to the Nth Digit/piCalc.py | 648 | 4.125 | 4 | import math
from math import factorial
from decimal import *
digitAccuracy = int(input("Enter the digit of Pi to calculate to: "))
digitCounter = int(input("Enter desired accuracy of calulation: "))
getcontext().prec = int(digitAccuracy)
pi = Decimal(0)
k = 0
while k < digitCounter:
pi += (Decimal(-1) ** k) * (Decimal(factorial(6 * k)) / ((factorial(k) ** 3) * (factorial(3 * k))) * (13591409 + 545140134 * k) / (640320 ** (3 * k)))
k = k + 1
pi = pi * Decimal(10005).sqrt()/4270934400
pi = pi**(-1)
accuracy = 100*((Decimal(math.pi)-pi)/pi)
print("Pi is about: ", pi)
print("Error is about: ", accuracy, "%")
| true |
0d589c2b7cfc1cae4300a2de0670378130ced1b0 | nom1/exercise | /19_bmi.py | 616 | 4.34375 | 4 | #this calculates BMI depending on your weight and height.
def BMI_calc ():
weight_kg = float(raw_input("what is your weight (kg): "))
height_cm = int(raw_input("what is your height (cm): "))
weight = weight_kg * 2.2
height = height_cm * 0.3937007874
BMI = (weight/(height*height))*703
if BMI > 18.5 and BMI < 25:
print("you are within the ideal range")
elif BMI > 25:
print("you are overweight. you should see your doctor.")
else:
print("your BMI is {0}.".format(BMI))
print("you are underweight. you should see your doctor")
BMI_calc()
| true |
1dc0e815f6070b98e31a92e120c5e5326e3f8f87 | yanxiqing/python-programming-questions | /Elementary/problem_2_mm.py | 213 | 4.21875 | 4 | """
Problem 2: Write a program that asks the user for her name and greets her with her name.
"""
if __name__ == "__main__":
user_name = input("Please type your name: ")
print("Hello " + user_name + "!")
| true |
93d58c6c72de0bffc6a6bd81e47bf430d6ab5831 | oway13/Schoolwork | /15Fall/1133 Intro to Programming Concepts/Python Labs/Lab 3/l3 s2.py | 466 | 4.3125 | 4 | xval = float(input('First value x: '))
yval = float(input('Second value y: '))
zval = float(input('Third value z: '))
if xval >= yval and xval >= zval:
#x greatest -> x
#x=y > z -> x/y
#x=y=z -> x/y/z
print(xval, 'is the largest value')
elif yval > xval and yval >= zval:
#y greatest -> y
#y=z > x -> y/z
print(yval, 'is the largest value')
elif zval > xval and zval > yval:
#z greatest -> z
print(zval, 'is the largest value')
| false |
cde7aae5095e16dedc1a14e2d248375ee761ad3b | SamSamhuns/financial_utility_applications | /Discounted Cash Flow/main_DCF.py | 2,464 | 4.1875 | 4 | # coding: utf-8
import matplotlib.pyplot as plt
import numpy as np
import sys
# Utility Python program for calculating Net Present Value of cash flows over a yearly period
# DCF Calculations for yearly cash flows
# All cash flows must be presented on a yearly basis in the form of a CSV file as described below
# discount rate has to be entered separately.
# Author: Samridha Man Shrestha
# 2018-11-12
# Using Python 3
# import matplotlib as mpl
# mpl.use('Agg')
# Function to calculate present value of cash flow
# rate is in % per year and time is in years
def presentVal(futureVal, rate, time):
return futureVal / ((1 + (rate / 100))**time)
# CSV file format
# Note that current year is stated as 0
# year, cash_flow
# 0, -30000
# 1, 1500
# 2, 1600
def main():
if len(sys.argv) != 3:
print("Usage: python main_DCF.py <DISCOUNT RATE> <CSV FILE>")
sys.exit()
# Error check
try:
fp = open(sys.argv[2], 'r')
# Discount rate entered as a percentage
d_rate = float(sys.argv[1])
except IOError:
print(sys.argv[2], " does not exist." )
print("Usage: python main_DCF.py <DISCOUNT RATE> <CSV FILE>")
sys.exit()
except ValueError:
print(sys.argv[1], " must be a number without %." )
print("Usage: python main_DCF.py <DISCOUNT RATE> <CSV FILE>")
sys.exit()
# Generate header, a list containing the first two elems of the CSV file
header = fp.readline().strip().split(',')
npv = 0 # Net Present Value
cashFlowList = []
# loop to go through the CSV file parsing each line to separate the years and cash flow
# into a two dimensional array cashFlowList
for line in fp:
line = line.strip().split(',')
cashFlowTemp = []
for i in range(len(header)):
cashFlowTemp.append(int(line[i]))
cashFlowList.append(cashFlowTemp)
npv += presentVal(cashFlowTemp[1], d_rate, cashFlowTemp[0])
npCF = np.array(cashFlowList)
# Creating a bar chart showing the cash flows overtime
plt.title("Cash Flows over time: Given a NPV of %.2f and yearly rate of %.2f%%" % (
npv, d_rate))
plt.xlabel('Years (0 = current year )')
plt.ylabel('Cash flow ($)')
plt.bar(npCF[:, 0], npCF[:, 1], alpha=0.9, width=0.2)
plt.savefig('cash_flow_fig.png')
plt.show()
fp.close()
if __name__ == "__main__":
main()
| true |
fa723aa150ed439c093ad3332ee9478f09f6fae3 | Samthecode132/Project-1 | /menu.py | 571 | 4.15625 | 4 | print("Hello. Welcome to Sam's Diner. What would you like to drink?")
def onlist(item,drinks_list):
for drink in drinks_list:
print (drink)
if drink == drinks_list:
return True
else:
return False
print("Ok. I will get that for you right away.")
answer==input ("What kind of appeatizer would you like?")
drink = ["water", "apple juice", "lemonade", "soda"]
x = [["Garlic Rolls", "Chicken Wings", "Meatballs"],["Chicken", "Spagetti", "Pizza", "Cheese Burger", "Steak"],["Cookies", "Cake", "Ice Cream", "Chocolate"]
| true |
4869238cb288c694968231deb4dfc3a0f451cbae | sky3cabe/Age | /input.py | 661 | 4.125 | 4 | def lol() :
if age > 5 :
print ("You are still kids.You should not go outside without your parents permission.")
if age > 12 :
print ("You are started to be a teenager.Good luck.")
if age > 18 :
print ("You are now a teenager.You still need your parents permission to go outside.")
if age > 25 :
print ("You are an adult.")
if age > 40 :
print ("You are started to be an old people.So fighting because you need to becareful of your health.")
if age > 59 :
print ("You are now an old people.")
# this is for the input
age=float (input("What is your age :"))
# this is for the output
age=lol() | true |
58c679554b35ed3cfb4223943ec60dc7b11aa9a2 | lidongze6/leetcode- | /976. 三角形的最大周长.py | 766 | 4.125 | 4 | def largestPerimeter(A):
"""
选择排序,依次找到最大的三个数,判断能否组成三角形
"""
if len(A) <= 2: return 0
l = len(A)
A=mergesort(A)
m = 0
while m <= l - 3:
if A[m] < A[m + 1] + A[m + 2]:
return A[m] + A[m + 1] + A[m + 2]
else:
m += 1
return 0
def mergesort(A):
if len(A)==1:
return A
mid=len(A)//2
left=mergesort(A[:mid])
right=mergesort(A[mid:])
return merge(left,right)
def merge(left,right):
res=[]
while left and right:
if left[0]>right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
res=res+left+right
return res
A = [3,6,2,3]
print(largestPerimeter(A))
| false |
5c2a746f0b44624de1c52ac64e76bc52ca505068 | bezmo/antbook | /scripts/recursive_func.py | 992 | 4.15625 | 4 | """Fibonacci sequence
"""
from typing import List
def fibonacci(i: int) -> int:
"""フィボナッチ数列
再起的に呼び出して計算する。
i = 40 くらいの小さいと思われる数値でも計算量が大変多くなる。
"""
if i == 1 or i == 0:
return i
return fibonacci(i - 1) + fibonacci(i - 2)
def fast_fibonacci(i: int) -> int:
"""高速化した(計算量を減らした)フィボナッチ数列
一度計算した i 番目のフィボナッチ数列をメモ用の配列に入れる。
配列のインデックスとフィボナッチ数列の i 番目を対応させること。
"""
memo: List[int] = [0] * (i + 1)
def _fibonacci(i):
if i == 1 or i == 0:
return i
if memo[i] != 0:
return memo[i]
memo[i] = _fibonacci(i - 1) + _fibonacci(i - 2)
return memo[i]
return _fibonacci(i)
if __name__ == '__main__':
print(fast_fibonacci(40))
| false |
3e139e7a7b41fa26ad7ccc4d8c11ddf345cb805e | puneeth1999/progamming-dsa-with-python | /Week-3/selectionSort.py | 1,081 | 4.34375 | 4 | '''
Notes on SELECTION SORT:
=> Scan the list from left to right
=> During the scan, perform the following:
=> Set min_pos to the current position.
=> Now, scan again using another loop from the current position to the right of the list. Let's call this a slice.
=> If the present element within the slice is less than min_pos element, l[min_pos] = l[present]
=> At this point, the minimum value of the current slice is found.
=> Now, swap the minimum value with the current position
=> Return the list.
Time Complexity : O(N^2) where N is the size of the input
Space Complexity: O(1) since, it does not take up any extra space
'''
def selectionSort(l):
# Scans from left to right
for start in range(len(l)):
min_pos = start # Gets assigned to the current position of the pointer
# Starts searching for min value from the current pointer (start) position
for i in range(start, len(l)):
if (l[i] < l[min_pos]):
min_pos = i
# Swap
l[min_pos], l[start] = l[start], l[min_pos]
return l
if __name__ == "__main__":
print(selectionSort([7,6,4,5,9,2,0,1]))
| true |
766cfad6c95ef18cdc5ec28ef35d2b636c385041 | CodeDrome/soundex-python | /soundex.py | 1,081 | 4.25 | 4 |
def soundex(name):
"""
The Soundex algorithm assigns a 1-letter + 3-digit code to strings,
the intention being that strings pronounced the same but spelled
differently have identical encodings; words pronounced similarly
should have similar encodings.
"""
soundexcoding = [' ', ' ', ' ', ' ']
soundexcodingindex = 1
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
mappings = "01230120022455012623010202"
soundexcoding[0] = name[0].upper()
for i in range(1, len(name)):
c = ord(name[i].upper()) - 65
if c >= 0 and c <= 25:
if mappings[c] != '0':
if mappings[c] != soundexcoding[soundexcodingindex-1]:
soundexcoding[soundexcodingindex] = mappings[c]
soundexcodingindex += 1
if soundexcodingindex > 3:
break
if soundexcodingindex <= 3:
while(soundexcodingindex <= 3):
soundexcoding[soundexcodingindex] = '0'
soundexcodingindex += 1
return ''.join(soundexcoding)
| true |
13d515f4b198aeac0e7826aeb33d0bde63e44e4f | exer047/Homework-2-Part-2 | /Task 2.py | 368 | 4.125 | 4 | first_number = int(input("Enter first number: "))
second_number = int(input("Enter second number: "))
third_number = int(input("Enter third number: "))
if first_number == second_number or second_number == third_number or third_number == first_number:
print(first_number + 5, second_number + 5, third_number + 5)
else:
print("There are no equal numbers!") | true |
e36888013efda40c82913bf1ae7da18013e10258 | PabloPedace/Python-Curso-Youtube | /expresiones_regulares1.py | 953 | 4.15625 | 4 | #Expresiones regulares
#Son una secuencia de caracteres que forman un patron de busqueda
#Sirven para el trabajo y procesamiento de texto
#Ejemplos:
#Buscar un texto que se ajusta a un formato determinado(correo electronico)
#Buscar sin existe o no una cadena de caracteres dentro de un texto
#Contar el numero de coincidencias dentro de un texto
#Etc.
import re
cadena="Vamos a aprender expresiones regulares en Python. Python es un lenguaje de sintaxis sencilla"
print(re.search("aprender", cadena))
print(re.search("aprenderrrr", cadena))
textoBuscar="aprender"
if re.search(textoBuscar, cadena) is not None:
print("He encontrado el texto")
else:
print("No he encontrado el texto")
textoEncontrado=re.search(textoBuscar, cadena)
print(textoEncontrado.start())
print(textoEncontrado.end())
print(textoEncontrado.span())
textoBuscar="Python"
print(re.findall(textoBuscar, cadena))
print(len(re.findall(textoBuscar, cadena)))
| false |
36a6cb5863e09839b462c82de91cb493da20eeab | PabloPedace/Python-Curso-Youtube | /lists.py | 1,953 | 4.53125 | 5 | #Listas
#Estructura de datos que nos permite almacenar gran cantidad
#de valores(equivalente a los array en otros lenguajes de programacion)
#En Python las lista pueden guardar diferente tipo de valores(en otros
#lenguajes no ocurre esto con los array)
#Se pueden expandir dinamicamente añadiendo nuevos elementos(otra)
#novedad respecto a los arrays en otros lenguajes
#
#Sintaxis
#nombreLista=[elem1, elem2, elem3....]
miLista=["María", "Pepe", "Marta", "Antonio"] * 3
print(miLista)
print(miLista[2])
print(miLista[-3])
#Porcion
print(miLista[0:3]) #Incluye el indice 0, 1 y 2, el 3 lo excluye
print(miLista[:2]) #Incluye el indice 1 y 1
print(miLista[2:]) #Incluye el indice 2 y 3
miLista.append("Carlos")
miLista.insert(2,"Sandra")
miLista.extend(["Pablo", "Ana", "Lucia"])
print(miLista)
print(miLista.index("Pablo"))
print("Ana" in miLista)
demo_list = [100, "Hello", True, [1, 2, 3, 'Hello World']]
print(demo_list)
colors = ["red", "blue", "green", "red"]
numero_lista = list((1, 2, 3, 4))
print(numero_lista)
numeros_listas = list((1, 2, 3, 4))
print(type(numeros_listas))
r = list(range(1, 11))
print(r)
print(type(colors))
print(dir(colors))
print(len(colors)) #Longitud
print(colors[1])
print("green" in colors)
print("orange" in colors)
print(colors)
#colors[1] = "black"
#print(colors)
#colors.append(("white", "yellow")) #Adjuntar
#colors.append(["white", "yellow"]) #Ampliar
colors.extend(["white", "yellow"])
print(colors)
(colors.insert(1, "violet")) #Inserta en cualquier posicion
colors.insert(len(colors), "violet") #Inserta en la ultima posicion
colors.pop() #o colors.pop(2) #Elimino el ultimo elemento
colors.remove("green") #Elimio el elemento green
#colors.clear() #Limpia todos los valores
colors.sort() #Ordena alfabeticamente
colors.sort(reverse=True) #Ordena alfabeticamente de manera inversa
print(colors.index("red"))
print(colors.index("yellow"))
print(colors.count("red"))
print(colors)
| false |
79c5410ff867b73c0961d990cfb49aace8209e96 | ravikiran32/Code | /Python/ExamplePyScripts/ReadingDataFromFile.py | 1,763 | 4.25 | 4 | #Simple reading from a text file in the same directory
#with open('pi_digits.txt') as file_object:
#contents = file_object.read()
#print(contents.rstrip())
#READING FROM A RELATIVE PATH
#Reading from a relative path i.e. a folder withing the host folder wher
#the python file is stored you use the \ notation to show where the file is located
#i.e. textfiles\Test_text.txt
#with open('textFiles\pi_digits.txt') as file_object:
#contents = file_object.read()
#print(contents.rstrip())
#READING FILE FROM ANY LOCATION ON THE NETWORK
#Remember that you will require security access to the files for this to work
#file_path = 'C:\TxtFiles\pi_digits.txt'
#with open(file_path) as file_object:
#contents = file_object.read()
#print(contents.rstrip())
#READ LINE BY LINE
#with open('textFiles\pi_digits.txt') as file_object:
#for line in file_object:
#print(line.rstrip())
#CONTENT TO A LIST
#with open('textFiles\pi_text.txt') as file_object:
#lines = file_object.readlines()
#for line in lines:
#print(line.rstrip().title())
#MANIPULATION DATA
#Place all data in one string
#file_name = 'textFiles\pi_digits.txt'
#with open(file_name) as file_object:
#lines = file_object.readlines()
#digit_string = ''
#for line in lines:
#digit_string += line.strip()
#print('Combined digit string'+digit_string+' With a length of '+str(len(digit_string)))
#Look for data in a string
file_name = 'textFiles\pi_digits.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
digit_string = ''
for line in lines:
digit_string += line.strip()
birthday = input('Enter your birthday in the format of ddmmyy:')
if birthday in digit_string:
print("its there")
else:
print("Sorry")
| true |
012dc94af01695bbdc0baf08a6234b6922312b64 | hirochri/job_prep | /binary_search.py | 2,086 | 4.1875 | 4 | def main():
#TODO write tests for these
pass
def binarySearch(self, nums, target):
l, r = 0, len(nums) - 1
#leq because it might be a list with one value
#and we still need to check equality, only need
#to return when l > r
while l <= r: #*
m = l + (r-l) // 2
if nums[m] > target:
r = m - 1 #Reduce right side of search space
elif nums[m] < target:
l = m + 1 #Reduce left side of search space
else:
return True
return False
#* If you have a problem where you are guaranteed an answer (can be value or just index to put value), you can do l < r and return nums[l]
# If you aren't guaranteed an answer, you need to be able to check when l == r and then return false if you end
# up moving l > r
# Binary search and insert has l < r since it has a guaranteed insert point always
#Return the index if the target is found,
#otherwise return the index where it would be if it were
#inserted in order. (Like bisect.bisect_left)
def binarysearch_insert(nums, target):
l, r = 0, len(nums) #Want to be able to insert past last element of array
#Usually len(nums)-1 for search only -> don't care about adding new elements
while l < r: #Guaranteed to always find an insertion point
m = l + (r-l) // 2
if nums[m] >= target: #$
#Reduce right side of search space
#Trying to find first element that is larger or equal to target
#Want to include this element and keep moving right boundary
#to the left if mid is another element that is greater or equal
r = m
else:
#Reduce left side of search space
l = m + 1
return l
#Returns index at which target is or leftmost index where it should be inserted
#To make this return the rightmost index at which target should be inserted,
#we can make the $ conditional simply nums[m] > target. This then makes it
#so in the end l is the index one past our rightmost target. To know if
#the rightmost target itself exists, simply check nums[l-1] == target
if __name__ == "__main__":
main()
| true |
cb187bd341915835e4b59515165251054a116aca | thaitanthien/CS50 | /exercises/cs50/pset6/pset6_mario less.py | 386 | 4.25 | 4 | from cs50 import get_int, get_string
# This program prints out a half-pyramid of a specified height
# Input the pyramid's height
while True:
n = get_int("Height: ")
if (n >= 1 and n <= 8):
break
# Generate the desired half-pyramid
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for k in range(i+1):
print("#", end="")
print() | true |
d3974ac87266817eca44873bb10f9d366aff3dfa | SwarnadeepGhosh/Python-Small-Projects | /weather_forecast_by_MetaWeather_API.py | 2,828 | 4.125 | 4 | # https://github.com/SwarnadeepGhosh
# Six Days Weather Forecast using Python and MetaWeather API
import requests
import time
API_ROOT = 'https://www.metaweather.com'
API_LOCATION = '/api/location/search/?query=' # + city
API_WEATHER = '/api/location/' # + woeid
def print_pause(printable_data):
time.sleep(1)
print(printable_data+'\n')
def display_weather(weather_data):
for i in range(len(weather_data)):
date = weather_data[i]['applicable_date']
state = weather_data[i]['weather_state_name']
max_temp = weather_data[i]['max_temp']
max_temp = round(max_temp, 2)
min_temp = weather_data[i]['min_temp']
min_temp = round(min_temp, 2)
print(f" {date} \t {state} \t High: {max_temp}°C \t Low: {min_temp}°C")
def check_again():
again = input('\nDo You want to check again ? (y/n) ').lower()
if again == 'n':
print_pause('Have a Good Day ..')
time.sleep(1.5)
elif again == 'y':
weather_report()
else:
print('I cant understand, Please try again..')
check_again()
def weather_report():
try:
print('Swarnadeep Welcomes you to the Weather Report Forecast.\n')
time.sleep(1)
city = input('Where in the World are you ? ')
print_pause('\nGetting Location Data...')
r1 = requests.get(API_ROOT + API_LOCATION + city)
# if r1.status_code == 200:
location_data = r1.json()
woeid = location_data[0]['woeid']
# print("Where on Earth ID is : "+str(woeid))
print_pause('Location Data Fetched successfully...')
time.sleep(1)
r2 = requests.get(API_ROOT + API_WEATHER + str(woeid))
print_pause('Getting Weather Data, Please wait...')
print_pause('Weather Data of ' + city.capitalize() + ':')
# We will get a dictionary having keys: consolidated_weather, time, sun_rise, sun_set, timezone_name, parent, sources, title, location_type, woeid, latt_long, timezone.
weather_data = r2.json()['consolidated_weather']
# We will get 6 day Weather Forecast data in weather data as a list of dictionaries.
# Each day having keys: id,weather_state_name, weather_state_abbr, wind_direction_compass, created, applicable_date, min_temp, max_temp, the_temp, wind_speed, wind_direction, air_pressure, humidity, visibility, predictability
display_weather(weather_data)
check_again()
except requests.exceptions.ConnectionError:
print('Sorry there is a network error')
time.sleep(1)
except:
print("I don't know where that is. Please enter only famous cities.\n")
time.sleep(1)
weather_report()
if __name__ == '__main__':
weather_report()
| false |
8737d582f37cb1ef3a35fe3fdcea24fa606ba777 | jamesluttringer2019/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 629 | 4.25 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
l = 0
maxlist=[]
while k <= len(nums):
chunk = nums[l:k]
m = chunk[0]
for i in chunk:
if i > m:
m = i
maxlist.append(m)
l+=1
k+=1
return maxlist
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
53adfc0e87e44c604f43b7d10859978f5d19f95c | jmg5219/Python_Dictionaries | /mad_lib_2.py | 1,690 | 4.375 | 4 | # Starting with an empty dictionary
madlib_word_choices = {
"noun": {},
"verb": {},
"adjective": {}
}
#User is prompted for inputs and these inputs are stored to the dictionary
#John was drinking a cold beer when his parrot attacked
madlib_word_choices["noun"][0] = input("Enter a noun: ") #John
madlib_word_choices["verb"][0] = input("Enter a verb: ") #drinking
madlib_word_choices["adjective"][0] = input("Enter an adjective: ") #cold
madlib_word_choices["noun"][1] = input("Enter a noun: ") #beer
madlib_word_choices["noun"][2] = input("Enter a noun: ") #parrot
#String interpolation prints the different inputs to the sentence
print("%s was %s a %s %s when his %s attacked." % (madlib_word_choices['noun'][0], madlib_word_choices['verb'][0], madlib_word_choices['adjective'][0], madlib_word_choices['noun'][1], madlib_word_choices['noun'][2]))
#New set of user inputs that are stored in the dictionary
# e.x: He dropped his beer and chased the parrot into the wrong alley.
madlib_word_choices["verb"][1] = input("Enter a verb: ") #Dropped
madlib_word_choices["noun"][3] = input("Enter a noun: ") # Beer
madlib_word_choices["verb"][2] = input("Enter a verb: ") #Chased
madlib_word_choices["noun"][4] = input("Enter a noun: ") # Parrot
madlib_word_choices["adjective"][1] = input("Enter an adjective: ") #Wrong
madlib_word_choices["noun"][5] = input("Enter a noun: ") #Alley
#string interpolation to use the inputs in the sentence
print("He %s his %s and %s the %s into the %s %s." % (madlib_word_choices['verb'][1], madlib_word_choices['noun'][3], madlib_word_choices['verb'][2], madlib_word_choices['noun'][4], madlib_word_choices['adjective'][1], madlib_word_choices['noun'][5]))
| true |
daa906f5e42176dddeed8a17bbf7de36481dce8b | Joaovictoroliveira/Exercicios-Python-Curso-em-Video | /ex_06_dobro_triplo_raizquadrada.py | 284 | 4.15625 | 4 | num = int(input('Digite um número: '))
dobro = num * 2
triplo = num * 3
raiz_quadrada = num ** (1/2)
print('O número digitado foi {}'.format(num))
print('Seu Dobro é {}'.format(dobro))
print('Seu triplo é {}'.format(triplo))
print('Sua raiz quadrada é {}'.format(raiz_quadrada)) | false |
2550ca89cba2575b646192472f1a9ef40ec6b8d4 | NobTakeda/PythonTraining | /20210201/tupleLesson.py | 334 | 4.1875 | 4 | tuple1=(3,5,7)
#タプルは中身の修正ができない。
print(len(tuple1))
print(tuple1[1])
print(sum(tuple1))
list1=list(tuple1) #タプルをリストに変換することは可能
print(list1)
list1.append(10)
print(list1)
a,b,c=tuple1
print(a,b,c)
x=10
y=20
x,y=y,x #2値の入れ替えが1行で済む
print(x)
print(y)
| false |
b8980fe88b6c5398a7c06b22eb8c9d8ec484c68f | COMPTCA/COMPTCA.github.io | /Tutorials/Python In Easy Steps Book/35-PartitioningSorts.py | 673 | 4.1875 | 4 | def quick_sort(array):
if len(array) > 1:
pivot = int(len(array)-1)
less = []; more = []
for element in range(len(array)):
value = array[element]
if element != pivot:
if value < array[pivot]:
less.append(value)
else:
more.append(value)
quick_sort(less); quick_sort(more)
print('\tLess:', less, '\tPivot:', array[pivot], '\tMore:', more)
array[:] = less + [array[pivot]] + more
print('\t\t...Merged:', array)
array = [5, 3, 1, 2, 6, 4]
print('Quick Sort...\nArray:', array)
quick_sort(array)
print('Array:', array)
| true |
8dc94a236f6f2018970b706abec0a96776cd1aac | Syase4ka/SomePythonExercises | /addGst.py | 551 | 4.15625 | 4 | def add_gst (list_of_prices):
""" Calculates a new list of prices including GST
Arguments:
list_of_prices - list of prices excluding GST (float)
Returns:
A new list where each element of the original list has GST added (float)
GST - 15%
>>> add_gst([])
[]
>>> add_gst([100])
[115.0]
>>> add_gst([100,200,350,712.23])
[115.0, 230.0, 402.5, 819.06]
"""
add_gst=[]
for item in list_of_prices:
list_with_gst = round(item*1.15,2)
add_gst+=[list_with_gst]
return add_gst
| true |
dc1f75ff342328d3491a1a14d9abd39e84e54ec4 | Syase4ka/SomePythonExercises | /binaryToDecimal.py | 496 | 4.3125 | 4 | def binary_to_decimal (binary_list):
""" Converts a list of binary digits into a decimal number
Arguments:
binary_list = list that consists of only 1's and 0's
Returns:
a decimal number (int)
>>> binary_to_decimal([1,0,0,1,1,0])
38
>>> binary_to_decimal([1,1,0,0,1])
25
"""
sum = 0
place_value = 1
for i in reverse_list(binary_list):
product = i*place_value
sum+=product
place_value = place_value*2
return sum
| true |
7e128587d954740c05b2995e4baa85332aa2fde4 | Syase4ka/SomePythonExercises | /bodyMaxIndex.py | 765 | 4.4375 | 4 | """ Calculates the Body Mass Index based on the height and weight of a person.
"""
# weight_in_kilograms = 44.5
weight_in_kilograms = 84
height_in_metres = 1.82
# height_in_metres = 1.58
body_mass_index = weight_in_kilograms/height_in_metres**2
print ("My weight is: " + str(weight_in_kilograms) + " kg") # str() - built-in python function, which transform float to string format. It allows you to concatenate both values
print ("My height is: " + str(height_in_metres) + " m")
print ("My Body Mass Index is: " + str(body_mass_index))
"""
If you don't want to use the str() function you can use multiple prints instead:
print ("My weight is: ")
print (weight_in_kilograms)
print ("My height is: ")
print (height_in_metres)
...
etc.
"""
| true |
3d4e288bb1dd7307d80fac672abce60574c8c1fd | VenkatramanTR/PythonLearning | /learning/basic_concepts/Decorator.py | 674 | 4.53125 | 5 | #Decorators are used to modify code of a function without directly editing a function. Lets say you have a
# remote function which you dont have access and you want to slightly modify the functionality of the
# function then we use decorator functionality in those cases
def div(a,b): # remote function which you dont have access
return a/b
def smartDiv(func):
def inner(a,b):
if(a<b):
a,b = b,a
return a/b
return inner
div_new = smartDiv(div)
div = smartDiv(div) # you can also have the same name of the original function. This line is same as that of
# the previous line
print(div_new(3,12))
print(div(4,20))
| true |
124e466b10211f301305684a43ce3e76a99953a8 | VenkatramanTR/PythonLearning | /learning/basic_concepts/IfLoop.py | 324 | 4.1875 | 4 | x=int(input("enter a number from 0 to 5 "))
if x==1:
print("you have entered one")
elif x==2:
print("you have entered two")
elif(x==3):
print("you have entered three")
elif(x==4):
print("you have entered four")
elif(x==5):
print("you have entered five")
else:
print("You have entered a wrong number") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.