blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
35f60514ec8786b329995344a6bc3e838c3eb046
|
ChWeiking/PythonTutorial
|
/Python基础/day11(继承、多态、类属性、类方法、静态方法)/demo/01_继承/02_覆盖重写.py
| 2,862
| 4.34375
| 4
|
'''
子类和父类都有相同的属性、方法
子类对象在调用的时候,会覆盖父类的,调用子类的
与参数无关,只看名字
覆盖、重写:
扩展功能
'''
class Fu(object):
def __init__(self):
print('init1...')
self.num = 20
def sayHello(self):
print("halou-----1")
class Zi(Fu):
def __init__(self):
print('init2...')
self.num = 200
def sayHello(self):
print("halou-----2")
'''
改变指针
def sayHaha(self):
print("haha-----1")
def sayHaha(self):
print("haha-----2")
'''
zi = Zi()
zi.sayHello()
print(zi.num)
print(Zi.__mro__)
print('*****************************************华丽的分割线*****************************************')
class C1:
def haha(self):
print('C1...haha')
class C2:
def haha(self):
print('C2...haha')
class C3(C1,C2):
def haha(self):
print('C3...haha')
c3 = C3()
c3.haha()
print(C3.__mro__)
print('*****************************************华丽的分割线*****************************************')
'''
super() 这个super类的对象,可以在子类中,找到父类的属性、方法。
并不是直接的父类对象
'''
class Fu(object):
def sayHello(self):
print("halou-----1...self=%s"%self)
class Zi(Fu):
def sayHello(self):
print("halou-----2...self=%s"%self)
#super(Zi,self).sayHello()
#super().sayHello()
Fu.sayHello(self)
print('super=%s...super()=%s...id(super())=%s'%(super,super(),hex(id(super()))))
zi = Zi()
zi.sayHello()
print(zi)
print('*****************************************华丽的分割线*****************************************')
class Fu1(object):
def sayHello(self):
print("halou-----fu1")
class Fu2(object):
def sayHello(self):
print("halou-----fu2")
class Zi(Fu1,Fu2):
def sayHello(self):
print("halou-----zi")
#super().sayHello()
Fu2.sayHello(self)
zi = Zi()
zi.sayHello()
print('*****************************************华丽的分割线*****************************************')
class Fu(object):
def sayHello(self,name):
print("halou-----fu")
class Zi(Fu):
def sayHello(self):
super().sayHello('老王')
print("halou-----zi")
zi = Zi()
zi.sayHello()
#zi.sayHello('xxx')
print('*****************************************华丽的分割线*****************************************')
'''
class Fu(object):
def __init__(self,name,age):
self.name = name
self.age = age
class Zi(Fu):
def __init__(self,sex,name,age):
self.sex = sex
self.name = name
self.age = age
zi = Zi('女','老王',20)
print(zi.name)
print(zi.age)
print(zi.sex)
'''
class Fu(object):
def __init__(self,name,age):
self.name = name
self.age = age
class Zi(Fu):
def __init__(self,sex,name,age):
self.sex = sex
#super().__init__(name,age)
Fu.__init__(self,name,age)
zi = Zi('女','老王',20)
print(zi.name)
print(zi.age)
print(zi.sex)
| false
|
28624d6b4fe400671cec84c3b57ff5948db2a323
|
ChWeiking/PythonTutorial
|
/Python高级/day38(算法)/demo/02_二叉树_广度优先.py
| 2,028
| 4.1875
| 4
|
class MyQueue(object):
"""队列"""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
"""出队列"""
return self.items.pop()
def size(self):
"""返回大小"""
return len(self.items)
class MyNode(object):
"""节点"""
def __init__(self,item,lchild=None,rchild=None):
self.item = item
self.lchild = lchild
self.rchild = rchild
class MyTree(object):
"""二叉树"""
def __init__(self, item=None):
node = None
if item:
node = MyNode(item)
self.__root = node
def add(self,item):
"""新增"""
myNode = MyNode(item)
if self.__root==None:
self.__root = myNode
return
myQueue = MyQueue() #创建新的队列:先进先出
myQueue.enqueue(self.__root) #放入根节点
while myQueue.size(): #循环
cur = myQueue.dequeue() #出队列
if cur.lchild == None: #左孩子是否为None
cur.lchild = myNode
return
elif cur.rchild == None:
cur.rchild = myNode
return
else:
myQueue.enqueue(cur.lchild)
myQueue.enqueue(cur.rchild)
def travel(self):
myQueue = MyQueue() # 创建新的队列:先进先出
myQueue.enqueue(self.__root) # 放入根节点
while myQueue.size(): # 循环
cur = myQueue.dequeue() # 出队列
print(cur.item)
if cur.lchild != None: # 左孩子是否为None
myQueue.enqueue(cur.lchild)
if cur.rchild != None:
myQueue.enqueue(cur.rchild)
if __name__ == '__main__':
myTree = MyTree()
myTree.add(1)
myTree.add(2)
myTree.add(3)
myTree.travel()
| false
|
46a4b5fac21253cff9e24012c4c6a5d1053f65f0
|
ChWeiking/PythonTutorial
|
/Python基础/day05(集合容器、for循环)/demo/02_tuple/01_tuple.py
| 555
| 4.28125
| 4
|
'''
元组:是用小括号的
'''
directions = ('东','西','南','北','中')
print(directions)
print(directions[1])
print('*'*20)
t1 = (1,2,3)
#t1[0]=2
t2 = ([1,2,3],110,'120',(1,2,3))
t2[0].append(110)
print(t2)
'''
列表和元组相互转换
ls = list(元组)
tu = tuple(列表)
'''
ls = [1,2,3]
print(type(ls))
print(ls)
tu = tuple(ls)
print(type(tu))
print(tu)
tu = (1,2,3)
print(type(tu))
print(tu)
ls = list(ls)
print(type(ls))
print(ls)
'''
变量赋值
'''
a,b = [110,120]
print(a)
print(b)
a,b = (110,120)
print(a)
print(b)
| false
|
251b26428c895b27abb3e0db7ff0316e5bc8a7e1
|
Filjo0/PythonProjects
|
/Ch3.py
| 2,197
| 4.25
| 4
|
"""
Chapter 3.
11. In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7,
the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible,
a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and so
on. A little mathematical analysis reveals that there are not enough ways to win
to make the game worthwhile; however, because many people’s eyes glaze over
at the first mention of mathematics, your challenge is to write a program that
demonstrates the futility of playing the game. Your program should take as input
the amount of money that the player wants to put into the pot, and play the game
until the pot is e mpty. At that point, the program should print the number of
rolls it took to break the player, as well as maximum amount of money in the pot.
"""
import random
from time import sleep
pot = 0
print("Hello. Lets play \"The Lucky Sevens game\"!",
"\nRules: You roll a pair of dice. If the dots add up to 7, you WIN $4"
"\nOtherwise, you lose $1"
"\nThere are lots of ways to WIN: (1, 6), (2, 5), (3, 4)")
while True:
try:
pot = int(input("How much money would you like to deposit into the pot: $"))
print("Press ENTER to roll a pair of dice")
input()
except ValueError:
print("Please print the number: ")
while pot > 0:
print("Rolling...")
sleep(2)
dice_roll = random.randint(1, 6), random.randint(1, 6)
print("You rolled number:", dice_roll[0], "and", dice_roll[1])
my_roll = (dice_roll[0] + dice_roll[1])
if my_roll == 7:
pot += 4
print("Congratulations! The dots add up to 7! You've won $4 "
"\nYour balance is: $" + str(pot),
"\nPress ENTER to try again")
else:
pot -= 1
print("Unlucky! The dots add up to:", my_roll, "You've lost $1"
"\nYour balance is: $" + str(pot),
"\nPress ENTER to try again")
input()
print("You need to deposit money into your pot")
| true
|
3cd6ff12af16a6a3d672cad425a9df0d398cedb1
|
lslewis1/Python-Labs
|
/Week 5 Py Labs/Seconds converter.py
| 747
| 4.21875
| 4
|
#10/1/14
#This program will take a user input of a number of seconds.
#The program will then display how many full minutes, hours, days, and leftover seconds there are
#ts is the input of seconds
#s1 is the leftover seconds for the minutes
#s2 is the seconds for hours
#s3 is the seconds for days
#m is the number of minutes
#h is the number of hours
#d is the number of days
ts=int(input("Enter the number of seconds :"))
if ts>=60:
m=ts//60
s1=(ts%60)
if ts>=3600:
h=ts//3600
s2=(ts%3600)
if ts>=86400:
d=ts//86400
s3=(ts%86400)
print(ts,"Seconds are equal to :")
print(m,"full minute(s) and",s1,"seconds.")
print(h,"full hour(s) and",s2,"seconds.")
print(d,"full day(s) and",s3,"seconds.")
| true
|
c46d80d326ba0b65ca97c0679faa2e50aa384371
|
lslewis1/Python-Labs
|
/Week 5 Py Labs/BMI.py
| 530
| 4.34375
| 4
|
#10/1/14
#This program will determine a person's BMI
#Then it will display wheter the person in optimal weight, over, or under
#bmi is the body mass indicator
#w is the weight
#h is the height
w=float(input("Enter your weight in pounds :"))
h=float(input("Enter your height in inches :"))
bmi=(w*703)/(h*h)
print("Your body mass indicator is", \
format(bmi, '.2f'))
if bmi>25:
print("You are overweight.")
elif bmi>=18.5:
print("Your weight is optimal.")
else:
print("You are underweight.")
| true
|
f22d1886a08da98b613d9ed89432a39d47679830
|
lslewis1/Python-Labs
|
/Week 6 Py Labs/calories burned.py
| 327
| 4.125
| 4
|
#10/6/14
#This program will use a loop to display the number of calories burned after time.
#The times are: 10,15,20,25, and 30 minutes
#i controls the while loop
#cb is calories burned
#m is minutes
i=10
while i<=30:
m=i
cb=m*3.9
i=i+5
print(cb,"Calories burned for running for", m,"minutes.")
| true
|
29260166c31c491e47c68e1674e384bc56c6a2d5
|
lslewis1/Python-Labs
|
/Week 8 Py Labs/Temperature converter.py
| 919
| 4.4375
| 4
|
#10/20/14
#This program will utilize a for loop to convert a given temperature.
#The conversion will be between celsius and fahrenheit based on user input.
ch=int(input("Enter a 1 for celsuis to fahrenheit, or a 2 for fahrenheit to celsius: "))
if ch==1:
start=int(input("Please enter your start value: "))
end=int(input("Please enter your end value: "))
step=int(input("Please enter what you want to count by: "))
for temp in range(start,end+1,step):
F=(9/5*temp)+32
print(temp,"degrees Celsius =",format(F,'.2f'),"degrees Fahrenheit.")
elif ch==2:
start=int(input("Please enter your start value: "))
end=int(input("Please enter your end value: "))
step=int(input("Please enter what you want to count by: "))
for temp in range(start,end+1,step):
F=(temp-32)*(5/9)
print(temp,"degrees Fahrenheit =",format(F,'.2f'),"degrees Celsius.")
| true
|
d31c472acb56ddda5e696e10c957d3d85cf88220
|
lslewis1/Python-Labs
|
/Week 4 Py Labs/Letter grade graded lab.py
| 536
| 4.375
| 4
|
#9/26/14
#This program will display a student's grade.
#The prgram will print a letter grade after receiving the numerical grade
#Grade is the numerical grade
#Letter is the letter grade
Grade=float(input("Please enter your numerical grade :"))
if Grade>=90:
print("Your letter grade is an A.")
elif Grade>=80:
print("Your letter grade is a B.")
elif Grade>=70:
print("Your letter grade is a C.")
elif Grade>=60:
print("Your letter grade is a D.")
else:
print("Your letter grade is an F.")
| true
|
7f0bcddba963482972f1c6b2e9d6d9688cf5cee6
|
samanta-antonio/python_basics
|
/fizz.py
| 283
| 4.21875
| 4
|
#Receba um número inteiro na entrada e imprima Fizz se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada.
numero = int(input("Digite um número: "))
resto = (numero % 3)
if resto == 0:
print("Fizz")
else:
print(numero)
| false
|
6b6bee3144bce48f71c9eb02c574d7540f0f42da
|
aaqibgouher/python
|
/numpy_random/generate_rn.py
| 815
| 4.34375
| 4
|
from numpy import random
# 1. for random integer till 100. also second parameter is size means how much you wanna generate
# num_1 = random.randint(100) #should give the last value
# print(num_1)
# 2. for random int array :
# num = random.randint(100,size=10)
# print(num)
# 3. for random float ;
# num_2 = random.rand() # last value is not required but if will give n digit then it will show a list containing n elements
# print(num_2)
# 4. for 2d random int array :
# num = random.randint(100,size=(3,5))
# print(num)
# 5. for 2d random float array :
# num = random.rand(3,5)
# print(num)
# 6. random value from an array :
# num = random.choice([1,2,3,4,5])
# print(num)
# 7. from random value in the array generate a 2d array :
# num = random.choice([1,2,3,4,5],size=(2,2))
# print(num)
| true
|
962557880d2b679913ac49c86658aa8e5bb1205d
|
aaqibgouher/python
|
/numpy_eg/vector/summation.py
| 995
| 4.21875
| 4
|
import numpy as np
# 1. simple add element wise
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# print(np.add(arr_1,arr_2))
# 2. summation - first it will sum the arr_1,arr_2 and arr_3 individually and then sum it at once and will give the output. also axis means it will sum and give the output in one axis
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# arr_3 = np.array([2,4,6,8,10])
# new_arr = np.sum([arr_1,arr_2,arr_3],axis=1)
# print(new_arr)
# 3. cummulative sum
# arr_1 = np.array([1,2,3,4,5])
# print(np.cumsum(arr_1))
# 4. product
# arr_1 = np.array([1,2,3,4,5])
# print(np.prod(arr_1))
# 5. product of more than 2 arrays
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# print(np.prod([arr_1,arr_2],axis=1)) #if will not give that axis,then it will give prod of both 2 arrays but after giving axis = 1, it will give individual product
# 6. cummulative product
# arr_1 = np.array([1,2,3,4,5])
# print(np.cumprod(arr_1))
| true
|
cc22a9186c232e9b318940858ad2f0757b6ae77a
|
GHubgenius/DevSevOps
|
/2.python/0.python基础/day13/代码/7 匿名函数.py
| 659
| 4.25
| 4
|
'''
匿名函数:
无名字的函数
# :左边是参数, 右边是返回值
lambda :
PS: 原因,因为没有名字,函数的调用 函数名 + ()
匿名函数需要一次性使用。
注意: 匿名函数单独使用毫无意义,它必须配合 “内置函数” 一起使用的才有意义。
有名函数:
有名字的函数
'''
# 有名函数
def func():
return 1
print(func()) # func函数对象 + ()
print(func())
# 匿名函数:
# def ():
# pass
#
# () # + ()
# 匿名(), return 已经自动添加了
# lambda 匿名(): return 1
# func = lambda : 1
# print(func())
# func = lambda : 1
# print()
| false
|
45511470c4e3732cb408a609b81daf21b0567553
|
GHubgenius/DevSevOps
|
/2.python/0.python基础/day13/代码/8 内置函数.py
| 1,042
| 4.21875
| 4
|
'''
内置函数:
range()
print()
len()
# python内部提供的内置方法
max, min, sorted, map, filter
sorted: 对可迭代对象进行排序
'''
# max求最大值 max(可迭代对象)
# list1 = [1, 2, 3, 4, 5]
# max内部会将list1中的通过for取出每一个值,并且进行判断
# print(max(list1)) #
# dict1 = {
# 'tank': 1000,
# 'egon': 500,
# 'sean': 200,
# 'jason': 500
# }
# 获取dict1中薪资最大的人的名字
# 字符串的比较: ASCII
# print(max(dict1, key=lambda x: dict1[x]))
# 获取dict1中薪资最小的人的名字
# print(min(dict1, key=lambda x:dict1[x]))
# sorted: 默认升序(从小到大) reverse:反转 reverse默认是False
# list1 = [10, 2, 3, 4, 5]
# print(sorted(list1))
# # reverse=True--> 降序
# print(sorted(list1, reverse=True))
dict1 = {
'tank': 100,
'egon': 500,
'sean': 200,
'jason': 50
}
# new_list = ['egon', 'sean', 'tank', 'jason']
new_list = sorted(dict1, key=lambda x: dict1[x], reverse=True)
print(new_list)
| false
|
a7f71f51a443042364a36a82503ab431e29394a8
|
GHubgenius/DevSevOps
|
/2.python/0.python基础/day10/代码/02 函数的嵌套.py
| 551
| 4.15625
| 4
|
# 函数的嵌套调用:在函数内调用函数
# def index():
# print('from index')
#
#
# def func():
# index()
# print('from func')
#
#
# func()
# def func1(x, y):
# if x > y:
# return x
# else:
# return y
# print(func1(1,2))
# def func2(x, y, z, a):
# result = func1(x, y)
# result = func1(result, z)
# result = func1(result, a)
# return result
#
#
# print(func2(1, 200000, 3, 1000))
# 函数的嵌套定义:
def index():
def home():
print("from home")
home()
index()
| false
|
07923c14b2d3cc7e14a49c0eaff1e20d8769b7cb
|
Jonaugustin/MyContactsAssignment
|
/main.py
| 2,408
| 4.34375
| 4
|
contacts = [["John", 311, "noemail@email.com"], ["Robert", 966, "uisemali@email.com"], ["Edward", 346, "nonumber@email.ca"]]
menu = """
Main Menu
1. Display All Contacts Names
2. Search Contacts
3. Edit Contact
4. New Contact
5. Remove Contact
6. Exit
"""
def displayContact():
if contacts:
print("Contact Names are: ")
for i in range(len(contacts)):
print(contacts[i][0])
else:
print("Sorry, as of right now there are no contacts.")
callInput()
def searchContact():
txt = """
Name: {}
Phone Number: {}
Email: {}
"""
cherch = str(input("Please enter name of individual you would wish to search: "))
for i in range(len(contacts)):
for x in contacts[i]:
if cherch == x:
print(txt.format(contacts[i][0], contacts[i][1], contacts[i][2]))
callInput()
def editContact():
cherch = str(input("Please enter name of individual you would wish to search: "))
for i in range(len(contacts)):
for x in contacts[i]:
if cherch == x:
contacts[i][0] = str(input("Please enter in a new name for this contact: "))
contacts[i][1] = int(input("Please enter in a new number for this contact: "))
contacts[i][2] = str(input("Please enter in a new email for this contact: "))
callInput()
def newContact():
name = str(input("Please enter in a name for this contact: "))
phone = int(input("Please enter in a number for this contact: "))
email = str(input("Please enter in an email for this contact: "))
contacts.append([name, phone, email])
callInput()
def removeContact():
cherch = str(input("Please enter name of individual you would wish to remove: "))
for i in range(len(contacts)):
if cherch == contacts[i][0]:
del contacts[i]
break
callInput()
def callInput():
print(menu)
option = int(input("Please select a number from 1 to 6: "))
if option == 1:
displayContact()
elif option == 2:
searchContact()
elif option == 3:
editContact()
elif option == 4:
newContact()
elif option == 5:
removeContact()
elif option == 6:
exit()
else:
option = int(input("Please select a number again from 1 to 6: "))
callInput()
| true
|
7e46a856a34046e99f4353318d1cc9bf787973b2
|
lukejskim/sba19-seoulit
|
/Sect-A/source/sect07_class/s720_gen_object.py
| 255
| 4.125
| 4
|
# 클래스 정의
class MyClass:
name = str()
def sayHello(self):
hello = "Hello, " + self.name + "\t It's Good day !"
print(hello)
# 객체 생성, 인스턴스화
myClass = MyClass()
myClass.name = '준영'
myClass.sayHello()
| false
|
57d9d25fe134eff49886a76ba6d8ea91f9498073
|
nikhilpatil29/AlgoProgram
|
/algo/MenuDriven.py
| 2,442
| 4.125
| 4
|
'''
Purpose: Program to perform all sorting operation like
insertion,bubble etc
@author Nikhil Patil
'''
from utility import *
class MenuDriven:
x = utility()
choice = 0
while 1:
print "Menu : "
print "1. binarySearch method for integer"
print "2. binarySearch method for String"
print "3. insertionSort method for integer"
print "4. insertionSort method for String"
print "5. bubbleSort method for integer"
print "6. bubbleSort method for String"
print "7.Exit"
choice = int(input("\nenter your choice\n"))
if choice == 1:
numList = [1,3,6,9,11,32,54,59,61]
print numList
ele = input("enter the element to search")
pos = x.binarySearchInteger(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 2:
numList = ['a','b','c','d','e','f','g']
print numList
ele = raw_input("enter the element to search")
pos = x.binarySearchString(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 3:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print numList
array1 = x.insertionSortInteger(numList)
print"Sorted Insertion Sort Array : ",array1
elif choice == 4:
array = ["nikhil", "kunal", "zeeshan", "amar"]
print array
array1 = x.insertionSortString(array)
print"Sorted Insertion Sort Array : ",array1
elif choice == 5:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print "list before sort"
print numList, "\n"
print "list after sort"
print(x.bubbleSort(numList))
elif choice == 6:
array = ["nikhil","kunal","zeeshan","amar"]
print("Sorted Bubble Sort Array : ")
print array
print("Sorted Bubble Sort Array : ")
x.bubbleSortString(array)
else:
exit(0)
#
#
#
# insertionSortString(str1, size)
# print("Sorted Insertion Sort Array : ")
# printStringArray(str1, size)
# break
| true
|
953f3587f7cba8d48585a093ce5e0c8e2942d35f
|
noite-m/nlp2020
|
/chart1/practice09.py
| 1,876
| 4.125
| 4
|
'''
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
ただし,長さが4以下の単語は並び替えないこととする.
適当な英語の文
(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)
を与え,その実行結果を確認せよ.
'''
import random
'''
ランダムに複数の要素を選択(重複なし): random.sample()
randomモジュールの関数sample()で、リストからランダムで複数の要素を取得できる。要素の重複はなし(非復元抽出)。
第一引数にリスト、第二引数に取得したい要素の個数を指定する。リストが返される。
'''
def typoglycemia(word):
if len(word) <= 4:
return word
else:
text = random.sample(list(word[1:-1]),len(word[1:-1]))
return ''.join([word[0]] + text + [word[-1]])
sentense = input("解答1の英文>>")
ans = [typoglycemia(word) for word in sentense.split()]
print('解答1の変換結果:'+' '.join(ans))
'''
元のリストをシャッフル: random.shuffle()
randomモジュールの関数shuffle()で、元のリストをランダムに並び替えられる。
'''
#解答2
result = []
def Typoglycemia(target):
for word in target.split(' '):
if len(word) <= 4:
result.append(word)
else:
chr_list = list(word[1:-1])
random.shuffle(chr_list)
result.append(word[0] + ''.join(chr_list) + word[-1])
return ' '.join(result)
# 対象文字列の入力
target = input('解答2の英文--> ')
# タイポグリセミア
result = Typoglycemia(target)
print('解答2の変換結果:' + result)
| false
|
cbfa94e5ab45819bb1dd9ee3834ec98d1b826911
|
webfarer/python_by_example
|
/Chapter2/016.py
| 317
| 4.125
| 4
|
user_rainy = str.lower(input("Tell me pls - is a rainy: "))
if user_rainy == 'yes':
user_umbrella = str.lower(input("It is too windy for an umbrella?: "))
if user_umbrella == 'yes':
print("It is too windy for an umbrella")
else:
print("Take an umbrella")
else:
print("Enjoy your day")
| true
|
fe3b3b55e4d537cab59c9c4943361b4714eabf64
|
afeldman/sternzeit
|
/year/year.py
| 2,904
| 4.78125
| 5
|
#!/usr/bin/env python3
def is_leap_year(year):
""" if the given year is a leap year, then return true
else return false
:param year: The year to check if it is a leap year
:returns: It is a Leap leap year (yes or no).
"""
return (year % 100 == 0) if (year % 400 == 0) else (year % 4 == 0)
def year_month_day(year, day_of_year):
""" calculate the year, month and day form year and day as input
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to check the month and day in
:param day_of_year: the day you want to check for monath in the given year
:returns: the year, the month and the day of the given data
"""
K = 1 if (is_leap_year(year)) else 2
M = 1 if (day_of_year < 32) else int((9*(K + day_of_year)) / 275.0 + 0.98 )
D = day_of_year - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return K, M, D
def number_of_days_in_month(year, month):
""" check the number of days in the given month.
Because of leap years the year information is mandatory
:param year: The year to get the day of monthes
:param month: the month to check
:returns: number of days for a given month in a given year. If the month is bigger then 12 or smaller the 1, then -1 is returned
"""
if (month < 1) or (month > 12):
return -1
return {
1: 31,
2: 29 if (is_leap_year(year)) else 28,
3: 31,
4: 2,
5: 31,
6: 2,
7: 31,
8: 31,
9: 30,
10:31,
11:30,
12:31,
}[month]
def length_of_year(year):
""" the length of a day
:param year: The year you wuld like to know the length.
:returns: exact days. a day is longer then 365 days.
"""
return float(365.2564) if is_leap_year(year) else float(364.2564)
def day_of_year(year, month, day):
""" calculate the day of a year
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to calculate the day
:param month: month the day is in
:param day: day of month in the given year
:returns: the day in the given year
"""
K = 1 if is_leap_year(year) else 2
return (int((275 * month) / 9.0) - K * int((month + 9) / 12.0) + day - 30)
def minuts_in_the_year(year, month, day, hours, minute):
""" calculate the day of a year
To calculate this, read :
*Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7*
:param year: The year to calculate the day
:param month: month the day is in
:param day: day of month in the given year
:param houres: the hour of the day in the month of the requested year
:returns: the hour in the given year
"""
return float( day_of_year(year, month, day) - 1.0 + float(hours)/24.0 + float(minute)/1440.0)
| false
|
126ba2113fe13cb7a8008b772793718001df3c94
|
KacperKubara/USAIS_Workshops
|
/Clustering/k-means.py
| 1,734
| 4.1875
| 4
|
# K-NN classification with k-fold cross validation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Read Data
dataset = pd.read_csv("Mall_Customers.csv")
# Choose which features to use
x = dataset.iloc[:, 3:5].values # Features - Age, annual income (k$)
"""
K-Means clustering is unsupervised ML algorithm. It means that
it will figure the classes on its own (contrary to ML classification algorithms)
The purpose of clustering is to find out if a certain group of data points have
similar charactertics, i.e. if they create a cluster
Therefore, we won't need train-test split. Feature scaling might also be unnecessary
as the 2 features have v.similar values
"""
inertia = []
cluster_count = []
from sklearn.cluster import KMeans
for i in range(1,15):
cluster = KMeans(n_clusters = i, random_state = 42)
cluster.fit(x)
inertia.append(cluster.inertia_)
cluster_count.append(i)
fig0, ax0 = plt.subplots()
ax0.plot(cluster_count, inertia)
ax0.set_title("Elbow Method")
ax0.set_xlabel("No. clusters")
ax0.set_ylabel("WCSS")
# By looking on the elbow method plot,
# let's choose n_clusters = 5
# Cluster the data and assign labels ('classes')
cluster = KMeans(n_clusters = 5, random_state = 42)
y_pred = cluster.fit_predict(x)
# Visualise Results
from matplotlib import colors
my_colors = list(colors.BASE_COLORS.keys())
fig1, ax1 = plt.subplots()
ax1.set_title("Clusters")
ax1.set_xlabel("Annual Income")
ax1.set_ylabel("Spending Score")
# Plotting cluster
for i, label in enumerate(cluster.labels_):
ax1.scatter(x[i, 0], x[i, 1], c = my_colors[label])
ax1.scatter(cluster.cluster_centers_[:, 0], cluster.cluster_centers_[:, 1],
s = 300, c = 'yellow', label = 'Centroids')
| true
|
f0749405938e25a640b1955262887d8e5924397a
|
betty29/code-1
|
/recipes/Python/52316_Dialect_for_sort_by_then_by/recipe-52316.py
| 1,587
| 4.15625
| 4
|
import string
star_list = ['Elizabeth Taylor',
'Bette Davis',
'Hugh Grant',
'C. Grant']
star_list.sort(lambda x,y: (
cmp(string.split(x)[-1], string.split(y)[-1]) or # Sort by last name ...
cmp(x, y))) # ... then by first name
print "Sorted list of stars:"
for name in star_list:
print name
#
# "cmp(X, Y)" return 'false' (0) when X and Y compare equal,
# so "or" makes the next "cmp()" to be evaluated.
# To reverse the sorting order, simply swap X and Y in cmp().
#
# This can also be used if we have some other sorting criteria associated with
# the elements of the list. We simply build an auxiliary list of tuples
# to pack the sorting criteria together with the main elements, then sort and
# unpack the result.
#
def sorting_criterium_1(data):
return string.split(data)[-1] # This is again the last name.
def sorting_criterium_2(data):
return len(data) # This is some fancy sorting criterium.
# Pack the auxiliary list:
aux_list = map(lambda x: (x,
sorting_criterium_1(x),
sorting_criterium_2(x)),
star_list)
# Sort:
aux_list.sort(lambda x,y: (
cmp(x[1], y[1]) or # Sort by criteria 1 (last name)...
cmp(y[2], x[2]) or # ... then by criteria 2 (in reverse order) ...
cmp(x, y))) # ... then by the value in the main list.
# Unpack the resulting list:
star_list = map(lambda x: x[0], aux_list)
print "Another sorted list of stars:"
for name in star_list:
print name
| true
|
da7d9b543243c19783719c409b67347ce4b126a3
|
betty29/code-1
|
/recipes/Python/304440_Sorting_dictionaries_value/recipe-304440.py
| 843
| 4.21875
| 4
|
# Example from PEP 265 - Sorting Dictionaries By Value
# Counting occurences of letters
d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
# operator.itemgetter is new in Python 2.4
# `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter
# Items sorted by key
# The new builtin `sorted()` will return a sorted copy of the input iterable.
print sorted(d.items())
# Items sorted by key, in reverse order
# The keyword argument `reverse` operates as one might expect
print sorted(d.items(), reverse=True)
# Items sorted by value
# The keyword argument `key` allows easy selection of sorting criteria
print sorted(d.items(), key=itemgetter(1))
# In-place sort still works, and also has the same new features as sorted
items = d.items()
items.sort(key = itemgetter(1), reverse=True)
print items
| true
|
809a2e466bf5784e776a0249cf43460147cb14e0
|
betty29/code-1
|
/recipes/Python/578935_Garden_Requirements_Calculator/recipe-578935.py
| 2,723
| 4.21875
| 4
|
'''
9-16-2014
Ethan D. Hann
Garden Requirements Calculator
'''
import math
#This program will take input from the user to determine the amount of gardening materials needed
print("Garden Requirements Calculator")
print("ALL UNITS ENTERED ARE ASSUMED TO BE IN FEET")
print("_____________________________________________________")
print("")
#Gather all necessary input from user
side_length = input("Enter the length of one side of garden: ")
spacing = input("Enter the spacing between plants: ")
depth_garden = input("Enter the depth of the garden soil: ")
depth_fill = input("Enter the depth of the fill: ")
#Convert input to floats so that we can do math with them
side_length = float(side_length)
spacing = float(spacing)
depth_garden = float(depth_garden)
depth_fill = float(depth_fill)
#Calculate radius of each circle and semi-circle
r = side_length / 4
#1 - Number of plants for all semi-circles
area = (math.pi * (r**2)) / 2
number_plants_semi = math.trunc(area / (spacing**2))
#2 - Number of plants for the circle garden
area = math.pi * (r**2)
number_plants_circle = math.trunc(area / (spacing**2))
#3 - Total number of plants for garden
total_number_plants = number_plants_circle + (number_plants_semi*4)
#4 - Soil for each semi-circle garden in cubic yards
volume = (math.pi * (r**2) * depth_garden) / 2
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_semi = round(cubic_volume, 1)
#5 - Soil for circle garden in cubic yards
volume = math.pi * (r**2) * depth_garden
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_circle = round(cubic_volume, 1)
#6 - Total amount of soil for the garden
total_soil = (cubic_volume_rounded_semi * 4) + cubic_volume_rounded_circle
total_soil_rounded = round(total_soil, 1)
#7 - Total fill for the garden
volume_whole = (side_length**2) * depth_fill
all_volume_circle = (math.pi * (r**2) * depth_garden) * 3
total_volume_fill = volume_whole - all_volume_circle
cubic_total_volume_fill = total_volume_fill / 27
cubic_total_volume_fill_rounded = round(cubic_total_volume_fill, 1)
#Print out the results
print("")
print("You will need the following...")
print("Number of plants for each semi-circle garden:", number_plants_semi)
print("Number of plants for the circle garden:", number_plants_circle)
print("Total number of plants for the garden:", total_number_plants)
print("Amount of soil for each semi-circle garden:", cubic_volume_rounded_semi, "cubic yards")
print("Amount of soil for the circle garden:", cubic_volume_rounded_circle, "cubic yards")
print("Total amount of soil for the garden:", total_soil_rounded, "cubic yards")
print("Total amount of fill for the garden:", cubic_total_volume_fill_rounded, "cubic yards")
| true
|
e2f6af7d70e34e1fd89e1239bcbac0709810dc25
|
betty29/code-1
|
/recipes/Python/577344_Maclaurinsseriescos2x/recipe-577344.py
| 1,458
| 4.15625
| 4
|
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/008/10
#version :2.6
"""
maclaurin_cos_2x is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos(2x) = 1- 2^2*x^2/2! + 2^4*x^4/4! - 2^6*x^6/6! ...........
"""
from math import *
def maclaurin_cos_2x(value,k):
"""
Compute maclaurin's series approximation for cos(2x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos(2x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos_2x_1 = maclaurin_cos_2x(60,100)
print maclaurin_cos_2x_1
maclaurin_cos_2x_2 = maclaurin_cos_2x(45,100)
print maclaurin_cos_2x_2
maclaurin_cos_2x_3 = maclaurin_cos_2x(30,100)
print maclaurin_cos_2x_3
######################################################################FT python "C:\
#urine series\M
#-0.5
#0.0
#0.5
| true
|
a752a877f7aa023a64622cb406d86f9655133808
|
betty29/code-1
|
/recipes/Python/577345_Maclaurinsseriescos_x/recipe-577345.py
| 1,429
| 4.21875
| 4
|
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/08/10
#version :2.6
"""
maclaurin_cos_pow2 is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos²(x) = 1- x^2 + 2^3*x^4/4! - 2^5*x^6/6! ...........
"""
from math import *
def maclaurin_cos_pow2(value,k):
"""
Compute maclaurin's series approximation for cos^2(x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos^2(x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**(item-1))*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**(item-1))*((value*pi/180)**item/factorial(item))
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos1 = maclaurin_cos_pow2(135,100)
print maclaurin_cos1
maclaurin_cos2 = maclaurin_cos_pow2(45,100)
print maclaurin_cos2
maclaurin_cos3 = maclaurin_cos_pow2(30,100)
print maclaurin_cos3
#############################################################
#FT python "C:
#0.5
#0.5
#0.75
| true
|
a5431bb48049aa784132d0a08a866223d580d2d4
|
betty29/code-1
|
/recipes/Python/577574_PythInfinite_Rotations/recipe-577574.py
| 2,497
| 4.28125
| 4
|
from itertools import *
from collections import deque
# First a naive approach. At each generation we pop the first element and append
# it to the back. This is highly memmory deficient.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = list(it)
for i in range(len(l)):
yield iter(l)
l = l[1:]+[l[0]]
# A much better approach would seam to be using a deque, which rotates in O(1),
# However this does have the negative effect, that generating the next rotation
# before the current has been iterated through, will result in a RuntimeError
# because the deque has mutated during iteration.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = deque(it)
for i in range(len(l)):
yield iter(l)
l.rotate()
# The trick is to use subsets of infinite lists. First we define the function tails,
# which is standard in many functal languages.
# Because of the way tee is implemented in itertools, the below implementation will
# use memory only propertional to the offset difference between the generated
# iterators.
def tails(it):
""" tails([1,2,3,4,5]) --> [[1,2,3,4,5], [2,3,4,5], [3,4,5], [4,5], [5], []] """
while True:
tail, it = tee(it)
yield tail
next(it)
# We can now define two new rotations functions.
# The first one is very similar to the above, but since we never keep all list
# elements, we need an extra length parameter.
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return (islice(rot,N) for rot in islice(tails(cycle(it)),N))
# The above works fine for things like:
# >>> for rot in rotations(range(4), 4):
# ... print (list(rot))
# ...
# [0, 1, 2, 3]
# [1, 2, 3, 0]
# [2, 3, 0, 1]
# [3, 0, 1, 2]
#
# But that is not really where it shines, since the lists are iterated one after
# another, and so the tails memory usage becomes linear.
#
# In many cases tails and infinite lists lets us get away with an even simpler
# rotaions function:
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return islice(tails(cycle(it)),N)
# This one works great for instances where we are topcut anyway:
# >>> for rot in rotations(range(4), 4):
# ... print (list(zip(range(4), rot)))
# ...
# [(0, 0), (1, 1), (2, 2), (3, 3)]
# [(0, 1), (1, 2), (2, 3), (3, 0)]
# [(0, 2), (1, 3), (2, 0), (3, 1)]
# [(0, 3), (1, 0), (2, 1), (3, 2)]
| true
|
d821b07149089dba24a238c3ad83d5c8b6642fd6
|
betty29/code-1
|
/recipes/Python/577965_Sieve_Eratosthenes_Prime/recipe-577965.py
| 986
| 4.34375
| 4
|
def primeSieve(x):
'''
Generates a list of odd integers from 3 until input, and crosses
out all multiples of each number in the list.
Usage:
primeSieve(number) -- Finds all prime numbers up until number.
Returns: list of prime integers (obviously).
Time: around 1.5 seconds when number = 1000000.
'''
numlist = range(3, x+1, 2)
counter = 0 # Keeps count of index in while loop
backup = 0 # Used to reset count after each iteration and keep count outside of while loop
for num in numlist:
counter = backup
if num != 0:
counter += num
while counter <= len(numlist)-1: # Sifts through multiples of num, setting them all to 0
numlist[counter] = 0
counter += num
else: # If number is 0 already, skip
pass
backup += 1 # Increment backup to move on to next index
return [2] + [x for x in numlist if x]
| true
|
849e48eba0db9689f82e2c23ec9d9ae777c78a54
|
betty29/code-1
|
/recipes/Python/466321_recursive_sorting/recipe-466321.py
| 443
| 4.25
| 4
|
"""
recursive sort
"""
def rec_sort(iterable):
# if iterable is a mutable sequence type
# sort it
try:
iterable.sort()
# if it isn't return item
except:
return iterable
# loop inside sequence items
for pos,item in enumerate(iterable):
iterable[pos] = rec_sort(item)
return iterable
if __name__ == '__main__':
struct = [[1,2,3,[6,4,5]],[2,1,5],[4,3,2]]
print rec_sort(struct)
| true
|
25fc1d2d9fe540cc5e2994ac04c875cb40df2f8c
|
betty29/code-1
|
/recipes/Python/334695_PivotCrosstabDenormalizatiNormalized/recipe-334695.py
| 2,599
| 4.40625
| 4
|
def pivot(table, left, top, value):
"""
Creates a cross-tab or pivot table from a normalised input table. Use this
function to 'denormalize' a table of normalized records.
* The table argument can be a list of dictionaries or a Table object.
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621)
* The left argument is a tuple of headings which are displayed down the
left side of the new table.
* The top argument is a tuple of headings which are displayed across the
top of the new table.
Tuples are used so that multiple element headings and columns can be used.
Eg. To transform the list (listOfDicts):
Name, Year, Value
-----------------------
'Simon', 2004, 32
'Russel', 2004, 64
'Simon', 2005, 128
'Russel', 2005, 32
into the new list:
'Name', 2004, 2005
------------------------
'Simon', 32, 128
'Russel', 64, 32
you would call pivot with the arguments:
newList = pivot(listOfDicts, ('Name',), ('Year',), 'Value')
"""
rs = {}
ysort = []
xsort = []
for row in table:
yaxis = tuple([row[c] for c in left])
if yaxis not in ysort: ysort.append(yaxis)
xaxis = tuple([row[c] for c in top])
if xaxis not in xsort: xsort.append(xaxis)
try:
rs[yaxis]
except KeyError:
rs[yaxis] = {}
if xaxis not in rs[yaxis]:
rs[yaxis][xaxis] = 0
rs[yaxis][xaxis] += row[value]
headings = list(left)
headings.extend(xsort)
t = []
#If you want a list of dictionaries returned, use a cheaper alternative,
#the Table class at:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621
#and replace the above line with this code:
#t = Table(*headings)
for left in ysort:
row = list(left)
row.extend([rs[left][x] for x in rs[left]])
t.append(dict(zip(headings,row)))
return t
if __name__ == "__main__":
import random
#Build a list of dictionaries
c = "Employee","Year","Month","Value"
d = []
for y in xrange(2003,2005):
for m in xrange(1,13):
for e in xrange(1,6):
d.append(dict(zip(c,(e,y,m,random.randint(10,90)))))
#pivot the list contents using the 'Employee' field for the left column,
#and the 'Year' field for the top heading and the 'Value' field for each
#cell in the new table.
t = pivot(d,["Employee"],["Year"],"Value")
for row in t:
print row
| true
|
a2e8e4bc7ec3c702eca1668891cfe72ea1a70113
|
betty29/code-1
|
/recipes/Python/502260_Parseline_break_text_line_informatted/recipe-502260.py
| 1,089
| 4.1875
| 4
|
def parseline(line,format):
"""\
Given a line (a string actually) and a short string telling
how to format it, return a list of python objects that result.
The format string maps words (as split by line.split()) into
python code:
x -> Nothing; skip this word
s -> Return this word as a string
i -> Return this word as an int
d -> Return this word as an int
f -> Return this word as a float
Basic parsing of strings:
>>> parseline('Hello, World','ss')
['Hello,', 'World']
You can use 'x' to skip a record; you also don't have to parse
every record:
>>> parseline('1 2 3 4','xdd')
[2, 3]
>>> parseline('C1 0.0 0.0 0.0','sfff')
['C1', 0.0, 0.0, 0.0]
"""
xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
result = []
words = line.split()
for i in range(len(format)):
f = format[i]
trans = xlat.get(f)
if trans: result.append(trans(words[i]))
if len(result) == 0: return None
if len(result) == 1: return result[0]
return result
| true
|
486e319264ee6470f902c3dd3240f614d06dff83
|
betty29/code-1
|
/recipes/Python/498090_Finding_value_passed_particular_parameter/recipe-498090.py
| 1,180
| 4.125
| 4
|
import inspect
def get_arg_value(func, argname, args, kwargs):
"""
This function is meant to be used inside decorators, when you want
to find what value will be available inside a wrapped function for
a particular argument name. It handles positional and keyword
arguments and takes into account default values. For example:
>>> def foo(x, y): pass
...
>>> get_arg_value(foo, 'y', [1, 2], {})
2
>>> get_arg_value(foo, 'y', [1], {'y' : 2})
2
>>> def foo(x, y, z=300): pass
...
>>> get_arg_value(foo, 'z', [1], {'y' : 2})
300
>>> get_arg_value(foo, 'z', [1], {'y' : 2, 'z' : 5})
5
"""
# first check kwargs
if argname in kwargs:
return kwargs[argname]
# OK. could it be a positional argument?
regargs, varargs, varkwargs, defaults=inspect.getargspec(func)
if argname in regargs:
regdict=dict(zip(regargs, args))
if argname in regdict:
return regdict[argname]
defaultdict=dict(zip(reversed(regargs), defaults))
if argname in defaultdict:
return defaultdict[argname]
raise ValueError("no such argument: %s" % argname)
| true
|
f15d9fdb5bd40bfa44342919598f3df07340b086
|
J-Cook-jr/python-dictionaries
|
/hotel.py
| 334
| 4.125
| 4
|
# This program creates a dictionary of hotel rooms and it's occupants.
# Create a dictionary that lists the room number and it's occupants.
earlton_hotel ={
"Room 101" : "Harley Cook",
"Room 102" : "Mildred Tatum",
"Room 103" : "Jewel Cook",
"Room 104" : "Tiffany Waters",
"Room 105" : "Dejon Waters"
}
print(earlton_hotel)
| true
|
bf44d7003cfce950a3002a4bb62d4a91e5d6f0a8
|
cczhouhaha/data_structure
|
/1016堆,优先队列/堆heap.py
| 2,352
| 4.1875
| 4
|
#堆是完全二叉树,又分为最大堆(根>左右孩子)和最小堆(根<左右孩子)
class Heap:
def __init__(self):
self.data_list = [] #用数组实现
# 得到父节点的下标
def get_parent_index(self,index):
if index < 0 or index >= len(self.data_list):
raise IndexError("The index out of range")
else:
return (index-1) >> 1 #孩子结点坐标(二进制)右移一位得到父节点坐标
def swap(self,child_index,parent_index): #孩子结点与父节点相互交换
self.data_list[child_index],self.data_list[parent_index]=self.data_list[parent_index],self.data_list[child_index]
def insert(self,data):
self.data_list.append(data)
index = len(self.data_list)-1
parent_index = self.get_parent_index(index)
while self.data_list[parent_index] < data and parent_index >= 0: #如果插入数值大于父节点值,进行循环替换操作
self.swap(index,parent_index) #先让两者的值进行交换
index = parent_index #下标进行交换
parent_index = self.get_parent_index(index) #找到新下标的父节点
def __repr__(self):
return str(self.data_list)
def pop(self): #删除堆顶
remove_data = self.data_list[0] #记录要删除的堆顶
self.data_list[0] = self.data_list[-1] #将堆顶的值替换为最后一个元素的值
del self.data_list[-1] #删除最后一个元素的值
self.heapify(0) #然后堆化 (即重新排序)
return remove_data
def heapify(self,index): #堆顶化 即重新排序
size = len(self.data_list)-1 #整个长度的范围
max_index = index #最大值下标max_index
while True:
if 2*index+1 <= size and self.data_list[max_index] < self.data_list[2*index+1]: #如果最大值发生变化,需要进行移位变换
max_index = 2*index+1
if 2*index+2 <= size and self.data_list[max_index] < self.data_list[2*index+2]:
max_index = 2*index+2
if max_index == index:
break
self.swap(index,max_index)
index = max_index
h = Heap()
h.insert(10)
h.insert(7)
h.insert(8)
h.insert(9)
h.insert(6)
print(h)
h.insert(11)
print(h)
h.insert(5)
print(h)
h.pop()
print(h)
| false
|
f74e3aaff1778023fc4d7180c9c3e7a96cd871ee
|
MatthewGerges/CS50-Programming-Projects
|
/MatthewGerges-cs50-problems-2021-x-sentimental-readability/readability.py
| 2,780
| 4.125
| 4
|
from cs50 import get_string
# import the get_string function from cs50's library
def main():
# prompt the user to enter a piece of text (a paragraph/ excerpt)
paragraph1 = get_string("Text: ")
letters = count_letters(paragraph1)
# the return value of count_letters (how many letters there are in a paragraph) is assigned to the variable letters
words = count_words(paragraph1)
# the variable words is assigned the return value of the count_words function (tells you how many words are in a paragraph)
sentences = count_sentences(paragraph1)
# the variable sentences is assigned the return value of the count_sentences function(tells you how many sentences are in a paragraph)
# letters100 is automatically converted to a double in python
letters100 = (letters * 100) / words
# calculate the average number of letters and sentences per 100 words in the text
sentences100 = (sentences * 100) / words
formula = (0.0588 * letters100) - (0.296 * sentences100) - 15.8
# The above is Coleman-Liau formula, whose rounded value tells you the grade-reading level of a particular text
grade = round(formula)
# if formula gives you a number between 1 and 16, print that number as the grade reading level
if (grade >= 1 and grade < 16):
print(f"Grade {grade}")
# if the formula gives you a number that it is not in that range, specify if it is too low or too high of a reading level
elif (grade < 1):
print("Before Grade 1")
elif (grade >= 16):
print("Grade 16+")
# count the letters in the paragraph by checking the if the letters are alphabetical
def count_letters(paragraph):
letters = 0
for char in paragraph:
if char.isalpha():
# char.isalpha() returns true if a character is a letter and false otherwise
letters += 1
return letters
# count the words in the paragraph by adding 1 to the number of spaces
def count_words(paragraph):
words = 1
for i in range(len(paragraph)):
if (" " == paragraph[i]):
words += 1
return words
# count the number of sentences by counting the number of punctuation marks in the paragraph (compare strings and add to a counting variable)
def count_sentences(paragraph):
sentences = 0
for i in range(len(paragraph)):
# check for periods, exclamations, and question marks
if (paragraph[i] == "." or paragraph[i] == "!" or paragraph[i] == "?"):
sentences += 1
return sentences
main()
'''
# This is how to iterate through each character in a string and check if it is a letter
s = 'a123b'
for char in s:
print(char, char.isalpha())
'''
| true
|
602ea8ecddf9d0747115b17773236b33780a8507
|
TTUSDC/practical-python-sdc
|
/Week 1/notes/testing.py
| 1,407
| 4.1875
| 4
|
print("Hello World")
pizza = 3
print(pizza)
pizza = 3.3
print(pizza)
pizza = "i like pizza"
print(pizza)
pizza = 333333333333
print(pizza)
# + - / ** * // %
x = 3
y = 5
print(x - y)
print(x + y)
print(x // y)
print(x * y)
print(x ** y)
print(30 % 11)
# True, False
# and, or, is, not
print(True is True)
print(True is False)
print(False is False)
print(True is not False)
print(False is not True)
print(True or False) # True
print(True and False) # False
# <=, ==, >=, !=
greeting1 = 'Hello'
greeting2 = 'Helloo'
print("The id of the first Hello is", id(greeting1))
print("The id of the second Hello is", id(greeting2))
print(1 < 2 > 3)
print(1 != 1)
if 1 == 2:
print("Hello")
elif 1 != 1 or 1 > 0:
print("What's up")
for x in range(5):
x = x + 1
print(x)
i = 0
while i <= 5:
print("Hi")
i += 1 # Same: i = i + 1
# f(x, y) = x + y
def f(x, y):
def z(x, y):
print("Inside function z:", x, y)
print("Inside function f:", x, y)
x -= 1
y -= 1
z(x, y)
return x, y
x, y = f(1, 2)
print("Outside function f:", x, y)
my_list = [1, 2, "string", 4, False]
print("Before loop:", my_list)
for x in range(len(my_list)):
my_list[x] = my_list[x] * 5
print("After loop:", my_list)
my_dict = {"key1":[1, 2, 3, 4], "key2": 2 ,"key3": 3, "key4": 4, "key5": 5 }
"""
dict
list
int
str
float
"""
for x in my_dict.items():
print(x)
| false
|
fa4348c886de9e98fee1878c424aab1ebe8e448e
|
marina-h/lab-helpers
|
/primer_helper.py
| 813
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import readline
reverse_comp_dict = {'A':'T', 'T':'A','G':'C', 'C':'G'}
def melting_temp(p):
Tm = 0
for n in p:
if n == 'A' or n == 'T':
Tm += 2
if n == 'G' or n == 'C':
Tm += 4
return Tm
def reverse_comp(p):
reverse = ""
for n in p[::-1]:
reverse += reverse_comp_dict[n]
return reverse
while True:
print "--------------------START--------------------"
primer = raw_input("\nWhat is your primer sequence? \
\n(Press CTRL-C to terminate program.) \
\n> ").upper()
print "\nYour primer sequence is:\n5' %s (%s bp)\n" % (primer, len(primer))
print "Its reverse complement is:\n5'", reverse_comp(primer), "(%s bp)\n" % len(primer)
print "The Tm of this primer (A,T=2°C, G,C=4°C) is:\n", melting_temp(primer), "°C"
print "\n"
| false
|
ae6a511723cc0f54dc39d56b2c9ed70ed3bb9305
|
lnbe10/Math-Thinking-for-Comp-Sci
|
/combinatory_analysis/dice-game.py
| 2,755
| 4.1875
| 4
|
# dice game:
# a shady person has various dices in a table
# the dices can have arbitrary values in their
# sides, like:
# [1,1,3,3,6,6]
# [1,2,3,4,5,6]
# [9,9,9,9,9,1]
# The shady person lets you see the dices
# and tell if you want to choose yor dice before
# or after him
# after both of you choose,
# them roll your dices, and see
# who wins (the one with bigger number showing up)
# to maximize the chances of winning, you have to
# do some tasks:
# 1- check if there's a dice better than all others
# 1.1 - if it exists, you choose first and select it
# 1.2 - if it doesn't exist, you let the shady person
# choose a dice and you choose one wich is better
# than his one .-.
def count_wins(dice1, dice2):
assert len(dice1) == 6 and len(dice2) == 6
dice1_wins, dice2_wins = 0, 0
for i in dice1:
for j in dice2:
if i>j:
dice1_wins+=1;
if j>i:
dice2_wins+=1;
return (dice1_wins, dice2_wins)
dice1 = [1, 2, 3, 4, 5, 6];
dice2 = [1, 2, 3, 4, 5, 6];
count_wins(dice1,dice2);
dice3 = [1, 1, 6, 6, 8, 8];
dice4 = [2, 2, 4, 4, 9, 9];
count_wins(dice3,dice4);
def find_the_best_dice(dices):
assert all(len(dice) == 6 for dice in dices)
wins = [0 for i in range(len(dices))];
for i in range(len(dices)):
for j in range(i+1, len(dices)):
versus = count_wins(dices[i], dices[j]);
if versus[0]>versus[1]:
wins[i]+=1;
if versus[1]>versus[0]:
wins[j]+=1;
if max(wins) == len(dices)-1:
#print('best dice is', wins.index(max(wins)));
return wins.index(max(wins));
#print('no best dice');
return -1
find_the_best_dice([[1, 1, 6, 6, 8, 8], [2, 2, 4, 4, 9, 9], [3, 3, 5, 5, 7, 7]]);
find_the_best_dice([[3, 3, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [4, 4, 4, 4, 0, 0], [5, 5, 5, 1, 1, 1]]);
find_the_best_dice([[1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7], [1, 2, 3, 4, 5, 6]]);
def compute_strategy(dices):
assert all(len(dice) == 6 for dice in dices)
strategy = dict()
strategy["choose_first"] = True
strategy["first_dice"] = 0
for i in range(len(dices)):
strategy[i] = (i + 1) % len(dices)
if find_the_best_dice(dices) != -1:
strategy["choose_first"] = True;
strategy["first_dice"] = find_the_best_dice(dices);
else:
strategy["choose_first"] = False;
for i in range(len(dices)):
for j in range(i+1, len(dices)):
versus = count_wins(dices[i], dices[j]);
if versus[0]>versus[1]:
strategy[j]=i;
if versus[1]>versus[0]:
strategy[i]=j;
print(strategy);
return strategy;
dices = [[4, 4, 4, 4, 0, 0], [7, 7, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [5, 5, 5, 1, 1, 1]];
compute_strategy(dices);
dices2 = [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]];
#compute_strategy(dices2);
| true
|
a60df60f1bd19896da30e8d46be5fee3a020413c
|
battyone/Practical-Computational-Thinking-with-Python
|
/ch4_orOperator.py
| 220
| 4.125
| 4
|
A = True
B = False
C = A and B
D = A or B
if C == True:
print("A and B is True.")
else:
print("A and B is False.")
if D == True:
print("A or B is True.")
else:
print("A or B is False.")
| true
|
1c9483e36d864bd7a8f5722f60801cda7e6c521f
|
tx621615/pythonlearning
|
/02tab.py
| 223
| 4.15625
| 4
|
# 测试缩进,python中没有大括号,通过相同的缩进表示同一个代码块
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False") # 缩进不同则不在同一个块中
| false
|
255c09b29bc9cd76e730a64a0722d24b003297c8
|
ugneokmanaite/api_json
|
/json_exchange_rates.py
| 1,068
| 4.3125
| 4
|
import json
# create a class Exchange Rates
class ExchangeRates:
# with required attributes
def __init__(self):
pass
# method to return the exchange rates
def fetch_ExchangeRates(self):
with open("exchange_rates.json", "r") as jsonfile:
dataset = json.load(jsonfile)
# For loop to get all exchange rates
for e in dataset:
if e == "rates":
print(dataset(["rates"]))
currency = input("What currency would you like the exchange rate of, please see list.\n")
# display exchange rates with specific currencies
print(dataset["rates"][currency])
e = ExchangeRates
e.__init__(ExchangeRates)
# fetch the data from exchange_rates.json
# method to return the exchange rates
# creating an object of class
# rate_display = ExchangeRates ("exchange_rates.json")
# print(rate_display.rates)
# display the data
# display the type of data
# method to return the exchange rates
# display exchange rates with specific currencies
| true
|
9445b358d4c35b1caec4c3bc2620b47ef514d331
|
MathewsPeter/PythonProjects
|
/biodata_validater.py
| 1,124
| 4.5625
| 5
|
'''Example: What is your name? If the user enters * you prompt them that the input is wrong, and ask them to enter a valid name.
At the end you print a summary that looks like this:
- Name: John Doe
- Date of birth: Jan 1, 1954
- Address: 24 fifth Ave, NY
- Personal goals: To be the best programmer there ever was.
'''
while(1):
name = input("Enter name: ")
if name.replace(" ", "").isalpha():
break
print("Name shall have only alphabets and space. Please try again.\n")
while(1):
dob = input("Enter DOB as DDMMYYY: ")
dd = (int)(dob[0:2])
mm = (int)(dob[2:4])
yyyy = (int)(dob[4:8])
if(dd>0 and dd<=31):
if(mm>0 and mm<=12):
if(yyyy>1900 and yyyy<=2021):
break;
else:
print("Year should be between 1900 and 2021. Please try again.\n")
else:
print("Month should be between 1 and 12. Please try again.\n")
else:
print("Date should be between 1 and 31. Please try again.\n")
print("Name is ", name)
print("DOB is ", dd,"-",mm,"-",yyyy)
| true
|
f105606ceb0d3a72e2d35e88a78952fed10f38a7
|
MathewsPeter/PythonProjects
|
/bitCountPosnSet.py
| 408
| 4.15625
| 4
|
'''
input a 8bit Number
count the number of 1s in it's binary representation
consider that as a number, swap the bit at that position
'''
n = (int)(input("enter a number between [0,127] both inclusive"))
if n<0 or n>127:
print("enter properly")
else:
n_1= n
c = 0
while n:
if n&0b1:
c+=1
n = n>>1
print(c)
n_2 = n_1 ^ (1<<c)
print(n_2)
| true
|
3966d55212271c1a681156beaee25f6820a076fc
|
zsamantha/coding_challenge
|
/calc.py
| 1,217
| 4.125
| 4
|
import math
print("Welcome to the Calculator App")
print("The following operations are available: + - / *")
print("Please separate entries with a space. Ex: Use 1 + 2 instead of 1+2")
print("Type \"Q\" to quit the program.")
result = None
op = None
while(True):
calc = input().strip().split()
if calc[0].lower() == "q":
break
for item in calc:
if item.isnumeric():
if result is None:
result = int(item)
else:
num = int(item)
if op == "+":
result += num
elif op == "-":
result -= num
elif op == "*":
result *= num
elif op == "/":
result /= num
else:
print("Bad Input.")
result = None
break
elif item.isalpha():
print("Bad Input")
result = None
break
else:
op = item
if result is not None:
if result % 1 == 0:
print("= ", math.trunc(result))
else:
print("= {0:.2f}".format(result))
print("Goodbye :)")
| true
|
31d0b19e04fce106e14c19aec9d7d6f463f0d852
|
panchaly75/MyCaptain_AI
|
/AI_MyCaptainApp_03(1).py
| 863
| 4.3125
| 4
|
#Write a Python Program for Fibonacci numbers.
def fibo(input_number):
fibonacci_ls=[]
for count_term in range(input_number):
if count_term==0:
fibonacci_ls.append(0)
elif count_term==1:
fibonacci_ls.append(1)
else:
fibonacci_ls.append(fibonacci_ls[count_term-2]+fibonacci_ls[count_term-1])
return fibonacci_ls
number = int(input("Enter how much terms you want?\t:\t"))
ls = fibo(number)
print(ls)
'''
#if you want to print without list type, so in place of print(ls), you can use below lines of code
for item in ls:
print(item, end=' ')
#in place of define fuction you may also use only for loop
https://github.com/panchaly75/MyCaptainPythonProjects/blob/main/project03.py
in this above github link has same code with for loop
'''
#https://colab.research.google.com/drive/1gK-J2dPT7Cn5HP0EFNJrf0S-6x0pyWki?usp=sharing
| true
|
ebb169123be03b88cdd6dcfab33657bd4a60f573
|
Devlin1834/Games
|
/collatz.py
| 1,792
| 4.15625
| 4
|
## Collatz Sequence
## Idea from Al Sweigart's 'Automate the Boring Stuff'
def collatz():
global over
over = False
print("Lets Explore the Collatz Sequence")
print("Often called the simplest impossible math problem,")
print("the premise is simple, but the results are confusing!")
print("Lets start and see if you can catch on...")
c = ''
while c == '':
try:
c = int(input("Type in any integer: "))
except ValueError:
print("Thats very funny but its NOT an integer")
while c != 1:
if c % 2 == 0:
c = c // 2
print(c)
elif c % 2 == 1:
c = (3 * c) + 1
print(c)
if c == 1:
print("Do you get it?")
print("For ANY real integer, you can reduce it down to 1 using the Collatz Sequence")
print("If the number is even, take n/2")
print("If the number is odd, take 3n+1")
print("Follow that sequence with your answers until you reach 1")
print()
print("Lets keep going")
print("Type 0 at any point to return to the Games screen")
while over == False:
newc = ''
while newc != 0:
try:
print("-" * 65)
newc = int(input("Type in any number: "))
except ValueError:
print("Thats very funny but its NOT a number")
if newc == 0:
over = True
break
while newc != 1:
if newc % 2 == 0:
newc = newc // 2
print(newc)
elif newc % 2 == 1:
newc = (3 * newc) + 1
print(newc)
| true
|
26a77eaf507d1b0107e311ee09706bc352e70ced
|
ScottG489/Task-Organizer
|
/src/task/task.py
| 2,528
| 4.125
| 4
|
"""Create task objects
Public classes:
Task
TaskCreator
Provides ways to instantiate a Task instance.
"""
from textwrap import dedent
# TODO: Should this be private if TaskCreator is to be the only
# correct way to make a Task instance?
class Task():
"""Instantiate a Task object.
Provides attributes for tasks and methods to compare Task instances.
"""
def __init__(self, **kwargs):
try:
self.key = kwargs['key']
except KeyError:
self.key = None
try:
self.title = kwargs['title']
except KeyError:
self.title = None
try:
self.notes = kwargs['notes']
except KeyError:
self.notes = None
# self.priority = priority
# self.tags = tags
def __str__(self):
return dedent('''\
ID: %(key)s
Title: %(title)s
Notes: %(notes)s''') % {
'key': self.key,
'title': self.title,
'notes': self.notes
}
def __eq__(self, other):
if not isinstance(other, Task):
return False
if self.key == other.key\
and self.title == other.title\
and self.notes == other.notes:
return True
return False
def __ne__(self, other):
if not isinstance(other, Task):
return True
if self.key != other.key\
or self.title != other.title\
or self.notes != other.notes:
return True
return False
class TaskCreator():
"""Create a Task instance automatically.
Public methods:
build(arg_dict)
Create a Task instance in a automatic and safer manner."""
def __init__(self):
pass
@staticmethod
def build(arg_dict):
"""Creates a Task instance given a dictionary.
Args:
arg_dict (dict): dictionary formatted to create a Task
The given dictionary must have a correct naming scheme. However, it
can be missing any field.
"""
task_item = Task()
try:
task_item.key = arg_dict['key']
except KeyError:
task_item.key = None
try:
task_item.title = arg_dict['title']
except KeyError:
task_item.title = None
try:
task_item.notes = arg_dict['notes']
except KeyError:
task_item.notes = None
return task_item
| true
|
3ac26042891246dead71c85f0fd59f5f7316a516
|
akhilpgvr/HackerRank
|
/iterative_factorial.py
| 408
| 4.25
| 4
|
'''
Write a iterative Python function to print the factorial of a number n (ie, returns n!).
'''
usersnumber = int(input("Enter the number: "))
def fact(number):
result = 1
for i in range(1,usersnumber+1):
result *= i
return result
if usersnumber == 0:
print('1')
elif usersnumber < 0:
print('Sorry factorial exists only for positive integers')
else:
print(fact(usersnumber))
| true
|
a412e958ac2c18dd757f6b5a3e91fd897eda6658
|
akhilpgvr/HackerRank
|
/fuzzbuzz.py
| 435
| 4.1875
| 4
|
'''
Write a Python program to print numbers from 1 to 100 except for multiples of 3
for which you should print "fuzz" instead, for multiples of 5 you should print
'buzz' instead and for multiples of both 3 and 5, you should print 'fuzzbuzz' instead.
'''
for i in xrange(1,101):
if i % 15 == 0:
print 'fuzzbuzz'
elif i % 3 == 0:
print 'fuzz'
elif i % 5 == 0:
print 'buzz'
else:
print i
| true
|
0cacf9f1b270d2814847c7d4091de5592bc47bad
|
SherriChuah/google-code-sample
|
/python/src/playlists.py
| 1,501
| 4.1875
| 4
|
"""A playlists class."""
"""Keeps the individual video playlist"""
from .video_playlist import VideoPlaylist
class Playlists:
"""A class used to represent a Playlists containing video playlists"""
def __init__(self):
self._playlist = {}
def number_of_playlists(self):
return len(self._playlist)
def get_all_playlists(self):
"""Returns all available playlist information from the playlist library."""
return list(self._playlist.values())
def get_playlist(self, playlist_name):
"""Returns the videoplaylist object (name, content) from the playlists.
Args:
playlist_name: Name of playlist
Returns:
The VideoPlaylist object for the requested playlist_name. None if the playlist does not exist.
"""
for i in self._playlist:
if i.lower() == playlist_name.lower():
return self._playlist[i]
def add_playlist(self, playlist: VideoPlaylist):
"""Adds a playlist into the dic of playlists
Args:
playlist: VideoPlaylist object
"""
lower = [i.lower() for i in self._playlist.keys()]
if playlist.name.lower() in lower:
return False
else:
self._playlist[playlist.name] = playlist
return True
def remove_playlist(self, name):
"""Remove a playlist from the dic of playlists
Args:
name: name of playlist
"""
lower = [i.lower() for i in self._playlist.keys()]
if name.lower() in lower:
self._playlist.pop(self.get_playlist(name).name)
return True
else:
return False
| true
|
861ada8af86a6060dfc173d19e0364e2132a447e
|
DataActivator/Python3tutorials
|
/Decisioncontrol-Loop/whileloop.py
| 944
| 4.21875
| 4
|
'''
A while loop implements the repeated execution of code based on a given Boolean condition.
while [a condition is True]:
[do something]
As opposed to for loops that execute a certain number of times, while loops are conditionally based
so you don’t need to know how many times to repeat the code going in.
'''
# Q1:- run the program until user don't give correct captain name
captain = ''
while captain != 'Virat':
captain = input('Who is the captain of indian Team :- ')
print('Yes, The captain of india is ' + captain)
print('Yes, the captain of india is {} ' .format(captain))
print(f'Yes, The captain of India is {captain.upper()}')
# break & continue example in while loop
i = 0
while i<5:
print(i)
if i == 3:
break
i += 1
# else block in for & while loop
i = 0
while i<5:
print(i)
# if i == 3:
# break
i += 1
else :
print('After while loop ')
print('Data Activator')
| true
|
7646890051144b6315cd22fd1b5e04a44d9b266a
|
jabedude/python-class
|
/projects/week3/jabraham_guessing.py
| 1,625
| 4.1875
| 4
|
#!/usr/bin/env python3
'''
This program is an implementation of the "High-Low Guessing Game".
The user is prompted to guess a number from 1 to 100 and the
program will tell the user if the number is greater, lesser, or
equal to the correct number.
'''
from random import randint
def main():
'''
This function is the entry point of the program and handles user
interaction with the game.
'''
# CONSTANTS #
ANSWER = randint(1, 100)
BANNER = '''Hello. I'm thinking of a number from 1 to 100...
Try to guess my number!'''
PROMPT = "Guess> "
# MESSAGES #
err_msg = "{} is an invalid choice. Please enter a number from 1 to 100."
suc_msg = "{} was correct! You guessed the number in {} guess{}."
wrong_msg = "{} is too {}!"
print(BANNER)
valid_guesses = 0
while True:
user_input = input(PROMPT)
valid_guesses += 1
try:
user_input = int(user_input)
if user_input not in range(1, 101):
raise ValueError
elif user_input == ANSWER:
guess_ending = "es"
if valid_guesses == 1:
guess_ending = ""
print(suc_msg.format(user_input, valid_guesses, guess_ending))
exit(0)
else:
guess_clue = "high"
if user_input < ANSWER:
guess_clue = "low"
print(wrong_msg.format(user_input, guess_clue))
except ValueError:
valid_guesses -= 1
print(err_msg.format(user_input))
if __name__ == "__main__":
main()
| true
|
fcdebbb78ba2d4c5b41967801b0d537c35e85c3a
|
jabedude/python-class
|
/chapter5/ex6.py
| 384
| 4.125
| 4
|
#!/usr/bin/env python3
def common_elements(list_one, list_two):
''' returns a list of common elements between list_one and list_two '''
set_one = set(list_one)
set_two = set(list_two)
return list(set_one.intersection(set_two))
test_list = ['a', 'b', 'c', 'd', 'e']
test_list2 = ['c', 'd', 'e', 'f', 'g']
test = common_elements(test_list, test_list2)
print(test)
| true
|
53c1ca380af737aabe9ce0e265b18011a3e290a2
|
jabedude/python-class
|
/chapter9/ex4.py
| 655
| 4.3125
| 4
|
#!/usr/bin/env python3
''' Code for exercise 4 chapter 9 '''
import sys
def main():
'''
Function asks user for two file names and copies the first to the second
'''
if len(sys.argv) == 3:
in_name = sys.argv[1]
out_name = sys.argv[2]
else:
in_name = input("Enter the name of the input file: ")
out_name = input("Enter the name of the output file: ")
with open(in_name, "r") as in_file, open(out_name, "w") as out_file:
while True:
line = in_file.readline()
if not line:
break
out_file.write(line)
if __name__ == "__main__":
main()
| true
|
c722a49a7f8b4b80ed4238b53759e922299957e2
|
jabedude/python-class
|
/chapter7/restaurant.py
| 1,686
| 4.21875
| 4
|
#!/usr/bin/env python3
class Category():
''' Class represents Category objects. Only has a name '''
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
def __str__(self):
return self.name
class MenuItem(Category):
''' Class represents a MenuItem object. Has a name, description, and price. '''
def __init__(self, name, desc, price):
super().__init__(name)
self.desc = desc
self.price = price
@property
def desc(self):
return self._desc
@desc.setter
def desc(self, desc):
self._desc = desc
@property
def price(self):
return self._price
@price.setter
def price(self, price):
self._price = price
def __str__(self):
return "Name: {}\nDescription: {}\nPrice: ${}".format(self.name, self.desc, self.price)
class Restaurant():
'''
Class represents a Restaurant object, a list of MenuItems. Has add() method
to add MenuItems to list.
'''
def __init__(self, *menu_items):
self.menu_items = list(menu_items)
@property
def menu_items(self):
return self._menu_items
@menu_items.setter
def menu_items(self, menu_items):
self._menu_items = menu_items
def add(self, item):
''' Method adds MenuItem to Restaurant obj '''
self.menu_items.append(item)
def __str__(self):
results = []
for num, item in enumerate(self.menu_items):
results.append("Item {}\n{}\n".format(num + 1, item))
return "\n".join(results)
| false
|
9e3dac800bd632b85beb9c905687e1141547732c
|
UlisesND/CYPUlisesND
|
/listas2.py
| 1,361
| 4.40625
| 4
|
# arreglos
#lectura
#escritura/ asignacion
#actualizacion: insercion, eliminacion, modificacion
#busqueda
#escritura
frutas = ["Zapote", "Manzana" , "Pera", "Aguaquate", "Durazno", "uva", "sandia"]
#lectura, el selector [indice]
print (frutas[2])
# Lectura con for
#for opcion 1
for indice in range (0,7,1):
print (frutas[indice])
print ("-------")
# for opcion 2 -- por un iterador each
for fr in frutas:
print (fr)
#asignacion
frutas[2]="melon"
print (frutas)
#insercion al final
frutas.append("Naranja")
print(frutas)
print(len(frutas))
frutas.insert(2,"limon")
print(frutas)
print(len(frutas))
frutas.insert(0, "mamey")
print(frutas)
#eliminacion con pop
print(frutas.pop())
print(frutas)
print(frutas.pop(1))
print(frutas)
frutas[2]="limon"
frutas.append("limon")
print(frutas)
frutas.remove("limon")
print(frutas)
#ordenamiento
frutas.sort()
print(frutas)
frutas.reverse()
print(frutas)
#busqueda
print(f"El limon esta en la posicion, {frutas.index('limon') }")
print(f"El limon esta {frutas.count('limon')} veces en la lista")
#concatenar
print(frutas)
otras_frutas = ["rambutan","mispero", "liche","pitahaya"]
frutas.extend(otras_frutas)
print(frutas)
# copiar
copia=frutas
copia.append("naranja")
print(frutas)
print(copia)
otracopia = frutas.copy()
otracopia.append("fresa")
otracopia.append("fresa")
print(frutas)
print(otracopia)
| false
|
ed544f53a3a328aff0bdd1246a7a1db33867589c
|
Dulal-12/Python-basic-300
|
/50+/Test6.py
| 202
| 4.15625
| 4
|
#Find BMI
height = float(input("Enter height ft(foot) : "))
weight = float(input("Enter weight Kg : "))
height = (height*12*2.54)/100
BMI = round(weight/height**2)
print(f'Your BMI is {BMI} KGM^2')
| false
|
4bfff67203f0ab60a696bdb49cbc00de7db79767
|
govindak-umd/Data_Structures_Practice
|
/LinkedLists/singly_linked_list.py
| 2,864
| 4.46875
| 4
|
"""
The code demonstrates how to write a code for defining a singly linked list
"""
# Creating a Node Class
class Node:
# Initialize every node in the LinkedList with a data
def __init__(self, data):
# Each of the data will be stored as
self.data = data
# This is very important because is links one
# of the node to the next one and by default
# it is linked to none
self.next = None
# Creating a LinkedList class
class LinkedList:
def __init__(self, ):
# The below is the head of the LinkedList
# which is the first element of a LinkedList
self.head = None
# Writing a function to print the LinkedList
def PrintLinkedList(self):
temporary_head = self.head
while temporary_head is not None:
print(temporary_head.data)
temporary_head = temporary_head.next
# Implement addition at the beginning functionality
def addBeginning(self, new_node):
new_node_beg = Node(new_node)
new_node_beg.next = self.head
self.head = new_node_beg
# Implement addition at the end functionality
def addEnd(self, new_node):
new_node_end = Node(new_node)
# creating a temporary head
temp_head = self.head
# keep looping until the head doesn't have anything next
while temp_head.next:
temp_head = temp_head.next
temp_head.next = new_node_end
# Implement addition at the middle functionality
def removeNode(self, new_node):
new_node_removed = Node(new_node)
temp_head = self.head
# removing the first element
if self.head.data == new_node_removed.data:
temp_head = temp_head.next
self.head = temp_head
# for removing the any other element other than the first element
while temp_head.next:
if temp_head.next.data == new_node:
temp_head.next = temp_head.next.next
break
else:
temp_head = temp_head.next
if __name__ == '__main__':
# Creating a LinkedList object
linked_list_object = LinkedList()
# Defining the head for the linkedList
linked_list_object.head = Node(1)
# defining the second, third and fourth elements in the linked list
second = Node(2)
third = Node(3)
fourth = Node(4)
# Linking each element to the next element starting with
# linking the head to the second element
linked_list_object.head.next = second
second.next = third
third.next = fourth
# Testing adding in the beginning
linked_list_object.addBeginning(99)
# Testing adding at the end
linked_list_object.addEnd(55)
# Testing removing any key in the LinkedList
linked_list_object.removeNode(3)
linked_list_object.PrintLinkedList()
| true
|
dc8e36cdd048bcff0c3bfaa69c71923fd53ec7bc
|
pgrandhi/pythoncode
|
/Assignment2/2.VolumeOfCylinder.py
| 367
| 4.15625
| 4
|
#Prompt the use to enter radius and length
radius,length = map(float, input("Enter the radius and length of a cylinder:").split(","))
#constant
PI = 3.1417
def volumeOfCylinder(radius,length):
area = PI * (radius ** 2)
volume = area * length
print("The area is ", round(area,4), " The volume is ", round(volume,1))
volumeOfCylinder(radius,length)
| true
|
670e2caa200e7b81c4c67abe0e8db28c9d3bce5d
|
pgrandhi/pythoncode
|
/Class/BMICalculator.py
| 584
| 4.3125
| 4
|
#Prompt the user for weight in lbs
weight = eval(input("Enter weight in pounds:"))
#Prompt the user for height in in
height = eval(input("Enter height in inches:"))
KILOGRAMS_PER_POUND = 0.45359237
METERS_PER_INCH = 0.0254
weightInKg = KILOGRAMS_PER_POUND * weight
heightInMeters = METERS_PER_INCH * height
#Compute BMI = WgightInKg/(heightInMeters squared)
bmi = weightInKg /(heightInMeters ** 2)
print("BMI is: ", bmi)
if(bmi <18.5):
print("Under-weight")
elif (bmi <25):
print("Normal weight")
elif (bmi <30):
print("Over-weight")
else:
print("Obese")
| true
|
7b8241125841ad4f17077ed706af394576f6a0dc
|
briand27/LPTHW-Exercises
|
/ex20.py
| 1,172
| 4.15625
| 4
|
# imports System
from sys import argv
# creates variables script and input_file for arguments
script, input_file = argv
# define a function that takes in a file to read
def print_all(f):
print f.read()
# define a function that takes in a file to seek
def rewind(f):
f.seek(0)
# defines a function that prints out the given line of a given file
def print_a_line(line_count, f):
print line_count, f.readline()
# creates a variable that represents the open input_file
current_file = open(input_file)
print "First let's print the whole file:\n"
# calls print_all on the given file
print_all(current_file)
print "Now let's rewind, kind of like a tape."
# calls rewind on the given current_file
rewind(current_file)
print "Let's print three lines:"
# sets current_line to 1 the prints that line of the current_file
current_line = 1
print_a_line(current_line, current_file)
# sets the current_line one higher then prints that line of the current_file
current_line += 1
print_a_line(current_line, current_file)
# sets the current_line one higher again then prints that line of
# the current_file
current_line += 1
print_a_line(current_line, current_file)
| true
|
38aa94d68254fe0903e6eb1de10d10c23eab47b6
|
mlbudda/Checkio
|
/home/sort_by_frequency.py
| 542
| 4.34375
| 4
|
# Sort Array by Element Frequency
def frequency_sort(items):
""" Sorts elements by decreasing frequency order """
return sorted(items, key=lambda x: (-items.count(x), items.index(x)))
# Running some tests..
print(list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2])
print(list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex'])
print(list(frequency_sort([17, 99, 42])) == [17, 99, 42])
print(list(frequency_sort([])) == [])
print(list(frequency_sort([1])) == [1])
| false
|
03389bd8ab6b7f1a14d681c6f209c264e2e27aad
|
mlbudda/Checkio
|
/o_reilly/index_power.py
| 440
| 4.15625
| 4
|
# Index Power
def index_power(array: list, n: int) -> int:
"""
Find Nth power of the element with index N.
"""
try:
return array[n] ** n
except IndexError:
return -1
# Running some tests..
print(index_power([1, 2, 3, 4], 2) == 9, "Square")
print(index_power([1, 3, 10, 100], 3) == 1000000, "Cube")
print(index_power([0, 1], 0) == 1, "Zero power")
print(index_power([1, 2], 3) == -1, "IndexError")
| true
|
473d7d7500ffc160f056d661b0ef8a1d297a84a7
|
mnsupreme/artificial_intelligence_learning
|
/normal_equation.py
| 2,911
| 4.3125
| 4
|
#This code solves for the optimum values of the parameters analytically using calculus.
# It is an alternative way to optimizing iterarively using gradient descent. It is usually faster
# but is much more computationally expensive. It is good if you have 1000 or less parameters to solve for.
# complexity is O(n^3)
# This examply assumes the equation y = param_0(y-intercept) + param_1 * input_1 + param_2 * input_2....
# If you have an equation in a different form such as y = param_0(y-intercept) + param_1 * input_1 * input_2 + param_2 * (input_2)^2
# then you must make adjustments to the design matrix accordignly. (Multiply the inputs acordingly and use those results in the design matrix)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np
from numpy.linalg import inv
data = np.loadtxt('gradient_descent/ex3Data/ex3x.dat',dtype=float)
#this function helps put the inputs in vector form as the original data already came as a design matrix.
#This way the data is more realistic. Technically, this function is unecessary
def vectorize_data():
#regular python list
vectorized_data = []
for row in data:
# inserts a 1 in the beginning every row of the matrix to represent x_0 input
row = np.insert(row,0,1)
print "row {0}, \n row_transpose {1}".format(row, row.reshape((-1,1)))
#converts [element1, element 2] to [ form.
# element1,
# element2,
# ]
vectorized_data.append(row.reshape((-1,1)))
#you need to convert design matrix into a numpy array because it starts out as a regular python list.
vectorized_data = np.array(vectorized_data)
print vectorized_data
return vectorized_data
x = vectorize_data()
#converts vectorized data into a design matrix.
# The design matrix looks like this: design_matrix = [transpose_of_each_input_vector or transpose_of_each_row_in_vectorized_data]
def assemble_design_matrix():
#regulare python list
design_matrix = []
for row in x:
design_matrix.append(row.transpose())
#you need to convert design matrix into a numpy array before you convert it to a matrix because it starts out asa regular python list.
design_matrix = np.matrix(np.array(design_matrix))
print "design_matrix {0} \n design_matrix_transpose {1}".format(design_matrix, design_matrix.transpose())
return design_matrix
def normal():
design_matrix = assemble_design_matrix()
y = np.loadtxt('gradient_descent/ex3Data/ex3y.dat', dtype=float)
y = y.reshape(47,1)
# THIS IS THE NORMAL EQUATION FORMULA
# the function is inverse(design_matrix_transpose * design_matrix) * (design_matrix_transpose * y_vector)
# this will yield a matrix full of your optimized theta parameter values
result = inv((design_matrix.transpose() * design_matrix)) * (design_matrix.transpose() * y)
print result
return result
if __name__ == '__main__':
normal()
| true
|
ef2fb36ea0588d36aa6b49ad55d57ee4a5d64bc0
|
dguest/example-text-parser
|
/look.py
| 1,851
| 4.15625
| 4
|
#!/usr/bin/env python3
import sys
from collections import Counter
from csv import reader
def run():
input_name = sys.argv[1]
csv = reader(open(input_name), skipinitialspace=True)
# first read off the titles
titles = next(csv)
indices = {name:number for number, name in enumerate(titles)}
# keep track of something (proj_by_company) in this case
proj_by_company = Counter()
# iterate through all the records
for fields in csv:
# build up a dictionary of fields
named_fields = {titles[idx]:val for idx, val in enumerate(fields)}
company = named_fields['Company Name']
# The empty string us used in the CSV to represent zero.
comp_projs_as_string = named_fields['# projects completed']
# Unfortunately, this means that we have to manually enter
# zero in the case of en empty string. Empty strings evaluate
# to False.
#
# Note that this whole operation could be represented with some
# more magic as:
# > comp_projs = int(named_fields['# projects completed'] or 0)
# but it's a bit confusing to understand why that works.
if not comp_projs_as_string:
comp_projs = 0
else:
comp_projs = int(comp_projs_as_string)
# add to the counter
proj_by_company[company] += comp_projs
# Do some sorting. The sort function works on a container, which
# we get by using `.items()` to return a list of (key, value)
# pairs. In this case we're sorting by the second value, thus the
# anonymous function created with `lambda`.
sorted_companies = sorted(proj_by_company.items(),key=lambda x: x[1])
for company, count in reversed(sorted_companies):
if count > 0:
print(company, count)
if __name__ == '__main__':
run()
| true
|
21ebaf035e0a5bda9b9836a8c77221f20c9f4388
|
timomak/CS-1.3
|
/First try 😭/redact_problem.py
| 692
| 4.21875
| 4
|
def reduct_words(given_array1=[], given_array2=[]):
"""
Takes 2 arrays.
Returns an array with the words from the first array, that were not present in the second array.
"""
output_array = [] # Array that is gonna be returned
for word in given_array1: # For each item in the first array, loop O(n)
if word not in set(given_array2): # Check if the current item is present in the second array.
output_array.append(word) # Append to output array
return output_array # return the final array after for loop
# Custom test ;)
if reduct_words([1,2,3,4,5,10], [1,2,3,4,5,6,7,8,9,0]) == [10]:
print("works")
else:
print("Doesn't work")
| true
|
5f21ab9fdf6d7bab8a4572054ca007bc62db42d8
|
Win-Victor/algs
|
/algs_2_t8.py
| 835
| 4.1875
| 4
|
"""8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры."""
num = input('Введите цифру для подсчета в наборе чисел:\n')
count = int(input('Укажите сколько наборов чисел Вы будете вводить:\n'))
my_count = 0
my_sum = 0
while my_count != count:
my_count += 1
numbs = input(f'Введите {my_count} число:\n')
my_sum += numbs.count(num)
print(f'Цифра {num} встречалась во введенных числах {my_sum} раз(а).')
| false
|
dfa668f57584dc42dbc99c5835ebc0a5c0b1e0cd
|
avir100/ConsultAdd
|
/task2/task2_10.py
| 815
| 4.125
| 4
|
from random import randint
'''
Write a program that asks five times to guess the lucky number. Use a while loop and a counter, such as
counter=1
While counter <= 5:
print(“Type in the”, counter, “number”
counter=counter+1
The program asks for five guesses (no matter whether the correct number was guessed or not). If the correct number is guessed, the program outputs “Good guess!”, otherwise it outputs “Try again!”. After the fifth guess it stops and prints “Game over!”.
'''
counter = 1
answer = randint(1,10)
print "Answer: ", answer
while counter <= 5:
number = int(raw_input("Guess the lucky number between 1-10: \n"))
if (number == answer):
print ("Good guess!")
else:
if counter == 5:
print ("Game over!")
else:
print ("Try again!")
counter += 1
| true
|
0386d42dfae2e6489d916e10af178dd42a31cf26
|
TimeMachine00/pythonProject-4
|
/Chose-rock-paper-scissor.py
| 871
| 4.21875
| 4
|
print("created by hussainatphysics@gmail.com(hussainsha syed)")
print("welcome to the game")
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
choice = int(input("what would you like to choose? 0 for rock, 1, paper, 2 for scissors\n"))
a =[rock, paper, scissors]
b= random.randint(0,len(a)-1)
print(b)
c=a[b]
# print(c)
if b==choice:
print(c)
print("you win the game")
else:
print(c)
print("you lost the game, computer wins")
print()
but1= print(input("press enter for bye..........."))
# l = random.choice(a)
# print(l)
#
# if a.index(l)==choice:
# print('you won')
# else:
# print('you lost')
| false
|
8fdb362aa4fb0de01b740a5a840904bf329b5f22
|
lzeeorno/Python-practice175
|
/terminal&py.py
| 696
| 4.125
| 4
|
#how to use python in terminal
def main():
while True:
s = input('do you come to learn how to open py doc in terminal?(yes/no):')
if s.lower() == 'yes':
print('cd use to enter doc, ls to look the all file, python filename.py to open the py document')
s1 = input('do you understand?(yes/no):')
if s1.lower() == 'yes':
print('nice, bye')
break
else:
print('ok, come to ask again')
break
elif s.lower()== 'no':
print('ok, goodbye')
break
else:
print('wrong input, please enter yes/no')
continue
main()
| true
|
14a84fdbc18ce604fc44ae7faff93686e7622761
|
Degureshaff/python.itc
|
/python/day17/def_1.py
| 447
| 4.15625
| 4
|
def calculator(num1, num2, suff):
if suff == '*':
print(num1 * sum2)
elif suff == '/':
print(num1 / num2)
elif suff == '**':
print(num1 ** num2)
elif suff == '+':
print(num1 + num2)
elif suff == '-':
print(num1 - num2)
num1 = int(input('Число 1: '))
num2 = int(input('Число 2: '))
a = input('Какое действие предпочитаете: ')
calculator(num1, num2, a)
| false
|
94e971d062803bda0dbee06307607932b0654849
|
zongrh/untitled_python
|
/test02.py
| 1,008
| 4.15625
| 4
|
# coding=utf-8
print("hello world")
print "你好,世界!";
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "john" # 字符串
print counter
print miles
print name
# -----------------------------标准数据类型
# Numbers(数字)
# String(字符串)
# List(列表)
# Tuple(元组)
# Dictionary(字典)
# -------------------------------Python数字
var1 = 1
var2 = 10
print var1
print var2
del var1
del var2
print("--------------")
# ------------------------------Python字符串
str = "hello world"
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[5] # 输出字符串中的第五个字符(null)
print str[2:5] # 输出字符串中的第三个至第五个之间的字符串
print str[2:] # 输出第三字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出链接的字符串
print("-------------")
# --------------------------------------------------
| false
|
4f21735e9b85b9072567a6aa2df7d17ac121f39c
|
Leahxuliu/Data-Structure-And-Algorithm
|
/Python/Binary Search/33.Search in Rotated Sorted Array.py
| 1,766
| 4.28125
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/03/26
# @Author : XU Liu
# @FileName: 33.Search in Rotated Sorted Array.py
'''
1. 题目理解:
找到目标值
给到的arr是部分sort,都是升序,旋转
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand
输出target的index(0-based)
如果不存在target就输出-1
2. 题目类型:
很常考
binary search
有target,部分sort
旋转
3. 输出输入以及边界条件:
input: nums: List[int], target: int
output: int
corner case: None
4. 解题思路
1. binary search
2. 核心 arr[mid]与arr[mid+1]之间的关系
arr[mid]与arr[r]/arr[l]之间的关系
5. 时间空间复杂度:
时间复杂度:O(log n)
空间复杂度:O(1)
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: # corner case
return -1
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if target == nums[mid]:
return mid
if nums[l] < nums[mid]: # 左边是sorted
if nums[l] <= target < nums[mid]: # T在左边sorted部分内
r = mid - 1
else: # T在右边的unsorted内
l = mid + 1
elif nums[l] == nums[mid]: # 只有两个数字的时候,下一轮就return -1
l = mid + 1 # 或者l += 1
elif nums[l] > nums[mid]: # 左边是unsorted,右边是sorted
if nums[mid] < target <= nums[r]: # T在右边sortedd内
l = mid + 1
else:
r = mid - 1
return -1
| false
|
5952daff834f8f713be39ef520f25d896034a006
|
sahthi/backup2
|
/backup_files/practice/sample/exp.py
| 374
| 4.125
| 4
|
import math
x=[10,-5,1.2,'apple']
for i in x:
try:
fact=math.factorial(i)
except TypeError:
print("factorial is not supported for given input:")
except ValueError:
print ("factorial only accepts positive integers")
else:
print ("factorial of a", x, "is",fact)
finally:
print("release any resources in use")
| true
|
c980d7814d270c5f4ab39a023b3fd81d4313046e
|
JuneJoshua/Python-MITx-
|
/MITx I/Problem Set 1/vowels.py
| 249
| 4.125
| 4
|
vowels = 0
s = str(input("Enter a string: "))
for falchion in s:
if falchion == 'a' or falchion == 'e' or falchion == 'i' or falchion == 'o' or falchion == 'u':
vowels += 1
else:
vowels += 0
print("Number of vowels: " , vowels)
| false
|
b3b0800b6add715999684c41393d1df9a636459d
|
All-I-Do-Is-Wynn/Python-Codes
|
/Codewars_Challenges/get_sum.py
| 547
| 4.28125
| 4
|
# Given two integers a and b, which can be positive or negative,
# find the sum of all the integers between and including them and return it.
# If the two numbers are equal return a or b.
# Note: a and b are not ordered!
def get_sum(a,b):
sum = 0
if a < b:
for x in range(a,b+1):
sum += x
else:
for x in range(b,a+1):
sum += x
return sum
# Shortened
def get_sum2(a,b):
return sum(range(min(a,b),max(a,b)+1))
if __name__ == '__main__':
print(get_sum(0,2))
print(get_sum2(0,-2))
| true
|
15fdbc037475927e58bf3b36a60c5cffc95264bc
|
rayvantsahni/after-MATH
|
/Rotate a Matrix/rotate_matrix.py
| 1,523
| 4.40625
| 4
|
def rotate(matrix, n, d):
while n:
matrix = rotate_90_clockwise(matrix) if d else rotate_90_counter_clockwise(matrix)
n -= 1
return matrix
def rotate_90_counter_clockwise(matrix):
"""
The function rotates any square matrix by 90° counter clock-wise.
"""
for row in matrix:
row.reverse()
n = len(matrix)
for row in range(n):
for col in range(row, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
return matrix
def rotate_90_clockwise(matrix):
"""
The function rotates any square matrix by 90° clock-wise.
"""
n = len(matrix)
for row in range(n):
for col in range(row, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
for row in matrix:
row.reverse()
return matrix
if __name__ == "__main__":
# matrix_1 = [[1]]
# matrix_2 = [[1, 2],
# [3, 4]]
matrix_3 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# matrix_4 = [[1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# [13, 14, 15, 16]]
number_of_rotations = int(input("Enter the number of times you want to rotate the matrix:\n"))
print("To rotate COUNTER-CLOCKWISE enter 0, OR\nTo rotate CLOCKWISE enter 1.")
direction = int(input())
print("Rotated Matrix:")
for row in (rotate(matrix_3, number_of_rotations % 4, direction % 2)):
print(row)
| true
|
1adada8a6b7d5332bed5c37d411571ca2ab1eae8
|
ursawd/springboardexercises
|
/Unit18/Unit18-2/fs_4_reverse_vowels/reverse_vowels.py
| 1,200
| 4.25
| 4
|
def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Reverse Vowels In A String")
'RivArsI Vewols en e Streng'
>>> reverse_vowels("aeiou")
'uoiea'
>>> reverse_vowels("why try, shy fly?")
'why try, shy fly?'
"""
vowels = "aeiou"
new_s = list(s)
stop = len(s)
for i in range(0, len(s) - 1, 1): # start,stop,index
if s[i] in vowels:
for j in range(stop - 1, -1, -1):
if j + 1 == i:
return "".join(new_s)
if new_s[j] in vowels:
new_s[j], new_s[i] = new_s[i], new_s[j]
stop = j
break
return "".join(new_s)
# print(reverse_vowels("1a2e3i4o"))
# # 1d2c3b4a
# print(reverse_vowels("Hello!"))
# print(reverse_vowels("Tomatoes"))
# #'Temotaos'
# print(reverse_vowels("Reverse Vowels In A String"))
# #'RivArsI Vewols en e Streng'
# print(reverse_vowels("aeiou"))
| false
|
c6d2d5095d319fdfe43ad2dc712cd97cbe44cb9e
|
rohit-kuma/Python
|
/List_tuples_set.py
| 1,822
| 4.1875
| 4
|
courses = ["history", "maths", "hindi"]
print(courses)
print(len(courses))
print(courses[1])
print(courses[-1])
print(courses[0:2])
courses.append("art")
courses.insert(1, "Geo")
courses2 = ["Art", "Education"]
print(courses)
#courses.insert(0, courses2)
#print(courses)
courses2.extend(courses)
print(courses2)
print(courses2.pop())
print(courses2)
courses2.remove("Geo")
print(courses2)
courses2.reverse()
print(courses2)
courses2.sort()
print(courses2)
num = [5, 1, 4]
num.sort(reverse=True)
print(num)
#without altering the original
num2 = sorted(num)
print(num2)
print(min(num2))
print(max(num2))
print(sum(num2))
print(num2.index(4))
print(4 in num2)
for i in courses2:
print(i)
for index, courses in enumerate(courses2):
print(index, courses)
for index, courses in enumerate(courses2, start = 1):
print(index, courses)
courses_str = ", ".join(courses2)
print(courses_str)
new_list = courses_str.split(", ")
print(new_list)
#Tuples
#List are mutables tuples are not
# Mutable
print("Mutable List")
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1
print(list_1)
print(list_2)
list_1[0] = 'Art'
print(list_1)
print(list_2)
print("Immutable List")
# Immutable
tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# tuple_1[0] = 'Art'
print(tuple_1)
print(tuple_2)
print("Sets")
# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
art_courses = {"Math", "GEO", "Physics"}
print(cs_courses)
print(art_courses)
print(cs_courses.intersection(art_courses))
print(cs_courses.difference(art_courses))
print(cs_courses.union(art_courses))
# Empty Lists
empty_list = []
empty_list = list()
# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()
# Empty Sets
empty_set = {} # This isn't right! It's a dict
empty_set = set()
| true
|
598a1c47c454c6e31408824cdec50d9d4a262cef
|
mswinkels09/Critters_Croquettes_server
|
/animals/petting_animals.py
| 2,463
| 4.3125
| 4
|
# import the python datetime module to help us create a timestamp
from datetime import date
from .animals import Animal
from movements import Walking, Swimming
# Designate Llama as a child class by adding (Animal) after the class name
class Llama(Animal):
# Remove redundant properties from Llama's initialization, and set their values via Animal
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift # stays on Llama because not all animals have shifts
self.walking = True
def feed(self):
print(f'{self.name} was not fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Goose(Animal, Walking, Swimming):
def __init__(self, name, species, food):
# No more super() when initializing multiple base classes
Animal.__init__(self, name, species, food)
Swimming.__init__(self)
Walking.__init__(self)
# no more self.swimming = True
...
def honk(self):
print("The goose honks. A lot")
# run is defined in the Walking parent class, but also here. This run method will take precedence and Walking's run method will not be called by Goose instances
def run(self):
print(f'{self} waddles')
def __str__(self):
return f'{self.name} the Goose'
class Goat(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
def feed(self):
print(f'{self.name} was enthusiastically fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Donkey(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
def feed(self):
print(f'{self.name} was obnoxiously fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Pig(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
class Ox(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
| true
|
c27892b565bb1731b02f2fa7f6258419bad34edd
|
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
|
/Day42_RedactText.py
| 1,421
| 4.6875
| 5
|
# Day 42 Challenge: Redacting Text in a File
# Sensitive information is often removed, or redacted, from documents before they are released to the public.
# When the documents are released it is common for the redacted text to be replaced with black bars. In this exercise
# you will write a program that redacts all occurrences of sensitive words in a text file by replacing them with
# asterisks. Your program should redact sensitive words wherever they occur, even if they occur in the middle of
#another word. The list of sensitive words will be provided in a separate text file. Save the redacted version of the
# original text in a new file. The names of the original text file, sensitive words file, and redacted file will all
# be provided by the user...
#Main
fname = input("Enter Source File Name:")
inf = open(fname, "r")
senfile = input("Enter File name contains Sensitive words:")
fsen = open(senfile, "r")
words = []
for line in fsen.readlines():
line = line.rstrip()
line = line.lower()
if line != " ":
words.append(line)
fsen.close()
#print(words)
outfile = input("Enter Output File name:")
outf = open(outfile, "w")
line = inf.readline()
while line != "":
line = line.rstrip()
line = line.lower()
for word in words:
line = line.replace(word, "*" * len(word))
outf.write(line)
line = inf.readline()
inf.close()
outf.close()
| true
|
dc24942f5115667462dd5c11064d903c92d38825
|
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
|
/Day67_LastlineFile.py
| 553
| 4.46875
| 4
|
# Day 67 Challenge: Print last Line of a File.
# Function iterates over lines of file, store each line in lastline.
# When EOF, the last line of file content is stored in lastline variable.
# Print the result.
def get_final_line(fname):
fhand = open(fname, "r")
for line in fhand:
fhand = line.rstrip()
lastline = line
print("The Last Line is:")
print(lastline)
# Main
# Read the File name & pass it as an argument to get_final_line function.
fname = input('Enter a File Name:')
get_final_line(fname)
| true
|
ec508478bbd76531f1ef8e2a7a849254092cb3e4
|
Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges
|
/Day45_RecurStr.py
| 689
| 4.28125
| 4
|
# Day 45: Recursive (String) Palindrome
def Palindrome(s):
# If string length < 1, return TRUE.
if len(s) < 1:
return True
else:
# Last letter is compared with first, function called recursively with argument as
# Sliced string (With first & last character removed.)
if s[0] == s[-1]:
return Palindrome(s[1:-1])
else:
return False
# Main
# Read Input String.
str = input("Enter a String:")
# Convert to lower case to avoid mistake.
str = str.lower()
# Function call & Print Result.
if Palindrome(str):
print("The Given String is a Palindrome.")
else:
print("The Given String is Not a Palindrome.")
| true
|
a3cb102f415dfe67c53f3ff697b3d78369b5da11
|
sehammuqil/python-
|
/day18,19.py
| 481
| 4.1875
| 4
|
#list
student =['sara','nora','hind']
print(student)
#append
student =['sara','nora','hind']
student.append("seham")
print(student)
#insert
student =['sara','nora','hind']
student.insert(2,"seham")
print(student)
#pop
student =['sara','nora','hind']
student.pop(2)
print(student)
#clear
student =['sara','nora','hind']
student.clear()
print(student)
tuple = ("java","python","swift")
if "python" in tuple:
print("yes python in the tuple")
| false
|
ae91ee6ae54b217b4db050fdb6312e1a1ba116b8
|
sehammuqil/python-
|
/day16.py
| 572
| 4.34375
| 4
|
thistuple = ("apple","banana","cherry")
print(thistuple)
thistuple=()
print(thistuple)
thistuple=(3,)
print(thistuple)
thistuple=(3,1.3,4.1,7)
print(thistuple)
thistuple=("ahmad",1.1,4,"python")
print(thistuple)
thistuple = ("apple","banana","cherry")
print(thistuple[1])
thistuple = ("apple","banana","cherry")
for x in thistuple:
print(x)
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple)
thistuple = ("apple", "banana", "cherry","orange")
print(thistuple [0:3])
| false
|
1645420882248e7ffa84200b538f9294884da028
|
jmohit13/Algorithms-Data-Structures-Misc-Problems-Python
|
/data_structures/queue.py
| 1,719
| 4.25
| 4
|
# Queue Implementation
import unittest
class Queue:
"""
Queue maintain a FIFO ordering property.
FIFO : first-in first-out
"""
def __init__(self):
self.items = []
def enqueue(self,item):
"""
Adds a new item to the rear of the queue.
It needs the item and returns nothing.
"""
# temp_list = []; temp_list.append(item)
# self.items = temp_list + self.items
self.items.insert(0,item)
def dequeue(self):
"""
Removes the front item from the queue.
It needs no parameters and returns the item. The queue is modified.
"""
return self.items.pop()
def isEmpty(self):
"""
Tests to see whether the queue is empty.
It needs no parameters and returns a boolean value.
"""
return self.items == []
def size(self):
"""
Returns the number of items in the queue.
It needs no parameters and returns an integer.
"""
return len(self.items)
class QueueTest(unittest.TestCase):
def setUp(self):
self.q = Queue()
def testEnqueue(self):
self.q.enqueue('ball')
self.assertEqual(self.q.items[0],'ball')
def testDequeue(self):
self.q.enqueue('baseball')
removedItem = self.q.dequeue()
self.assertEqual(removedItem,'baseball')
def testIsEmpty(self):
self.assertTrue(self.q.isEmpty())
def testSize(self):
self.q.enqueue('ball')
self.q.enqueue('football')
self.assertEqual(self.q.size(),2)
if __name__ == "__main__":
unittest.main()
| true
|
dcb72ba1322aa085b0851b78b2d3e29f17b2ff99
|
haidragon/Python
|
/Python基础编程/Python-04/items/ItemDemo.py
| 813
| 4.28125
| 4
|
info = {"name": "laowang", "age": 18}
# 遍历key
for temp in info.keys():
print(temp)
# 遍历value
for temp in info.values():
print(temp)
# 遍历items
#Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
info_Item = info.items()
print(info_Item)
#打印字典内的数据
#方法一:直接打印元组
for temp in info.items():
print(temp)
'''结果:
('name', 'laowang')
('age', 18)'''
print("="*50)
#方法二:下标
for temp in info.items():
print("key=%s,value=%s"%(temp[0],temp[1]))
'''结果:
key = name, value = laowang
key = age, value = 18'''
print("="*50)
#方法三:拆包
for temp1,temp2 in info.items():
print("key=%s,value=%s"%(temp1,temp2))
'''结果:
key = name, value = laowang
key = age, value = 18'''
| false
|
9b4e92729e98d64c54dc2e77720ad805deecde1b
|
haidragon/Python
|
/Python基础编程/Python-09/对象/创建对象.py
| 778
| 4.15625
| 4
|
#创建一个类
class cat:
#属性
#方法
def __init__(self,a,b):
self.name = a
self.age = b
def __str__(self):
return "--str--"
def eat(self):
print("猫在吃饭")
def drink(self):
print("猫在喝水")
#若需要创建多个对象都调用这个方法,则形参需要都为self
def introduce(self):
print("%s的年龄为%d"%(self.name,self.age))
#创建一个对象
tom = cat("汤姆",40)
#调用类中的方法
tom.drink()
tom.eat()
#添加属性
#tom.name = "汤姆"
#tom.age = 40
#调用自我介绍方法
tom.introduce()
#定义第二个类
lanmao = cat("蓝猫",20)
#lanmao.name = "蓝猫"
#lanmao.age = 20
lanmao.introduce()
#定义第三个类
jumao = cat("橘猫",10)
print(jumao)
| false
|
1a6b2d6da21f7e87c107dd45b2ffeec143c2aef6
|
nivetha-ashokkumar/python-basics
|
/factorial.py
| 459
| 4.125
| 4
|
def factorial(number1, number2):
temp = number1
number1 = number2
number2 = temp
return number1, number2
number1 = int(input("enter first value:"))
number2 = int(input("enter second vakue:"))
result = factorial(nnumber1, number2)
print("factorial is:", result)
def check(result):
if(result != int):
try:
print(" given input is not integer")
except:
print("error")
return result
| true
|
8a1e5c9a01cdf662d892e06dd1344f44be378593
|
luhralive/python
|
/AK-wang/0001/key_gen_deco.py
| 837
| 4.15625
| 4
|
#!/usr/bin/env python
# -*-coding:utf-8-*-
# 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),
# 使用 Python 如何生成 200 个激活码(或者优惠券)?
import string
import random
KEY_LEN = 20
KEY_ALL = 200
def base_str():
return (string.letters+string.digits)
def key_gen():
keylist = [random.choice(base_str()) for i in range(KEY_LEN)]
return ("".join(keylist))
def print_key(func):
def _print_key(num):
for i in func(num):
print i
return _print_key
@print_key
def key_num(num, result=None):
if result is None:
result = []
for i in range(num):
result.append(key_gen())
return result
if __name__ == "__main__":
# print_key(KEY_ALL)
key_num(KEY_ALL)
| false
|
36d4bb1df1b94b7d8abcac43da7c482453cf0f4c
|
luhralive/python
|
/sarikasama/0011/0011.py
| 507
| 4.1875
| 4
|
#!/usr/bin/env python3
#filter sensitive words in user's input
def filter_sensitive_words(input_word):
s_words = []
with open('filtered_words','r') as f:
line = f.readline()
while line != '':
s_words.append(line.strip())
line = f.readline()
if input_word in s_words:
print("Freedom")
else:
print("Human Rights")
if __name__ == '__main__':
while True:
input_word = input('--> ')
filter_sensitive_words(input_word)
| false
|
2c8697bc9d189648ee827974fa2051fc02ada2c5
|
luhralive/python
|
/AK-wang/0012/f_replace.py
| 985
| 4.28125
| 4
|
#!/usr/bin/env python
# -*-coding:utf-8-*-
# 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,
# 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
def f_words(f_file):
filtered_list = []
with open(f_file, 'r') as f:
for line in f:
filtered_list.append(line.strip())
return filtered_list
def filtered_or_not(f_word, input_str):
return (f_word in input_str)
def f_replace(f_word, input_str):
return input_str.replace(f_word, "**")
def main(f_file, input_str):
f_words_list = f_words(f_file)
for f_word in f_words_list:
if filtered_or_not(f_word, input_str):
input_str = f_replace(f_word, input_str)
return input_str
if __name__ == "__main__":
input_str = raw_input("please input your string:")
f_file = "filtered_words.txt"
print main(f_file, input_str)
| false
|
a31fcd621eacd25158fe063530c23c9caa0e8955
|
luhralive/python
|
/renzongxian/0012/0012.py
| 1,016
| 4.125
| 4
|
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-12-22
# Python 3.4
"""
第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,
例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
"""
def filter_words(words):
# Read filtered words from file named 'filtered_words.txt'
file_object = open('filtered_words.txt', 'r')
filtered_words = []
for line in file_object:
filtered_words.append(line.strip('\n'))
file_object.close()
# Check if the input words include the filtered words and replace the filtered with '*'
for filtered_word in filtered_words:
if filtered_word in words:
words = words.replace(filtered_word, '*'*len(filtered_word))
print(words)
if __name__ == '__main__':
while True:
input_words = input('Input some words:')
filter_words(input_words)
| false
|
231490f1ba7aa8be510830ec4a16568b5e4b2adb
|
THUEishin/Exercies-from-Hard-Way-Python
|
/exercise15/ex15.py
| 503
| 4.21875
| 4
|
'''
This exercise is to read from .txt file
Pay attention to the operations to a file
Namely, close, read, readline, truncate, write(" "), seek(0)
'''
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here is your file {filename}")
#readline() is to read a line from the file
#strip(*) is to delete the character * at the beginning or end of the string
line = txt.readline().strip(' ').strip('\n')
while line:
print(line)
line = txt.readline().strip(' ').strip('\n')
| true
|
5cfafd423c1d2d315dadc17c6796ec3cc860dad4
|
aav789/pengyifan-leetcode
|
/src/main/python/pyleetcode/keyboard_row.py
| 1,302
| 4.4375
| 4
|
"""
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American
keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
"""
def find_words(words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboards = ['qwertyuiop',
'asdfghjkl',
'zxcvbnm',]
out = []
for word in words:
for row in keyboards:
in_row = False
not_in_row = False
for c in word.lower():
if c in row:
in_row = True
else:
not_in_row = True
if in_row and not not_in_row:
out.append(word)
break
return out
def test_find_words():
input = ["Hello","Alaska","Dad","Peace"]
expected = ["Alaska","Dad"]
assert find_words(input) == expected
input = ["asdfghjkl","qwertyuiop","zxcvbnm"]
expected = ["asdfghjkl","qwertyuiop","zxcvbnm"]
assert find_words(input) == expected
if __name__ == '__main__':
test_find_words()
| true
|
98ca0cf6d09b777507091ea494f28f756f6ca1e1
|
aav789/pengyifan-leetcode
|
/src/main/python/pyleetcode/Reverse_Words_in_a_String_III.py
| 682
| 4.40625
| 4
|
"""
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
"""
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
if not s:
return s
return ' '.join([w[::-1] for w in s.split(' ')])
def test_reverseWords():
assert reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc"
if __name__ == '__main__':
test_reverseWords()
| true
|
91e826ad0ea139bf3abe1a4889c86338f833edfa
|
Sandy134/FourthSem_Material
|
/Python_Lab/Termwork1b.py
| 1,068
| 4.1875
| 4
|
#11/5/2021
MAX = 3
def add(q, item):
if len(q) == MAX:
print("\nQueue Overflow")
else:
q.append(item)
def delete(q):
if len(q) == 0:
return '#'
else:
return q.pop(0)
def disp(q):
if len(q) == 0:
print("\nQueue is empty")
return
else:
print("\nQueue Contents are :",q)
def main():
queue = []
while True:
print("\n1.add 2.Remove 3.Display 4.Exit")
opt = int(input("Enter your option : "))
if opt == 1:
item = input("Enter the item to be added to the queue : ")
add(queue, item)
elif opt == 2:
item = delete(queue)
if item == '#':
print("\nQueue Underflow")
else:
print("\nItem Deleted")
elif opt == 3:
disp(queue)
elif opt == 4:
break
else:
print("\nPlease enter a valid option ")
if __name__=='__main__':
main()
| false
|
1af36f5047e5ed15218cdc84f3b2bc9ea77bc57c
|
faridmaamri/PythonLearning
|
/PCAP_Lab Palindromes_method2.py
| 1,052
| 4.34375
| 4
|
"""
EDUB_PCAP path: LAB 5.1.11.7 Plaindromes
Do you know what a palindrome is?
It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
asks the user for some text;
checks whether the entered text is a palindrome, and prints result.
Note:
- assume that an empty string isn't a palindrome;
- treat upper- and lower-case letters as equal;
- spaces are not taken into account during the check - treat them as non-existent;
there are more than a few correct solutions - try to find more than one.
"""
### Ask the user to enter the text or sentence
text=input('Please enter the text to check : ')
##remove spaces and convert all caracters to lower case
string=text.replace(' ','')
string=string.lower()
for i in range (len(string)):
if string[-i-1]!=string[i]:
print(i,(-i-1))
print('it\'s not a palindrome')
break
if i == (len(string)-1):
print('it\'s a palindrome')
| true
|
7a7e4c2393928ca31e584f184f4a6c51689a42c5
|
DominiqueGregoire/cp1404practicals
|
/prac_04/quick_picks.py
| 1,351
| 4.4375
| 4
|
"""asks the user how many "quick picks" they wish to generate. The program then generates that
many lines of output. Each line consists of 6 random numbers between 1 and 45.
pseudocode
get number of quick picks
create a list to hold each quick pick line
generate a random no x 6 to make the line
print the line
repeat this x number of quick picks"""
from random import randint
NUMBERS_PER_LINE = 6
MAXIMUM = 45
MINIMUM = 1
def main():
amount = int(input("How many quick picks? "))
while amount < 0: # check for invalid amount of quick picks
print("Invalid amount")
amount = int(input("How many quick picks? "))
for i in range(amount):
quick_pick_lines = []
for number in range(NUMBERS_PER_LINE): # create a list of 6 random numbers between 1 and 45
number = randint(MINIMUM, MAXIMUM)
if number in quick_pick_lines:
number = randint(MINIMUM, MAXIMUM)
quick_pick_lines.append(number)
# print(quick_pick_lines)
quick_pick_lines.sort()
# print(quick_pick_lines)
# quick_pick_lines = [str(number) for number in quick_pick_lines]
# print(quick_pick_lines)
# print(' '.join(quick_pick_lines))
print(' '.join('{:2}'.format(number) for number in quick_pick_lines))
main()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.