blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
1571c5675a0e614056cfcee317d8addcfb5c474d
|
Anjali-225/PythonCrashCourse
|
/Chapter_4/Pg_122_Try_It_Yourself_4-15.py
| 1,018
| 4.15625
| 4
|
#4-14 Read through it all
################################
#4-15
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(f"The first three items in the list are: {players[0:3]}")
print("")
print(f"Three items from the middle of the list are: {players[1:4]}")
print("")
print(f"The last three items in the list are: {players[-3:]}")
################################
simple_foods = ('potatoes', 'rice', 'soup', 'sandwiches', 'sauce')
for food in simple_foods:
print(food)
#simple_foods[0] = 'mash'
print("")
simple_foods = ('mash','rice','soup','pizza','sandwiches')
for food in simple_foods:
print(food)
###############################
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are: ")
for food in my_foods:
print(f"{food}")
print("")
print("My friends favorite foods are: ")
for foods in friend_foods:
print(f"{foods}")
| false
|
07af6c34d8365158a21250d6dc858399169fb80c
|
bharathkumarreddy19/python_loops_and_conditions
|
/odd_even.py
| 232
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 19:00:17 2020
@author: bhara_5sejtsc
"""
num = int(input("Enter a number: "))
if num%2 == 0:
print("The given number is even")
else:
print("The given number is odd")
| false
|
f8087e5bf4e1234b7dddf18f6cd7f3612b4563c4
|
ElminaIusifova/week1-ElminaIusifova
|
/04-Swap-Variables**/04.py
| 371
| 4.15625
| 4
|
# # Write a Python program to swap two variables.
#
# Python: swapping two variables
#
# Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.
#
#
# ### Sample Output:
# ```
# Before swap a = 30 and b = 20
# After swaping a = 20 and b = 30
# ```
a=30
b=20
print(a,b)
c=a
a=b
b=c
print(a,b)
| true
|
da4cf09617b4a09e36a1afa5ebcb28ae049331fe
|
ElminaIusifova/week1-ElminaIusifova
|
/01-QA-Automation-Testing-Program/01.py
| 968
| 4.28125
| 4
|
## Create a program that asks the user to test the pages and automatically tests the pages.
# 1. Ask the user to enter the domain of the site. for example `example.com`
# 2. After entering the domain, ask the user to enter a link to the 5 pages to be tested.
# 3. Then display "5 pages tested on example.com".
# 4. Add each page to a variable of type `list` called` tested_link_list`.
# 5. Finally, display `tested pages:` and print the links in the `tested_link_list` list.
siteDomain=input("Please enter domain of the site:")
link1 =input ("Please enter link 1 to be tested:")
link2 =input ("Please enter link 2 to be tested:")
link3 =input ("Please enter link 3 to be tested:")
link4 =input ("Please enter link 4 to be tested:")
link5 =input ("Please enter link 5 to be tested:")
tested_link_list = [link1, link2, link3, link4, link5]
print(siteDomain)
print(tested_link_list)
print("5 pages tested on", siteDomain)
print("tested pages: ", tested_link_list)
| true
|
563c9c6658a045bee7b35b510f706a1ae17039b8
|
Dilan/projecteuler-net
|
/problem-057.py
| 1,482
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
# By expanding this for the first four iterations, we get:
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
# The next three expansions are 99/70, 239/169, and 577/408,
# but the eighth expansion, 1393/985, is the first example where
# the number of digits in the numerator exceeds the number of digits in the denominator.
# In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
import time
ti=time.time()
def sum_up(a, fraction): # a + b/c
# print a, '+', b, '/', c, ' = ', (c * a + b), '/', c
b = fraction[0]
c = fraction[1]
return ((c * a + b), c)
def plus1(fraction): # a + b/c
return sum_up(1, fraction)
def swap(fraction): # a + b/c
return (fraction[1], fraction[0])
def is_length_different(x, y):
return len(str(x)) != len(str(y))
def solution(length):
counter = 0
prev = (3, 2)
while length > 0:
# 1 + 1 / (prev)
prev = sum_up(1, swap(plus1(prev)))
if is_length_different(prev[0], prev[1]):
counter += 1
length -= 1
return counter
print 'Answer is:', solution(1000), '(time:', (time.time()-ti), ')'
| true
|
3c8802f63b9ff336168a750a2d82e7e42c6ee7ec
|
Chou-Qingyun/Python006-006
|
/week06/p5_1classmethod.py
| 2,320
| 4.25
| 4
|
# 让实例的方法成为类的方法
class Kls1(object):
bar = 1
def foo(self):
print('in foo')
# 使用类属性、方法
@classmethod
def class_foo(cls):
print(cls.bar)
print(cls.__name__)
cls().foo()
# Kls1.class_foo()
########
class Story(object):
snake = 'python'
# 初始化函数,并非构造函数。构造函数: __new__()
def __init__(self, name):
self.name = name
# 类的方法
@classmethod
def get_apple_to_eve(cls):
return cls.snake
s = Story('anyone')
# get_apple_to_eve 是bound方法,查询顺序先找s的__dict__是否有get_apple_to_eve,如果没有,查类Story
print(s.get_apple_to_eve)
# 类和实例都可以使用
print(s.get_apple_to_eve())
print(Story.get_apple_to_eve())
#####################
class Kls2():
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def print_name(self):
print(f'first name is {self.fname}')
print(f'last name is {self.lname}')
me = Kls2('qingyun','chow')
me.print_name()
# 修改输入为 qingyun-chow
# 解决方法1:修改__init__()
# 解决方法2: 增加__new__构造函数
# 解决方法3: 增加 提前处理的函数
def pre_name(obj,name):
fname, lname = name.split('-')
return obj(fname, lname)
me2 = pre_name(Kls2, 'qingyun-chow')
#####
class Kls3():
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
@classmethod
def pre_name(cls,name):
fname, lname = name.split('-')
return cls(fname, lname)
def print_name(self):
print(f'first name is {self.fname}')
print(f'last name is {self.lname}')
me3 = Kls3.pre_name('qingyun-chow')
me3.print_name()
#########
class Fruit(object):
total = 0
@classmethod
def print_total(cls):
print(cls.total)
print(id(Fruit.total))
print(id(cls.total))
@classmethod
def set(cls, value):
print(f'calling {cls}, {value}')
cls.total = value
class Apple(Fruit):
pass
class Orange(Fruit):
pass
Apple.set(100)
# calling <class '__main__.Apple'>, 100
Orange.set(200)
org = Orange()
org.set(300)
# calling <class '__main__.Orang'>, 300
Apple.print_total()
Orange.print_total()
| false
|
3f2e1e7f00004e07ed45b0499bfcacb873d6ef92
|
CodedQuen/python_begin1
|
/simple_database.py
| 809
| 4.34375
| 4
|
# A simple database
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil': {
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
# Descriptive lables for the phone number and address.
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = input('Name:')
# Are we looking for a phone number or an address?
request = input('Phone number (p) or address (a)?')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in our dictionary:
if name in people:
print ("%s's %s is %s." % (name, labels[key], people[name][key]))
| true
|
92ab0a09b8eab1d3a27beab9c4093d3acd30991b
|
JunaidRana/MLStuff
|
/Advanced Python/Virtual Functions/File.py
| 364
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 19:51:27 2018
@author: Junaid.raza
"""
class Dog:
def say(self):
print ("hau")
class Cat:
def say(self):
print ("meow")
pet = Dog()
pet.say() # prints "hau"
another_pet = Cat()
another_pet.say() # prints "meow"
my_pets = [pet, another_pet]
for a_pet in my_pets:
a_pet.say()
| false
|
e84ea0ce2afb28b4bb2c13a0f8b44fbbb08788bc
|
aayanqazi/python-preparation
|
/A List in a Dictionary.py
| 633
| 4.25
| 4
|
from collections import OrderedDict
#List Of Dictionary
pizza = {
'crust':'thick',
'toppings': ['mashrooms', 'extra cheese']
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for toppings in pizza['toppings']:
print ("\t"+toppings)
#Examples 2
favourite_languages= {
'jen': ['python', 'ruby'],
'sarah': ['c'],
' edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name,languages in favourite_languages.items():
print("\n"+name.title()+"'s favourite languages are :")
for language in languages:
print ("\t"+language.title())
| true
|
05a1e4c378524ef50215bd2bd4065b9ab696b80d
|
Glitchier/Python-Programs-Beginner
|
/Day 2/tip_cal.py
| 397
| 4.15625
| 4
|
print("Welcome to tip calculator!")
total=float(input("Enter the total bill amount : $"))
per=int(input("How much percentage of bill you want to give ? (5%, 10%, 12%, 15%) : "))
people=int(input("How many people to split the bill : "))
bill_tip=total*(per/100)
split_amount=float((bill_tip+total)/people)
final_bill=round(split_amount,2)
print(f"Each person should pay : ${final_bill}")
| true
|
14a7f65f931c18bf4e7fa39e421d1a688e47356c
|
rg3915/Python-Learning
|
/your_age2.py
| 757
| 4.3125
| 4
|
from datetime import datetime
def age(birthday):
'''
Retorna a idade em anos
'''
today = datetime.today()
if not birthday:
return None
age = today.year - birthday.year
# Valida a data de nascimento
if birthday.year > today.year:
print('Data inválida!')
return None
# Verifica se o dia e o mês já passaram;
# se não, tira 1 ano de 'age'.
if today.month < birthday.month or (today.month == birthday.month and today.day < birthday.day):
age -= 1
return age
if __name__ == '__main__':
birthday = input('Digite sua data de nascimento no formato dd/mm/yyyy: ')
birthday = datetime.strptime(birthday, '%d/%m/%Y')
if age(birthday):
print(age(birthday))
| false
|
507fdcb28060f2b139b07853c170974939267b63
|
Abhinav-Rajput/CodeWars__KataSolutions
|
/Python Solutions/Write_ Number_in_Expanded_Form.py
| 611
| 4.34375
| 4
|
# Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
strNum = str(num)
line = ''
for i in range(0,len(strNum)):
if strNum[i]=='0':
continue
line += strNum[i] + ''
for j in range(0,(len(strNum)-(i+1))):
line += '0'
line += ' + '
line = line[0:len(line)-3]
return line
| true
|
b8ca7993c15513e13817fa65f892ebd014ca5743
|
Satona75/Python_Exercises
|
/Guessing_Game.py
| 816
| 4.40625
| 4
|
# Computer generates a random number and the user has to guess it.
# With each wrong guess the computer lets the user know if they are too low or too high
# Once the user guesses the number they win and they have the opportunity to play again
# Random Number generation
from random import randint
carry_on = "y"
while carry_on == "y":
rand_number = randint(1,10)
guess = int(input("Try and guess the number generated between 1 and 10 "))
while guess != rand_number:
if guess < rand_number:
guess = int(input("Sorry too low! Try again.. "))
else:
guess = int(input("Sorry too high! Try again.. "))
print("Congratulations!! You have guessed correctly!")
carry_on = input("Do you want to play again? (y/n).. ")
print("Thanks for playing!")
| true
|
c069374b1d2c822c9a71b4c7c95ac5e7e3ca945f
|
Satona75/Python_Exercises
|
/RPS-AI.py
| 1,177
| 4.3125
| 4
|
#This game plays Rock, Paper, Scissors against the computer.
print("Rock...")
print("Paper...")
print("Scissors...\n")
#Player is invited to choose first
player=input("Make your move: ").lower()
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
elif player == "scissors":
print("Computer Wins!")
elif computer == "paper":
if player == "scissors":
print("You Win!")
elif player == "rock":
print("Computer Wins!")
elif computer == "scissors":
if player == "rock":
print("You Win!")
elif player == "paper":
print("Computer Wins!")
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
| true
|
474ae873c18391c8b7872994da02592b59be369c
|
Satona75/Python_Exercises
|
/RPS-AI-refined.py
| 1,977
| 4.5
| 4
|
#This game plays Rock, Paper, Scissors against the computer
computer_score = 0
player_score = 0
win_score = 2
print("Rock...")
print("Paper...")
print("Scissors...\n")
while computer_score < win_score and player_score < win_score:
print(f"Computer Score: {computer_score}, Your Score: {player_score}")
#Player is invited to choose first
player=input("Make your move: ").lower()
if player == "quit" or player == "q":
break
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer = "rock"
elif comp_int == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer has chosen: " + computer)
if player == "rock" or player == "paper" or player == "scissors":
if computer == player:
print("It's a tie!")
elif computer == "rock":
if player == "paper":
print("You Win!")
player_score += 1
elif player == "scissors":
print("Computer Wins!")
computer_score += 1
elif computer == "paper":
if player == "scissors":
print("You Win!")
player_score += 1
elif player == "rock":
print("Computer Wins!")
computer_score += 1
elif computer == "scissors":
if player == "rock":
print("You Win!")
player_score += 1
elif player == "paper":
print("Computer Wins!")
computer_score += 1
else:
print("Something has gone wrong!")
else:
print("Please enter either rock, paper or scissors")
if computer_score > player_score:
print("Oh no! The Computer won overall!!")
elif player_score > computer_score:
print("Congratulations!! You won overall")
else:
print("It's a tie overall")
| true
|
19dbab140d55e0b7f892d66f08b9dc26ba5f4095
|
timurridjanovic/javascript_interpreter
|
/udacity_problems/8.subsets.py
| 937
| 4.125
| 4
|
# Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
#iterative solution
def listSubsets(list, subsets=[[]]):
if len(list) == 0:
return subsets
element = list.pop()
for i in xrange(len(subsets)):
subsets.append(subsets[i] + [element])
return listSubsets(list, subsets)
print listSubsets([1, 2, 3, 4, 5])
#recursive solution
def sublists(big_list, selected_so_far):
if big_list == []:
print selected_so_far
else:
current_element = big_list[0]
rest_of_big_list = big_list[1:]
sublists(rest_of_big_list, selected_so_far + [current_element])
sublists(rest_of_big_list, selected_so_far)
dinner_guests = ["LM", "ECS", "SBA"]
sublists(dinner_guests, [])
| true
|
c593ca80cbc671e86d12f8d2ffaf0829fdb024ea
|
jacobfdunlop/TUDublin-Masters-Qualifier
|
/10.py
| 470
| 4.1875
| 4
|
usernum1 = int(input("Please enter a number: "))
usernum2 = int(input("Please enter another number: "))
usernum3 = int(input("Please enter another number: "))
if usernum1 > usernum2 and usernum1 > usernum3:
print(usernum1, " is the largest number")
elif usernum2 > usernum1 and usernum2 > usernum3:
print(usernum2, " is the largest number")
elif usernum3 > usernum1 and usernum3 > usernum2:
print(usernum3, " is the largest number")
| true
|
267335a2b28e9bc77b99f0b288f5bbb6f5b4d763
|
KelseySlavin/CIS104
|
/Assignments/Lab1/H1P1.py
| 524
| 4.15625
| 4
|
first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
age = int(input("What is your age?: "))
confidence=int(input("How confident are you in programming between 1-100%? "))
dog_age= age * 7
print("hello, " + first_name+ " " + last_name + " , nice to meet you! You might be " + str(age) + " in human years, but in dog year you are " +str(dog_age)+"." )
if confidence < 50:
print("I agree, programmers can't be trusted!")
else:
print("Writing good code takes hard work!")
| true
|
87e0c4f5b7335390da9274aedad193cbdb99d5ce
|
Ghelpagunsan/classes
|
/lists.py
| 2,473
| 4.15625
| 4
|
class manipulate:
def __init__(self, cars):
self.cars = cars
def add(self):
self.cars.append("Ford")
self.cars.sort()
return self.cars
def remove(self):
print("Before removing" + str(self.cars))
self.cars.remove("Honda")
return str("After removing" + str(self.cars))
def update(self, car):
car.update(["Pajero", "Mitzubishi"])
sorted(car)
return car
class show:
def __init__(self, num):
self.num = num
def getvalue(self):
return str(self.num.index(4))
def popval(self):
self.num.pop()
return self.num
def reversing(self):
self.num.reverse()
return self.num
def counting(self):
i = 0
for j in self.num:
i+=1
return i
class change:
def __init__(self,year):
self.year = year
def deletingval(self):
del self.year[3]
return self.year
def looping(self):
for x in self.year:
print(x)
def check(self):
if 2001 in self.year:
return str("Found!")
class compare:
def __init__(self, a, b):
self.a = a
self.b = b
def length(self, n):
return str("The length of the list is " + str(len(n)))
def multipleset(self, n):
return str(n)
y = n[0]
return str(y)
x = y[0]
return str(x)
z = x[1]
return str(z)
def intersections(self):
c = self.a.intersection_update(self.b)
return str(c)
def differences(self):
c = self.b.difference(self.a)
return str(c)
def symmetric(self):
c = self.a.symmetric_difference(self.b)
sorted(c)
return str(c)
def unions(self, a, b, c, d):
e = a.union(b, c, d)
return str(e)
def extends(self, x, y):
y.extend(x)
return str(y)
class order:
def __init__(self, a):
self.a = a
def whileloop(self):
i = 0
while i<5:
i+=2
print(i)
def sorting(self):
self.a.append(7)
self.a.sort()
return str(self.a)
def forloop(self):
i = 0
for i in self.a:
print(i)
i+=1
# print(add())
# print(remove())
# print(update())
# print(getvalue([1, 2, 3, 4 ,5]))
# print(popval(['a', 'b', 'c', 'd']))
# print(reversing([2, 4, 6, 8]))
# print(counting([1, 2, 3, 4, 5, 6, 7, 8]))
# print(deletingval(["Davao", "Cebu", "Manila", "Butuan"]))
# looping()
# print(check())
# print(length([1, 2, 3, 4, 5, 6]))
# print(multipleset())
# print(intersections({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(differences({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(symmetric({"a", "b", "c", "d"}, {"a", "d", "f"}))
# print(unions())
# print(extends())
# whileloop()
# print(sorting([8, 4, 5, 6]))
# forloop()
| true
|
265049dd5c7273612076608f805ee6f00e3f2430
|
DangerousCode/DAM-2-Definitivo
|
/Python/Funciones de Alto orden/Ejemplo4.py
| 1,256
| 4.3125
| 4
|
__author__ = 'AlumnoT'
'''Funcion dada una lista de numeros y un numero cota superior,
queremos devolver aquellos elementos menores a dicha
cota'''
lista=list(range(-5,5))
'''1)Modificar la sintaxis anterior para que solo nos muestre los numeros negativos'''
print filter(lambda x:x<0,lista)
'''2)Crear funcion a la que le vamos a pasar una lista de los valores 0,1,2,3,4 y esa funcion
tiene que devolvernos una lista formada por el cuadrado del primer valor con el cubo del primer valor
(con todos los valores)'''
print map(lambda x:[x*x,x*x*x],[0,1,2,3,4])
'''3)Generar dos listas una con valores numericos del 0 al 5 y otra con tres cadenas cuando ejecutemos la funcion
queremos que nnos muestre la media de la lista que contiene los numeros y que las tres cadenas de la segunda lista
aparezcan como una sola frase'''
lista=list(range(0,6))
listacad=["hola","que","tal"]
print (reduce(lambda x,z:x+z,lista))/len(lista)
print reduce(lambda a,b:a+" "+b,listacad)
'''4)Se nos va a facilitar una lista y una tupla con numeros debemos realizar una funcion que sume cada numero de la lista
con el correspondiente numero de su misma posicion en la tupla todo ello usando map,reduce,filter, lambda'''
lis=[1,2,3]
tup=(3,2,1)
print map(lambda x,y:x+y,lis,tup)
| false
|
3cac0579ed84aaeeb6cd68e8dba63fbfa5caefee
|
brentirwin/automate-the-boring-stuff
|
/ch7/regexStrip.py
| 1,091
| 4.6875
| 5
|
#! python3
# regexStrip.py
'''
Write a function that takes a string and does the same thing as the strip()
string method. If no other arguments are passed other than the string to strip,
then whitespace characters will be removed from the beginning and end of the
string. Otherwise, the characters specified in the second argument to the
function will be removed from the string.
'''
import re
def regexStrip(string, substring = None):
# No substring
if substring == None:
# Find whitespace at beginning and/or end
startSpaceRegex = re.compile(r'^\w+')
endSpaceRegex = re.compile(r'\w+$')
# Remove whitespace at beginning and/or end
string = startSpaceRegex.sub('', string)
string = endSpaceRegex.sub('', string)
return string
# Yes substring
else:
substringRegex = re.compile(substring)
return substringRegex.sub('', string)
string = input("String: ")
substring = input("Substring: ")
if substring == '':
print(regexStrip(string))
else:
print(regexStrip(string, substring))
| true
|
c86a09cf6d893b85a67cf094b8fcf3e1b1e22e9b
|
realdavidalad/python_algorithm_test_cases
|
/longest_word.py
| 325
| 4.375
| 4
|
# this code returns longest word in a phrase or sentence
def get_longest_word(sentence):
longest_word=""
for word in str(sentence).split(" "): longest_word=word if len(word) > len(longest_word) else longest_word
return longest_word
print get_longest_word("This is the begenning of algorithm")
| true
|
fa0c8bc224b3c091276166cd426bd5153edb0b73
|
Lynkdev/Python-Projects
|
/shippingcharges.py
| 508
| 4.34375
| 4
|
#Jeff Masterson
#Chapter 3 #13
shipweight = int(input('Enter the weight of the product '))
if shipweight <= 2:
print('Your product is 2 pounds or less. Your cost is $1.50')
elif shipweight >= 2.1 and shipweight <= 6:
print('Your product is between 2 and 6 pounds. Your cost is $3.00')
elif shipweight >= 6.1 and shipweight <= 10:
print('Your product is between 6 and 10 pounds. Your cost is $4.00')
elif shipweight > 10:
print('Your product is over 10 pounds. Your cost is $4.75')
| true
|
3647c4684453494b07d2000b1f7d2a9cfd7eaef0
|
ching-yi-hsu/practice_python
|
/6_String_Lists/string_lists.py
| 206
| 4.3125
| 4
|
str_word = str(input("enter a string : "))
str_word_rev = str_word[::-1]
if str_word == str_word_rev :
print(str_word , " is a palindrome word")
else :
print(str_word, " isn't a palindrome word")
| false
|
bf07fa0385b64213f01583fe22a86deb00ea65d2
|
mandarwarghade/Python3_Practice
|
/ThinkPython_Ex3.py
| 1,035
| 4.1875
| 4
|
#Exercise 3
#Note: This exercise should be done using only the statements and other features we have learned so far.
#Write a function that draws a grid like the following:
#+ - - - - + - - - - +
#| | |
#| | |
#| | |
#| | |
#+ - - - - + - - - - +
#| | |
#| | |
#| | |
#| | |
#+ - - - - + - - - - +
def do_twice(f, arg):
f(arg)
f(arg)
def print_twice(arg):
print(arg,end="")
print(arg,end="")
def print_twice_newline(arg):
print(arg)
print(arg)
def do_four(f, arg):
do_twice(f,arg)
do_twice(f,arg)
# do_twice(print_twice, "natasha")
# do_four(print_twice, "natasha")
def make_grid():
print_twice("+" + "----")
print("+")
do_twice(print_twice_newline, "|" + " " + "|" + " " + "|")
print_twice("+" + "----")
print("+")
do_twice(print_twice_newline, "|" + " " + "|" + " " + "|")
print_twice("+" + "----")
print("+")
make_grid()
| false
|
bec5623135d5387e7bb16e3f63d93522a2a6f69a
|
sbuffkin/python-toys
|
/stretched_search.py
| 1,172
| 4.15625
| 4
|
import sys
import re
#[^b]*[b][^o]*[o][^a]*[a][^t]*[t](.?)
#([^char]*[char])*(.?) <- general regex
#structure of regex, each character is [^(char)]*[(char)]
#this captures everything that isn't the character until you hit the character then moves to the next state
#you can create a "string" of these in regex to see if you can find the given string within a larger document,
#perhaps hidden somewhere
#this will find the first such occurance.
#takes in a string as input
"""
If any group is captured (even an empty one) that means we got a hit!
It might been stretched across the entire document but YAY.
"""
def regexBuild(string):
regex = ""
for char in string:
regex += "[^{0}]*[{0}]".format(char)
regex += "(.)"
p = re.compile(regex)
return p
def find(reg):
try:
filename = sys.argv[2]
except:
print('Need filename arg')
try:
f = open(filename,'r')
words = f.read()
m = reg.match(words)
print(m)
if m:
print('Found Match')
else:
print('No Match')
except:
print("File not found")
reg = regexBuild(sys.argv[1])
find(reg)
| true
|
91a5122f9957141be0966121bf67ac11ae2a2f22
|
Pranitha-J-20/Fibonacci
|
/Fibonacci series.py
| 306
| 4.21875
| 4
|
num=int(input("enter the number of terms: "))
n1=0
n2=1
count=0
if num<=0:
print("enter a positive integer")
elif num==1:
print('fibonacci seies: ',n1)
else:
print("fibonacci series: ")
while count<num:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+1
| false
|
b4c8c18405a914afecee69a0d7f55f57bca6aed5
|
helen5haha/pylee
|
/game/CountandSay.py
| 1,012
| 4.15625
| 4
|
'''
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Every round, when encounter a different char then stop the count of this round.
Please note that the last round, because it encounters the end of the string, so we have to force stop the round
'''
def doCountAndSay(src):
char = src[0]
num = 0
result = ""
for c in src:
if char == c:
num += 1
else:
result += (str(num) + char)
char = c
num = 1
result += (str(num) + char)
return result
def countAndSay(n):
if 0 == n:
return ""
elif 1 == n:
return "1"
result = "1"
for i in range(1,n):
result = doCountAndSay(result)
return result
countAndSay(4)
| true
|
84806db8304b6bb9b25f9aced5bcb078492bae2a
|
helen5haha/pylee
|
/matrix/SpiralMatrix.py
| 827
| 4.21875
| 4
|
'''
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
def spiralOrder(matrix):
m = len(matrix)
if 0 == m:
return []
n = len(matrix[0])
if 0 == n:
return []
arr = []
round = (min(m,n) + 1) / 2
for x in range(0, round):
for y in range(x, n-x):
arr.append(matrix[x][y])
for y in range(x+1, m-x-1):
arr.append(matrix[y][n-x-1])
if m - 2*x > 1:
for y in range(n-x-1, x-1, -1):
arr.append(matrix[m-x-1][y])
if n - 2*x > 1:
for y in range(m-x-2, x, -1):
arr.append(matrix[y][x])
return arr
| false
|
5cffad649c630930892fb1bbe38c7c8b6c177b60
|
Keerthanavikraman/Luminarpythonworks
|
/oop/polymorphism/demo.py
| 1,028
| 4.28125
| 4
|
### polymorphism ...many forms
##method overloading...same method name and different number of arguments
##method overriding...same method name and same number of arguments
###method overloading example
# class Operators:
# def num(self,n1,n2):
# self.n1=n1
# self.n2=n2
# print(self.n1+self.n2)
#
# class Display(Operators):
# def num(self,n3):
# self.n3=n3
# print(self.n3)
# d=Display()
# d.num(3)
#
# class Operators:
# def num(self,n1,n2):
# self.n1=n1
# self.n2=n2
# print(self.n1+self.n2)
#
# class Display(Operators):
# def num(self,n3):
# self.n3=n3
# print(self.n3)
# d=Display()
# d.num(3,4) ## donot support
#
###method overriding example
class Person:
def printval(self,name):
self.name=name
print("inside person method",self.name)
class Child(Person):
def printval(self,class1):
self.class1=class1
print("inside child method",self.class1)
ch=Child()
ch.printval("abc")
| true
|
820abce4f9d2ca4f8435512d9ad69873abb106b3
|
Vani-start/python-learning
|
/while.py
| 553
| 4.28125
| 4
|
#while executes until condition becomes true
x=1
while x <= 10 :
print(x)
x=x+1
else:
print("when condition failes")
#While true:
# do something
#else:
# Condifion failed
#While / While Else loops - a while loop executes as long as an user-specified condition is evaluated as True; the "else" clause is optional
#x = 1
#while x <= 10:
# print(x)
#x += 1
#else:
# print("Out of the while loop. x is now greater than 10")
#result of the above "while" block
#1 2 3 4 5 6 7 8 9 10
#Out of the while loop. x is now greater than 10
| true
|
495429537628e1b51b144775abb34d060034ac20
|
Vani-start/python-learning
|
/convertdatatype.py
| 980
| 4.125
| 4
|
#Convet one datatype into otehr
int1=5
float1=5.5
int2=str(int1)
print(type(int1))
print(type(int2))
str1="78"
str2=int(str1)
print(type(str1))
print(type(str2))
str3=float(str1)
print(type(str3))
###Covert tuple to list
tup1=(1,2,3)
list1=list(tup1)
print(list1)
print(tup1)
set1=set(list1)
print(set1)
####bin, dec,hex
number=10
num_to_bin=bin(number)
print(num_to_bin)
num_to_hex=hex(number)
print(num_to_hex)
num_from_bin=int(num_to_bin,2)
print(num_from_bin)
num_from_hex=int(num_to_hex,16)
print(num_from_hex)
#Conversions between data types
#str() #converting to a string
#int() #converting to an integer
#float() #converting to a float
#list() #converting to a list
#tuple() #converting to a tuple
#set() #converting to a set
#bin() #converting to a binary representation
#hex() #converting to a hexadecimal representation
#int(variable, 2) #converting from binary back to decimal
#int(variable, 16) #converting from hexadecimal back to decimal
| true
|
876792dac3431422495d8b71eb97b5faf662f201
|
risabhmishra/parking_management_system
|
/Models/Vehicle.py
| 931
| 4.34375
| 4
|
class Vehicle:
"""
Vehicle Class acts as a parent base class for all types of vehicles, for instance in our case it is Car Class.
It contains a constructor method to set the registration number of the vehicle to registration_number attribute
of the class and a get method to return the value stored in registration_number attribute of the class.
"""
def __init__(self, registration_number):
"""
This constructor method is used to store the registration number of the vehicle to registration_number attribute
of the class.
:param registration_number: str
"""
self.registration_number = registration_number
def get_registration_number(self):
"""
This method is used to return the value stored in the registration_number attribute of the class.
:return: registration_number:str
"""
return self.registration_number
| true
|
27e8ec33ff0f380bf54428032445ab8905d3164f
|
detjensrobert/cs325-group-projects
|
/ga1/assignment1.py
| 2,273
| 4.40625
| 4
|
"""
This file contains the template for Assignment1. You should fill the
function <majority_party_size>. The function, recieves two inputs:
(1) n: the number of delegates in the room, and
(2) same_party(int, int): a function that can be used to check if two members are
in the same party.
Your algorithm in the end should return the size of the largest party, assuming
it is larger than n/2.
I will use <python3> to run this code.
"""
def majority_party_size(n, same_party):
"""
n (int): number of people in the room.
same_party (func(int, int)): This function determines if two delegates
belong to the same party. same_party(i,j) is True if i, j belong to
the same party (in particular, if i = j), False, otherwise.
return: The number of delegates in the majority party. You can assume
more than half of the delegates belong to the same party.
"""
return majority_party_size_helper([i for i in range(n)], same_party)[1]
def majority_party_size_helper(delegates, same_party):
# PARAM: delegates[] = indexes of delegates to check
# RETURN: tuple(index of majority party candidate, size of majority party)
if len(delegates) >= 2:
# recursively check each half of our delegate list to find the majority party of each half
mid = int(len(delegates) / 2)
(left_delegate, _) = majority_party_size_helper(delegates[:mid], same_party)
(right_delegate, _) = majority_party_size_helper(delegates[mid:], same_party)
# Count up the size of each half's majority party for the whole chunk
left_party_size = 0
right_party_size = 0
for i in delegates:
if same_party(left_delegate, i):
left_party_size += 1
if same_party(left_delegate, i):
right_party_size += 1
# who's bigger?
if left_party_size > right_party_size:
maj_delegate = left_delegate
maj_size = left_party_size
else:
maj_delegate = right_delegate
maj_size = right_party_size
return (maj_delegate, maj_size)
else: # Base case: single delegate -- only one possible majority here!
return (delegates[0], 1)
| true
|
58e59338d5d1fc79374d0ce438582c4d73185949
|
Neethu-Mohan/python-project
|
/projects/create_dictionary.py
| 1,091
| 4.15625
| 4
|
"""
This program receives two lists of different lengths. The first contains keys, and the second contains values.
And the program creates a dictionary from these keys and values. If the key did not have enough values, the dictionary will have the value None. If
Values that did not have enough keys will be ignored.
"""
from itertools import chain, repeat
keys = []
def get_list():
keys = [item for item in input("Enter the first list items : ").split()]
values = [item for item in input("Enter the second list items : ").split()]
dictionary_ouput = create_dictionary(keys, values)
print(dictionary_ouput)
def create_dictionary(keys, values):
difference = compare_length(keys, values)
if difference <= 0:
dic_value = dict(zip(keys, values))
return dic_value
elif difference > 0:
dic_value = dict(zip(keys, chain(values, repeat(None))))
return dic_value
def compare_length(keys, values):
difference = check_length(keys) - check_length(values)
return difference
def check_length(item):
return len(item)
| true
|
a99612c8ed99a9d0596c7a9f342e8831c21d0b63
|
SayedBhuyan/learning-python
|
/if else.py
| 781
| 4.1875
| 4
|
#mark = int(input("Enter Mark: "))
# if else
mark = 85
if mark >= 80:
print("A+")
elif mark >= 70:
print("A")
elif mark >= 60:
print("A-")
elif mark >= 50:
print("B+")
elif mark >= 40:
print("B")
elif mark >= 33:
print("B-")
else:
print("Fail")
'''
if (mark % 2) == 0:
print("Even")
else :
print("Odd")
'''
# nested if statement
if 5 > 2:
if 7 > 2:
print("good")
else:
print("Not matched")
else :
print("Not a even")
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
num3 = int(input("Enter third number"))
if num1 > num2:
if num1 > num3:
print(num1)
else:
print(num3)
else:
if num2 > num3:
print(num2)
else :
print(num3)
| false
|
488675687a2660c01e9fd7d707bdf212f94abb62
|
NM20XX/Python-Data-Visualization
|
/Simple_line_graph_squares.py
| 576
| 4.34375
| 4
|
#Plotting a simple line graph
#Python 3.7.0
#matplotlib is a tool, mathematical plotting library
#pyplot is a module
#pip install matplotlib
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values, squares, linewidth = 5) #linewidth controls the thickness of the line that plot() generates.
#Title and label axes
plt.title("Square Numbers", fontsize = 24)
plt.xlabel("Value", fontsize = 14)
plt.ylabel("Square of value", fontsize = 14)
#Set size of tick labels
plt.tick_params(axis ='both', labelsize = 14)
plt.show()
| true
|
9ed2d0f9f15fde3e123ea8f30c2ffa714db1460a
|
tristaaa/learnpy
|
/getRemainingBalance.py
| 819
| 4.125
| 4
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def getMonthlyBalance(balance, annualInterestRate, monthlyPaymentRate):
'''
return: the remaining balance at the end of the month
'''
minimalPayment = balance * monthlyPaymentRate
monthlyUnpaidBalance = balance - minimalPayment
interest = monthlyUnpaidBalance * annualInterestRate / 12
return monthlyUnpaidBalance + interest
def getFinalBalance(balance, annualInterestRate, monthlyPaymentRate):
for m in range(12):
balance = getMonthlyBalance(
balance, annualInterestRate, monthlyPaymentRate)
remainingBalance = round(balance, 2)
print('Remaining balance:', remainingBalance)
getFinalBalance(balance, annualInterestRate, monthlyPaymentRate)
| true
|
6df041ded350202d4e74f98a104fd3470e21683d
|
tristaaa/learnpy
|
/bisectionSearch_3.py
| 910
| 4.46875
| 4
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# use bisection search to guess the secret number
# the user thinks of an integer [0,100).
# The computer makes guesses, and you give it input
# - is its guess too high or too low?
# Using bisection search, the computer will guess the user's secret number
low = 0
high = 100
guess = (low+high)//2
print('Please think of a number between 0 and 100!')
while True:
print('Is your secret number '+str(guess)+'?')
is_secret_num = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if is_secret_num =='l':
low = guess
elif is_secret_num =='h':
high = guess
elif is_secret_num =='c':
break
else:
print('Sorry, I did not understand your input.')
guess = (low+high)//2
print('Game over. Your secret number was:',guess)
| true
|
0dc00b065c4e8460cb7e85db60d3bfea2189803a
|
AnnapurnaThakur/python_code
|
/anubreak19.py
| 600
| 4.3125
| 4
|
# for x in range (1,5):
# for i in range(1,5):
# if i==3:
# print("Sorry")
# print("loop2")
# break
# print("loop1")
# print("end")
####2nd example:
for x in range (1,5):
for i in range(1,5):
if i==3:
print("Sorry")
break
print("loop2")
print("loop1")
print("end")
######3rd example:
# for x in range (1,5):
# for i in range(1,7):
# if i==3:
# print("sorry")
# continue
# print("loop i= " , i , "and loop i =" ,x)
# print("loop completed x" , x)
# print("end")
| false
|
537ddca25824fd995727cbb026fecefa5bdcaf8b
|
wkomari/Lab_Python_04
|
/data_structures.py
| 1,383
| 4.40625
| 4
|
#lab 04
# example 1a
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne')
print groceries
# example1b
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne') # add champagne to the list of groceries
groceries.remove('bread') # remove bread from the list of groceries
print groceries
# example 1c
groceries = ['bananas','strawberries','apples','bread']
groceries.append('champagne') # add champagne to the list of groceries
groceries.remove('bread') # remove bread from the list of groceries
groceries.sort()
print groceries
# example 2a
print 'Dictionary would be used as the data type'
dict = {'Apples':'7.3','Bananas':'5.5','Bread':'1.0','Carrot':'10.0','Champagne':'20.90','Strawberries':'32.6'}
print 'Apple is', dict['Apples']
dict['Strawberries'] = 63.43
print 'The price of Strawberries in winter now is', dict['Strawberries'] # updated strawberries price
dict['chicken'] = 6.5
print dict # prints all entries in the dictionary
print 'Hehe customers we have chicken now in stock at', dict['chicken']
#example3
in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries')
always_in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries')
print 'Come to shoprite! We always sell:\n', always_in_stock[0:6]
for i in always_in_stock:
print i
#example4
| true
|
5f168aeaf97ebb2100fafcbaef59928522f86d70
|
sha-naya/Programming_exercises
|
/reverse_string_or_sentence.py
| 484
| 4.15625
| 4
|
test_string_sentence = 'how the **** do you reverse a string, innit?'
def string_reverser(string):
reversed_string = string[::-1]
return reversed_string
def sentence_reverser(sentence):
words_list = sentence.split()
reversed_list = words_list[::-1]
reversed_sentence = " ".join(reversed_list)
return reversed_sentence
example_1 = string_reverser(test_string_sentence)
print(example_1)
example_2 = sentence_reverser(test_string_sentence)
print(example_2)
| true
|
18fae6895c6be30f0a3a87531a2fafe965a3c89f
|
pkdoshinji/miscellaneous-algorithms
|
/baser.py
| 1,873
| 4.15625
| 4
|
#!/usr/bin/env python3
'''
A module for converting a (positive) decimal number to its (base N) equivalent, where
extensions to bases eleven and greater are represented with the capital letters
of the Roman alphabet in the obvious way, i.e., A=10, B=11, C=12, etc. (Compare
the usual notation for the hexadecimal numbers.) The decimal number and the
base (N) are entered in the command line: baser.py <base> <decimal number to convert>
'''
import sys
#Character set for representing digits. For (base N) the set is characters[:N]
characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
#Usage guidelines
def usage():
print('[**]Usage: baser.py <base> <number to convert>')
print(f' <base> must be less than or equal to {len(characters)}')
print(f' <number> must be a nonnegative integer')
#Get the most significant digit (MSD) of the decimal number in (base N)
def getMSD(base, number):
MSD = 1
while True:
if (base ** MSD) > number:
return MSD
MSD += 1
#Convert the decimal number to (base N)
def convert(MSD, base, number):
result = ''
for i in range(MSD - 1, -1, -1):
value = number // (base ** i)
result += chars[value]
number = number % (base ** i)
return result
def main():
#Input sanitization
try:
base = int(sys.argv[1])
except:
usage()
exit()
try:
number = int(sys.argv[2])
except:
usage()
exit()
if base > len(characters):
usage()
exit(0)
if number == 0:
print(0)
exit(0)
if number < 0:
usage()
exit(0)
global chars
chars = characters[:base] #Get the (base N) character set
print(convert(getMSD(base, number), base, number)) #Convert and output
if __name__ == '__main__':
main()
| true
|
fe03952ad6982e0e51a9218b01dc9231df641b41
|
cbrandao18/python-practice
|
/celsius-to-f.py
| 226
| 4.1875
| 4
|
def celsiusToFahrenheit(degree):
fahrenheit = degree*1.8 + 32
print fahrenheit
celsiusToFahrenheit(0)
celsiusToFahrenheit(25)
n = input("Enter Celsius you would like converted to Fahrenheit: ")
celsiusToFahrenheit(n)
| false
|
2cee626ca8bbdd1c78751e9df019279d323d1e06
|
Philngtn/pythonDataStructureAlgorithms
|
/Arrays/ArrayClass.py
| 1,291
| 4.15625
| 4
|
# # # # # # # # # # # # # # # # # # # # # # # #
# Python 3 data structure practice
# Chap 1: Implementing Class
# Author : Phuc Nguyen (Philngtn)
# # # # # # # # # # # # # # # # # # # # # # # #
class MyArray:
def __init__(self):
self.length = 0
# Declare as dictionary
self.data = {}
# Convert the class object into string
def __str__(self):
# convert all the class object to dictionary type {length, data}
return str(self.__dict__)
def get(self,index):
return self.data[index]
def push(self, item):
self.data[self.length]= item
self.length +=1
def pop(self):
lastitem = self.data[self.length - 1]
del self.data[self.length - 1]
self.length -= 1
return lastitem
def delete(self, index):
deleteditem = self.data[index]
# Shifting the data to one slot
for i in range(index, self.length -1):
self.data[i] = self.data[i+1]
# Delete the last array slot
del self.data[self.length - 1]
self.length -= 1
return deleteditem
newArray = MyArray()
newArray.push("Hello. ")
newArray.push("How")
newArray.push("are")
newArray.push("you")
newArray.push("!")
newArray.delete(1)
print(newArray)
| false
|
358c68067412029677c59023d1f4b35af58c54ff
|
yuniktmr/String-Manipulation-Basic
|
/stringOperations_ytamraka.py
| 1,473
| 4.34375
| 4
|
#CSCI 450 Section 1
#Student Name: Yunik Tamrakar
#Student ID: 10602304
#Homework #7
#Program that uses oython function to perform word count, frequency and string replacement operation
#In keeping with the Honor Code of UM, I have neither given nor received assistance
#from anyone other than the instructor.
#----------------------
#--------------------
#method to get number of words in string
def wordCount(a):
b = a.split(" ")
count = 0
for word in b:
count = count + 1
print("The number of words is {}".format(count))
#method to get the most repititive word
def mostFrequentWord(b):
c = b.split(" ")
dict = {}
#mapping word with its wordcount.
for word in c:
dict[word] = c.count(word)
max = 0
for word in dict:
if (dict[word] > max):
max = dict[word]
for word in dict:
if(dict[word] == max):
print('The word with max occurence is', word)
#method to replace the words in the string
def replaceWord(a, d ,c):
words = a.split(" ")
wordCheck = False
for word in words:
if d == word:
wordCheck = True
if wordCheck:
print("\nOriginal is ",a)
print("The new string after replacement is ",a.replace(d,c))
else:
print("Word not found")
#main method to call the functions
a= input("Enter a word\n")
wordCount(a)
mostFrequentWord(a)
b = input("\nEnter a word you want to be replaced. Separate them with a space\n")
c = b.split(" ")
#invoke the replaceWord method
replaceWord(a, c[0], c[1])
| true
|
5649dabbf39457cb906368ebc3591f964108713c
|
ijoshi90/Python
|
/Python/hacker_rank_staricase.py
| 460
| 4.3125
| 4
|
"""
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 30-Oct-19 at 08:06
"""
# Complete the staircase function below.
"""def staircase(n):
for stairs in range(1, n + 1):
print(('#' * stairs).rjust(n))
"""
def staircase(n):
for i in range(n-1,-1,-1):
for j in range(i):
print (" ",end="")
for k in range(n-i):
print("#",end="")
print("")
if __name__ == '__main__':
staircase(6)
| false
|
75aabcea6f84ac4f13a725080c9858954074472c
|
ijoshi90/Python
|
/Python/maps_example.py
| 1,385
| 4.15625
| 4
|
"""
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 19-12-2019 at 11:07
"""
def to_upper_case(s):
return str(s).upper()
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
#print(to_upper_case("akshay"))
#print_iterator("joshi")
# map() with string
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
# Map iterator with tuple
map_iterator = map(to_upper_case, (1, "ab", "xyz"))
print_iterator(map_iterator)
# Map with list
map_iterator = map(to_upper_case, [1, 2, "Aksh"])
print_iterator(map_iterator)
# Converting map to list, tuple or set
map_iterator = map(to_upper_case, ['a,b', 'b', 'c'])
my_list = list(map_iterator)
print (type(my_list))
print(my_list)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(type(my_set))
print(my_set)
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(type(my_tuple))
print(my_tuple)
# Map with
list_numbers = [1, 2, 3, 4]
mapite = map(lambda x: x * 2, list_numbers)
print(type(mapite))
for i in mapite:
print(i)
# Map with multiple arguments
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
mapitnow = map(lambda x,y : x * y, list_numbers, tuple_numbers)
for each in mapitnow:
print("From multiple arguments in lambda : {}".format(each))
| false
|
bbcdeafd4fdc92f756f93a1a4f990418d295c643
|
ijoshi90/Python
|
/Python/variables_examples.py
| 602
| 4.375
| 4
|
"""
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 26-Sep-19 at 19:24
"""
class Car:
# Class variable
wheels = 2
def __init__(self):
# Instance Variable
self.mileage = 20
self.company = "BMW"
car1 = Car()
car2 = Car()
print ("Wheels : {}".format(Car.wheels))
# Override the value of wheels with 4
Car.wheels = 4
print (car1.company, car1.mileage, car1.wheels)
print (car2.company, car2.mileage, car2.wheels)
# Changing values of Car 2
car2.company = "Mini"
car2.mileage = "25"
car2.wheels = "3"
print (car2.company, car2.mileage, car2.wheels)
| true
|
e41d966e65b740a9e95368d7e5b9286fe587f2cb
|
donwb/whirlwind-python
|
/Generators.py
| 537
| 4.28125
| 4
|
print("List")
# List - collection of values
L = [n ** 2 for n in range(12)]
for val in L:
print(val, end=' ')
print("\n")
print("Generator...")
# Generator - recipie for creating a list of values
G = (n ** 2 for n in range(12))
#generator created here, not up there...
for val in G:
print(val, end=' ')
# Generators can only be used once,
# but they can be stopped/started
GG = (n**2 for n in range(12))
for n in GG:
print(n, end=' ')
if n > 30: break
print("\ndoing something in between")
for n in GG:
print(n, end=' ')
| true
|
d3dd23e8f5e164ca4378e7817f983fca0bf89e1b
|
DylanGuidry/PythonFunctions
|
/dictionaries.py
| 1,098
| 4.375
| 4
|
#Dictionaries are defined with {}
friend = {
#They have keys/ values pairs
"name": "Alan Turing",
"Cell": "1234567",
"birthday": "Sep. 5th"
}
#Empty dictionary
nothing = {}
#Values can be anything
suoerhero = {
"name": "Tony Stark",
"Number": 40,
"Avenger": True,
"Gear": [
"fast car",
"money",
"iron suit",
],
"car": {
"make": "audi",
"model": "R8"
},
"weakness": "his ego"
}
#Get values with key names:
print(suoerhero)
#Get method also works, and can have a "fallback"
print(suoerhero.get("name", "Uknown"))
#Access to all values aof all keys:
print(suoerhero.values())
#Searching for a keys in a dictionary:
if "weakness" in suoerhero:
print("bad guys might win")
else:
print("bad guys go home")
#Updating values:
suoerhero["avenger"] == "fartbutt"
print(suoerhero)
#Deleting from a dictionary:
del suoerhero["gear"]
#Accessing data:
print(suoerhero["name"])
for item in suoerhero["Gear"]:
print(item)
# for key, value in suoerhero:items():
# print(f"Suoerhero's {key} is")
# print(value)
| true
|
109aebf88bfac4cd1e7e097b085d3a3f909923fa
|
helinamesfin/guessing-game
|
/random game.py
| 454
| 4.15625
| 4
|
import random
number = random.randrange(1,11)
str_guess= input("What number do you think it is?")
guess= int(str_guess)
while guess != number:
if guess > number:
print("Not quite. Guess lower.")
elif guess < number:
print("Not quite. Guess higher.")
str_guess= input("What number do you think it is?")
guess= int(str_guess)
if guess==number:
print("Great job! You guessed right.")
| true
|
11c57367b1f26d98d8ccab7ab1fc44fedfe7ca42
|
IceMints/Python
|
/blackrock_ctf_07/Fishing.py
| 1,503
| 4.25
| 4
|
# Python3 Program to find
# best buying and selling days
# This function finds the buy sell
# schedule for maximum profit
def max_profit(price, fee):
profit = 0
n = len(price)
# Prices must be given for at least two days
if (n == 1):
return
# Traverse through given price array
i = 0
while (i < (n - 1)):
# Find Local Minima
# Note that the limit is (n-2) as we are
# comparing present element to the next element
while ((i < (n - 1)) and ((price[i + 1])<= price[i])):
i += 1
# If we reached the end, break
# as no further solution possible
if (i == n - 1):
break
# Store the index of minima
buy = i
buying = price[buy]
i += 1
# Find Local Maxima
# Note that the limit is (n-1) as we are
# comparing to previous element
while ((i < n) and (price[i] >= price[i - 1])):
i += 1
while (i < n) and (buying + fee >= price[i - 1]):
i += 1
# Store the index of maxima
sell = i - 1
selling = price[sell]
print("Buy on day: ",buy,"\t",
"Sell on day: ",sell)
print(buying, selling)
profit += (selling - fee - buying)
print(profit)
# sample test case
# Stock prices on consecutive days
price = [1, 3, 2, 8, 4, 9]
n = len(price)
# Fucntion call
max_profit(price, 2)
| true
|
a1514c507909bd3d00953f7a8c7dd09223779ead
|
VEGANATO/Organizing-Sales-Data-Code-Academy
|
/script.py
| 651
| 4.53125
| 5
|
# Len's Slice: I work at Len’s Slice, a new pizza joint in the neighborhood. I am going to use my knowledge of Python lists to organize some of the sales data.
print("Sales Data")
# To keep track of the kinds of pizzas sold, a list is created called toppings that holds different toppings.
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
# A list called "prices" is created to track how much each pizza costs.
prices = [2, 6, 1, 3, 2, 7, 2]
len(toppings)
num_pizzas = len(toppings)
print("We sell " + str(num_pizzas) + " different kinds of pizza!")
pizzas = list(zip(prices, toppings))
print(pizzas)
| true
|
4c4dcc03d10adde7510c0f9e1c252050b23cad92
|
brennomaia/CursoEmVideoPython
|
/ex039.py
| 724
| 4.15625
| 4
|
from datetime import date
aNasc = int(input('Digite o ano de nascimento: '))
aAtual = date.today().year
idade = aAtual - aNasc
# Menores de idade
if idade < 18:
calc = 18-idade
print('Quem nasceu em {} tem {} anos em {}.\nAinda faltam {} anos para o alistamento militar!\nO alistamento será em {}.'.format(aNasc, idade, aAtual, calc, (aAtual+calc)))
# Maiores
elif idade > 18:
calc = idade-18
print('Quem nasceu em {} tem {} anos em {}\nDeveria ter se alistado há {} anos.\nO alismento foi no ano de {}.'.format(aNasc, idade, aAtual, calc, (aAtual-calc)))
# Iguais a 18 anos
elif idade == 18:
print('Quem nasceu em {} tem {} anos em {}.\nDeve se alistar IMEDIATAMENTE!'.format(aNasc, idade, aAtual))
| false
|
7df64998ce5965ba3fabcbd54cedc6751ca413c8
|
gustavovalverde/intro-programming-nano
|
/Python/Work Session 5/Loop 4.py
| 2,343
| 4.46875
| 4
|
# We now would like to summarize this data and make it more visually
# appealing.
# We want to go through count_list and print a table that shows
# the number and its corresponding count.
# The output should look like this neatly formatted table:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
# Here is our code we have written so far:
import random
# Create random list of integers using while loop --------------------
random_list = []
list_length = 20
while len(random_list) < list_length:
random_list.append(random.randint(0, 10))
# Aggregate the data -------------------------------------------------
count_list = [0] * 11
index = 0
while index < len(random_list):
number = random_list[index]
count_list[number] += 1
index += 1
# Write code here to summarize count_list and print a neatly formatted
# table that looks like this:
"""
number | occurrence
0 | 1
1 | 2
2 | 3
3 | 2
4 | 2
5 | 1
6 | 1
7 | 2
8 | 3
9 | 1
10 | 2
"""
print count_list
print sum(count_list)
# Hint: To print 10 blank spaces in a row, we can multiply a string
# by a number "n" to print this string n number of times:
print "number | ocurrence"
index = 0
while index <= 10:
if index < 10:
print " " * 5 + str(index) + " | " + str(count_list[index] * "*")
else:
print " " * 4 + str(index) + " | " + str(count_list[index] * "*")
index += 1
print ""
print "-----------------"
print "Another approach"
print "-----------------"
print ""
print "number | occurrence"
index = 0
num_len = len("number")
while index < len(count_list):
num_spaces = num_len - len(str(index))
print " " * num_spaces + str(index) + " | " + str(count_list[index])
index = index + 1
# BONUS!
# From your summarize code you just wrote, can you make the table even
# more visual by replacing the count with a string of asterisks that
# represent the count of a number. The table should look like:
"""
number | occurrence
0 | *
1 | **
2 | ***
3 | **
4 | **
5 | *
6 | *
7 | **
8 | ***
9 | *
10 | **
"""
# Congratulations! You just created a distribution table of a list
# of numbers! This is also known as a histogram
| true
|
a9bed93ff1f778a466167b06cbc8afa902dabf9e
|
gustavovalverde/intro-programming-nano
|
/Python/Problem Solving/Calc_age_on_date.py
| 2,173
| 4.21875
| 4
|
# Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isLeapYear(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
def isDateValid(y1, m1, d1, y2, m2, d2):
if y1 < y2:
return True
elif y1 == y2:
if m1 < m2:
return True
elif m1 == m2:
if d1 <= d2:
return True
else:
print "Please enter a valid initial date"
return False
else:
print "Please enter a valid initial date"
return False
def daysinYear(y1, y2):
days = 0
if y1 < y2:
for y in range(y1, y2):
if isLeapYear(y) is True:
days += 366
else:
days += 365
return days
def daysInMonth(m1, d1, m2, d2):
birthDate = sum(daysOfMonths[0: m1 - 1]) + d1
currentDate = sum(daysOfMonths[0: m2 - 1]) + d2
currentDays = currentDate - birthDate
return currentDays
def daysBetweenDates(y1, m1, d1, y2, m2, d2):
finalDays = daysinYear(y1, y2) + daysInMonth(m1, d1, m2, d2)
if ((isLeapYear(y1) is True) and (m1 >= 3)) or (
(isLeapYear(y2) is True) and (m2 >= 3)):
finalDays += 1
print "You are " + str(finalDays) + " days old"
return finalDays
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
((2012, 1, 1, 2012, 3, 1), 60),
((2011, 6, 30, 2012, 6, 30), 366),
((2011, 1, 1, 2012, 8, 8), 585),
((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()
| true
|
1018f2da0c71c59aa9491bf5ab74ab734accb09d
|
adirickyk/course-python
|
/try_catch.py
| 302
| 4.3125
| 4
|
#create new exception
try:
Value = int(input("Type a number between 1 and 10 : "))
except ValueError:
print("You must type a number between 1 and 10")
else:
if(Value > 0) and (Value <= 10):
print("You typed value : ", Value)
else:
print("The value type is incorrect !")
| true
|
17b0b49f8b26d7ddf8f5e7543df2b457494e985e
|
younga7/leap_year
|
/alex_young_hw2.py
| 550
| 4.1875
| 4
|
# CS362 HW2
# Alex Young
# 1/26/2021
# Run this file using python3 alex_young_hw2.py
# This program checks if a year is a leap year with error handling
c = 0
while c == 0:
try:
n = int (input('Enter year: '))
c = 1
except:
print ('Error, input is not valid, try again!')
if n % 4 == 0:
if n % 400 == 0:
print (n, 'is a leap year.')
else:
if n % 100 == 0:
print (n, 'is not a leap year.')
else:
print (n, 'is a leap year.')
else:
print (n, 'is not a leap year.')
| false
|
e8368e5d17e8682b1f8d59ab9466995584747627
|
castacu0/codewars_db
|
/15_7kyu_Jaden Casing Strings.py
| 1,069
| 4.21875
| 4
|
from string import capwords
"""
Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you'll have to capitalize each word, check out how contractions are expected to be in the example below.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
def to_jaden_case(string):
# ...
"""
def to_jaden_case(string):
return print(" ".join(i.capitalize() for i in string.split()))
# split() makes a list. any whitespace is by default
# join makes a str again and takes an iterable
# Best practices
# from string import capwords
def to_jaden_case(string):
return string.capwords(string)
to_jaden_case("kou liu d'wf")
| true
|
9940f02410122ddc6d0a9394479576fa0fb1a4fb
|
marizmelo/udacity
|
/CS262/lesson3/mapdef.py
| 267
| 4.125
| 4
|
def mysquare(x): return x * x
print map( mysquare, [1, 2, 3, 4, 5])
print map( lambda(x): x * x, [1, 2, 3, 4, 5]) # this use of lambda is sometimes called anonymous function
print [len(x) for x in ["hello", "my", "friends"]]
print [x * x for x in [1, 2, 3, 4, 5]]
| true
|
1451fa9c04e5ce8636d023001c663fb6a988b0bf
|
wajishagul/wajiba
|
/Task4.py
| 884
| 4.375
| 4
|
print("*****Task 4- Variables and Datatype*****")
print("Excercise")
print("1. Create three variables (a,b,c) to same value of any integer & do the following")
a=b=c=100
print("i.Divide a by 10")
print(a,"/",10,"=",a/10)
print("ii.Multiply b by 50")
print(b,"*",50,"=",b*50)
print("iii.Add c by 60")
print(c,"+",50,"=",b+50)
print("2.Create a String variable of 5 characters and replace the 3rd character with G")
str="ABCDE"
print("Length of the string is:",len(str))
s1="C"
s2="G"
print("new string after replacement:",str.replace(s1,s2))
print("3.Create two values (a,b) of int,float data type & convert the vise versa")
a,b=200,55.5
print("a=",a,"b=",b)
a=float(a)
b=int(b)
print("value of a and b after type conversion:")
print("a=",a,"b=",b)
print("data type of a after conversion:",type(a))
print("data type of b after conversion:",type(b))
print("-----Task 4 Completed-----")
| true
|
e4849cacfa472b48f1fdb666339c05655b491ffa
|
vspatil/Python3-HandsOn
|
/Chapter_6_UserInputs_whileLoops/Exercise_7.5.py
| 1,580
| 4.15625
| 4
|
"""prompt = "Enter a series of toppings : "
message = ""
while message != 'quit':
message = input(prompt)
if message == 'quit':
break
else:
print("We will add " + message + " to the pizza!")"""
"""
age=''
while age != 'quit':
age = input("Enter your age : ")
if age == 'quit':
break
elif age < 3:
print("The ticket is free!")
elif age > 3 and age < 12:
print("The ticket costs $10!")
else:
print("The ticket costs $15!")
"""
#using condition in the while stmt
"""age=''
while age != 'quit':
age = input("Enter your age : ")
if age == 'quit':
break
elif age <= 3:
print("The ticket is free!")
elif age > 3 and age <= 12:
print("The ticket costs $10!")
elif age > 12 :
print("The ticket costs $15!")"""
#Using active variable to control the loop
"""active = True
while active:
age = input("Enter your age : ")
if age == 'quit':
active = False
elif age <= 3:
print("The ticket is free!")
elif age > 3 and age <= 12:
print("The ticket costs $10!")
else:
print("The ticket costs $15!")"""
#using break stmt to exit the loop
"""
age=''
while age != 'quit':
age = input("Enter your age : ")
if age == 'quit':
break
elif age <= 3:
print("The ticket is free!")
elif age > 3 and age <= 12:
print("The ticket costs $10!")
else:
print("The ticket costs $15!")"""
# loop that never ends or infinte loop
x = 1
while x <= 5:
print(x)
# x=x+1
| false
|
fc70c57920b9e56aae696754aa6ff347e7971aba
|
Jackroll/aprendendopython
|
/exercicios_udemy/desafio_contadores_41.py
| 375
| 4.3125
| 4
|
"""fazer uma iteração para gerar a seguinte saída:
0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
"""
# método 01 - usando while
i = 0
j = 10
while i <= 8:
print(i, j)
i = i+1
j = j-1
print('------------------')
# método 02 - usando for com enumerate e range
for r, i in enumerate(range(10,1, -1)): #enumerate conta quantas vezes houve a iteração
print(r, i)
| false
|
972a883e10eda7523b400da701755868927938e8
|
Jackroll/aprendendopython
|
/agregacao/classes.py
| 982
| 4.3125
| 4
|
""" Agregação é quando uma classe pode existir sozinha, no entanto ela depende de outra classe para funcionar corretamente
por exemplo: A Classe 'Carrinho de compras' pode existir sózinha, mas depende da classe 'Produtos' para pode funcionar corretamente
pois seus métodos dependem da classe produto.
E classe Produtos por sua vez existe sozinha e não depende em nada da classe Carrinho de compras
"""
class CarrinhoDeCompras:
def __init__(self):
self.produtos = []
def inserir_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
i = 0
for produto in self.produtos:
i = i+1
print(f'Item : {i} - {produto.nome} R$ {produto.valor}')
def soma_total(self):
total = 0
for produto in self.produtos:
total += produto.valor
return total
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
| false
|
0c1622a3e7497ab2ef4a8274bf3cae27492824df
|
Jackroll/aprendendopython
|
/exercicios/PythonBrasilWiki/exe003_decisao.py
| 490
| 4.1875
| 4
|
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
letra = str(input('Digite F ou M :'))
letra_upper = letra.upper() #transforma a string para Uppercase para não haver erro em caso de digitação da letra em minusculo
if letra_upper == 'F':
print(f'{letra_upper} - é feminino')
elif letra_upper == 'M' :
print(f'{letra_upper} - é masculino')
else :
print ('Sexo invalido')
| false
|
55dace0617bee83c0abef6e191326eb87f464c6a
|
Jackroll/aprendendopython
|
/exercicios_udemy/Programacao_Procedural/arquivos/arquivo_aula_83.py
| 1,867
| 4.125
| 4
|
file = open('abc.txt', 'w+') #cria o arquivo 'abc.txt' em modo de escrita w+ apaga tudo que ta no arquivo antes de iniciar a escrita
file.write('linha 1\n') #escreve varias linhas no arquivo
file.write('linha 2\n')
file.write('linha 3\n')
file.write('linha 4\n')
print('-=' * 50)
file.seek(0,0) #coloca o cursor no inicio do arquivo para fazer a leitura
print('Lendo o arquivo :')
print(file.read()) #faz a leitura do arquivo
print('-=' * 50)
file.seek(0, 0) #coloca o cursor no inicio do arquivo para fazer a leitura
print(file.readlines()) #gera uma lista com as linhas do arquivo
print('-=' * 50)
file.seek(0, 0)
for linha in file.readlines(): #lendo atraves de um for
print(linha, end='') #end = '' retira a quebra de linha
file.close() #fecha o arquivo
print('-=' * 50)
with open ('abc2.txt', 'w+') as file: #utilizando o with não precisar mandar fechar o arquivo com file.close()
file.write('Arquivo 2 - linha 1\n') #escreve varias linhas no arquivo
file.write('Arquivo 2 - linha 2\n')
file.write('Arquivo 2 - linha 3\n')
file.write('Arquivo 2 - linha 4\n')
file.seek(0)
print(file.read())
print('-=' * 50)
with open ('abc3.txt', 'a+') as file: #Adicionando linhas ao arquivo, o a+ manda o cursor para o final do arquivo
file.write('Adcicionando linhas 1\n')
file.write('Adcicionando linhas 2\n')
file.write('Adcicionando linhas 3\n')
file.write('Adcicionando linhas 4\n')
file.write('Adcicionando linhas 5\n')
file.seek(0)
print(file.read())
print('-=' * 50)
with open ('abc3.txt', 'r+') as file: #lendo oque esta dentro do arquivo e mostrando na tela atraves do r+
print(file.read())
| false
|
2f18dce6db44f8cbde41683bccd3f16611aace20
|
Jackroll/aprendendopython
|
/exercicios_udemy/Modulos_uteis/Json/json_main.py
| 978
| 4.34375
| 4
|
"""
trabalhando com json
Documentação : https://docs.python.org/3/library/json.html
json -> python = loads / load
python -> json = dumps / dump
"""
from aprendendopython.exercicios_udemy.Modulos_uteis.Json.dados import *
import json
# convertendo dicionário para json
dados_json = json.dumps(clientes_dicionario, indent =4) #usado ident=4 para dar a correta identação
print(dados_json)
#convertendo de json para pyhton (dicionário)
print('xx'*50)
dicionario_json = json.loads(clientes_json)
for v,j in dicionario_json.items():
print(v)
print(j)
print('xx'*50)
#convertendo, criando e gravando um dicionário em json
with open('clientes.json', 'w') as arquivo:
json.dump(clientes_dicionario, arquivo, indent=4)
print('Conversão efetuada !')
print('xx'*50)
#convertendo e lendo um json em dicionário
with open('clientes.json', 'r') as arquivo:
dados = json.load(arquivo)
for chave, valor in dados.items():
print(chave)
print(valor)
| false
|
1b139816100f6157c1492c44eb552c096fb8b32f
|
verma-rahul/CodingPractice
|
/Medium/InOrderTraversalWithoutRecursion.py
| 2,064
| 4.25
| 4
|
# Q : Given a Tree, print it in order without Traversal
# Example: 1
# / \
# 2 3 => 4 2 5 1 3
# / \
# 4 5
import sys
import random
# To set static Seed
random.seed(1)
class Node():
"""
Node Struct
"""
def __init__(self,val=None):
self.val=val
self.right=None
self.left=None
class BinaryTree():
def __init__(self,root=None):
self.root=root
def make_random_balnaced_tree(self,size):
"""
Constructs a random Balanced Tree &
prints as an Array
Ex: [1,2,3,4,5] => 1
/ \
2 3
/ \
4 5
"""
val=random.randint(0, 100)
self.root=Node(val)
stack=[self.root];size=size-1;arr_tree=[val]
while size>0:
node=stack.pop(0)
val=random.randint(0,100)
left=Node(val)
arr_tree.append(val)
node.left=left
stack.append(left)
size=size-1
if size>0:
val=random.randint(0,100)
right=Node(val)
node.right=right
arr_tree.append(val)
stack.append(right)
size=size-1
print("Balanced Tree as Array: ", arr_tree)
def print_inorder(self):
"""
Prints the Tree Inorder
"""
stack=[self.root]
node=self.root
print("Inorder Traversal of Tree: ")
while len(stack)>0:
if node!=None and node.left!=None:
stack.append(node.left)
node=node.left
else:
poped=stack.pop()
print(poped.val)
node=poped.right
if node!=None:
stack.append(node)
def main(args):
tree=BinaryTree()
tree.make_random_balnaced_tree(10)
tree.print_inorder()
if __name__=='__main__':
main(sys.argv[1:])
| true
|
81eba7d41e0f8962458519751b02c21dc52c88a5
|
Sreenidhi220/IOT_Class
|
/CE8OOPndPOP.py
| 1,466
| 4.46875
| 4
|
#Aum Amriteshwaryai Namah
#Class Exercise no. 8: OOP and POP illustration
# Suppose we want to model a bank account with support for 'deposit' and 'withdraw' operations.
# One way to do that is by Procedural Programming
# balance = 0
# def deposit(amount):
# global balance
# balance += amount
# return balance
# def withdraw(amount):
# global balance
# balance -= amount
# return balance
#The above example is good enough only if we want to have just a single account.
#Things start getting complicated if we want to model multiple accounts.
# Have multiple accounts as list or dictionary or separate variables?
def deposit(name, amount):
Accounts[name] += amount
return Accounts[name]
def withdraw(name, amount):
Accounts[name] -= amount
return balance
Accounts = {}
Accounts["Arya"] = 2000
Accounts["Swathi"] = 2000
Accounts["Urmila"] = 2000
print("Arya's balance is %d" % deposit("Arya", 200))
class BankAccount:
def __init__(self):
self.balance = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
Arya = BankAccount()
Swathi = BankAccount()
Urmila = BankAccount()
Swathi.deposit(400)
Urmila.deposit(700)
print(Urmila.balance)
#Referece :https://anandology.com/python-practice-book/object_oriented_programming.html
| true
|
c79f3df4eb01631e73363cd6e5e6546e15380b30
|
edran/ProjectsForTeaching
|
/Classic Algorithms/sorting.py
| 2,073
| 4.28125
| 4
|
"""
Implement two types of sorting algorithms: Merge sort
and bubble sort.
"""
def mergeMS(left, right):
"""
Merge two sorted lists in a sorted list
"""
llen = len(left)
rlen = len(right)
sumlist = []
while left != [] and right != []:
lstack = left[0]
while right != []:
rstack = right[0]
if lstack < rstack:
sumlist.append(lstack)
left.pop(0)
break
else:
sumlist.append(rstack)
right.pop(0)
if left == []:
sumlist += right
else:
sumlist += left
return sumlist
def mergeSort(l):
"""
Divide the unsorted list into n sublists, each containing 1
element (a list of 1 element is considered sorted). Repeatedly
merge sublists to produce new sorted sublists until there is only
1 sublist remaining. This will be the sorted list.
"""
# I actually implemented without reading any of the formal algorithms,
# so I'm not entirely sure I did a good job. I have to read up and compare
# my solution with a standard one.
if len(l) == 1:
return l
split = len(l) / 2
a = mergeMS(mergeSort(l[:split]), mergeSort(l[split:]))
return a
def bubbleSort(l):
"""
simple sorting algorithm that works by repeatedly stepping through
the list to be sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order
"""
n = list(l)
swapped = True
k = len(n) - 1
while swapped:
swapped = False
i = k
while i > 0:
u = n[i]
d = n[i - 1]
if u < d:
n[i] = d
n[i -1] = u
swapped = True
i -= 1
return n
def main():
t = raw_input("List of numbers> ")
t = eval("[" + t + "]")
r = mergeSort(t)
b = bubbleSort(t)
print "MergeSort: ", r
print "BubbleSort: ", b
if __name__ == "__main__":
main()
| true
|
4b41489f518c4cbca1923440c3416cdfef345f88
|
edran/ProjectsForTeaching
|
/Numbers/factprime.py
| 657
| 4.28125
| 4
|
"""
Have the user enter a number and find all Prime Factors (if there
are any) and display them.
"""
import math
import sys
def isPrime(n):
for i in range(2,int(math.sqrt(n)) + 1): # premature optimization? AH!
if n % i == 0:
return False
return True
def primeFacts(n):
l = []
for i in range(1,int(math.ceil(n/2))+1):
if n % i == 0 and isPrime(i):
l.append(i)
if n not in l and isPrime(n):
l.append(n) # for prime numbers
return l
def main():
i = int(raw_input("Factors of which number? "))
print primeFacts(i)
if __name__ == "__main__":
while 1:
main()
| true
|
1ab87bc5c2863c90dea96185241b0869f2259f30
|
sonusbeat/intro_algorithms
|
/Recursion/group_exercise2.py
| 489
| 4.375
| 4
|
""" Group Exercise Triple steps """
def triple_steps(n):
"""
A child is running up a staircase with n steps and can hop
either 1 step, 2 steps, or 3 steps at a time.
Count how many possible ways the child can run up the stairs.
:param n: the number of stairs
:return: The number of possible ways the child can run up the stairs.
"""
if n <= 2:
return n
return triple_steps(n-1) + triple_steps(n-2) + triple_steps(n-3)
print(triple_steps(3))
| true
|
916e2aa4bc23a717c6ba3d196b26cb44a02e6c78
|
sonusbeat/intro_algorithms
|
/7.Loops/01.exercise.py
| 469
| 4.21875
| 4
|
# Exercises
# 1. Write a loop to print all even numbers from 0 to 100
# for num in range(101):
# if num % 2 == 0:
# print(num)
# list comprehension
# [print(i) for i in range(101) if i % 2 == 0]
# 2. Write a loop to print all even numbers from 0 to 100
# for i in range(0, 101):
# if i % 2 == 1:
# print(i, end=" ")
# print()
# print("*" * 40)
# for ch in "hello":
# print(ch)
# for ch in ["hello", "Hola", "Konichiwa"]:
# print(ch)
| false
|
ec45e6109ddd2f2f3b9984404f015b828f0ca4f1
|
sonusbeat/intro_algorithms
|
/SearchingAlgorithms/2.binary_search.py
| 1,037
| 4.28125
| 4
|
"""
Binary Search
- how you look up a word in a dictionary or a contact in phone book.
* Items have to be sorted!
"""
alist = [
"Australia", "Brazil", "Canada", "Denmark",
"Ecuador", "France", "Germany", "Honduras",
"Iran", "Japan", "Korea", "Latvia",
"Mexico", "Netherlands", "Oman", "Philippines",
"Qatar", "Russia", "Spain", "Turkey",
"Uruguay", "Vietnam", "Wales", "Xochimilco", "Yemen", "Zambia"
]
def binary_search(collection, target):
start = 0
end = len(collection) - 1
steps = 0
while start <= end:
mid = (start + end) // 2
steps += 1
if collection[mid] == target:
steps_message = "s" if steps > 1 else ""
return F"\"{collection[mid]}\" is at position {str(mid)} and it took {str(steps)} step{steps_message}"
elif collection[mid] < target:
start = mid + 1
else:
end = mid - 1
return F"Your country \"{target}\" is not on the list!"
print(binary_search(alist, input("What's your country? ")))
| true
|
4bb0736d12da8757a76839f242d902fb08afc461
|
vamsikrishna6668/python
|
/class2.py
| 559
| 4.3125
| 4
|
# w.a.p on class example by static method and static variables and take a local variable also print without a reference variable?
class student:
std_idno=101
std_name="ismail"
@staticmethod
def assign(b,c):
a=1000
print("The Local variable value:",a)
print("The static variable name:",student.std_name)
print("The static variable idno: ",student.std_idno)
print("Iam a static method")
print(b*c)
#call
student.assign(50,60)
print(student().std_idno)
print(student().std_name)
| true
|
3a5908b10e1eb651085ac4dee75e344b8bb9cc83
|
singzinc/PythonTut
|
/basic/tut2_string.py
| 785
| 4.3125
| 4
|
# ====================== concat example 1 ===================
firstname = 'sing'
lastname = 'zinc '
print(firstname + ' ' + lastname)
print(firstname * 3)
print('sing' in firstname)
# ====================== concat example 2 ===================
foo = "seven"
print("She lives with " + foo + " small men")
# ====================== Concat example 3 ===================
x = 'apples'
y = 'lemons'
z = 'In the basket are %s and %s' % (x,y)
print(z)
#=============== example 2 ===================
firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)
# this is incorrect example
# x = 'Chris' + 2
# print(x)
x = 'Chris' + str(2)
print(x)
| true
|
590b4ee6898e35551b8059ef9256d307a8bcce59
|
markvakarchuk/ISAT-252
|
/Python/Rock, Paper, Scissors - Linear.py
| 1,891
| 4.1875
| 4
|
import time
import random
# defining all global variables
win_streak = 0 # counts how many times the user won
play_again = True # flag for if another round should be played
game_states = ["rock", "paper", "scissors"]
#printing the welcome message
print("Welcome to Rock, Paper, Scissors, lets play!")
time.sleep(0.5)
input("Press Enter to continue... \n")
# this function is promted at the beginning and after every round if the user won
# def play_round():
while play_again:
# define local variables
user_move = input("Enter 'rock','paper', or 'scissors': ")
# computers turn to generate move
comp_move = random.choice(game_states)
# see if user won
# user can win with 3 different combinations
# 1) Scissors beats Paper5
# 2) Rock beats Scissors
# 3) Paper beats Rock
if comp_move == user_move: # first check if it was a time
print("Tie! Go again! \n")
play_again = True
elif comp_move == 'paper' and user_move == 'scissors': # check for combo 1
print("Scissors beats paper! Go again! \n")
win_streak += 1
play_again = True
elif comp_move == 'scissors' and user_move == 'rock': # check for combo 2
print("Rock beats scissors! Go again! \n")
win_streak += 1
play_again = True
elif comp_move == 'rock' and user_move == 'paper': # check for combo 3
print("Paper beats rock! Go again! \n")
win_streak += 1
play_again = True
else: # means computer won, print how computer won and end round
print("\n" + str(comp_move) + " beats your move of " + str(user_move))
print("Better luck next time! \n")
play_again = False
print("********************************")
print("Win streak: " + str(win_streak))
print("********************************")
print("\n")
print("Thanks for playing!")
print("\n")
print("\n")
| true
|
c3f3e836042df5e06d1f19b26fda1197726d2030
|
mikofski/poly2D
|
/polyDer2D.py
| 2,204
| 4.25
| 4
|
import numpy as np
def polyDer2D(p, x, y, n, m):
"""
polyDer2D(p, x, y, n, m)
Evaluate derivatives of a 2-D polynomial using Horner's method.
Evaluates the derivatives of 2-D polynomial `p` at the points
specified by `x` and `y`, which must be the same dimensions. The
outputs `(fx, fy)` will have the same dimensions as `x` and `y`.
The order of `x` and `y` are specified by `n` and `m`, respectively.
Parameters
----------
p : array_like
Polynomial coefficients in order specified by polyVal2D.html.
x : array_like
Values of 1st independent variable.
y : array_like
Values of 2nd independent variable.
n : int
Order of the 1st independent variable, `x`.
m : int
Order of the 2nd independent variable, `y`.
Returns
-------
fx : ndarray
Derivative with respect to x.
fy : ndarray
Derivative with respect to y.
See Also
--------
numpy.polynomial.polynomial.polyval2d : Evaluate a 2-D polynomial at points (x, y).
Example
--------
>>> print polyVal2D([1,2,3,4,5,6],2,3,2,1)
>>> (39, 11)
>>> 1*2*2*3 + 2*3 + 4*2*2 + 5
39
>>> 1*(2**2) + 2*2 + 3
11
>>> print polyVal2D([1,2,3,4,5,6,7,8,9],2,3,2,2)
>>> (153, 98)
>>> 1*2*2*(3**2) + 2*(3**2) + 4*2*2*3 + 5*3 + 7*2*2 + 8
153
>>> 1*2*(2**2)*3 + 2*2*2*3 + 3*2*3 + 4*(2**2) + 5*2 + 6
98
"""
# TODO: check input args
p = np.array(p)
x = np.array(x)
y = np.array(y)
n = np.array(n)
m = np.array(m)
# fx = df/dx
fx = n * p[0]
for ni in np.arange(n - 1):
fx = fx * x + (n - ni - 1) * p[1 + ni]
for mi in np.arange(m):
mj = (n + 1) * (mi + 1)
gx = n * p[mj]
for ni in np.arange(n - 1):
gx = gx * x + (n - ni - 1) * p[mj + 1 + ni]
fx = fx * y + gx
# fy = df/dy
fy = p[0]
for ni in np.arange(n):
fy = fy * x + p[1 + ni]
fy = m * fy
for mi in np.arange(m - 1):
mj = (n + 1) * (mi + 1)
gy = p[mj]
for ni in np.arange(n):
gy = gy * x + p[mj + 1 + ni]
fy = fy * y + (m - mi - 1) * gy
return fx, fy
| true
|
4f6c341cb5903f526d9780af9d1aa2f8b2b87e35
|
JakeBednard/CodeInterviewPractice
|
/6-1B_ManualIntToString.py
| 444
| 4.125
| 4
|
def int_to_string(value):
"""
Manually Convert String to Int
Assume only numeric chars in string
"""
is_negative = False
if value < 0:
is_negative = True
value *= -1
output = []
while value:
value, i = divmod(value, 10)
output.append((chr(i + ord('0'))))
return ('-' if is_negative else '') + "".join(reversed(output))
print(int_to_string(133))
print(int_to_string(-133))
| true
|
5573f3eeb4a16263a4204b4ef1058858646b9873
|
sptechguru/Python-Core-Basics-Programs
|
/oops/multipleinhertance.py
| 1,101
| 4.1875
| 4
|
import time
class phone:
def __init__(self,brand,model_name,price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
return f"{self.brand}{self.model_name} {self.price}"
# multiple inheritance in class phone is Dervive Class & Main Class
# smartphone is child Class
class Smartphone(phone):
def __init__(self,brand,model_name,price,ram,internal_memory,rear_camera):
super().__init__(brand,model_name,price)
self.ram =ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
def last_name(self):
return f"{self.brand}{self.model_name} {self.price} {self.ram}{self.internal_memory} {self.rear_camera}"
phone = phone(' Nokia ','110',1000)
smartphone = Smartphone(' oneplus :','5+ :','30000 :' ,'6Gb :','64GB :','20Mp')
print(phone.full_name())
print()
time.sleep(2)
print(smartphone.last_name())
# print(smartphone.full_name()+ f" And Price is {smartphone.price}{smartphone.ram} "
# f"{smartphone.internal_memory}{smartphone.rear_camera}")
| false
|
7d26e6913a4b0024fa1082e5f3ea7c9ff0cbc50b
|
Azab007/Data-Structures-and-Algorithms-Specialization
|
/algorithms on strings/week2/suffix_array/suffix_array.py
| 572
| 4.21875
| 4
|
# python3
import sys
from collections import defaultdict
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffix = []
for i in range(len(text)):
suffix.append((text[i:], i))
suffix.sort()
for arr, indx in suffix:
print(indx, end=' ')
if __name__ == '__main__':
text = sys.stdin.readline().strip()
build_suffix_array(text)
| true
|
eba2ffaeaf9b38da5f9ae60b785f406070267873
|
nuggy875/tensorflow-of-all
|
/7. gradient descent algorithm.py
| 1,147
| 4.125
| 4
|
# 7. gradient descent algorithm
# 경사 하강법 이해를 목적으로 한다.
import tensorflow as tf
# 그래프 빌드 #
# 데이터
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# 변하는 값
W = tf.Variable(tf.random_normal([1]), name='weight')
# 데이터를 담는 값 'feed_dict'
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * W --> simplify the numerical expression
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session
# Minimize : Gradient Descent using derivative: W -= Learning_rate * derivative
# gradient = d ( cost ) / dw
# W = W - rate * d/dw( cost )
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
# assign : 연산 후 새 값을 재 설정하는 operator
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(21):
sess.run(update, feed_dict={X: x_data, Y: y_data})
print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
| false
|
01aaf5aec0ca74fdfec8f95d7137979737c313a4
|
JMH201810/Labs
|
/Python/p01320g.py
| 1,342
| 4.5
| 4
|
# g. Album:
# Write a function called make_album() that builds a dictionary describing
# a music album. The function should take in an artist name and an album
# title, and it should return a dictionary containing these two pieces of
# information. Use the function to make three dictionaries representing
# different albums. Print each return value to show that the dictionaries
# are storing the album information correctly.
# Add an optional parameter to make_album() that allows you to store the
# number of tracks on an album. If the calling line includes a value for
# the number of tracks, add that value to the album's dictionary.
# Make at least one new function call that includes the number of tracks on
# an album.
def make_album(artist_name, album_title, nTracks=''):
if nTracks:
d = {'artist_name':artist_name,
'album_title':album_title,
'nTracks':nTracks}
else:
d = {'artist_name':artist_name,
'album_title':album_title}
return d
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3')
print ('\n', d1, '\n', d2, '\n', d3)
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3', 7)
print ('\n', d1, '\n', d2, '\n', d3)
| true
|
64a30bf626d62b29ae78c9ac9435dc1ca5c929f3
|
JMH201810/Labs
|
/Python/p01320L.py
| 568
| 4.15625
| 4
|
# l. Sandwiches:
# Write a function that accepts a list of items a person wants on a sandwich.
# The function should have one parameter that collects as many items as the
# function call provides, and it should print a summary of the sandwich that
# is being ordered.
# Call the function three times, using a different number
# of arguments each time.
def toppings(*thing):
print ()
for t in thing:
print('-', t)
toppings('butter', 'air', 'salt')
toppings('worms', 'sand', 'rocks', 'tahini')
toppings('wallets', 'staplers')
| true
|
ae64e924773c4243da27404de13e74ce2e973b56
|
JMH201810/Labs
|
/Python/p01310j.py
| 631
| 4.59375
| 5
|
# Favorite Places:
# Make a dictionary called favorite_places.
# Think of three names to use as keys in the dictionary, and store one to
# three favorite places for each person.
# Loop through the dictionary, and print each person's name and their
# favorite places.
favorite_places = {'Alice':['Benton Harbor', 'Alice Springs', 'Utah'],
'Brenda':['Ann Arbor', 'Detroit', 'Eau Claire'],
'Charles':['under the couch', 'VBISD', 'Michigan']}
for person,placeList in favorite_places.items():
print("\n",person,"'s favorite places are:", sep='')
for place in placeList:
print(place)
| true
|
d6c1fa3d43547d59fa10a9e6d1e51e169dac8a18
|
JMH201810/Labs
|
/Python/p01210i.py
| 924
| 4.875
| 5
|
# Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza
# names in a list, and then use a for loop to print the name of each pizza.
pizzaTypes = ['Round', 'Edible', 'Vegetarian']
print("Pizza types:")
for type in pizzaTypes:
print(type)
# i. Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like I like pepperoni
# pizza.
print("Using a sentence:")
for type in pizzaTypes:
print("I like",type,"pizza.")
# ii. Add a line at the end of your program, outside the for loop, that states how
# much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as I
# really love pizza!
print ("I really love pizza!")
| true
|
e86600435612f88fbf67e3e805f0e21e6f0f51f8
|
23-Dharshini/priyadharshini
|
/count words.py
| 253
| 4.3125
| 4
|
string = input("enter the string:")
count = 0
words = 1
for i in string:
count = count+1
if (i==" "):
words = words+1
print("Number of character in the string:",count)
print("Number of words in the string:",words)
| true
|
1622d36817330cc707a1a4e4c4e52810065aa222
|
Whatsupyuan/python_ws
|
/4.第四章-列表操作/iterator_044_test.py
| 1,306
| 4.15625
| 4
|
# 4-10
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("The first three items in the list are" )
print(players[:3])
print()
# python3 四舍五入 问题
# 官方文档写了,round(number[, ndigits]) values are rounded to the closest multiple of 10 to the power minus ndigits;
# if two multiples are equally close, rounding is done toward the even choice
# (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
# 就是说round(1/2)取离它最近的整数,如果2个数(0和1)离它一样近,则取偶数(the even choice)。
# 因此round(1.5)=2, round(2.5)=2, round(3.5)=4, round(4.5)=4。
# http://www.cnblogs.com/lxmwb/p/7988913.html
# 4-10-2 打印列表中间的3个元素
print("Three items from the middle of the list are:")
import decimal
half_length = len(players)
a = decimal.Decimal(half_length)/2
decimal.getcontext().rounding = decimal.ROUND_UP
half_num = round(a,0)
print(players[int(half_num-2):int(half_num+1)])
print()
# 4-10-3 打印列表尾部的3个元素
print("The last three items in the list are:")
print(players[half_length-3:])
# 4-11-1
pizzas = ["one_pizza" , "two_pizza" , "thress_pizza"]
friend_pizzas = pizzas[:]
pizzas.append("none-pizza");
print(pizzas)
print(friend_pizzas)
for p in pizzas:
print(p)
| true
|
134d4811b1e629067e1f711f145fff9b889617aa
|
Whatsupyuan/python_ws
|
/6.第六章-字典(Dictionary)/06_dic_0603_iteratorDictionary.py
| 734
| 4.28125
| 4
|
favorite_num_dic = {"Kobe": 24, "Jame": 23, "Irving": 11}
# 自创方法,类似于Map遍历的方法
for num in favorite_num_dic:
print(num + " " + str(favorite_num_dic[num]))
print()
# 高级遍历方法 items() 方法
print(favorite_num_dic.items())
for name,number in favorite_num_dic.items():
print(name + " " + str(number))
print()
# key获取 字典 中的所有key --- keys()
# 如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages: ,输出将不变。
for key in favorite_num_dic.keys():
print(key)
print()
# 字典获取所有的 value --- values()
# 类似于 Map.keys() 与 Map.values()
vals = favorite_num_dic.values()
for val in vals:
print(val)
| false
|
3d999ca8f12348a3cb229be5af0f9cdba4ccc0b2
|
ArvindAROO/algorithms
|
/sleepsort.py
| 1,052
| 4.125
| 4
|
"""
Sleepsort is probably the wierdest of all sorting functions
with time-complexity of O(max(input)+n) which is
quite different from almost all other sorting techniques.
If the number of inputs is small then the complexity
can be approximated to be O(max(input)) which is a constant
If the number of inputs is large then the complexity is
approximately O(n)
This function uses multithreading a kind of higher order programming
and calls n functions, each with a sleep time equal to its number.
Hence each of the functions wake in Sorted form
But this function is not stable for very large values
"""
from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v:
mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
sorted_x=sleepsort(x)
print(sorted_x)
| true
|
77d4482ba88837a3bca6280a08320a2b0eb70aac
|
KD4N13-L/Data-Structures-Algorithms
|
/Sorts/merge_sort.py
| 1,591
| 4.21875
| 4
|
def mergesort(array):
if len(array) == 1:
return array
else:
if len(array) % 2 == 0:
array1 = []
half = (int(len(array) / 2))
for index in range(0, half):
array1.append(array[index])
array2 = []
for index in range(half, len(array)):
array2.append(array[index])
array1 = mergesort(array1)
array2 = mergesort(array2)
return merge(array1, array2)
else:
array1 = []
half = (int((len(array) + 1) / 2))
for index in range(0, half):
array1.append(array[index])
array2 = []
for index in range(half, len(array)):
array2.append(array[index])
array1 = mergesort(array1)
array2 = mergesort(array2)
return merge(array1, array2)
def merge(array1, array2):
temp_array = []
while array1 and array2:
if array1[0] > array2[0]:
temp_array.append(array2[0])
array2.pop(0)
else:
temp_array.append(array1[0])
array1.pop(0)
while array1:
temp_array.append(array1[0])
array1.pop(0)
while array2:
temp_array.append(array2[0])
array2.pop(0)
return temp_array
def main():
array = input("Enter the number of array members, seperated by a coma")
array = array.split(',')
length = len(array)
for item in range(length):
array[item] = int(array[item])
print(mergesort(array))
main()
| false
|
911d4753a01ab601346e3bc2f3b483a61d21c7ae
|
bspindler/python_sandbox
|
/classes.py
| 1,180
| 4.3125
| 4
|
# A class is like a blueprint for creating objects. An object has properties and methods (functions)
# associated with it. Almost everything in Python is an object
# Create Class
class User:
# constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def increase_age(self):
self.age += 1
# Extends class
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
# Init user object
brad = User('Brad Traversy', 'brad@gmail.com', 37)
print(type(brad), brad)
janet = Customer('Janet Z', 'janet@gmail.com', 57)
print(type(janet), janet)
janet.set_balance(500)
print(janet.greeting())
# Access properties
print(brad.name, brad.email, brad.age)
# Run method on class
print(brad.greeting())
brad.increase_age()
print(brad.greeting())
| true
|
c246c6a153b6bc176ed0e279a60d32f1b2100711
|
ntkawasaki/complete-python-masterclass
|
/7: Lists, Ranges, and Tuples/tuples.py
| 1,799
| 4.5625
| 5
|
# tuples are immutable, can't be altered or appended to
# parenthesis are not necessary, only to resolve ambiguity
# returned in brackets
# t = "a", "b", "c"
# x = ("a", "b", "c") # using brackets is best practice
# print(t)
# print(x)
#
# print("a", "b", "c")
# print(("a", "b", "c")) # to print a tuple explicitly include parenthesis
# tuples can put multiple data types on same line
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975
bad = "Bad Company", "Bad Company", 1974
budgie = "Nightflight", "Budgie", 1981
imelda = "More Mayhem", "Emilda Way", 2011
metallica = "Ride the Lightening", "Metallica", 1984
# print(metallica)
# print(metallica[0]) # print one part of tuple
# print(metallica[1])
# print(metallica[2])
# cant change underlying tuple, immutable object
# metallica[0] = "Master of Puppets"
# ca get around this like this though
imelda = imelda[0], "Emilda Way", imelda[2]
# python also evaluates the right side of this expression first, then assigns it to a new variable "imelda"
# creates a new tuple
print(imelda)
# can alter a list though
metallica2 = ["Ride the Lightening", "Metallica", 1984]
print(metallica2)
metallica2[0] = "Master of Puppets"
print(metallica2)
print()
# metallica2.append("Rock")
# title, album, year = metallica2
# print(title)
# print(album)
# print(year)
# will draw a too many values to unpack error because not enough variables assigned
# unpacking the tuple, extract values from and assign to variables
title, album, year = imelda
print(imelda)
print("Title: {}".format(title))
print("Album: {}".format(album))
print("Year: {}".format(year))
# tuples don't have an append() method
imelda.append("Rock")
# notes
# lists are intended to hold objects of the same type, tuples not necessarily
# tuples not changing can protect code against bugs
| true
|
acf3384d648aa16c781ac82c61b8e3c275538bae
|
ntkawasaki/complete-python-masterclass
|
/10: Input and Output/shelve_example.py
| 1,638
| 4.25
| 4
|
# like a dictionary stored in a file, uses keys and values
# persistent dictionary
# values pickled when saved, don't use untrusted sources
import shelve
# open a shelf like its a file
# with shelve.open("shelf_test") as fruit: # makes a shelf_test.db file
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# when outside of the with, it closes the file
# print(fruit) # prints as a shelf and not a dictionary
# to do this with manual open and closing
fruit = shelve.open("shelf_test")
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# # change value of "lime"
# fruit["lime"] = "goes great with tequila!"
#
# for snack in fruit:
# print(fruit[snack])
# while True:
# dict_key = input("Please enter a fruit: ")
# if dict_key == "quit":
# break
#
# if dict_key in fruit:
# description = fruit[dict_key]
# print(description)
# else:
# print("We don't have a " + dict_key)
# alpha sorting keys
# ordered_keys = list(fruit.keys())
# ordered_keys.sort()
#
# for f in ordered_keys:
# print(f + " - " + fruit[f])
#
# fruit.close() # remember to close
for v in fruit.values():
print(v)
print(fruit.values())
for f in fruit.items():
print(f)
print(fruit.items())
fruit.close()
| true
|
fcd60015393e712316586a32f75462eff2f4543f
|
ntkawasaki/complete-python-masterclass
|
/11: Modules and Functions/Functions/more_functions.py
| 2,460
| 4.125
| 4
|
# more functions!
# function can use variables from main program
# main program cannot use local variables in a function
import math
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
def parabola(page, size):
"""
Returns parabola or y = x^2 from param x.
:param page:
:param size
:return parabola:
"""
for x_coor in range(size):
y_coor = x_coor * x_coor / size
plot(page, x_coor, y_coor)
plot(page, -x_coor, y_coor)
# modify the circle function so that it allows the color
# of the circle to be specified and defaults to red
def circle(page, radius, g, h, color="red"):
""" Create a circle. """
for x in range(g * 100, (g + radius) * 100):
page.create_oval(g + radius, h + radius, g - radius, h - radius, outline=color, width=2)
# x /= 100
# print(x)
# y = h + (math.sqrt(radius ** 2 - ((x - g) ** 2)))
# plot(page, x, y)
# plot(page, x, 2 * h - y)
# plot(page, 2 * g - x, y)
# plot(page, 2 * g - x, 2 * h - y)
def draw_axis(page):
"""
Draws a horizontal and vertical line through middle of window to be used as
the x and y axis.
:param page:
:return:
"""
page.update() # allows you to use winfo_width/height
x_origin = page.winfo_width() / 2
y_origin = page.winfo_height() / 2
page.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
# create_line(x1, y1, x2, y2)
page.create_line(-x_origin, 0, x_origin, 0, fill="black") # horizontal
page.create_line(0, y_origin, 0, -y_origin, fill="black") # vertical
# shows all local variables in this function
print(locals())
def plot(page, x_plot, y_plot):
"""
Plots points on canvas from params x and y.
:param page:
:param x_plot:
:param y_plot:
:return:
"""
page.create_line(x_plot, -y_plot, x_plot + 1, -y_plot + 1, fill="red")
# window
main_window = tkinter.Tk()
main_window.title("Parabola")
main_window.geometry("640x480")
# canvas
canvas = tkinter.Canvas(main_window, width=640, height=480, background="gray")
canvas.grid(row=0, column=0)
# call function
draw_axis(canvas)
parabola(canvas, 300)
parabola(canvas, 20)
circle(canvas, 100, 100, 100, color="blue")
circle(canvas, 100, 100, 100, color="yellow")
circle(canvas, 100, 100, 100, color="green")
circle(canvas, 10, 30, 30, color="black")
main_window.mainloop()
| true
|
4ccdd7851dc2177d6a35e72cb57069685d75f72c
|
echo001/Python
|
/python_for_everybody/exer9.1.py
| 706
| 4.21875
| 4
|
#Exercise 1 Write a program that reads the words in words.txt and stores them as
# keys in a dictionary. It doesn’t matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is
# in the dictionary.
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('Ther is no this file %s ' % fname)
exit()
word = dict()
for line in fhand:
line = line.rstrip()
# if line not in word:
# word[line] = 1
# else:
# word[line] = word[line] + 1 #count how many times the same word appear
word[line] = word.get(line,0) + 1 # the same as if.... else...
print(word)
| true
|
19e74e3bc318021556ceec645597199996cfba98
|
echo001/Python
|
/python_for_everybody/exer10.11.3.py
| 1,251
| 4.40625
| 4
|
#Exercise 3 Write a program that reads a file and prints the letters in
# decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program
# should not count spaces, digits, punctuation, or anything other than
# the letters a-z. Find text samples from several different languages
# and see how letter frequency varies between languages. Compare your
# results with the tables at wikipedia.org/wiki/Letter_frequencies.
import string
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('This file can not be opened. ')
exit()
letterCount = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('','',string.punctuation)) #delete all punctuation
linelist = line.lower()
for letter in linelist:
if letter.isdigit(): #delete all digit
continue
letterCount[letter] = letterCount.get(letter,0) + 1 #count letters from files
letterCountList = list(letterCount.items())
letterCountList.sort() #sort letters from a to z
for letter,count in letterCountList:
print(letter,count)
| true
|
3168d9379b4ff8064b60ed5e6db65d504c91f5a0
|
marcluettecke/programming_challenges
|
/python_scripts/rot13_translation.py
| 482
| 4.125
| 4
|
"""
Function to shift every letter by 13 positions in the alphabet. Clever use of maketrans and translate.
"""
trans = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
def rot13(message):
"""
Translation by rot13 encoding.
Args:
message: string such as 'Test'
Returns:
translated string, such as 'Grfg'
"""
return message.translate(trans)
| true
|
ae038beb027640e3af191d24c6c3abbb172e398e
|
mihaidobri/DataCamp
|
/SupervisedLearningWithScikitLearn/Classification/02_TrainTestSplit_FitPredictAccuracy.py
| 777
| 4.125
| 4
|
'''
After creating arrays for the features and target variable, you will split them into training and test sets,
fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method.
'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# Create feature and target arrays
X = digits.data
y = digits.target
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42, stratify=y)
# Create a k-NN classifier with 7 neighbors: knn
knn = KNeighborsClassifier(n_neighbors = 7)
# Fit the classifier to the training data
knn.fit(X_train,y_train)
# Print the accuracy
print(knn.score(X_test, y_test))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.