blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
ba6de8d63f90c93405f2d699c674dfc6faca22c4
|
DinakarBijili/Python-Preparation
|
/Problem Solving/HARDER_LEVEL/Simple_calculator.py
| 769
| 4.25
| 4
|
""" Simple Calculator """
def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mul(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def mod(num1,num2):
return num1 % num2
#Taking input from the User
num1 = int(input("Enter 1st Number : "))
operation = input("What you want to do (+,-.*,/,%) : ")
num2 = int(input("Enter 2nd Number : "))
result = 0
if operation == "+":
result = add(num1,num2)
elif operation == "-":
result = sub(num1,num2)
elif operation == "*":
result = mul(num1,num2)
elif operation == "/":
result = div(num1,num2)
elif operation == "%":
result = mod(num1,num2)
else:
print("Please enter: +, -, *, / or %")
print(num1, operation, num2, '=', result)
| false
|
224fc51576ce0320b8b78210fde376cf4aba4b37
|
S411m4/very_simple_python_database
|
/very_simple_python_database.py
| 1,386
| 4.21875
| 4
|
class School:
def __init__(self, firstName, lastName, email, money, job):
self.firstName = firstName
self.lastName = lastName
self.email = email
self.money = money
self.job = job
def __str__(self):
data = [self.firstName, self.lastName, self.email, self.money, self.job]
return str(data)
def enter_data():
global firstName, lastName, money, job, email
firstName = input("first name: ")
lastName = input("last name: ")
money = input("student's fees or worker's salary: ")
email = input("email: ")
job = input("job: ")
print("\n")
def enter_data_answer():
answer = input("do you want to enter data of another person (yes / no): ")
if answer not in ["yes", "y", "no", "n"]:
print("\n")
print("enter a valide option (yes / no)")
print("\n")
enter_data_answer()
return answer
data_base = []
def make_object():
school_object = School(firstName, lastName, money, email, job)
data_base.append(school_object.__str__())
if __name__ == '__main__':
enter_data()
make_object()
while enter_data_answer() in ["yes", "y"]:
enter_data()
make_object()
print("\n")
for data in data_base:
print(data)
| true
|
9492b53ff84e6463ca659d5ade4c4b6be287501a
|
michalmaj90/basic_python_exercises
|
/ex1.py
| 346
| 4.21875
| 4
|
'''Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.'''
name = input("What's your name?? ")
age = input("What's your age?? ")
year = str((100 - int(age)) + 2018)
print("Hello " + name + "! You'll be 100 years old in " + year)
| true
|
dc7a57d761082468346561bfa10083e4e5b80e56
|
mohammedjasam/Coding-Interview-Practice
|
/LeetCode/LongestSubstring.py
| 850
| 4.125
| 4
|
"""Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring."""
#
class LongestSubstring:
maxi = ""
def find(self, s):
sub = ""
lsub = []
for i in s:
if not(i in sub):
# print(i)
sub += i
else:
# print(i)
lsub.append((len(sub),sub))
sub = ""
sub += i
# sorted(lsub,reverse = True)
return max(lsub)[1]
s = 'pojasam'
# if 'a' in s:
a = LongestSubstring();
print(a.find(s))
| true
|
0d7d6aa9fdf8aaed45bb449a8e6ada38cc252118
|
RustemSult/a-byte-of-python
|
/03_Operators_String.py
| 1,750
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
print("--- Операции со строками ---\n")
## Операции со строками
a = 'What\'s '
b = 'your name?'
print(a + b)
a = 'Вывод 1.'
b = '\tВывод 2 c отступом(табуляцией).'
print(a + b)
a = '\tВывод 1 c отступом.'
b = '\tВывод 2 c отступом.'
print(a + b)
a = 'Строка 1'
b = '\nСтрока 2'
print(a + b)
b = '\n\tВывод 2 строки c отступом'
print(a + b)
# Метод len() для строк
print("\n--- Метод len() ---\n")
a = 'This is string'
b = 'This\'s string'
l = len(a)
print("Это строка '{}' и её длина равна {}".format(a, l))
print("Это строка '{}' и её длина равна {}".format(b, len(b)))
## Применение чисел в строках
# Метод str()
print("\n--- Метод str() ---\n")
# вывод с ошибкой
print("Это строка '" + a + "' и её длина равна " + l)
# правильно
print("Это строка '" + a + "' и её длина равна " + str(l))
print("Это строка '" + b + "' и её длина равна " + str(len(b)))
print("\n--- Использование спец. символов ---\n")
# Вывод на экран с использованием спец. символов
print("Это строка '%s' и её длина равна %s" % (a, l))
print("Это строка '%s' и её длина равна %s" % (b, len(b)))
print("a = %s" % a)
a = 5
print("%s ** 2 = %s" % (a, a ** 2))
a, b, c = 5, 6, 7
print("a * b + c = %s*%s + %s = %s" % (a, b, c, a*b + c))
print("a * b / c = %s*%s / %s = %s" % (a, b, c, a*b / c))
print("\n--- End ---")
| false
|
aff69fc6ff8b5b58c30305febf4d384b4e68d9d4
|
jesicaduarte-test/code_challenge
|
/palindromeTest.py
| 673
| 4.34375
| 4
|
def palindrome(e):
if type(e) != str:
return False
else:
e = e.replace(" ", "")
if len(e) <= 0:
return False
else:
if str.lower(e) == str.lower(e)[::-1]:
return True
else:
return False
# In this array we define the values that we want to use in our function
dataSet = [3, 2.3,' ','999','98','ERe!eRE','Re!eRE','!!!','!!"!','mum','mun','somos o no somos','somos no somos','Somos o no soMos','Somos NO somos',' space','space ','e3e@e3e','e3e@ee','12/11/21','02/02/2020']
for e in dataSet:
# If the element of the data set it's a palindrome this function will print True if it's not, this function will print False
print(palindrome(e))
| false
|
0e8f5383d8e33592ec5f1b0ebb18c7f9bfe9f7dc
|
Shashankhs17/Hackereath-problems_python
|
/Basic/palindrome_string.py
| 461
| 4.15625
| 4
|
'''
You have been given a String S.
You need to find and print whether this string is a palindrome or not.
If yes, print "YES" (without quotes), else print "NO" (without quotes).
'''
string = input("Enter the string:")
lenght = len(string)
flag = 0
i = 0
while i<lenght/2:
if string[i] == string[lenght - 1]:
flag = 1
else:
flag = 0
break
i += 1
lenght -= 1
if flag == 1:
print("YES")
else:
print("NO")
| true
|
247bf8d334045c2af71b90ee7dd9be4a67dc1941
|
mmore500/hstrat
|
/hstrat/_auxiliary_lib/_capitalize_n.py
| 454
| 4.1875
| 4
|
def capitalize_n(string: str, n: int) -> str:
"""Create a copy of `string` with the first `n` characers capitalized.
If `n` is negative, the last `n` characters will be capitalized.
Examples
--------
>>> capitalize_n('hello world', 2)
'HEllo world'
>>> capitalize_n('goodbye', 4)
'GOODbye'
"""
return (
string[:n].upper() + string[n:]
if n >= 0
else string[:n] + string[n:].upper()
)
| true
|
4adec0efa3c15a3ab80eb6ec7706f4dfc51cb015
|
mmore500/hstrat
|
/hstrat/_auxiliary_lib/_render_to_numeral_system.py
| 1,278
| 4.21875
| 4
|
# adapted from https://cs.stackexchange.com/a/65744
def render_to_numeral_system(n: int, alphabet: str) -> str:
"""Convert an integer to its digit representation in a custom base.
Parameters
----------
n : int
The non-negative integer to be converted to a custom base
representation.
alphabet : str
A string of unique characters representing the digits in the custom
base.
The i-th character in the alphabet corresponds to the i-th digit in the
base.
Returns
-------
str
A string of characters representing the custom base representation of the given integer.
Raises
------
AssertionError
If the integer is negative or if the alphabet contains repeated
characters.
Examples
--------
>>> render_to_numeral_system(163, '0123456789abcdef')
'a3'
>>> render_to_numeral_system(42, '01234567')
'52'
>>> render_to_numeral_system(7, '01')
'111'
"""
assert n >= 0
assert len(alphabet) == len(set(alphabet))
if n == 0:
return alphabet[0]
b = len(alphabet)
reverse_digits = []
while n > 0:
reverse_digits.append(alphabet[n % b])
n = n // b
return "".join(reversed(reverse_digits))
| true
|
02901ed5551932dcd71f9c33e75361f815bc963c
|
Isaac12x/codeexamples
|
/split_list.py
| 1,858
| 4.40625
| 4
|
def sub_split_list_by_reminder(list, splitter):
"""
Function to create a nested list with length equal
to the reminder of division
This function splites the list into an amount of nested lists equally sized
to the second parameter.
It also spreads the contents of the first list in nested lists equals to
that reminder.
Parameters
----------
list : list of ints
splitter : int
Returns
-------
nested list of ints
>>> sub_split_list_by_reminder([1,2,3,4,5], 3)
[[1,2], [3,4], [5]]
>>> sub_split_list_by_reminder([21, 3123, 34], 2)
[[21, 3123], [34]]
"""
# Required variables
list_length = len(list)
new_list = []
lower_end_slice = 0
next_slice = 0
# Calculate the length of each new nested list
nested_list_length = list_length % splitter
next_slice = nested_list_length
# Use the splitter as the iterator - can also be accomplished with
# list comprehension, but it seems clearer in this more verbose way
while splitter >= 1:
# Construct a new list by slicing the first one where required
new_list.append(list[lower_end_slice:next_slice])
# Update the slicers
lower_end_slice += nested_list_length
next_slice += nested_list_length
# Once a list is created, substract that from the remaining to create
splitter -= 1
# Uncoment the following line if you want to see the results
print new_list
# Return the updated list
return new_list
# You can check the otutputs by going to terminal and write in the directory
# python test.py and you'll see the results || alternatively you can use
# Doctest to test the input in the docstring.
sub_split_list_by_reminder([1, 2, 3, 4, 5], 3)
sub_split_list_by_reminder([21, 3123, 34], 2)
sub_split_list_by_reminder([21, 3123, 34], 30)
| true
|
2ceb823659761ef5050ccbbd95fda076be548c7f
|
Joycici/Coding
|
/Python/Exercise/ex3.py
| 893
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
__author='Joycici'
__version__='1.0'
"""
print "I will now count my chickens:"
# 输出hens的数量
print "Hens",25.0 - 30 / 6
# 输出Roosters数量
print "Roosters", 100.0 - 25 * 3 % 4
# 输出鸡蛋的数量
print "Now I will count the eggs:"
print 3.0 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# 比较3+2和5-7的大小
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
# 分别计算3+2和5-7
print "What is 3 + 2? ", 3 + 2
print "What is 5 - 7? " , 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?",5 <= -2
# 输出浮点数,只要待计算的数中有一个是浮点数,就会自动输出浮点数
print "7.0 / 4.0" , 7.0 / 4.0
print " 7 / 4" , 7 / 4
print " 7.0 / 4 " , 7.0 / 4
print "7 /4.0 ", 7 / 4.0
| false
|
a1c3b7af2265f6c2ff76ff7d9e32be78236487af
|
Joycici/Coding
|
/Python/Exercise/ex29.py
| 959
| 4.125
| 4
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Exercise 29: What If
'''
"""
__author='Joycici'
__version__='1.0'
"""
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people == dogs:
print "People are dogs."
# 附加题
'''
1. 如果if为真,则执行下一行缩进的代码
2. 为什么要缩进,IF最后的: 告诉python要创建一个新的代码块,缩进后的代码表示自己属于新的代码块
3. 如果不缩进会报错,应为: 后面要求必须有缩进
4. 判断真假的都可以放在if后面
5. 会输出不同的值呀
'''
if True and False:
print "return false"
if True or False:
print "return true"
| false
|
787d8c98b29972ac759a8e13175dccb84f1dd69a
|
paulopimenta6/ph_codes
|
/python/edx_loop_for_3.py
| 263
| 4.34375
| 4
|
#Using a for loop, write a program which asks the user to type an integer, n, and then prints the sum of all numbers from 1 to n (including both 1 and n).
number = int(input("write a number: "))
sum=0
for i in range(1,number+1):
sum = sum + (i**2)
print(sum)
| true
|
856d53f1392e78d169f0f4bf1d557a1b05930bf4
|
mai-mad/PythonLearning
|
/june/18.06.py
| 1,630
| 4.125
| 4
|
import re
txt = "Ilya hates windows"
print(txt)
x = txt.replace("hates", "loves")
print(x)
x = x.replace("windows", "MACos")
print(x)
x = x.upper()
print(x)
x = x.lower()
print(x)
# Phonde code -> City
phone = "(8422) 41-23-93" # krasnodar perm ulyanovsk
x = phone.find("(495)")
if x >= 0:
print("Moscow")
x = phone.find("(812)")
if x >= 0:
print("Piter")
x = phone.find("(861)")
if x >= 0:
print("Krasnodar")
x = phone.find("(342)")
if x >= 0:
print("Perm")
x = phone.find("(8422)")
if x >= 0:
print("Ulyanovsk")
# Создать строку и определить есть ли в ней предлоги "в, без, до, из"
y = "Производные бе предлоги образовались более позднее время от слов других частей речи и подразделяются на"
r = re.findall(r'[^а-я](в|без|до|из|от) ', y)
n = len(r) # n - это количество предлогов
print ("r: "+str(len(r)))
if n >= 1:
print("предлоги найдены")
else:
print("предлоги не найдены")
# Method Split
a = "is,red,This" # This is red
m = a.split(",")
print(m) # returns ['Hello', ' World!']
# print Ivan
#print(m[0])
# print Dima
#print(m[1])
# print This is red!
print(m[2], m[0], m[1])
# Operator "in"
txt = "The rain in Spain stays mainly in the plain"
if "Rediska" in txt:
print("OK")
else:
print("not OK")
# Concatinations
a = "Hello"
b = "World"
c = a + " " + b + "!"
# Hello World! Hello Ivan!
print(c + " Hello Ivan!")
age = 36
txt = "My name is John, I am " + str(age)
print(txt)
| false
|
52c9228ae50befb9f2080031dc823750fde2b954
|
mai-mad/PythonLearning
|
/july/11.07.2020.py
| 844
| 4.125
| 4
|
fruits = ["apple", "banana", "cherry", "pear", "persimmon", "date", "peach"]
i = 1
for x in fruits:
print (str(i)+" "+ x)
i=i+1
# print all even positions:
i = 1
for x in fruits:
if i % 2 == 0:
print (str(i)+" "+ x)
i=i+1
# print all odd positions:
i = 1
for x in fruits:
if i % 2 == 1:
print (str(i)+" "+ x)
i=i+1
# print all fruits which starts with "p"
c = 'p'
for x in fruits:
if x[0]==c:
print(x)
# print all fruits which second letter "a"
c = "a"
for x in fruits:
if x[1]==c:
print(x)
#2 print all fruits with third letter "a"
c = "a"
for x in fruits:
if x[2]==c:
print(x)
#print all fruits with last letter "e"
c = "e"
for x in fruits:
if x[3]==c:
print(x)
#5. print all fruits with first letter "a" or "b"
c = "a",
c1= "b"
for x in fruits:
if x[0]==c or x[0]==c1:
print(x)
| false
|
90b9a6ed8f46b120764be142824d76cac1f88a2f
|
sssandesh9918/Python-Basics
|
/Functions/11.py
| 291
| 4.28125
| 4
|
'''Write a Python program to create a lambda function that adds 15 to a given
number passed in as an argument, also create a lambda function that multiplies
argument x with argument y and print the result.'''
add= lambda a: a+15
mul =lambda x,y: x*y
r=add(10)
s=mul(15,10)
print(r)
print(s)
| true
|
ff1908e083e96ca7f60b802cf1ff4549a789fde2
|
sssandesh9918/Python-Basics
|
/Data Types/7.py
| 373
| 4.21875
| 4
|
'''Write a Python function that takes a list of words and returns the length of the
longest one.'''
def func(a):
b=[]
for i in range(a):
words=list(input("Enter words"))
b.append(words)
print(b)
c=[]
for j in range(len(b)):
c.append(len(b[j]))
print(max(c))
a=int(input("Enter the number of words you want to enter"))
func(a)
| true
|
a8434f61ab39cdab8ba3622b7b0f0456bcd424de
|
sssandesh9918/Python-Basics
|
/Functions/1.py
| 254
| 4.28125
| 4
|
'''Write a Python function to find the Max of three numbers.'''
def highest(x,y,z):
return(max(x,y,z))
a=input("Enter first number")
b=input("Enter second number")
c=input("Enter third number")
m=highest(a,b,c)
print("The max of three numbers is ",m)
| true
|
9d3fdd56d2421bbaf118afaa03bbba63f2c39382
|
ArthurMelo9/100daysofCode
|
/examples.py
| 955
| 4.15625
| 4
|
#A rollercoaster ride
#print("Welcome to Rollercoaster!")
#height= int(input("Enter your height in cm: "))
#if height > 120:
# print("You can ride the rollercoaster!")
#else:
# print("Sorry, you have to grow taller before you can ride.")
print("Welcome to rollercoaster!")
height=int(input("What is your height in cm? "))
if height>=120:
print("You're eligible to ride")
age= int(input("What is your age? "))
bill = 0
#if age < 18:
#print("Ticket costs $5")
#else:
#print ("Ticket costs $12")
if age < 12:
bill = 5
print ("Ticket costs $5")
elif age <=18:
bill = 18
print ("Ticket costs $7")
elif age>=45 and age<=55:
bill = 0
print ("You have a free ride!")
else:
bill = 12
print("Ticket costs $12")
want_photo = input ("Do you want a picture? Y or N ")
if want_photo == "Y":
bill +=3
print(f"Your total bill is ${bill}")
else:
print("You're not eligible to ride")
| true
|
0c7efc52a64526e2c9fb5c3dbc7495bb479908b7
|
omvikram/python-advance
|
/decorators.py
| 661
| 4.125
| 4
|
#Return a function
def myfunc1(name=""):
print("This is myfunc1()")
def welcome():
print("\t This is welcome()")
def greet():
print("\t This is greet()")
if(name == "Om"):
return welcome
else:
return greet
f = myfunc1()
f()
f= myfunc1("Om")
f()
#Pass a function as param
def myfunc2(param_func):
print("This is myfunc2() start")
param_func()
print("This is myfunc2() end")
myfunc2(myfunc1("Om"))
#Check the decorator now
# add @myfunc2 on top of myfunc1 so that myfunc1() can be wrapped under the myfunc2()
@myfunc2
def myfunc3():
print("This is myfunc3() which will use the decorator")
| true
|
8436a1dc91a3328e45aba2a4b8e9c8192561aef8
|
mingyuea/pythonScriptingProblems
|
/routeCircle.py
| 821
| 4.125
| 4
|
class Solution:
def judgeCircle(self, moves):
"""
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
"""
moveDict = {'U': (1,1), 'D':(1, -1), 'L':(0, -1), 'R':(0, 1)}
pos = [0, 0]
for move in moves:
pos[moveDict[move][0]] += moveDict[move][1]
if pos[0] == 0 and pos[1] == 0:
return True
else:
return False
| true
|
10c0939b7af758a843a5e4d654e1758f6058ca7d
|
shoaib30/SE-Lab
|
/Triangle.py
| 352
| 4.34375
| 4
|
a = input("Enter First side : ")
b = input("Enter Second side : ")
c = input("Enter Third Side : ")
if((a+b) < c or (b+c) < a or (c+a) < b):
print "Not a triangle"
else:
if(a == b or b == c or c == a):
if(a == b and b == c):
print "Equilateral"
else:
print "Isosceles"
else:
print "Scalene"
| false
|
52353fc78521cb3723dc76db40f354eb873d3bf4
|
costagguilherme/python-desafios
|
/exercicios/laço-while/desafio63.py
| 272
| 4.125
| 4
|
num = int(input('Digite um número de termo para sequência Fibonacci: '))
cont = 1
anterior = 0
proxima = 1
soma = 1
while cont <= num:
print(anterior, end='-')
cont += 1
soma = proxima + anterior
anterior = proxima
proxima = soma
print('Fim')
| false
|
9d84d6e4962d69d5e3bd6fc9e5d3d1f2b06ce5ef
|
nickk2021/python
|
/master-python/10-sets-diccionarios/diccionarios.py
| 828
| 4.3125
| 4
|
"""
Diccionario:
un tipo de dato que almacena un conjunto de datos.
en formato clave > valor.
Es parecido aun array asociativo o un objeto json.
"""
persona = {
"nombre": "Pablo",
"apellido": "Rojas",
"web":"Pablorojas.ar"
}
print(persona["apellido"])
# LISTAS CON DICCIONARIOS
contactos = [
{
"nombre": "Antonio",
"email": "Amtonio@antonio.com"
},
{
"nombre": "Alberto",
"email": "Alberto@alberto.com"
},
{
"nombre": "Juan",
"email": "Juan@juan.com"
}
]
contactos[0]["email"] = "antoñito@antoñito.com"
print(contactos[1]["email"])
print("\nListado de contactos: ")
for contacto in contactos:
print(f"Nombre del contacto: {contacto['nombre']}")
print(f"email del contacto: {contacto['email']}")
print("----------------------------")
| false
|
1234197b9ea59d5b5004b2cd424e6e9b38417df0
|
cskamil/PcExParser
|
/python/py_trees_insert_binarytree/insert_binarytree.py
| 2,602
| 4.3125
| 4
|
'''
@goalDescription(In a BinaryTree, adding new nodes to the tree is an important capability to have.\nConstruct a simple implementation of a BinaryTree consisting of an __init__ method and an insertLeft method, which adds new nodes to the tree to the left of the root. )
@name(Inserting binary tree)
'''
# Define a binary tree class
class BinaryTree:
'''@helpDescription( We want to define the __init__ method for the BinaryTree class to take in a root node, so we specify the two parameters to be self and root. Recall that self is a required parameter.)'''
def __init__(self, root):
'''@helpDescription(We set the key value of the BinaryTree equal to root)'''
self.key = root
'''@helpDescription(We set the node to the left of root equal to None (since it doesn’t exist yet))'''
self.left = None
'''@helpDescription(We set the node to the right of root equal to None (since it doesn’t exist yet))'''
self.right = None
# Define a function to insert node from the left
'''@helpDescription( We want to define a function that inserts a new node to the left of an existing node, so we specify the two parameters self and new_node)'''
def insert_left(self, new_node):
'''@helpDescription(We need to check if there are any existing node to the left of the root.)'''
if self.left is None:
'''@helpDescription( If the node to the left of the root doesn’t exist,then we set it equal to a new instance of BinaryTree with the new node as its root)'''
self.left = BinaryTree(new_node)
'''@helpDescription(If the node to the left of the root already exists, then we replace the already existing left node with the new node.)'''
else:
node_tree = BinaryTree(new_node)
'''@helpDescription(Here, we update the references to make sure the nodes reference each other correctly. Here we insert each left node right next to the root node.)'''
node_tree.left = self.left
self.left = node_tree
# Define a function to print the tree
'''@helpDescription(We need to define a function to print our tree structure.)'''
def print_tree(self):
'''@helpDescription(We want to print each node from left to right.)'''
if self.left:
self.left.print_tree()
print(self.key, " ", end="")
if self.right:
self.right.print_tree()
# Initializing a tree
root = BinaryTree(10)
root.insert_left(5)
root.insert_left(6)
root.insert_left(14)
root.print_tree()
| true
|
502ce16f0984b5d247561afe4fe2ef29f9a4bd72
|
paulatumwine/andelabs
|
/Day 2/OOP/oop_concepts.py
| 1,944
| 4.625
| 5
|
from abc import ABCMeta
class Product(object):
"""
An abstract class
"""
__metaclass__ = ABCMeta
unit_price = 0
def __init__(self, name, maker):
self.__name = name
self.__maker = maker
self._quantity = 0
self._total_stock_price = 0
def add_stock(self, quantity):
self._quantity += quantity
self._total_stock_price += self.unit_price * quantity
def sell(self, quantity):
self._quantity -= quantity
self._total_stock_price -= self.unit_price * quantity
def get_name(self):
"""Demonstration of encapsulation; this is a wrapper to allow access to the value in __name"""
return self.__name
def check_product_catalogue(self):
"""A method to demonstrate polymorphism"""
pass
class Phone(Product):
"""
Implementing a phone class, which is a subclass
of the product class, to demonstrate inheritance
"""
unit_price = 400
def check_product_catalogue(self):
return str(self._quantity) + " " + self.get_name() + " phones at " + str(Phone.unit_price) + "@, total: " + str(self._total_stock_price)
class China(Phone):
"""
Similar to the Phone class
"""
unit_price = 100
def check_product_catalogue(self):
"""A demonstration of polymorphism"""
return str(self._quantity) + " " + self.get_name() + " at " + str(China.unit_price) + "@, total: " + str(self._total_stock_price)
def main():
product = Product("Corolla", "Toyota")
phone = Phone("Samsung Galaxy S6 Edge", "Samsung")
phone.add_stock(10)
print(phone.check_product_catalogue())
phone.sell(5)
print(phone.check_product_catalogue())
phone = China("Plates", "Nice house of plastics")
phone.add_stock(12)
print(phone.check_product_catalogue())
phone.sell(6)
print(phone.check_product_catalogue())
if __name__ == '__main__':
main()
| true
|
fda3cec9a0c0ce2ff34e75e8b2f1707e44c18570
|
saqibsidd67/CIS2348
|
/Homework 1/CodingProblem1_main.py
| 1,051
| 4.3125
| 4
|
# Saqib Siddiqui
# PSID: 1495537
print('Birthday Calculator')
print('Current Day')
current_month = int(input('Month:'))
current_day = int(input('Day:'))
current_year = int(input('Year:'))
print('Birthday')
birth_month = int(input('Month:'))
birth_day = int(input('Day:'))
birth_year = int(input('Year:'))
if current_month == birth_month and current_day == birth_day:
current_age = current_year - birth_year
print('Happy Birthday!')
print('You are',current_age,'years old.')
elif current_month < birth_month:
current_age = current_year - birth_year - 1
print('You are', current_age, 'years old.')
elif current_month > birth_month:
current_age = current_year - birth_year
print('You are', current_age, 'years old.')
elif current_month == birth_month and current_day > birth_day:
current_age = current_year - birth_year
print('You are', current_age, 'years old.')
elif current_month == birth_month and current_day < birth_day:
current_age = current_year - birth_year - 1
print('You are', current_age, 'years old.')
| false
|
836a489eaa421947cd9e5bfe255897c9ba835def
|
julio-segura/python-calculator
|
/main.py
| 834
| 4.34375
| 4
|
# programa para hacer operaciones matemáticas sencillas (suma, resta, multiplicación, división)
some_text = "Welcome to the Calculatora Magnifique."
print(some_text)
# valor igual a variable (info introducida por el usario (llamada a la acción))
x = int(input("Enter the value for x: "))
y = int(input("Now enter the value for y: "))
# valor igual a info introducida por el usuario (que en este caso, ha de escoger entre las opciones proporcionadas en la llamada a la acción)
operation = input("Choose math operation +, -, *, /")
# reglas por las cuales el programa llevará a cabo las operaciones
if operation == "+":
print(x + y)
elif operation == "-":
print(x - y)
elif operation == "*":
print(x * y)
elif operation == "/":
print(x / y)
else:
print("You did not provide the correct math operation.")
| false
|
17207416f919bca290c26a5d09e370225ec6c4ba
|
debasissil-python/debasissil-python
|
/str_formatting.py
| 824
| 4.21875
| 4
|
name = input("What's Your Name: ")
surname = input ("And Your surname please: ")
age = input('May we know your age: ')
address = input("Where do you live: ")
work = input("What do You do: ")
move = input ("Do you want to relocate to Canada: ")
where = input('Which Province: ')
when = input("When can You relocate: ")
job = input ("Do you have a job: ")
search = input('Have You searched: ')
need = input ("Do you need a job: ")
how_many = input ('How many jobs: ')
total = "Hallo %s %s ! You are %s and you live in %s ." % (name, surname, age, address)
thoughts = f"You are {work} and it's a {move} that you want to come to {where} {when}"
jobs = "You {} but {}. You {} and I recommend you will need {}.".format(job, search, need, how_many)
print (total)
print(thoughts)
print(jobs)
| false
|
08199d5030d91da6c6ec701b5e4d1fb76f97c591
|
debasissil-python/debasissil-python
|
/sec9_list_comprehensions.py
| 2,281
| 4.25
| 4
|
# ALWAYS REMEMBER ---->
# For list comprehension with or without if statement, the code should be -
# [a for a in list if a>10] ---> It'll iterate through the list and give the output
# For list comprehension with if else statement, the code should be -
# [a if a>10 else 'none' for a in list] ---> The for loop goes at the very end
#l = [99, 95, 94,'no data']
#def func(l):
# new_l = [num for num in l if isinstance(num, int)]
# print (new_l)
#int_list = [2,3,5,'hallo']
#def func(int_list):
# new_list = [i for i in int_list if isinstance(i, int)]
# if else statement
#list = [2,3,78,65,0,100]
#new_list = [n if n > 50 else 'Below Grade' for n in list ]
#print (new_list)
# if else statement
#list = [2,3,78,65,0,100,'hhh', 'xxx']
#new_list = [a > 50 if isinstance(a, int) else 'A Str' for a in list]
#print (new_list)
# if else statement
#list = [2,3,78,65,0,100,'hhh', 'xxx']
#new_list = [a > 50 for a in list if isinstance(a, int)]
#print (new_list)
# if else statement
#list = [2,3,78,65,0,100,'hhh', 'xxx']
#new_list = [a for a in list if isinstance(a, int)]
#print (new_list)
# if else statement
#list = [2,3,78,65,0,100,'hhh', 'xxx']
#new_list = [a for a in list if isinstance(a, int) if a>50]
#print (new_list)
l = [ 2, 3, 6, 'no num', 'all num']
#new_l = [a if isinstance (a, int) else a == 0 for a in l]
#print(new_l)
n_l = [a for a in l]
n_l_1 = [a for a in l if isinstance(a, int)]
n_l_2 = [a if isinstance(a, int) else 0 for a in l]
n_l_3 = [a if not isinstance(a, str) else 0 for a in l]
print (n_l)
print (n_l_1)
print (n_l_2)
print (n_l_3)
lst = [65,98,32,'lkjh','poiu']
def func(lst):
return [a if isinstance(a, int) else 0 for a in lst]
print (func(lst))
# A list comprises of str with floating numbers. Output needs to be sum of all those numbers and
# changing them to float
#l = [99.3, 95.8, 94.5]
#def func(l):
# return sum(l)
#print (func(l))
lst = ['99.3', '95.8', '94.5']
#def func(lst):
# return sum([float(a) for a in lst])
#print (func(sum([float(a) for a in lst])))
n_l = sum(float(a) for a in lst)
print (n_l)
| false
|
1c6a50a9e56712b4d1500ed489a876408d0075fd
|
cyrsis/TensorflowPY36CPU
|
/_15_Crawler/showTuple.py
| 1,165
| 4.375
| 4
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
__author__ = 'hstking hstking@hotmail.com'
class ShowTuple(object):
def __init__(self):
self.T1 = ()
self.createTuple()
self.subTuple(self.T1)
self.tuple2List(self.T1)
def createTuple(self):
print(u"建立tuple:")
print(u"T1 = (1,2,3,4,5,6,7,8,9,10)")
self.T1 = (1,2,3,4,5,6,7,8,9,10)
print(u"T1 = "),
print(self.T1)
print('\n')
def subTuple(self,Tuple):
print(u"tuple分片:")
print(u"取tuple T1 的第4 個到最後一個tuple 組成的新tuple,執行指令T1[3:]")
print(self.T1[3:])
print(u"取tuple T1 的第2 個到倒數第2 個元素組成的新tuple,步長為2,執行指令T1[1:-1:2]")
print(self.T1[1:-1:2])
print('\n')
def tuple2List(self,Tuple):
print(u"tuple 轉換成串列:")
print(u"顯示tuple")
print(u"T1 = "),
print(self.T1)
print(u"執行指令 L2 = list(T1)")
L2 = list(self.T1)
print(u"顯示串列")
print(u"L2 = "),
print(L2)
print(u"串列追加一個元素100 後,轉換成tuple。執行指令L2.append(100) tuple(L2)")
L2.append(100)
print(u"顯示新tuple")
print(tuple(L2))
if __name__ == '__main__':
st = ShowTuple()
| false
|
39c5f391e9016907762f2465f47b5251316bfd8c
|
Emile-Dadou-EPSI/EulerProject
|
/problem1.py
| 501
| 4.15625
| 4
|
## Euler Project problem 1 :
## If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
## The sum of these multiples is 23.
## Find the sum of all the multiples of 3 and 5 below 1000.
def findMultiples(nbMax):
res = 0
for x in range(nbMax):
if x % 3 == 0 or x % 5 == 0:
res = res + x
return res
def main():
print("Start problem 1 : \n")
res = findMultiples(1000)
print(res)
if __name__ == "__main__":
main()
| true
|
7d3a72a7c767addcf1320b785bedd3b5e61f95ea
|
padmini06/pythonExamples
|
/example.py
| 486
| 4.1875
| 4
|
#!/usr/bin/python3
print("hello")
x=""
x=input("enter your name \n")
print("Hello",x)
x=input("enter number 1 \n")
y=input("enter number 2 \n ")
if x>y:
print("x is greater than y");
print("anscscdsafasf")
else:
print("y is greater than x");
def MaxNumber(a,b,c):
"This function will return the max of the three value passed"
if a>b and a>c : return a
elif b>c and b>a : return b
else:return c
max= MaxNumber(5,12,10)
print("Max number is :",max)
| true
|
deb17862f7715aca87c07a2b0a74571da13bbfc7
|
padmini06/pythonExamples
|
/Example5.py
| 970
| 4.21875
| 4
|
#!/usr/bin/python3
"""
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. """
# Python code to generate random numbers and append them to a list
import random
def Rand(start, end, num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
#num = 10
#start = 20
#end = 40
#print(Rand(start, end, num))
list_1 = Rand(10,100,8)
list_2 = Rand(10,100,6)
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(list_1)
print(list_2)
output = []
for i in list_1 :
if i in list_2 :
if i not in output :
output.append(i)
print(output)
| true
|
a8170f6055aac917f096ce057feba9015c713bed
|
padmini06/pythonExamples
|
/example1.py
| 396
| 4.375
| 4
|
"""
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old."""
_name= input("Enter your name\n")
_age = int(input("Enter you age \n"))
if _age > 100 :
print("your age is greater than 100")
else:
diff = 100-_age;
print(_name + " will reach 100 after",diff,"years")
| true
|
0e12c929ff4cbb6a9b263a4bbe074edeea8546f1
|
rogerwoods99/UCDLessons
|
/UCDLessons/DataCampDictionary.py
| 2,374
| 4.4375
| 4
|
# find the capital based on index of the country, a slow method
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
ind_ger=countries.index("germany")
# Use ind_ger to print out capital of Germany
print(capitals[ind_ger])
#===========================================================
#===========================================================
# A dictionary has been defined. Find values within it
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Print out the keys in europe
print(europe.keys())
# Print out value that belongs to key 'norway'
print(europe['norway'])
#===========================================================
#===========================================================
# add 2 new countries to the capitals list for Europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Add italy to europe
europe['italy']='rome'
# Print out italy in europe. This verifies that Italy is in the list
print('italy' in europe)
# Add poland to europe
europe["poland"]='warsaw'
# Print europe
print(europe)
#===========================================================
#===========================================================
# add and edit items in a dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw',
'australia':'vienna' }
# Update capital of germany
europe.update({'germany':'berlin'})
# Remove australia
del(europe["australia"])
# Print europe
print(europe)
#===========================================================
#===========================================================
# this is about dictionaries within dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':46.77 },
'france': { 'capital':'paris', 'population':66.03 },
'germany': { 'capital':'berlin', 'population':80.62 },
'norway': { 'capital':'oslo', 'population':5.084 } }
# Print out the capital of France
print(europe['france']['capital'])
# Create sub-dictionary data
data={'capital':'rome','population':59.83}
# Add data to europe under key 'italy'
europe['italy']=data
# Print europe
print(europe)
| true
|
444283f159d5fc198a4bb0a990968fd321c18e87
|
planktonlex55/ajs
|
/basics/rough_works/2_iterators.py
| 841
| 4.8125
| 5
|
#for can be used to iterate over many data structures in python.
#ex. 1
list1 = [10, 20, 30]
for x in list1:
print x
string1 = "python"
for x in string1:
print x
dict1 = {"key1": "value1", "key2": "value2", "key3": 10}
print dict1 #order of printing seems to be from last to first
for x in dict1:
print x #o/p is: key3 key2 and key1
print dict1[x] #o/p are the values
#one more way to use for
#>>> for line in open("a.txt"):
#... print line,
#...
#first line
#second line
print "this way we can use for"
print "Note: The built-in function iter takes an iterable object and returns an iterator."
y = iter (list1)
print y #<listiterator object at 0x021375D0>
print y.next()
print y.next()
print y.next()
#parantheses is a must.
print y.next() #Expected StopIteration error
| true
|
c9a7d17b5534f997709ab430eb851262b4e06a5d
|
Shivani-Y/assignment-3-prime-factors-Shivani-Y
|
/prime.py
| 785
| 4.28125
| 4
|
"""
prime.py -- Write the application code here
"""
def generate_prime_factors(number):
""" Code to generate prime factors """
prime_list = []
i = 2
if not isinstance(number, int): #raises an error of function called for any type but integer
raise ValueError("Only integers can be used in the function")
if number == 1: #if number 1 then prints a blank list
print(prime_list)
elif number == 2 and number%i == 0: #if number is 2 then prime factor is 2
prime_list.append(number)
print(prime_list)
else:
while i <= number:
if (number%i) == 0:
prime_list.append(i)
number = number / i
else:
i = i+1
print(prime_list)
return prime_list
| true
|
9511d38e439478be9b7166629091ba87f9652836
|
YoungWenMing/gifmaze
|
/examples/example4.py
| 1,793
| 4.375
| 4
|
# -*- coding: utf-8 -*-
"""
This script shows how to run an animation on a maze.
"""
import gifmaze as gm
from gifmaze.algorithms import prim
# size of the image.
width, height = 605, 405
# 1. define a surface to draw on.
surface = gm.GIFSurface(width, height, bg_color=0)
# define the colors of the walls and tree.
# we use black for walls and white for the tree.
surface.set_palette('kw')
# 2. define an animation environment to run the algorithm.
anim = gm.Animation(surface)
# 3. add a maze into the scene.
# the size of the maze is 119x79 but it's scaled by 5
# (so it occupies 595x395 pixels) and is translated 5 pixels
# to the right and 5 pixels to the bottom to make it located
# at the center of the image.
maze = gm.Maze(119, 79, mask=None).scale(5).translate((5, 5))
# pause two seconds, get ready!
anim.pause(200)
# 4. the animation runs here.
# `speed` controls the speed of the animation,
# `delay` controls the delay between successive frames,
# `trans_index` is the transparent color index,
# `mcl` is the minimum code length for encoding the animation
# into frames, it's at least 2 and must satisfy
# 2**mcl >= number of colors in the global color table.
# `start` is the starting cell for running Prim's algorithm. (it's a cell,
# not a pixel).
# `cmap` controls how the cells are mapped to colors, i.e. {cell: color}.
# here `cmap={0: 0, 1: 1}` means the cells have value 0 (the walls) are colored
# with the 0-indexed color (black), cells have value 1 (the tree) are colored
# with the 1-indexed color (white).
anim.run(prim, maze, speed=30, delay=5, trans_index=None,
cmap={0: 0, 1: 1}, mcl=2, start=(0, 0))
# pause five seconds to see the result clearly.
anim.pause(500)
# 5. save the result.
surface.save('example4_simple_anim.gif')
surface.close()
| true
|
5f4c8a6d164228395c8aaecd4893ee887de0034b
|
Lingrui/Learn-Python
|
/Beginner/tuple.py
| 390
| 4.21875
| 4
|
#!/usr/bin/python
#define an empty tuple
tuple = ()
#a comma is required for a tuple with one item
tuple = (3,)
personInfo = ("Diana",32,"New York")
#data access
print(personInfo[0])
print(personInfo[1])
#assign multiple variables at once
name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)
#append to an existing tuple
x = (3,4,5,6)
x = x + (1,2,3)
print(x)
| true
|
b9a63cdacea35210a3952f4ca597399e1fc2cb87
|
Lingrui/Learn-Python
|
/Beginner/objects_classes.py
| 1,078
| 4.5
| 4
|
#!/usr/bin/python
###class######
## The __init__() method is called the constructor and is always called when creating an object.
class User:
name = ""
def __init__(self,name):
self.name = name
def sayHello(self):
print "Hello, my name is " + self.name
#creat virtual objects
james = User("James")
david = User("David")
eric = User("Eric")
#call methods owned by virtual objects
james.sayHello()
david.sayHello()
###class variables
class CoffeeMachine:
name = ""
beans = 0
water = 0
def __init__(self,name,beans,water):
self.name = name
self.beans = beans
self.water = water
def addBean(self):
self.beans = self.beans + 1
def removeBean(self):
self.beans = self.beans - 1
def addWater(self):
self.water = self.water + 1
def removeWater(self):
self.water = self.water - 1
def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)
pythonBean = CoffeeMachine("Python Bean", 83,20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()
| true
|
88073a7b852e94d8fcbf21de3b0c9b1ac0447563
|
ChiDrummer/CodingDojoPythonStack
|
/PythonFundamentals/math.py
| 504
| 4.53125
| 5
|
"""Multiples
Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000."""
for number in range(1,101,2):
print number
for number in range(5,100):
if number % 5 == 0:
print number
#sum the list
"""a = [1, 2, 5, 10, 255, 3]
print sum(a)"""
#average of list
"""a = [1, 2, 5, 10, 255, 3]
average = sum(a)/len(a)
print average"""
| true
|
54afcc3930bfaf9e2c5afa953cbcdd0438dd1e35
|
smahs/euler-py
|
/20.py
| 767
| 4.15625
| 4
|
#!/usr/bin/python2
"""
Statement:
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from unittest import TestCase, main
class Problem20(object):
def __init__(self, bound):
self.bound = bound
def fn(self):
return sum(map(int, str(reduce(lambda i, j: i*j,
xrange(*self.bound)))))
class TestProblem20(TestCase):
def setUp(self):
self.bound = (1, 100)
self.answer = 648
def test_main(self):
self.assertEqual(Problem20(self.bound).fn(), self.answer)
if __name__ == '__main__':
main()
| true
|
5c54b1cc7380b8069d74bbb105d682e8d3f851e2
|
RamSinha/MyCode_Practices
|
/python_codes/sorting/bubbleSort.py
| 602
| 4.125
| 4
|
#!/usr/bin/python
def bubbleSort(array):
swapped = True
for i in range(len(array))[::-1]:
if swapped is False:
break
swapped = False
for j in range(0,i):
if array[j] >= array[j + 1 ]:
swap(array, j , j + 1)
swapped = True
def swap(array, i, j):
if array[i] == array[j]:
return
array[i] = array[i] ^ array[j]
array[j] = array[i] ^ array[j]
array[i] = array[i] ^ array[j]
if __name__=='__main__':
input = [int(i) for i in raw_input().split(' ')]
bubbleSort(input)
print input
| false
|
a7b980f2e78b2720dbb60ca9ba2ef8c242a8e38b
|
jakubowskaD/Rock_Papper_Scissors-TEAM_ONE
|
/Rock_paper_scissors_game.py
| 1,947
| 4.15625
| 4
|
import random
scoretable = [0,0]
def computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def player_choice(player):
if player == "1":
player_choice = "rock"
elif player == "2":
player_choice = "paper"
else:
player_choice = "scissors"
return player_choice
def add_point_computer():
scoretable[0] = scoretable[0] + 1
def add_point_player():
scoretable[1] = scoretable[1] + 1
def run_game():
print("\nGame begins")
computer = computer_choice()
player = input("Choose 1 = rock, 2 = paper, 3 = scissors: ")
if (player != "1" and player != "2" and player!="3"):
print("Invalid choice")
return
test = player + computer[0]
player_winning_condition = ['1s', '2r', '3p']
player_draw_condition = ['1r', '2p', '3s']
print("You picked: ", player_choice(player))
print("Computer picked:", computer)
if (test in player_winning_condition):
print("You won!")
add_point_player()
elif (test in player_draw_condition):
print("It's a draw!")
else:
print("You lost!")
add_point_computer()
print("")
score_display()
def score_display():
print("")
print("--------------------------------")
print("Score table")
print("Computer:", scoretable[0])
print("Player:", scoretable[1])
def game_finish():
score_display()
input("Press enter to exit")
quit()
if __name__ == "__main__":
while (True):
run_game()
while (True):
play_again = input("Play Again? [Y/n]: ").lower()
if play_again == "" or play_again == "y":
break
elif play_again == "n":
game_finish()
else:
print("Wrong choice, try again")
| true
|
bd73fb30e905df4c30601a00e541c9eaab9ac50a
|
tashfiahasan/calculator-project
|
/calc.py
| 2,153
| 4.21875
| 4
|
# #addition
# def add(x, y):
# return x + y
# #subtraction
# def subtract(x, y):
# return x - y
# #multiplication
# def multiply(x, y):
# return x * y
# #division
# def divide(x, y):
# return x / y
# while True:
# # Take input from the user
# choice = input("Enter choice(+/-/*//): ")
# # Check if choice is one of the four options
# if choice in ('+', '-', "*', '/'):
# num1 = float(input("Enter first number: "))
# num2 = float(input("Enter second number: "))
# if choice == '1':
# print(num1, "+", num2, "=", add(num1, num2))
# elif choice == '2':
# print(num1, "-", num2, "=", subtract(num1, num2))
# elif choice == '3':
# print(num1, "*", num2, "=", multiply(num1, num2))
# elif choice == '4':
# print(num1, "/", num2, "=", divide(num1, num2))
# break
# else:
# print("Invalid Input")
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ to Add
- to Subtract
* to Multiply
/ to Divide
^ for Exponents
''')
number_1 = int(input('Please enter the first number:'))
number_2 = int(input('Please enter the second number:'))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
elif operation == '^':
print('{} ** {} ='.format(number_1, number_2))
print(number_1 ** number_2)
else:
print('Invalid Input.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
| false
|
df08c1c86d29e0187566b66bd0e0cb8a8d7813a5
|
RakhshandaMujib/The-test-game
|
/Test_game.py
| 1,992
| 4.1875
| 4
|
import math
def single_digits_only (list_is):
'''
This method checks a list of number for any number that has more than
2 digits. If there is any, it splits the digits of the same.
Argument:
list_is - List. The list of numbers to check.
Returns:
list_is - Revised list.
'''
index = 0
while True:
if list_is[index] >= 10:
insert = [int(digit) for digit in str(list_is[index])]
list_is = list_is[:index] + insert + list_is[index+1:]
index += 1
if index >= len(list_is):
break
return list_is
def del_spcl_char(list_is):
'''
This method removes specifiec the special characters & spaces from a list.
Argument:
list_is - List. The list of charcters we want to work with.
Returns:
list_is - Revised list.
'''
illegal_char = {' ', '.', ',', '?', "'", '!'}
list_is = [char for char in list_is if char not in illegal_char]
return list_is
def main():
event = input("What do you want to test?\n")
lower = event.lower()
unique_letters = set(lower)
in_order = sorted(unique_letters, key = lower.find)
filtered = del_spcl_char(in_order)
letter_count = {letter : lower.count(letter) for letter in filtered}
counts_list = [count for count in letter_count.values()]
counts_list = single_digits_only(counts_list)
is_100 = False
print(f"\nHere is your result:")
while len(counts_list) != 2:
back = len(counts_list) - 1
temp = []
for front in range(math.ceil(len(counts_list)/2)):
if back == front:
temp.append(counts_list[front])
break
temp.append(counts_list[front] + counts_list[back])
back -= 1
counts_list = single_digits_only(temp)[:]
if len(counts_list) == 3 and (counts_list[0]*100) + (counts_list[1]*10) + counts_list[2] == 100:
is_100 = True
break
if is_100:
result = 100
else:
result = (counts_list[0]*10)+counts_list[1]
print(f"\n\tWe are {result}% positive about the above!")
if __name__ == '__main__':
main()
| true
|
2b2989045ce3fbf972faf3653e8ea9f65ac45e71
|
CadetPD/Kodilla_4_2
|
/zad_4-2_palindrom_.py
| 391
| 4.1875
| 4
|
def palindrome(word):
"""
Palindrome(word) checks if a word is palindrome or not
Parameter: word
Argument: 'word'
Sollution: compare lists for argument ([normal] vs [reversed])
Func result: returns after func execution
"""
if list(word.lower()) == list(reversed(word.lower())):
return True
else:
return False
print(palindrome("Kajak"))
| true
|
2b7329ca49a053e7bb0392d43233c360a8344de3
|
caitinggui/leetcode
|
/zigzag_conversion.py
| 2,099
| 4.28125
| 4
|
#!usr/bin/python
# coding:utf-8
''' The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
("PAYPALISHIRING", 3) ('ab', 2), ('abc', 2), ('abcd', 2)
'''
from collections import defaultdict
class Solution(object):
# @param {string} s
# @param {integer} numrows
# @return {string}
def convert(self, s, numrows):
if numrows == 1:
return s
lines = defaultdict(str)
for i, c in enumerate(s):
rem = i % (numrows + numrows - 2)
if rem < numrows:
lines[rem] += c
else:
lineno = numrows * 2 - 2 - rem
lines[lineno] += c
print str(lines)
ss = "".join([lines[i] for i in range(numrows)])
return ss
class Solution_ok(object):
def convert(self, s, numrows):
"""
:type s: str
:type numrows: int
:rtype: str
"""
# The key is started with zero line
if numrows <= 1:
return s
linelength = 2 * numrows - 2
ss = [[] for i in range(numrows)]
sm = []
for i, x in enumerate(s):
numlocation = i % linelength
if numlocation >= numrows:
numlocation = numrows - 1 - (numlocation - numrows + 1)
ss[numlocation].append(x)
for i in range(numrows):
sm += (ss[i])
return ''.join(sm)
solution = Solution()
assert 'PAHNAPLSIIGYIR' == solution.convert("PAYPALISHIRING", 3)
assert 'ab' == solution.convert("ab", 2)
assert 'acb' == solution.convert("abc", 2)
assert 'acbd' == solution.convert("abcd", 2)
| true
|
566fa1ae85da1c75006ff57a27e582a1290b1047
|
caitinggui/leetcode
|
/189_rotate_array.py
| 1,410
| 4.34375
| 4
|
# coding: utf-8
'''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
'''
class Solution(object):
def rotate1(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
for _ in range(k):
nums.insert(0, nums.pop())
def rotate2(self, nums, k):
if not nums:
return
k = k % len(nums)
if k == 0:
return
nums[:k], nums[k:] = nums[-k:], nums[:-k]
# nums[-k:], nums[k:] = nums[:k], nums[-k:]
def rotate(self, nums, k):
if not nums:
return
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]
s = Solution()
nums = [1, 2, 3, 4, 5, 6, 7]
s.rotate(nums, 3)
print(nums, [5,6,7,1,2,3,4])
print
nums = []
s.rotate(nums, 0)
print(nums, [])
print
nums = [1]
s.rotate(nums, 0)
print(nums, [1])
print
nums = [1, 2]
s.rotate(nums, 5)
print(nums, [2, 1])
print
nums = [1, 2]
s.rotate(nums, 0)
print(nums, [1, 2])
print
| true
|
d8c7134b884879119809e2d4d9073df88fd472fe
|
romperstomper/petshop
|
/arrayflatten.py
| 705
| 4.25
| 4
|
"""Flatten an array of arbitrarily nested arrays.
Array elements will be integers and nested arrays. Result in a flat array.
E.g. [[1,2,[3]],4] -> [1,2,3,4]."""
def flatten(target_list):
"""Flattens a nested list.
Args:
target_list: (int|list|tuple)
Yields:
(int)
Raises:
TypeError: Error if target array contains a type that is not an int or a
nested array.
"""
for elem in target_list:
if isinstance(elem, (list, tuple)):
for nested in flatten(elem):
yield nested
elif isinstance(elem, int):
yield elem
else:
raise TypeError
def nested(mylist):
"""Thin wrapper around flatten."""
return [x for x in flatten(mylist)]
| true
|
f435655c8e051070c5672f122d0d6af36d29f28e
|
Anoopsmohan/Project-Euler-solutions-in-Python
|
/project_euler/pjt_euler_pbm_9.py
| 406
| 4.1875
| 4
|
'''A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc. '''
def pythagorean():
for a in xrange(1, 501):
for b in xrange(a+1, 501):
c = 1000 - a -b
if (a*a + b*b == c*c):
return a*b*c
print pythagorean()
| true
|
acb00c5ece15950069d9a074de30b7b5e8e634d9
|
onyinyealadiume/Count-Primes
|
/main.py
| 523
| 4.15625
| 4
|
# Determine if the input number is prime
def isPrime(n):
for current_number in range(2,n):
# if the input number is evenly divisible by the current number?
if n % current_number == 0:
return False
return True
# Determine how many prime numbers are UNDER the input number
def countPrimes(n):
count_of_primes = 0
for(current_number) in range(2,n):
# check if prime number or not
if isPrime(current_number):
count_of_primes +=1
return count_of_primes
countPrimes(10)
| true
|
6314aca8cc2d6e3df75c95a095d9c2fdd816a55f
|
sxdegithub/myPythonStudy
|
/Study/oob_objvar.py
| 1,257
| 4.15625
| 4
|
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: sx
class Robot:
"""表示一个带有名字的机器人."""
# 一个类变量,用来统计机器人的数量
population = 0
def __init__(self, name):
self.name = name
print('(Initializing {})'.format(self.name))
# 当有人被创建时,机器人数量加1
Robot.population += 1
def die(self):
"""机器人挂了"""
print("{} is being destroyed".format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{} is the last one'.format(self.name))
else:
print("There are still {:d} robots".format(Robot.population))
def say_hi(self):
"""来自机器人的问候
没问题你做得到"""
print('Hello,my name is {}'.format(self.name))
@classmethod
def how_many(cls):
"""打印当前人口数量"""
print('There are {:d} robots'.format(cls.population))
droid1 = Robot('WALL')
droid1.say_hi()
Robot.how_many()
droid2 = Robot('E')
droid2.say_hi()
Robot.how_many()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()
Robot.how_many()
| false
|
fe2db7b0d45f4bb358389c68557d21680f618b31
|
sxdegithub/myPythonStudy
|
/Study/ds_str_methods.py
| 497
| 4.375
| 4
|
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: sx
# 这是一个字符串对象
name = 'Swaroop'
if name.startswith('Swar'):
print('Yes,the string starts with Swar')
if name.startswith(('a', 's')):
print("yes there is a 'S'")
if 'a' in name:
print("Yes ,the string contains character 'a'")
if name.find('war') != -1:
print("Yes,it contains the string 'war'")
delimiter = '_*_'
mylist = ['brazil', 'Russia', 'India', 'China']
print(mylist)
print(delimiter.join(mylist))
| true
|
f1e8831044ec44f2cae9076789715eb5682934f5
|
prossellob/CodeWars
|
/duplicate_encoder.py
| 721
| 4.15625
| 4
|
'''
The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples:
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
'''
def duplicate_encode(word):
a,b,word = [],{},word.lower()
for letter in word:
b[letter] = 0
for letter in word:
b[letter] += 1
for letter in word:
if b[letter] >= 2:
a.append(')')
elif b[letter] < 2:
a.append('(')
return ''.join(a)
| true
|
b36649f74f78e09023d0a9db48c12cbd2a4f769a
|
anoopch/PythonExperiments
|
/print_test.py
| 832
| 4.28125
| 4
|
# Pass it as a tuple:
name = "Anoop CH"
score = 9.0
print("Total score for %s is %s" % (name, score))
# Pass it as a dictionary:
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
# There's also new-style string formatting, which might be a little easier to read:
# Use new-style string formatting:
print("Total score for {} is {}".format(name, score))
# Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):
print("Total score for {0} is {1}".format(name, score))
# Concatenate strings:
print("Total score for " + str(name) + " is " + str(score))
# The clearest two, in my opinion: Just pass the values as parameters:
print("Total score for", name, "is", score)
# Use the new f-string formatting in Python 3.6:
print(f'Total score for {name} is {score}')
| true
|
b74d7bd074117eac432209dd90ec6117e890b53d
|
anoopch/PythonExperiments
|
/Lab_Ex_23_Factorial_Of_Number_while.py
| 509
| 4.4375
| 4
|
# Program to Factorial of a number
number = int(input('Enter an Integer number : '))
if number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif number == 0 or number == 1:
print("The factorial of {0} is {1}".format(number, number))
else:
i = 1
factorial = 1
while i < number + 1:
factorial = factorial * i
i += 1
# for i in range(1, number + 1):
# factorial = factorial * i
print("The factorial of {0}, is {1}".format(number, factorial))
| true
|
5ca09128a7e6200bc5df8a766fa1f86f739c8db4
|
anoopch/PythonExperiments
|
/Lab_Ex_16_celcius_to_farenheit.py
| 223
| 4.40625
| 4
|
# Convert celcius to farenheit
celcius=float(input('Enter the temperature in Celcius : '))
farenheit=(celcius*(9/5)) + 32
print('The temperature equivalent of {} Celcius is {} Farenheit'.format(celcius, farenheit))
| true
|
d1f09f88680f085e6666fefee0f6304430579d42
|
MeghaGajare/Algorithms
|
/String/reverse a string.py
| 247
| 4.3125
| 4
|
#reverse a string
string = input()
a = string[::-1]
print('reverse string: ',a)
# or
b = ''
for i in string:
b=i+b
print(b)
#check palindrome string
if(a == string):
print("It is a palindrome.")
else:
print("It is not palindrome.")
| true
|
bafb73885ef959997ef30080692ab47a8ebc7ecf
|
Chenfc2019/python-data-structure
|
/linkedlist_stack.py
| 1,633
| 4.28125
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : linkedlist_stack.py
# @Author: Small-orange
# @Date : 2020-12-07
# @Desc : 栈结构的链表实现
class Node(object):
"""节点定义"""
def __init__(self, data):
self.data = data
self.next = None
class Stack(object):
"""链表实现栈"""
def __init__(self):
self.head = None
def is_empty(self):
"""判断栈空"""
return self.head is None
def push(self, data):
"""在栈顶添加元素"""
node = Node(data)
# 栈为空时
if self.is_empty():
self.head = node
else:
node.next = self.head
self.head = node
def pop(self):
"""弹出栈顶元素"""
val = None
if self.is_empty():
return val
else:
val = self.head.data
# 将头指针指向头节点的下一个节点
self.head = self.head.next
return val
def peek(self):
"""取栈顶元素,不修改栈内容"""
return self.head.data
def size(self):
"""栈大小"""
cur = self.head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
if __name__ == '__main__':
stack = Stack()
print('栈是否为空:', stack.is_empty())
stack.push(10)
stack.push(20)
stack.push(30)
print('栈大小:', stack.size())
print('peek取栈顶元素:', stack.peek())
print('---出栈---')
print(stack.pop())
print(stack.pop())
print(stack.pop())
| false
|
ac34b15de951625480c670d0ce60bd3586b77931
|
ddh/leetcode
|
/python/perform_string_shifts.py
| 1,958
| 4.1875
| 4
|
"""
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
direction can be 0 (for left shift) or 1 (for right shift).
amount is the amount by which string s is to be shifted.
A left shift by 1 means remove the first character of s and append it to the end.
Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
Return the final string after all operations.
Example 1:
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
Example 2:
Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"
Explanation:
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
Constraints:
1 <= s.length <= 100
s only contains lower case English letters.
1 <= shift.length <= 100
shift[i].length == 2
0 <= shift[i][0] <= 1
0 <= shift[i][1] <= 100
"""
from typing import List
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
right_shifts_count = 0
left_shifts_count = 0
for step in shift:
if step[0] == 0:
left_shifts_count += step[1]
else:
right_shifts_count += step[1]
shift_count = (right_shifts_count - left_shifts_count)
if shift_count == 0:
return s
elif shift_count > 0:
return ''.join([s[i - (shift_count % len(s))] for i, letter in enumerate(s)])
else:
return ''.join([s[(i - shift_count) % len(s)] for i, letter in enumerate(s)])
# Driver
# print(Solution().stringShift("abcdefg", [[1,1],[1,1],[0,2],[1,3]])) # "efgabcd"
print(Solution().stringShift("wpdhhcj", [[0,7],[1,7],[1,0],[1,3],[0,3],[0,6],[1,2]])) # "hcjwpdh"
| true
|
d72c8326f3567ad955f46f848e232247bf1b573a
|
ddh/leetcode
|
/python/shortest_word_distance.py
| 1,834
| 4.125
| 4
|
"""
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
"""
# Idea: Keep track of two indexes, one for encountering the first word, the other for the second word.
# We then iterate through the array just once, updating the index of each word we encounter.
# Whenever we encounter the word, we see if the currently held shortest_distance is better, then store it.
# Time complexity should be O(n) as we iterate through the list of words just the one time. O(1) space, no additional space created.
from typing import List
class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
# Keep track of the indexes where we find word1, word2
word1_index = -1
word2_index = -1
shortest_distance = len(words) - 1 # The max distance if words were at both ends of the list
for i, word in enumerate(words):
if word == word1:
word1_index = i
if word2_index >= 0:
shortest_distance = min(abs(word1_index - word2_index), shortest_distance)
if word == word2:
word2_index = i
if word1_index >= 0:
shortest_distance = min(abs(word1_index - word2_index), shortest_distance)
return shortest_distance
# Driver:
print(Solution().shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice")) # 3
print(Solution().shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "makes", "coding")) # 1
| true
|
7c43bb2aa58e7787c6b36e405cad2d56e2a44f79
|
xexugarcia95/LearningPython
|
/CodigoFran/ListasTuplas/Ejercicio8.py
| 384
| 4.28125
| 4
|
"""Escribir un programa que pida al usuario una
palabra y muestre por pantalla si es un palíndromo."""
palabra = input("Introduzca una palabra: ")
letras = []
for i in range(len(palabra)):
letras.append(palabra[i])
inversion = letras[::-1]
if inversion == letras:
print(f"{palabra} ES una palabra palindroma")
else:
print(f"{palabra} NO ES una palabra palindroma")
| false
|
4a84ecbe814a8c31be787739dcca41c5e1ee5ab8
|
xexugarcia95/LearningPython
|
/CodigoJesus/SintaxisBasica/Ejercicio5.py
| 463
| 4.5
| 4
|
"""Escribir un programa que pregunte el nombre del usuario en la consola y
después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene
<n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y <n>
es el número de letras que tienen el nombre."""
mi_nombre = input("Introduce tu nombre: ")
# La funcion upper te comvierte el str en mayusculas
print("El nombre " + mi_nombre.upper() + " tiene " + str(len(mi_nombre))
+ " letras")
| false
|
b3b1d5f2aca03f3c70376bf7a4d712ff5989a1a4
|
xexugarcia95/LearningPython
|
/CodigoJesus/Bucles/Ejercicio4.py
| 316
| 4.125
| 4
|
"""Escribir un programa que pida al usuario un número entero positivo y
muestre por pantalla la cuenta atrás desde ese número hasta cero separados
por comas."""
num = int(input("Introduce un numero entero positivo: "))
for i in range(num, -1, -1):
print(i, end="")
if i != 0:
print(",", end="")
| false
|
bceef65db35644a54d700d1e63218801157572e4
|
xexugarcia95/LearningPython
|
/CodigoJesus/Bucles/Ejercicio6.py
| 268
| 4.375
| 4
|
"""Escribir un programa que pida al usuario un número entero y muestre por
pantalla un triángulo rectángulo como el de más abajo, de altura el número
introducido."""
num = int(input("Introduce un numero entero: "))
for i in range(1, num+1, 1):
print("*"*i)
| false
|
222154c4bd26e4470820e0d722d0be03538900bd
|
xexugarcia95/LearningPython
|
/CodigoJesus/Listas/Ejercicio7.py
| 502
| 4.28125
| 4
|
"""Escribir un programa que almacene el abecedario en una lista, elimine de la
lista las letras que ocupen posiciones múltiplos de 3, y muestre por pantalla
la lista resultante."""
lista = []
lista2 = []
# chr() te convierte el numero en caracter de la tabla ascii correspondiente
for i in range(97, 123, 1):
lista.append(chr(i))
for i in range(len(lista)):
if (i+1) % 3 != 0:
lista2.append(lista[i])
print("Lista antes: ")
print(lista[:])
print("Lista después: ")
print(lista2[:])
| false
|
aa3b7b494722c78588acd89948b556ca329733c7
|
xexugarcia95/LearningPython
|
/CodigoJesus/Listas/Ejercicio3.py
| 715
| 4.3125
| 4
|
"""Escribir un programa que almacene las asignaturas de un curso (por ejemplo
Matemáticas, Física, Química, Historia y Lengua) en una lista, pregunte al
usuario la nota que ha sacado en cada asignatura, y después las muestre por
pantalla con el mensaje En <asignatura> has sacado <nota> donde <asignatura>
es cada una des las asignaturas de la lista y <nota> cada una de las
correspondientes notas introducidas por el usuario."""
lista = ["Matematicas", "Fisica", "Quimica", "Historia", "Lengua"]
lista2 = []
for i in range(len(lista)):
lista2.append(int(input("Qué nota has sacado en " + lista[i] + "?: ")))
for i in range(len(lista)):
print("En " + lista[i] + " he sacado un " + str(lista2[i]))
| false
|
a0157e9d059f448f30af6ddb873b9eef438ec171
|
CalebKnight10/CS_260_4
|
/factorial_recursive.py
| 276
| 4.34375
| 4
|
# A factorial is multiplying our num by the numbers before it
# Ex, 5 would be 5x4x3x2x1
def factorial(num):
if num <= 1:
return num
else:
return factorial(num - 1) * num
def main():
print(factorial(9))
if __name__ == '__main__':
main()
| true
|
010fb27996b2a30bffb70755ba9c86266215f4b2
|
Tradd-Schmidt/CSC236-Data-Structures
|
/T/T12/count_evens.py
| 2,009
| 4.34375
| 4
|
# -------------------------------------------------------------------------------
# Name: count_evens.py
# Purpose: This program is designed to use recursion to count the number of
# even numbers are read from a file. This sequence is stored in a
# linked list.
#
# Created: 08/10/2014
# -------------------------------------------------------------------------------
from ListNode import ListNode
from LList import LList
# recursive function to count the number of even numbers in this linked list.
def count_evens(currentNode, maximum):
"""
Keeps track of the largest item of the linked list and returns it
:param currentNode: Current node being checked
:param maximum: The maximum value so far
:return: the maximum value
"""
if currentNode == None:
return maximum
else:
if currentNode.item > maximum:
maximum = currentNode.item
return count_evens( currentNode.link, maximum)
else:
return count_evens(currentNode.link, maximum)
def read_numbers_return_list( ):
'''preconditions: none
postconditions: the numbers in the file with the name asked by the user will
be placed into a linked list and returned.'''
filename = input("What is the name of the file?")
file = open(filename, "r")
# get the list of strings from the file. This list will need to be converted to
# a list of numbers in a
stringList = file.read().split()
file.close()
# time to create an integer version of the numbers list
numberList = []
for item in stringList :
numberList.append(int(item))
# Now create a linked list version of this number sequence
created_list = LList(numberList)
return created_list
def main():
numbersList = read_numbers_return_list()
print( count_evens( numbersList.head, numbersList.head.item) )
if __name__ == '__main__':
main()
| true
|
e8e7d5b2eac6d3937b518a55d0219d2951b2a784
|
Tradd-Schmidt/CSC236-Data-Structures
|
/A/A08/LinkedLIst_smdriver.py
| 2,037
| 4.125
| 4
|
# -------------------------------------------------------------------------------
# Name: LinkedList_smdriver.py
# Purpose: Rudimentary driver for the LinkedList class.
#
# Edited by: Tradd Schmidt on 9/21/17
# -------------------------------------------------------------------------------
from LList import LList
def main():
print("Make a linked list in honor of Donna Schmidt")
mom = LList((8, 21, 1962)) # Named after Donna Schmidt, my mom because she is the strongest willed person I know
print("Make a linked list in honor of Jim Carrey")
truman = LList((6, 17, 1962)) # Named after Jim Carrey because he is always his true with himself and others about who he is
print("Make a linked list for a fictional character")
fictional = LList(((8 + 6) // 2, (21 + 17) // 2, 1962)) # Fictional persons birthday
# Printing the Birthdays
# ---------------------------------------------------------------------------------------
print("\n")
print("Printing Donna's birthday")
for item in mom:
print(str(item) + " ",)
print("\n")
print("Printing Jim Carrey's birthday")
for item in truman:
print(str(item) + " ",)
print("\n")
print("Printing the fictional character's birthday")
for item in fictional:
print(str(item) + " ",)
# Changing the year of the fictional character
# ---------------------------------------------------------------------------------------
year = fictional._find(len(fictional) - 1)
year.item += 100
print("\n")
print("Printing the fictional character's revised birthday")
for item in fictional:
print(str(item) + " ", )
# Deleting the date of the fictional character's birthday
# ----------------------------------------------------------------------------------------
fictional.__delitem__(1)
print("\n")
print("Printing the fictional character's revised birthday")
for item in fictional:
print(str(item) + " ", )
main()
| true
|
92fb30404522bc211979ebf91b8c33d55c91be96
|
gayatri-p/python-stuff
|
/challenge/games/guess.py
| 541
| 4.21875
| 4
|
import random
start = 0
end = 100
n = random.randint(start, end)
tries = 1
print('-----Guessing Game-----')
print(f'The computer has guessed an integer between {start} and {end}.')
guess = int(input('Guess the number: '))
while guess != n:
tries += 1
if n > guess:
print('The number is larger than you think.')
elif n < guess:
print('The number is smaller than you think.')
guess = int(input('Guess again: '))
print(f'Yes the number is {n}.')
print(f'You have guessed it correctly in {tries} tries.')
| true
|
8fcc321aa45145737d6343a0387637a586a20d01
|
ramiro-arias/HeadPython
|
/HeadPython/Chapter02/p56.py
| 732
| 4.15625
| 4
|
# Source: Chapter01/The Basics/p56.py
# Book: Head First Python (2nd Edition) - Paul Barry
# Name in the book: Working with lists
# Eclipse project: HeadFirstPython
'''
Created on May 2, 2019
@author: ramiro
'''
# We will use the shell to first define a list called vowels, then check to see if
# each letter in a word is in the vowels list. Let us define a list of vowels:
vowels = ['a', 'e', 'i', 'o', 'u']
# With vowels defined, we now need a word to check, so let’s create a
# variable called word and set it to "Milliways":
word = 'Milliways'
print ('Vowels contained in', word)
# We can check if one object is contained within a collection with operator 'in'
for letter in word:
if letter in vowels:
print (letter)
| true
|
6e3542bf51343ab56329a32dfc76cbe504f55bf0
|
dhking1/PHY494
|
/03_python/heavisidefunc.py
| 414
| 4.1875
| 4
|
# Heaviside step function
def heaviside(x):
"""Heaviside step function
Arguments
---------
x = float
input value
Returns
---------
Theta : float
value of heaviside
"""
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
theta = 1.
return theta
x = 3
theta = heaviside(x)
print("heaviside", str(x), "|:", str(theta))
| true
|
e1a778777bd164df6a46519e74ee6f35d84fc22b
|
missingcharacter/janky-stuff
|
/python/rename_trim_multiple_spaces.py
| 515
| 4.21875
| 4
|
#!/usr/bin/env python3
# Python3 code to rename multiple
# files in a directory or folder
# importing os module
import os
import re
# Function to rename multiple files
def main():
for filename in os.listdir("./"):
src = filename
dst = re.sub(' +', ' ', filename)
# rename() function will
# rename all the files
print(f"filename before {src} after {dst}")
os.rename(src, dst)
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
| true
|
b16e84881f252e7bb69cae559e249d524284c599
|
FabianCaceresH/ejercicios_profundizaci-n_sesion_2
|
/profundización/ejercicio_profundización_2.py
| 1,461
| 4.15625
| 4
|
# Tipos de variables [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta.
# Requiere mayor tiempo de dedicación e investigación autodidacta.
# IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA
# Ejercicios de práctica numérica y cadenas
a = str(input("digite su nombre completo:"))
b = int(input("digite su DNI"))
C = int(input("digite su edad:"))
d = int(input("digite su altura"))
print(f"su nombre completo es {a},su DNI es {b}")
print(f"su edad es {C},su altura es {d}")
'''
Enunciado:
Realice un programa que consulte por consola:
- El nombre completo de la persona
- El DNI de la persona
- La edad de la persona
- La altura de la persona
Finalmente el programa debe imprimir dos líneas de texto por separado
- En una línea imprimir el nombre completo y el DNI, aclarando de que
campo se trata cada uno
Ej: Nombre Completo: Nombre Apellido , DNI:35205070,
- En la segunda línea se debe imprimir el nombre completo, edad y
altura de la persona
Nuevamente debe aclarar el campo de cada uno, para el que lo lea
entienda de que se está hablando.
'''
print('Sistema de ingreso de datos')
# Empezar aquí la resolución del ejercicio
| false
|
9908b618ce802c2f87b408d13a66a92cf43cb8db
|
marinavicenteartiaga/KeepCodingModernProgrammingWithPython
|
/module0/e0.py
| 708
| 4.125
| 4
|
name = input("What's your name?\n")
print("Hello " + name + "!")
strAge = input("How old are you?\n")
strYear = input("What year is it?\n")
strBirthdayYet = input("Has it already been your birthday? (YES/NO)\n")
age = int(strAge)
year = int(strYear)
while strBirthdayYet != "YES" or strBirthdayYet != "NO":
strBirthdayYet = input("Error. Has it already been your birthday? (YES/NO)\n")
if strBirthdayYet == "YES":
birthYear = year - age
break
elif strBirthdayYet == "NO":
birthYear = year - age - 1
break
if strBirthdayYet == "YES":
birthYear = year - age
elif strBirthdayYet == "NO":
birthYear = year - age - 1
print("You were born in ", birthYear)
| false
|
1fc26b0beb9013585a58985916541dcc1b95f3e1
|
Tanges/assignment5_1-python
|
/sequence.py
| 746
| 4.25
| 4
|
n = int(input("Enter the length of the sequence: ")) # Do not change this line
#The sequence for the algorythm is 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, …
#Idea: i + 2 power of i
#Algorithm adds up last 3 inputs and returns the sum of it
#Make a list with first 3 inputs which are already determined
#Print out the first 3 on the screen and then use a storage variable to keep the first 3 inputs
listi = [1,2,3]
for i in range(0, n):
if i < 3: #Check through the list and print out first 3 numbers
print(listi[i])
else: #Print out the rest until lenght of the sequence is finished
storage = sum(listi)
listi = listi[1:] + [storage] #Adds last number in list and adds it to storage variable
print(storage)
| true
|
a37ffbff5331c3c7e1741073bec9c177ec4ac244
|
Sean-Stretch/CP1404_Pracs
|
/Prac_01/shop_calculator.py
| 876
| 4.34375
| 4
|
"""
The program allows the user to enter the number of items and the price of each different item.
Then the program computes and displays the total price of those items.
If the total price is over $100, then a 10% discount is applied to that total before the amount is displayed on the screen.
"""
total_cost = 0
valid_input = False
while valid_input is False:
number_of_items = int(input("Enter number of items: "))
if number_of_items > 0:
valid_input = True
else:
print("Please enter a valid number")
for i in range(1, number_of_items + 1):
cost = float(input("Please enter price of item: $"))
total_cost += cost
if total_cost > 100:
print("Total Price for {0:} items is ${1:.2f}".format(number_of_items, total_cost - (total_cost * 0.1)))
else:
print("Total Price for {0:} items is {1:.2f}".format(number_of_items, total_cost))
| true
|
e1acc07b442cc2063ba350d51f7e865cca49f6d3
|
brunopesmac/Python
|
/Python/curso/ex33.py
| 984
| 4.21875
| 4
|
numero1 = float(input ("Digite o 1 numero: "))
numero2 = float(input ("Digite o 2 numero: "))
numero3 = float(input ("Digite o 3 numero: "))
if numero1 > numero2 and numero1 > numero3:
if numero2>numero3:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero1,numero3))
if numero3>numero2:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero1,numero2))
if numero2 > numero1 and numero2 > numero3:
if numero1 > numero3:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero2,numero3))
if numero3 > numero1:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero2,numero1))
if numero3 > numero1 and numero3 > numero2:
if numero1 > numero2:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero3,numero2))
if numero2 > numero1:
print("O maior numero é o {:.2f} e o menor é o {:.2f}".format(numero3,numero1))
| false
|
327197a5ee25edcae773ad77af22eca04e35495b
|
nikhilbagde/Grokking-The-Coding-Interview
|
/topological-sort/examples/tasks-scheduling/python/MainApp/app/mainApp.py
| 2,454
| 4.125
| 4
|
from collections import defaultdict
class MainApp:
def __init__(self):
pass
'''
There are ‘N’ tasks, labeled from ‘0’ to ‘N-1’.
Each task can have some prerequisite tasks which need to be completed before it can be scheduled.
Given the number of tasks and a list of prerequisite pairs, find out if it is possible to schedule all the tasks.
Example 1:
Input: Tasks=3, Prerequisites=[0, 1], [1, 2]
Output: true
Explanation: To execute task '1', task '0' needs to finish first. Similarly, task '1' needs to finish
before '2' can be scheduled. A possible scheduling of tasks is: [0, 1, 2]
Example 2:
Input: Tasks=3, Prerequisites=[0, 1], [1, 2], [2, 0]
Output: false
Explanation: The tasks have cyclic dependency, therefore they cannot be scheduled.
Example 3:
Input: Tasks=6, Prerequisites=[2, 5], [0, 5], [0, 4], [1, 4], [3, 2], [1, 3]
Output: true
Explanation: A possible scheduling of tasks is: [0 1 4 3 2 5]
'''
@staticmethod
def run(req, tasks):
# turn req into req_graph
req_graph = defaultdict(list)
for (target, dependency) in req:
req_graph[target].append(dependency)
if dependency not in req_graph:
req_graph[dependency] = []
print(MainApp().run(req=[
(0, 1),
(1, 2),
(2, 0)
], tasks=3))
print("\n====================")
print(MainApp().run(req=[
(0, 1),
(1, 2)
], tasks=3))
print("\n====================")
print(MainApp().run(req=[
(2, 5),
(0, 5),
(0, 4),
(1, 4),
(3, 2),
(1, 3)
], tasks=3))
# def detect_cycle(req):
# # turn req into req_graph
# req_graph = defaultdict(list)
# for (target, dependency) in req:
# req_graph[target].append(dependency)
# if dependency not in req_graph:
# req_graph[dependency] = []
#
# def dfs(graph, start, visited=set()):
# if start not in visited:
# visited.add(start)
# for neighbour in graph[start]:
# if neighbour in visited:
# return False
# return dfs(graph, neighbour, visited)
# return True
#
# for node in req_graph:
# print(dfs(req_graph, node, set()))
# break
#
#
# req = [
# (0, 1),
# (1, 2)
# ]
# detect_cycle(req)
#
#
# req = [
# (0, 1),
# (1, 2),
# (2, 0)
# ]
# detect_cycle(req)
| true
|
ca140ef57f7b1a6616faf90660071bf1e276fa9a
|
nikhilbagde/Grokking-The-Coding-Interview
|
/sliding-window/examples/no_repeat_substring/python/MainApp/app/mainApp.py
| 1,272
| 4.15625
| 4
|
import sys
class MainApp:
def __init__(self):
pass
'''
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
'''
def run(self, s: str) -> int:
window_start = 0
longest_substring_length = float('-inf')
unique_character_set = set()
for window_end in range(len(s)):
if s[window_end] in unique_character_set:
unique_character_set.discard(s[window_start])
window_start += 1
else:
unique_character_set.add(s[window_end])
window_end += 1
longest_substring_length = max(
longest_substring_length, len(unique_character_set))
return (longest_substring_length, 0)[len(s) == 0]
| true
|
aac73ba75af9ca633c06abf6d78725b838e55bfc
|
nikhilbagde/Grokking-The-Coding-Interview
|
/two-pointers/examples/subarrays-with-products-less-than-k/python/MainApp/app/mainApp.py
| 1,235
| 4.125
| 4
|
class MainApp:
def __init__(self):
pass
'''
Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays
where the product of all the elements in the subarray is less than k.
Example 1:
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
```
TPFA
10 5 2 6
^ ^
product = 60 == 100
subarray_count = [10] [5] [10 5] [2] [5 2] [6] [5 2 6] [2 6]
window_start = 0
window_end = 3
```
'''
def run(self, nums, target) -> int:
window_start = 0
if target <= 1:
return 0
subarray_count = 0
product = 1
for window_end in range(len(nums)):
product *= nums[window_end]
while product >= target:
product /= nums[window_start]
window_start += 1
subarray_count += window_end - window_start + 1
return subarray_count
print(MainApp().run([10, 5, 2, 6], 100))
| true
|
c957a225ec65cf3aad4a51a334f7d241f51c866d
|
nikhilbagde/Grokking-The-Coding-Interview
|
/tree-bfs/examples/reverse-level-order-traversal/python/MainApp/app/mainApp.py
| 1,853
| 4.1875
| 4
|
from queue import Queue
class FifoDataStructure:
def __init__(self):
self.stack = list()
def push(self, e):
self.stack.insert(0, e)
def get(self):
if len(self.stack) == 0:
return None
self.stack.pop(0)
def get_stack(self):
return self.stack
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class MainApp:
def __init__(self):
pass
'''
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values.
(i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
'''
@staticmethod
def run(root):
if not root:
return []
else:
q = Queue()
q.put((root, 0))
current_level = 0
nodes_in_corresponding_levels = FifoDataStructure()
nodes_in_current_level = list()
while not q.empty():
(node, level) = q.get()
if current_level == level:
nodes_in_current_level.append(node.val)
else:
nodes_in_corresponding_levels.push(nodes_in_current_level)
nodes_in_current_level = [node.val]
current_level += 1
if node.left:
q.put((node.left, level + 1))
if node.right:
q.put((node.right, level + 1))
nodes_in_corresponding_levels.push(nodes_in_current_level)
return nodes_in_corresponding_levels.get_stack()
| true
|
957472acc148e3088ae2dc0a453c783065ff0dd4
|
nikhilbagde/Grokking-The-Coding-Interview
|
/fast-and-slow-pointers/examples/middle-of-linked-list/python/MainApp/app/mainApp.py
| 1,085
| 4.125
| 4
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MainApp:
def __init__(self):
pass
'''
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.nxt.val = 4, ans.nxt.nxt.val = 5, and ans.nxt.nxt.nxt = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
'''
@staticmethod
def run(head):
slow = fast = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
return slow.val
| true
|
82e2a58a20f4e9896cc97e34af2074e55baf6ccb
|
imtiazraqib/Tutor-CompSci-UAlberta
|
/CMPUT-174-Fa19/guess-the-word/Guess_The_Word_V1.py
| 1,410
| 4.28125
| 4
|
#WordPuzzle V1
#This version plans to implement the ability for the program to select a word from a limited word list
#The program will then remove the first letter and replace it with an _ and the player can make a guess
#if correct, the program congratulates. if not then condolensces are sent
#Functions such as multiple guesses and multiple _ in place of letters will be absent
import random
def main():
#This prints the instructions to the game
instructions_file = open("instructions Wordpuzzle.txt", "r")
file_contents = instructions_file.read()
instructions_file.close()
print(file_contents)
#the word list and the method used to delete the first letter
wordbank = ['Mango', 'Banana', 'Watermelon', 'Kiwi']
random_word = random.choice(wordbank)
rest_of_random = random_word[1:]
guess = '_' + rest_of_random
#prompts user for a guess
print("The answer so far is " )
print(guess)
player_input = input("Guess the letter: ")
#method used to remove all but the first letter in order to match player input
first_of_random = random_word[:1]
if player_input.lower() == first_of_random.lower():
print('Good job! You found the word ' + random_word + '!')
else:
print('Not quite, the correct word was ' + random_word + '. Better luck next time')
input('Press enter to end the game.')
main()
| true
|
15a6ed0d48f867c9163defbe6f25428091c0e2cd
|
Nandi22/hardway3
|
/ex18.py
| 697
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 18:45:33 2019
@author: ferna
"""
# this one is like your scripts with argv
def print_two(*args):# defines what function does
arg1, arg2 = args # asks for arguments
print (f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):# args inside ()
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
| true
|
e28857ed5e13136e51a95d8991451371504aa2ae
|
zengyongsun/python_study
|
/变量与数据类型/name_case.py
| 625
| 4.5
| 4
|
# 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。
# 显示的消息应非常简单,如“Hello Eric, would you like to learn some Python today?”。
name = 'eric'
print('Hello ' + name.title() + ',' + 'would you like to learn some Python today ?')
#调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。
name = 'he zheng xiang'
print(name.lower())
print(name.upper())
print(name.title())
# 空白字符
name = '\t zeng yong sun \n '
print(name.lstrip())
print(name.rstrip())
print(name.strip())
| false
|
80ab3308aae777be47cadae6a97ca30c2a192e42
|
airaider/python_algo_study
|
/16장_트라이/트라이 구현.py
| 1,047
| 4.15625
| 4
|
class TrieNode:
def __init__(self):
self.word = False
self.children = {}
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word:str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.word = True
def search(self, word:str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.word
def startsWith(self, word:str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return True
if __name__ == '__main__':
t =Trie()
t.insert('apple')
t.insert('appear')
t.insert('appeal')
print(t)
print(t.search('apple'))
print(t.startsWith('ap'))
| false
|
dac7d2d70f4736f453f5b446453120568896df33
|
jitendrabhamare/Problems-vs-Algorithms
|
/Sort_012.py
| 1,364
| 4.25
| 4
|
# Dutch National Flag Problem
# Author: Jitendra Bhamare
def sort_012(list_012):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args: list_012(list): List to be sorted
"""
next_pos_0 = 0
next_pos_2 = len(list_012) - 1
front_index = 0
while front_index <= next_pos_2:
if list_012[front_index] == 0:
list_012[front_index] = list_012[next_pos_0]
list_012[next_pos_0] = 0
next_pos_0 += 1
front_index += 1
elif list_012[front_index] == 2:
list_012[front_index] = list_012[next_pos_2]
list_012[next_pos_2] = 2
next_pos_2 -= 1
else:
front_index += 1
return list_012
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
## Edge cases
test_function([]) # Empty Array
test_function([0]) # Array with one element
test_function([2, 0]) # Array with 2 elements
test_function([2, 1, 0]) # Array with 3 elements
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
| true
|
10e5e22683d76cd7f02845a05047643950bfa2d2
|
Vivekagent47/data_structure
|
/Python/doubly_linked_list.py
| 2,923
| 4.3125
| 4
|
'''
In this program wi impliment the Doubly LinkedList
here we can do 4 differnt operations:
1- Insert Node at Beginning
2- Insert Node at End
3- Delete the node you want
4- Print List
'''
class Node:
def __init__(self, data, next = None, previous = None):
self.data = data
self.next = next
self.previous = previous
class LinkedList:
def __init__(self):
self.head = None
def insertNodeBeg(self, data):
if self.head == None:
newNode = Node(data)
self.head = newNode
else:
newNode = Node(data)
self.head.previous = newNode
newNode.next = self.head
self.head = newNode
def insertNodeEnd(self, data):
newNode = Node(data)
temp = self.head
while(temp.next != None):
temp = temp.next
temp.next = newNode
newNode.previous = temp
def deleteNode(self, data):
temp = self.head
if(temp.next != None):
if(temp.data == data):
temp.next.previous = None
self.head = temp.next
temp.next = None
return
else:
while(temp.next != None):
if(temp.data == data):
break
temp = temp.next
if(temp.next):
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
else:
temp.previous.next = None
temp.previous = None
return
if (temp == None):
return
def printList(self):
temp = self.head
if self.head == None:
print("Empty List")
else:
print("List : ", end=" ")
while temp is not None:
print(temp.data, end=" ")
if temp.next:
print("-> ", end="")
temp = temp.next
print()
if __name__ == "__main__":
lst = LinkedList()
while True:
print("Select the any option")
print("[1] Insert Node at Beginning of List")
print("[2] Insert Node at End of List")
print("[3] Delete Node")
print("[4] Print List")
print("[5] Exit")
print("\n")
i = int(input())
print("\n")
if i == 1:
lst.insertNodeBeg(input("Enter data you want to insert: "))
elif i == 2:
lst.insertNodeEnd(input("Enter data you want to insert: "))
elif i ==3:
lst.deleteNode(input("Enter data you want to delete: "))
elif i == 4:
lst.printList()
elif i == 5:
break
print("\n")
| true
|
41da7c31e33c98cb1a8aeb8443920252c16d8312
|
Jaynath1992/Python_Automation
|
/Python_Classes/Python_Day5_To_9/Python_Day5_To_9/Python day_9/myCar.py
| 1,912
| 4.3125
| 4
|
class Car(object):
no_of_tyres = 6
def __init__(self, no_of_tyres =5):
self.no_of_tyres = no_of_tyres
def __del__(self): # destructor : destroying objects
print 'Destroying an object of the class'
def move_car(self, direction):
print 'car is moving towards {} direction'.format(direction)
def set_no_of_tyres(self, count):
self.no_of_tyres = count
def get_no_of_tyres(self):
return self.no_of_tyres
def moveSteering(self,direction):
self.direction = direction
print 'car is moving towards {} direction'.format(direction)
if __name__ == '__main__':
ciaz = Car(no_of_tyres=5)
wagonR = Car(4)
print ciaz.no_of_tyres
print wagonR.no_of_tyres
#ciaz = Car() # ciaz is a object od Car class
#ciaz2 = Car() # again ciaz2 is a object of Car class
'''
ciaz.no_of_tyres = 10 # set attribute no_of_tyres = 10, this change would be only in ciaz object not ciaz2
print ciaz.no_of_tyres
Car.no_of_tyres = 5 # static attribute , using classname.attribute_name, here changes would be reflected to all objects
print ciaz2.no_of_tyres
print Car.function1()
'''
#ciaz = Car()
#ciaz.moveSteering(direction='right')
# Here ciaz will be passed to self parameter in the function, and 2nd parameter would be direction
# attributes ar bydefault static but methods are non static , they are dynamic , u cant access function/methods
# with help of Class.methodname() - not possibel will throw error
# However you can access attributes with help of class.attribute_name,and object.attribute_name, because by default attributes are staic
#wagonR = Car()
#wagonR.moveSteering('left')
# self is a parameter in a function inside class whose value will be object calling that function
#ciaz.set_no_of_tyres(5)
#wagonR.set_no_of_tyres(4)
#print ciaz.get_no_of_tyres()
#print wagonR.get_no_of_tyres()
| false
|
0636c88fef8fc6340db92c5c000ef166ab482543
|
Jaynath1992/Python_Automation
|
/Python_Classes/Python_Day5_To_9/Python_Day5_To_9/Python_Assignment_Exercise _1/14_Leap_Year.py
| 577
| 4.21875
| 4
|
# 14) WAP to find out the leap year.
# (Except a year from the user using raw_input)
# A leap year is exactly divisible by 4 except for century years
# (years ending with 00). The century year is a leap year only if
# it is perfectly divisible by 400. For example
def Check_LeapYear(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print 'Year is leap year : ' + str(year)
else:
print 'Year is not leap year : ' + str(year)
# Call to above function
year = int(raw_input('Enter year to be checked: '))
Check_LeapYear(year)
| false
|
6da9eac046121212d554fa6500eb2da6cd2be4b0
|
Rhornberger/Python
|
/python_folder/roll_dice.py
| 1,235
| 4.125
| 4
|
'''
Rolling dice with gui interface using tkinter
written by Rhornberger
last updated nov 12 2019
'''
# import library
from tkinter import *
# create the window size and welcome text
window = Tk()
window.title('Welcome to the D20 roller!')
lbl = Label(window, text = 'Welcome!', font =('arial', 20))
lbl.grid(column = 0, row = 0)
window.geometry('300x200')
# creat a function for the button to do something
def clicked():
lbl.configure(text = 'Button was clicked!!')
btn = Button(window, text = 'Click to Roll', command = clicked, bg = 'black', fg = 'red')
btn.grid(column = 1, row = 0)
# create check buttons for type of die to use
rad1 = Radiobutton(window, text = 'D20', value = 1)
rad2 = Radiobutton(window, text = 'D12', value = 2)
rad3 = Radiobutton(window, text = 'D10', value = 3)
rad4 = Radiobutton(window, text = 'D8', value = 4)
rad5 = Radiobutton(window, text = 'D6', value = 5)
rad6 = Radiobutton(window, text = 'D4', value = 6)
rad7 = Radiobutton(window, text = 'D%', value = 7)
rad1.grid(column = 0, row = 1)
rad2.grid(column = 1, row = 1)
rad3.grid(column = 2, row = 1)
rad4.grid(column = 3, row = 1)
rad5.grid(column = 4, row = 1)
rad6.grid(column = 5, row = 1)
rad7.grid(column = 6, row = 1)
window.mainloop()
| true
|
02e0f413935a045783423ee27aa57c71acb3551c
|
JaredBigelow/Python-Projects
|
/Nesting, Div, and Mod/Star.py
| 2,516
| 4.1875
| 4
|
#Author: Jared Bigelow
#Date: February 27 2015
#Purpose: To create star patterns based on inputted type and size
#Input: Type, size
#Output: Star Pattern
#Star Patterns
################################################################################
import math
repeat = "Y"
while repeat == "Y" or repeat == "y":
print("Choose your type:(1:Square 2:Triangle 3:Hollow Square 4:Hollow Triangle)")
patternType = int (input ("Type:"))
while patternType < 1 or patternType > 4:
patternType = int (input ("Error, enter a number between 1 and 4:"))
print("Choose your size. (1-30)")
patternSize = int (input ("Size:"))
while patternSize < 1 or patternSize > 30:
patternSize = int (input ("Error, enter a size between 1 and 30:"))
if patternType == 1:
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
for star in range (1, patternSize):
print ("*","", end="")
print ()
elif patternType == 2:
number = 0
print ()
for star in range (1, patternSize + 1):
number = number + 1
for star in range (1, number + 1):
print ("*","", end="")
print ()
elif patternType == 3:
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
for star in range (1, patternSize - 1):
print ("*","", end="")
for star in range (2, patternSize):
print (" ", end="")
print ("*","", end="")
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
elif patternType ==4:
numberOne = 0
numberTwo = 0
print ()
for star in range (1, 3):
numberOne = numberOne + 1
for star in range (1, numberOne + 1):
print ("*","", end="")
print ()
for star in range (1, patternSize - 2):
print ("*","", end="")
for star in range (2, patternSize - (patternSize - 3)):
numberTwo = numberTwo + 1
for star in range (1, numberTwo + 1):
print (" ", end="")
print ("*","", end="")
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
print ()
repeat = input ("Do another? (Y/N):")
| true
|
ff9baf913c50c07d3b7805702505cbf78d01bde7
|
chelseavalentine/Courses
|
/Intro-Programming/[10]AnotherSortOfSort.py
| 647
| 4.1875
| 4
|
"""
Assignment Name: Another Sort of Sort
Student Name: Chelsea Valentine (cv851)
"""
import random
#ask for input & keep the user in a loop until they type 'done'
while True:
n = int(input("Enter an integer to create a random list, or type 'done' to finish: "))
#check whether user entered 'done' & define the random list
if n == 'done':
break
randomlist=[]
#show create a list of random values
for i in range(0,n):
randomlist.append(random.randint(1,3*n))
i += 1
print("The list with", n, "random values is:", randomlist)
print("When we sort that list, we get:", sorted(randomlist))
print()
| true
|
4602412de2c9a2a876149e9ed2fb249a789b3413
|
ShazamZX/Data-Structure-and-Algorithm
|
/Array Questions/PalinMerge.py
| 1,084
| 4.3125
| 4
|
"""
Given an array of positive integers. We need to make the given array a ‘Palindrome’. The only allowed operation is”merging” (of two adjacent elements). Merging two adjacent elements means replacing them with their sum. The task is to find the minimum number of merge operations required to make the given array a ‘Palindrome’.
To make any array a palindrome, we can simply apply merge operation n-1 times where n is the size of the array (because a single-element array is always palindromic, similar to single-character string). In that case, the size of array will be reduced to 1. But in this problem, we are asked to do it in the minimum number of operations.
"""
def minMerge(arr):
ans = 0
n = len(arr)
l = 0
r = n-1
while(l<=r):
if arr[l] == arr[r]:
l+=1
r-=1
elif arr[l]<arr[r]:
l+=1
arr[l]+=arr[l-1]
ans+=1
else:
r-=1
arr[r]+=arr[r+1]
ans+=1
return ans
#driver code
arr = [1, 4, 5, 9, 1]
print(minMerge(arr))
| true
|
8cc89bb11638aa49abdcfd1c52b5e8b983bd0131
|
ShazamZX/Data-Structure-and-Algorithm
|
/Array Questions/ZeroSumSubA.py
| 609
| 4.125
| 4
|
#check if an array has a any subarray whose sum is zero (Prefix sum method)
#the idea is that we calculate prefix sum at every index, if two prefix sum are same then the subarray between those two index have sum as zero
def subSum(arr):
prefix_sum = set()
prefix_sum_till_i = 0
for i in range(len(arr)):
prefix_sum_till_i+=arr[i]
if prefix_sum_till_i == 0 or prefix_sum_till_i in prefix_sum:
return True
prefix_sum.add(prefix_sum_till_i)
return False
#driver code
arr = [-3, 2, 3, 1, 6]
print(subSum(arr))
arr1 = [4, 2, -3, 1, 6]
print(subSum(arr1))
| true
|
9cfd7b4f89b93e5af2765e5c60e3eb0fb58db748
|
Mehedi-Bin-Hafiz/Python-OOP
|
/classes/creating_a_class.py
| 2,156
| 4.8125
| 5
|
# Making an object from a class is called instantiation, and you work with
# instances of a class.
#### when we write function in a class then it called method
# ((Methods are associated with the objects of the class they belong to.
# Functions are not associated with any object. We can invoke a function just by its name.
# Functions operate on the data you pass to them as arguments.))
#### Variables that are accessible through instances like this are called attributes.
###The __init__() method at is a special method
#Python runs automatically whenever we create a new instance of a class
def call_able():
pass
class Dog():
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name #Variables that are accessible through instances like this are called attributes.
self.age = age
##Any variable prefixed with self is available to every method in the class, and we’ll also be
##able to access these variables through any instance created from the class.
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
### __init___###
#it must be included in the definition because when Python calls this __init__() method later (to create an
#instance of Dog), the method call will automatically pass the self argument.
#### VVI####
#Every method call associated with a class automatically passes self, which
#is a reference to the instance itself; it gives the individual instance access to
#the attributes and methods in the class.
if __name__ == '__main__':
my_dog = Dog('willie', 6) #When Python reads this line, it calls the __init__() method in Dog with the arguments 'willie' and 6.
#We store that instance in the variable my_dog.
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.