blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
07a2b70ca25f20852834cf6b5451951ad90e4a33
|
psyde26/Homework1
|
/assignment2.py
| 501
| 4.125
| 4
|
first_line = input('Введите первую строку: ')
second_line = input('Введите вторую строку: ')
def length_of_lines(line1, line2):
if type(line1) is not str or type(line2) is not str:
return('0')
elif len(line1) == len(line2):
return('1')
elif len(line1) > len(line2):
return('2')
elif len(line1) != len(line2) and line2 == ('learn'):
return('3')
result = length_of_lines(first_line, second_line)
print(result)
| true
|
45b08672f5802bd07e54d45df20b24c1538a2673
|
jxthng/cpy5python
|
/Practical 03/q7_display_matrix.py
| 383
| 4.4375
| 4
|
# Filename: q7_display_matrix.py
# Author: Thng Jing Xiong
# Created: 20130221
# Description: Program to display a 'n' by 'n' matrix
# main
# import random
import random
# define matrix
def print_matrix(n):
for i in range(0, n):
for x in range (0, n):
print(random.randint(0,1), end=" ")
print(" ")
x = int(input("Enter an integer: "))
print_matrix(x)
| true
|
02f76ae07d4bb429bf6a8319cce2aba0cb80ef58
|
jxthng/cpy5python
|
/compute_bmi.py
| 634
| 4.59375
| 5
|
# Filename: compute_bmi.py
# Author: Thng Jing Xiong
# Created: 20130121
# Modified: 20130121
# Description: Program to get user weight and height and
# calculate body mass index (BMI)
# main
# prompt and get weight
weight = int(input("Enter weight in kg:"))
# prompt and get height
height = float(input("Enter height in m:"))
# calculate bmi
bmi = weight / (height * height)
# display result
print ("BMI={0:.2f}".format(bmi))
# determine health risk
if bmi >=27.50:
print("High Risk!!!")
elif 23.5 <= bmi <27.5:
print ("Moderate risk!!")
elif 18.5 <= bmi <23:
print ("Healthy! :D")
else:
print ("Malnutrition :(")
| true
|
723f43c5f3555576fb2f01526ac4924675e93c5f
|
jxthng/cpy5python
|
/Practical 03/q2_display_pattern.py
| 515
| 4.40625
| 4
|
# Filename: q2_display_pattern.py
# Author: Thng Jing Xiong
# Created: 20130221
# Description: Program to display a pattern
# main
# define display pattern
def display_pattern(n):
prev_num = []
for i in range(1, n + 1):
prev_num.insert(0, str(i) + " ")
length = len("".join(prev_num))
prev_num = []
for j in range(1,n+1):
prev_num.insert(0, str(j) + " ")
print("{0:>s}".format(("".join(prev_num))).rjust(length))
x = int(input("Enter an integer: "))
display_pattern(x)
| false
|
1b40fd6dfbc67682a85fed5140d9f1d16a810286
|
Usuallya/python
|
/class-object/c4.py
| 1,727
| 4.1875
| 4
|
#python类的封装、继承和多态
#import people
from people import People
#1、继承的写法
class Student(People):
# sum = 0
# def __init__(self,name,age):
# self.name=name
# self.age = age
# self.__score=0
# self.__class__.sum+=1
#派生类的构造函数需要传入父类需要的参数,然后调用父类的构造函数来完成初始化
def __init__(self,school,name,age):
self.school = school
#注意:这里必须传入self,否则无法构造成功
#这里相当于用类来调用了实例方法,是一个普通的调用,因此需要像
#普通函数调用一样,传self
People.__init__(self,name,age)
#但是上面这样的构造方式并不推荐,开闭原则,比方说我们更换父类,那么派生类中
#可能要修改很多地方,这不可取,而是应该采用下面这个方法
super(Student,self).__init__(name,age)
def do_homework(self):
#可以再这里调用父类的同名方法
super(Student,self).do_homework()
print('english homework')
#现在student类中没有任何类变量和实例变量,而Student类继承了people中的类变量
#和实例变量,在实例化时,由于父类要求传入name和age,因此这里也必须传入
student=Student('bupt','wang',20)
# print(student.sum)
# print(Student.sum)
# print(student.name)
# print(student.age)
#对于方法的继承
student.get_name()
#注意:python允许多继承
#2、接下来是重载、多态相关内容
student1 = Student('swjtu','li',18)
#函数重名时,如果直接调用,那么直接使用当前对象的函数,这类似于C++
student1.do_homework()
| false
|
3c144e821443e44da6317169ecdc9992134a34fc
|
DevJ5/Automate_The_Boring_Stuff
|
/Dictionary.py
| 1,184
| 4.28125
| 4
|
import pprint
pizzas = {
"cheese": 9,
"pepperoni": 10,
"vegetable": 11,
"buffalo chicken": 12
}
for topping, price in pizzas.items():
print(f"Pizza with {topping}, costs {price}.")
print("Pizza with {0}, costs {1}.".format(topping, price))
# There is no order in dictionaries.
print('cheese' in pizzas) # True
print('ham' not in pizzas) # True
# print(pizzas['ham']) # KeyError
# Solution:
if 'ham' in pizzas:
print(pizzas['ham'])
# Alternative solution:
print(pizzas.get('ham', "doesnt exist"))
# There is also a setdefault method on dictionaries
message = '''It was a bright cold day in April when I parked my car.'''
count = {}
for character in message.upper():
count.setdefault(character, 0)
count[character] +=1
pprint.pprint(count) # Shows the dictionary in a readable format.
text = pprint.pformat(count) # Returns a string value of this output format
print(text)
print(pizzas.values()) # Returns a listlike datatype (dict_values)
list(pizzas.values()) # Returns list of values
list(pizzas.keys()) # Returns list of keys
list(pizzas.items()) # Returns list of tuples
for key in pizzas.keys():
print(key)
| true
|
0bb5501ebf856a20a70f2ec604495f21e10a4b0c
|
MachFour/info1110-2019
|
/week3/W13B/integer_test.py
| 399
| 4.25
| 4
|
number = int(input("Integer: "))
is_even = number%2 == 0
is_odd = not is_even
is_within_range = 20 <= number <= 200
is_negative = number < 0
if is_even and is_within_range:
print("{} passes the test.".format(number))
# Else if number is odd and negative
elif is_odd and is_negative:
print("{} passes the test.".format(number))
else:
print("{} does not pass the test.".format(number))
| true
|
bf86e2e9ac26825248273684b72b95427cc26328
|
MachFour/info1110-2019
|
/week6/W13B/exceptions.py
| 778
| 4.25
| 4
|
def divide(a, b):
if not a.isdigit() or not b.isdigit():
raise ValueError("a or b are not numbers.")
if float(b) == 0:
# IF my b is equal to 0
# Raise a more meaningful exception
raise ZeroDivisionError("Zero Division Error: Value of a was {} and value of b was {}".format(a,b))
return float(a)/float(b)
while True:
a = input("Numerator: ")
b = input("Denominator: ")
try:
x = divide(a,b)
except ZeroDivisionError as err:
print("Catching Zero Divsion Error \n {}".format(err))
raise Exception("The user is dumb")
except ValueError as err:
print("Catching Value Error \n {}".format(err))
continue
finally:
print("Try putting in different numbers again")
| true
|
b9d7faf00bcac19f2e292331e9800c05b4b489fa
|
MachFour/info1110-2019
|
/week11/W13B/fibonacci.py
| 923
| 4.1875
| 4
|
def fibonacci(n):
if n < 0:
raise ValueError("n can't be negative!")
# just for curiosity
print("fibonacci({:d})".format(n))
# base case(s)
if n == 0:
return 0
elif n == 1:
return 1
# else
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci_iterative(n):
if n < 0:
raise ValueError("n can't be negative!")
# just for curiosity
print("fibonacci({:d})".format(n))
# base case(s)
if n == 0:
return 0
elif n == 1:
return 1
# else
# F(n) = F(n-1) + F(n-2)
# previous two fibonacci sequence values
two_steps_behind = 0
one_step_behind = 1
i = n
while i > 1: # iterate until 'base case'
next_number = two_steps_behind + one_step_behind
# update previous values
two_steps_behind = one_step_behind
one_step_behind = next_number
i -= 1
return next_number
| false
|
02930644ec3cd051b1416e2860a002da5d374224
|
MachFour/info1110-2019
|
/week5/R14D/control-flow-revision.py
| 354
| 4.25
| 4
|
a = 123
if a == "123":
print("a is 123")
if a > 0:
print("a is greater than 0")
else:
print("a is less than or equal to 0???")
a = 123
while True:
if a == 123:
print("Hello from inside the while loop")
a = a - 1
elif a > 122 or a < 0:
break
else:
a = a - 1
print("here's an else")
| false
|
70514719b85a8c73f1881ae521606a66466b215c
|
aarthymurugappan101/python-lists
|
/append.py
| 289
| 4.1875
| 4
|
numbers = [2,3,5,7,89] # List Datatype
# print("Before",numbers)
numbers.append(100)
# print("After",numbers)
numbers.append(33)
# print(numbers)
numbers.insert(2, 66)
# print(numbers)
print(numbers)
numbers.pop()
print(numbers)
numbers.pop(1)
print(numbers)
numbers.sort()
print(numbers)
| false
|
da7b7caea279a8444cd63c43cabe65240ca21b57
|
Jyun-Neng/LeetCode_Python
|
/104-maximum-depth-of-binary-tree.py
| 1,301
| 4.21875
| 4
|
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
"""
import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = collections.deque([])
queue.append([root, 1])
# BFS
while queue:
node, depth = queue.popleft()
if node.left:
queue.append([node.left, depth + 1])
if node.right:
queue.append([node.right, depth + 1])
return depth
if __name__ == "__main__":
vals = [3, 9, 20, None, None, 15, 7]
root = TreeNode(vals[0])
node = root
node.left = TreeNode(vals[1])
node.right = TreeNode(vals[2])
node = node.right
node.left = TreeNode(vals[5])
node.right = TreeNode(vals[6])
print(Solution().maxDepth(root))
| true
|
6e784b269099a926400bc136e6810610a96a88ed
|
Jyun-Neng/LeetCode_Python
|
/729-my-calendar-I.py
| 2,328
| 4.125
| 4
|
"""
Implement a MyCalendar class to store your events.
A new event can be added if adding the event will not cause a double booking.
Your class will have the method, book(int start, int end).
Formally, this represents a booking on the half open interval [start, end),
the range of real numbers x such that start <= x < end.
A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)
For each call to the method MyCalendar.book,
return true if the event can be added to the calendar successfully without causing a double booking.
Otherwise, return false and do not add the event to the calendar.
Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
Note:
The number of calls to MyCalendar.book per test case will be at most 1000.
In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
Example:
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(15, 25); // returns false
MyCalendar.book(20, 30); // returns true
Explanation:
The first event can be booked. The second can't because time 15 is already booked by another event.
The third event can be booked, as the first event takes every time less than 20, but not including 20.
"""
class TreeNode:
def __init__(self, s, e):
self.start, self.end = s, e
self.left = None
self.right = None
class MyCalendar:
def __init__(self):
self.root = None
def book(self, start: 'int', end: 'int') -> 'bool':
new_node = TreeNode(start, end)
if not self.root:
self.root = new_node
return True
node = self.root
# binary search tree
while node:
if new_node.end <= node.start:
if not node.left:
node.left = new_node
return True
node = node.left
elif new_node.start >= node.end:
if not node.right:
node.right = new_node
return True
node = node.right
else:
return False
if __name__ == "__main__":
obj = MyCalendar()
print(obj.book(10, 20))
print(obj.book(15, 25))
print(obj.book(5, 10))
| true
|
4038b6ca7e62b6bd3b5ba7ef3cf01de2d3e8ee84
|
rishabh2811/Must-Know-Programming-Codes
|
/Series/Geometric.py
| 751
| 4.3125
| 4
|
# Geometric.py
""" Geometric takes the first number firstElem, the ratio and the number of elements Num, and returns a list containing "Num" numbers in the Geometric series.
Pre-Conditions - firstElem should be an Number.
- ratio should be an Number.
- Num should be an integer >=1.
Geometric(firstElem=7,ratio = 9,Num = 5) --> Standard function call
Output --> Num numbers are returned in series starting from firstElem with geometric value ratio
Example:
Geometric(1,1,2) returns --> [1,1]
Geometric(2,2,5) returns --> [2,4,8,16,32]
"""
def Geometric(firstElem, ratio, Num):
return [firstElem * (ratio ** i) for i in range(Num)]
if __name__ == '__main__':
print(Geometric(1, 1, 2))
print(Geometric(2, 2, 5))
| true
|
24eb50260ff182ad58f58665b2bbbe609a713f6b
|
manansharma18/BigJ
|
/listAddDelete.py
| 1,280
| 4.34375
| 4
|
def main():
menuDictionary = {'breakfast':[],'lunch':[], 'dinner':[]}
print(menuDictionary)
choiceOfMenu = ''
while choiceOfMenu != 'q':
choiceOfMenu = input('Enter the category (enter q to exit) ')
if choiceOfMenu in menuDictionary:
addOrDelete= input('Do you want to list, add or delete ')
if addOrDelete =='add':
addItem = input('Enter the item you want to add ')
if addItem not in menuDictionary[choiceOfMenu]:
menuDictionary[choiceOfMenu].append(addItem)
print("Item added sucessfully")
else:
print('Item already added in list')
elif addOrDelete =='delete':
deleteItem = input('Enter the item you want to delete ')
if deleteItem in menuDictionary[choiceOfMenu]:
menuDictionary[choiceOfMenu].remove(deleteItem)
print(menuDictionary)
else:
print('Item is not in list')
else:
print('entered choice is not available, try again')
else:
print('entered category is not available, try again')
if __name__ == "__main__":
main()
| true
|
d6f7a02cd03634786a3bf5168094e7560044cd18
|
alexisanderson2578/Data-Structures-and-Algorithms
|
/SortingAlgorithms.py
| 1,400
| 4.125
| 4
|
def InsertionSort(alist):
for i in range(1,len(alist)):
key = alist[i]
currentvalue = i-1
while (currentvalue > -1) and key < alist[currentvalue]:
alist[currentvalue+1]= alist[currentvalue]
currentvalue =currentvalue-1
alist[currentvalue+1] = key
return alist
#bubblesort
arr = [63, 3, 5, 2, 122, 1, 9,67]
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
print ("Sorted array is:")
print(arr)
def selectionListSort(selectedList):
index = range(0,len(selectedList))
for i in index:
intMin = i
for j in range(i+1 , len(selectedList)):
if selectedList[j] < selectedList[intMin]:
intMin = j
if intMin != i:
selectedList[intMin],selectedList[i]= selectedList[i],selectedList[intMin]
return selectedList
def merge_sorted_lists(list_1, list_2):
output_list = []
i = 0
j = 0
while i < len(list_1) and j < len(list_2):
if list_1[i] < list_2[j]:
output_list.append(list_1[i])
i+=1
else:
output_list.append(list_2[j])
j+=1
return output_list + list_1[i:] + list_2[j:]
#list1 = [1, 3, 5]
#list2 = [2, 4, 6]
#print(merge_sorted_lists(list1, list2))
| false
|
0ab1712df48bd99d3e5c744138caaea015ca12e1
|
Rupam-Shil/30_days_of_competative_python
|
/Day29.py
| 496
| 4.1875
| 4
|
'''write a python program to takes the user
for a distance(in meters) and the time was
taken(as three numbers: hours, minutes and seconds)
and display the speed in miles per hour.'''
distance = float(input("Please inter the distance in meter:"))
hour, min, sec = [int(i) for i in input("Please enter the time taken in hh/mm/ss order:").split()]
hour = hour + (min /60) + (sec/3600)
mile = distance * 0.000621371
speed = mile / hour
print("THe speed of the car is {:.5f}m/hr".format(speed))
| true
|
48ded77911e4f9e63e254d4cc5265e02f8f593e1
|
BrimCap/BoredomBot
|
/day.py
| 1,010
| 4.3125
| 4
|
import datetime
import calendar
def calc_day(day : str, next = False):
"""
Returns a datetime for the next or coming day that is coming.
Params:
day : str
The day you want to search for. Must be in
[
"monday"
"tuesday"
"wednesday"
"thursday"
"friday"
"saturday"
"sunday"
]
next : bool
If true, returns the next day (skips the first one)
Defaults to False if not passed in
Returns:
A datetime.date of the day
"""
delta = 8 if next else 1
date = datetime.date.today() + datetime.timedelta(days = delta)
for _, i in enumerate(range(7)):
date += datetime.timedelta(days = 0 if i == 0 else 1)
if calendar.day_name[date.weekday()].lower() == day.lower():
return date
if __name__ == "__main__":
print(calc_day('thursday', True))
| true
|
ad1ae0039c48c95c13268cfd96241e93a858d57b
|
papri-entropy/pyplus
|
/class7/exercise4c.py
| 710
| 4.15625
| 4
|
#!/usr/bin/env python
"""
4c. Use the findall() method to find all occurrences of "zones-security".
For each of these security zones, print out the security zone name
("zones-security-zonename", the text of that element).
"""
from pprint import pprint
from lxml import etree
with open("show_security_zones.xml") as f:
xml_str = f.read().strip()
xml_data = etree.fromstring(xml_str)
print("Finding all occurrences of 'zones-security'")
xml_zon_sec_all = xml_data.findall(".//zones-security")
print(xml_zon_sec_all)
print("Prining the zone names of each sec zones:")
for zone in xml_zon_sec_all:
for ele in zone:
if ele.tag == "zones-security-zonename":
print(ele.text)
| true
|
e0e0d097adba29f9673331887f6527caa5b3d2ad
|
fr3d3rico/python-machine-learning-course
|
/study/linear-regression/test4.py
| 2,734
| 4.53125
| 5
|
# https://www.w3schools.com/python/python_ml_polynomial_regression.asp
# polynomial regression
import matplotlib.pyplot as plt
x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]
plt.scatter(x, y)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]
mymodel = np.poly1d(np.polyfit(x, y, 3))
myline = np.linspace(1, 22, 100)
plt.scatter(x, y)
plt.plot(myline, mymodel(myline), c='r')
plt.show()
"""
R-Squared
It is important to know how well the relationship between the values of the x- and y-axis is, if there are no relationship the polynomial regression can not be used to predict anything.
The relationship is measured with a value called the r-squared.
The r-squared value ranges from 0 to 1, where 0 means no relationship, and 1 means 100% related.
Python and the Sklearn module will compute this value for you, all you have to do is feed it with the x and y arrays:
"""
from sklearn.metrics import r2_score
print(r2_score(y, mymodel(x)))
"""
Predict Future Values
Now we can use the information we have gathered to predict future values.
Example: Let us try to predict the speed of a car that passes the tollbooth at around 17 P.M:
To do so, we need the same mymodel array from the example above:
mymodel = numpy.poly1d(numpy.polyfit(x, y, 3))
"""
import numpy as np
from sklearn.metrics import r2_score
x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]
mymodel = np.poly1d(np.polyfit(x,y,3))
speed = mymodel(17)
print(speed)
"""
Bad Fit?
Let us create an example where polynomial regression would not be the best method to predict future values.
Example
These values for the x- and y-axis should result in a very bad fit for polynomial regression:
import numpy
import matplotlib.pyplot as plt
x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]
y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]
mymodel = numpy.poly1d(numpy.polyfit(x, y, 3))
myline = numpy.linspace(2, 95, 100)
plt.scatter(x, y)
plt.plot(myline, mymodel(myline))
plt.show()
And the r-squared value?
Example
You should get a very low r-squared value.
import numpy
from sklearn.metrics import r2_score
x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40]
y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15]
mymodel = numpy.poly1d(numpy.polyfit(x, y, 3))
print(r2_score(y, mymodel(x)))
The result: 0.00995 indicates a very bad relationship, and tells us that this data set is not suitable for polynomial regression.
"""
| true
|
02e08da64766c262406de320027d2d53b5e3dfa2
|
Fanniek/intro_DI_github
|
/lambda.py
| 1,305
| 4.53125
| 5
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 19:20:40 2019
@author: fannieklein
"""
#Exercise 1:
mylist =[" hello"," itsme ","heyy "," i love python "]
mylist = list(map(lambda s: s.strip(), mylist))
#print(mylist)
#Explanattion of Exercise 1:
#This function should use map function --> map applies to every element. First we build:
#map(lambda s: s.strip(), mylist) --> The map applies to every element of the list,
# s --> every string: I want to STRIP every string in my list
# --> then the argument is that I want this done inside mylist
# returning this will be an object. We need to set the map object to a list, therefor add
# list(map(lambda s: s.strip(), mylist))
#Exercise 2:
people = {"eyal":20, "JOHN":10, "PaBlo":23, "reX":11}
legal_people = {k.lower():v for k, v in people.items() if v > 18}
#print(legal_people)
#Exercise 3:
marks = [("John",46), ("Ethan",22), ("Sean",60)]
marks.sort(key = lambda t: t[1])
#print(marks)
#Cope one list to a new list without a whole yadyada function
my_list = [3,2,43455,6,23,456546567]
my_list_2 = [x for x in my_list]
#print(my_list_2)
string = "This is a string"
rev_s = " ".join([w[::-1] for w in string.split(" ")])
#print(rev_s)
## joining a list --> need to know every word, to know every word we need split it
| true
|
fe4952c3cadc4c1f541a10d18a8a39f75cfdd42f
|
ivov/fdi
|
/FDI/3_9.py
| 605
| 4.125
| 4
|
# Leer un número correspondiente a un año e imprimir un mensaje indicando si es
# bisiesto o no. Se recuerda que un año es bisiesto cuando es divisible por 4. Sin
# embargo, aquellos años que sean divisibles por 4 y también por 100 no son bisiestos,
# a menos que también sean divisibles por 400. Por ejemplo, 1900 no fue
# bisiesto pero sí el 2000.
año = int(input("Ingrese un año: "))
es_año_bisiesto = (año % 4 == 0 and año % 100 != 0) or (año % 400 == 0)
if (es_año_bisiesto):
print("El año ingresado es bisiesto")
else:
print("El año ingresado no es bisiesto")
| false
|
8ad71cb6e4e52fc454528ad87e4ecf657a6e406f
|
userddssilva/ESTCMP064-oficina-de-desenvolvimento-de-software-1
|
/distances/minkowski.py
| 513
| 4.125
| 4
|
def minkowski(ratings_1, ratings_2, r):
"""Computes the Minkowski distance.
Both ratings_1 and rating_2 are dictionaries of the form
{'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5}
"""
distance = 0
commonRatings = False
for key in ratings_1:
if key in ratings_2:
distance += pow(abs(ratings_1[key] - ratings_2[key]), r)
commonRatings = True
if commonRatings:
return pow(distance, 1/r)
else:
return 0 # Indicates no ratings in common
| true
|
9ad2e6f1e44f976b5a34b08705420da4ee5598b5
|
nihal-wadhwa/Computer-Science-1
|
/Labs/Lab07/top_10_years.py
| 2,524
| 4.21875
| 4
|
"""
CSCI-141 Week 9: Dictionaries & Dataclasses
Lab: 07-BabyNames
Author: RIT CS
This is the third program that computes the top 10 female and top 10 male
baby names over a range of years.
The program requires two command line arguments, the start year, followed by
the end year.
Assuming the working directory is set to the project's data/ directory
when run:
$ python3 top_10_years 1880 2018
TOP 10 BABY NAMES OF 1880-2018
RANK FEMALE NAME MALE NAME
1 Mary James
2 Elizabeth John
3 Patricia Robert
4 Jennifer Michael
5 Linda William
6 Barbara David
7 Margaret Joseph
8 Susan Richard
9 Dorothy Charles
10 Sarah Thomas
"""
import names_util # get_most_popular_name_year, START_YEAR, END_YEAR
import sys # argv, stderr.write
# constants for the printed table
RANK = 'RANK'
FEMALE_NAME = 'FEMALE NAME'
MALE_NAME = 'MALE NAME'
def main():
"""
The main program reads the command line, calls the function to compute
and return the results, and then prints out the results.
"""
# verify the command line contains the arguments
if len(sys.argv) != 3:
sys.stderr.write('Usage: python3 top_10_years.py start-year end-year')
else:
# convert the start and end year from command line strings to integers
start_year, end_year = int(sys.argv[1]), int(sys.argv[2])
# verify start year is less than or equal to the end year
if start_year > end_year:
sys.std.write('Start year must be less than or equal to end year')
# verify both years fall within the valid range for the data
elif start_year < names_util.START_YEAR or end_year > names_util.END_YEAR:
sys.stderr.write('Year must be between ' + str(names_util.START_YEAR) +
' and ' + str(names_util.END_YEAR))
else:
# call names_util.get_top_years and print the results
top_year = names_util.get_top_years(start_year, end_year)
print(f'TOP 10 BABY NAMES OF {start_year}-{end_year}')
print(f'{RANK:<10}{FEMALE_NAME:<20}{MALE_NAME:<20}')
rank = 1
for female, male in zip(top_year.females, top_year.males):
print(f'{rank:<10}{female:<20}{male:<20}')
rank += 1
if __name__ == '__main__':
main()
| true
|
6f2539ffb11dc17d1f277f6cbe7e7ed2b10377a1
|
loyti/GitHubRepoAssingment
|
/Python/pythonPlay/bikePlay.py
| 1,065
| 4.15625
| 4
|
class Bike(object):
def __init__ (price,maxSpeed,miles):
self.price = "$Really$ Expen$ive"
self.maxSpeed = maxSpeed
self.miles = 0
def displayInfo(self):
print "A little about your Bike: $Price: {}, {} max kph & {} miles traveled".format(str(self.price), int(self.maxSpeed), str(self.miles))
retrun self
def ride(self):
self.miles += 10
print "You just went on a 10 mile journey"
retrun self
def reverse(self):
self.miles -= 5
print "Backing up 5 miles in reverse is quite interesting You have gone {} miles ".format(self.miles)
return self
def noNeg(self):
if (self.miles < 0):
self.miles = 0
print "You backed up off a cliff and were saved just in time but the bike is gone :( Here is a new one :)"
return self
bike1 = Bike(99.99, 12)
bike1.drive()
bike1.drive()
bike1.drive()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(139.99, 20)
bike2.drive()
bike2.drive()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
| true
|
9bcc9a4088f6081d67388d517bc7d0ef80154e3e
|
securepadawan/Coding-Projects
|
/Converstation with a Computer/first_program_week2.py
| 2,283
| 4.125
| 4
|
print('Halt!! I am the Knight of First Python Program!. He or she who would open my program must answer these questions!')
Ready = input('Are you ready?').lower()
if Ready.startswith('y'):
print('Great, what is your name?') # ask for their name
else:
print('Run me again when you are ready!')
exit()
myName = input()
if myName.lower() == 'jamie martin':
print('Well hello, Professor Martin! I hope you enjoy Month Python puns!') # special greeting for Professor.
elif myName.lower() == 'ian ince':
print('All Hail The Creator!') #special greetings for Creator
else:
print('Nice to meet you, ' + myName + '!')
print('What is your quest? (degree program at Champlain College?)') # ask for their degree
degree = input()
if degree == 'Cybersecurity':
print('My creator as well!')
elif degree == "i don't know":
print("Don't me get the Black Knight. He's invincible and may bleed on you.") #insert pun here
else:
print('I bet a lot of people are interested in ' + degree)
print('What is your favorite color?') # ask for their favorite color
color = input ()
if color.lower () == 'green':
print('Speaking of green.... Bring me..... A Shrubbery!')
else:
print(color + ' is a nice color')
print('How many kids do you have?') #ask if have kids
kid = input ()
if kid == '0':
print("Don't be a DINK! (double income no kids). Kids makes life interesting! This means you only have " + str(int(kid)+1) + ' or ' + str(int(kid)+2) + " (if you have a spouse) in your immediate family.")
exit()
if kid == '1':
print('Nice! Does your child also enjoy the color ' + color + '?') #ask if kid have like same color
else:
print('Nice! Does any of your ' + kid + ' children enjoy the color ' + color + '?')
likecolor = input ()
if likecolor.startswith('y'):
print('Great! You have something in common in your family of ' + str(int(kid)+1) + ' or ' + str(int(kid)+2) + ' (if you have a spouse).') #add parent and kid's age
else:
print('Well that stinks! I hope your family of ' + str(int(kid)+1) + ' or ' + str(int(kid)+2) + ' (if you have a spouse) have something else in common.' )
print('I will now ride off in the sunset with my coconuts. Now for something completely different. Goodbye!')
| true
|
f4f8dfb4f59a722fd628f0634654aca2ba592a5e
|
NguyenLeVo/cs50
|
/Python/House_Roster/2020-04-27 import.py
| 1,569
| 4.1875
| 4
|
# Program to import data from a CSV spreadsheet
from cs50 import SQL
from csv import reader, DictReader
from sys import argv
# Create database
open(f"students.db", "w").close()
db = SQL("sqlite:///students.db")
# Create tables
db.execute("CREATE TABLE Students (first TEXT, middle TEXT, last TEXT, house TEXT, birth NUMERIC)")
# Check for arguments (import.py, character.csv)
if len(argv) != 2:
print("Usage: python import.py character.csv")
exit()
# Open CSV file by command line argument and read it
with open(argv[1]) as database:
# Read it into memory as a list
database_reader = reader(database)
for row in database_reader:
# Populate the house and birth year
data = [None] * 5
data[3] = row[1]
data[4] = row[2]
# For each row, parse name
# Use split method to split name into first, middle, and last names
# Insert each student into the student table in students.db
# db.execute to insert a row into the table
name = row[0].split()
if len(name) == 3:
data[0] = name[0]
data[1] = name[1]
data[2] = name[2]
db.execute("INSERT INTO Students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
data[0], data[1], data[2], data[3], data[4])
elif len(name) == 2:
data[0] = name[0]
data[2] = name[1]
db.execute("INSERT INTO Students (first, last, house, birth) VALUES(?, ?, ?, ?)",
data[0], data[2], data[3], data[4])
| true
|
7bab4b14a82a9e79dd6dd2ebc52f6a1c315d9176
|
JASTYN/30dayspyquiz
|
/exam/spaces.py
| 253
| 4.1875
| 4
|
"""
Write a loop that counts the number of words in a string
"""
space = ' '
count = 0
sentence = input("Enter a sentence: ")
for letter in sentence:
if letter == space:
count = count + 1
print(f'Your sentence has {count + 1} words')
| true
|
d29b0a47e7fe7df6a7906e8c96e7e43492c8ccd9
|
JASTYN/30dayspyquiz
|
/exam/hey/finalav.py
| 980
| 4.1875
| 4
|
def getNumberList(filename):
f = open(filename,'r')
#opening the file
line = f.readline()
#reading the file line by line
numbers = line.split(',')
#The split() method splits a string into a list.
numberList = []
#An array to store the list
for i in numbers:
numberList.append(int(i))
return numberList
def getAverage(numbers):
sum = 0
#for storage of the sum of the numbers in the file
counter = 0
#for cointing numbers present in the file
for i in numbers:
sum = sum + i
counter = counter + 1
average = sum/counter
# Getting the average
return average
def main():
#user input
filename = input("Enter filename : ")
#getting numbers from the required file
numbers = getNumberList(filename)
#get the average from the numbers list
average = getAverage(numbers)
#display the average
print(average)
if __name__ == "__main__":
main()
| true
|
2e4e0012235649961b56e64101e1b417ef98738e
|
hemanthkumar25/MyProjects
|
/Python/InsertionSort.py
| 409
| 4.21875
| 4
|
def insertionSort(list):
for index in range(1,len(list)):
currentvalue = list[index]
position = index
while position > 0 and list[position-1]>currentvalue:
list[position] = list[position -1]
position = position -1
list[position] = currentvalue
list = [1,9,87,646,2,57,5]
insertionSort(list)
print list
| true
|
a72bec9020e351bc3ef6e30d72aa3202021f2eab
|
severinkrystyan/CIS2348-Fall-2020
|
/Homework 4/14.11 zylab_Krystyan Severin_CIS2348.py
| 790
| 4.125
| 4
|
"""Name: Krystyan Severin
PSID: 1916594"""
def selection_sort_descend_trace(integers):
for number in range(len(integers)):
# Sets first number of iteration as largest number
largest = number
for i in range(number+1, len(integers)):
# Checks for number in list that is larger than the number initially set
if integers[i] > integers[largest]:
largest = i
# Sets the largest number found to be first element
integers[number], integers[largest] = integers[largest], integers[number]
if number != len(integers)-1:
print(*integers, '')
if __name__ == '__main__':
numbers = input().split()
integer_list = [int(number) for number in numbers]
selection_sort_descend_trace(integer_list)
| true
|
89d058658ca383637a76dc63c1156e98c90d5be4
|
Vincent1127/Waste-Self-Rescue-Scheme
|
/雨初的笔记/备课/实训/day04/string3.py
| 868
| 4.1875
| 4
|
#coding:utf-8
#可以将字符串改为元组或者列表输出
la = 'python'
print(tuple(la))
print(list(la))
#得到字符对应的ASCII ord(str)得到ASCII码 chr(ASCII)得到字符串 ??如何随机的十位a-z的字符串??
print(ord('中'))
print(ord('a'))
#得到ASCII代指的字符
print(chr(20013))
print(chr(65))
#得到字符中某个字符的下标
print(la.index('t'))
print('y' in la)
#.strip()去除字符串中首尾的空格
strA = ' aaBcdD '
print(strA.strip())
#判断字段是否为全英文 isalpha()
print(strA.isalpha())
#转大写 upper() 转小写lower()
print(strA.upper())
print(strA.lower())
#可以通过某个字符将字符串分割为一个列表
strC = "tyy|abcd|qwer|df"
print(strC.split('|'))
print(strC.split('|')[2])
#判断字符串是否为全大写,全小写
print(strC.isupper())
print(strC.islower())
| false
|
fbeaf00fea7890184e40e34f3e403b2121f6b289
|
BriannaRice/Final_Project
|
/Final_Project.py
| 1,201
| 4.125
| 4
|
'''
I already started before I knew that they all had to go together
so some of it makes sense the rest doesn't
'''
# 3/11/19 Final Project
# Brianna Rice
print('Pick a number between 1 and 30', "\n")
magic_number = 3
guess = int(input('Enter a number:', ))
while guess != magic_number:
print('Guess again', "\n")
guess = int(input('Enter a number:'))
print('Now that you got the number I have another task for you.', "\n")
# I'm getting them to guess the numb
while True:
Mystery = int(input("Enter number: "))
if Mystery > 100:
print("Nope to big of a number sorry", "\n")
elif Mystery < 20:
print("No lager number", "\n")
else:
print("Good choice", "\n")
break
print('Ok your next task is .... ', "\n")
# I am hoping I can attach this code so it can work with my for loop, functions and so on.
def print_multiple_times(string, times):
for i in range(times):
print(string)
print_multiple_times('money', 5)
scan = str('Im hungry')
def print_something():
scan_van = str('This is confusing')
print('\r\n',scan_van)
print('\r\n', scan)
print_something()
for i in range(1,3):
for j in range(7,10):
print(i,j)
| true
|
b4faf014046390f8f5807217a159d0bda12d79c8
|
jankovicgd/gisalgorithms
|
/listing25.py
| 993
| 4.53125
| 5
|
# 2.5 Determining the position of a point with the respect to a line
# Listing 2.5: Determining the side of a point
# Imports
from geometries.point import *
def sideplr(p, p1, p2):
"""
Calculates the side of point p to the vector p1p2
Input:
p: the point
p1, p2: the start and end points of a line
Output:
-1: p is on the left side of p1p2
0: p is on the line of p1p2
1: p is on the right side of p1p2
"""
return int((p.x - p1.x) * (p2.y - p1.y) - (p2 . x - p1.x) * (p.y - p1.y))
# Examples
if __name__ == "__main__":
p = Point(1, 1)
p1 = Point(0, 0)
p2 = Point(1, 0)
print("Point {} to line {} -> {}: {}".format(p, p1, p2, sideplr(p, p1, p2)))
print("Point {} to line {} -> {}: {}".format(p, p2, p1, sideplr(p, p2, p1)))
p = Point(0.5, 0)
print("Point {} to line {} -> {}: {}".format(p, p1, p2, sideplr(p, p1, p2)))
print("Point {} to line {} -> {}: {}".format(p, p1, p2, sideplr(p, p2, p1)))
| false
|
858fd9f1634b03d69550a3202c2f12a7295d568b
|
hutbe/python_space
|
/8-Decorators/decorators.py
| 1,017
| 4.34375
| 4
|
# Decorator
# Using a wrap function to add extra functions to a function
def my_decorator(fun):
def wrap_fun():
print(f"==== Function: {fun.__name__}")
fun()
return wrap_fun
@my_decorator
def say_hi():
print(f"Hello everyone, nice to be here!")
say_hi()
@my_decorator
def generator_even_odd():
result_list = ["even" if num % 2 == 0 else "odd" for num in range(10)]
print(result_list)
generator_even_odd()
# Decorator Pattern
def new_decorator(fun):
def wrap_fun(*args, **kwargs):
print(f"==== Function: {fun.__name__}")
fun(*args, **kwargs)
return wrap_fun
@new_decorator
def say_something(words, emoji = ":)"):
print(words, emoji)
say_something("A bomb is coming!!!!!!")
# Another example
from time import time
def performance(fn):
def wrapper(*args, **kwargs):
t1 = time()
result = fn(*args, **kwargs)
t2 = time()
print(f"This function took: {t2 - t1}s")
return result
return wrapper
@performance
@new_decorator
def caculate():
for i in range(10000):
i*5
caculate()
| true
|
9a6cd4518c1bb000496a8aef48336b7b5179f809
|
hutbe/python_space
|
/13-FileIO/read_file.py
| 1,054
| 4.34375
| 4
|
test_file = open('Test.txt')
print("File read object:")
print(test_file)
print("Read file first time")
print(test_file.read()) # The point will move to the end of file
print("Read file second time")
test_file.seek(0) # move the point back to the head of file
print(test_file.read())
print("Read file third time")
print(test_file.read()) # nothing will print here
test_file.seek(0)
print(test_file.readline()) # read file line by line
print(test_file.readline())
print(" ======== readlines =======")
test_file.seek(0)
file_list = test_file.readlines()
print(file_list)
print(" ======= end =========")
test_file.close() # close the file
# The standard way to open a file
# Do not need seek with as handle file opening and closing
print(" ======== open file with as First =======")
with open('Test.txt') as file_object:
print(file_object.read())
print(" ======= end =========")
print(" ======== open file with as Second =======")
with open('Test.txt') as file_object:
print(file_object.readlines())
print(" ======= end =========")
| true
|
d5c8b082ed261c2e01b595bbe3eb2eb6b4366300
|
LinLeng/xiaoxiyouran_all
|
/python2/20180718零基础学习python/Python-From-Zero-to-One/unmd/课时038 类和对象 继承/review002.py
| 599
| 4.15625
| 4
|
# Summary:定义一个点(Point)类和直线(Line)类,使用getLen方法可以获得直线的长度
# Author: Fangjie Chen
# Date: 2017-11-15
import math
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
class Line(Point):
def __init__(self, p1, p2):
self.x = p1.x - p2.x
self.y = p1.y - p2.y
self.len = 0
# 计算直线长度
def getLen(self):
self.len = math.sqrt(self.x * self.x + self.y * self.y)
return self.len
| false
|
ed8e8f7646b93809bf53f84dc4654ecc61ffbac7
|
Omkar2702/python_project
|
/Guess_the_number.py
| 887
| 4.21875
| 4
|
Hidden_number = 24
print("Welcome to the Guess The Number Game!!")
for i in range(1, 6):
print("Enter Guess", int(i), ": ")
userInput = int(input())
if userInput == Hidden_number:
print("Voila! you've guessed it right,", userInput, "is the hidden number!")
print("Congratulations!!!!! You took", i, "guesses to win the game!")
break
elif 0 < userInput < 24:
if 20 < userInput < 24:
print("You are very close to get it right! Guess a higher number now!")
else:
print("You've guessed it very less buddy!")
else:
if 24 < userInput < 28:
print("You are very close to get it right! Guess a lower number now!")
else:
print("You've gone too far away!")
print("You are left with ", (5-i), "guesses")
print("GAME OVER!")
print("The Hidden_number was: ", Hidden_number)
| true
|
7fbdcfad250a949cb0575167c87d212f376e4d98
|
vaish28/Python-Programming
|
/JOC-Python/NLP_Stylometry/punct_tokenizer.py
| 405
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Punctuation tokenizer
"""
#Tokenizes a text into a sequence of alphabetic and non-alphabetic characters.
#splits all punctuations into separate tokens
from nltk.tokenize import WordPunctTokenizer
text="Hey @airvistara , not #flyinghigher these days we heard? #StayingParkedStayingSafe #LetsIndiGo laugh/cry"
tokens=WordPunctTokenizer().tokenize(text)
print(tokens)
| true
|
0290746b9b476109ea203930c5ccaaf2ec98bf31
|
qwatro1111/common
|
/tests/tests.py
| 1,917
| 4.125
| 4
|
import unittest
from math import sqrt
from homework import Rectangle
class Test(unittest.TestCase):
def setUp(self):
self.width, self.height = 4, 6
self.rectangle = Rectangle(self.width, self.height)
def test_1_rectangle_perimeter(self):
cheack = (self.width+self.height)*2
result = self.rectangle.get_rectangle_perimeter()
self.assertEqual(cheack, result)
def test_2_rectangle_square(self):
cheack = self.width*self.height
result = self.rectangle.get_rectangle_square()
self.assertEqual(cheack, result)
def test_3_sum_of_corners_valid(self):
cheack = 4*90
result = self.rectangle.get_sum_of_corners(4)
self.assertEqual(cheack, result)
def test_4_sum_of_corners_invalid(self):
with self.assertRaises(ValueError):
self.rectangle.get_sum_of_corners(6)
def test_5_sum_of_corners_invalid(self):
with self.assertRaises(ValueError):
self.rectangle.get_sum_of_corners(0)
def test_6_rectangle_diagonal(self):
cheack = sqrt(self.width**2 + self.height**2)
result = self.rectangle.get_rectangle_diagonal()
self.assertEqual(cheack, result)
def test_7_radius_of_circumscribed_circle(self):
cheack = self.rectangle.get_rectangle_diagonal() / 2
result = self.rectangle.get_radius_of_circumscribed_circle()
self.assertEqual(cheack, result)
def test_8_radius_of_inscribed_circle(self):
rectangle = Rectangle(width=1, height=1)
cheack = rectangle.get_rectangle_diagonal() / 2 * sqrt(2)
result = rectangle.get_radius_of_inscribed_circle()
self.assertEqual(cheack, result)
def test_9_radius_of_inscribed_circle(self):
with self.assertRaises(ValueError):
return self.rectangle.get_radius_of_inscribed_circle()
if __name__ == '__main__':
unittest.main()
| true
|
8c44895f64d1161588c25e339ff6b23c82d8290e
|
KhaledAchech/Problem_Solving
|
/CodeForces/Easy/File Name.py
| 2,425
| 4.375
| 4
|
"""
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by 1. For example, if you delete the character in the position 2 from the string "exxxii", then the resulting string is "exxii".
Input
The first line contains integer n (3≤n≤100) — the length of the file name.
The second line contains a string of length n consisting of lowercase Latin letters only — the file name.
Output
Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.
"""
#inputs
n = int(input())
s = input()
#initializing x : x_counter and i : iteration_counter
x = 0
i = 0
#specific case so we don't loop for unecessary reasons
#i ve noticed that if the string is containing only x's
#then x will be n(length of the string 's') - 2
if 'x'*n == s :
x = n - 2
#another specification where if there s no 'xxx' in the whole string
#then we ll go ahead and give x the 0 value :)
elif s.count('xxx') == 0:
x = 0
else:
#the actual work start here :)
#the loop will go on until there is no more 'xxx' in s
while s.count('xxx') != 0:
#each new time the loop will go on i will be initialized
i = 0
while i!=len(s):
#sub will hold every 3 characters of the string
sub = s[i:i+3]
#now sub will be compared to 'xxx' if they are equal
#then we ll need to leave one 'x' behind and increment the x value :)
if sub == 'xxx':
s = s[i+1:n]
x += 1
#then reinitialize i as the length of s has changed
i = 0
else:
#else we ll just increment i to get another sub in the next loop :)
i += 1
#printing the result :)
print(x)
| true
|
33290292667e0df5ef32c562b2320933446a118e
|
KhaledAchech/Problem_Solving
|
/CodeForces/Easy/Helpful Maths.py
| 1,112
| 4.21875
| 4
|
"""
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input
The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.
Output
Print the new sum that Xenia can count.
"""
#input
s = input()
#spliting the string by '+' so we can sort it
l = sorted(s.split('+'))
#result
new_s = '+'.join(l)
print(new_s)
| true
|
df968f4a057fb8d98111729759b1ef5ddb2eb2b2
|
dirtypy/python-train
|
/cn/yanxml/hello/firstStep.py
| 265
| 4.125
| 4
|
#!/usr/bin/python3
#coding=utf-8
#Python3 编程第一步
#Python3 first step of programming
#Fabonacci series
a,b=0,1
while b < 10:
print (b)
a,b=b,a+b;
i=265*256
print ("i 's value is : ", i);
a,b=0,1
while b<1000:
print(b,end=",")
a,b=b,a+b
| false
|
afebc658717b8f3badb5ee990c9d9e48ef32bc0e
|
makyca/Hacker-Rank
|
/Power-Mod_Power.py
| 286
| 4.25
| 4
|
#Task
#You are given three integers: a, b, and m, respectively. Print two lines.
#The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m).
a = int(raw_input())
b = int(raw_input())
m = int(raw_input())
print pow(a,b)
print pow(a,b,m)
| true
|
e0f20d297d8816da124a9f4e8a41a23e680e95b7
|
makyca/Hacker-Rank
|
/Sets-Symmetric_Difference.py
| 719
| 4.28125
| 4
|
#Task
#Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates
#those values that exist in either M or N but do not exist in both.
#Input Format
#The first line of input contains an integer, M.
#The second line contains M space-separated integers.
#The third line contains an integer, N.
#The fourth line contains N space-separated integers.
#Output Format
#Output the symmetric difference integers in ascending order, one per line.
Memova = int(raw_input())
m = set(map(int, raw_input().split(' ')))
Nemova = int(raw_input())
n = set(map(int, raw_input().split(' ')))
mix1 = n.symmetric_difference(m)
for x in sorted(list(mix1)):
print x
| true
|
8f6a0b68353c38fad53150c779444b96abc1b8e5
|
levi-terry/CSCI136
|
/hw_28JAN/bool_exercise.py
| 1,284
| 4.15625
| 4
|
# Author: LDT
# Date: 27JAN2019
# Title: bool_exercise.py
# Purpose: This program is comprised of several functions.
# The any() function evaluates an array of booleans and
# returns True if any boolean is True. The all() function
# evaluates an array of booleans and returns True if all
# are True.
# Function to evaluate if any values in an array are true
def any(booleanArray):
for i in booleanArray:
if i:
return True
else:
return False
# Function to evaluate if all values in an array are true
def all(booleanArray):
flag = True
for i in booleanArray:
if not i:
flag = False
return flag
# Code Testing
if __name__ == "__main__":
trueArray = [True, True, True, True]
tfArray = [True, False, True, False]
falseArray = [False, False, False, False]
print("This should return True: ", end='')
print(any(trueArray))
print("This should return True: ", end='')
print(any(tfArray))
print("This should return False: ", end='')
print(any(falseArray))
print("This should return True: ", end='')
print(all(trueArray))
print("This should return False: ", end='')
print(all(tfArray))
print("This should return False: ", end='')
print(all(falseArray))
| true
|
1c73961f953b4686742f415bc9aaf2fe389f8d14
|
levi-terry/CSCI136
|
/hw_30JAN/recursion_begin.py
| 1,860
| 4.15625
| 4
|
# Author: LDT
# Date: 27JAN2019
# Title: recursion_begin.py
# Purpose: This program implements two functions.
# The first function accepts an int array as a parameter
# and returns the sum of the array using recursion. The
# second function validates nested parentheses oriented
# correctly, such as (), (()()), and so on using recursion
# Int sum w/recursion function
def int_sum(array):
if len(array) == 0:
return 0
else:
return array[0] + int_sum(array[1:])
# Parentheses function recursion
def parentheses_nesting(string): # FIXME: Add the code, what to return?
pass
# Code testing
if __name__ == "__main__":
# Test int_sum function
intArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
intArray2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print("Testing int_sum function on first array...")
print("Results should read 55:")
print(int_sum(intArray))
if int_sum(intArray) == 55:
print("Success!")
else:
print("Need to fix int_sum function...")
print("Testing int_sum function on second array...")
print("Results should read 145")
print(int_sum(intArray2))
if int_sum(intArray2) == 145:
print("Success!")
else:
print("Need to fix int_sum function...")
# Test parentheses_nesting function
paren1 = "()" # Good
paren2 = "()()" # Good
paren3 = "(()())" # Good
paren4 = "((()()()))" # Good
paren5 = ")(" # Bad
paren6 = "(()))())" # Bad
print("Testing parentheses_nesting function...")
print("Results TBD") # FIXME: Figure out what results should look like after writing code
print(parentheses_nesting(paren1))
print(parentheses_nesting(paren2))
print(parentheses_nesting(paren3))
print(parentheses_nesting(paren4))
print(parentheses_nesting(paren5))
print(parentheses_nesting(paren6))
| true
|
7868d39dfc5a0e63481d605c23d303303c851bb9
|
levi-terry/CSCI136
|
/hw_28JAN/three_true.py
| 912
| 4.34375
| 4
|
# Author: LDT
# Date: 27JAN2019
# Title: three_true.py
# Purpose: This program implements a function which returns
# True if 1 or 3 of the 3 boolean arguments are True.
# Function to perform the checking of 3 booleans
def three_true(a, b, c):
if a:
if b:
if c:
return True
else:
return False
elif c:
return False
else:
return True
elif b:
if c:
return False
else:
return True
elif c:
return True
else:
return False
# Testing Code
if __name__ == "__main__":
t = True
f = False
print(three_true(t, t, t))
print(three_true(t, t, f))
print(three_true(t, f, t))
print(three_true(t, f, f))
print(three_true(f, t, t))
print(three_true(f, t, f))
print(three_true(f, f, t))
print(three_true(f, f, f))
| true
|
f9646e355ca1ee3d740e122152613929508bb03d
|
theprogrammer1/Random-Projects
|
/calculator.py
| 342
| 4.34375
| 4
|
num1 = float(input("Please enter the first number: "))
op = input("Please enter operator: ")
num2 = float(input("Please enter the secind number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
else:
print("Invalid operator")
| false
|
66afd8353ae48aa03ac42674765b59b18884d19a
|
wjwainwright/ASTP720
|
/HW1/rootFind.py
| 2,848
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
def bisect(func,a,b,threshold=0.0001):
"""
Bisect root finding method
Args:
func: Input function that takes a single variable i.e. f(x) whose root you want to find
a: lower bound of the range of your initial guess where the root is an element of [a,b]
b: upper bound of the range of your initial guess where the root is an element of [a,b]
threshold: degree of accuracy you want in your root such that |f(root)| < threshold
Returns:
If an even number (including zero) of roots is located between the points a and b, then the function returns nothing and prints accordingly.
Otherwise, the function returns a float c where f(c) is within the threshold of zero.
"""
c = (a+b)/2
count = 0
while(True):
if func(a) < 0 and func(b) < 0 :
print("Both f(a) and f(b) are negative. Try again, buddy")
return 0,0
elif func(a) > 0 and func(b) > 0 :
print("Both f(a) and f(b) are positive. Try again, buddy")
return 0,0
else:
if func(a)*func(c) < 0 :
b = float(c)
else:
a = float(c)
c = (a+b)/2
count += 1
if(abs(func(c)) < threshold):
return c,count
def newton(func,funcPrime,pos,threshold=0.0001):
"""
Newton root finding method
Args:
func: Input function that takes a single variable i.e. f(x) whose root you want to find
funcPrime: Input function for the analytical derivative of the same function f(x)
pos: initial guess for an x value that is ideally somewhat close to the root
threshold: degree of accuracy you want in your root such that |f(root)| < threshold
Returns:
Returns a float c where f(c) is within the threshold of zero.
"""
count = 0
while(abs(func(pos)) > threshold):
pos = pos - func(pos)/funcPrime(pos)
count += 1
return pos,count
def secant(func,a,b,threshold=0.0001):
"""
Secant root finding method
Args:
func: Input function that takes a single variable i.e. f(x) whose root you want to find
a: lower bound of the range of your initial guess where the root is an element of [a,b]
b: upper bound of the range of your initial guess where the root is an element of [a,b]
threshold: degree of accuracy you want in your root such that |f(root)| < threshold
Returns:
Returns a float c where f(c) is within the threshold of zero.
"""
count = 0
while(abs(func(b)) > threshold):
temp = float(b)
b = b - func(b) * ( (b-a)/(func(b)-func(a)) )
a = float(temp)
count += 1
return b,count
| true
|
fe0e8af3b6d088f25a8726e32abe1ab08c03b8c3
|
vickyjeptoo/DataScience
|
/VickyPython/lesson3a.py
| 381
| 4.1875
| 4
|
#looping - repeat a task n-times
# 2 types :for,while,
#modcom.co.ke/datascience
counter = 1
while counter<=3:
print('Do Something',counter)
age=int(input('Your age?'))
counter=counter+1 #update counter
# using while loop print from 10 to 1
number=11
while number>1:
number=number-1
print(number)
#print -20 to -1
x=-21
while x<-1:
x=x+1
print(x)
| true
|
e9a0af2257266fa452fddf4b79e1939784bca493
|
vickyjeptoo/DataScience
|
/VickyPython/multiplication table.py
| 204
| 4.21875
| 4
|
number = int(input("Enter a number to generate multiplication table: "))
# use for loop to iterate 10 times
for i in range(1, 13):
print(number, 'x', i, '=', number * i)
#print a triangle of stars
| true
|
32bdec09e8dc8ef94efd14ff0ab50b7585fdda7d
|
vickyjeptoo/DataScience
|
/VickyPython/lesson5.py
| 1,511
| 4.25
| 4
|
#functions
#BMI
def body_mass_index():
weight=float(input('Enter your weight:'))
height=float(input('Enter your height:'))
answer=weight/height**2
print("Your BMI is:",answer)
#body_mass_index()
#functions with parameters
#base&height are called parameters
#these parameters are unknown,we provide them during function call
def area(base,height):
#base = 50
#height =5
answer=0.5*base*height
print('Your area is:',answer)
area(base=50,height=5)
#function to calculate electricity bill
#Units is a parameter
def electricity(units):
if units<=50:
print('pay',units*3.40)
elif units>=50 and units<=100:
print('pay',units*4)
elif units>=100 and units<=200:
print('pay',units*4.50)
else:
print('pay',units*5.20)
#value=float(input('What are your units'))
electricity(units=444)
#parameters vs arguments
#parameters are defined in the function i.e def function(param1,param2,....)
#arguments are provided during function call to fit the defined parameters.
#write a function to convert kshs to any other currency(USD,EURO,YEN,RAND)
def convert_money(KES):
print(KES*0.0096,'USD')
print(KES*0.0087,'EURO')
print(KES*1.05 ,'YEN')
print(KES*0.14,'RAND')
value=float(input('Enter amount you wish to convert:'))
convert_money(KES=value)
#OOP-Object Oriented Programming
#create a function that check if a password has a Capital,Number,Symbol,not less than 8 letters.
#hint:ifs,re(regular expression)
#test :qweRT#123
| true
|
6c29609d8a5ab1027cdff8124b794110b5a9e7fa
|
Aamecstha/pythonClass
|
/functionPart3.py
| 1,132
| 4.1875
| 4
|
# def main():
# def inner_func():
# print("i am inner function")
#
# def outer_func():
# print("i am outer function")
#
# return inner_func,outer_func
#
# print(main())
# inf,onf=main()
# inf()
# onf()
# def main(n):
# def add(a,b):
# return a+b
# def sub(a,b):
# return a-b
#
# if n==1:
# return add
# elif n==2:
# return sub
#
# type=int(input("enter a type: "))
# ref=main(type)
# num1=int(input("enter a no: "))
# num2=int(input("enter a no: "))
# print(ref(num1,num2))
##Immutable obj example
# num=10
#
# def main_func():
# global num #using gloabl keyword to link num to the global variable otherwise it would reference to local variable
# num=num+1
# print(num)
#
# main_func()
#
# #mutable obj example
# alist=[1,2]
#
# def main():
# alist.append(5)
#
# print(alist)# main()
# print(alist)
num=5
def main():
num=10
def inner_func():
nonlocal num #using nonlocal keyword to reference to parenet fucntion variable
num=num+1
print(num)
inner_func()
main()
| false
|
a4322a82e093af0b6a1a4acdfcbb5540b7084db5
|
PragmaticMates/python-pragmatic
|
/python_pragmatic/classes.py
| 675
| 4.25
| 4
|
def get_subclasses(classes, level=0):
"""
Return the list of all subclasses given class (or list of classes) has.
Inspired by this question:
http://stackoverflow.com/questions/3862310/how-can-i-find-all-subclasses-of-a-given-class-in-python
Thanks to: http://codeblogging.net/blogs/1/14/
"""
# for convenience, only one class can can be accepted as argument
# converting to list if this is the case
if not isinstance(classes, list):
classes = [classes]
if level < len(classes):
classes += classes[level].__subclasses__()
return get_subclasses(classes, level+1)
else:
return classes
| true
|
bbf2d3478a74caf1156c2a174a2674366244857c
|
Code-JD/Python_Refresher
|
/02_string_formatting/code.py
| 731
| 4.21875
| 4
|
# name = "Bob"
# greeting = f"Hello, {name}"
# print(greeting)
# name = "Ralph"
# print(greeting)
# ---------------OUTPUT-------------
# Hello, Bob
# Hello, Bob
# name = "Bob"
# print(f"Hello, {name}")
# name = "Ralph"
# print(f"Hello, {name}")
# ---------------OUTPUT-------------
# Hello, Bob
# Hello, Ralph
# name = "Bob"
# greeting = "Hello, {}"
# with_name = greeting.format(name)
# with_name_two = greeting.format("Ralph")
# print(with_name)
# print(with_name_two)
# ---------------OUTPUT-------------
# Hello, Bob
# Hello, Ralph
longer_phrase = "Hello, {}. Today is {}."
formatted = longer_phrase.format("Ralph", "Monday")
print(formatted)
# ---------------OUTPUT-------------
# Hello, Ralph. Today is Monday.
| false
|
b09b2657f56cb03fae84b598ce256753b6eb4571
|
prashant523580/python-tutorials
|
/conditions/neg_pos.py
| 336
| 4.4375
| 4
|
#user input a number
ui = input("enter a number: ")
ui = float(ui) #converting it to a floating point number
#if the number is greater then zero
# output positive
if ui > 0:
print("positive number")
#if the number is less then zero
#output negative
elif ui < 0:
print("negative number")
#in all other case
else:
print("zero ")
| true
|
6d8d75053d9d281db48f32327598b55e1010ee78
|
deepak1214/CompetitiveCode
|
/InterviewBit_problems/Sorting/Hotel Booking/solution.py
| 1,298
| 4.34375
| 4
|
'''
- A hotel manager has to process N advance bookings of rooms for the next season.
His hotel has C rooms. Bookings contain a list A of arrival date and a list B of departure date.
He wants to find out whether there are enough rooms in the hotel to satisfy the demand.
- Creating a function hotel which will take 3 arguments as arrive, depart and K
- First we will sort both the list arrive and depart
- Then we will traverse the list arrive and check for the index elements at i+K that the element in
arrive is less than depart i.e. arrive date is less than depart date
- If arrive date is less than depart date then there are no rooms and returning False
- But if no arrive date is less than depart date then there are enough rooms for N bookings and hence returning True
'''
def hotel(arrive, depart, K):
arrive.sort()
depart.sort()
for i in range(len(arrive)):
if i+K<len(arrive) and arrive[i+K]<depart[i]:
return False
return True
if __name__=="__main__":
A=[ 13, 14, 36, 19, 44, 1, 45, 4, 48, 23, 32, 16, 37, 44, 47, 28, 8, 47, 4, 31, 25, 48, 49, 12, 7, 8 ]
B=[ 28, 27, 61, 34, 73, 18, 50, 5, 86, 28, 34, 32, 75, 45, 68, 65, 35, 91, 13, 76, 60, 90, 67, 22, 51, 53 ]
C=23
result=hotel(A,B,C)
print(result)
| true
|
4eb966b642158fd2266ae747d4cd6fcf694acfe2
|
deepak1214/CompetitiveCode
|
/LeetCode_problems/Invert Binary Tree/invert_binary_Tree.py
| 1,436
| 4.125
| 4
|
from collections import deque
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
# invert of binary tree means left elemtns goes to right and right element goes to left
# this is the most simple problem but sometimes confused when they see it first time
# so here is the solution
def invertTree(root):
if root is None:
return 0
# invert the elements simple swapping
root.left , root.right = root.right , root.left
# left Invert
root.left = invertTree(root.left)
# right invert
root.right = invertTree(root.right)
return root
root = TreeNode(5)
insert(root , TreeNode(3))
insert(root , TreeNode(8))
insert(root , TreeNode(2))
insert(root , TreeNode(4))
insert(root , TreeNode(7))
insert(root , TreeNode(9))
inorder(root)
print('Inverted')
inorder(invertTree(root))
| true
|
d4cc2c4c13be0e76bb0b78f50f32dacef61b63ee
|
deepak1214/CompetitiveCode
|
/Hackerrank_problems/counting_valleys/solution.py
| 1,605
| 4.125
| 4
|
# Importing the required Libraries
import math
import os
import random
import re
import sys
# Fuction For Counting the Valleys Traversed. Takes the number of steps(n) and The path(s[D/U]). Returns the Number.
def countingValleys(n, s):
count = 0
number_of_valleys = 0 # Initialized Variables count and number_of_valleys with 0.
for i in range(n): # Looping the steps traversed by the no. of steps given.
if(s[i] == 'U'): # Check if the Step equal to 'U' Then Count Incremented by 1
count += 1
if(count == 0): # Check if After certain steps The counter reaches to 0, Means a valleys is trversed.
number_of_valleys += 1 # Hence increment the number_of_valleys by one.
elif(s[i] == 'D'): # Check if the Step equal to 'U' Then Count Incremented by 1
count -= 1
return(number_of_valleys) # Returning the number of valleys traversed.
# Check if the main is there and then run the main program.
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input()) # Taking the input from user. The number of steps in the hike.
s = input() # A single string of Steps characters that describe the path (D/U).
result = countingValleys(n, s) # Calling the countingvalleys function, Return the number of valleys traversed
fptr.write(str(result) + '\n') # Writing/Printing the Result
fptr.close() # Closing the Program
| true
|
26614f5cbe266818c5f34b536b9f921c922a18d2
|
WSMathias/crypto-cli-trader
|
/innum.py
| 2,012
| 4.5625
| 5
|
"""
This file contains functions to process user input.
"""
# return integer user input
class Input:
"""
This class provides methods to process user input
"""
def get_int(self, message='Enter your number: ', default=0, warning=''):
"""
Accepts only integers
"""
hasInputNumbers = False
while hasInputNumbers==False:
try: # try to convert user input into a integer number
userInput = input(message)
if userInput is '':
if default == 0:
message = message+'\r'
continue
else:
return default
userInput = int(userInput)
hasInputNumbers=True
return userInput
except ValueError: # if it gives a ValueError, return to line 2!
print("[!] invalid input try again")
# return floating point user input
def get_float(self, message='Enter your number: ', default=0,warning=''):
"""
Accepts integer and floating point numbers
"""
hasInputNumbers = False
while hasInputNumbers==False:
try: # try to convert user input into a floating number
userInput = input(message)
if userInput is '':
if default == 0:
continue
else:
return default
userInput = float(userInput)
hasInputNumbers=True
return userInput
except KeyboardInterrupt :
raise
except ValueError: # if it gives a ValueError, return to line 2!
print("[!] invalid input try again")
def get_coin(self, message='Enter Coin symbol : ', default='', warning=''):
"""
Accepts Coin Symbol
"""
return input(message)
#TODO: Logic need to be implimented
| true
|
b76b9aaa2581473624e311da1306aff5bedc5e0d
|
luckcul/LeetCode
|
/algorithms/Implement Queue using Stacks/ImplementQueueUsingStack.py
| 1,276
| 4.21875
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-11-30 21:13:57
# @Author : luckcul (tyfdream@gmail.com)
# @Version : 2.7.12
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack.append(x)
def pop(self):
"""
:rtype: nothing
"""
sta = []
l = len(self.stack)
for i in range(l):
tmp = self.stack.pop()
sta.append(tmp)
sta.pop()
for i in range(l-1):
tmp = sta.pop()
self.stack.append(tmp)
def peek(self):
"""
:rtype: int
"""
sta = []
l = len(self.stack)
for i in range(l):
tmp = self.stack.pop()
sta.append(tmp)
ret = sta.pop()
self.stack.append(ret)
for i in range(l-1):
tmp = sta.pop()
self.stack.append(tmp)
return ret
def empty(self):
"""
:rtype: bool
"""
return True if len(self.stack)==0 else False
x = Queue()
x.push(1)
x.push(2)
print x.peek()
x.pop()
print x.peek()
print x.empty()
x.pop()
print x.empty()
| false
|
20191d04dad06de1f7b191ed7538828580eac557
|
jeremycross/Python-Notes
|
/Learning_Python_JoeMarini/Ch2/variables_start.py
| 609
| 4.46875
| 4
|
#
# Example file for variables
#
# Declare a variable and initialize it
f=0
# print(f)
# # # re-declaring the variable works
# f="abc"
# print(f)
# # # ERROR: variables of different types cannot be combined
# print("this is a string" + str(123))
# Global vs. local variables in functions
def someFunction():
global f #tells program that we are using f found as a global
f="def"
print(f)
print(f) #prints f = 0
someFunction() #changes and prints f
print(f) #prints new value of f
del f #deletes the definition of a variable that was previously declared
print(f) #f is no longer defined here
| true
|
6ec438602e86c1eeebbab11746d4445b84e0187a
|
jeremycross/Python-Notes
|
/Essential_Training_BillWeinman/Chap02/hello.py
| 365
| 4.34375
| 4
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 42
print('Hello, World. %d' % x) #you can use ''' for strings for '"' for strings, either works
# above line is legacy from python 2 and is deprecated
print('Hello, world. {}'.format(x))
# format is a function of the string object
print(f'Hello, world. {x}') # f-string here call format function
| true
|
6a2928e4bfce469b9681a4f263dd43d95b0d5c7f
|
AmiMunshi/mypythonprojects
|
/semiprime
| 1,014
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 5 15:16:46 2019
@author: maulik
"""
def prime(num):
for i in range(2,num):
if num % i ==0:
#print("Not prime")
return False
break
else:
return True
#print("prime")
def semiprime(N):
for i in range(2, int(N**0.5)+1):
if N%i==0:
num1=int(i)
#print(num1)
num2= int(N/num1)
#print(num2)
if num1==num2:
#print("Not a semiprime")
return False
break
elif prime(num1) and prime(num2)==True:
#print("The number is semiprime")
return True
break
else:
#print("Not a semiprime")
return False
N1=int(input())
for i in range(2, N1-1):
s1= i
s2= N1-i
if semiprime(s1) and semiprime(s2)== True:
print("Yes")
break
else:
print("No")
| false
|
9fbd24524c7fbeec9a79c7f6a2ecdc1d6992ab08
|
Crewcop/pcc-exercises
|
/chapter_three_final.py
| 822
| 4.21875
| 4
|
# 3-8
# list of locations
destinations = ['london', 'madrid', 'brisbane', 'sydney', 'melbourne']
print(destinations)
# print the list alphabetically without modifying it
print('\nHere is the sorted list : ')
print(sorted(destinations))
# print the original order
print('\nHere is the original list still :')
print(destinations)
# print the list in reverse alpha order
print('\nHere is the sorted list in reverse : ')
print(sorted(destinations, reverse=True))
print(destinations,'\n')
# use reverse to change the order
destinations.reverse()
print(destinations, '\n')
# reverse it back
destinations.reverse()
print(destinations, '\n')
# sort the list alphabetically permanently
destinations.sort()
print(destinations, '\n')
# use sort() to reverse the order
destinations.sort(reverse=True)
print(destinations, '\n')
| true
|
8b93a72a07be2865330628e84d8255718bf838d0
|
aakash19222/Pis1
|
/p.py
| 351
| 4.1875
| 4
|
def rotate(s, direction, k):
"""
This function takes a string, rotation direction and count
as parameters and returns a string rotated in the defined
direction count times.
"""
k = k%len(s)
if direction == 'right':
r = s[-k:] + s[:len(s)-k]
elif direction == 'left':
r = s[k:] + s[:k]
else:
r = ""
print("Invalid direction")
return r
| true
|
c8c3de51f3c5828ac8ce280924f83c7d8474b3c0
|
PrinceCuet77/Python
|
/Extra topic/lambda_expression.py
| 824
| 4.3125
| 4
|
# Example : 01
def add(a, b) :
return a + b
add2 = lambda a, b : a + b # 'function_name' = lambda 'parameters' : 'return_type'
print(add(4, 5))
print(add2(4, 5))
# Example : 02
def multiply(a, b) :
return a * b
multiply2 = lambda a, b : a * b
print(multiply(4, 5))
print(multiply2(4, 5))
# Calling function and lambda
print(add)
print(add2)
print(multiply)
print(multiply2)
# Example : 03
# Cheching a number is even or not
is_even = lambda a : a % 2 == 0
print()
print(is_even(2))
print(is_even(3))
# Example : 04
# Printing the last character of the string
last_char = lambda s : s[-1]
print(last_char('Prince'))
print()
# Example : 05
# Lambda expression with if else condition
checking = lambda a : True if a > 5 else False
print(checking(3))
print(checking(6))
print()
| true
|
bd802c4bae44b75a820c70349a5eab4221bac821
|
PrinceCuet77/Python
|
/Tuple/tuple.py
| 1,323
| 4.3125
| 4
|
example = ('one', 'two', 'three', 'one')
# Support below functions
print(example.count('one'))
print(example.index('one'))
print(len(example))
print(example[:2])
# Function returning tuple
def func(int1, int2) :
add = int1 + int2
mul = int1 * int2
return add, mul
print(func(2, 3)) # Returning tuple
add, mul = func(4, 5) # Unpacking tuple two variable
print(add)
print(mul)
# Looping into tuple
mixed = (1, 2.0, 'three')
for i in mixed : # Using for loop
print(i, end = ' ')
print()
i = 0
while i < len(mixed) : # Using while loop
print(mixed[i])
i += 1
# Tuple with one element
one = (1)
word = ('word')
print(type(one))
print(type(word))
one1 = (1,)
word1 = ('word',)
print(type(one1))
print(type(word1))
# Tuple without paranthesis
num = 'one', 'two', 'three'
num1 = 1, 2, 3
print(type(num))
print(type(num1))
# Tuple unpacking
st = ('prince', 23)
name, age = st # Unpacking
print(name)
print(age)
# List inside tuple
value = (1, 2, ['three', 'four'])
value[2].pop()
value[2].append('five')
print(value)
# range(), tuple(), max(), min(), sum() functions
t = tuple(range(1, 6))
print(max(t))
print(min(t))
print(sum(t))
| true
|
553c0af65afd7d80a9ebfca8a1bc80f1ab660726
|
PrinceCuet77/Python
|
/List/list_comprehension.py
| 1,520
| 4.28125
| 4
|
# List comprehension
# With the help of list comprehension, we can create a list in one line
# Make a list of square from 1 to 10
sq = [i**2 for i in range(1, 11)]
print(sq)
# Create a list of negative number from 1 to 10
neg = [-i for i in range(1, 11)]
print(neg)
# Make a list where store the first character from the other list which consists of strings
name = ['Rezoan', 'Shakil', 'Prince']
new_list = [ch[0] for ch in name]
print(new_list)
# Make a list where store the reverse string from other list which consists of strings
name = ['Rezoan', 'shakil', 'Prince']
l = [ch[::-1] for ch in name]
print(l)
# List comprehensive with if statement
# Make a list where store only even numbers from 1 to 10
l = [i for i in range(1, 11) if i % 2 == 0]
print(l)
l2 = [i for i in range(1, 11) if i & 1 == 0]
print(l2)
# Make a list where store only int or float variable in the form of string from the other list which consists all data types
def make_list(l) :
return [str(i) for i in l if (type(i) == int or type(i) == float)]
l = [True, False, (1, 2, 3), [4, 5], {4, 5}, {3:3}, 1, 'string', 4.4]
new_l = make_list(l)
print(new_l)
# List comprehensive with if else statement
# Make a list where store odd numbers as negative and even numbers as square of even numbers
l = [i**2 if (i & 1 == 0) else -i for i in range(1, 11)]
print(l)
l2 = [i**2 if (i % 2 == 0) else -1 for i in range(1, 11)]
print(l2)
# Nested list
# Using list comprehension
mat = [[i for i in range(1, 4)] for i in range(3)]
print(mat)
| true
|
712f46fc65f3c6d3c8ca8154748f9a942c6781f2
|
cnaseeb/Pythonify
|
/queue.py
| 815
| 4.125
| 4
|
#!/usr/bin/python
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items ==[] #further conditions implementation needed
def enqueue(self, item):
return self.items.insert(0, item) #further checks needed if queue already contains items
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
#instantiate the queue object
q = Queue()
# check the size of the queue
q.size()
#Insert items into the queue
q.enqueue('test1')
q.enqueue('item2')
q.enqueue('Ams')
q.enqueue('CPH')
#check the size again
q.size()
#check if teh queue is empty or not
q.isEmpty()
#delete or dequeue an item
q.dequeue()
#check teh size after the deletion of an item
q.size()
| true
|
3b66cd079d10af6018cc90c45eacac8e52c053a6
|
sporttickets/Portfolio-programming
|
/deciding.py
| 212
| 4.25
| 4
|
#learning about if statements
number = int(raw_input("enter your age\n"))
if number < 15:
print "you still are in middle school"
else:
print "you know everthing"
if number < 5:
print "you are not in school"
| false
|
2d7308d13f713b7c98492c3a8aa0a95a2aad0903
|
charliepoker/pythonJourney
|
/simple_calculator.py
| 876
| 4.25
| 4
|
def add(x,y):
return x + y
def Subraction(x,y):
return x - y
def Multiplication(x,y):
return x * y
def Division(x,y):
return x / y
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
num_1 = float(input('Enter your first number: '))
num_2 = float(input('Enter your second number: '))
if operation == '+':
print('{} + {} = '.format(num_1,num_2))
print(num_1 + num_2)
elif operation == '-':
print('{} - {} = ' .format(num_1, num_2))
print(num_1 - num_2)
elif operation == '*':
print('{} * {} = ' .format(num_1, num_2))
print(num_1 * num_2)
elif operation == '/':
print('{} / {} = '.format(num_1, num_2))
print(num_1 / num_2)
else:
print('You selected an invalid operator, please run the program again.')
| true
|
77f5fe9c0172c1eecc723b682a3d2c82eda2918d
|
charliepoker/pythonJourney
|
/lists.py
| 2,340
| 4.40625
| 4
|
#list is a value that contains multiple values in an ordered sequence.
number = [23, 67, 2, 5, 69, 30] #list of values assigned to number
name = ['mike', 'jake', 'charlie', 'tim', 'dave', 'jane'] #list of values assigned to name
print(name[2] + ' is ' + str(number[5]) + ' years old.')
#list can be contained in other list
spam =[['cat', 'dog', 'bat'], [4, 80, 57, 'figo', 'ayo'], [10, 45, 100, 5, 6, 9]] #This list contains 3 lists
print(spam[1] [4])
print(spam[2] [2])
print(spam[1] [2])
#Negative indexes
animals = ['cat', 'bat', 'rat', 'elephant']
print('The ' + animals[-4] + ' is ' + 'afraid ' + ' of the ' + animals[-1] + '.')
#Getting sublist with slices
animals = ['cat', 'bat', 'rat', 'elephant', 'goat']
print(animals[1:3])
animals[1:4] = ['snake', 'fox', 'antelope']
print(animals)
name = ['mike', 'jake', 'charlie', 'tim', 'dave', 'jane']
print(name[:5]) #This is a shortcut that leaves out the first index or the begining of the list but starts the slice from 0
print(name[3:]) #This is a shortcut that leaves out the second index of the list but ends the slice at the end of the list
print(name[:]) #This is a shortcut that slices the list from the begining to the end
print(len(name)) #This gives the lenght of the list
#Changing values in the list with slices
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
city[2] = 'auchi' #This switches the value in index 2 which is kano to auchi
print(city)
city[3] = city[5] #This makes the value in index 3 same with index 5
print(city)
city[-1] = 'Bida'
print(city)
#List Concatenation and List Replication
new_list = animals + city #This adds both list together to form a new list
print(new_list)
new_list = (new_list + name)
print(new_list)
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
new_city = city * 3 #This replicates the list 3 times
print(new_city)
#Removing Values from Lists with del Statements
city = ['lagos', 'abuja','kano','benin', 'jos', 'ilorin', 'ibadan', 'owerri']
del(city[2]) # this removes the value at index 2 from the list
print(city)
#list(function)
x = ('Hello World')
list(x)
print(list(x))
| true
|
0211c3fa0ff36391c2394f1ea8973d07d4555c87
|
bodawalan/HackerRank-python-solution
|
/cdk.py
| 2,845
| 4.3125
| 4
|
# Q.1
#
# Write a function that takes as input a minimum and maximum integer and returns
# all multiples of 3 between those integers. For instance, if min=0 and max=9,
# the program should return (0, 3, 6, 9)
#
# A
# you can type here
def func(min, max):
for in xrange(min, max):
if (i % 3 == 0)
print
i
end
# Q.2
# Write a function to detect whether a string is a palindrome - that is,
# the string reads the same in reverse as it does forward. Samples:
# racecar, tacocat, madam, level, etc. Function should return True or False
def main():
inputStr = input("Enter a string": ")
if ispalindrome(inputStr):
print("String is Palindrome")
else:
print("String is not palindrome")
def isPalindrome(string):
if len(string) <= 1:
return True
if String[0] == String[len(string) - 1]:
return isPalindrome(string[1: len(string) - 1])
else:
return False
# Q.3
# Modify your function to work with sentences, ignoring punctuation and capitalization.
# For instance, these should be detected as palindromes:
#
# Eva, Can I Stab Bats In A Cave?
# A Man, A Plan, A Canal-Panama!
import string
def isPalindrome
whitelist = set(string.ascii_lowercase)
s = s.lower
s = ''.join(([char for char in s if char in whitelist])
return s = s[::-1]
revstring = mystring[::-1]
if (mysrtring == revstring):
print("its a palindrome")
else:
# Q.4
# if tuples are immutable, why does this work?
mytuple = (1, 2, 'abc', ['x', 'y'])
mytuple[3].append('z')
mytuple
# (1, 2, 'abc', ['x', 'y', 'z'])
# But this does not work?
mytuple[3] = ['x', 'y', 'z']
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'tuple' object does not support item assignment
# Q.5
# Write a function to find the longest number of consecutive appearances of a
# character in a string
# for example: 'fzccsawetaaafb' => (a, 3)
word = "foo"
count = 1
lenght = ""
for i in range(1, len(word)): # range(1, 3)
if word[i - 1] == word[i]: # word[3] <-- key error
count += 1
else:
length += word[i - 1] + "repeats +str(count)+", "
count = 1
length += ("and" + word[i] + "repeats" + str(count))
print(length)
b
"aabbbbbbccaaa"
("b", 6) < - output
if (cur_count > count)
count = cur_count;
res = str
# Q.6
# Write a function to swap the elements of one list with another, for examples:
#
# l1 = [1,2,3]
# l2 = ['a', 'b', 'c']
# swap_elements(l1, l2)
#
# l1 is now ['a', 'b', 'c']
# l2 is now [1,2,3]
def swap_elements(11, 12)
11, 12 = 12, 11
# Jon - output here:
>> > def swap_elements(l1, l2):
...
l1, l2 = l2, l1
...
>> > l1 = [1, 2, 3]
>> > l2 = ['a', 'b', 'c']
>> >
>> > swap_elements(l1, l2)
>> > l1
[1, 2, 3]
>> > l2
['a', 'b', 'c']
import dis
def swap1():
| true
|
07969f835c57729793df401fc7e367e4e6d399a6
|
dodieboy/Np_class
|
/PROG1_python/coursemology/Mission32-CaesarCipher.py
| 1,288
| 4.71875
| 5
|
#Programming I
####################################
# Mission 3.2 #
# Caesar Cipher #
####################################
#Background
#==========
#The encryption of a plaintext by Caesar Cipher is:
#En(Mi) = (Mi + n) mod 26
#Write a Python program that prompts user to enter a plaintext
#and displays the encrypted result using Caesar Cipher.
#Important Notes
#===============
#1) Comment out ALL input prompts before submitting.
#2) You MUST (at least) use the following variables:
# - plaintext
# - ciphertext
#START CODING FROM HERE
#======================
#Perform Encryption of given plaintext
def caesarEncrypt(plaintext, key):
#Code to do the conversion
ciphertext = ""
for i in range(len(plaintext)):
char = plaintext[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
ciphertext += chr((ord(char) + key-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
ciphertext += chr((ord(char) + key - 97) % 26 + 97)
print(ciphertext) #Modify to display the encrypted result
return ciphertext #Do not remove this line
#Do not remove the next line
#caesarEncrypt(plaintext,key)
caesarEncrypt('HELLOWORLDTHESECRETISOUT',5)
| true
|
03396cc7b38b7a779ca33d376a6ccb33720289b0
|
dodieboy/Np_class
|
/PROG1_python/coursemology/Mission72-Matrix.py
| 1,081
| 4.25
| 4
|
#Programming I
#######################
# Mission 7.1 #
# MartrixMultiply #
#######################
#Background
#==========
#Tom has studied about creating 3D games and wanted
#to write a function to multiply 2 matrices.
#Define a function MaxtrixMulti() function with 2 parameters.
#Both parameters are in a matrix format.
#Important Notes
#===============
#1) Comment out ALL input prompts before submitting.
A = [[1,2,3],
[4,5,6],
[7,8,9]]
B = [[2,0,0],
[0,2,0],
[0,0,2]]
#START CODING FROM HERE
#======================
#Create your function here
def matrixmulti(A, B):
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(A)):
# iterate through columns of Y
for j in range(len(B[0])):
# iterate through rows of Y
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print(result)
return result
#Do not remove the next line
matrixmulti(A, B)
#3) For testing, print out the output
# - Comment out before submitting
| true
|
c3ba57ea7ad83b5819851bafb7e88d62cd267c8d
|
jason-neal/Euler
|
/Completed Problems/Problem 5-smallest_multiple.py
| 641
| 4.15625
| 4
|
"""Smallest multiple
Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to
10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers
from 1 to 20?
"""
import numpy as np
def smallest_multiple(n):
"""Smallest multiple of numbers 1 thru n."""
numbers = np.arange(n) + 1
num = n
while True:
if np.all(num % numbers):
return num
else:
num += 1
assert smallest_multiple(10) == 2520
prob_num = 20
sm = smallest_multiple(prob_num)
print("Smallest multiple of 1 thru {} = {}".format(prob_num, sm))
| true
|
cbc97978dbafa655d385b6741d6c046cb648cff4
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Basics/4_Conditional_Statements/fruit_or_vegitable.py
| 386
| 4.34375
| 4
|
product_name = input()
if product_name == 'banana' or product_name == 'apple' or product_name == 'kiwi' or product_name == 'cherry' or \
product_name == 'lemon' or product_name == 'grapes':
print('fruit')
elif product_name == 'tomato' or product_name == 'cucumber' or product_name == 'pepper' or product_name == 'carrot':
print('vegetable')
else:
print('unknown')
| true
|
0569f8f4243c3694a236fd8daf00171893d8666c
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Fundamentals/03_Basic_Syntax_Conditions_Loops/maximum_multiple.py
| 397
| 4.1875
| 4
|
'''
Given a Divisor and a Bound, find the largest integer N, such that:
N is divisible by divisor
N is less than or equal to bound
N is greater than 0.
Notes: The divisor and bound are only positive values. It's guaranteed that a divisor is found
'''
divisor = int(input())
bound = int(input())
max_num = 0
for i in range(1, bound+1):
if i % divisor == 0:
max_num = i
print(max_num)
| true
|
5b3145219fbf8802f747d84079e0c4ca2099a4a8
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Basics/4_Conditional_Statements/number_100_200.py
| 587
| 4.15625
| 4
|
"""
Conditional Statements - Lab
Check: https://judge.softuni.bg/Contests/Practice/Index/1012#0
06. Number 100 ... 200
Condition:
Write a program that reads an integer entered by the user and checks if it is below 100,
between 100 and 200 or over 200. Print messages accordingly, as in the examples below:
Sample input and output
entrance exit entrance exit entrance exit
95 Less than 100 120 Between 100 and 200 210 Greater than 200
"""
num = int(input())
if num < 100:
print('Less than 100')
elif num <= 200:
print('Between 100 and 200')
else:
print('Greater than 200')
| true
|
fc8c286f691360c9b96b4c91fa3fabeccade2aac
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Fundamentals/04_Lists/bread_factory.py
| 2,805
| 4.3125
| 4
|
"""
As a young baker, you are baking the bread out of the bakery.
You have initial energy 100 and initial coins 100. You will be given a string, representing the working day events. Each event is separated with '|' (vertical bar): "event1|event2|event3…"
Each event contains event name or item and a number, separated by dash("{event/ingredient}-{number}")
If the event is "rest": you gain energy, the number in the second part. But your energy cannot exceed your initial energy (100). Print: "You gained {0} energy.".
After that, print your current energy: "Current energy: {0}.".
If the event is "order": You've earned some coins, the number in the second part. Each time you get an order, your energy decreases with 30 points.
If you have energy to complete the order, print: "You earned {0} coins.".
If your energy drops below 0, you skip the order and gain 50 energy points. Print: "You had to rest!".
In any other case you are having an ingredient, you have to buy. The second part of the event, contains the coins you have to spent and remove from your coins.
If you are not bankrupt (coins <= 0) you've bought the ingredient successfully, and you should print ("You bought {ingredient}.")
If you went bankrupt, print "Closed! Cannot afford {ingredient}." and your bakery rush is over.
If you managed to handle all events through the day, print on the next three lines:
"Day completed!", "Coins: {coins}", "Energy: {energy}".
Input / Constraints
You receive a string, representing the working day events, separated with '|' (vertical bar): " event1|event2|event3…".
Each event contains event name or ingredient and a number, separated by dash("{event/ingredient}-{number}")
Output
Print the corresponding messages, described above.
"""
events = input().split('|')
energy = 100
coins = 100
is_closed = False
for event in events:
args = event.split('-')
event_ingredient = args[0]
number = int(args[1])
if event_ingredient == 'rest':
temp = 0
if energy + number <= 100:
temp = number
energy += number
else:
temp = int(100 - energy)
energy = 100
print(f'You gained {temp} energy.')
print(f'Current energy: {energy}.')
elif event_ingredient == 'order':
if energy >= 30:
energy -= 30
coins += number
print(f'You earned {number} coins.')
else:
energy += 50
print("You had to rest!")
else:
if coins-number <= 0:
is_closed = True
break
else:
coins -= number
print(f'You bought {event_ingredient}.')
if is_closed:
print(f'Closed! Cannot afford {event_ingredient}.')
else:
print(f'Day completed!\nCoins: {coins}\nEnergy: {energy}')
| true
|
b4bb635ae844e30f8fd58d64eeab5adda17726b2
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Fundamentals/04_Lists/04.Search.py
| 1,153
| 4.3125
| 4
|
"""
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#3
SUPyF2 Lists Basics Lab - 04. Search
Problem:
You will receive a number n and a word. On the next n lines you will be given some strings.
You have to add them in a list and print them.
After that you have to filter out only the strings that include the given word and print that list also.
Examples:
Input:
3
SoftUni
I study at SoftUni
I walk to work
I learn Python at SoftUni
Output:
['I study at SoftUni', 'I walk to work', 'I learn Python at SoftUni']
['I study at SoftUni', 'I learn Python at SoftUni']
Input:
4
tomatoes
I love tomatoes
I can eat tomatoes forever
I don't like apples
Yesterday I ate two tomatoes
Output:
['I love tomatoes', 'I can eat tomatoes forever', "I don't like apples", 'Yesterday I ate two tomatoes']
['I love tomatoes', 'I can eat tomatoes forever', 'Yesterday I ate two tomatoes']
"""
lines = int(input())
special_word = input()
my_list = []
special_list = []
for _ in range(lines):
word = input()
if special_word in word:
special_list.append(word)
my_list.append(word)
print(my_list)
print(special_list)
| true
|
5fc56d9d02475b497d20988fbe8a244faec680e9
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Projects_Creation.py
| 762
| 4.3125
| 4
|
"""
Simple Operations and Calculations - Lab
05. Creation Projects
Check: https://judge.softuni.bg/Contests/Compete/Index/1011#2
Write a program that calculates how many hours it will take an architect to design several
construction sites. The preparation of a project takes approximately three hours.
Entrance
2 lines are read from the console:
1. The name of the architect - text;
2. Number of projects - integer.
Exit
The following is printed on the console:
"The architect {architect's name} will need {hours needed} hours to complete {number of projects} project / s."
"""
name = input()
projects_count = int(input())
time_needed = int(projects_count*3)
print(f"The architect {name} will need {time_needed} hours to complete {projects_count} project/s.")
| true
|
b0e20c859c4c65478d955ee75ec04bbf2c0a370a
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Fundamentals/04_Lists/number_filter.py
| 1,173
| 4.1875
| 4
|
"""
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#4
SUPyF2 Lists Basics Lab - 05. Numbers Filter
Problem:
You will receive a single number n. On the next n lines you will receive integers.
After that you will be given one of the following commands:
• even
• odd
• negative
• positive
Filter all the numbers that fit in the category (0 counts as a positive). Finally, print the result.
Example:
Input:
5
33
19
-2
18
998
even
Output:
[19, -2, 18, 998]
Input:
3
111
-4
0
negative
Output:
[-4]
"""
n = int(input())
numbers = []
filtered = []
for i in range(n):
current_number = int(input())
numbers.append(current_number)
command = input()
if command == "even":
for number in numbers:
if number % 2 == 0:
filtered.append(number)
elif command == "odd":
for number in numbers:
if number % 2 != 0:
filtered.append(number)
elif command == "negative":
for number in numbers:
if number < 0:
filtered.append(number)
elif command == "positive":
for number in numbers:
if number >= 0:
filtered.append(number)
print(filtered)
| true
|
eec96339c928ff8c2148957172c237c2cb015a2f
|
stevalang/Coding-Lessons
|
/SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Fish_Tank.py
| 582
| 4.1875
| 4
|
# 1. Read input data and convert data types
lenght = int(input())
width = int(input())
height = int(input())
percent_stuff = float(input())
# 2. Calculating aquarium volume
acquarium_volume = lenght * width * height
#3. Convert volume (cm3) -> liters
volume_liters= acquarium_volume * 0.001
#4. Calculating litter taken from stuffs
volume_stuff = (volume_liters*percent_stuff)/100
#5. Calculating volume left
final_volume = volume_liters- volume_stuff
#4. Print and format
print(f'{final_volume:.3f}')
# a = 5
# b = 2
# result = a % b
# print(result)
# print(type(result))
| true
|
73ca29ffb697d7e08b72cbc825a7a7672d989dd4
|
happyandy2017/LeetCode
|
/Rotate Array.py
| 2,287
| 4.1875
| 4
|
# Rotate Array
# Go to Discuss
# Given an array, rotate the array to the right by k steps, where k is non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Example 2:
# Input: [-1,-100,3,99] and k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
# Note:
# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
# Could you do it in-place with O(1) extra space?
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
N = len(nums)
k = k%N
if N==1 or k==0:
return
nums[:] = nums[-k:]+nums[:-k]
def rotate_2(self, nums, k):
N = len(nums)
k = k%N
if N==1 or k==0:
return
l=0 # number of swaps
i=0
j=(i+k)%N
while l<N-1:
if i == j:
i+=1
j=(i+k)%N
l+=1 # need to reduce by 1
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
j= (j+k)%N
l+=1
# for j in range(k):
# temp = nums[N-1]
# for i in range(N-2,-1, -1):
# nums[i+1]=nums[i]
# nums[0] = temp
# count = 0
# i = 0
# while count<N:
# i_next = i+k
# if i_next>=N:
# i_next = i_next%N
# temp = nums[i_next]
# nums[i_next]=nums[i]
# i=i_next+1
# else:
# temp = nums[i_next]
# nums[i_next]=nums[i]
# i=i_next
# count+=1
# return nums
import time
time1 = time.time()
nums = [1,2,3,4,5,6]
k = 6
Solution().rotate(nums, k)
print(nums)
print('time', time.time()-time1)
| true
|
ab4b0424777999fbe22abb732279e9f3de3efeb3
|
happyandy2017/LeetCode
|
/Target Sum.py
| 2,048
| 4.125
| 4
|
'''
Target Sum
Go to Discuss
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
'''
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
# dynamic program
if not nums:
return 0
dict = {0:1}
for i in range(len(nums)):
# tdict = {}
import collections
tdict = collections.defaultdict(int)
for sum in dict: # 把相同的sum key的merge起来
# tdict[nums[i]+sum] = tdict.get(nums[i]+sum,0)+dict.get(sum,0)
# tdict[-nums[i]+sum] = tdict.get(-nums[i]+sum,0)+dict.get(sum,0)
tdict[sum+nums[i]] += dict[sum]
tdict[sum-nums[i]] += dict[sum]
dict = tdict
return dict.get(S,0)
# def findTargetSumWays_time_limit_exceed(self, nums, S):
# """
# :type nums: List[int]
# :type S: int
# :rtype: int
# """
# if not nums:
# return 0
# if len(nums)==1:
# if nums [0]== 0 and S == 0: # important, +-0 = 0, two ways
# return 2
# if nums[0]==S or -nums[0]==S:
# return 1
# return 0
# return self.findTargetSumWays(nums[1:], S-nums[0]) + self.findTargetSumWays(nums[1:], S+nums[0])
| true
|
1e458d8bbd986b4b838f784b15ed9f6aaf5eccfc
|
mblue9/melb
|
/factorial.py
| 928
| 4.1875
| 4
|
import doctest
def factorial(n):
'''Given a number returns it's factorial e.g. factorial of 5 is 5*4*3*2*1
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(3)
6
'''
if not type(n) == int:
raise Exception("Input to factorial() function must be an integer")
if n < 0:
raise Exception("Factorial for negative numbers is not defined")
total = 1
while n > 1:
total *= n
n -= 1
return total
def fibonacci(n):
'''Returns the Nth value in the Fibonacci
sequence
F(N) = F(N-1) + F(N-2)
F(0) = 0, F(1) = 1
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(5)
5
'''
assert n >= 0
assert isinstance(n, int)
a, b = 0, 1
while n > 0:
a, b = b, a+b
n -= 1
return a
if __name__ == "__main__":
doctest.testmod()
| true
|
a000ab576b9eefeb3be6565177102dea660a1b74
|
TrafalgarSX/graduation_thesis_picture-
|
/lineChart.py
| 678
| 4.4375
| 4
|
import matplotlib.pyplot as pyplot
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
pyplot.plot(x, y, color='green',linestyle='dashed', linewidth=3, marker='*',markerfacecolor='blue',markersize=12, label = "line 1")
x1 = [1,2,3]
y1 = [4,1,3]
# plotting the line 2 points
pyplot.plot(x1, y1, label = "line 2")
#setting x and y axis range
pyplot.ylim(0,9)
pyplot.xlim(0,9)
# naming the x axis
pyplot.xlabel('x -axis')
# naming the y axis
pyplot.ylabel('y -axis')
#giving a title to my graph
pyplot.title('Some cool customizations!')
#show a legend on the plot
pyplot.legend()
# function to show the plot
pyplot.show()
| true
|
992e6ee0179e66863f052dce347c35e0d09b9138
|
rowaxl/WAMD102
|
/assignment/0525/factorial.py
| 316
| 4.25
| 4
|
def fact(number):
if number == 0:
return 1
if number == 1 or number == -1:
return number
if number > 0:
nextNum = number - 1
else:
nextNum = number + 1
return number * fact(nextNum)
number = int(input("Enter a number for calculate factorial: "))
print(f"{number}! = ", fact(number))
| true
|
4b52d601646ac88a58de8e75d09481e65d758fa5
|
seriousbee/ProgrammingCoursework
|
/src/main.py
| 2,452
| 4.125
| 4
|
def print_welcome_message():
print('Welcome to Split-it')
def print_menu_options():
menu_dict = {'About\t\t': '(A)', 'CreateProject\t': '(C)',
'Enter Votes\t': '(V)', 'Show Project\t': '(S)',
'Quit\t\t': '(Q)'}
for k, v in menu_dict.items():
print(f'{k} {v}') # not 100% what this f is but it doesn't work without it
print("Please choose an option and press <ENTER>:")
def is_int(text):
try:
int(text)
return True
except ValueError:
return False
def safe_int_input():
text = input()
if is_int(text):
return int(text)
print("Try again. Enter an integer number:")
safe_int_input()
def option_a():
print('\033[1m' + 'Option A: About Spliddit\n' + '\033[0m')
print("Hello. This is Spliddit. "
"I am an app that can help you share and distribute things with your friends and colleagues, "
"from grades to bills, to notes and good memories. "
"What would you like to split today? "
"You can decide that by personalizing me in option C.")
input("\nPress <Enter> to return to the main menu: ")
def option_c():
print('\033[1m' + 'Option C: Creating a Project' + '\033[0m')
print("Enter the project name: ")
project_name = input() # value never used
students = [] # value never used
print("Enter the number of team members:")
number = safe_int_input()
while number <= 0:
print("The number must be positive:")
number = safe_int_input()
for i in range(number):
print("\t Enter the name of team member " + str(i+1) + ": ")
student = input()
students.append(student)
input("\nPress <Enter> to return to the main menu:\n ")
def get_menu_option_from_user(attempt=0):
if attempt == 0:
print_menu_options()
choice = input()
choice = choice.upper()
if choice == "A":
option_a()
get_menu_option_from_user(0)
elif choice == "Q":
exit(0)
elif choice == "V":
get_menu_option_from_user(0)
elif choice == "S":
get_menu_option_from_user(0)
elif choice == "C":
option_c()
get_menu_option_from_user(0)
else:
print("\n Please choose only options from the menu above: ")
get_menu_option_from_user(1)
def main():
print_welcome_message()
get_menu_option_from_user()
if __name__ == '__main__':
main()
| true
|
d60ce1dada99b234ac9eaf94e2e59826656e048b
|
Abhirashmi/Python-programs
|
/Faulty_calculator.py
| 934
| 4.3125
| 4
|
op = input("Enter the operator which you want to use(+,-,*,/):")
num1 = int(input("Enter 1st Number:"))
num2 = int(input("Enter 2st Number:"))
if op == "+":
if num1 == 56 or num1 == 9:
if num2 == 9 or num2 == 56:
print("Addition of", num1, " and", num2, " is 77")
else:
print("Addition of",num1," and",num2," is ",num1+num2)
elif op == "*":
if num1 == 45 or num1 == 3:
if num2 == 3 or num2 == 45:
print("Multiplication of", num1, " and", num2, " is 555")
else:
print("Multiplication of",num1," and",num2," is ",num1*num2)
elif op == "/":
if num1 == 56 and num2 == 6:
print("Multiplication of", num1, " and", num2, " is 4")
else:
print("Division of", num1, " and", num2, " is ", num1 / num2)
elif op == "-":
print("Subtraction of", num1, " and", num2, " is ", num1 - num2)
else:
print("Enter valid Operator")
| false
|
18c271cc6a83f2402125fe692919b625e2af5265
|
shants/LeetCodePy
|
/225.py
| 1,627
| 4.125
| 4
|
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = []
self.q2 = []
self.isFirst = True
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
if self.isFirst:
self.q1.append(x)
else:
self.q2.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if self.isFirst:
for i in range(len(self.q1)-1):
e = self.q1.pop(0)
self.q2.append(e)
self.isFirst = False
e1 = self.q1.pop()
self.q1 = []
return e1
else:
for i in range(len(self.q2)-1):
e = self.q2.pop(0)
self.q1.append(e)
self.isFirst = True
e1 = self.q2.pop()
self.q2 = []
return e1
def top(self):
"""
Get the top element.
:rtype: int
"""
if self.isFirst:
return self.q1[len(self.q1)-1]
else:
return self.q2[len(self.q2) - 1]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self.q1)==0 and len(self.q2)==0
# Your MyStack object will be instantiated and called as such:
obj = MyStack()
obj.push(1)
obj.push(2)
param_2 = obj.pop()
param_3 = obj.top()
param_4 = obj.empty()
print(param_2)
print(param_3)
print(param_4)
| false
|
be4579851af7ea20e3ed8cfeeeb0e493426273c4
|
mayankkuthar/GCI2018_Practice_1
|
/name.py
| 239
| 4.28125
| 4
|
y = str(input(" Name "))
print("Hello {}, please to meet you!".format(y))
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = y
print ("Did you know that your name backwards is {}?".format(reverse(s)))
| true
|
72bbfab5a298cda46d02758aae824188c0703f8c
|
josan5193/CyberSecurityCapstone
|
/CapstoneMain.py
| 859
| 4.1875
| 4
|
def main():
while True:
Test1Word = input("What's your name?: ")
try:
Test1Num = int(input("Please choose one of three presidential candidates: \n 1. Donald Trump \n 2. Joe Biden \n 3. Bernie Sanders \n"))
if Test1Num >= 1 and Test1Num <= 3:
print("Congratulations," , Test1Word, ", you have voted!")
else:
print("Please choose a valid option between 1 and 3, or this session will be closed\n\n")
Test1Num = int(input("Please choose one of three presidential candidates: \n 1. Donald Trump \n 2. Joe Biden \n 3. Bernie Sanders \n"))
if Test1Num >= 1 and Test1Num <= 3:
print("Congratulations, You have voted")
else:
print("This session will close. Please ask election staff for assistance")
except ValueError:
print("Error! This is not a number. This session will close. Please ask election staff for assistance \n\n")
break
main()
| true
|
49d2f9a2183b3fc93c29d450ae3e84923ceefea8
|
python-packages/decs
|
/decs/testing.py
| 907
| 4.4375
| 4
|
import functools
def repeat(times):
"""
Decorated function will be executed `times` times.
Warnings:
Can be applied only for function with no return value.
Otherwise the return value will be lost.
Examples:
This decorator primary purpose is to repeat execution of some test function multiple times:
import random
@repeat(10)
def test_int_is_taken():
examples = list(range(10)
assert type(random.choice(examples)) == int, 'Error!'
# No error, test is repeated 10 times.
Args:
times(int): required number of times for the function to be repeated.
Returns:
None
"""
def repeat_helper(func):
@functools.wraps(func)
def call_helper(*args):
for i in range(times):
func(*args)
return call_helper
return repeat_helper
| true
|
9279ba88a2f2fd3f7f3a5e908362cb0b0449c97d
|
KendallWeihe/Artificial-Intelligence
|
/prog1/main[Conflict].py
| 1,477
| 4.15625
| 4
|
#Psuedocode:
#take user input of number of moves
#call moves ()
#recursively call moves() until defined number is reached
#call main function
import pdb
import numpy as np
#specifications:
#a 0 means end of tube
#1 means empty
red_tube = np.empty(6)
red_tube[:] = 2
green_tube = np.empty(5)
green_tube[:] = 3
yellow_tube = np.empty(4)
yellow_tube[:] = 4
blue_tube = np.empty(3)
blue_tube[:] = 5
white_tube = np.empty(2)
white_tube[:] = 6
black_tube = np.empty(1)
black_tube[:] = 7
pdb.set_trace()
solved_puzzle = np.empty((12,6))
solved_puzzle[12:12,10:12,8:12,6:12,4:12,2:12] = 0.0
solved_puzzle[6:12,5:10,4:8,3:6,2:4,1:2] = 1.0
pdb.set_trace()
def main():
#function is called by move() after k moves has been reached
print
def move(num_moves, num_moves_left, puzzle):
#make recursive move
#check for whether or not move has reached defined number of moves
#else make random move (out of the three)
#then recursively call move()
#finally call solver function
#after each recursive call, move() needs to check if the user wants to undo another move
#if rotate, calculate size of new arrays, generate new arrays, and fill with necessary elements
#if tube is cut in half, move balls past threshold value into new array
#if flip, reorder all arrays in reverse
print
k = input("Please enter the number of moves to shuffle the puzzle: ")
print "Number of moves = " + str(k)
moves(k,k,empty_puzzle)
| true
|
14709bc0146ea083df29d1d42f0c23abeae1d0d8
|
HBlack09/ICTPRG-Python
|
/Examples/upperlower.py
| 225
| 4.375
| 4
|
# upper/lower case example
txt = "Hello my friends"
txt2 = txt.upper()
print(txt)
print(txt2)
txt3 = txt.lower()
print(txt3)
t1 = "aBc"
t2 = "AbC"
print("t1: ", t1)
print("t2: ", t2)
print(t1 == t2)
print(t1.upper() == t2.upper())
| false
|
cc315e7aa80c04128721d665deb4c1eadf081d8f
|
YaqoobAslam/Python3
|
/Assignment/Count and display the number of lines not starting with alphabet 'A' present in a text file STORY2.TXT.py
| 863
| 4.53125
| 5
|
Write a function in to count and display the number of lines not starting with alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.
def func():
Count = 0
fread = open('STORY2.TXT','r')
for line in fread:
lines = line
if lines.startswith('A'):
continue
Count +=1
print(lines)
print("Number of lines is:",Count)
func()
output:
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.
Number of lines is: 5
----------------------------------------
The rose is red.
There is a playground.
Numbers are not allowed in the password.
Number of lines is: 3
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.