blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4a7ba22c431cb61001dad9d7d1656e8bcc257b03 | Sagar-1807/Python-Projects | /Algorithms/Selection Sort.py | 500 | 4.28125 | 4 | # MULTIPLE SWAPPING CONSUME MUCH CPU POWER,OR MEMORY POWER
# SORT FROM START TO END
def bubblesort(list):
for i in range(5): # UPPER INDEX :7, INITIAL i=0
min=i
for j in range(i, 6):
if list[j] < list[min]:
min = j
temp = list[i]
list[i] = list[min]
list[min] = temp
print(list)
list=[12,18,27,36,11,10]
bubblesort(list)
print(" "),print("---Below is final sorted list ---- ")
print(list) | true |
f9649f0473bc7900d653fd0e216a35d95b6412a3 | gxgarciat/Playground-GUI-Tkinter | /4_entry.py | 738 | 4.375 | 4 | from tkinter import *
# Everything on tkinter is based using widgets
# The program will expand depending on the content
root = Tk()
# For this, an entry widget will be required
e = Entry(root,width=50,borderwidth=5)
e.pack()
# This will get the event from clicking the Button. It needs to be inside of the function
# e.get()
# This will insert a message in the entry box
e.insert(0,"Enter your name: ")
# Defining events that will occur when pressing the Button
def myClick():
fetching = e.get()
myLabel = Label(root,text="Hello " + fetching)
myLabel.pack()
# This will create a label widget
myButton = Button(root,text="Your name is: ",command=myClick)
myButton.pack()
# This will keep it as a loop
root.mainloop()
| true |
dc557b764ba7e2bacf978872247772ac0a222a8d | HALF-MAN/pythonlearn | /learning/oop/InstanceAndClassaAttributes.py | 1,307 | 4.71875 | 5 | """
直接在class中定义属性,这种属性是类属性,归Student类所有:
class Student(object):
name = 'Student'
当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。
>>> class Student(object):
... name = 'Student'
...
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student
在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,
因为相同名称的实例属性将屏蔽掉类属性,
但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
"""
class Student(object):
__name = 'Student'
if __name__ == '__main__':
print(Student._Student__name) | false |
bd4b01a4f57c749e711c7bce1cbcd2fefaf9ba2a | HALF-MAN/pythonlearn | /learning/oop_advanced_features/binding.py | 2,716 | 4.1875 | 4 | """
正常情况下,当我们定义了一个class,创建了一个class的实例后,
我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class:
class Student(object):
pass
给实例绑定一个方法:
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
给一个实例绑定的方法,对另一个实例是不起作用的
为了给所有实例都绑定方法,可以给class绑定方法:
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
使用__slots__
但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
>>> class GraduateStudent(Student):
... pass
...
>>> g = GraduateStudent()
>>> g.score = 9999
除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
"""
from types import MethodType
class Student(object):
pass
def set_age(self, age):
self.age = age
if __name__ == "__main__":
b = Student()
# b.set_age = MethodType(set_age, b)
# b.set_age(6)
Student.set_age = set_age
b.set_age(6)
# b.set_age(5)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
class GraduateStudent(Student):
pass
s = Student() # 创建新的实例
s.name = 'Michael' # 绑定属性'name'
s.age = 25 # 绑定属性'age'
# ERROR: AttributeError: 'Student' object has no attribute 'score'
try:
s.score = 99
except AttributeError as e:
print('AttributeError:', e)
g = GraduateStudent()
g.score = 99
print('g.score =', g.score) | false |
73b8018ce662ca4b68220e091a3cfa9bc546c507 | HALF-MAN/pythonlearn | /learning/functional_programming/higher_order_function/Filter.py | 1,222 | 4.375 | 4 | """
Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
filter()这个高阶函数,关键在于正确实现一个“筛选”函数。
注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
"""
print()
# -*- coding: utf-8 -*-
def main():
for n in primes():
if n < 1000:
print(n)
else:
break
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it)
if __name__ == '__main__':
main() | false |
4236a00fc82ac2bed48764a68e3bb8f4be2791b5 | webfudge95/codenation | /DayTwo/challenge6.py | 444 | 4.3125 | 4 |
def is_even(num):
if (num % 2) == 0:
return True
else:
return False
def addition(num1, num2):
num3 = num1 + num2
return num3
num1 = int(input("What's the first number: "))
num2 = int(input("What's the second number: "))
num3 = addition(num1, num2)
print("The sum of {} and {} is {}".format(num1, num2, num3))
if is_even(num3):
print("And that number is even.")
else:
print("And that number is odd.") | true |
b83bba009e6e982bc75af1503329a627babef0dd | webfudge95/codenation | /DayTwo/challenge2.py | 278 | 4.46875 | 4 | num = int(input("Please type a number: "))
if (num % 3) != 0:
print("Your number is not dividasable by 3")
else:
print("Your number is divisable by 3")
if (num % 5) != 0:
print("Your number is not dividasable by 5")
else:
print("Your number is divisable by 5") | false |
ae6b39bf461f69f0dd0e01b562925c852693e15a | JPB-CHTR/mycode | /challenge_labs/sleepytime.py | 975 | 4.1875 | 4 | #!/usr/bin/env python3
def toddler():
diaper = input("Is the diaper wet? (Y or N)")
if diaper == "Y":
print("Change Diaper")
elif diaper == "N":
print("Give milk")
else:
print("You should have answered Y or N")
def teen():
wakestate = input("Is the kid sleep walking (Y or N)")
if wakestate == "Y":
print("Walk back to bed")
elif wakestate =="N":
print("Ask why they decided it was a good idea to drink a monster?")
else:
print("You should have answered Y or N")
while True:
try:
age = int(input("Please Enter your child's age: "))
break
except ValueError:
print("seriosly bro, maybe try a whole number")
if age >=0 and age <= 4:
print("I see you have a todler, god bless")
toddler()
elif age >= 5 and age <= 17:
print("Well here you go")
teen()
elif age > 18:
print("Child out of range. Move out")
else:
print("Try a positive number")
| true |
64d16b3172d910897e8f36d186684e9d88f46cb7 | bundu10/lpthw | /example4.py | 1,987 | 4.25 | 4 | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("USING THE NORMAL METHOD OF (CONCATENATE) STRINGS")
# Blank line
print()
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each cars.")
print()
print(">" * 50)
print(">" * 50)
print()
# This code is simillar to the code above but the format is different.
# USING THE (str) METHOD THE SAME CODE CAN BE WRITTEN IN THIS FORMAT.
print("USING THE (str) method:")
# Blank line
print()
print("There are " + str(cars) + " cars available.")
print("There are only " + str(drivers) + " drivers available.")
print("There will be " + str(cars_not_driven) + " empty cars today.")
print("We can transport " + str(carpool_capacity) + " people today.")
print("We have " + str(passengers) + " to carpool today.")
print('We need to put about ' + str(average_passengers_per_car) + ' in each cars.')
print()
print(">" * 50)
print(">" * 50)
print()
# This code is simillar to the code above but the format is different.
# USING THE (.format) METHOD THE SAME CODE CAN ALSO BE WRITTEN IN THIS FORMAT.
print("USING THE (.format) method:")
# Blank line
print()
print("There are {} cars available.".format(cars))
print("There are only {} drivers available.".format(drivers))
print("There will be {} empty cars today.".format(cars_not_driven))
print("We can transport {} people today.".format(carpool_capacity))
print("We have {} to carpool today.".format(passengers))
print("We need to put about {} in each cars.".format(average_passengers_per_car))
| true |
0f75d6bf0c8928802e6e31076ba6d42bccc2ae14 | HK002/JavaBasics | /Code/Data Structures/Linked Lists/MiddleElement.py | 1,269 | 4.125 | 4 | class Node:
def __init__(self,data):
self.value = data
self.link = None
class LinkedList:
def __init__(self):
self.start = None
def insert(self,data):
if self.start is None:
self.start = Node(data)
else:
x = self.start
while x.link is not None:
x = x.link
x.link = Node(data)
def display(self):
if self.start is None:
print("List is Empty")
else:
x=self.start
while x is not None:
print(x.value, end = " ")
x = x.link
def middleElement(self):
if self.start is None :
print("Empty List")
else:
spointer = self.start
fpointer = self.start
while fpointer is not None and fpointer.link is not None:
spointer = spointer.link
fpointer = fpointer.link.link
print("\nMiddle Element : " + str(spointer.value))
obj=LinkedList()
obj.insert(1)
obj.insert(2)
obj.insert(3)
obj.insert(4)
obj.insert(5)
obj.display()
obj.middleElement()
obj.insert(6)
obj.display()
obj.middleElement() | true |
3468217eda250070effb82e9c49c2a4ceeee9724 | Neil-C1119/CIS156-Projects | /3exercise12.py | 1,102 | 4.25 | 4 | #Print the table of quantities and discount percentages
print("Here is the table of discounts: \n")
print(" QUANTITY | DISCOUNT")
print("------------------------")
print(" 10-19 | 10%")
print(" 20-49 | 20%")
print(" 50-99 | 30%")
print(" 100 or more | 40%")
#Store the user's package amount in a variable and convert it to an integer
package_amount = int(input("\n\nHow many packages will you purchase?: "))
#If the package amount is 10 or more but less than 20
if package_amount >= 10 and package_amount <= 19:
print("You will get a 10% discount.")
#If the package amount is 20 or more but less than 50
elif package_amount >= 20 and package_amount <= 49:
print("You will get a 20% discount.")
#If the package amount is 50 or more but less than 100
elif package_amount >= 50 and package_amount <= 99:
print("You will get a 30% discount.")
#If the package amount is 100 or more
elif package_amount >= 100:
print("You will get a 40% discount.")
#If the package amount is 10 or less
else:
print("You will not get a discount.")
| true |
9bcbe5a5caa77120fe736a32f57e83b393a443e4 | Neil-C1119/CIS156-Projects | /6exercise6n9.py | 2,498 | 4.21875 | 4 | #Start of try
try:
#This opens the file as the var numbers, then closes the file once finished running
with open("numbers.txt", "r") as numbers:
#Variable for each line of the file
lines = numbers.readlines()
#Variable for the amount of lines in the file
line_amount = len(lines)
#Variables for calculation and the final answer
calculate = 0
iter = 0
final_number = 0
#If there are multiple lines
if line_amount > 1:
#For each line
for line in lines:
#The string is stripped of the newline character and converted into a floating point
number = float(line.strip("\n"))
#Add the number to the calculate variable
calculate = calculate + number
#Record the amount of iterations AKA how many numbers there are
iter = iter + 1
#Calculate the final number
final_number = calculate / iter
#Print the final number rounded to 2 decimal places
print("The average is", round(final_number, 2))
#If there is only one line
elif line_amount == 1:
#Reset to the beginning of the file since we already read it for the lines variable above
numbers.seek(0)
#Variable to hold the string on the only line
line = numbers.readline()
#Variable that holds a list of each number that is separated by spaces
numbers = line.split()
#For each number in the numbers list
for number in numbers:
#Add the number (converted to floating point) to the calculate variable
calculate = calculate + float(number)
#Record the amount of iterations AKA how many numbers there are
iter = iter + 1
#Calculate the final number
final_number = calculate / iter
#Print the final number rounded to 2 decimal places
print("The average is", round(final_number, 2))
#If there is an IOError during the try statement tell the user the file couldn't be found
except IOError:
print("File could not be found. . .")
#If there is a ValueError during the try statement tell the user one or more of the values are not valid numbers
except ValueError:
print("One or more of the values are not valid numbers. . .")
| true |
969dd51c64bf4eeab6f4f8c19360b1e7b4d3825b | Neil-C1119/CIS156-Projects | /4exercise12.py | 597 | 4.40625 | 4 | #Factorial
#Ask the user to input a number to calculate
number = int(input("Which number would you like to find the factorial of? "))
#Defining the factorial function
def factorialFunc(number):
#Set the final_number variable to start at 1
final_number = 1
#For every number between 1 and the user's number, including the user's number...
for each in range(1,number + 1):
#Add final_number * each number to the final number
final_number = final_number * each
print("The factorial of", number, "is", final_number)
factorialFunc(number)
| true |
758db104ef47bfb2cd00843ef90063c2bbb86199 | sharonbrak/DI-Sharon | /Week_4/day_3/Exercises_XP_Gold.py | 1,746 | 4.28125 | 4 | # Exercise 1
fruits = input('What is/are your favorite fruits? ')
print(fruits)
type(fruits)
mylist = fruits.split(' ')
newfruit = input('Type another fruit: ')
if newfruit in mylist:
print('you chose one of your favorite fruits! Enjoy!')
else:
print('You chose a new fruit. I hope you enjoy it too!')
if len(mylist) >=2:
last = mylist[-1]
mylist.append("and")
mylist.append(last)
Exercise 2
mypassword =input('Give me a password: ')
# We check if it includes a digit
ifdigit = []
for x in mypassword:
if x.isdigit():
print('yes')
ifdigit.append(x)
else:
print('no')
print(ifdigit)
#Another way to check if digit
# any([char.isdigit() for char in password])
if mypassword.upper() != mypassword and mypassword.lower() != mypassword and len(ifdigit)>0 and '@' in mypassword or '#' in mypassword or '$' in mypassword and len(mypassword)>=6 and len(mypassword) <=12:
print('Great!')
else:
print('OOOPS!')
# Exercise 3
for x in range(3,31):
if x%3 == 0:
print(x)
# Exercise 4
mylist = [1,2,3,4,5,6,7,8,9,10]
insertindex = 4
item = 'here'
''' We want to insert in index 5 the word 'here' '''
mylist1 = mylist[0:int(insertindex)]
mylist2 = mylist[int(insertindex):len(mylist)]
mylist1.append(item)
newlist = mylist1 + mylist2
print(newlist)
# Exercise 5
# Exercise 6
Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700.
for x in range(1500,2701):
if x % 7 == 0 and x % 5 ==0:
print(x)
# Exercice 7
mystring = 'hdzio hzias hzau hzuszajjo'
numspace = 0
for x in mystring:
if x == " ":
numspace +=1
print(numspace)
# Exercice 8
mystring = 'hdzio hzias hzau hzuszajjo'
len(mystring.split())
| true |
f41aa1be3a521b5004c0ed67f26137d03c57d2dd | alvas-education-foundation/K.Muthu-courses | /25 May 2020/qstn_complex.py | 1,627 | 4.21875 | 4 | """
Problem Statement:
Take an input string parameter and determine if exactly 3 question marks exist between every pair of numbers that add up to 10.
If so, return true, otherwise return false. Some examples test cases are below:
"arrb6???4xxbl5???eee5" => true
"acc?7??sss?3rr1??????5" => true
"5??aaaaaaaaaaaaaaaaaaa?5?5" => false
"9???1???9???1???9" => true
"aa6?9" => false
"""
#importing numpy module
import numpy as np
#Function checks the sum of pair numbers
#Also finds the frequency of element '?' in the list
def check(n1 , n2 , li):
n = 0
for l in li:
if l == '?':
n += 1
num = n1 + n2
if num == 10:
buf.append(n)
#This function finds the pair numbers (num1 , num2)
#Also groups the elements between the pair of numbers
def group(input_string , x):
list = []
num1 = int(input_string[x])
num2 = 0
x += 1
while x < len(input_string):
if input_string[x].isdigit():
num2 = int(input_string[x])
break
else:
list.append(input_string[x])
x += 1
check(num1 , num2 , list)
if __name__ == '__main__':
input_string = input("Enter the string : ")
global buf
buf = []
#Finding digits in the input string
for i in range(len(input_string)):
if input_string[i].isdigit():
group(input_string , i)
#Comparing the conditions and printing final result
val = np.unique(buf)
if len(val) == 1 and val[0] == 3:
print('True')
else:
print('False') | true |
68b024412a8e0ff9e57797211031660e0118a94e | alvas-education-foundation/K.Muthu-courses | /19 May 2020/Function.py | 266 | 4.21875 | 4 | # Convert the temperature into Fahrenheit, given celsuis as inpit using function.
#Function definition
def temp(c):
f=(c*9/5)+32
return f
c=int(input("Enter the temperature in celsius : "))
#Function call
f=temp(c)
#Output
print("Temperature in Fahrenheit : ",f) | true |
9d49d0866bfb843c538298bb26585fd6f75851bb | venkateshwaracholan/Thinkpython | /chapter 8/eight_ten.py | 212 | 4.21875 | 4 | def is_palindrome_modified(word):
"""Returns true if the string is palindrome in a sinle check statement
without involving loop"""
return word==word[::-1]
print is_palindrome_modified("madam")
| true |
763f8d9d7db3093bb454ff43ea3a0c58c13fca7a | venkateshwaracholan/Thinkpython | /chapter 12/twelve_two.py | 731 | 4.21875 | 4 | import random
def sort_by_length(words):
""" sorts with 2 argument tuple"""
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
print t
res = []
for length, word in t:
print length, word
res.append(word)
return res
def sort_by_length_random(words):
""" sorts with 3 argument tuple (length,random priority,word)"""
t = []
for word in words:
t.append((len(word), random.random(), word))
t.sort(reverse=True)
#print t
res = []
for length, _, word in t:
print length, _, word
res.append(word)
return res
test = ['a', 'b', 'c', 'ab', 'bc', 'aav', 'accc', 'ddda']
print sort_by_length_random(test)
| false |
3b82dcc452a6fe1f964f02bb2661f56d7efc0a57 | venkateshwaracholan/Thinkpython | /chapter 9/nine_one.py | 212 | 4.15625 | 4 | """reads all the words from the text file and prints
the words which has more than 20 characters"""
fin = open('words.txt')
for line in fin:
word = line.strip()
if(len(word) >= 20):
print word
| true |
e2fa6f5594de3d52b39cae5fa29867778f5c520a | morganjacklee/com404 | /1-basics/3-decision/8-nestception/bot.py | 1,294 | 4.40625 | 4 | print("Where shall I look?")
print("Choices are:")
print("""- Bedroom
- Bathroom
- Labratory
- Somewhere else""")
location = str(input())
# Using if, else and elif statements
if location == "Bedroom" :
print("Where in the bedroom?")
print("""- Under the bed
- Somewhere else""")
location_bedroom = str(input())
if location_bedroom == "Under the bed" :
print("Found some socks but no battery.")
elif location_bedroom == "Somewhere else" :
print("Found some mess but no battery.")
elif location == "Bathroom":
print("Where in the bathroom?")
print("""- In the Bathtub
- Somewhere else""")
location_bathroom = str(input())
if location_bathroom == "In the bathtub" :
print("Found a rubber duck but no battery.")
elif location_bathroom == "Somewhere else" :
print("It's wet and there is no battery.")
elif location == "Labratory":
print("Where in the labratory?")
print("""- On the table
- Somewhere else""")
location_labratory = str(input())
if location_labratory == "On the table" :
print("Found the battery!")
elif location_labratory == "Somewhere else" :
print("Found some tools but no battery.")
elif location == "Somewhere else":
print("I don't know where that is but I will keep looking!")
else:
print("I'm not sure what you mean!")
| true |
16214125be23fce25190cbb1857d02b14105e11d | warriorwithin12/python-django-course | /course/WarGameProject/hand.py | 1,045 | 4.25 | 4 | class Hand:
'''
This is the Hand class. Each player has a Hand, and can add or remove
cards from that hand. There should be an add and remove card method here.
'''
def __init__(self, cards):
self.cards = cards
def add_card(self, card):
"""
Add card to hand if not exists previously.
"""
if card not in self.cards:
self.cards.append(card)
else:
print("Card already in hand! Nothing added.")
def remove_card(self):
"""
Remove a card from hand if hand has cards left.
"""
if len(self.cards) > 0:
return self.cards.pop()
else:
print("No cards left in hand! Nothing removed.")
return None
def __del__(self):
"""
Delete a hand, deleting it's cards.
"""
del self.cards
# print("Deleted cards from Hand")
def __str__(self):
return "Hand: {}".format(str(self.cards))
def len(self):
return len(self.cards)
| true |
c5b341105b836ce803e61bd4c065eae6df2a9925 | wmm98/homework1 | /视频+刷题/6章2/生词本的生词.py | 1,449 | 4.1875 | 4 | """
【问题描述】
生词本包含多个条目。每个条目由生词和该生词的含义组成。例如,生词name的含义是名字。编写程序,输出多个生词及其含义,列出生词本中包含的生词。
【输入形式】
输入多行。每一行包含生词及其含义。这一行内,生词和含义之间用冒号分隔。
【输出形式】
输出一行。列出所有的生词,之间用空格分隔。生词按字典序从小到大排序
【样例输入】
name:名字
hello:你好
python:蟒蛇
【样例输出】
hello name python
【提示】
1. 在Pycharm集成开发环境中,运行程序的时候如何告诉程序输入已经结束?答案是,按Ctrl + D组合键。在Windows命令行中运行程序的话,
则是按Ctrl + Z组合键。
2. 使用字典的keys方法能得到全部的键。也就是这一题的生词。
"""
import sys
words_list = []
while True:
word = sys.stdin.readline().strip()
if word == "":
break
words = word.split(":")
words_list.append(words)
# print(words_list)
words_dict = {}
for i in words_list:
words_dict[i[0]] = i[1]
# print(words_dict)
for j in sorted(words_dict):
print(j, end=" ")
# import sys
#
# result = {}
#
# while True:
# nums = sys.stdin.readline().strip()
# if nums == "":
# break
# temp = nums.split(":")
# result[temp[0]] = temp[1]
# for i in sorted(result):
# print(i, end=" ")
| false |
23763e6a12f59c64cbc2a32b42aa06da0d74c470 | wmm98/homework1 | /视频+刷题/函数/带参数装饰器注意事项.py | 896 | 4.15625 | 4 | # # 当程序有返回值的时候
# def print_num(func):
# def inner(n, m):
# print("*" * 30)
# func(n, m)
#
# return inner
#
#
# @print_num
# def pnum(n, m):
# print(n, m)
#
#
# pnum(1, 2) # 相当于调用inner函数,所以在在这里赋值的时候,
# # 所以要传相应的参数到inner函数里面,而后面还要调用pnum函数
# # 其函数也要传相对应得函数
# 当有几个函数的的时候,不能每个函数都配有有个装饰器,这样代码就会冗余
# 可以用缺省参数的办法解决问题,即用元组和字典来接收传进来的参数
def print_num(func):
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs) # 拆包
return inner
@print_num
def pnum(n, m):
print(n, m)
@print_num
def pnum1(n1, n2, n3):
print(n1, n2, n3)
pnum(1, 2)
pnum1(3, 0, n3="000")
| false |
212f63b5b38e596fff59af833d73efea2cce750c | wmm98/homework1 | /视频+刷题/第四章练习/单词个数统计.py | 1,104 | 4.4375 | 4 | """编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如,对于句子“one little two little three little boys",总共有5个不同的单词,one, little, two, three, boys。
说明:
(1)句子当中包含有空格。
(2)输入的句子当中只包含英文字符和空格,单词之间用一个空格隔开。
(3)不用考虑单词的大小写,假设输入的都是小写字符。
(4)句子长度不超过100个字符
(5)该问题实现的基本思路是:
a. 先定义一个存储不同单词的列表
b. 每次从句子中读取下一个单词
c.不断将新读取的单词加入该单词列表中。若单词列表中已存在该单词,则不添加。
【输入形式】
输入只有一行,为输入的句子
【输出形式】
输出只有一行,为句子当中不同的单词个数
【样例输入】
one little two little three little boys
【样例输出】
5
"""
words = input().split()
new_list = []
for i in words:
i.lower()
if i not in new_list:
new_list.append(i)
print(len(new_list)) | false |
86bcf759663bf85c225c3e3560fe0d3dbfdc0c90 | uschwell/DI_Bootcamp | /Week4 (18.7-22.7)/Day3 (20.7)/DailyChallenge/ceaser_cypher.py | 1,747 | 4.21875 | 4 | from typing import final
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#function that builds an encryption dictionary
def build_dict(shift):
shift=int(shift)
dict={}
for letter in range(len(alphabet)):
if(letter+shift)<len(alphabet):
dict[alphabet[letter]]=str(alphabet[letter+shift])
else:
dict[str(alphabet[letter])]=str(alphabet[(letter+shift)-26])
return(dict)
#function that builds a decryption dictionary
def break_dict(shift):
shift=int(shift)
dict={}
for letter in range(len(alphabet)):
if(letter-shift)>=0:
dict[alphabet[letter]]=str(alphabet[letter-shift])
else:
dict[str(alphabet[letter])]=str(alphabet[26-(letter+shift)])
return(dict)
#uses the encrypt dictionary to encrypt a message
def encrypt_message(dict):
message=input("what is the message you would like me to decrypt?")
final=''
for letter in message:
final+=dict[letter]
return final
#uses the encrypt dictionary to decrypt a message
def decrypt_message(dict):
message=input("what is the message you would like me to decrypt?")
final=''
for letter in message:
final+=dict[letter]
return final
process=input("Do you want to encrypt or decrypt your message?")
shift=input("What shift value should I be using?")
#we create the relevant dictionary
#send the relevant dictionary to the relevant encrypter/decrypter
if(process=='encrypt'):
dict=build_dict(shift)
code=encrypt_message(dict)
elif(process=='decrypt'):
dict=break_dict(shift)
code=decrypt_message(dict)
print("Your final message is: ")
print(code) | false |
3f7d5cc212695f3f9459c5dca44d05d5a318c61c | vyanphan/codingchallenges | /reverse_linked_list.py | 1,270 | 4.21875 | 4 | '''
Reversing a singly linked list in-place.
You should be able to do this in O(n) time.
Do not put the items into an array, reverse the
array, and put them back into the linked list.
'''
'''
For testing purposes.
'''
class LinkedNode(object):
data = None
next = None
def __init__(self, data):
self.data = data
class LinkedList(object):
head = None
tail = None
def add(self, node):
if type(node) is LinkedNode:
if self.tail == None:
self.head = node
self.tail = node
elif type(self.tail) is LinkedNode:
self.tail.next = node
self.tail = node
def print_nodes(self):
curr = self.head
ans = ''
while curr != None:
ans += str(curr.data) + ' -> '
curr = curr.next
print(ans + 'None')
''' Reverses linked list in-place in O(n) time. '''
def reverse(ll):
prev = ll.head
if prev != None:
curr = prev.next
while curr != None:
ll.head.next = curr.next
curr.next = prev
prev = curr
curr = ll.head.next
ll.head = prev
def reverse_tester(n):
ll = LinkedList()
for i in range(1, n+1):
ll.add(LinkedNode(i))
ll.print_nodes()
reverse(ll)
ll.print_nodes()
print()
reverse_tester(0)
reverse_tester(1)
reverse_tester(2)
reverse_tester(7)
| true |
47c52239a862d693010207f8477f58140a372fe7 | vyanphan/codingchallenges | /regex.py | 1,940 | 4.28125 | 4 | '''
Make a simple regex function that matches * and +
+ matches any single or empty character
* matches any sequence (including empty)
text: 'baaabab'
regex: 'baa*a++' True
regex: 'ba*a+' True
regex: 'a*ab' False
'''
def regex_match_recursive(string, regex):
if string == '' and regex == '':
return True
elif len(string)<1:
for c in regex:
if c != '*' and c != '+':
return False
return True
elif len(regex)<1:
return False
else:
if string[0]==regex[0]:
return regex_match_recursive(string[1:],regex[1:])
elif regex[0]=='+':
return regex_match_recursive(string[0:], regex[1:]) \
or regex_match_recursive(string[1:], regex[1:])
elif regex[0]=='*':
for i in range(len(string)):
if regex_match_recursive(string[i:], regex[1:]):
return True
else:
return False
def regex_match_dp(string, regex):
matches = [None] * len(string)
print(regex_match_recursive('baaabab', 'baa*a++'))
print(regex_match_recursive('baaabab', 'baa*b++'))
print(regex_match_recursive('baaabab', 'baa*b+'))
print(regex_match_recursive('baaabab', 'ba*a+'))
print(regex_match_recursive('baaabab', 'ba*a++'))
print(regex_match_recursive('', '*'))
print(regex_match_recursive('', '***'))
print(regex_match_recursive('', '+'))
print(regex_match_recursive('', '+++'))
print(regex_match_recursive('a', ''))
print(regex_match_recursive('', '+++a'))
print(regex_match_recursive('', '*ab'))
print(regex_match_recursive('baaabab', 'a*ab'))
# def regex_match_dp(string, regex):
# matches = [None] * len(string)
# if string==regex:
# return True
# i = 0 # string index
# j = 0 # regex index
# while i < len(string):
# if string[i] == regex[j]:
# i += 1
# j += 1
# matches[i] = True
# elif regex[j] == '+':
# return regex_match(string[i:], regex[j+1:]) \
# or regex_match(string[i+1:], regex[j+1:])
# elif regex[j] == '*':
| false |
21360bf9fec454ffe7b9c05e97e6c26f328ec225 | lzxysf/python | /cli/python_043_dynamic.py | 2,333 | 4.3125 | 4 | # python是动态语言
# 动态语言是运行时可以改变其结构的语言
# C、C++是静态语言
import types
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{} is {} years old".format(name, age))
def eat(self):
print("i am eating")
p = Person('liming', 15) # liming is 15 years old
print(p.age) # 15
# 运行过程中给对象绑定(添加)属性
# 只会影响类的这个实例对象,不会对类对象本身和类创建的其它实例对象有影响
p.sex = 'male'
print(p.sex) # male
p1 = Person('laowang', 33) # laowang is 33 years old
# p1.sex # 此句报错,在新创建的实例中,sex是没有被定义的
# 运行过程中给类绑定(添加)属性
# 这样就可以使所有的类的实例对象拥有这个属性
Person.sex = None
p = Person('xiaoli', 24) # xiaoli is 24 years old
print(p.sex) # None
# 运行过程中给类绑定方法
# python中方法可以分为实例方法、静态方法、类方法
# 实例方法:需要绑定要一个对象上,第一个参数默认使用self,会把对象作为第一个参数传递进来
# 静态方法:使用装饰器@staticmethod进行定义,类和对象都可以调用,不需要默认参数
# 类方法:使用装饰器@classmethod进行定义,类和对象都可以调用,第一个参数默认使用cls,会把类作为第一个参数传递进来
print('-'*30)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("{} is {} years old".format(name, age))
def eat(self):
print("i am eating")
# 定义实例方法
def run(self):
print('I am running')
# 定义静态方法
@staticmethod
def testStatic():
print('test static')
# 定义类方法
@classmethod
def testClass(cls):
print('test class')
# 给对象动态添加实例方法
p = Person('xiaoq', 21)
p.run = types.MethodType(run, p)
p.run() # I am running
# 给类动态添加静态方法
Person.testStatic = testStatic
Person.testStatic() # test static
# 给类动态添加类方法
Person.testClass = testClass
Person.testClass() # test class
# 动态删除对象的属性或方法
# del 对象.属性
# delattr(对象, 属性)
del p.run
# p.run() # 删除run方法后执行会报错,找不到run | false |
bc5a2f1f7114718e5cc4406e165f252bdde907be | Audarya07/99problems | /P33.py | 344 | 4.1875 | 4 | # Determine whether two positive integer numbers are coprime.
def gcd(a, b) :
if b == 0:
return a
return gcd(b, a%b)
num1 = int(input("Enter first number : "))
num2 = int(input("Enter Second number : "))
if gcd(num1, num2) == 1:
print("Given numbers ARE co-primes")
else :
print("Given numbers are NOT co-primes") | true |
38b08a3205e61662c82c1fce1aa055514e2f926c | SeggevHaimovich/Python-projects | /Aestroids/asteroid.py | 2,520 | 4.75 | 5 | ###############################################################################
# FILE : asteroid.py
# WRITER : ShirHadad Seggev Haimovich, seggev shirhdd
# EXERCISE : intro2cs2 ex10 2021
# DESCRIPTION: the class: Asteroid
###############################################################################
import math
class Asteroid:
"""
A class for the asteroid object.
the class builds an asteroid object with the following information:
location, speed, size and radius.
the asteroid object purpose is to save all the data of a single asteroid.
"""
INITIAL_SIZE_ASTEROID = 3
def __init__(self, location, speed, size=INITIAL_SIZE_ASTEROID):
"""
builds the asteroid object.
gets the location and speed from the class call.
sets the size variable as the initial value unless it gets size from
the class call.
calculates the radius variable according to the size.
:param location: tuple (x and y coordinates)
:param speed: tuple (speed in x direction and y direction)
:param size: int
"""
self.__location = location
self.__speed = speed
self.__size = size
self.__radius = self.__size * 10 - 5
def get_location(self):
"""
:return: the current location of the asteroid
"""
return self.__location
def get_speed(self):
"""
:return: the current speed of the asteroid
"""
return self.__speed
def get_size(self):
"""
:return: the size of the asteroid
"""
return self.__size
def get_radius(self):
"""
:return: the radius of the asteroid
"""
return self.__radius
def set_location(self, x, y):
"""
changes the location of the asteroid to the given coordinates.
:param x: float
:param y: float
:return: None
"""
self.__location = (x, y)
def has_intersection(self, obj):
"""
checks if the asteroid and the given object clash.
:param obj: ship or torpedo
:return:True if they clash and False otherwise
"""
distance = math.sqrt(
(obj.get_location()[0] - self.__location[0]) ** 2 + (
obj.get_location()[1] - self.__location[1]) ** 2)
if distance <= (self.get_radius() + obj.get_radius()):
return True
return False
| true |
1dcdafb730f5addeef92b23d02184f30de3bef2d | gurmeetkhehra/python-practice | /Listhomwork4.py | 614 | 4.25 | 4 | # 4. Write a Python program to check a list is empty or not. Take few lists with one of them empty.
fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana']
fruits1 = []
fruits2 = ['mango', 'strawberry', 'peach']
# print (fruits[3])
# print (fruits[-2])
# print (fruits[1])
# #
# print (fruits[0])
# print (fruits)
#
# fruits = []
# print (fruits)
fruits. append('apple')
fruits.append('banana')
fruits.append ('pear')
fruits.append('cherry')
print(fruits)
fruits. append('apple')
fruits.append('banana')
fruits.append ('pear')
fruits.append('cherry')
print(fruits)
# #
# print (fruits[0])
# print (fruits2[2])
#
| false |
608309973a1b4917b47c610e571f5c14b0fe521b | gurmeetkhehra/python-practice | /list after removing.py | 383 | 4.3125 | 4 | # 7. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
# Go to the editor
# Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
# Expected Output : ['Green', 'White', 'Black']
colors = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
colors.remove('Red')
colors.remove('Pink')
colors.remove('Yellow')
print(colors) | true |
a29f0ca42991b52d22f538584f6cbc0b53587823 | mateusers/Homeworks-PYTHON | /matrix.py | 2,268 | 4.125 | 4 | print("Добро пожаловать в вычисление матриц!")
operacia = input("Вас интересует сложение или умножение матриц?\nЕсли сложение, то введите: +\nЕсли умножение, то введите: *\n")
x = int(input("1 число 'первой' матрицы: "))
y = int(input("2 число 'первой' матрицы: "))
z = int(input("3 число 'первой' матрицы: "))
m = int(input("4 число 'первой' матрицы: "))
n = int(input("5 число 'первой' матрицы: "))
s = int(input("6 число 'первой' матрицы: "))
a = int(input("7 число 'первой' матрицы: "))
b = int(input("8 число 'первой' матрицы: "))
c = int(input("9 число 'первой' матрицы: "))
print("Вид 'первой' матрицы:")
print(x, y, z)
print(m, n, s)
print(a, b, c)
print("Значения второй марицы")
X = int(input("1 число 'второй' матрицы: "))
Y = int(input("2 число 'второй' матрицы: "))
Z = int(input("3 число 'второй' матрицы: "))
M = int(input("4 число 'второй' матрицы: "))
N = int(input("5 число 'второй' матрицы: "))
S = int(input("6 число 'второй' матрицы: "))
A = int(input("7 число 'второй' матрицы: "))
B = int(input("8 число 'второй' матрицы: "))
C = int(input("9 число 'второй' матрицы: "))
print("Вид 'второй' матрицы:")
print(X, Y, Z)
print(M, N, S)
print(A, B, C)
if operacia == "+":
x1 = x+X
y1 = y+Y
z1 = z+Z
m1 = m+M
n1 = n+N
s1 = s+S
a1 = a+A
b1 = b+B
c1 = c+C
print("Результат сложения матриц: ")
print(x1, y1, z1)
print(m1, n1, s1)
print(a1, b1, c1)
if operacia == "*":
X1 = x*X+y*M+z*A
Y1 = x*Y+y*N+z*B
Z1 = x*Z+y*S+z*C
M1 = m*X+n*M+s*A
N1 = m*Y+n*N+s*B
S1 = m*Z+n*S+s*C
A1 = a*X+b*Y+c*Z
B1 = a*Y+b*N+c*B
C1 = a*Z+b*S+c*C
print("Результат умножения матриц: ")
print(X1, Y1, Z1)
print(M1, N1, S1)
print(A1, B1, C1)
| false |
522237f16f2ea405b0cb2afa37b95331bc9294b3 | gokayozcoban/3.b.g.-Data-Types---Strings---Metodlar---find-ve-index---aranan-harfi-kelimeyi-sayar-metin-icinde | /3.b.g. Data Types - Strings - Metodlar - find() ve index()- aranan harfi kelimeyi sayar, metin içinde kaçıncı sırada olduğunu.py | 1,115 | 4.125 | 4 | # find() ve index()
# Aranan karakterin veya kelimenin yerini bulurlar. Ama bunu sayı ile verir.
# Yani metin değişkeni içerisinde bir kelime ya da karakter arıyorsak
# find() ve index() metodları bize onun kaçıncı karakterde başladığını söyler.
# karakterleri saymaya 0'dan başlarlar. 0,1,2,3... gibi:
metin = """Buraya ayazdığım metin değişkeni içerisine ilk önce ingilizce yazmak
istedim ama aklıma bi şey gelmedi. Sonra bu yazdığımı ingilizce yazabilirim di-
ye düşündüm:
I had want to write here in English what I will write in variable."""
print(metin.find("I"))
162
print(metin.find("had"))
164
print(metin.index("I"))
162
print(metin.count("had"))
164
# Her ikisi de ilk bulduğunu verir. Yani "I" karakterini veya "had" kelimesini
# ilk nerede gördüyse o sırayı yazar.
# index ayrıca tersten de yazdırır:
sayılar = ("1","2","3","3","5","6","2","4","8","12","156","123","456","568")
print(sayılar[-1])
568 # -1 yazdığım için sondan yazdırdı.
print(sayılar[1:-1])
('2', '3', '3', '5', '6', '2', '4', '8', '12', '156', '123', '456')
| false |
f25df7963a9a9c81d8b28186b223350cf8d9ba87 | wudizhangzhi/leetcode | /medium/merge-two-binary-trees.py | 2,296 | 4.40625 | 4 | # -*- coding:utf8 -*-
"""
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
else:
return t1 or t2
def print_node(node):
print(node.val)
def _print_node(nodelist):
next_level = []
for node in nodelist:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if next_level:
print([i.val for i in next_level])
_print_node(next_level)
else:
return
_print_node([node])
'''
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
'''
if __name__ == '__main__':
t1 = TreeNode(1, left=TreeNode(3,left=TreeNode(5)), right=TreeNode(2))
t2 = TreeNode(2, left=TreeNode(1, right=TreeNode(4)), right=TreeNode(3, right=TreeNode(7)))
sol = Solution()
result = sol.mergeTrees(t1, t2)
print_node(result)
| true |
2c8eea9be7b8b5de96a5c44cf1d3c8e365eda746 | ChrisMatthewLee/Lab-9 | /lab9-70pt.py | 847 | 4.25 | 4 | ############################################
# #
# 70pt #
# #
############################################
# Create a celcius to fahrenheit calculator.
# Multiply by 9, then divide by 5, then add 32 to calculate your answer.
# TODO:
# Ask user for Celcius temperature to convert
# Accept user input
# Calculate fahrenheit
# Output answer
#----------------------------------------------------------------------
#ask
print "Put in the amount of degrees celcius that you would like to convert to fahrenheit"
#define variable
cel = int(raw_input())
#calculate
def fahcalc(cel):
fah = cel * 9
fah = fah / 5
fah = fah + 32
return fah
#Give answer
print "It is " + str(fahcalc(cel)) + " degrees fahrenheit." | true |
93ed0f3ceef0a0fa18cb59080ff6542697db2335 | KyleKing/dash_charts | /dash_charts/equations.py | 2,691 | 4.4375 | 4 | """Equations used in scipy fit calculations."""
import numpy as np
def linear(x_values, factor_a, factor_b):
"""Return result(s) of linear equation with factors of a and b.
`y = a * x + b`
Args:
x_values: single number of list of numbers
factor_a: number, slope
factor_b: number, intercept
Returns:
y_values: as list or single digit
"""
return np.add(
np.multiply(factor_a, x_values),
factor_b,
)
def quadratic(x_values, factor_a, factor_b, factor_c):
"""Return result(s) of quadratic equation with factors of a, b, and c.
`y = a * x^2 + b * x + c`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
factor_c: number
Returns:
y_values: as list or single digit
"""
return np.add(
np.multiply(
factor_a,
np.power(x_values, 2),
),
np.add(
np.multiply(factor_b, x_values),
factor_c,
),
)
def power(x_values, factor_a, factor_b):
"""Return result(s) of quadratic equation with factors of a and b.
`y = a * x^b`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
Returns:
y_values: as list or single digit
"""
return np.multiply(
factor_a,
np.power(
np.array(x_values).astype(float),
factor_b,
),
)
def exponential(x_values, factor_a, factor_b):
"""Return result(s) of exponential equation with factors of a and b.
`y = a * e^(b * x)`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
Returns:
y_values: as list or single digit
"""
return np.multiply(
factor_a,
np.exp(
np.multiply(factor_b, x_values),
),
)
def double_exponential(x_values, factor_a, factor_b, factor_c, factor_d):
"""Return result(s) of a double exponential equation with factors of a, b, c, and d.
`y = a * e^(b * x) - c * e^(d * x)`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
factor_c: number
factor_d: number
Returns:
y_values: as list or single digit
"""
return np.subtract(
np.multiply(
factor_a,
np.exp(
np.multiply(factor_b, x_values),
),
),
np.multiply(
factor_c,
np.exp(
np.multiply(factor_d, x_values),
),
),
)
| true |
6f1d5c730e20841150ac7b491b56cb52d28b221e | zingpython/december | /day_four/Exercise2.py | 1,322 | 4.28125 | 4 |
def intToBinary(number):
#Create empty string to hold the binary number
binary = ""
#To find a binary number divide by 2 untill the number is 0
while number > 0:
#Find the remainder to find the binary digit
remainder = number % 2
#Add the binary digit to the left of the current binary number
binary = str(remainder) + binary
#Divide the number by 2 using integer division
number = number // 2
# print(number)
#Return the completed binary number
return binary
print( intToBinary(210) )
def binaryToInt(binary):
# #Reverse the string so we can use a for loop going forwards instead of backwards
# binary = binary[::-1]
# #Create a total variable that will hold the total of the binary number
# total = 0
# #Create a variable that holds how much to increase the total by on a "1"
# increase = 1
# #FOr each digit in the binary number
# for digit in binary:
# #If the digit is a "1" increase the total by increase
# if digit == "1":
# total = total + increase
# #As the last step in the for loop double increase
# increase = increase * 2
# #Return the total of the binary number
# return total
binary = binary[::-1]
total = 0
for index in range( len(binary) ):
if binary[index] == "1":
total = total + (2 ** index)
return total
print( binaryToInt("11010010") ) | true |
8cb15496c6ef28903d1ea910ab0abb964522d3d9 | missbanks/pythoncodes | /21062018.py | 359 | 4.125 | 4 | # TASK
# print(51 % 48)
name = input ("Hi what is your name")
add_time = 51
current_time = int(input("What is your current time"))
alarm_time = 5
extra_time = 3
if current_time == "2pm":
print("your alarm will go off at 5pm you have {} extra hours to go".format(extra_time))
else:
print("sorry you entered the wrong time, try again ")
# ASSIGNMENT
| true |
75e03f156082c03a2170993e90c2507dff58721a | ge01/StartingOut | /Python/chapter_03/programming_exercises/pe_0301/pe_0301/pe_0301.py | 1,107 | 4.65625 | 5 | #########################################################
# Kilometer Converter #
# This program asks the user to enter a distance in #
# kilometers, and then converts that distance to miles. #
# The conversion formula is as follows: #
# Miles = Kilometers * 0.6214 #
#########################################################
CONSTANT = 0.6214
def main():
# Display the intro screen.
intro()
# Get the distance in kilometers.
kilometers = float(input('Enter the distance in kilometers: '))
# Convert the kilometers to miles.
kilometers_to_miles(kilometers)
# The intro function displays an introductory screen.
def intro():
print('This program converts distance to miles.')
print('')
# The kilometers_to_miles function accepts a number in
# kilometers and displays the equivalent number in miles.
def kilometers_to_miles(kilos):
miles = kilos * CONSTANT
print('That converts to', \
format(miles, '.2f'), \
'miles. \n')
# Call the main function
main() | true |
abdd052b5d57d6181e0d12a28283889354f045e5 | jjsanabriam/JulianSanabria | /Taller_1/palindromo.py | 410 | 4.4375 | 4 | '''It reads a word and it validates if word is a palindrome
Args:
PALABRA (string): word to validate
Returns (print):
resultado (string): Result of validate word (False or True)
+ word validate
'''
print("Ingrese Palabra: ")
PALABRA = input()
PALABRA_MAYUSCULA = PALABRA.upper()
if PALABRA_MAYUSCULA != PALABRA_MAYUSCULA[::-1]:
print("False " + PALABRA)
else:
print("True " + PALABRA)
| true |
5f430dcd768230062b69004348041912274cb180 | piskunovma/Python_hw | /les3/hw1.py | 873 | 4.3125 | 4 | """
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def my_func(number1, number2):
try:
number1, number2 = int(number1), int(number2)
if number2 == 0:
print("Введите второе число не 0!")
else:
result = number1 / number2
return round(result, 2)
except ValueError:
print("Вы ввели не число, введите число!")
number1 = input("Введите первое число: \n")
number2 = input("Введите второе число: \n")
print(my_func(number1, number2)) | false |
b91944901cb2c351bb0f1844e6436b8067f6138c | piskunovma/Python_hw | /les2/hw3.py | 1,843 | 4.21875 | 4 | """
3. Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
Напишите решения через list и через dict.
"""
# Решение через list
# month = input("Введите номер месяца : ")
# result_list = ["Зима", "Весна", "Лето", "Осень"]
#
# if month.isdigit():
# month = int(month)
# if month == 12 or month == 1 or month == 2:
# result = result_list[0]
# elif month > 2 and month < 6:
# result = result_list[1]
# elif month > 5 and month < 9:
# result = result_list[2]
# elif month > 8 and month < 12:
# result = result_list[3]
# else:
# result = f"Вы ввели {month}, введите число от 1 до 12"
# else:
# result = "Вы ввели не число, введите число от 1 до 12"
# print(result)
# Решение через dict
month = input("Введите номер месяца : ")
result_dict = {
'time_year1':'Зима',
'time_year2': 'Весна',
'time_year3': 'Лето',
'time_year4': 'Осень'
}
if month.isdigit():
month = int(month)
if month == 12 or month == 1 or month == 2:
result = result_dict['time_year1']
elif month > 2 and month < 6:
result = result_dict['time_year2']
elif month > 5 and month < 9:
result = result_dict['time_year3']
elif month > 8 and month < 12:
result = result_dict['time_year4']
else:
result = f"Вы ввели {month}, введите число от 1 до 12"
else:
result = "Вы ввели не число, введите число от 1 до 12"
print(result)
| false |
facc0ddf980a825b8587cc05e4caf70ff85415b8 | bdllhdrss3/fizzbuzz | /fizzbuzz.py | 556 | 4.1875 | 4 | #making a fizz buzz app
#creating input of list
list1 = input("Enter list one : ")
list2 = input("Enter list two : ")
length1 = len(list(list1))
length2 = len(list(list2))
sumation = length1 + length2
fizz = sumation%3
buzz = sumation%5
#now creating the fizzbuzz function
def fizzbuzz():
if buzz == 0 and fizz == 0:
print('fizzbuzz')
elif buzz == 0:
print('buzz')
elif fizz == 0:
print('fizz')
else:
print('the lists are neither a fizzbuzz nor buzz nor fizz')
fizzbuzz()
| true |
a8b0b1306df3c42d9333f9d979b494a39ca79d96 | Resham1458/Max_Min_Number | /max_min_nums.py | 520 | 4.34375 | 4 | total=int(input("How many numbers you want to enter?")) #asks user the total number he/she wants to enter
numbers = [int(input("Enter any whole number:")) for i in range(total)] # lets the user to enter desired number of numbers
print("The list of numbers you entered is:",numbers) #displays list of numbers
print("The largest number you entered is:",max(numbers)) #out puts largest number
print ("The smallest number you entered is:",min(numbers)) #out puts smallest number
| true |
0cc4375b4bdce67644fa9a56784738b057b847f5 | kathytuan/CoffeeMachine | /main.py | 2,606 | 4.125 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
profit = 0
resources = {
"water": 300,
"milk": 200,
"coffee": 100
}
def menu_cost():
"""print items on menu and their cost"""
print("=== MENU ===")
for item in MENU:
item_cost = MENU[item]["cost"]
print(f"{item}: ${item_cost}")
# TODO: 3. check to see if resources are sufficient
def check_inv(order):
"""takes user's order and check to see if there's sufficient amount of resource inventory"""
for items in MENU:
if order == items:
recipe = MENU[items]["ingredients"]
# print(recipe)
for i in recipe:
if recipe[i] > resources[i]:
print(f"sorry, there's not enough {i}.")
else:
resources[i] -= recipe[i]
# check_inv(order)
# TODO: 4. process coins
def payment(order):
order_cost = MENU[order]["cost"]
input("Please insert coins.")
quarter = int(input("how many quarters? "))
dime = int(input("how many dime? "))
nickle = int(input("how many nickle? "))
penny = int(input("how many penny? "))
payment_total = round((quarter * 0.25 + dime * 0.10 + nickle * 0.05 + penny * 0.01), 2)
# TODO 5. check transaction successful
if payment_total >= order_cost:
global profit
profit += order_cost
change = round(float(payment_total - order_cost), 2)
print(f"Here's ${change} in change")
print(f"Here is your {order} ☕ Enjoy!")
else:
print("Sorry that's not enough money. Money refunded")
# payment(order)
def coffee_machine():
machine_if_off = False
while not machine_if_off:
menu_cost()
# TODO: 1. print report of the resources
order = (input("What would you like? (espresso/latte/cappuccino) "))
if order == "report":
for ingredients in resources:
print("{}: {}".format(ingredients, resources[ingredients]))
print(f"money: {profit}")
elif order == "off":
machine_if_off = True
exit()
else:
check_inv(order)
payment(order)
coffee_machine()
| true |
a87fa54c7333f4b517a7c4daf7883b6d463a6234 | kayanpang/champlain181030 | /week5-2_functions_181129/function.py | 684 | 4.34375 | 4 | # example: repetition
print("this is line 1")
print("---------------")
print("this is line 2")
print("---------------")
print("this is line 3")
print("---------------")
# so create a function to do this repetition
def print_underscores():
print("---------------")
# function needs to be defined before used
print("this is line 1")
print_underscores()
print("this is line 2")
print_underscores()
print("this is line 3")
# give a line to separate between function line
def print_equal():
print("==========")
def print_dash():
print("___---___")
def print_separator(width):
for w in range(width):
print("*", end="")
print("this is line 1")
print_separator(50) | true |
e4754d3dce75fe063cd24ecfc5dc2d543cdf0932 | kayanpang/champlain181030 | /190225_revision/different-kinds-of-array.py | 1,524 | 4.5625 | 5 | # list is ordered and changeable. Allows duplicate members. it uses [] square brackets
# – Use lists if you have a collection of data that does not need random access.
# Try to choose lists when you need a simple, iterable collection that is modified frequently.
mylist = [1, 2, 'Brendan']
print(mylist[1])
# tuple is ordered and unchangeable. Allows duplicate members. it uses () round brackets
# – Use tuples when your data cannot change.
mytuple = ('apple', 'banana', 'cherry', 1)
print(mytuple[1])
# a set is unordered and unindexed. it uses {} curly bracket
# need a for loop to get access to the set, cannot refer to index
# – Use a set if you need uniqueness for the elements
myset = {'apple', 'banana', 'cherry', 1, 2}
for x in myset:
print(x)
# a dictionary is unordered, changeable and indexed. it has keys and values. it uses {} curly bracket
# can access the items in a dictionary using its key name
# When to use a dictionary:
# – When you need a logical association between a key:value pair.
# – When you need fast lookup for your data, based on a custom key.
# – When your data is being constantly modified. Remember, dictionaries are mutable.
# https://monjurulhabib.wordpress.com/2016/09/22/python-when-to-use-list-vs-tuple-vs-dictionary-vs-set-theory/
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
y = mydict["model"]
print(y)
# use for loop to access to a dictionary
for key, value in mydict.items():
print("\nKey: " + key)
print("Value: " + value) | true |
c8b21caf9356d06471480f3488522d6ca31b01ed | kayanpang/champlain181030 | /week7-2_private-contribution/encapsulation.py | 859 | 4.375 | 4 | # worker - employee - contractor initializer in child Classes (slide15)
# read everything about class he whole chapter
class Worker:
"""this class represents a worker"""
def __init__(self, worker_name=""):
self.name = worker_name
def set_name(self, new_name):
self.__name - new_name
def get_name(self):
return self.__name
class Employee(Worker):
"""this class specializes Worker and is salaried."""
def __init__(self, initial_salary, initial_name):
self.__salary = initial_salary
super().__init__(initial_name)
# super represents parent (Worker), it specify __init__
def set_salary(self, new_salary):
self.__salary = new_salary
def get_salary(self):
return self.__salary
e1 = Employee(50000, "Bob")
print(e1.get_name())
print(e1.get_salary())
print(e1.__salary) | true |
6c01d290efd21c4d689c0c102398550d308dda30 | adesanyaaa/ThinkPython | /fermat.py | 941 | 4.46875 | 4 | """
Fermat's Last Theorem says that there are no positive integers a, b, and c such that
a^n=b^n=c^n
Write a function named check_fermat that takes four parameters-a, b, c
and n-and that checks to see if Fermat's
theorem holds. If n is greater than 2 and it turns out to be true
the program should print, "Holy smokes, Fermat was wrong!"
Otherwise the program should print, "No, that doesn't work."
Write a function that prompts the user to input values
for a, b, c and n, converts them to integers, and uses
check_fermat to check whether they violate Fermat's theorem.
"""
def check_fermat():
a = int(input("Enter the first number:"))
b = int(input("Enter the second number:"))
c = int(input("Enter the third number:"))
n = int(input("Enter the value of n:"))
if (a ** n + b ** n == c ** n and n > 2):
print("HOly Smokes Fermat was wrong")
else:
print("Nope, that doesnt work")
check_fermat()
| true |
32c8fe672f6a6127973b4b28a62ab056321249bf | adesanyaaa/ThinkPython | /lists10.py | 862 | 4.15625 | 4 | """
To check whether a word is in the word list, you could use the in operator, but it
would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search (also
known as binary search), which is similar to what you do when you look a word up in the dictionary
"""
def binary_search(my_list, word):
if len(my_list) == 0:
return False
else:
midpoint = len(my_list) // 2
if my_list[midpoint] == word:
return True
else:
if word < my_list[midpoint]:
return binary_search(my_list[:midpoint], word)
else:
return binary_search(my_list[midpoint + 1:], word)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42, ]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))
| true |
3f7e4990a911eabae25c224a4d9454f1196d4e4e | adesanyaaa/ThinkPython | /VolumeOfSphere.py | 300 | 4.375 | 4 | """ The volume of a sphere with radius r is (4/3)*pi*r^3
What is the volume of a sphere with the radius 5
Hint: 392.7 is wrong
"""
# For this we will be using the math.pi function in python
# first we need to import the math class
import math
r = 5
volume = (4 / 3) * math.pi * r ** 3
print(volume)
| true |
712e3c920965f9a21bedcdd7df712a7f79cd9dbd | adesanyaaa/ThinkPython | /dictionary2.py | 502 | 4.34375 | 4 | """
Dictionaries have a method called keys that returns the keys of the dictionary, in
no particular order, as a list.
Modify print_hist to print the keys and their values in alphabetical order.
"""
hist = {1: 2, 3: 4, 5: 6, 7: 8}
mydict = {'carl': 40,
'alan': 2,
'bob': 1,
'danny': 3}
def print_hist():
myList = mydict.keys()
# Use of keys() function now for sorting the file
print(myList)
for key in sorted(mydict):
print(key)
print_hist()
| true |
88140b85b4cbc6075b2f18b09f12beb48eacc55a | adesanyaaa/ThinkPython | /store_anagrams.py | 1,116 | 4.1875 | 4 | """
Write a module that imports anagram_sets and provides two new functions: store_anagrams
should store the anagram dictionary in a "shelf;" read_anagrams should look up a word and return
a list of its anagrams.
"""
import shelve
import sys
from anagram_set import *
def store_anagrams(filename, ad):
"""Stores the anagrams in ad in a shelf.
filename: string file name of shelf
ad: dictionary that maps strings to list of anagrams
"""
shelf = shelve.open(filename, 'c')
for word, word_list in ad.iteritems():
shelf[word] = word_list
shelf.close()
def read_anagrams(filename, word):
"""Looks up a word in a shelf and returns a list of its anagrams.
filename: string file name of shelf
word: word to look up
"""
shelf = shelve.open(filename)
sig = signature(word)
try:
return shelf[sig]
except KeyError:
return []
def main(command='store'):
if command == 'store':
ad = all_anagrams('words.txt')
store_anagrams('anagrams.db', ad)
else:
print(read_anagrams('anagrams.db', command))
main()
| true |
a6ae696b7ffe00652f7ef0d1c5ab8c4a7de0b474 | adesanyaaa/ThinkPython | /lists3.py | 570 | 4.21875 | 4 | """
Write a function that takes a list of numbers and returns the cumulative sum
that is, a new list where the ith element is the sum of the
first i + 1 elements from the original list. For
example, the cumulative sum of [1, 2, 3] is [1, 3, 6]
"""
def nested_sum():
a = int(input("Enter the number of Elements you want to add:"))
mylist = []
for i in range(0, a):
mylist.append(int(input()))
mylist2 = []
mysum = 0
for i in range(0, a):
mysum = mysum + mylist[i]
mylist2.append(mysum)
print(mylist2)
nested_sum()
| true |
481095e995d267d95df513b8deace98d3492090a | adesanyaaa/ThinkPython | /VariableAndValues.py | 849 | 4.6875 | 5 | """ Assume that we execute the following statements
width= 17
height=12.0
delimiter='.'
for each of the expressions below write down the expression and the type
1. width/2
2. width/2.0
3. height/3
4. 1+2*5
5. delimiter*5
"""
width = 17
height = 12.0
delimiter = '.'
# 1. Width /2 should give an integer value of 8.5-float
first = width / 2
print(first)
print(type(first))
# Width /2.0 should give an integer value of 8.5-float
second = width / 2.0
print(second)
print(type(second))
# height/3 should give 4.0 as float
third = height / 3
print(third)
print(type(third))
# Printing a simple mathematical expression will give an int value
maths = 1 + 2 * 5
print(maths)
print(type(maths))
# delimiter*5 will print the delimiter five times and the type will be string
print(delimiter * 5)
FiveDelimiter = delimiter * 5
print(type(FiveDelimiter))
| true |
97914bc6f8c62c76aa02de1bd5c5f2a82e02e6db | nuria/study | /EPI/11_real_square_root.py | 748 | 4.1875 | 4 | #!usr/local/bin
import sys
import math
def inner_square_root(_max, _min, n):
tolerance = 0.05
middle = (_max - _min) *0.5
middle = _min + middle
print "max: {0}, min:{1}, middle:{2}".format(_max, _min, middle)
if abs(middle* middle -n) < tolerance:
return middle
elif middle * middle < n:
return inner_square_root(_max, middle, n)
else:
return inner_square_root(middle, _min, n)
def square_root(n):
# square root can be bigger than the number if the number <1
if n >= 1:
# solution is between [1,n/2]
return inner_square_root(n, 1, n)
else:
return inner_square_root(1, n, n)
if __name__=="__main__":
n = int(sys.argv[1])
print square_root(n)
| true |
fd5abb56732e9ddf37f093fe007c6c848d414b44 | nuria/study | /misc/five-problems/problem3.py | 714 | 4.25 | 4 | #!/usr/local/bin/python
'''
Write a function that computes the list of the first 100 Fibonacci numbers. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
'''
def main():
# caches prior fib numbers to avoid recurring for ever
# using an array
cache = []
def fib(i):
if i>= len(cache):
f = cache[i-1] + cache[i-2]
cache.append(f)
return cache[i]
cache.append(0)
cache.append(1)
for n in range(0, 101):
print fib(n)
if __name__ == "__main__":
main()
| true |
d929b25cb329d8a2c6589856e48e660c372b7aae | nuria/study | /crypto/xor.py | 1,748 | 4.46875 | 4 | #!/usr/local/bin/python
import sys
import bitstring
import virtualenv
# snipet given in coursera crypto course
# note xor of 11 and 001 will be 11, chops the last '1' at the longer string
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
def random(size=16):
return open("/dev/urandom").read(size)
def encrypt(key, msg):
c = strxor(key, msg)
print
print c.encode('hex')
return c
def _main():
key = random(1024)
ciphertexts = [encrypt(key, msg) for msg in MSGS]
#returns raw ascii codes (decimal)
def getAscii(text):
asciiText = ''
for ch in text:
asciiText = asciiText+" "+ str(ord(ch))
return asciiText
# assumes input is a hex string, decides it before doing an xor
def main():
ct1 = sys.argv[1];
ct2 = sys.argv[2];
# let's xor all strings together and see what we get
_next = strxor(ct1.decode("hex"),ct2.decode("hex"));
print getAscii(ct1.decode("hex"));
print getAscii(ct2.decode("hex"));
# print everything with ascii codes
print _next.encode("hex");
print _next
'''
When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
'''
if __name__ == '__main__':
main()
| true |
352b8196d758694512da5c5105977cf6d4e76ce4 | nuria/study | /EPI/tmp_linked_list_flatten.py | 1,957 | 4.1875 | 4 | #!usr/local/bin
# define each node with two pointers
class llNode:
def __init__(self, value, _next = None, head = None):
self.value = value
# next node
self.next = _next
self.head = head
def __str__(self):
if self.value is None:
return 'None ->'
return self.value + "->"
def flatten(head):
# simply walk the list
node = head
prior = None
while (node is not None):
if node.value is not None:
# continue, lawful value
prior = node
node = node.next
else:
# this is the head of a list, two possible
# ways, remove it (it is empty)
# or flatten it
if node.head is None:
# remove this node, it is an empty head
prior.next = node.next
# prior does not change
node = node.next
else:
# this node is the start of a list
# find list end
item = node.head
while (item.next is not None):
item = item.next
# item contains last node of this list
prior.next = item
item.next = node.next
prior = item
node = item.next
return head
def print_list(head):
node = head
while (node is not None):
print node
node = node.next
if __name__=="__main__":
# as coded all elements have null head pointers
# not just one
# the empty head that has to be removed just has '' value
a = llNode('a')
b = llNode('b')
c = llNode('c')
d = llNode('d')
e = llNode('e')
empty_1 = llNode(None)
empty_2 = llNode(None)
a.next = b
b.next = empty_1
empty_1.next = c
c.next = empty_2
empty_2.head = d
d.next = e
print_list(a)
print "****"
print_list(flatten(a))
| true |
cc3c31b09a402b7637ed05d98a01476620f26280 | nuria/study | /misc/five-problems/problem6.py | 1,726 | 4.25 | 4 | #!/usr/local/bin/python
import sys
def main():
'''
Given a sorted array and a target value, return the index
if the target is found. If not, return the index where
it would be if it were inserted in order. There won't be duplicate values in the array.
For example:
[1, 3, 5, 6] with target value 5 should return 2.
[1, 3, 5, 6] with target value 2 should return 1.
[1, 3, 5, 6] with target value 7 should return 4.
[1, 3, 5, 6] with target value 0 should return 0.
make sure it works for arrays that are large enough
Call like: python problem6.py 2 '1 2 3 4'
'''
def find_target(t, l, left_index):
# binary search, we need to keep track of indexes,
# just remember left and right index of the sublist in which we are looking
size = len(l)
if size == 1:
if t == l[0]:
# base case
print str(left_index)
else:
if l[0] < t:
print left_index + 1
else:
if left_index != 0:
print left_index - 1
else:
print 0
else:
# split in two
middle = int(size/2)
if l[middle] == t:
print left_index + middle
elif l[middle] > t:
left = l[left_index:middle]
find_target(t, left, left_index)
elif l[middle] < t:
right = l[middle:size]
find_target(t, right, left_index + middle)
target = sys.argv[1]
l = sys.argv[2].split()
find_target(target, l, 0)
if __name__ == "__main__":
main()
| true |
e37aeda0aa6f7d493dd27b2715d362a25138392a | maike-hilda/pythonLearning | /Ex2_5.py | 469 | 4.28125 | 4 | #Exercise 2.5
#Write a program that prompts the user for a Celsius temperature,
#convert the temperature to Fahrenheit, and print out the converted
#temperature
#Note: 0 deg C equals 32 deg F and 1 C increase equals 9/5 F increase
C = raw_input('Enter the current temperature in Degree Celcius:\n')
try:
C = float(C)
except:
print 'Please enter a number.'
F = C * 9/5 + 32
print 'The current temperature is ' + str(F) + ' degree Fahrenheit'
| true |
767d08be4e912dd1824c4431dc5a4a047b53f805 | maike-hilda/pythonLearning | /Ex6_3.py | 326 | 4.21875 | 4 | #Exercise 6.3
#Write a function named count that accepts a string and a letter to
#be counted as an argument
def count(word, countLetter):
count = 0
for letter in word:
if letter == countLetter:
count = count + 1
print 'The letter', countLetter, 'appeared', count, 'times.'
| true |
c362e44626893049bbf9753c7d46da60d4f07604 | fslaurafs/NanoCourses-FiapOn | /Python/Python/Cap3/Manipulação de Listas, Funções e Módulos/Ep01_listas.py | 410 | 4.125 | 4 | # Ep01 - INTRODUÇÃO: VARIÁVEIS E LISTAS
inventario = []
resposta = "S"
while resposta == "S":
inventario.append(input("Equipamento: "))
inventario.append(input("Valor: R$"))
inventario.append(input("Número Serial: "))
inventario.append(input("Departamento: "))
resposta = input("Digite \"S\" para continuar: ").upper()
for elemento in inventario:
print(elemento)
| false |
fbda37076aa297d6d627f467a4d9a9c573c01a9d | fslaurafs/NanoCourses-FiapOn | /Python/Python/Cap2/Variáveis, Tomada de Decisão e Laços de Repetição/Ep01_variaveis.py | 857 | 4.1875 | 4 | # Ep01 - CONCEITUAÇÃO E TIPOS DE VARIÁVEIS
nome = input("Digite um funcionário: ")
empresa = input("Digite a instituição: ")
qtde_funcionarios = int(input("Digite a quantidade de funcionários: "))
mediaMensalidade = float(input("Digite a média da mensalidade: R$"))
print(nome + " trabalha na empresa " + empresa)
print("Possui: ", qtde_funcionarios, " funcionários.")
print("A média da mensalidade é de: R$" + str(mediaMensalidade))
print("\033[1;32m=============== Verifique os tipos de dados abaixo: ===============\033[m")
print("O tipo de dado da variável [nome] é: ", type(nome))
print("O tipo de dado da variável [empresa] é: ", type(empresa))
print("O tipo de dado da variável [qtde_funcionarios] é: ", type(qtde_funcionarios))
print("O tipo de dado da variável [mediaMensalidade] é: ", type(mediaMensalidade))
| false |
e9840375c81c4bc383698ab2fd105ddabfd0f27f | kobeding/python | /lxfpy/class/special_getattr.py | 811 | 4.15625 | 4 | #!/usr/bin/python3.5
#__getattr()__:动态的返回一个属性
class Student(object):
def __init__ (self):
self.name = 'kobe'
def __getattr__ (self,attr): #调用不存在,会试图调用这个来尝试获取属性
if attr == 'score':
return 99
if attr == 'age':
return lambda:25 #返回函数也是完全可以的
raise AttributeError(" Student() object has no attribute '%s' "% attr )
#把一个类的所有属性的调用方法都动态化处理了,不需要任何特殊手段
#可以针对完全动态的情况做调用
s = Student()
print(s.name)
print(s.score)
print(s.age()) #调用方式要改变,是函数的调用方式
print(s.grade)
#raise AttributeError(" Student() object has no attribute '%s' % attr ")
#AttributeError: Student() object has no attribute '%s' % attr | false |
7c46d453e8cc017101c8e96a9cb192baea562d71 | VilmaLago/Estudos_iniciais_Python | /testes_iniciais/teste_funções.py | 641 | 4.125 | 4 | # Testes iniciais para aprender sobre funções.
# Defina a função para formatar nomes.
def nome_formatado(primeiro_nome, sobrenome):
'''Formate o nome da pessoa'''
nome_completo = primeiro_nome + ' ' + sobrenome
return nome_completo.title()
# Receba os inputs de nome e sobrenome.
print("Digite seu nome completo: ")
print("Digite 'sair' a qualquer momento para sair.")
while True:
p_nome = input("Primeiro nome: ")
if p_nome.lower() == "sair":
break
s_nome = input("Sobrenome: ")
if s_nome.lower() == "sair":
break
nome_completo = nome_formatado(p_nome, s_nome)
print(nome_completo)
| false |
20ef3d59c8d2b75569e2fbe8a419dc8a6461a38e | VilmaLago/Estudos_iniciais_Python | /testes_iniciais/teste_exceptions.py | 577 | 4.15625 | 4 | # Testes iniciais para aprender sobre exceções.
print("Dê-me dois números e eu irei dividí-los: ")
print("Digite 'sair' sempre que quiser fechar o programa.")
while True:
primeiro_numero = input("Digite o primeiro número: ")
if primeiro_numero.lower() == 'sair':
break
segundo_numero = input("Digite o segundo número: ")
if segundo_numero.lower() == 'sair':
break
try:
resposta = int(primeiro_numero)/int(segundo_numero)
except ZeroDivisionError:
print("You can't divide by 0.")
else:
print(resposta) | false |
14e0fa9c2a493870a09bd9be0818e2c0d0766ca2 | priya510/Python-codes | /01.10.2020 python/min.py | 419 | 4.125 | 4 |
num1=int(input("Enter the first number: "));
num2=int(input("Enter the second number: "));
num3=int(input("Enter the Third number: "));
def find_Min():
if(num1<=num2) and (num1<=num2):
smallest=num1
elif(num2<=num1) and (num2<=num3):
smallest=num2
elif(num3<=num1) and (num3<=num2):
smallest=num3
print("minimum number is",smallest)
find_Min();
| true |
4ddcecdbb97a17c6537ad2d9360cba1f9f2dc54e | CUCEI20B/zodiaco-AndresSanchez-A | /main.py | 2,047 | 4.21875 | 4 | print("Simbolo del Zodiaco")
dia = int(input("Numero de dia de nacimiento: "))
mes = int(input("Numero de mes de nacimiento: "))
if mes == 12:
if dia >= 1 and dia <= 21:
print("Tu simbolo es sagitario")
if dia >= 22 and dia <= 31:
print("Tu simbolo es capricornio")
elif mes == 1:
if dia >= 1 and dia <= 20:
print("Tu simbolo es capricornio")
if dia >= 21 and dia <= 31:
print("Tu simbolo es acuario")
elif mes == 2:
if dia >= 1 and dia <= 18:
print("Tu simbolo es acuario")
if dia >= 19 and dia <= 28:
print("Tu simbolo es piscis")
elif mes == 3:
if dia >= 1 and dia <= 20:
print("Tu simbolo es piscis")
if dia >= 21 and dia <= 31:
print("Tu simbolo es aries")
elif mes == 4:
if dia >= 1 and dia <= 20:
print("Tu simbolo es aries")
if dia >= 21 and dia <= 30:
print("Tu simbolo es tauro")
elif mes == 5:
if dia >= 1 and dia <= 20:
print("Tu simbolo es tauro")
if dia >= 21 and dia <= 30:
print("Tu simbolo es geminis")
elif mes == 6:
if dia >= 1 and dia <= 21:
print("Tu simbolo es geminis")
if dia >= 22 and dia <= 30:
print("Tu simbolo es cancer")
elif mes == 7:
if dia >= 1 and dia <= 22:
print("Tu simbolo es cancer")
if dia >= 23 and dia <= 31:
print("Tu simbolo es leo")
elif mes == 8:
if dia >= 1 and dia <= 22:
print("Tu simbolo es leo")
if dia >= 23 and dia <= 31:
print("Tu simbolo es virgo")
elif mes == 9:
if dia >= 1 and dia <= 22:
print("Tu simbolo es virgo")
if dia >= 23 and dia <= 30:
print("Tu simbolo es libra")
elif mes == 10:
if dia >= 1 and dia <= 22:
print("Tu simbolo es libra")
if dia >= 23 and dia <= 31:
print("Tu simbolo es escorpio")
elif mes == 11:
if dia >= 1 and dia <= 22:
print("Tu simbolo es escorpio")
if dia >= 23 and dia <= 30:
print("Tu simbolo es sagitario")
else:
print("Error en lo datos ingresados") | false |
c8503897bb274bac5cb7d4ed0762db5316501b9c | MythicalCuddles/Learning-Python | /simple calculator.py | 350 | 4.1875 | 4 |
# int only allows whole numbers
num1 = input("Please enter a number: ")
num2 = input("Please enter another number: ")
result = int(num1) + int(num2)
print(result)
# float allows for decimals
num1 = input("Please enter a number: ")
num2 = input("Please enter another number: ")
result = float(num1) + float(num2)
print(result)
| false |
b6de4bd1f23daba6a2cee75f17ec0a19d32a9256 | BogdanSorbun/Date_Finder | /what_day_is_it.py | 614 | 4.25 | 4 | days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday']
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# day 1 started on a saturday
def num_of_leap(year):
leap_years = int(year/4)-(int(year/100) - int(year/400))
return leap_years
def date(year, month, day):
months = sum(days_in_month[:(month)])
total_days = ((year)*365) + num_of_leap(year) + day + months
if month == 2 and day == 29:
total_days = total_days - 1
cycle_of_days = total_days % len(days)
print(days[cycle_of_days].capitalize())
| false |
886ab87338fe873257b61abdb90971044bfb1db1 | jdn8608/Analysis_of_Algo_hw_2 | /src/sphere.py | 2,341 | 4.1875 | 4 | import math
'''
Name: Joseph Nied
Date: 2/12/20
Class: CSC-261
Question: 3
Description: Algorithm to see if given a points, if any would lie on a sphere together
'''
def main() -> None:
SIZE = int(input())
#Create an empty array with size SIZE
Magnitude = [None] * SIZE
#Get the input coordinates
for i in range(SIZE):
inputVal = input()
list = inputVal.split()
temp_x = int(list[0])
temp_y = int(list[1])
temp_z = int(list[2])
#Enter in the magnitude^2 for each point (this stays an int)
Magnitude[i] = int((math.pow(temp_x, 2) + math.pow(temp_y, 2) + math.pow(temp_z, 2)))
determind(Magnitude, SIZE)
def determind(Magnitude, size):
#Determine the max value in magnitude
max = Magnitude[0]
for x in range(1, len(Magnitude)):
if max < Magnitude[x]:
max = Magnitude[x]
#Sort the data in about O(n) time:
radixSort(Magnitude, max, size)
#loop through the array in O(n) time
#See if any neighbors are equal, if so, they lie on a sphere together
answer = 'NO';
for i in range(len(Magnitude)-1):
if Magnitude[i] == Magnitude[i+1]:
answer = 'YES'
print(answer)
def countSort(Magnitude, power,size):
#answer array that will hold the sorted data
answer = [0] * len(Magnitude)
#empty array that will contain the counts
count = [0] * size
#counts the occureces of a #//power % size
#this is specifc for radixsort
for i in range(len(Magnitude)):
digitValue = (Magnitude[i]//power)%size
count[digitValue]+=1
#makes the count array cummalative
for j in range(1,len(count)):
count[j] = count[j-1] + count[j]
#loops through backwards and slowly fills the answer array given the count array
k = len(Magnitude)-1
while k >=0:
digitValue = (Magnitude[k]//power)%size
answer[count[digitValue] - 1] = Magnitude[k]
count[digitValue] -= 1
k-=1
#Convert Magnitude to the answer array
for l in range(len(Magnitude)):
Magnitude[l] = answer[l]
def radixSort(Mag, maxVal,size):
place = 1
while (maxVal/place) > 0:
countSort(Mag, place, size)
#increment place but a multiplicity of size
place = place*size
if __name__ == '__main__':
main() | true |
cec6fafd666635de71fc1c2a2d188f297c8b514b | Khalid-Sultan/Section-2 | /to binary.py | 273 | 4.1875 | 4 | def main():
value=eval(input("Enter an integer:"))
print("The binary value is",decimalToBinary(value))
def decimalToBinary(value):
result=""
while value!=0:
bit=value%2
result=str(bit)+result
value=value//2
return result
main()
| false |
61af3f82b452f1e0402cafc2a5797e3ffbb399be | Tamabcxyz/Python | /th2/dictionariescollectioninpython.py | 371 | 4.15625 | 4 | #A dictionary is a collection unordered can changeable, index. In python dictionary are written with curly brackets
#the have keys and values
a={"name":"Tran Minh Tam", "age":22}
print(a)
for x in a.values():
print(x)
for x in a.keys():
print(x)
for x,y in a.items():
print(f"a have key {x} values is {y}")
#add item you can write below
a["address"]="VL_CT"
print(a) | true |
d5438545ead5bb2d41c7791b6e86c72c4f93aa66 | LuannaLeonel/data-structures | /src/python/InsertionSort.py | 314 | 4.125 | 4 | def insertionSort(value):
for i in range(len(value)):
j = i
while (j > 0 and value[j] <= value[j-1]):
value[j], value[j-1] = value[j-1], value[j]
j -= 1
return value
a = [1,3,7,9,5]
b = [5,5,7,3,0,2,1,52,10,6,37]
print insertionSort(a)
print insertionSort(b)
| true |
197fb6b7d7b4db1ccde7078e85475f80d9c604d9 | arpith143a/best-practices | /interview_easy/interview3.2.py | 204 | 4.125 | 4 | m=int(input('Enter number:'))
if m<=0:
print('Enter number greater than zero')
for i in range(1,m+1):
for k in range(i,m):
print(' ',end='')
for j in range(1,i+1):
print('*',end='')
print('')
| false |
37679aa5f19d56a0cd004f0349fb566d902f9464 | nara-l/100pythonexcercises | /Ex66basic_translator.py | 299 | 4.125 | 4 |
def translator(word):
d = dict(weather="clima", earth="terra", rain="chuva")
try:
return d[word.lower()]
except KeyError:
return "We don't understand your choice."
word = input("Please enter a word to translate, weather, earth, rain etc. \n ")
print(translator(word))
| true |
43dd5fb872255883905ff1748a99867cd3c7079a | Plaifa/python | /test2.py | 610 | 4.125 | 4 | from datetime import datetime , timedelta
current = datetime.now()
print('Today is '+ str(current))
oneday = timedelta(days=1)
ytd = current - oneday
print ('Yesterday is '+ str(ytd))
oneweek = timedelta(weeks=1)
lastw = current - oneweek
print ('last week is '+ str(lastw))
print('-------------------------')
print('Day : '+ str(current.day) )
print('Month : '+ str(current.month))
print('Year : '+ str(current.year))
print('Time : '+ str(current.hour) +':'+str(current.minute))
birth = input('Enter birthday (dd/mm/yyy) :')
birthday = datetime.strptime(birth,'%d/%m/%Y')
print('Birth = '+str(birthday)) | false |
7d614f93d73dae587402e28e85e31062bafbdfa6 | matthewosborne71/MastersHeadstartPython | /Programs/Exercise1.py | 411 | 4.125 | 4 | # Write a program that generates a random integer between 1 and 100
# and then has the user guess the number until they get it correct.
import random
Number = random.randint(1,100)
Guess = -99
print "I thought of a number, want to guess? "
while Guess != Number:
Guess = int(raw_input())
if Guess != Number:
print "You're wrong, loser. Guess again."
print "Way to go! You did it! Awesome!"
| true |
b68ed99d0e68860f0ccdff2b272babe8ab836381 | InFamousGeek/PythonBasics | /ProgramToFindTheLngthOfAString1.py | 276 | 4.375 | 4 | # Python Program to find the length of a String (2nd way)
# using for loop
# Returns length of string
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = str(input("Enther the string : "))
print(findLen(str))
| true |
cf0fcc053e157beaa2b6eee2a78fa788d7cb2b8c | jonathan-murmu/ds | /data_structure/leetcode/easy/344 - Reverse String/reverse_string.py | 991 | 4.3125 | 4 | '''
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
'''
class Solution:
def reverseString(self, s) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# length = len(s)
# for i in range( length//2 ):
# temp = s[i]
# s[i] = s[(length-1) - i]
# s[(length - 1) - i] = temp
#
# # s[i], s[(length - 1) - i] = s[(length - 1) - i], s[i]
l = 0
r = len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return s
s = ["h","e","l","l","o"]
# s = ["H","a","n","n","a","h"]
obj = Solution()
print(obj.reverseString(s)) | true |
3fb235ced0711f77d36d1d8a59c62bd1fdf7d564 | naman-32/Python_Snippets | /BASIC/v6.py | 1,107 | 4.28125 | 4 |
if True:#False not ok
print("alright")
else :
print("not ok")
#nkgnkgnkgbnkbgl#lkvjbljgkglbvjlbjbklbkbvlkbvljlbvjj
#"""jigbjljgfjgfljgfjlfgjbgfbjgfjlfjdrnamanjgoenka is very
language = 'jav'
if language == 'python':
print("la is python")
elif language == 'java':
print("la is java")
else:
print("nothing")
if 2>=3:
print("gh")
else:
print("ji")
if not 2>=3:
print("gh")
else:
print("ji")
if 2!=3:
print("gh")
else:
print("ji")
if not 2*3>=6:
print("gh")
else:
print("ji")
c = [1,4,2,3]
d = [1,4,2,3]
print(id(c))
print(id(d))
if c is d:
print("gh")
else:
print("ji")
c= d
print(id(c))
print(id(d))
if c is d:
print("gh")
else:
print("ji")
logged_in = True
age = 17
if logged_in== True and age >= 18:
print ('Welcome')
else:
print('not allowed')
if logged_in== True or age >= 18:
print ('Welcome')
else:
print('not allowed')
condition = set() #False None 0 [] () '' {}
if condition == True :
print('condition is true')
else:
print('false')
| false |
d49fc41036398468f691da9300ab49fd2a3c0f9b | ranoaritsiky/Udemy_tsiky | /udemy.py | 732 | 4.125 | 4 | # liste = ["Java", "Python", "C++"]
# liste.insert(3, liste[1])
# liste.remove("Python")
# print (liste)
# liste = ["Maxime", "Martine", "Christopher", "Carlos", "Michael", "Eric"]
# print (liste[0:3])
# liste = [1, 2, 3, 4, 5]
# liste.append(6)
# if 6 in liste:
# print ("Le nombre 6 a bien été ajouté à la liste.")
# print(liste)
mdp = input("Entrez un mot de passe (min 8 caractères) : ")
mdp_trop_court = "votre mot de passe est trop court."
mdp=str(mdp)
ln_mdp=len(mdp)
if ln_mdp =="":
print (mdp_trop_court.upper())
elif ln_mdp <=8:
print(mdp_trop_court.capitalize())
elif mdp.isdigit() and ln_mdp>8:
print('Votre mot de passe ne contient que des nombres.')
else:
print("Inscription terminée.")
| false |
05a2eece1e470e7324b753635da58de637b61b7c | Descent098/schulich-ignite-winter-2021 | /Session 3/Solutions/Exercise 1.py | 1,266 | 4.34375 | 4 | """Exercise 1: Country Roads
Steps:
1. Fill out fill_up() so that it fills the fuel level to the gas tank size (line 18)
2. Fill out drive() so that it removes the amount of fuel it should for how far you drove(line 22)
3. Fill out kilometres_available so that it returns the amount of kilometers left based on the fuel economy(line 26)
"""
class Car:
"""A class representing a car with details about how far it can travel"""
def __init__(self, gas_tank_size, fuel, litres_per_kilometre):
self.gas_tank_size = gas_tank_size
self.fuel = fuel
self.litres_per_kilometre = litres_per_kilometre
def fill_up(self):
"""Fills up the car's Fuel"""
self.fuel = self.gas_tank_size
def drive(self, kilometres_driven):
"""Remove the amount of fuel, based on distance driven"""
self.fuel -= (self.litres_per_kilometre * kilometres_driven)
def kilometres_available(self):
"""Return the number of kilometers that the car could drive with the current amount of fuel"""
return self.fuel / self.litres_per_kilometre
# Code to test
c = Car(10,9,2)
print(c.kilometres_available())
c.drive(4)
print(c.kilometres_available())
c.fill_up()
print(c.kilometres_available())
| true |
dd29ea41437ef40746dc5df10398a3b9ca4c1389 | tic0uk/python-100daysofcode | /day-5-fizzbuzz-game.py | 420 | 4.28125 | 4 | # replicating a game called fizzbuzz that children play;
for i in range(1,101):
# if number is divisible by both 3 or 5 say "fizzbuzz"
if (i % 3 == 0 and i % 5 == 0):
print ("fizzbuzz")
# if number is divisible by 3 say "fizz"
elif i % 3 == 0:
print ("fizz")
# if number is divisible by 5 say "buzz"
elif i % 5 == 0:
print ("buzz")
# otherwise display the number as usual
else:
print (i)
| false |
4b88131b589761baf17e03992be46cb9742c0a62 | praemineo/backpropagation | /backpropagation.py | 1,720 | 4.15625 | 4 | import numpy as np
#define sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# X is a unit vector
x = np.array([0.5, 0.1, -0.2])
# target that we want to predict
target = 0.6
#learning rate or alpha
learnrate = 0.5
#weight that we initialize
weights_input_hidden = np.array([[0.5, -0.6],
[0.1, -0.2],
[0.1, 0.7]])
#weight that produced by hidden layer as a output
weights_hidden_output = np.array([0.1, -0.3])
# # Feed - Forward
## Forward pass
hidden_layer_input = np.dot(x, weights_input_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
print("hidden_layer_output :",hidden_layer_output)
output_layer_input = np.dot(hidden_layer_output, weights_hidden_output)
output = sigmoid(output_layer_input)
print("Predicted output : ", output)
# # Backpropagation
## Backwards pass
## Calculating output error
error = target - output
print("error: ", error)
# Calculating error term for output layer
output_error_term = error * output * (1 - output)
# Calculating error term for hidden layer
hidden_error_term = np.dot(output_error_term, weights_hidden_output) * hidden_layer_output * (1 - hidden_layer_output)
# Calculating change in weights for hidden layer to output layer
delta_weight_hidden_output = learnrate * output_error_term * hidden_layer_output
# Calculate change in weights for input layer to hidden layer
delta_weight_input_hidden = learnrate * hidden_error_term * x[:, None]
# # Weight change between the layers
print('Change in weights for hidden layer to output layer:')
print(delta_weight_hidden_output)
print('\nChange in weights for input layer to hidden layer:')
print(delta_weight_input_hidden)
| true |
5a47d18b0353a71db8c6d177beed9cbda00ab3b6 | birdcar/exercism | /python/scrabble-score/scrabble_score.py | 584 | 4.1875 | 4 | from typing import Dict
# Generates a mapping of letters to their scrabble score e.g.
#
# { 'A': 1, ..., 'Z': 10 }
#
SCORE_SHEET: Dict[str, int] = dict(
[(x, 1) for x in 'AEIOULNRST'] +
[(x, 2) for x in 'DG'] +
[(x, 3) for x in 'BCMP'] +
[(x, 4) for x in 'FHVWY'] +
[(x, 5) for x in 'K'] +
[(x, 8) for x in 'JX'] +
[(x, 10) for x in 'QZ']
)
def score(word: str) -> int:
"""
Given a word, compute the scrabble score for that word.
"""
if not x.isalpha():
return 0
return sum(SCORE_SHEET[char] for char in word.upper())
| true |
d7025c13f88527f24d10fc1a9b131f0c7e7bd627 | TheAughat/Setting-Out | /Python Practice/app4.py | 641 | 4.15625 | 4 | # The following block of code writes the times table for anything till times 10. Users can enter 'please stop' to quit
print('Writes the times table for anything till times 10. Enter "please stop" to quit.')
while True:
print()
tables = input("Which number do you want to see the tables of? ")
number = 0
if tables.lower() == "please stop":
print()
print("Alright, kiddo. Enough math for now.")
print()
break
else:
for times10 in range(int(tables), int(tables) * 11, int(tables)):
number += 1
print(f'{int(tables)} x {number} = {times10}')
| true |
d969a5a2b642277e499e2c6cafe59c947e7be3f3 | AliHassanUOS/PythonProgramaAndProject | /dictionaryinpython.py | 2,338 | 4.1875 | 4 | # print("Dictionary in python")
# print()
#
#
# print(dic[2])
#
# print(dic)
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
#
# print(11 not in dic)
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
# print(dic)
# print()
# dic.clear()
# print(dic)
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
#
#
# result=dic.items()
# lst = list(result)
# print(lst)
# print(type(lst))
# print(lst[2][1])
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
# # # dic [11] = 'aks'
# # # print(dic)
# # # print(dic[1])
# # # result = dic.items()
# # # print(result)
# # print(dic)
# # print()
# # dic.update({11:'new dictionary'})
# # print(dic)
# How to add 3 dictionary
# dic1 = {1: 'ali', 2 :'hassan'}
# dic2 = {3 :' ahmad', 4 : 'adeel'}
#
# dic3 = {}
#
# for i in (dic1, dic2):
# dic3.update(i)
# print(dic3)
# print(type(dic3))
# print(dic.pop(7))
# print(dic.pop(8))
# print(dic.pop(6))
# print(dic)
#
# print(dic.popitem())
# print(dic.popitem())
# print(dic.popitem())
# print(dic.popitem())
# print(dic)
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
#
# val = {5 : 'ahmad', 6 : 'kamran', 7 :'adeel', 8 : 'junaid'}
# dic.update(val)
#
# for key in dic:
# print(key ,dic[key])
# Taking input from user in dictionary
# emptydic = {}
#
# userinput = int(input("Enter values that you want to add in dictionary :"))
#
# for i in range(userinput):
# key = input("Enter key :")
# val = input("Enter values :")
# emptydic.update({key : val})
# print(emptydic)
#
# dic = {1: 'ali', 2: 'hassan', 3: 'rubab', 4: 'ahmad'}
# dic[5] = 'python'
#
# print(8 not in dic)
# n = int(input("Enter number that you want to enter :"))
#
# d = dict()
#
# for x in range(1, n+1):
# d[x] = x*x
# print(d)
#
# Previousnumber = 0
#
# for i in range(0,10):
# sum = Previousnumber+i
# print("Current number is ", i, "Previous Number is ", Previousnumber, "Sum of number is ", sum)
# Previousnumber=i
# def printEveIndexChar(str):
# for i in range(0, len(str), 3):
# print("index[",i,"]", str[i] )
#
# inputStr = "pynative"
# print("Orginal String is ", inputStr)
#
# print("Printing only even index chars")
# printEveIndexChar(inputStr)
list1 = [1,2,3,4,5,6,11,22,100]
list2 = [1,2,3,4,5,6,11,22,100]
if list1[0] == list2[-1]:
print('True')
else:
print('False') | false |
1cabb3e6a643fcb1d052eda08e4a1fd96f0f820c | AliHassanUOS/PythonProgramaAndProject | /OopPractice.py | 1,709 | 4.28125 | 4 | print("ALLAH")
# class calculator(object): # create calculator class
#
# def add(self, x, y):
# return x + y
#
# def sub(self, x, y):
# return x - y
#
# def mul(self, x, y):
# return x * y
#
# def divide(self, x, y):
# return x // y
#
#
# obj = calculator()
# while True:
# try:
# print("1: ADD")
# print("2: Subtract")
# print("3: Multiply")
# print("4: Division")
# print("5: Exit")
#
# userinput = int(input("Please enter number "))
# if userinput == 5:
# break
# x = int(input("Enter x "))
# y = int(input("Enter Y "))
#
# if userinput == 1:
# print(x, "+", y, "=", obj.add(x, y))
# elif userinput == 2:
# print(x, "-", y ,"=", obj.sub(x,y))
# elif userinput ==3:
# print(f"{x} * {y} = {obj.mul(x,y)}")
# elif userinput==4:
# print(f"{x} // {y} == {obj.divide(x,y)}")
#
# else:
# print("Please enter number between 1,5")
# except:
# print("Enter only integer ")
# class cal:
# def add(self):
#
# print("1 : Add")
# print("2 : Break")
# userinput = int(input("Enter number "))
# while True:
#
# if userinput == 1:
# a = int(input("enter element "))
# b = int(input("enter element "))
# sum = a + b
# print(sum)
# break
#
# elif userinput == 2:
# break
# obj = cal()
# obj.add()
################################### Rent a bike system in Python #######################################################
| false |
9208bc3b8e1ef3b6ef3e291d410057f926b0a2ac | kenedilichi1/calculator | /main.py | 917 | 4.15625 | 4 |
def add(x, y):
''' Adds 2 numbers '''
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
isRunning = True
while isRunning:
choice = input("operator: ")
if choice in ('add', 'subtract', 'multiply', 'divide'):
num1 = float(input("Enter num1: "))
num2 = float(input("Enter num2: "))
if choice == 'add':
result = add(num1, num2)
print(int(result))
elif choice == 'subtract':
result = subtract(num1, num2)
print(int(result))
elif choice == 'multiply':
result = multiply(num1, num2)
print(int(result))
elif choice == 'divide':
result = divide(num1, num2)
print(int(result))
else:
print("Input error")
| true |
8a4a09865d205160bc4fdbcbedbd77e8d1f48124 | Prithvi103/code-with-me | /Longest Mountain in Array {Medium}.py | 2,314 | 4.125 | 4 | """
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
"""
"""
Solved by considering situations where the current number is greater, lesser and equal to the
previous number. Single pass O(n) solution and O(1) time complexity.
"""
class Solution:
def longestMountain(self, A: List[int]) -> int:
if A is None or len(A) < 3:
return 0
start = False
down = False
up = False
highest = 0
l = 1
for i in range(1,len(A)):
if i==(len(A)-1):
if up:
if A[i]<A[i-1]:
l+=1
if l>highest:
highest = l
if A[i]>A[i-1]:
if down and up:
if l>highest:
highest = l
l = 1
down = False
if up is False:
up = True
start = True
l = 1
l += 1
if A[i]<A[i-1]:
if up:
down = True
else:
continue
l+=1
if A[i] == A[i-1]:
if up:
if down:
up = False
down = False
if l>highest:
highest = l
l = 1
else:
up = False
l = 1
else:
continue
return highest | true |
9be5923a412b0d78f7a283c93f5acb80b52ac9b8 | musicakc/NeuralNets | /Tutorial/threelayernn.py | 1,701 | 4.15625 | 4 | '''
Neural Networks Tutorial 1:
https://iamtrask.github.io/2015/07/12/basic-python-network/
3 input nodes, 4 training examples
'''
import numpy as np
'''
Nonlinearity or sigmoid function used to map a value to a
value between 0 and 1
'''
def nonlin(x,deriv=False):
#ouput can be used to create derivative
if(deriv == True):
return x*(1-x) #slope or derivative
return 1/(1 + np.exp(-x)) #formula of sigmoid fuction
#input x_(4*3)
x = np.array([[0,0,1], [0,1,1],[1,0,1],[1,1,1]])
#output y_(4*1)
y = np.array([[0,1,1,0]]).T #transpose the output array
#seed random numbers
np.random.seed(1)
'''
Initialise weights randomly with mean 0,
of dimension [3*1] for 3 inputs and 1 ouput
'''
syn0 = 2 * np.random.random((3, 4)) - 1
syn1 = 2 * np.random.random((4, 1)) - 1
#iterate multiple times to optimise our neural network
for i in range(60000):
#forward propogation
l0 = x
#hidden layer l1_(4*4) = [l0_(4*3) dot syn0_(3*4)]
l1 = nonlin(np.dot(l0,syn0))
#hidden layer l2_(4*1) = [l1_(4*4) dot syn1_(4*1)]
l2 = nonlin(np.dot(l1,syn1))
#calculate error between output and l2
l2_error = y - l2
if ((i % 10000) == 0):
print ("Error:" + str(np.mean(np.abs(l2_error))))
#slope of l2 * error to reduce error of high confidence predictions
l2_delta = l2_error * nonlin(l2,True)
'''
calculate confidence weighted error by calculating how much
each node value contributed to the error in l2
'''
l1_error = l2_delta.dot(syn1.T)
#slope of l1 * error to reduce error of high confidence predictions
l1_delta = l1_error * nonlin(l1,True)
#update weights using l2_delta
syn1 += np.dot(l1.T, l2_delta)
#update weights using l1_delta
syn0 += np.dot(l0.T, l1_delta)
#print (l1)
| true |
ca5d631772a998607acba42ead0af35f7956b6ee | nonstoplearning/python_vik | /ex13.py | 1,135 | 4.125 | 4 | from sys import argv
script, first, second, third = argv
fourth = input("Enter your fourth variable: ")
fifth = input("Enter your fifth variable: ")
print ("Together, your first variable is %r, your second variable is %r, your third variable is %r, "
"your fourth variable is %r, your fifth variable is %r" % (first, second, third, fourth, fifth))
"""
github vikram.talware$ python ex13.py stuff things
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
"""
"""
vikram.talware$ python ex13.py stuff things that vik
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: too many values to unpack (expected 4)
"""
script, first, second, third = argv, input("Enter your first variable: "), input("Enter your second variable: "), input("Enter your third variable: ")
print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
| true |
db7f21092dc6cba286f2c1270129f7c56b706d25 | cheokjw/Pytkinter-study | /tkinter/Codes/tk button.py | 849 | 4.3125 | 4 | from tkinter import *
# Initializing Tk class OOP(Object-Oriented Programming)
root = Tk()
# A function that shows the text "Look! I clicked a Button"
def myClick():
myLabel = Label(root, text = "Look! I clicked a Button !")
myLabel.pack()
# Button(root, text) = having a button for user to click
# state = DISABLED = wont allow user to click the button, but it'll still show the button
# padx = num = controlling the x-axis(width size) of the button
# pady = num = controlling the y-axis(length size) of the button
# command = func = letting the button to do something
# fg = "colour" = changing the text colour
# bg = "colour" = changing the button background color
myButton = Button(root, text = "Click Me!", padx = 50, pady = 50, fg = "Blue", bg = "light green", command = myClick)
myButton.pack()
# Tkinter loop func
root.mainloop() | true |
fdb87fcf446a3f42b572033a2af22279516bf5e5 | gom7430/Basic-ML-algorithms | /kmeans_algo.py | 932 | 4.34375 | 4 | #---------------------------------------------------------------
#basic implementation of k-means clustering algorithm
#---------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
#prepare the data
x = np.array([[5,3],[10,15],[15,12],[24,10],[30,45],[85,70],[71,80],[60,78],[55,52],[80,91]])
#visualize in a scatter plot
plt.scatter(x[:,0], x[:,1], label='true position')
plt.show()
#create clusters
kmeans = KMeans(n_clusters=2)
kmeans.fit(x)
print(kmeans.cluster_centers_)
print(kmeans.labels_)
#visualize clusters
plt.scatter(x[:,0],x[:,1],c=kmeans.labels_,cmap='Accent')
plt.show()
#try with 3 clusters
kmeans_three = KMeans(n_clusters = 3)
kmeans_three.fit(x)
print(kmeans_three.cluster_centers_)
print(kmeans_three.labels_)
plt.scatter(x[:,0],x[:,1],c=kmeans_three.labels_,cmap='rainbow')
plt.show() | false |
ac6b346fd9f0262cfd9381e374236955ee972a5e | bfakhri/deeplearning | /mini-1/bfakhri_fakhri/regressor.py | 1,365 | 4.28125 | 4 | """
Author: Bijan Fakhri
Date: 2/3/17
CSE591 - Intro to Deep Learning
This file implements the regressor class which performs a linear regression given some data
"""
import numpy as np
class regressor(object):
"""
Class that implements a regressor. After training, it will have weights that can be exported.
Args:
train_data: data with which to train the regressor.
alpha (optional): sets the regularization parameter alpha
"""
def __init__(self, train_data, **kwargs):
# Regularization Param
if 'alpha' in kwargs.keys():
self.alpha = kwargs['alpha']
else:
self.alpha = 1
# Changes name of incoming data for clearer representation below
X = train_data[0]
#X = np.append(X, np.ones(X.shape[1]), axis=0)
ones_c = np.ones((X.shape[0], 1))
X = np.concatenate((X, ones_c), axis=1)
Y = train_data[1]
# Begin Regression
m1_1 = np.dot(np.transpose(X), X)
m1_2 = np.multiply(self.alpha, np.identity(X.shape[1]))
m1 = m1_1 + m1_2
m2 = np.linalg.inv(m1)
m3 = np.dot(m2, np.transpose(X))
m4 = np.dot(m3, Y)
self.w = m4
def get_params(self):
return self.w
def get_predictions(self, test_data):
ones_c = np.ones((test_data.shape[0], 1))
test_data = np.concatenate((test_data, ones_c), axis=1)
return np.transpose(np.dot(np.transpose(self.w), np.transpose(test_data)))
if __name__=='__main__':
pass
| true |
4c483c108073d56208c7d1e56497e2dca3e6588a | NewAwesome/Fundamental-algorithms | /LeetCode/21. Merge Two Sorted Lists/Solution.py | 1,321 | 4.1875 | 4 | from ListNode import ListNode
class Solution:
# Iteration
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# create a var named 'head' node, used for point to head of the result LinkedList
# create a var named 'cur' node, used for iteration point to the smaller node of l1 and l2.
head = cur = ListNode()
# iteration
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur.next = l1 or l2
return head.next
# Recursive
# base case 是比较l1和l2的val值,如果l1.val更小,那么需要:1. l1.next指向下一个(因为不在本次base case 中,所以就指向递归调用);2. return l1
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
# end case : l1 or l2 is None
if not l1 or not l2:
return l1 or l2
# base case : compare l1.val and l2.val, the smaller one such as l1 will recursively be invoked with the arguments of l1.next and l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists1(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists1(l1,l2.next)
return l2 | true |
5e8d193c0a21c3c3dfafcb0fb94419777359e9ca | jjunsheng/learningpython | /mosh python/quiz(comparison operators).py | 438 | 4.46875 | 4 | #if name is less than 3 characters long
#name must be at least 3 characters
#otherwise if it's more than 50 characters long
#name can be a maximum of 50 chatacters
#otherwise
#name looks good
name = input('Name : ')
if len(name) < 3:
print("Name must be a minumum of 3 characters. Please try again.")
elif len(name) > 50:
print("Name can be a maximum of 50 characters. Please try again.")
else:
print("Name looks good!")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.