blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4a1510182817ca687e96b12c6ff1764e5413ae40 | mikebpedersen/python_med_gerth | /uge_5/opgave8_4.py | 1,624 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Exercise 8.4* (validate leaf-labeled binary trees)
Assume we want to represent binary trees, where each leaf has a string as a
label, by a nested tuple. We require the leaves are labeled with distinct
non-empty strings and all non-leaf nodes have exactly two children.
E.g. is the following such a valid binary tree.
((('A', 'B'), 'C'), ('D', ('F', 'E')))
Write a function validate_string_tuple(t) that checks, i.e. returns
True or False, if the value t is a tuple only containing distinct strings,
e.g. ('a', 'b', 'c').
"""
def validate_string_tuple(t):
if isinstance(t, tuple):
return [True for i in range(len(t))] == [isinstance(a, str) for a in set(t)]
else:
return False
t = ('A', 'B')
print(validate_string_tuple(t))
"""
Write a recursive function valid_binary_tree(t) program that checks,
i.e. returns True or False, if a value is a recursive tuple representing a
binary tree as described above.
Hint. Use the method isinstance to check if a value is of class tuple or a str,
and solve (b) using a recursive function. Collect all leaf labels in a list,
and check if all leaves are distinct by converting to set.
"""
def valid_binary_tree(t):
b = []
print(validate_string_tuple(t))
if validate_string_tuple(t):
if len(t) == 2:
for i in t:
if isinstance(i, tuple):
valid_binary_tree(i)
b.append(t)
print(b)
print(validate_string_tuple(tuple(b)))
return b
t = ((('A', 'B'), 'C', 'G'), ('D', ('F', 'E')))
print(valid_binary_tree(t))
| true |
d9c23e09c23090d9f1b4da7686f5c1bae152392d | mikebpedersen/python_med_gerth | /uge_2/opgave2_7.py | 1,572 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 12:20:09 2020
@author: JensTrolle
"""
"""
import math
n = float(input("Write a number equal to or above 1 here "
"to approximate the square root: "))
while n <= 1: # Check for
n = float(input("Your number has to be equal to or "
"above 1, try again: "))
print("This is the actual square root of", n, ": ", math.sqrt(n))
x = n
# Set limit for how close the approximation has to be.
low = 10e-14
# No need for absolute value, as is squared, and x set = to n.
# If fraction of f(x) over f'(x) is greater than limit, then we
# have reached the precision we want.
# Simple calculation using newtons method as a base.
while low < (( x / 2 ) - ( n / ( 2 * x ))):
print("Current approximation: ", x)
x = x - (( x / 2 ) - ( n / ( 2 * x )))
print("This is the approximation of the square root of ", n, ": ", x)
"""
import math
n = float(input("Write a number equal to or above 1 here "
"to approximate the square root: "))
while n <= 1: # Check for input higher than 1.
n = float(input("Your number has to be equal to or "
"above 1, try again: "))
print("This is the actual square root of", n, ": ", math.sqrt(n))
x = n
high = n + 1
# Simple calculation using newtons method.
while high > x:
print("Current approximation: ", x)
high = x
x = x - ((x/2) - (n/(2*x)))
print("This is the approximation of the square root of ", n, ": ", x)
| true |
7042e40fc79bca2079f52355dfdf1ce45e0a8cd0 | mikebpedersen/python_med_gerth | /uge_5/opgave7_1.py | 715 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Exercise 7.1 (average)
"""
"""
Write a function average2(x,y) that computes the average of x and y,
i.e. (x+y)/2.
"""
def average2(x, y):
return (x+y)/2
print(average2(2, 6))
"""
Write a function list_average(L) that computes the average of the numbers in
the list L.
"""
L = [2, 3, 4, 31]
def list_average(L):
return sum(L)/len(L)
print(list_average(L))
"""
Write a function average(x1,...,xk) that takes an arbitray number of arguments
(but at least one) and computes the average of x1, ..., xk.
Hint. Use a * to indicate an arbitrary argument list.
"""
def average(x, *y):
return list_average([x]+list(y))
print(average(1))
| true |
ad28a851eca6e4bbf663c671666248c0f56d82d0 | mikebpedersen/python_med_gerth | /uge_4/opgave5_2.py | 490 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given a list of first names first = ['Donald', 'Mickey', 'Scrooge'] and last
names last = ['Duck', 'Mouse', 'McDuck'], use list comprehension, zip, and
sorted to generate an alphabetically sorted list of names
'lastname, firstname', i.e. generates the list:
['Duck, Donald', 'McDuck, Scrooge', 'Mouse, Mickey'].
"""
first = ['Donald', 'Mickey', 'Scrooge']
last = ['Duck', 'Mouse', 'McDuck']
print(sorted([x + ", " + y for (x, y) in zip(last, first)]))
| true |
df1ec46df1e55ca8e8f46db217159836d1256687 | DuvanSGF/Python3x | /Listas2.py | 444 | 4.40625 | 4 | """
Una lista puede contener datos de todo tipo, lo que incluye cadenas,
numeros y hasta otras listas. Ademas, dentro de una lista puede mezclar tipos de Datos.
Para Acceder al contenido de una Lista dentro de otra, se pone un indice acontinuacion del otro:
"""
lista = [["1", "2", "3"], ["Uno", "Dos", "Tres"],"Hola"]
# Si quiero imprimir Dos
print lista[1][1]
# si quiero imprimir 3
print lista[0][2]
print lista[2][3]
print lista[1][0]
| false |
7cbfe54d027d3f83c972b06413347cddb18b4c58 | eduardobrennand/estrutura_sequencial | /11.py | 543 | 4.40625 | 4 | """Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
a)o produto do dobro do primeiro com metade do segundo .
b)a soma do triplo do primeiro com o terceiro.
c)o terceiro elevado ao cubo."""
n1 = int(input('Primeiro numero inteiro: '))
n2 = int(input('Segundo numero inteiro: '))
n3 = float(input('Numero real: '))
a = (n1 * 2) * (n2 / 2)
b = (n1 * 3) + n3
c = n3 ** 3
print('O resultado da letra A: {}'.format(a))
print('O resultado da letra B: {}'.format(b))
print('O resultado da letra C: {}'.format(c)) | false |
1e30df646d4e07c84f2becbacc64ae255da06a6a | Suleiman99Hesham/Algorithms-Foundations | /factorial.py | 303 | 4.3125 | 4 | def power(num,pwr):
if (pwr==0):
return 1
else:
return num*(power(num,pwr-1))
def factorial(num):
if num==0:
return 1
else:
return num*factorial(num-1)
print("{} to the power of {} is {}".format(2,3,power(2,3)))
print("{}! is {} ".format(3,factorial(3))) | true |
7f8bf75aac959e0a15af1349d1a53b1c9928a39a | Isabellajones71/plhme | /animal.py | 485 | 4.25 | 4 | #Abstraction is displaying only essential information to the user and hiding
# the details from the user
class Animal():
animal_kind = "Canine"
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
return("{}SaysI am eating Chicken".format(self.name))
# Dog1=Animal("Nyme",10)
# Dog2=Animal("Mone",5)
# print(Dog1.name)
# print("The first Dog's name is ",Dog1.name)
# print(Dog1.age)
# print(Dog1.eat())
# print(Dog2.eat()) | true |
964545ad94e3ec490a1c24a8bf40aeeb29780983 | mondaya/CodingCojo | /pythonstack/fundamentals/tasks/PythonFundamnetals/fun_with_function.py | 1,245 | 4.71875 | 5 | """
Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
"""
def odd_even() :
for num in range(1,2001):
if num % 2 == 1 :
print "Number is {}.".format(num), "This is odd number"
else :
print "Number is {}.".format(num), "This is even number"
"""
Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
"""
def multiply(data, mul):
new_list = []
for num in data :
new_list.append(num * mul);
return new_list;
# Verify
odd_even();
print multiply([2, 4, 10, 16], 5);
"""
Write a function that takes the multiply function call as an argument. Your new function should return the multiplied list as a two-dimensional list. Each internal list should contain as many ones as the number in the original list. Here's an example:
"""
def layered_multiples(arr):
new_list = []
for num in arr :
new_list.append([1 for i in range(0, num)]);
return new_list
# Verify
x = layered_multiples(multiply([2,4,5],3))
print x
| true |
fdd0783ae2773f4530ea0baf0bfb3d38d3f77206 | mondaya/CodingCojo | /pythonstack/fundamentals/tasks/PythonFundamnetals/names.py | 2,204 | 4.28125 | 4 | """
Part I:
Given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
Copy
Create a program that outputs:
Michael Jordan
John Rosales
Mark Guillen
KB Tonel
"""
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
for student in students :
print student['first_name'], student['last_name']
print
print
"""
Part II:
Now, given the following dictionary:
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
Copy
Create a program that prints the following format (including number of characters in each combined name):
Students
1 - MICHAEL JORDAN - 13
2 - JOHN ROSALES - 11
3 - MARK GUILLEN - 11
4 - KB TONEL - 7
Instructors
1 - MICHAEL CHOI - 11
2 - MARTIN PURYEAR - 13
"""
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
for type_of_users,users in dict.items(users) :
print type_of_users
for index, person in enumerate(users):
first = person['first_name'].upper()
last = person['last_name'].upper()
print index+1, "-", first, last, "-", len(first + last)
| false |
d1d63d749bc4669cc9e4ca06975805fdd9a26b50 | alex-dsouza777/Python-Basics | /Chapter 5 - Dictionary & Sets/05_set_methods.py | 514 | 4.21875 | 4 | #Creating empty set
b = set()
print(type(b))
#Adding values to an empty set
b.add(4)
b.add(5)
b.add(5) #Set is a collection of non repatative items so it will print 5 only once
b.add(5)
b.add(5)
b.add((4,5,6)) #You can add touple in set
#b.add({4:5}) # Cannot add list or dictionary to sets
print(b)
#Length of set
print(len(b)) #Prints the lngth of the set
#Removal of items
b.remove(5) #removes 5 from set b
#b.remove(10) #throws an error because 10 is not present in the set
print(b)
print(b.pop())
print(b) | true |
bc2db92500488ec07b4034dd8118d1b824989470 | alex-dsouza777/Python-Basics | /Chapter 7 - Loops in Python/12_pr_03.py | 202 | 4.40625 | 4 | #Program to print multiplication table of a given number using while loop
num = int(input("Enter the number "))
i=1
while i<=10:
a = num * i
print(f"{num} X {i} = {num*i}")
i=i+1
| true |
3605e055d5a03b1c1e8ea12a482e328336918086 | alex-dsouza777/Python-Basics | /Chapter 3 - Strings/09_pr_05.py | 295 | 4.15625 | 4 | #Format the following letter using escape sequence characters
#letter = "Dear Root, welcome to python course. Thank You!"
letter = "Dear Root, welcome to python course. Thank You!"
print(letter)
formatted_letter = "Dear Root, \n\tWelcome to python course.\n Thank You!"
print(formatted_letter) | true |
270444411a071df27ae14699aa4ffeab8bd4a74d | alex-dsouza777/Python-Basics | /Chapter 7 - Loops in Python/10_pr_01.py | 228 | 4.46875 | 4 | #Program to print multiplication table of a given number using for loop
num = int(input("Enter the number "))
for i in range(1, 11):
# print(str(num) + " X " +str(i) + " = " + str(i*num))
print(f"{num} X {i} = {num*i}") | true |
44ee90743a5ab2acf930418db50b534793cbec12 | alex-dsouza777/Python-Basics | /Chapter 13 - Advanced Python 2/09_pr_02.py | 459 | 4.4375 | 4 | #Write a program to input name, marks and phone number of a student and format it using the format function like below:
# “The name of the student is Root, his marks are 72 and the phone number is 99999888”
name = input("Enter Your Name: ")
marks = int(input("Enter Your Marks: "))
phone = int(input("Phone Number: "))
template = "The name of the student is {} his marks are {} and phone is {}"
output = template.format(name, marks, phone)
print(output) | true |
becf87c41cb32dcb20746b06c89951b9b6998b03 | Mikes-new/automate-stuff | /regexStrip.py | 505 | 4.15625 | 4 | #! python3
# regexStrip.py - performs same task as strip string method, using regexStrip
import re
def regexStrip(s, side=None): # s is string to be processed; side is left/right side of string
whitespaceRegex = re.compile(r'(\s*)(\S+.*\S+)(\s*)')
mo = whitespaceRegex.match(s)
if mo == None:
return ''
if side not in ["left", "right"]:
return mo.group(2)
elif side == "left":
return mo.group(2) + mo.group(3)
else:
return mo.group(1) + mo.group(2) | true |
637d88d2a950499b8b521069973da7ea65097516 | sanidhya-singh/sample-code-in-every-language | /python/quick-sort.py | 769 | 4.125 | 4 | """
SORTING ALGORITHM : QUICK SORT
TIME COMPLEXITY : O(nlogn)
"""
# implementation
def quicksort(arr):
if len(arr) <= 1: # base line for recursion
return arr
else:
pivot = arr.pop() # pivot, in this place last item in array
item_lower = [] # list having elements lower than pivot
item_greater = [] # list having elements greater than pivot
for item in arr: # adding elemnts into respective lists i.e lower/greater
if item < pivot:
item_lower.append(item)
else:
item_greater.append(item)
return quicksort(item_lower) + [pivot] + quicksort(item_greater) # returns [1..[pivot]....n]
arr = [5,4,3,2,1] # unsorted array
print(quicksort(arr))
| true |
64551fe02f2c244f9a89655e4e8720c5edaae789 | ajh1143/FireCode_Solutions | /Level_1/RepeatedArrayElements.py | 620 | 4.375 | 4 | """
Write a function - duplicate_items to find the redundant or repeated items in a list and return them in sorted order.
This method should return a list of redundant integers in ascending sorted order (as illustrated below).
Examples:
duplicate_items([1, 3, 4, 2, 1]) => [1]
duplicate_items([1, 3, 4, 2, 1, 2, 4]) => [1, 2, 4]
"""
def duplicate_items(list_numbers):
holder = {}
for each_element in list_numbers:
element_count = list_numbers.count(each_element)
if element_count > 1:
holder[each_element] = element_count
solution = list(holder.keys())
return solution
| true |
e4807875c3365081448a756183814d528622bc27 | rodneygauna/palomar-CSIT175-Python | /10/10-7.py | 719 | 4.59375 | 5 | # 10.7 - Basic Coding Skills
# 1. Code a program in a .py file that displays "Hello Python" on the console
print("Hello Python")
# 2. Change that program to use two print statements... the first displays "Hello" and the second displays "Python" on the next line of the console.
print("Hello")
print("Python")
# 3. Change that program, to indent the second print statement by two spaces and run it. Then correct the error and run it again.
print("Hello")
print(" Python")
# 4. Add a single line comment by itself and a single line comment that is placed on the same line as the first print statement. Run your program again to be sure it stills works.
print("Hello Python") # output should still be Hello Python
| true |
eab2f2aa2eaafdffd80e09e80594a5f4fabafe12 | rodneygauna/palomar-CSIT175-Python | /10/gauna_asgn1.py | 1,290 | 4.65625 | 5 | # Assignment 1
# Rodney Gauna // February 5, 2021
# Please carefully read the Instructions and Grading Criteria.
# Write a program that determines approximately how many years of your life you have been asleep.
# Name your program yourlastname_asgn1.py (obviously, replace "yourlastname" with your last name!)
# 1. Collect the name, age, and number of hours they sleep entered by the user into program variables
print("Assignment 1")
print("")
print("What is your name? (Example: John)")
users_name = input()
print("How old are you, " + users_name + "? (Example: 21)")
users_age = int(input())
print("About how many hours of sleep would you get per night? (Example: 7)")
hours_slept = int(input())
# 2. Use the following conceptual formula to determine how many years of their life has been wasted sleeping... wasted_years = (hours_slept/24) * users_age
wasted_years = (hours_slept/24) * users_age
# 3. Round the wasted_years result to two decimal places
wasted_years_rounded = round(wasted_years, 2)
# 4. Format a string message that is in the following format...
# Hello Steve.
# You have been unconscious for 18.33 years!
# 5. Print the message on the console
print("")
print("Hello " + users_name + ".")
print("You have been unconscious for " + str(wasted_years_rounded) + " years!")
| true |
0782b6162eba654f86f36d598ecbde39a43991de | Irlirion/data_structures_and_algorithms | /sort/quick_sort.py | 1,460 | 4.15625 | 4 | def quick_sort(arr: list, simulation=False) -> list:
"""
Quick sort \n
Complexity: best O(n log(n), avg O(n log(n), worst O(n^2)
"""
iteration = 0
if simulation:
print("iteration", iteration, ':', *arr)
arr, _ = __quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation)
return arr
def __quick_sort_recur(arr, first, last, iteration, simulation):
if first < last:
pos = __partition(arr, first, last)
# Start our two recursive calls
if simulation:
iteration += 1
print('iteration', iteration, ':', *arr)
_, iteration = __quick_sort_recur(arr, first, pos - 1, iteration,
simulation)
_, iteration = __quick_sort_recur(arr, pos + 1, last, iteration,
simulation)
return arr, iteration
def __partition(arr, first, last):
wall = first
for pos in range(first, last):
if arr[pos] < arr[last]: # last is the pivot
arr[pos], arr[wall] = arr[wall], arr[pos]
wall += 1
arr[wall], arr[last] = arr[last], arr[wall]
return wall
if __name__ == '__main__':
import random
lst = random.sample(range(10 ** 5), k=10 ** 5)
lst_sorted = quick_sort(lst)
print(all(
map(lambda x: x[0] <= x[1],
zip(lst_sorted[:-1],
lst_sorted[1:]
)
)
)
)
| false |
45f5a8f8848572354be4ed6c191dfd5d179a0b25 | PdxCodeGuild/class_mouse | /1 Python/solutions/practice1.py | 2,084 | 4.25 | 4 |
# Write a function that tells whether a number is even or odd (hint, compare a/2 and a//2, or use a%2)
def is_even(a):
if a % 2 == 0:
return True
else:
return False
# while a != 1 and a !=0:
# a //= 2
# if a == 0:
# return True
# elif a == 1:
# return False
# print(is_even(5)) # False
# print(is_even(6)) # True
# print(is_even('hello'))
# Write a function that takes two integers, a and b, and returns
# True if one is positive and the other is negative, and return False otherwise.
def opposite(a, b):
if a > 0 and b < 0:
return True
elif a < 0 and b > 0:
return True
else:
return False
# print(opposite(10, -1)) # True
# print(opposite(2, 3)) # False
# print(opposite(-1, -1)) # False
# print(opposite(0, 5))
# Write a function that returns True if a number within 10 of 100.
def near_100(num):
# if 90 <= num <= 110:
# return True
# else:
# return False
if num in range(90, 111):
return True
else:
return False
# print(near_100(50)) # False
# print(near_100(99)) # True
# print(near_100(105)) # True
# Write a function that returns the maximum of 3 parameters.
def maximum_of_three(a, b, c):
# return max(a, b, c)
# if a > b:
# if a > c:
# return a
# else:
# return c
# elif b > a:
# if b > c:
# return b
# else:
# return c
# else:
# if a > c:
# return a
# else:
# return c
numbers = [a, b, c]
numbers.sort()
return numbers[-1]
# print(maximum_of_three(5,6,2)) # 6
# print(maximum_of_three(-4,3,10)) # 10
# print(maximum_of_three(4, 4, 8))
# Write a loop to print the powers of 2 from 2^0 to 2^20
def print_powers_2():
# num = 0
# while num < 21:
# num +=1
for num in range(0, 21):
if num == 20:
print(2 ** num)
else:
print(2 ** num, end=", ")
print_powers_2() # 1, 2, 4, 8, 16, 32, ... | true |
2d18633081d491981fcf8adc3a99f70bb60eff15 | Igor-Zhelezniak-1/ICS3U-Assignment-2-Python-Program | /program.py | 530 | 4.5 | 4 | #!/usr/bin/env python3
# Created by: Igor
# Created on: Oct 2021
# This program calculates the area of a rectangle
# where the user gets to enter the length and width in mm
import math
def main():
# main function
print("We will be calculating the area of a rectangle. ")
# input
length = int(input("Enter the length (mm): "))
width = int(input("Enter the width (mm): "))
# process
area = length * width
# output
print("Area is {} mm²".format(area))
if __name__ == "__main__":
main()
| true |
053dc414d0451a1485a81ac0065812e34aab918e | andrex-naranjas/test | /CodigoDePractica/CodigoPython/clases.py | 1,505 | 4.5 | 4 | # Una clase es como un plano para crear objetos. Un objeto tiene propiedades y metodos (funciones) asociadas a el. Casi todo en python es un objeto (clase)
#Create a class
class Usuario:
#Constructor (funcion que corre cuando haces una instanciacion d una clase)
def __init__(self, nombre, email, edad):
self.nombre = nombre
self.email = email
self.edad = edad
def saludos(self,num1=1):
print(num1)
return 'Me llamo {0} y tengo {1}'.format(self.nombre,self.edad)
def tengo_cumple(self):
self.edad+=1
#Extender la clase Usuario
class Cliente(Usuario):
#Constructor (funcion que corre cuando haces una instanciacion d una clase)
def __init__(self, nombre, email, edad):
self.nombre = nombre
self.email = email
self.edad = edad
self.saldo = 0
def establecer_saldo(self,saldo):
self.saldo = saldo
def saludos(self):
return 'Me llamo {0}, tengo {1} y mi saldo es {2}'.format(self.nombre,self.edad,self.saldo)
#Init un objeto para el usuario
Andres = Usuario('Andres Ramirez','andres@gmail.com',31)
print(type(Andres))
print(Andres.nombre)
print(Andres.saludos('d'))
Andres.tengo_cumple()
print(Andres.saludos())
print('--------------------------')
#Init un Cliente
Rufina_usuario = Usuario('Rufina Madrid', 'rufina@yahoo.com',2)
Rufina_cliente = Cliente('Rufina Madrid', 'rufina@yahoo.com',2)
Rufina_cliente.establecer_saldo(5e10)
print(Rufina_cliente.saludos())
print(Rufina_usuario.saludos())
| false |
27a3da7ffae3c001f3de463c3b31f0af99012de7 | QMSS-G5072-2020/cipher_Zhou_Xuanyi | /cipher_xz2959/cipher_xz2959.py | 906 | 4.40625 | 4 | def cipher(text, shift, encrypt=True):
"""
Encrypt the text using shift coding.
Args:
text (str): represent the source text
shift (int): the shift size
encrypt (bool): True for encrypt and False for decrypt
Returns:
str: represent the cipher
Examples:
>>> cipher("hello cipher!", 10)
rovvy mszroB!
>>> cipher("hello cipher!", -2)
fcjjm agnfcp!
>>> cipher("fcjjm agnfcp!", 2)
hello cipher!
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index + 1]
return new_text
| true |
c60eb356afc847057629ec1d0365bfedfc6e93b9 | Navaneeth1706/Agile_notes | /datatype.py | 1,185 | 4.28125 | 4 | #Day2 in training
# 1. Print function displays the contents
# 2. type function display data type of the variable
no = 10
print(no)
print(type(no))
no = 4.5
print(no)
print(type(no))
result = True
print(result)
print(type(result))
name = 'navanee'
print(name)
print(type(name))
print(id(name))
no = 2
print(no)
print(id(no))
no2 = 4
print(no2)
print(id(no2))
#len function takes length of the variable and print function displays the length of the variable.
name = 'thasha'
print(len(name))
no = 888.894555
#Round function takes whole number.
print(round(no))
#Round[round(no,2)] function gives 2numbers after decimalpoints
print(round(no,2))
#Round[round(no,3)] function gives 2numbers after decimalpoints
print(round(no,3))
#Follow practice shows us the way to display numbers in
# 1. Binary form
# 2. Octal form
# 3. Hexa decimal form
#binary form
no = 0B0101
print(no)
no = 0b0101
print(no)
#Octal form
no = 0o776
print(no)
no = 0O776
print(no)
#Hexa form
no = 0X123
print(no)
no = 0x123
print(no)
no = 0Xabc
print(no)
no = 0xCAB
print(no)
#Using functions for binary/octal/hexa
no = bin(20)
print(no)
no = oct(20)
print(no)
no = hex(20)
print(no)
| true |
5436afe22ed781d05b56c883689085b7c2e0ecd5 | IsFilimonov/Interviews | /LeetCode/Python/101-Symmetric_Tree.py | 1,239 | 4.25 | 4 | from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def is_equal(L, R):
if not L and not R:
return True
# Important: at first look for None nodes and after for values
if L and R and L.val == R.val:
# We move first along the ribs to maximum depth (DFS Preorder) on both sides.
# Turn right after reaching the bottom.
return is_equal(L.left, R.right) and is_equal(L.right, R.left)
return False
return is_equal(root, root)
if __name__ == "__main__":
s = Solution()
node_1 = TreeNode(1)
node_2 = TreeNode(2)
node_3 = TreeNode(2)
node_4 = TreeNode(3)
node_5 = TreeNode(3)
node_6 = TreeNode(4)
node_7 = TreeNode(4)
node_1.left = node_2
node_1.right = node_3
node_2.left = node_4
node_2.right = node_6
node_3.right = node_5
node_3.left = node_7
assert s.isSymmetric(node_1) == True
print("well done!")
| true |
f16f0128f3a8ef33871daddf811ee4ab20396fa7 | stur-na/wordguess_game | /word_game.py | 1,383 | 4.15625 | 4 | '''This project taught me about the open module and the readline method
and also the random shuffle method'''
#import the random shuffle module for shuffling the dictionary list
from random import shuffle
#Start game
def start_game():
print('Welcome to the word guess game, guess a word from the dictionary')
print('You have FIVE(5) guesses per round')
while True:
game()
ahead = input('would you like to play again?\npress any key to continue or press the ENTER key to exit the game: ')
if ahead:
continue
else:
print('Goodbye!')
break
#compare the user input with the computer word
def compare(ui, comp):
if ui == comp:
print('Hurray! you got the word correctly')
else:
print('Aw, you missed this time')
print('The word was {}'.format(comp))
#logic
def game():
count = 1
score = 0
wordlist = []
with open(r"C:\Users\Cloud\Documents\python-tuts\engmix.txt", encoding="ANSI") as dic_file:
wordlist = dic_file.readlines()
shuffle(wordlist)
for i in wordlist:
userinput = input('Guess a word from the list: ')
compare(userinput, i)
count+=1
if userinput == i:
score+=1
if count == 6:
break
print('you got {} word(s) correctly in this round'.format(score))
start_game()
| true |
4ef99db04a657a26292c03880b8656a67e96e60f | rex-mcall/Learn-Python-Course | /ex32.py | 682 | 4.59375 | 5 | the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this for loop goes through a list
for number in the_count:
print(f"This is count {number}")
for fruit in fruits:
print(f"A fruit type: {fruit}")
#We can go through mixed lists too
#We use an empty {} since we do not know what's in it
for i in change:
print(f"I got {i}")
#We can also build lists; first start with an empty one
elements = []
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)
# Now we can print that list:
for i in elements:
print(f"Element was: {i}.") | true |
3dc4eaecee2a1b71b7fbeb16f7429ea04ae8e8e0 | upeismcschatbot/upeismcschatbot | /chatbot/Chatbot_Server_Code.py | 825 | 4.1875 | 4 | """
This code receives an argument from a PHP code (could be any code really though. Since a sentence is received as an array it appends
the array together to get one string called result.
It is important to note that the Website will grab the first print statement it sees and return that to the user.
THERE SHOULD BE ONLY ONE PRINT STATEMENT IN THE FINAL VERSION OR THIS WILL NOT WORK, the print statement acts as a return statement.
"""
import sys
args = sys.argv[1:]#grabs the arguments (user's query)
result = ""
for arg in args: #Loops through the arguments (User's query) to convert it from an array to a string since arguments are passed as an array
result += (arg + " ")
result += ("here is an added on sentence")#appends an new line to the query
print (result)#returns the query to the user | true |
ff11412fb41a249d7dfb3efd8a9d57e6c1954271 | luohengsdjzu/python_study | /Day05/垃圾回收.py | 390 | 4.125 | 4 | # -*- encoding:utf-8 -*-
# 垃圾回收机制详解
# 1、引用计数
# x = 10 # 直接引用
# print(id(x))
#
# l = ['a', x] # 间接引用
# print(id(l[1]))
#
# d = {'name': x} # 间接引用
# print(id(d['name']))
x = 10
l = ['a', 'b', x] # 列表当中实际上存的是内存地址,跟x变量没关系
x = 123
print(l[2])
print(x)
# 2、标记清除
# 3、分代回收
| false |
679fef8e6b5042aac4d69704e59e88c044b795ba | NNADIHENRY/python_program | /area-of-a-sector.py | 223 | 4.28125 | 4 | """ area of a sector
by NNADI HENRY IFEANYI
08139264713 nnadihenry92@gmail.com """
pi = 3.142857
r = float(input("enter radius: "))
o = float(input("enter the angle in degree: "))
area = (o/360) * pi * r * r
print("area = " + str(area))
| false |
3256b9c3b9704fe7477cb2cd5adcffa1f7e9d474 | NNADIHENRY/python_program | /arc-lenght-of-an-angle.py | 237 | 4.21875 | 4 | """ arc length of an angle(2*pi*r*(angle/360))
by NNADI HENRY IFEANYI
08139264713 nnadihenry92@gmail.com """
pi = 3.142857
r = float(input("enter radius: "))
o = float(input("enter the angle: "))
length = 2*pi*r*(o/360)
print("area = " + str(length))
| false |
3c93e65dfe2297a146d72234a173992248152cda | monishreddy143/oops-concepts | /00p2.py | 1,125 | 4.375 | 4 | #inheritance
#super() method will allow the sub class ti acces any class constructers and
#als0 it is use to acces the methods also
class grandpa:
#constructers in inheritance
def __init__(self):
print("my son is father class")
def name1(self):
print("my name is monish im aged")
def age1(self):
print('my age is 70')
class father(grandpa):#[father:]
def __init__(self):
print("my son is child class")
super().__init__()
def name2 (self):
print('my name is roshan im middle aged')
def age2 (self):
print('my age is 40')
def show(self):
print(sis.name1(),sis.name2())
class child(father,grandpa):#[chile(grandpa , father)]#multilevel inheritance
def __init__(self):
print('im the son of father class')
super().__init__()
def name3(self):
print('my nams is munny im young')
def age3(self):
print("my age is 20")
def show(self):
print(sis.name1(),sis.name3())
super().show()
#note-if there is no constructre in the sub class sthen the constructer in super class will be used in subclasss
sis =child()
sis.show() | false |
a536eff68fa30383df537430136a0d8c4ad56dbc | TechArpit20/Python-Playlist | /operators1.py | 1,725 | 4.46875 | 4 | '''
Operatore are basically used to perform various operations on the values contained in different variables
Types of Operators:
1. Arithmetic operators=> Addition(+), Subtraction(-), Multiplication(*), Division(/), Modulus(%), Exponential(**), Floor Division(//)
2. Assignment => (=), (+=), (-=),
3. Comparison operators=> Equal(==), Not equal(!=), Greater than(>), Less than(<), Greater than and equal to(>=)
4. Logical operators=> and, or, not
5. Identity operators=> is, is not
6. Membership operators=> in, not in
7. Bitwise operators=> AND(&), OR(|), XOR(^), NOT(~), Zero fill Left Shift(<<), Signed Right Shift(>>)
'''
a=10
b=8
########### Arthmetic ################r#######
print('\nArithmetic')
print('Addition: ',a+b)
print('Subtraction: ',a-b)
print('Mutliplication: ',a*b)
print('Division: ',a/b)
print('Modulus: ',a%b)
print('Exponential: ',a**b)
print('Floor Division: ',a//b)
########### Assignment #######################
print('\nAssignment')
c=a
print('=: ',c)
c=10
c+=2 #c=c+2
print('+=: ',c)
c=10
c-=2
print('-=: ',c)
c=10
c*=2
print('*=: ',c)
c=10
c/=2
print('/=: ',c)
c=10
c**=2 # c= c**2
print('**=: ',c)
c=10
c//=2
print('//= ',c)
########### Comparison #######################
print('\nComparison')
a=10
b=5
c=10
d=[1,2,3]
e=[1,2,3]
f=[1,2,3,4]
print(a==b)
print(a==c)
print(d==e)
print(d==f)
print(a!=b)
print(a<b)
print(a>c)
print(a>=c)
print(a<c)
print(a<=c)
########### Logical #######################
print('\nLogical')
a=10
b=5
c=10
print(a==b and a==c) # False and True => False
print(a==b or a==c) # False and True => True
print(not(a==b))
print(not(a==b or a==c))
| true |
b15a11759446e52d6f0ac0a12f9f9527de5e10ea | diamondjaxx/PyNet_Test1 | /ex7_yaml_json.py | 596 | 4.1875 | 4 | #!/usr/bin/env python
'''
Write a Python program that reads both the YAML file and the JSON file created in exercise6 and pretty prints the data structure that is returned.
'''
import yaml
import json
from pprint import pprint
def main():
yaml_file = 'my_file.yml'
json_file = 'my_file.json'
with open(yaml_file) as f:
my_yaml_list = yaml.load(f)
with open(json_file) as f:
my_json_list = json.load(f)
print 'YAML'
pprint(my_yaml_list)
print '\n'
print '-' * 20
print 'JSON'
pprint(my_json_list)
if __name__ == "__main__":
main()
| true |
9454af19a1bdb0c7072603a7eca55ffdb1122dbb | pirategiri/30daysOfPython | /day2/lengthcon.py | 1,836 | 4.21875 | 4 | # Python Programming Course : GUI Applications
# -Kiran Giri
# Length Converter ( Meter <-> Inch <-> Foot )
from tkinter import *
# Main window
App = Tk()
App.title("Length Converter")
App.geometry('350x150')
# Scales to be used
scales = ['Meters', 'Inches', 'Foot']
# The scale of the length to be used for conversion
_from = StringVar()
from_menu = OptionMenu(App, _from, *scales)
from_menu.grid(row=0, column=0, pady=5)
# In between label
lbl = Label(App, text=' convert to ')
lbl.grid(row=0, column=1, pady=5)
# The scale of the length to convert the value to
to_ = StringVar()
to_menu = OptionMenu(App, to_, *scales)
to_menu.grid(row=0, column=2, pady=5)
# Entry pre-label
numL = Label(App, text='Enter the number: ')
numL.grid(row=1, column=0, columnspan=2, pady=5)
# Entry field
numE = Entry(App)
numE.grid(row=1, column=2, columnspan=2, pady=5)
# Converter function
def num_con():
froM = _from.get()
tO = to_.get()
num = int(numE.get())
# Scales:
# 1 meter = 39.37 inches
# 1 meter = 3.28 foot
# 1 foot = 12 inches
if froM == 'Meters' and tO == 'Inches':
converted_num = num * 39.37
elif froM == 'Meters' and tO == 'Foot':
converted_num = num * 3.28
elif froM == 'Inches' and tO == 'Meters':
converted_num = num / 39.37
elif froM == 'Inches' and tO == 'Foot':
converted_num = num / 12
elif froM == 'Foot' and tO == 'Meters':
converted_num = num / 3.28
elif froM == 'Foot' and tO == 'Inches':
converted_num = num * 12
else:
converted_num = num
conv_numL = Label(App, text=round(converted_num, 2), width=10)
conv_numL.grid(row=1, column=4, pady=5)
# Convert button
conB = Button(App, text='Convert', command=num_con)
conB.grid(row=2, column=0, pady=5)
App.mainloop() | true |
8d050db21f700046e4f19488aa3beef872ab3cd6 | Prabin-Neupane/task1.py | /task5.py | 1,672 | 4.21875 | 4 | # bird = ['crows','pigeon','eagles','falcon','pigeon','falcon','falcon']
# Remove all the duplicates from the following list using while.
bird = ['crows','pigeon','eagles','falcon','pigeon','falcon','falcon']
new =[]
while bird:
x = bird.pop()
if x not in new:
new.append(x)
print(new)
#Deli: Make a list called sandwich_orders and fill it with the names of various sandwiches.
#Then make an empty list called finished_sandwiches . Loop through the list of sandwich orders and print a message
#for each order, such as I made your tuna sandwich. As each sandwich is made, move it to the list of finished sandwiches.
# After all the sandwiches have been made, print a message listing each sandwich that was made.
sandwitch_orders=['every','night','in','my','dream','i','see','you']
finished_sandwitch = []
while sandwitch_orders:
x = sandwitch_orders.pop()
print("I am making your {} sandwitch".format(x))
finished_sandwitch.append(x)
for items in finished_sandwitch:
print(items + "sandwitch is made . Aaija khana xito aailey sakinxa")
# Dream Vacation: Write a program that polls users about their dream vacation.
# Write a prompt similar to If you could visit one place in the world, where would you go?
# Include a block of code that prints the results of the poll.
from collections import Counter
action = True
lists = []
x=0
while action:
place = input("\nenter your dream vacation :")
lists.append(place)
again = input("\nany other dreams ? (Y/N)\n")
if (again == "N"):
action = False
print(lists)
duplicate_dict = {i:lists.count(i) for i in lists}
print(duplicate_dict)
poll = Counter(lists)
print(poll)
| true |
927338a47736e15dba2ce0efd15725f725563fd0 | analien-16/LearnCodingInPython | /Lesson-one/fibonacci.py | 255 | 4.28125 | 4 | # Write a program to generate the Fibonacci series up to a number
a, b = 0, 1
x = int (input("What is the last term you would like to display up to? " ))
print (0,1,end=' ')
while True:
c = a + b
a = b
b = c
if c > x: break
print(c, end=' ')
| true |
c754668b054d5bbe0a48f28a7c5f335d6fc6dc1a | ZandbergenM/Homework-week-5_Zandbergen | /Part 1 Exercise 9.2.py | 832 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#9.2 Write a function called has_no_e that returns True if the given word doesn't have the letter "e" in it
# Write a program that reads words.txt and prints only the words that have no "e", Compute the percentage of words in the list that have no "e"
# In[67]:
def has_no_e(word):
if "e" in word:
return False
else:
return True
print(has_no_e('eel'))
print(has_no_e('cow'))
# In[84]:
def only_no_e(f):
no_e = 0
yes_e = 0
with open(f) as fin:
for line in fin:
yes_e += 1
word = line.strip()
if has_no_e(word):
print (word)
no_e += 1
print (no_e/yes_e)
only_no_e('words.txt')
# In[ ]:
# In[64]:
# In[ ]:
| true |
1dd5b839e79f148b3e2a8b013b7677586546b15a | TunTunNikitun/Python_Programming | /1_module/1.12.7.py | 1,202 | 4.28125 | 4 | """
Паша очень любит кататься на общественном транспорте, а получая билет, сразу проверяет, счастливый ли ему попался.
Билет считается счастливым, если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета.
Однако Паша очень плохо считает в уме, поэтому попросил вас написать программу,
которая проверит равенство сумм и выведет "Счастливый", если суммы совпадают, и "Обычный", если суммы различны.
На вход программе подаётся строка из шести цифр.
Выводить нужно только слово "Счастливый" или "Обычный", с большой буквы.
"""
number=list((str(input())))
first=int(number[0])+int(number[1])+int(number[2])
second=int(number[3])+int(number[4])+int(number[5])
if first==second:
print('Счастливый')
else:
print('Обычный') | false |
6aead7adb7b835fb5477e49b8370ecc3b21c126b | rrssantos/Python | /Python39/ex1t5py.py | 373 | 4.21875 | 4 | #Pedir um número qualquer ao usuário e apresentar o fatorial deste número. Quando o valor 0
#for informado o programa deverá encerrar
import math
a = 1
while a > 0 :
a =int(input("digite o valor do numero para descobrir o Fatorial: "))
if a > 0 :
b = math.factorial(a)
print("o faltorial é : ", b)
else :
print("Fim")
| false |
a3f618fbdfbc1b9980ff08eeea6bb158437837dd | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/Harry_Maher/Python210B/Session03/slicing.py | 1,191 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Write some functions that take a sequence as an argument, and return a copy of that sequence:
with the first and last items exchanged.
with every other item removed.
with the first 4 and the last 4 items removed, and then every other item in between.
with the elements reversed (just with slicing).
with the middle third, then last third, then the first third in the new order.
"""
a_string = "this is a string"
a_tuple = (2, 54, 13, 12, 5, 32)
def exchange_first_last(seq):
"""the first and last items exchanged."""
return seq[-1]+seq[1:-1]+seq[0]
#print(exchange_first_last(a_string))
def every_other_removed(seq):
"""every other item removed."""
return seq[::2]
#print(every_other_removed(a_tuple))
def keep_middle(seq):
""" the first 4 and the last 4 items removed, and then every other item in between."""
return seq[4:-4:2]
#print(keep_middle(a_string))
def reverse_it(seq):
return seq[::-1]
#print(reverse_it(a_string))
def reorder(seq):
"""with the middle third, then last third, then the first third in the new order"""
thrd = len(seq)//3
return seq[thrd:-thrd]+seq[-thrd:]+seq[:thrd]
print(reorder(a_string))
| true |
4c5141f78846558468c0d0063838394610fe74dc | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/TracyA/session03/list_lab3.py | 602 | 4.15625 | 4 | #!/usr/bin/env python
# Programming in python B Winter 2018
# February 5, 2017
# list Lab #3
# Tracy Allen - git repo https://github.com/tenoverpar/Wi2018-Classroom
# Series 3 of list lab exercises
# Create a list with Apples, Pears, Oranges, and Peaches. Print the list.
fruits3 = ["Apples", "Pears", "Oranges", "Peaches"]
for fruit in fruits3:
rep = input('Do you like ' + fruit.lower() + ' ? ')
while (rep.lower() != 'yes') and (rep.lower() != 'no'):
rep = input("Please respond with 'yes' or 'no': ")
if rep.lower() == 'no':
del fruits3[fruit.index(fruit)]
print(fruits3)
| true |
f54058443bbc32eb2457e05b8e71ae49127e0ffc | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/jchristo/session11/range_iterator_assignment.py | 1,514 | 4.5625 | 5 | #!/usr/bin/env python
import itertools
"""
Simple iterator examples
"""
class IterateMe_1:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
else:
raise StopIteration
class IterateMe_2:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from given start to stop with step
( like range(4) )
"""
def __init__(self, start,stop,step=1):
self.current = (start - step)
self.start = start
self.stop = stop
self.step = step
assert (step != 0),"Step must not be zero!"
def __iter__(self):
return self
def __next__(self):
if self.current < self.stop:
self.current += self.step
return self.current
else:
raise StopIteration
def __str__(self):
return int(self.current)
if __name__ == "__main__":
print("Testing the iterator")
for i in IterateMe_2(2,20,2):
print (repr(i))
print("Testing break point")
it = IterateMe_2(2, 20, 2)
for i in it:
if i > 10: break
print(i)
print("Resume after break point")
for i in it:
print(i)
| true |
ea92968b66755c86da0f93dac46e7ef7fe5a84af | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/alxsk/session04/File_exercise.py | 744 | 4.25 | 4 | '''
Read file exercise
A script that reads students.txt and generates a list of the languages students know.
'''
languages=set()
with open('students.txt', 'r') as file_name:
for line in file_name:
line_split = line.split(":") #creates list
keep_lang=line_split.pop() # removes and returns last item in the list
langs=keep_lang.split(",") # splitting string
for lang in langs: # loop through each string and clean up whitespace
strip_lang= lang.strip()
if strip_lang and not strip_lang[0].isupper(): # Check if first letter isn't uppercase and empty string
languages.add(strip_lang)
print(languages)
| true |
112aa1ed121e19113544074b4fae75ae239162ed | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /solutions/Session03/string_formatting.py | 1,647 | 4.59375 | 5 | #!/usr/bin/env python
"""
String formatting lab:
This version using the format() method
"""
#####
# Write a format string that will take the tuple:
# (2, 123.4567, 10000, 12345.67)
# and produce:
# 'file_002 : 123.46, 1.00e+04, 1.23e+04'
#####
print("file_{:03d} : {:10.2f}, {:.2e}, {:.3g}".format(2, 123.4567, 10000, 12345.67))
print()
# Note the subtle differnce between the 'e' and 'g' formatting strings.
# I like 'g' -- it does significant figures.
#######################
# Rewrite: "the 3 numbers are: %i, %i, %i"%(1,2,3)
# for an arbitrary number of numbers...
# solution 1
# the goal was to demonstrate dynamic building of format strings:
def formatter(t):
# The static part of the string
fstring = "the {:d} numbers are: ".format(len(t))
# This add the correct number of format specifiers:
fstring += ", ".join(['{:d}'] * len(t))
# The created string can be now applied to the tuple of numbers
# * unpacks a sequence into the arguments of a function -- we'll get to that!
return fstring.format(*t)
# call it with a couple different tuples of numbers:
print(formatter((2, 3, 5)))
print(formatter((2, 3, 5, 7, 9)))
# solution 2
# You may have realized that str() would make a nice string from
# a list or tuple
# perfectly OK to use that -- though it doesn't demonstrate how you can
# dynamically build up format strings, and then use them later...
numbers = (34, 12, 3, 56)
numbers_str = str(numbers)[1:-1] # make a string, remove the brackets
# put it together with the rest of the string
print("the first {:d} numbers are: {}".format(len(numbers), numbers_str))
| true |
df75460a1d78ed644dc6123a042785c3bdff3f02 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/rusty_mann/Session02/series.py | 1,339 | 4.125 | 4 |
def fibonacci(n):
#if n == 0:
if n == 0 or n == 1:
return 0
#elif n == 1:
elif n == 2:
return 1
else:
return fibonacci(n-2)+fibonacci(n-1)
######################################################################
def lucas(n):
if n == 0:
return 0
elif n == 1:
return 2
elif n == 2:
return 1
else:
return lucas(n-2)+lucas(n-1)
#####################################################################
def sum_series(n, a=0, b=1):
"""produce nth number in fibonacci sereis with default a, b arguments
and nth number in lucas series if a, b arguments are set to 2 and 1"""
if n == 0:
return 0
elif n == 1:
return a
elif n == 2:
return b
else:
return sum_series(n-2,a,b)+sum_series(n-1,a,b)
#####################################################################
#testing output of fibonacci function
assert fibonacci(5) == 3
assert fibonacci(8) == 13
#testing output of lucas function
assert lucas(5) == 7
assert lucas(8) == 29
#testing output of sum_series with default a,b arguments
assert sum_series(5) == 3
assert sum_series(8) == 13
#testing output of sum_series function with values 2,1 assigned to a,b arguments
assert sum_series(5,2,1) == 7
assert sum_series(8,2,1) == 29
| false |
eadafa5a48a4a2eba2e37d3713d21d651a9962d4 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/jchristo/session03/list_lab.py | 1,273 | 4.21875 | 4 | #List Lab
#!/usr/bin/env python3
"""
Series 1
Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”.
Display the list (plain old print() is fine…).
Ask the user for another fruit and add it to the end of the list.
Display the list.
Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). Remember that Python uses zero-based indexing, so you will need to correct.
Add another fruit to the beginning of the list using “+” and display the list.
Add another fruit to the beginning of the list using insert() and display the list.
Display all the fruits that begin with “P”, using a for loop.
"""
def list_lab_s1():
fruit_list = ["Apples","Pears","Oranges","Peaches"]
print (fruit_list)
response = input("Please add any type of fruit to the list: ")
fruit_list.append(response)
print (fruit_list)
response_2 = input("Please enter a number: ")
print ("You entered the number " + response_2 +", which is the following fruit in the list: " +fruit_list[int(response_2)])
print (["Kiwi"] + fruit_list)
fruit_list.insert(0,"Grapes")
print (fruit_list)
for i in fruit_list:
if "P" in i:
print (i)
| true |
d5e535b0b668e17c434ed6af84632736550b6e90 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/maria/test.py | 2,311 | 4.1875 | 4 | # Return a copy of the sequence given after ordering transformation.
def split(s,x):
"""Given a sequence break into three variables."""
first = s[:x]
last = s[-x:]
middle = s[x:-x]
return first, last, middle
def first_last(s):
"""Return a copy of a given sequence with first and last items swapped."""
first, last, middle = split(s,1)
ls = last + middle + first
return ls
def every_other(s):
"""Return a copy of a given sequence, but with every other item removed."""
new_s = s[::2]
return new_s
def fl4_every_other(s):
"""Return copy of a given sequence with the first and last 4 items removed, and every other item in between."""
return every_other(s[4:-4])
def reverse(s):
"""Return copy of a given sequence in the reverse order."""
new_s = s[::-1]
return new_s
def sort_thirds(s):
"""Return copy of given sequence with the middle third, then last third, then the first third in the new order."""
x = int(len(s)/3)
first, last, middle = split(s,x)
ls = middle + last + first
return ls
# Test block to verify the functions above work properly, throws error if not.
a_string = "this is a string"
a_tuple = (2, 54, 13, 77, 12, 5, 32, 1, 0, 33, 45, 19, 100)
a_list = ['thing', 'another', 'example','mixed', 'with', 'numbers', 0, 1, 2]
assert first_last(a_string) == "ghis is a strint"
assert first_last(a_tuple) == (100, 54, 13, 77, 12, 5, 32, 1, 0, 33, 45, 19, 2)
assert first_last(a_list) == [2, 'another', 'example','mixed', 'with', 'numbers', 0, 1,'thing']
assert every_other(a_string) == "ti sasrn"
assert every_other(a_tuple) == (2, 13, 12, 32, 0, 45, 100)
assert every_other(a_list) == ['thing', 'example', 'with', 0, 2]
assert fl4_every_other(a_string) == ' sas'
assert fl4_every_other(a_tuple) == (12, 32, 0)
assert fl4_every_other(a_list) == ['with']
assert reverse(a_string) == 'gnirts a si siht'
assert reverse(a_tuple) == (100, 19, 45, 33, 0, 1, 32, 5, 12, 77, 13, 54, 2)
assert reverse(a_list) == [2, 1, 0, 'numbers', 'with', 'mixed', 'example', 'another', 'thing']
assert sort_thirds(a_string) == 'is a stringthis '
assert sort_thirds(a_tuple) == (12, 5, 32, 1, 0, 33, 45, 19, 100, 2, 54, 13, 77)
assert sort_thirds(a_list) == ['mixed', 'with', 'numbers', 0, 1, 2, 'thing', 'another', 'example'] | true |
a42b9f46df26cdbb91b2625ee4ab6b44b55d9d89 | IshpreetKGulati/100DaysOfCode | /day7.py | 1,259 | 4.3125 | 4 | """
Monotonic Array
Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.
An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non -decreasing.
Sample Input:
array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
Sample Output:
True
"""
"""
def monoArray(array):
if array == sorted(array):
return (True)
elif array == sorted(array, reverse = True):
return (True)
else:
return(False)
if __name__ == "__main__":
array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
print(monoArray(array))
"""
def monoArray(array):
inc = 0
dec = 0
for i in range(0, len(array)-1):
if array[i] < array [i+1] :
inc +=1
if dec != 0: # if at any point the array starts showing the behaviour of increasing order, then it it not monotonic, hence return false
return False
elif array[i] > array [i+1]:
dec += 1
if inc != 0: # if at any point the array starts showing the behaviour of decreasing order, then it it not monotonic, hence return false
return False
return True
if __name__ == "__main__":
array = [1, 1, 5, 6, 7]
print(monoArray(array))
| true |
18bb62cde4bf84e4734d3cb1cd05ae236c57a0bb | IshpreetKGulati/100DaysOfCode | /day29.py | 1,565 | 4.1875 | 4 | """
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Will share image in whatsapp group
Note:
The total number of elements of the given matrix will not exceed 10,000
"""
def return_diag(input_matrix):
if len(input_matrix) == 0:
return []
n = len(input_matrix) #rows
m = len(input_matrix[0]) #columns
i = j = 0
res = []
up = True #to check if we have to print from up to down or vice vera
#iterate from 0 to total number of diagnols i.e. sum of rows and column
for _ in range(0, n + m):
if up:
# add all the elements in the diagnol to the list till we reach the first row and last column
while i >= 0 and j < m :
res.append(input_matrix[i][j])
i -= 1
j += 1
#set the points i and j
if i < 0 and j<= m-1:
i = 0
if j == m:
j -= 1
i += 2
up = False
else:
#daignol elements to be printed from bottom to up till we reach the last row and first column
while i < n and j >=0:
res.append(input_matrix[i][j])
i += 1
j -= 1
#set pints i and j
if j < 0 and i <= n-1:
j = 0
if i == n:
i -= 1
j += 2
up = True
return res
if __name__ == "__main__":
input_matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
print(return_diag(input_matrix))
| true |
cd31a899c6e416d592f4a9feca8b008064a1e54b | hardy-awan/learning-python | /latPy/kalkulator2.py | 758 | 4.1875 | 4 | print("Masukan angka anda")
def add(x, y):
return x + y
angka1 = int(input("silahkan masukan angka pertama : "))
angka2 = int(input("silahkan masukan angka kedua : "))
operator= input("silahkan masukan penjumlahan:")
if operator == '+':
print('{} + {} = ', add(angka1, angka2))
print()
elif operator == "-":
print('{} - {} = '.format(angka1, angka2))
print(angka1 - angka2)
elif operator == f("*"):
print('{} * {} = '.format(angka1, angka2))
print(angka1 * angka2)
elif operator == f("/"):
print('{} / {} = '.format(angka1, angka2))
print(angka1 / angka2)
else:
print('You have not typed a valid operator, please run the program again.')
# calculate() | false |
83462da197bb2f281be4cb41779ea530cdf64fa9 | eduOSS/configuration_files | /Documents/python/git/forExce/guessNumber.py | 1,896 | 4.21875 | 4 | #template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import simplegui
# initialize global variables used in your code
range_num = 100
# helper function to start and restart the game
def new_game():
global secret_num, range_num, count
if(range_num == 100):
count = 7
else:
count = 10
secret_num = random.randrange(0, range_num)
print"New game, Range is from 0 to", range_num
print"Number of remaining guess is", count
print""
def range100():
# button that changes range to range [0,100) and restarts
global range_num, count
range_num = 100
count = 7
new_game()
def range1000():
# button that changes range to range [0,1000) and restarts
global range_num, count
range_num = 1000
count = 10
new_game()
def input_guess(guess):
# main game logic goes here
global guess_num, count, secret_num
guess_num = int(guess)
count -= 1
print"Guess was", guess_num
print"Number of remaining guess is",count
if(count <= 0):
print"You ran out of guess. The number was", secret_num
print""
new_game()
else:
if(guess_num > secret_num):
print"Lower!"
elif(guess_num < secret_num):
print"Higher!"
else:
print"Correct!"
print""
new_game()
print""
# create frame
frame = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
frame.add_input("Enter a guess", input_guess, 200)
# call new_game and start frame
frame.start()
new_game()
| true |
b1bfaeefd86ff33e4f6435d12811422df64d7741 | Joey-Marcotte/ICS3U-Unit4-03-Python | /to_the_power_of.py | 712 | 4.5 | 4 | #!/usr/bin/env python3
# Created by: Joey Marcotte
# Created on: October 2019
# This program shows the factorial of a number
def main():
power_of_number = 0
total_number = 0
# input
number = input("Input the number: ")
try:
number_as_number = int(number)
if number_as_number > 0:
for power_of_number in range(number_as_number + 1):
# process
total_number = power_of_number**2
print("{0}^2 = {1}".format(power_of_number, total_number))
else:
print("not a positive number")
except(ValueError):
print("That is not a valid number")
if __name__ == "__main__":
main()
| true |
20311467d24015b8ebcc512a6c899f163a142d5b | Lwarren51/cti110 | /P3HW2_SoftwareSales_WarrenLorenzo.py | 1,898 | 4.1875 | 4 | # CTI-110
# P3HW2 - Software Sales
# Lorenzo Warren
# March 11, 2018
# Get the quantity of the packages purchased 1.
quantity10_19 = float(input('Enter the number of packages purchased 1: '))
# Calculate the amount the discount total purchased.
discount = quantity10_19 * 99
# Display the discount.
print('The discount is $', format (discount, ',.2f'))
# Calculate the amount the discount total purchased.
totalCost = 99 - quantity10_19 * 99
# Display the totalCost.
print('The totalCost is $', format (totalCost, ',.2f'))
# Get the quantity of the packages purchased 2.
quantity20_49 = float(input('Enter the number of packages purchased 2: '))
# Calculate the amount the discount total purchased.
discount = quantity20_49 * 99
# Display the discount.
print('The discount is $', format (discount, ',.2f'))
# Calculate the amount the discount total purchased.
totalCost = 99 - quantity20_49 * 99
# Display the totalCost.
print('The totalCost is $', format (totalCost, ',.2f'))
# Get the quantity of the packages purchased 3.
quantity50_99 = float(input('Enter the number of packages purchased 3: '))
# Calculate the amount the discount total purchased.
discount = quantity50_99 * 99
# Display the discount.
print('The discount is $', format (discount, ',.2f'))
# Calculate the amount the discount total purchased.
totalCost = 99 - quantity50_99 * 99
# Display the totalCost.
print('The totalCost is $', format (totalCost, ',.2f'))
# Get the quantity of the packages purchased 4.
quantity100 = float(input('Enter the number of packages purchased 4: '))
# Calculate the amount the discount total purchased.
discount = quantity100 * 99
# Display the discount.
print('The discount is $', format (discount, ',.2f'))
# Calculate the amount the discount total purchased.
totalCost = 99 - quantity100 * 99
# Display the totalCost.
print('The totalCost is $', format (totalCost, ',.2f'))
| true |
51fc1d9a5e2f1933b89a9a9874c86a41f1b37b58 | sbtries/Class_Polar_Bear | /Code/Ryan/python/python3_lab_1.py | 1,403 | 4.15625 | 4 | score = input('Please enter a number representing the score (0-100): ')
# Need to do an input validation if a letter is typed in this will be taught in 102 and requires
# a 'try' / 'except' structure to see if using the float() function on the str would produce an error.
try:
score = float(score)
except ValueError:
print('invalid grade..goodbye')
exit()
specific_score = score % 10
if score == 100:
grade = 'A'
specific_score = 9
elif score >= 90 and score < 100:
grade = 'A'
elif score >= 80 and score < 90:
grade = 'B'
elif score >= 70 and score < 80:
grade = 'C'
elif score >= 60 and score < 70:
grade = 'D'
elif score >= 0 and score < 60:
grade = 'F'
specific_score = 5
# There is no F+ or F- letter grade so setting the variable to a fixed number to complete the following if statement
else:
print('Please enter a valid score 0-100')
#print(specific_score)
if specific_score < 4.5:
specific_grade = '-'
elif specific_score >= 5.5:
specific_grade = '+'
elif specific_score >= 4.5 and specific_score < 5.5:
specific_grade = ' '
else:
print('')
#print(type(score))
print(f'Your score of ({score}) is a(n) {grade}{specific_grade}')
'''
Long hand of the same as modulus
if score >= 90 and score < 94.5:
grade = 'A-'
elif score >= 94.5 and score < 95.5:
grade = 'A'
elif score >= 95.5 and score <= 100:
grade = 'A+'
''' | true |
6f4fbbe0cec197d63d5f8b212595075817e45bd9 | sbtries/Class_Polar_Bear | /Code/Ryan/python/blackjack_advice.py | 2,404 | 4.375 | 4 | # Let's write a python program to give basic blackjack playing advice during a game by asking the player for cards. First, ask the user for three playing cards (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, or K). Then, figure out the point value of each card individually. Number cards are worth their number, all face cards are worth 10. At this point, assume aces are worth 1. Use the following rules to determine the advice:
from string import capwords
deck_of_cards = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10}
hand = []
def verify_card(message):
while True:
card = input(message)
key = card.upper()
if key in deck_of_cards:
#print('That is a valid card.')
break
else:
print('this is not a valid card.')
continue
return key
print('Use one character or number to describe your card: ')
first_card = verify_card("What's your first card: ")
second_card = verify_card("What's your second card: ")
third_card = verify_card("What's your third card: ")
hand_value = []
if first_card in deck_of_cards:
hand_value.append(deck_of_cards[first_card])
if second_card in deck_of_cards:
hand_value.append(deck_of_cards[second_card])
if third_card in deck_of_cards:
hand_value.append(deck_of_cards[third_card])
# for card in deck_of_cards:
# hand_value.append(deck_of_cards[first_card])
# print(f'{deck_of_cards[first_card]}')
# card_value = ({deck_of_cards[first_card]})
# # card_value = int(card_value)
# hand.append(card_value)
# if second_card in deck_of_cards:
# print(f'{deck_of_cards[second_card]}')
# hand.append({deck_of_cards[second_card]})
# if third_card in deck_of_cards:
# print(f'{deck_of_cards[third_card]}')
# hand.append({deck_of_cards[third_card]})
total = sum(hand_value)
print(f'Total points in your had: {total}')
if total < 17:
print('You should hit.')
elif total >= 17 and total < 21:
print('You should stay')
elif total == 21:
print('Blackjack!')
elif total > 21:
print('You already busted.')
# total = sum(hand)
# print(total)
# • Less than 17, advise to "Hit"
# • Greater than or equal to 17, but less than 21, advise to "Stay"
# • Exactly 21, advise "Blackjack!"
# • Over 21, advise "Already Busted"
# Print out the current total point value and the advice. | true |
c9ecc1d15bc842832d7845476a70018f99b961f8 | sbtries/Class_Polar_Bear | /2 Python/demo/hello.py | 359 | 4.1875 | 4 | "Hello" # string
4 # int
2.5 # float
True # boolean / False
None # none
x = input("Enter a number: ")
try:
x = int(x)
except ValueError:
print("That was not a number...")
exit()
if x > 0:
print("This number is positive")
print("😎")
elif x == 0:
print('The number is 0')
else:
print("This number is negative") | true |
66c40980c69ca5004482cf638ff8c92172a15288 | Shingirai98/Digital-Factorial-Summer- | /factorial-digits.py | 1,128 | 4.125 | 4 | # -------------------------------------------------------
# | Name: Digital Factorial Sum |
# | @Author: Shingirai Denver Maburutse |
# | Date: 18/07/2021 |
# -----------------------------------------------------
import numpy as np
import sys
# allow for a high recursion limit
sys.setrecursionlimit(10**8)
# convert an array type to another type
def cast(arr, data_type):
return np.array(list(map(data_type, arr)))
# ->convert list to integers -> convert list to numpy array -> sum up the elements
def summing(arr):
return np.sum(np.array(cast(arr, int)))
# lambda function to find factorial by recursion
fact = (lambda num: 1 if num == 0 else num* fact(num-1)) # Assignment operator(=) was used because its a recursive function but it is stored as a pointer which is space efficient
def main():
# ->listify the factorial -> find the sum
try:
print(summing(list(str(fact(int(sys.argv[1])))))) # sys.argv[1] -> user input bash argument
except:
print("Please enter a positive real number")
if __name__ == '__main__':
main()
| true |
826c4375823225cd442946ed45c02ee9a87f0b9d | raadzi/comp110-21ss1-workspace | /projects/pj01/data_utils.py | 1,699 | 4.125 | 4 | """Data utility functions."""
__author__ = "730429363"
from csv import DictReader
def read_csv_rows(path: str) -> list[dict[str, str]]:
"""Read a CSV file and return a table that is a list of its rows (dicts)."""
file_handle = open(path, "r", encoding="utf8")
csv_reader = DictReader(file_handle)
table: list[dict[str, str]] = []
for row in csv_reader:
table.append(row)
file_handle.close()
return table
def column_values(table: list[dict[str, str]], column: str) -> list[str]:
"""Return a column's values."""
values: list[str] = []
for row in table:
values.append(row[column])
return values
def columnar(table: list[dict[str, str]]) -> dict[str, list[str]]:
"""Convert a table of rows to a table of columns."""
result: dict[str, list[str]] = {}
keys = table[0].keys()
for key in keys:
result[key] = column_values(table, key)
return result
def head(table: dict[str, list[str]], rows: int) -> dict[str, list[str]]:
"""Get the first n rows."""
result: dict[str, list[str]] = {}
for key in table:
result[key] = table[key][:rows]
return result
def select(table: dict[str, list[str]], cols: list[str]) -> dict[str, list[str]]:
"""Select only a subset of columns."""
result: dict[str, list[str]] = {}
for col_name in cols:
result[col_name] = table[col_name]
return result
def count(values: list[str]) -> dict[str, int]:
"""Counts the number of times a value is present."""
counts: dict[str, int] = {}
for value in values:
if value in counts:
counts[value] += 1
else:
counts[value] = 1
return counts | true |
94d312e5bde0f084dd1fb9351e04ef5c4d408542 | Zhaoyubao/Onsite-Python | /Python OOP/Bike.py | 807 | 4.1875 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayinfo(self):
print "Bike's Price:", self.price
print "Bike's Maximum Speed:", self.max_speed
if self.miles < 0:
self.miles = -self.miles
print "Bike's Total Miles: %d miles"%self.miles
def ride(self):
print "Riding..."
self.miles += 10
def reverse(self):
print "Reversing..."
self.miles -= 5
bike1 = Bike(200, "25mph")
bike2 = Bike(300, "30mph")
bike3 = Bike(400, "35mph")
for i in range(3):
bike1.ride()
bike3.reverse()
bike1.reverse()
for i in range(2):
bike2.ride()
bike2.reverse()
bike1.displayinfo()
bike2.displayinfo()
bike3.displayinfo()
| true |
cf8994a4a1f3d61dc896e27c4533d1c895f7a85c | MattPhillips1/comp1531-wk8 | /Rectangle.py | 1,354 | 4.1875 | 4 | from abc import abstractmethod, ABC
class Shape(ABC):
def __init__(self, color):
self._color = color
@abstractmethod
def area(self):
pass
@abstractmethod
def scale(self, ratio):
pass
class Rectangle(Shape):
def __init__(self, width, height, color):
Shape.__init__(self, color)
self._width = width
self._height = height
@property
def height(self):
return self._height
@height.setter
def height(self, height):
self._height = height
@property
def width(self):
return self._width
@width.setter
def width(self, width):
self._width = width
def area(self):
return self._height * self._width
def scale(self, ratio):
self._width *= ratio
self._height *= ratio
def __str__(self):
return ("I'm a Rectangle!")
class Circle(Shape):
def __init__(self, radius, color):
Shape.__init__(self, color)
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = radius
def area(self):
return 3.14 * self._radius * self._radius
def scale(self, ratio):
self._radius *= ratio
def __str__(self):
return ("I'm a Circle!")
| false |
bf50bc2d83fc835fe197b3b0a6031eb875a37970 | green-fox-academy/Simon--Kerub88 | /week-04/day-3/E_02_Sum.py | 696 | 4.21875 | 4 | # Create a sum method in your class which has a list of integers as parameter
# It should return the sum of the elements in the list
# Follow these steps:
# Add a new test case
# Instantiate your class
# create a list of integers
# use the assertEquals to test the result of the created sum method
# Run it
# Create different tests where you
# test your method with an empyt list
# with a list with one element in it
# with multiple elements in it
# with a null
# Run them
# Fix your code if needed
class NewClass:
list_of_integers = [3, 1, 6, 5, 9, 2]
def sum(self):
print(sum(self))
stuff = NewClass()
stuff = [3, 1, 6, 5, 9, 2]
stuff.sum()
| true |
162050d2f9723d5194ccbb8b654f100809ab0cc5 | green-fox-academy/Simon--Kerub88 | /week-02/day-5/Guess_my_number.py | 1,978 | 4.3125 | 4 | # Write a program where the program chooses a number between 1 and 100. The player is then asked to enter a guess. If the player guesses wrong, then the program gives feedback and ask to enter an other guess until the guess is correct.
#
# Make the range customizable (ask for it before starting the guessing).
# You can add lives. (optional)
# Example
#
# I've the number between 1-100. You have 5 lives.
#
# 20
# Too high. You have 4 lives left.
#
# 10
# Too low. You have 3 lives left.
#
# 15
# Congratulations. You won!
import random
print("\n"
"\n"
"\n"
"///////////////////////////////\n"
"\n"
"Guess My Number! 0.1beta_build\n"
"\n"
"///////////////////////////////\n"
"\n"
"\n"
"\n"
"Set the range of guess\n"
"Guess between: \n"
"(first number?)" )
range1 = int(input())
print("(second number?)")
range2 = int(input())
my_number = random.randrange(range1, range2)
# print(my_number)
print("I thought a number between", range1, "-", range2)
tries = 3
found = False
if found:
print("****************************\n"
"\n"
"YOU WON! That was the numbe I guessed\n"
"\n"
"****************************")
while (not found) and tries > 0:
print("You have " + str(tries) + " tries. What is your guess?\n")
guess = int(input())
if guess < my_number:
print("Not the number I guessed\n"
"Try a higher number!\n")
tries -= 1
elif guess > my_number:
print("Not the number I guessed\n"
"Try a lower number\n")
tries -= 1
else:
found = True
print("**************************************\n"
"\n"
"YOU WON! That was the number I guessed\n"
"\n"
"**************************************")
if tries <= 0:
print("****************************\n"
"\n"
"GAME OVER\n"
"\n"
"****************************\n"
"\n"
"My number was " + str(my_number) + "\n"
"\n")
| true |
53b5bd025757649396f7dce0f3321fa6bb8925c1 | green-fox-academy/Simon--Kerub88 | /week-02/day-2/E_11_seconds-in-a-day.py | 399 | 4.28125 | 4 | current_hours = 14;
current_minutes = 34;
current_seconds = 42;
# Write a program that prints the remaining seconds (as an integer) from a
# day if the current time is represented bt the variables
TotalDaySeconds = 60*60*24
print(TotalDaySeconds)
current_seconds = (14*60*60) + (34*60) + 42
print(current_seconds)
print("Remaining seconds from the Day: " + str(TotalDaySeconds - current_seconds))
| true |
b545f00ca11459c59fa36c7ffb5a947175d8471a | PengChen11/math-series | /math_series/series.py | 1,337 | 4.21875 | 4 | # function to calculate the nth fibonacci number. I hate using recursion for this task cause the big O is 2*n and when n goes above 30, it eats up all my computer's resources.
# The following solution's big O is only n-2. much faster.
# n starts with 0.
def fibonacci(n):
prev, nex = 0, 1
for i in range(n - 1):
prev, nex = nex, prev + nex
if n==0:
return prev
else:
return nex
# this is the calculation based on fibonacci's fomular.
# (1+5**0.5)/2 is called golden mean
# I don't know how python calculate floats, but these two method starts to give different value when n=72. feels like something wrong with acturacy for float calculation when it's really a big number.
# n starts with 0
def fibonacci_1(n):
return int((((1 + 5 ** 0.5) / 2)**n-(1-((1 + 5 ** 0.5) / 2))**n)/(5**0.5))
# function to calculate the nth lucas number.
# n starts with 0
def lucas(n):
prev, nex = 2, 1
for i in range(n - 1):
prev, nex = nex, prev + nex
if n==0:
return prev
else:
return nex
# function to calculate the nth number, based on 2 optional prams.
# if no optional prams input, then using fibonacci.
def sum_series(n,prev=0,nex=1):
for i in range(n - 1):
prev, nex = nex, prev + nex
if n==0:
return prev
else:
return nex
| true |
beba030545cf43bc8b8921a9f65796af35ebacd7 | mahmud-sajib/30-Days-of-Python | /L #23 - Class & Object.py | 1,997 | 4.65625 | 5 | ## Day 23: Class & Object
## Concept: Creating a Class - To define a class, use the class keyword, and define the data points inside.
# Simple class with a property
class Person:
name = "John Wick"
## Concept: Creating an Object - o create a new object, simply reference the class you want to build the object out of
# Simple class with a property & an object instance
class Person:
name = "John Wick"
# creating an object instance
person = Person()
# accessing the class property
print(person.name) #output: John Wick
## Concept: Class Constructor - __init__() method. When we create a class without a constructor, Python automatically creates a default constructor for us that doesn’t do anything. Every class must have a constructor, even if it simply relies on the default constructor
"""
The __init__() function syntax is:
def __init__(self, [arguments])
1. The 'self' argument refers to the current object. It binds the instance to the init() method. It’s usually named “self” to follow the naming convention.
2. The init() method [arguments] are optional. We can define a constructor with any number of arguments.
"""
# Simple class constructor
class Person:
def __init__(self, person_name):
self.name = person_name
person1 = Person("Johnny Depp")
print(person1.name) # Johnny Depp
person2 = Person("Lora Akintson")
print(person2.name) # Lora Akintson
## Concept: Object Methods
# Simple class with custom method. 'self' is a must use argument in any method inside class.
class Person:
# class attribute
country = "England"
# instance attribute
def __init__(self, person_name, person_job):
self.name = person_name
self.job = person_job
# instance method
def intro(self):
print(f"{self.name} is a {self.job} from {self.country}")
person1 = Person("Johnny Depp", "Actor")
person1.intro() # Johnny Depp is a Actor from England
person2 = Person("Lora Akintson", "Doctor")
person2.intro() # Lora Akintson is a Doctor from England
| true |
f4aa81270ce4056c79fa5e5f165844b6984f4efe | mahmud-sajib/30-Days-of-Python | /L #20 - Generators.py | 934 | 4.46875 | 4 | ## Day 20: Python Generators
## What are generators in Python?
"""
Python generators are a simple way of creating iterators.
A generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
"""
## How to create a generator in Python?
"""
It is the same as defining a normal function, but with a 'yield' statement instead of a 'return' statement.
The difference is that while a return statement terminates a function entirely,
yield statement pauses the function saving all its states and later continues from there on successive calls.
"""
# Example of a generator
def my_iterable():
i = 5
while i > 0:
yield i
i -= 1
num = my_iterable()
# we can use next() to access values from generators
print(next(num)) # 5
print(next(num)) # 4
# alternatively we can use loop to access all the values at a time.
for i in my_iterable():
print(i)
# output: 5 4 3 2 1 | true |
0b94b60f57bc7df66c46ab53e8876cc79c41f505 | mahmud-sajib/30-Days-of-Python | /L #14 - First Class Functions.py | 2,892 | 4.125 | 4 | ## Day 14: First Class Functions
## Concept: What are first class functions?
""" In Python, functions are first class object (first class citizen too!). Programming language theorists defined some criteria for first class object of a programming language. A “first class object” is a program entity which can be :
1. created at run time
2. can be assigned to a variable
3. can be passed as function argument
4. can be returned from a function
"""
## Concept: Function Creation in run time
# runtime function calling (recursively)
def print_inversely(n):
print(n, end=" ")
if n > 0:
print_inversely(n - 1)
print_inversely(10)
# output: 10 9 8 7 6 5 4 3 2 1 0
"""
Here, we have a recursive function named print_inversely which will print n down to 0.
Number of calls of print_inversely function depends on value of n.
Depending on value of n it calls itself.
Before running the program it cannot decide about its behavior, number of calls etc.
At the run time it calls itself recursively depending on the value of n.
In other word, “here we are creating and calling the function at run time.
"""
# In Python, functions are object too. Here 'print_inversely' function is an instance of function class
def print_inversely(n):
print(n, end=" ")
if n > 0:
print_inversely(n - 1)
print(type(print_inversely))
# output: <class 'function'>
## Concept: Assigning function to a variable
def print_inversely(n):
print(n, end=", ")
if n > 0:
print_inversely(n - 1)
# assigning to a variable
our_first_class_function = print_inversely
# call function through variable
our_first_class_function(15)
# output: call function through variable
## Concept: Passing functions as argument
def print_inversely(n):
print(n, end=" ")
if n > 0:
print_inversely(n - 1)
def print_inversely_by_user_input(func):
n = int(input("\n Please input a number to start: "))
# call the print_inversely' function
func(n)
# takes 'print_inversely' function as an argument
print_inversely_by_user_input(print_inversely)
"""
Here 'print_inversely_by_user_input' function takes 'print_inversely' function as argument.
the new print_inversely_by_user_input' function takes an integer user input and call the print_inversely' function.
"""
## Concept: Returning function from function
def ever_or_odd(n):
def even():
print(f"{n} is even")
def odd():
print(f"{n} is odd")
if n % 2 == 0:
return even()
else:
return odd()
n = int(input("Write a integer to check: "))
ever_or_odd(n)
"""
ever_or_odd function returns a function depending of value of n.
If we pass an even number to n, then it will return reference of even() function otherwise it will return reference of odd() function.
Hence, a function is returning another function!
"""
| true |
c65dd1db722d58105d44319f10926aca267ff5b9 | srmchem/python-samples | /Python-code-snippets-101-200/149-Convert KMH to MPH.py | 298 | 4.21875 | 4 | '''
Python Code Snippets - stevepython.wordpress.com
149-Convert KMH to MPH
Source:
https://www.pythonforbeginners.com/code-snippets-source-code/
python-code-convert-kmh-to-mph/
'''
kmh = int(input("Enter km/h: "))
mph = 0.6214 * kmh
print ("Speed:", kmh, "KM/H = ", mph, "MPH")
| false |
d75a3e2695842452e0b9e7b79b45603d17c438ac | srmchem/python-samples | /Python-code-snippets-201-300/294-All permutations of a string.py | 615 | 4.3125 | 4 | """Code snippets vol-59
294-Print permutations of a given string
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Blog: stevepython.wordpress.com
Requirements:
None
origin:
https://gist.github.com/accakks/fbf2383ce782bbf089c68a807695b3e1
"""
from itertools import permutations
def print_permutations(s):
"""Prints permutations of a given string"""
ans = list(permutations(s))
cnt = 1
for permutation in ans:
print(str().join(permutation) + "\n" + str(cnt), end=" ")
cnt += 1
s = input('Enter input string\n')
print_permutations(s)
| true |
1f503566bf6c2b75cec56f463c8d255737b75f84 | srmchem/python-samples | /Python-code-snippets-201-300/284-Check string for pangram.py | 860 | 4.15625 | 4 | """Code snippets vol-57
284-Check string for a pangram
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Blog: stevepython.wordpress.com
Requirements:
None
original code here:
https://gist.github.com/Allwin12/4f8d9d8066adc838558a22949ba400c0
"""
import string
alphabets = string.ascii_lowercase
def test_pangram(sentence, alphabets):
for char in alphabets:
if char not in sentence.lower():
return False
return True
text_string = 'the quick brown fox jumps over a lazy dog'
print()
if test_pangram(text_string, alphabets):
print(text_string, '\nis a pangram because it contains every letter of '
'the alphabet exactly once.')
else:
print(text_string, '\nis not a pangram. A pangram has to contain every '
'letter of the alphabet exactly once.')
| true |
9e75fdf33b319779671252f257d4f6c018c6ea4c | KarlosTan/python-bootcamp | /session1/conditions/speed_func.py | 1,710 | 4.25 | 4 |
def speed_function_simple(speed): # example of function with no return value
if speed < 80:
print(" speed is ok")
else:
print(" you. have to pay a fine")
def speed_function_advanced(speed, provisonal): # example of function with return value
total_fine = 0
print(provisonal, ' is provisional')
if (speed < 80) :
print(" speed is ok.")
elif ((speed >= 80) and (speed < 100)) and (provisonal==True):
base_fine = 500
speed_diff = speed - 80
extra_fine = speed_diff * 10
total_fine = extra_fine + base_fine
print(" fine of (Pro is True) ", total_fine)
elif ((speed >= 80) and (speed < 100)) and (provisonal==False):
base_fine = 200
speed_diff = speed - 80
extra_fine = speed_diff * 10
total_fine = extra_fine + base_fine
print(" fine of ", total_fine)
elif (speed >= 100) and (speed < 140):
print(" fine of 600 AUD")
else:
print(" time to go to prison. ")
return total_fine
# adap it for fine system in your country of residence
def main():
print("Check speed of a vehicle and give fine!")
#speed = int(input("Enter speed in km/hr for simple function: "))
#speed_function_simple(speed)
speed_adv = int(input("Enter speed in km/hr for advanced function: "))
licence = input("Are you having a provisional licence? ")
if licence == 'yes' or licence == 'Yes':
provisional = True
else:
provisional = False
fine = speed_function_advanced(speed_adv, provisional)
print('the fine returned to main is: ', fine, ' dollars')
if __name__ == '__main__':
main()
| true |
40204f14232ce556f2a3b2221d24e4fe4737186e | KarlosTan/python-bootcamp | /session1/loops/nested_loops.py | 1,685 | 4.21875 | 4 |
import numpy as np
import random
import sys # for end or endline in nested food loops, python 3
def nested_loops():
print(' nested loops function')
#https://www.ict.social/python/basics/multidimensional-lists-in-python
length = 3
width = 4
height = 5
two_dimen = np.random.rand(length, width)
print(two_dimen)
first_row = two_dimen[0,:]
second_col = two_dimen[:,1]
print(first_row, ' first_row')
print(second_col, ' second_col')
three_dimen = np.zeros((length, width, height))
print(three_dimen)
for i in range(length): #0
for j in range(width): #0 1 2 3
two_dimen[i,j] = i*j #1
#0 1 2 3
print (two_dimen)
#print (k, end =' ') # end refers new line
print (' 3 nested ')
for i in range(1,3):
for j in range(1,3):
for k in range(1,3):
z = i*j * k
print (z) # end refers new line
print (' 3 nested save to np array ')
for i in range(length):
for j in range(width):
for k in range(height):
three_dimen[i,j,k] = i*j * k
print(three_dimen, ' ** ')
last_two_rows = three_dimen[2,2:4,3:5]
print(last_two_rows, ' **** ')
#operations to select parts of 2d array
# i is your mat
# j is your row
# k is your col
# 0 is mat
# 0 is row
# 0 1 2 3 is col
# 0 is mat
# 1 is row
# 0 1 2 3 is col
# 0 is mat
# 2 is row
# 0 1 2 3 is col
# 0 is mat
# 3 is row
# 0 1 2 3 is col
# 1 is mat
# 0 is row
# 0 1 2 3 is col
# 1 is mat
# 1 is row
# 0 1 2 3 is col
def main():
print('running: nested_loops()')
nested_loops()
if __name__ == '__main__':
main()
| false |
dbe62c68d5e967190b9c9b81b3bd8d52b33479b8 | KarlosTan/python-bootcamp | /session4/simple_programs/palindromine_others.py | 1,460 | 4.34375 | 4 |
#Source: https://www.geeksforgeeks.org/python-program-check-string-palindrome-not/
# Python program to check
# if a string is palindrome
# or not
x = "malayalam movies"
w = ""
for i in x:
w = i + w
print(w, ' *')
if (x == w):
print("Yes")
else:
print("No")
# Python program to check
# if a string is palindrome
# or not
st = 'tennnxnnet'
j = -1
flag = 0
for i in st:
print(i, st[j], ' *** ')
if i != st[j]:
j = j - 1
flag = 1
break
j = j - 1
if flag == 1:
print("NO")
else:
print("Yes")
# Recursive function to check if a
# string is palindrome
def isPalindrome(s):
#to change it the string is similar case
s = s.lower()
# length of s
l = len(s)
# if length is less than 2
if l < 2:
return True
# If s[0] and s[l-1] are equal
elif s[0] == s[l - 1]:
# Call is pallindrome form substring(1,l-1)
return isPalindrome(s[1: l - 1])
else:
return False
# Driver Code
s = "MalaYaLam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
# function to check string is
# palindrome or not
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "foolish"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
| false |
944099badbe822e8bddeec61d337320be7ec6c40 | BeefCakes/CS112-Spring2012 | /day4-2.py | 328 | 4.15625 | 4 | #!/usr/bin/env python
TAs = ["Alec","Jack","Jonah"] #added later, a list
name_in=raw_input("enter a name: ")
if name_in == "Paul":
print "you are cool"
elif name_in in TAs: #originally: elif name_in == "Alec" or name_in == "Jonah" or name_in == "Jack":
print "you smell bad"
else:
print "you need some learning"
| false |
8eaeaa038a8a7fe4cb91b24eb0d881645fccfd53 | BeefCakes/CS112-Spring2012 | /hw10/multidim.py | 2,653 | 4.3125 | 4 | #!/usr/bin/env python
"""
multidim.py
Multidimensional Arrays
=========================================================
This section checks to make sure you can create, use,
search, and manipulate a multidimensional array.
"""
# 1. find_coins
# find every coin (the number 1) in a givven room
# room: a NxN grid which contains coins
# returns: a list of the location of coind
#
# Example:
# 0 0 0 1 0 0
# 0 0 1 0 0 0
# 0 0 0 0 1 0
# 0 0 0 0 0 0
#
# >>> find_coins(room)
# [ [3, 0], [2, 1], [4, 2] ]
#
import random
def find_coins(room):
# rows, cols = room
n = room
# n = list(n)
rows = n[0]
# rows = int(rows)
cols = n[1]
# cols = int(cols)
print rows, cols
print n
grid = []
coins = []
print type(rows)
for i in range(rows): #number of rows
row = []
for j in range(cols): #number of columns
row.append(0)
grid.append(row)
print grid
while len(coins) < 3: #once there are 3 coins, stop creating random x and y
c_row = random.randint(1,rows) - 1
c_col = random.randint(1,cols) - 1
coins.insert(0,[c_row, c_col])
grid[(coins[0][0])][(coins[0][1])] = 1
##print rows
for i,row in enumerate(grid):
for j, val in enumerate(row):
print val,
print ""
print coins
return coins
find_coins((6,7))
"returns a list of every coin in the room"
# 2. distance_from_player
# calculate the distance from the player for each
# square in a room. Returns a new grid of given
# width and height where each square is the distance
# from the player
import math
def distance_from_player(player_x, player_y, width, height):
"calculates the distance of each square from the player"
grid = []
for i in range(width):
row = []
for j in range(height):
row.append(0)
grid.append(row)
print grid
grid[player_x][player_y] = "P"
distances = []
for i,row in enumerate(grid):
a = i - player_x
for j, val in enumerate(row):
b = j - player_y
if val == "P":
distance = 0.0
print val,
distances.append(distance)
else:
# distance = int(math.sqrt(a**2 + b**2))
distance = math.sqrt(a**2 + b**2)
print distance,
distances.append(distance)
#how do I get the rows as their own list elements?
print ""
print distances
return distances
distance_from_player(0, 0, 6, 6)
| true |
4be6912a06cdeb6e179e8168208d4869c8fab455 | ruchika0201/Basic-Data-Stuctures | /strings/Python/camel.py | 962 | 4.1875 | 4 | #Alice wrote a sequence of words in CamelCase as a string of letters, , having the following properties:
#It is a concatenation of one or more words consisting of English letters.
#All letters in the first word are lowercase.
#For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase.
#Given , print the number of words in on a new line.
#For example, . There are words in the string.
def camelcase(s):
i = 0
#length = len(s)
l = list(s)
count = 0
flag = 0
while i<len(l):
#print(i)
if l[0].islower() and flag==0:
count+=1
i+=1
flag=1
continue
if l[i].islower() and flag!=0:
i+=1
continue
if l[i].isupper():
count+=1
i+=1
return count
if __name__ == '__main__':
s = input("Enter string::")
result = camelcase(s)
print(result) | true |
d4bc2da87af4976f6a1e39162acfd8faea3504c5 | gugun/pythoncourse-coder-dojo | /day02/module_package/main.py | 374 | 4.3125 | 4 | """
This program will calculate triangle area using the formula
area = height * bottom /2
"""
import geometry.triangle as triangle
import geometry.square as square
import geometry.circle as circle
print 'Main Program'
print 'Triangle area', triangle.calc_triangle_area(10, 5)
print 'Square area', square.calc_square_area(3)
print 'Circle area', circle.calc_circle_area(5)
| true |
c04ee354b90c1f259d29db36178d280d2c81db09 | longlee218/Python-Algorithm | /020_week5/020_rectangles.py | 663 | 4.21875 | 4 | """
A rectangle is represented as a list [x1, y1, x2, y2] where (x1, y1) are the coordinates of its bottom-left
corner, and (x2, y2) are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only
touch at the corner or edges do not overlap.
"""
def solution(rec1, rec2):
if rec1[2] <= rec2[0] or rec2[2] <= rec1[0]:
return False
elif rec1[3] <= rec2[1] or rec2[3] <= rec1[0]:
return False
return True
if __name__ == '__main__':
print(solution(rec1=[1, 1, 3, 3], rec2=[1, 1, 2, 2]))
"""
+) Time complexity: O(1)
""" | true |
e4a6e5850fd8df693131d90db42251b15a8e5972 | longlee218/Python-Algorithm | /017_week2/17+4_dubstep.py | 1,384 | 4.25 | 4 | """
Let's assume that a song consists of some number of words. To make the dubstep remix of this song
,Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero)
,after the last word (the number may be zero), and between words (at least one between any pair of neighbouring
words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club
For example, a song with words "I AM X" can transform into dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot
transform into "WUBWUBIAMXWUB"
INPUT:
The input consists of a single non-empty string, consisting only of uppercase English letter, the string's
length doesn't exceed 200 characters. It is guaranteed that before Vasya remix the song, no word contained
substring "WUB" in it; Vasya didn't change the word order. It is also guaranteed that initially the song had at
least one word.
OUTPUT:
Print the word of the initial song that Vasya used to make a dubstep remix. Separate the words with a space.
"""
def decode():
strings = ""
while len(strings) > 200 or len(strings) == 0 or "WUB" not in strings:
strings = str(input("Enter: ").upper())
return " ".join(strings.replace('WUB', ' ').split())
if __name__ == '__main__':
print(decode())
| true |
9165aca764ec0baab0df685e9148912420b82e20 | longlee218/Python-Algorithm | /014_largest_mul.py | 2,715 | 4.15625 | 4 | """
Hi, here's your prblem today. This problem was recently ask by Microsoft
You are given an array of integers. Return the largest product that can be made by
multiplying any 3 integers in the array
Example
[-4, -4, 2, 8] should return 128 as the largest product can made by multiplying
-4 * -4 * 8 =128
Here's a staring point:
def maximum_product_of_three(lst):
# Fill this in.
print(maximum_product_of_three([-4, -4, 2, 8])
# 128
"""
# Solution1
def maximum_product_of_three1(lst):
max_number = max(lst)
for i in range(0, len(lst)-2):
for j in range(i+1, len(lst)-1):
for k in range(j+1, len(lst)):
if max_number < lst[i]*lst[j]*lst[k]:
max_number = lst[i]*lst[j]*lst[k]
return max_number
# Solution2
def max_one(a, b):
if a >= b:
return a
return b
def maximum_product_of_three3(lst):
if len(lst) < 3:
return -1
else:
min_value1 = 999999999999999
min_value2 = min_value1 # [ min_value1, min_value2, ....,max_value3, max_value2, max_value1 ]
max_value1 = -min_value1
max_value2 = max_value1
max_value3 = max_value1
for i in lst:
if i > max_value1:
max_value3 = max_value2
max_value2 = max_value1
max_value1 = i
elif i > max_value2:
max_value3 = max_value2
max_value2 = i
elif i > max_value3:
max_value3 = i
if i < min_value1:
min_value2 = min_value1
min_value1 = i
elif i < min_value2:
min_value2 = i
return max_one(min_value1*min_value2*max_value1, max_value1*max_value2*max_value3)
if __name__ == '__main__':
array = [-4, -20, 5, -2, -4, 6]
print(maximum_product_of_three1(array))
print(maximum_product_of_three3(array))
"""
Solution1:
+)Time complexity: O(n^3) <n là len của lst>
+)Space memory: O(1)
+)Phân tích: nhân 3 số với nhau rồi làm như tìm max bthg
Solution2:
+)Time complexity: O(n) <n là len của lst>
+)Space memory: O(1)
+)Phân tích: nhận thấy nếu tích 3 số để max có 2 trường hợp: 3 số dương và 2 sô âm 1 số dương
Tiến hành tìm 2 số âm nhỏ nhất của chuỗi và 3 số dương lớn nhất
[min1, min2,......... max3, max2, max1 ]
So sánh tích của 2 trường hợp này --> min1*min2*max1 với max3*max2*max1
""" | true |
74a4103afa9e439d53d2a2fe2f4d74a8d78ad209 | mariuszbrozda/python_rps_game | /rps.py | 2,072 | 4.375 | 4 |
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
print('\nWelcome in ROCK, PAPER, SCISSORS game !')
print('\n RULES OF THE GAME: \n Rock wins against scissors. \n Scissors win against paper. \n Paper wins against rock.\n')
player_name = input('Please type your name ')
print(f'{player_name}, to play the game simply type \n 0 for "ROCK" \n 1 for "SCISSORS"\n 2 for "PAPER"')
player_points = 0
computer_points = 0
player_choice = int(input('My choice: '))
computer_choice = random.randint(0, 2)
if player_choice >= 3 or player_choice < 0:
print('You typed invalid number - You lose! ')
else:
game = [rock, paper, scissors]
player_selection = game[player_choice]
computer_selection = game[computer_choice]
print(f'{player_name}: {player_choice} {player_selection} ')
print(f'Computer: {computer_choice} {computer_selection} ')
if player_selection == rock and computer_selection == scissors:
player_points += 1
print(f'RESULTS: {player_name} WINS')
elif computer_selection == rock and player_selection == scissors:
computer_points += 1
print('RESULTS: Computer WINS')
elif player_selection == scissors and computer_selection == paper:
player_points += 1
print(f'RESULTS: {player_name} WINS')
elif computer_selection == scissors and player_selection == paper:
computer_points += 1
print('RESULTS: Computer WINS')
elif player_selection == paper and computer_selection == rock:
player_points += 1
print(f'RESULTS: {player_name} WINS')
elif computer_selection == paper and player_selection == rock:
computer_points += 1
print('RESULTS: Computer WINS')
elif computer_selection == player_selection:
print('RESULT: DRWAW')
print(f'POINTS: {player_name}: {player_points} - Computer: {computer_points}')
| false |
b16767793fdab1333e0ae15b6a6f11ddb2d70012 | PatrickArthur/FunWithPython | /demo.py | 385 | 4.1875 | 4 | name = raw_input("What is your name? ")
while name != "Patrick":
print("{} Nice to meet you, how do you like python".format(name, name))
print "Your name length: {0}".format(len(name))
raw_input("Press <ENTER> to exit\n")
name = raw_input("What is your name? ")
else:
print("{} Is my name, and I like python".format(name))
print "Your name length: {0}".format(len(name))
| true |
118286ce5dc33d660367b05f66c5bcd9c336b371 | crystal1509/Day-5 | /facrecursion.py | 315 | 4.21875 | 4 | #Python Program to Find Factorial of Number Using Recursion
def fac_recursion(n):
if n==1:
return n
else:
return n*fac_recursion(n-1)
num=int(input("enter a number:"))
if num<0:
print("negative number!!! enter again")
else:
print("factorial is:",fac_recursion(num))
| false |
d530661de1b951cd8660beebd5e82f8343a87d4e | kamranajabbar/python3_practice | /10-classes.py | 1,458 | 4.46875 | 4 | #Chapter # 53-61 Classes
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.battery = "200 AMP" #Default attribute
def descriptionCar(self):
print(f"The make of car is {self.make}")
print(f"The model of car is {self.model}")
print(f"The year of car is {self.year}")
def move(self):
print(f"The {self.make} can move with speed")
def applyBreak(self):
print(f"The {self.model} has applied the break")
def setBatterySize(self, newSize):
self.battery = newSize
def getBatterySize(self):
print(f"The size of your car's battery is {self.battery} ")
#Create Object For Car Class
car1 = Car("Honda", "Civic", 2020)
car2 = Car("BMW", "Hi2020", 2021)
#Access attributes with objects
print(car1.make)
print(car2.make)
#Access method with objects
print(car1.move())
print(car2.descriptionCar())
#Changing an attributes value (Direct hit attributes value)
car1.make = "Ford"
print("New car make is:", car1.make)
#Get default attributes
print("Default attributes value =",car1.battery)
#Update/Change default attributes value directly
car1.battery = "300 AMP"
print("After Changed 'battery' value by attribute =",car1.battery)
#Update/Change default attributes value by method
car1.setBatterySize("400 AMP")
#Get default attributes value by method
print(car1.getBatterySize()) | true |
10335d9043dd5add872d6dc67802c171959cfbb0 | kamranajabbar/python3_practice | /13-csv.py | 930 | 4.375 | 4 | #Chapter # 67-73 CSV files
#67: CSV files
#68: CSV files: Reading them
#69: CSV files: Picking information out of them
#70: CSV files: Loading information into them. Part 1
#71: CSV files: Loading information into them. Part 2
#72: CSV files: Loading information into them. Part 3
#73: CSV files: Appending rows to them.
import csv
#Read CSv File
with open("mycsvfile.csv") as csvfile:
contents = csv.reader(csvfile)
for content in contents:
print(content)
#Write or Overwrite CSV File
with open("mycsvfile2.csv", "w", newline="") as csvfile:
fileWriter = csv.writer(csvfile)
fileWriter.writerow(["2021","ICC T20", "England"])
fileWriter.writerow(["2022","ICC T20", "China"])
#Append CSV File
with open("mycsvfile.csv", "a", newline="") as csvfile:
fileWriter = csv.writer(csvfile)
fileWriter.writerow(["2023","ICC T20", "Pakistan"])
fileWriter.writerow(["2024","ICC T20", "Pakistan"]) | true |
b54dfc1418d04d43179927efe953fcabcd067706 | khanhbao128/HB-Code-Challenge-Problems | /Whiteboarding problems/Easier/remove_duplicates.py | 818 | 4.21875 | 4 |
# given a list of items, return the new list of items in the same order but with all duplicates removed
# Q: what does an empty list return? empty list
def deduped(items):
"""Remove all duplicates in a list and return the new list of items in the same order"""
# new_list = []
# for item in items:
# if item not in new_list:
# new_list.append(item)
# return new_list
# Runtime: O(n*2) >> bc have to look at each item in new_list to make sure item not in new_list
# >> to improve runtime, create a set called seen and check item against the set
# better solution
seen = set()
new_list = []
for item in items:
if item not in seen:
new_list.append(item)
seen.add(item)
return new_list
print(deduped([1, 2, 1, 1, 3]))
| true |
080d4f2b339e75cb49611cd1920733dd26dece94 | tamatamsaigopi/python | /rotatearray.py | 829 | 4.6875 | 5 | # Python program to left rotate array
# Function to rotate arrays in Python
def rotateArrayLeft(arr, R, n):
for i in range(R):
firstVal = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = firstVal
# Taking array input from user
arr = [1, 2, 3, 4, 5, 6, 7]
n = int(input("Enter number of elements of the array: "))
arr = []
print("Enter elements of the array :")
for i in range(n):
numbers = int(input())
arr.append(numbers)
R = int(input("Enter rotation count: "))
# Printing array
print("Initial Array :", end = " ")
for i in range(n):
print ("%d"% arr[i],end=" ")
# Calling function for left Rotating array
rotateArrayLeft(arr, R, n)
# Printing new array
print("\nArray after rotation: ", end = " ")
for i in range(n):
print ("%d"% arr[i],end=" ")
| true |
117166ff8c5d0a3b4f2f08159c4056e071554d34 | xanderquigley/a1_prog1700 | /hipster_local_records.py | 1,751 | 4.34375 | 4 | """
Student Name: Alex Quigley - W0458866
Program Title: IT Data Analytics
Description: Assignment 1 - Problem 1 - Hipster's Local Vinyl Records
This program will take in customer information and calculate the total for the customer to pay for the records
purchased along with the price of delivery.
"""
def main():
# Print output message to start the program
print("Hipster's Local Vinyl Records - Customer Order Details")
# INPUT
# Create variables to store needed information
delivery_rate = 15 # $15/km
tax = 0.14
cust_name = input("Enter the customer's name: ")
distance_km = float(input("Enter the distance in kilometers for delivery: "))
records_cost = float(input("Enter the cost of records purchased: "))
# PROCESSING
delivery_cost = float(delivery_rate * distance_km) # delivery cost is a product of distance and delivery rate
purchase_cost = float(records_cost * (1 + tax)) # purchase cost is a product of the tax rate and records cost
total_cost = float(purchase_cost + delivery_cost) # total cost is the sum of purchase cost and delivery cost
# Format the variables into a two decimal format to be used later
formatted_delivery = "{:.2f}".format(delivery_cost)
formatted_purchase = "{:.2f}".format(purchase_cost)
formatted_total = "{:.2f}".format(total_cost)
# OUTPUT
# We need to print the totals for the user using concatenation of the formatted variables.
# Make sure to cast as string when printing.
print("Summary for " + cust_name)
print("Delivery Cost: $" + str(formatted_delivery))
print("Purchase Cost: $" + str(formatted_purchase))
print("Total Cost : $" + str(formatted_total))
if __name__ == "__main__":
main() | true |
556ce7be3a1a5d91f7138537ac575e94a72ff7b2 | alexpickering/Python | /printWithoutVowels.py | 600 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: taka0
"""
def print_without_vowels(s):
'''
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
'''
vowels = 'aeiou'
if s != None:
sCopy = s[:]
if any(vowels.find(letter.lower()) != -1 for letter in sCopy):
for letter in sCopy:
if vowels.find(letter.lower()) != -1:
sCopy = sCopy.replace(letter,"")
print(sCopy) | true |
56977469a39132bf485b07cc6401d77c9a169f8b | nekocheik/python__back | /exercises /sort_array_by_element_frequency.py | 1,282 | 4.25 | 4 | """Sort the given iterable so that its elements end up in the decreasing frequency order,
that is, the number of times they appear in elements. If two elements have the same frequency,
they should end up in the same order as the first appearance in the iterable."""
from collections import Counter
def frequency_sort(items):
# your code here
c = sorted(items)
counter = Counter(items).most_common(3);
items = []
for count in counter:
for i in range(0,count[1]):
items.append(count[0])
print(items)
return items
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']
assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]
assert list(frequency_sort([])) == []
assert list(frequency_sort([1])) == [1]
print("Coding complete? Click 'Check' to earn cool rewards!")
#BEST SOLUTIONS
def frequency_sort(items):
return sorted(items, key = lambda x: (-items.count(x), items.index(x))) | true |
0f0a720060fe01d52d250c29f505dc3d9010a27a | agastyajain/Number-Guessing-Game | /NumberGuessingGame.py | 594 | 4.21875 | 4 | import random
print('Welcome To The Number Guessing Game !!!')
number = random.randint(1,9)
chances = 0
print('Guess a number between 1 and 9 ...')
while chances < 5:
guess = int(input('Enter your guess: '))
if guess == number:
print('Congrats! You Won')
break
elif guess < number:
print('Your guess is too low. Guess a number higher than ', guess)
else:
print('Your guess was too high. Guess a number lower than ', guess)
chances = chances + 1
if not chances < 5:
print('YOU LOSE !!! And the number was ', number)
| true |
4848076f5d159bdd1ed89bc0632de8b5e4bb3b91 | wherculano/Curso-em-Video-Python | /Desafio103.py | 899 | 4.3125 | 4 | #Desafio103.py
'''
Faça um programa que tenha uma função chamada ficha(), que receba dois parametros
opcionais: o nome de um jogador e quantos gols ele marcou.
O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado
não tenha sido informado corretamente.
Nome do Jogador: Romario
Numero de Gols: 33
O jogador ROmario fez 33 gol(s) no campeonato
Nome do Jogador:
Numero de Gols: 10
O jogador <desconhecido> fez 10 gol(s) no campeonato
Nome do Jogador:
Numero de Gols:
O jogador <desconhecido> fez 0 gol(s) no campeonato
'''
def ficha(nome=None, gols = None):
if gols.isnumeric():
gols = int(gols)
else:
gols = 0
if nome.strip() == '':
nome = '<desconhecido>'
return f'O jogador {nome} marcou {gols} gols.'
n = input('Nome do jogador: ')
g = input('Gols marcados: ')
print(ficha(n, g))
| false |
72208fd934ad705cdc8a81773b01f37994349c65 | wherculano/Curso-em-Video-Python | /Desafio037.py | 649 | 4.125 | 4 | #Desafio037 - Binario, Octal e Hexadecimal
sair = 's'
while sair == 's':
n = int(input('\nDigite um número inteiro: '))
op = int(input('\nAgora escolha para qual base deseja converte-lo:\
\n1- Binário\n2- Octal\n3- Hexadecimal\n'))
if op == 1:
print('{} em Binário = {}\n'.format(n, str(bin(n)).replace('0b','')))
elif op == 2:
print('{} em Octal = {}\n'.format(n,str(oct(n)).replace('0o','')))
elif op == 3:
print('{} em Hexadecimal = {}\n'.format(n,str(hex(n)).replace('0x','')))
else:
print('Opção inválida!\n')
sair = input('Deseja continuar?\n(S/N): ').lower()
| false |
ed4c96100cc1fb4c6316a8f457884567d3875d4b | wherculano/Curso-em-Video-Python | /Desafio102.py | 859 | 4.4375 | 4 | #Desafio102.py
'''
Crie um programa que tenha uma função fatorial() que recebe dois parametros:
o primeiro que indique o numero a calcular e o outro chamado show,
que será um valor lógico (opcional) indicando se será mostrado ou não na
tela o processo de calculo do fatorial
print(fatorial(5))
>>> 120
print(fatorial(5, True))
>>> 5 x 4 x 3 x 2 x 1 = 120
'''
def fatorial(n, show=False):
'''
Calcula o Fatorial de um numero
:param n: o numero a ser calculado
:param show: (opcional) Mostrar ou nao a conta
'''
f = 1
for c in range(n,0,-1):
if show:
print(c, end='')
if c > 1:
print(' x ',end='')
else:
print(' = ',end='')
f *= c
return f
help(fatorial)
print(fatorial(5))
print(fatorial(5, True))
| false |
c7b0cb79a06393adb912e0b4ac6fdd38a002f2af | sofiakn/pycoding | /ch03-repetitions/01-while.py | 343 | 4.125 | 4 | number = int( input("Enter a number for times table (0 to stop): "))
while number != 0 :
print(f"{number} x 1 = {number*1}")
print(f"{number} x 2 = {number*2}")
print(f"{number} x 3 = {number*3}")
print()
number = int( input("Enter a number for times table (0 to stop): "))
print("Thank you for using this program.") | true |
595207952cdedd6cb8f38c34800546c70a2b244d | sofiakn/pycoding | /ch02-conditions/02tax.py | 261 | 4.1875 | 4 | # Ask for the price and if price is dollar or more, there will be tax otherwise no tax is charged
price = float(input("What is the \"price\"? "))
if price >= 1.0 :
print("You will be charged tax")
else :
print("You will not be charged tax")
| true |
0a72559c8782ecbf0fa9598ce478a8eb007c9116 | c4collins/Euler-Project | /euler25.py | 261 | 4.125 | 4 | def fibonacci(length):
# initialize variables
num1 = 1
num2 = 1
even_total = 0
term = 2
while len(str(num1)) < length:
# generate fibonacci series
num_total = num1 + num2
num2 = num1
num1 = num_total
term += 1
return term
print fibonacci(1000) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.