blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
333c0c5121e562c2afd6f443ffd43a946adbfb4f | NASA2333/study | /leetcode/leetcode_125.py | 575 | 4.34375 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
'''
def isPalindrome(s):
c = [c for c in s.lower() if c.isalnum()]
return c==c[::-1]
print(isPalindrome("A man, a plan, a canal: Panama"))
print(isPalindrome("race a car")) | true |
f54a58df1267f5d1ea70a299dda58dcde0e86968 | NASA2333/study | /leetcode/pass/leetcode_31.py | 892 | 4.21875 | 4 | '''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
'''
import operator
def nextPermutation(nums):
num = int(nums)
# b = ''
while 1:
num +=1
if sorted(str(num)) ==sorted(str(nums)):
return num
# break
elif len(str(num))>len(str(nums)):
return str(nums)[::-1]
print(nextPermutation(7654321))
# print(bool(dict(['a','b']) ==dict(['b','a'])))
# print(bool(set()))
# print(operator.eq('abc','bac'))
# b= [x for x in 'abc']
# print(b)
# print(str(123)[::-1]) | true |
fd9a876424f919ba05553f49e210a99d940b39af | NASA2333/study | /leetcode/pass/leetcode_75.py | 898 | 4.21875 | 4 | '''
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:You are not suppose to use the library's sort function for this problem.
尽量只是用一次循环,不适用排序,将列表中相同的的元素放在一起
输入: nums = [1, 2, 1, 2, 0, 2, 1, 0, 2, 0, 0, 2]
输出: [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]
'''
##insert 索引不可以为负数
def sortColors(nums):
L = len(nums)
sum1 = 0
while sum1 <=L:
if nums[sum1] ==0:
nums.insert(0,0)
del nums[sum1+1]
sum1 +=1
elif nums[sum1] ==2:
nums.extend([2])
del nums[sum1]
L -=1
else:
sum1 +=1
return nums
print(sortColors([1, 2, 1, 2, 0, 2, 1, 0, 2, 0, 0, 2,1,2,1,1,1,0,1,2,0]))
| true |
8090495b635faf68668a0334d68cbe414a79c0b6 | NASA2333/study | /leetcode/without/leetcode_69.py | 303 | 4.28125 | 4 |
'''
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
'''
# import math
#
# print(int(math.sqrt(8)))
def mysqrt(x):
for i in range(x//2+1):
if i*i <x and ((i+1)*(i+1))>x:
return i
elif i* i ==x:
return i
print(mysqrt(15)) | true |
df696be7394b9bdc3b29cc769ce6f6150da415be | princep2727/IANS-Practicals | /vignerecipher.py | 1,283 | 4.3125 | 4 | # Encryption of a plaintext
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i)for i in key]
plaintext_int = [ord(i) for i in plaintext]
ciphertext = ""
for i in range(len(plaintext_int)):
value = (plaintext_int[i]+key_as_int[ i % key_length]) % 26
ciphertext += chr(value + 65)
return ciphertext.upper()
# Decryphertext using encryot
def decrypt(ciphertext,key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
ciphertext_int = [ord(i) for i in ciphertext]
plaintext = ""
for i in range(len(ciphertext_int)):
value = (ciphertext_int[i] - key_as_int[i % key_length]) % 26
plaintext += chr(value + 65)
return plaintext.upper()
while True:
#input plaintext
print("hello what you wanna convert type 1 plaintext to ciphertext or 2 for ciphertext to plaintext")
a = int(input())
if a==1:
plaintext = input("enter the PLAINTEXT:")
key = input("Enter the key:")
print("Encrypted message",encrypt(plaintext, key))
elif a==2:
ciphertext = input("enter the CIPHERTEXT:")
key = input("Enter the key:")
print("Decrypted message", decrypt(ciphertext,key))
else:
print("sorry unable to code")
| false |
883d487d38d2a1abc43a9f24d6caa640867f47f1 | WangDrop/WangDropExercise | /python/A_Byte_Of_Python/cp12/objvar.py | 1,677 | 4.3125 | 4 | #!/usr/bin/env python
# coding=utf-8
class Robot:
''' represent a robot with a name '''
population = 0
def __init__(self, name):
'''Init the data '''
self.name = name
print('Initialze the {0}'.format(self.name))
Robot.population += 1
def __del__(self):
''' I am dying '''
print('{0} is now being destroyed !'.format(self.name))
Robot.population -= 1;
if(Robot.population == 0):
print('The ', self.name, ' is just the last one ')
else:
print('There also ',Robot.population , ' robots now working !')
def sayHi(self):
'''Greeting by the robots '''
print('Hello, my master call me {0}'.format(self.name))
def howMany(): #without self mean it is a static method
'''show the current population'''
print('we still have {0:d} robots '.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('wang');
droid1.sayHi()
Robot.howMany()
droid2 = Robot('cheng')
droid2.sayHi()
Robot.howMany()
del droid1
del droid2
#注意,这里的population实际上属于Robot类,但是name是属于对象的。前者相当于static变量
#howMany由于没有加上self进行限制,所以而且使用staticmethod修饰表示了其是一个静态方法
#当然,除了staticmethod修饰之外,也可以使用@staticmethod进行修饰,如下所示:
#@staticmethod
#def howMany():
#还有一点应该注意的是,python类中所有的成员,无论是数据还是方法都是共有的,有一个例外是
#双下划线前缀的数据成员例如:__privatevar,python会将其当做私有变量来看待
| false |
1922b03d039acc565cd349966ad673b566995a4e | zer0ttl/cryptopals-solutions | /set1/sol-6.py | 692 | 4.125 | 4 | import binascii
# bytes in python3 always return the ascii value of the byte
def to_binary(string):
return ''.join((format(char, '010b'))for char in string.encode("utf-8"))
# 010b means pad the output to 10 bits
# hamming_distance is also known as edit_distance
# hamming distance is the number of differing bits
def hamming_distance(string1, string2):
binary_string1 = to_binary(string1)
binary_string2 = to_binary(string2)
data = zip(binary_string1, binary_string2)
count = 0
for item in data:
if item[0] != item[1]:
count += 1
return count
s1 = "this is a test"
s2 = "wokka wokka!!!"
count = hamming_distance(s1, s2)
print(count) | true |
f6bd86a2d54c146d3d4a9bdb0ed34d91957104a2 | i81819168/280201079 | /lab3/example2.py | 294 | 4.21875 | 4 | num1=float(input("write the first number:"))
num2=float(input("write the second number:"))
num3=float(input("write the third number:"))
if num1<num2 and num1<num3:
print("minimum:",num1)
if num2<num1 and num2<num3:
print("minimum:",num2)
if num3<num1 and num3<num2:
print("minimum:",num3) | false |
12638649b4298d3029185deb877f2c40694d40be | tolekes/new_repo | /date and time.py | 550 | 4.1875 | 4 | import datetime
currentDate = datetime.date.today()
# # print(currentDate)
# # print(currentDate.day)
# # print(currentDate.strftime("%d %y %b"))
# userinput = input("Pls enter your birthday: (dd/mm/yy)")
# birthday = datetime.datetime.strptime(userinput,"%m/%d/%y").date()
# days = currentDate - birthday
# print(days.days)
deadline = input("when is the deadline for your project? :(dd:mm:yy)")
day = datetime.datetime.strptime(deadline,"%d:%m:%y").date()
no_of_days = day - currentDate
print("you have",no_of_days.days, "days before deadline") | false |
89e745a625fb1d75d4e6044e527c558e410a84e0 | MohamedSellahi/Python | /lists.py | 805 | 4.21875 | 4 | # the for statment
# ------------------
words = ['cat', 'window', 'defence']
for w in words:
print (w, len(w))
for w in words[:]:
if(len(w) > 6):
words.insert(0, w)
print(w)
print('after insertion')
for w in words:
print(w)
# Using range method
for i in range(0, 5):
print(i, ' ', end='')
print(end='\n')
for i in range(0, 10, 3):
print(i, ' ', end='')
print(end='\n')
print("i in range(10):")
for i in range(10):
print(i, ' ', end='')
print(end='\n')
print("""for i in range(len(a)):
print(i, a[i])""")
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
# list
it = list(range(5))
print("it = list(range(5))")
for i in it:
print(i, ' ', end='')
print(end='\n')
# Continue here : https://docs.python.org/3/tutorial/controlflow.html
| false |
bf3c8589d640be6c8e4dc5a4bfd2dd0fa7ab7055 | amaliawb/LearningPyhton | /Notes/functions.py | 1,856 | 4.375 | 4 | # FUNCTIONS
'''
- *args **kwags
- returns extra arguments in tuples, and extra key word args in dictionaries
- extra arguments and keyword arguments
- positional arguments = args based on position in func call
- keyword args = keyword = value, when theres an arg in calling a func which has a var set to
it meaning that if specified it doesnt matter in which position in the calling
- if func() returns an str u can use
string methods on it like func().lower
'''
def func(required_arg, *args, **kwargs):
print(required_arg)
if args:
print(args)
if kwargs:
print(kwargs)
# define
# function name and in () the parameters
def example():
print('\nbasic function learning')
a = 2 + 6
print(a)
example()
# or call the function in terminal without calling it in code
# PARAMETERS for functions
def simple_addition(num1, num2):
answer = num1 + num2
print('\nnum1 is', num1, 'num2 is', num2)
print(answer)
# when calling function I specify the parameters
simple_addition(2, 5)
simple_addition(num2=3, num1=6) # explicit parameter specification
# DEFAULT FUN PARAMETERS
def simple(num1, num2):
pass
# DEFAULT VALUE IN FUNC = when parameter is specified in fun define u dont have to specify it when calling, it is always that
def simple(num1, num2=5):
print(num1, num2)
simple(3)
## calling functions in functions
def one_good_turn(n):
return n + 1
def deserves_another(n):
return one_good_turn(n) + 2
# more and % division if number is divisible ny 3
def cube(number):
return number * number * number
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
# abs type
def distance_from_zero(x):
if (type(x) == int or type(x) == float):
return abs(x)
else:
return 'Nope'
| true |
240956f62f8c33389270fb09f80c9e19141f6209 | Harshu16/Linear-Regression-Model-Diabetes | /main.py | 2,122 | 4.21875 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use all features
diabetes_X= diabetes.data
# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-30]
diabetes_X_test = diabetes_X[-30:]
# Split the targets into training/testing sets
diabetes_Y_train = diabetes.target[:-30]
diabetes_Y_test = diabetes.target[-30:]
# Create linear regression object
model= linear_model.LinearRegression()
# Train the model using the training sets
model.fit(diabetes_X_train,diabetes_Y_train)
# Make predictions using the testing set
diabetes_Y_pred = model.predict(diabetes_X_test)
# In y=mx+b.....weight=m,feature=x,intercept=b.
print("Coefficient of linear regression or weights is:",model.coef_)
print("intercepts is:",model.intercept_)
# The mean squared error=The mean squared error tells you how close a regression line is to a set of points. It does this by taking the distances from the points to the regression line (these distances are the “errors”) and squaring them. The squaring is necessary to remove any negative signs.
print('Mean Squared error: %.2f'%mean_squared_error(diabetes_Y_test,diabetes_Y_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of prediction: %.2f'%r2_score(diabetes_Y_test,diabetes_Y_pred))
# Plot outputs
#plt.scatter(diabetes_X_test,diabetes_Y_test)
#plt.plot(diabetes_X_test,diabetes_Y_pred)
#plt.show()
#Output by extracting just one feature for plotting staight line y=mx+b is
#Coefficient of linear regression or weights is: [941.43097333]
#intercepts is: 153.39713623331698
#Mean Squared error: 3035.06
#Coefficient of prediction: 0.41
#Output by extracting all features is:
#Coefficient of linear regression or weights is: [ -1.16924976 -237.18461486 518.30606657 309.04865826 -763.14121622
458.90999325 80.62441437 174.32183366 721.49712065 79.19307944]
#intercepts is: 153.05827988224112
#Mean Squared error: 1826.54
#Coefficient of prediction: 0.65
| true |
071664ee0317b6951b1a5020370cb1fd59b7548c | sainanilakhni98/python3.0 | /rock paper scissors game.py | 934 | 4.1875 | 4 | #---------------------- Rock–paper–scissors game----------------------------
from random import choice
from time import sleep
l=["r","p","s"] ## From Random Module WE import Choice which provide Choice from list
while 1:
c=choice(l)
p=input("Enter R for Rock|P for Paper|S for Scissor% ----> ").strip().lower()
if p==c:
sleep(2) #From time module we import sleep which sleep the result for 2 second
print("Draw")
print("Computer choice",c)
elif p=="p" and c=="r" or p=="s" and c=="p" or p=="r" and c=="s":
sleep(2)
print("Player1 Wins")
print("computer choice",c)
else:
sleep(2)
print("computer Wins")
print("computer choice",c)
print()
print("For continue this game press y else press any key ")
ch=input("Enter your choice ")
if ch!="y":
break
| false |
8bdb7425ac3ec39c4946330d9bf00547894e9284 | michelleyick/Functions | /Class exercises (Revision Q2).py | 772 | 4.125 | 4 | #Michelle Yick
#08-12-2014
#Functions class exercises. Revision Q2
#The base of the pyramid
def pyramid_base(number):
total = ask_for_number()
return total
#Calculate answer(construction of the pyramid). IF the base number entered is odd.
def pyramid_body(number):
while number%2 == 0:
number = int(input("Please enter a odd number"))
total = "*" * ask_for_number()
return number,total
#Ask for number:
def ask_for_number():
number = int(input("Please enter a odd number"))
return number
#Display pyramid
def display_pyramid(total):
print(total)
#Main program
def printing_a_pyramid():
number = ask_for_number()
total = pyramid_body(number)
display_pyramid(total)
printing_a_pyramid()
| true |
c607bf6932911df67b68e6f222c26bd1b7f850a8 | mmkrisi/inf1340_2014_asst1 | /exercise1.py | 2,858 | 4.53125 | 5 | #!/usr/bin/env python3
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion
This module contains one function grade_to_gpa. It can be passed a parameter
that is an integer (0-100) or a letter grade (A+, A, A-, B+, B, B-, or FZ). All
other inputs will result in an error.
Example:
$ python exercise1.py
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2014 Susan Sim"
__license__ = "MIT License"
__status__ = "Prototype"
# imports one per line
def grade_to_gpa(grade):
"""
Returns the UofT Graduate GPA for a given grade.
:param:
grade (integer or string): Grade to be converted
If integer, accepted values are 0-100.
If string, accepted values are A+, A, A-, B+, B, B-, FZ
:return:
float: The equivalent GPA
Value is 0.0-4.0
:raises:
TypeError if parameter is not a string or integer
ValueError if parameter is out of range
"""
letter_grade = ""
gpa = 0.0
# dictionary with letter grades and gpa to use for assigning grade to letter_grade
letter_grade_gpa_dictionary = {"A+": 4.0, "A": 4.0, "A-": 3.7, "B+": 3.3, "B": 3.0, "B-": 2.7, "FZ": 0.0}
# list of letter grades to use when input is an int
list_of_letter_grade = ["A+", "A", "A-", "B+", "B", "B-", "FZ"]
if type(grade) is str:
#check that the grade is one of the accepted values
if grade in letter_grade_gpa_dictionary.keys():
#assign grade to letter_grade
return letter_grade_gpa_dictionary.get(grade)
else:
raise ValueError("Invalid letter grade passed as a parameter.")
elif type(grade) is int:
# check that grade is in the accepted range
if 0 <= grade <= 100:
# write a long if-statement to convert numeric grade to letter_grade
if 90 <= grade <= 100:
grade = list_of_letter_grade[0]
elif 85 <= grade < 90:
grade = list_of_letter_grade[1]
elif 80 <= grade < 85:
grade = list_of_letter_grade[2]
elif 77 <= grade < 80:
grade = list_of_letter_grade[3]
elif 73 <= grade < 77:
grade = list_of_letter_grade[4]
elif 70 <= grade < 73:
grade = list_of_letter_grade[5]
elif 0 <= grade < 70:
grade = list_of_letter_grade[6]
# assign grade to letter_grade
return letter_grade_gpa_dictionary.get(grade)
else:
raise ValueError ("Invalid percentage grade passed as a parameter.")
else:
raise TypeError("Invalid type passed as parameter")
if letter_grade in letter_grade_gpa_dictionary:
# assign the value to gpa
gpa = letter_grade_gpa_dictionary[grade]
return gpa
| true |
98b9773df27f329330270fb9d970d3dce5497abf | janam111/datastructures | /Recursion/Factorial.py | 282 | 4.21875 | 4 | # Non tail recursive
def get_fact(n):
if n == 1 or n == 0:
return 1
return n * get_fact(n-1)
# tail recursive
def get_factorial(n, k):
if n == 0 or n == 1:
return k
return get_factorial(n-1, k * n)
print(get_factorial(int(input('Enter num: ')), 1)) | false |
d1e23b111090342bdcb8cb6e6ca5bbabf007affc | IceBlueX/py | /6-面向对象编程/实例属性和类属性.py | 636 | 4.28125 | 4 | class Student(object):
name = 'Student'
s = Student() #创建实例s
print(s.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
print(Student.name) #打印类的name属性
s.name = 'Meiko' #给实例绑定name属性
print(s.name) #由于实例属性优先级比类属性高,因此他会屏蔽掉类的name属性
print(Student.name) #但是类属性并未消失,用Student.name仍可访问
del s.name #如果删除实例的name属性
print(s.name) #再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
| false |
90ba8a93f986a8d3bff0071242fc855c81297927 | KcNcoG/Algorithms | /Sort Algorithms/Annotated Version/selection_sort.py | 1,406 | 4.15625 | 4 | # selection_sort.py
# 首先在未排序序列中找到最小元素,存放到排序序列的起始位置。
# 然后,再从剩余未排序元素中继续寻找最小元素,然后放到已排序序列的末尾。
# 以此类推,直到所有元素均排序完毕。
def selection_sort(arr):
length = len(arr)
# 外层循环控制遍历的次数
# 选择排序中i的值从[0~length-2]
# -2 原因有以下两点:1.待排序数组索引的最大值为length-1。2.选择排序中如果length-1个元素已被排序,则整个序列有序
for i in range(length - 1):
# index用于保存未排序部分最小元素的索引
index = i
# 内层循环在每次遍历中将未排序部分最小的元素放至未排序部分首位
# 选择排序中j的取值范围为[i+1~length-1]
# i+1 由于内层循环开始时index=i,因此j最小取i+1
# -1 length-1是待排序部分最后一个元素的索引
for j in range(i + 1, length):
# 遍历未排序部分,如果找到更小的元素就保存其索引
if arr[j] < arr[index]:
index = j
# 将未排序部分最小的元素交换至未排序部分的首位
arr[i], arr[index] = arr[index], arr[i]
if __name__ == '__main__':
test = [8, 62, 82, 28, 70, 55, 60, 49, 66, 65]
selection_sort(test)
print(test)
| false |
4d1b981fa4512cb0355bb1b88400e6532869a05a | alen1994/Conditions-and-loops | /fizzbuzz.py | 348 | 4.125 | 4 | number = int(input("Hello User! Enter a number between 1 and 100: "))
print("The number is: " + str(number))
for number in range(1, number+1):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
| true |
a808734446415a3aefd1bf6c374f4fd647da9ca9 | bellaxin2010/PythonPraticeDemo | /pythonBasicDemo/TestCollection.py | 713 | 4.125 | 4 | # collect ,set ()
#
"""里面的元素不可变,代表你不能存一个list、dict 在集合里,字符串、数字、元组等不可变类型可以存
天生去重,在集合里没办法存重复的元素
无序,不像列表一样通过索引来标记在列表中的位置 ,元素是无序的,集合中的元素没有先后之分,如集合{3,4,5}和{3,5,4}算作同一个集合
"""
a ={1,3,4,2,1,3,'acb','ac','acb'}
#增加--
a.add('1')
# 不可变不可添加
#a.add(['ab'])
#元组可变可添加
a.add((1,3))
#删除--- discard 删除不存在的也不报错; pop()随机删 ;remove 没有就会报错
a.discard('ac2')
a.pop()
#a.remove('ac2')
#查
for i in a:
print(i)
print(a) | false |
3fedf1433491e3081f7131f016b471ee8a319081 | JDGC2002/programacion | /Examenes/Parcial1/Parcial1.py | 1,757 | 4.125 | 4 | #POINT 1
def SumSubsMult (Value1=0, Value2=0, Value3=0):
'''
This function will add, substract, multiplicate and divide the 3 values between them
'''
Sum = Value1+Value2+Value3
Subs = Value1-Value2-Value3
Mult = Value1*Value2*Value3
Div = Value1/Value2/Value3
Pot = Value1**Value2**Value3
print ("add is =", Sum, ",", "substract is =", Subs, ",", "multiplication is =", Mult, ",", "divition is =", Div, ",", "potentiation is =", Pot)
return Sum, Subs, Mult, Div, Pot
#POINT 2
def ShowThreeList (list1, list2, list3):
'''
Introduce 3 lists with the same lenght and program will show you them in screen
if you introduce a shorter or longer list it won't be show
'''
if (len(list1) == len(list2) == len(list3)):
print ('''
''',
list1,
'''
''',
list2,
'''
''',
list3)
else:
print("There is a shorter or longer list")
return list1, list2, list3
#POINT 3
def AreaCalculator (base= 0, alture= 0):
'''
This function will calculate the area of a triangle
'''
area = (base*alture)/2
print (area)
return area
#POINT 4
def ListMaxMinAvr (list1):
'''
this function will show you the highest/lowest number and an average of them
'''
print ("The highest number is:", max(list1))
print ("The lowest number is:", min(list1))
print ("The average is = ", sum(list1)/len(list1))
return None
#POINT 5
def FibSer (Number):
'''
this function will show you the number before a number you choose in fibonacci serie
'''
if (Number==0):
print (1)
elif (Number==1):
print (1)
else:
print ((Number-1)+(Number-2))
| true |
3ee3a689f45d39996349bcd06e07717b89612c9b | YounessTayer/Tk-Assistant | /squirts/scalers/vertical_scale.py | 968 | 4.1875 | 4 | """Vertical scale.
Stand-alone example from Tk Assistant.
Updated March 2021
By Steve Shambles
stevepython.wordpress.com
"""
import tkinter as tk
root = tk.Tk()
root.title('Vertical scale demo')
def set_height(can_vas, height_str):
"""Set scale height."""
height = 21
height = height + 21
height_y2 = height - 30
print(height_str) # Holds current scale pointer.
if height_y2 < 21:
height_y2 = 21
can_vas = tk.Canvas(root,
width=65,
height=50,
bd=0,
highlightthickness=0)
scale = tk.Scale(root,
orient=tk.VERTICAL,
length=284,
from_=0,
to=250,
tickinterval=25,
command=lambda h, c=can_vas: set_height(c, h))
scale.grid(padx=80, sticky='NE')
# Starting point on scale.
scale.set(125)
root.mainloop()
| true |
ea1788af57939ad08460fe6887d6dad31133927d | nieldeokar/LearningAlgorithms | /scripts/chapter3/factorial_45.py | 692 | 4.4375 | 4 | import sys
# This function calculates the factorial of a number passed as command line arg.
# Funtion calls itself Recursively to calculate the factorial.
def fact(x):
if x == 1:
return 1
else:
return x * fact(x-1)
if len(sys.argv[1:]) > 0 :
print fact(int(sys.argv[1]))
else:
print fact(3)
#Suppose you accidentally write a recursive function that runs forever.
#As you saw, your computer allocates memory on the stack for each function call.
#What happens to the stack when your recursive function runs forever?
#
# Ans :
# We get - maximum recursion depth exceeded Error
# To test remove line 7,8,9 and run program. It will run infinitely
# default recursion limit is 1000
| true |
1a199afdc24507162224e97baf643978308ad5ee | rok-povsic/SN-2019-4-predavanje11 | /seznami.py | 495 | 4.1875 | 4 | stevila = [5, 2, 8, 3]
# Izpis vseh števil
print(stevila)
stevila.sort()
print("Števila smo uredili.")
# Izpis urejenih števil
print(stevila)
# Izpis števila na mestu 1
print(stevila[1])
# Izpis števila vseh elementov
print("Število vseh elementov je " + str(len(stevila)))
stevila.append(7)
stevila.remove(3)
del stevila[0]
print("Spremenjen seznam:")
print(stevila)
print("Vsi elementi prek for zanke")
for stevilo in stevila:
print("Sedaj je stevilo enako " + str(stevilo))
| false |
58288ee4d9fe3a03f72dda422f09db48d3560ee7 | mahmoud-taya/OWS-Mastering_python_course | /Files/020.Lists_methods_part_two.py | 716 | 4.3125 | 4 | # ----------------------
# -- Lists methods 2 ---
# ----------------------
# clear()
a = [1, 2, 3, 4]
a.clear()
print(a)
# copy()
b = [1, 2, 3, 4]
c = b.copy()
print(b) # Main list
print(c) # Copied list
b.append(5)
print(b)
print(c) # The copied list doesnot related to the mailn list
# count()
d = [1, 2, 3, 4, 3, 9, 10, 1, 2, 1]
print(d.count(1))
# index()
e = ["Hasan", "Ahmed", "Sayed", "Osama", "Ahmed", "Osama"]
print(e.index("Osama"))
# insert()
f = [1, 2, 3, 4, 5, "a", "b"]
f.insert(0, "test") # Must add the index number of the element you want to add the new element (before) it
f.insert(-1, "test")
print(f)
# pop()
g = [1, 2, 3, 4, 5, "a", "b"]
print(g.pop(-3)) # Print 5 | true |
451ee7d2fa3eaf65d3217399f121771e59da3d53 | mahmoud-taya/OWS-Mastering_python_course | /Files/035.User_input.py | 616 | 4.5 | 4 | # -----------------------------
# ------- User input ----------
# -----------------------------
fName = input('What\'s your first name')
mName = input('What\'s your middle name')
lName = input('What\'s your last name')
fName = fName.strip().capitalize() # Remove spaces around string and make the first character capital
# mName = mName.strip().capitalize() # Remove spaces around string and make the first character capital
lName = lName.strip().capitalize() # Remove spaces around string and make the first character capital
print(f"My name is {fName} {mName.strip().capitalize():.1s} {lName}")
| true |
614393a3c92f31bec5ef5fe763dddf33d2109642 | mahmoud-taya/OWS-Mastering_python_course | /Files/107.OOP_part9_multiple_inheritance_and_methods_overriding.py | 1,997 | 4.5 | 4 | # ---------------------------------------------------------
# -- Object oriented programming => multiple inheritance --
# ---------------------------------------------------------
# class Food: # Base class
#
# def __init__(self, name, price):
#
# self.name = name
#
# self.price = price
#
# print(f"{self.name} Food is created from base class")
#
# def eat(self):
#
# print("Eat method from base class")
#
# class Apple(Food): # Derived class
#
# def __init__(self, name, price, amount):
#
# # Food.__init__(self, name) # Create instance from base class
#
# super().__init__(name, price)
#
# # self.name = name
# # self.price = price + 20 # The new attributes overwrite the base class attributes
#
# self.amount = amount
#
# print(f"{self.name} Apple is created from derived class and price is {self.price} and amount is {amount}")
#
# def get_from_tree(self):
#
# print("Get from tree from derived class")
#
# def eat(self): # This method override the method of the base class
#
# print("Eat method from derived class")
#
# # food_one = Food("Pizza")
#
# food_two = Apple("Pizza", 150, 500)
# food_two.eat()
# food_two.get_from_tree()
# ====================================
class BaseOne:
def __init__(self):
print("Base one")
def func_one(self):
print("One")
class BaseTwo:
def __init__(self):
print("Base Two")
def func_two(self):
print("Two")
class Derived(BaseOne, BaseTwo):
pass
var_one = Derived() # Print Base one because of the order of the inhertance classes
print(Derived.mro()) # Print the order of classes that this class inhertance methods from it
print(var_one.func_one)
print(var_one.func_two)
var_one.func_one()
var_one.func_two()
class Base:
pass
class DerivedOne(Base):
pass
class DerivedTwo(DerivedOne): # Inhertance from Base class two
pass | true |
444c7b1cf363b03c738c59226c0e883952052690 | mahmoud-taya/OWS-Mastering_python_course | /Files/017.Arithmetic_operators.py | 1,009 | 4.1875 | 4 | # ----------------------------
# --- Arithmetic operators ---
# ----------------------------
# [+] Addition
# [-] Subtraction
# [*] Muliplication
# [/] Division
# [%] Modulus
# [**] Exponent
# [//] Floor division
# ----------------------------
# Addition
print(10 + 30) # 40
print(-10 + 20) # 10
print(1 + 2.66) # 3.66
print(1.2 + 1.2) # 2.4
# Subtraction
print(60 - 30) # 30
print(-30 - 20) # -50
print(-30 - -20) # -10
print(5.66 - 3.44) # 2.22
# Muliplication
print(10 * 3) # 30
print(5 + 10 * 100) # 1005
print((5 + 10) * 100) # 1500
# Division
print(100 / 20) # 5.0
print(int(100 / 20)) # 5
# Modulus
print(8 % 2) # 0
print(9 % 2) # 1
print(20 % 5) # 0
print(20 % 5) # 2
# Exponent
print(2 ** 5) # 32
# print(2 * 2 * 2 * 2 * 2) # 32
print(5 ** 4) # 625
# print(5 * 5 * 5 * 5) # 625
# Floor division
print(100 // 20) # 5
# 110 // 20 => no
print(119 // 20) # 5
print(120 // 20) # 6
# 130 // 20 => no
print(139 // 20) # 6
print(140 // 20) # 7
print(130 // 20) | false |
219b179704fc8ca594f7d8f4f3fa0a871b41b541 | mahmoud-taya/OWS-Mastering_python_course | /Assignments/09.Assignment.09.py | 1,357 | 4.125 | 4 | # -------------------------------------------
num1 = int(input("---- Enter num 1 : "))
operation = str(input("Enter operation => + , - , * , / , % : "))
num2 = int(input("---- Enter num 2 : "))
if operation == '+' :
print(num1 + num2)
elif operation == '-' :
print(num1 - num2)
elif operation == '*' :
print(num1 * num2)
elif operation == '/' :
print(num1 / num2)
elif operation == '%' :
print(num1 % num2)
else :
print("Invaliad operation")
# ----------------------------------------
age = 17
print("Good" if age > 16 else "Not good")
# ------------------------------------------
age2 = int(input("Enter your age : "))
months = age2 * 12
weeks = months * 4
days = age2 * 364
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
if age2 > 10 and age2 < 100 :
print(f"{months} months")
print(f"{weeks} weeks")
print(f"{days} days")
print(f"{hours} hours")
print(f"{minutes} minutes")
print(f"{seconds} seconds")
else :
print("No")
# --------------------------------------
country = input("Enter your country : ").strip().capitalize()
countries = ["Egypt", "Syria", "Kuwait", "Jordon"]
discount = 30
price = 100
if country in countries :
print(f"The discount is {discount}")
else :
print(f"The price is {price}")
# ---------------------------------------- | false |
2d0e6df496b19b71b538522adedf5c76876c0c1f | mahmoud-taya/OWS-Mastering_python_course | /Files/015.Strings_formatting_new_way.py | 2,033 | 4.15625 | 4 | # -----------------------------
# Strings formatting ----------
# -----------------------------
name = "hasan"
age = 16
rank = 10
print("My name is: " + name)
# print("My name is: " + name + "and my age is: " + age) # Error => Cannot concatinate string with number
print("My name is : {}" .format("hasan"))
print("My name is : {}" .format(name))
print("My name is : {} and my age is {}" .format(name, age))
print("My name is : {:s} and my age is {:d} and my rank is {:f}" .format(name, age, rank))
# {:s} => String
# {:d} => Number
# {:f} => Float
n = "hasan"
l = "python"
y = 10
print("My name is {} i'm {} developer with {:f} years exp" .format(n, l, y))
# Control floating point number
num = 10
print("My number is {:d}" .format(num))
print("My number is {:f}" .format(num))
print("My number is {:.2f}" .format(num))
# Truncate string
var = "Hasan salah"
print("My name is {:s}" .format(var))
print("My name is {:.5s}" .format(var)) # print 5 elements of the string [ Ha ]
print("My name is {:.11s}" .format(var)) # print 11 elements of the string [ Hasan salah ]
# Format money
money = 578439248394
print("My money is {:d}" .format(money))
print("My money is {:_d}" .format(money))
print("My money is {:,d}" .format(money))
# print("My money is {:&d}" .format(money)) # Wrong
# Rearrange items
a, b, c = "one", "two", "three"
print("hasan {} {} {}".format(a, b, c)) # hasan one two three
print("hasan {1} {2} {0}".format(a, b, c)) # hasan two three one
print("hasan {2} {0} {1}".format(a, b, c)) # hasan tree one two
x, y, z = 10, 20, 30
print("hasan {} {} {}".format(x, y, z)) # hasan 10 20 30
print("hasan {1:d} {2:d} {0:d}".format(x, y, z)) # hasan 20 30 10
print("hasan {2:f} {0:f} {1:f}".format(x, y, z)) # hasan 30 10 20
print("hasan {2:.2f} {0:.4f} {1:.5f}".format(x, y, z)) # hasan 30 10 20
# Format version 3.6 and new versions
myname = "hasan"
myage = 16
print("My name is {myname} and my age is {myage}") # Error
print(f"My name is {myname} and my age is {myage}")
print("=" * 40)
| false |
bdcf527e51bb24a1e4cf620cfc8d024db5e34446 | mahmoud-taya/OWS-Mastering_python_course | /Files/083.Practical_loop_on_many_iterators_with_zip.py | 833 | 4.4375 | 4 | # ----------------------------------------------------
# -- Practical => loop on many iterators with zip() --
# ----------------------------------------------------
# zip() return a zip object cantains all objects
# zip() length is the length of lowest object
# ----------------------------------------------------
list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c", "d"]
tuple1 = ("Man", "Woman", "Girl", "Boy")
dict1 = {"Name" : "Hasan", "Age" : 16, "Country" : "Egypt", "Skill" : "Python"}
for item1, item2, item3, item4 in zip(list1, list2, tuple1, dict1) :
print("List 1 item is => ", item1)
print("List 2 item is => ", item2)
print("Tuple 1 item is => ", item3)
print("Dict 1 key is => ", item4, "value => ", dict1[item4])
zip_list = zip(list1, list2)
print(zip_list)
for item in zip_list :
print(item)
| true |
db034cbbc5d46cbea0eeb0b1591f2851b1f2145d | deliciafernandes/OpenOctober | /SoftwareDev/Python/bin_search.py | 900 | 4.28125 | 4 | #Python program to implement recursive binary search
#Contributed by Puranjay N Potnis
def bin_Search(arr, low, high, x):
if high >= low:
mid = (high+low) // 2
if arr[mid] == x:
#element is the middle element
return mid
elif arr[mid] > x:
#element is smaller than mid value
#check left sub-array
return bin_Search(arr, low, mid-1, x)
else:
#element is larger than mid value
#check right sub-array
return bin_search(arr, mid+1, high, x)
else:
return -1
arr = map(int, input("Enter space separated array: ").split())
x = int(input("Enter a number to be searched: "))
result = bin_Search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
| true |
882dd1fd0eb8fb40c3d412d186f3cb18cf5122cd | Dioni1195/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 738 | 4.34375 | 4 | #!/usr/bin/python3
""" This module contains a function that read n lines of a file """
def number_of_lines(filename=""):
""" Read and return the number of lines """
with open(filename, 'r', encoding='utf-8') as r_file:
return len(r_file.readlines())
def read_lines(filename="", nb_lines=0):
""" Read n lines of a file """
with open(filename, 'r', encoding='utf-8') as r_file:
num_lines = number_of_lines(filename)
if nb_lines <= 0 or nb_lines >= num_lines:
print(r_file.read(), end="")
else:
lines = r_file.readlines()
i = 0
while nb_lines > 0:
print(lines[i], end="")
i += 1
nb_lines -= 1
| true |
07e6ce8bbe95521d8f0a50f49996af731a45755b | LiYifei1218/AP-CSP-I | /Lab02EasterSunday/eastersunday.py | 795 | 4.375 | 4 | """
|-------------------------------------------------------------------------------
| eastersunday.py
|-------------------------------------------------------------------------------
|
| Author: Alwin Tareen
| Created: Sep 10, 2019
|
| This program determines the month and day of Easter.
|
"""
def retrievedate(year):
# Determine the month and day that Easter occurs, given a particular year.
# YOUR CODE HERE
a = year % 19
b = year // 100
c = year % 100
d = b // 4
e = b % 4
g = (8 * b + 13) // 25
h = (19 * a + b - d - g + 15) % 30
j = c // 4
k = c % 4
m = (a + 11 * h) / 319
r = (2 * e + 2 * j - k - h + m + 32) % 7
n = (h - m + r + 90) // 25
p = (h - m + r + n + 19) % 32
return (n, p)
result = retrievedate(2001)
print(result)
| false |
0ebbb0844b4e91e4cc1b5dd4a82d9de2516dfb60 | joel-christian/Starting-out-With-Programming-Logic-and-Design | /3.7 Fat_and_Carb.py | 2,240 | 4.71875 | 5 | #Joel Christian
#A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her
#evaluation, she asks members for the number of fat grams and carbohydrate grams that they
#consumed in a day. Then, she calculates the number of calories that result from the fat, using the
#following formula: Calories from Fat = Fat Grams × 9
#Next, she calculates the number of calories that result from the carbohydrates, using the following
#formula: Calories from Carbs = Carb Grams × 4
#The nutritionist asks you to design a modular program that will make these calculations.
#This program accepts the number of fat and carbohydrates gram consumed,
#calculates the total calories using fat grams,
#calculates the total calories using catbohydrates gram,
#then calculates the total calories from fat and carb calories
#and displays the total calories results.
#Create global constants
FATCAL_MULTIPLIER = 9
CARBCAL_MULTIPLIER = 4
#Create and initialize a global variable to store the total calories
totalCalories = 0
def main():
#Get the number of fat grams
inputFat = float(input("Enter the number of fat grams consumed: "))
#Get the number of carbohydrates grams
inputCarb = float(input("enter the number of carbohydrates grams consumed: "))
#Calculates and displays the number of fat calories
setFat(inputFat)
#Calculates and displays the number of carb calories
setCarb(inputCarb)
#Displays the total calories from both fat and carbs
print("The total number of calories consumed is: ", totalCalories)
#The setFat function calculates and displayes the total number of fat calories
#and adds it to the total calories
def setFat(totalFat):
fatCal = totalFat * FATCAL_MULTIPLIER
global totalCalories
totalCalories = totalCalories + fatCal
print("The total number of Fat Calories is:", fatCal)
#The setCarb function calculates and displays the total number of carbohydrates calories
#and adds it to the total calories
def setCarb(totalFat):
carbCal = totalFat * CARBCAL_MULTIPLIER
global totalCalories
totalCalories = totalCalories + carbCal
print("The total number of Carbohydrates Calories is:", carbCal)
#Call the main function
main()
| true |
b3cce748d098b011055d2ee09e144e60b2867ed2 | tazman555/python-examples | /classes.py | 2,583 | 4.53125 | 5 | #!/bin/python
# Classes use keyword class
# class Person(object):
# print("person called")
# pass
# type(Person)
# print(type(Person) == type(int))
# nobody = Person()
# print(type(nobody))
# class Person(object):
# species = " Homo Sapien"
# def talk(self):
# return "Hello there, how are you?"
# Example of class with initialisation name. This involves adding name to each instance after class creation a btter way is to _init_ shown below
# nobody = Person()
# print('0', nobody.species)
# print('1', nobody.talk())
# somebody = Person()
# somebody.species= 'Home inernetus'
# somebody.name='Mark'
# print('2', nobody.species)
# Person.species = 'Unknown1'
# print('3', nobody.species)
# print('4', somebody.species)
# Person.name = "Unknown2"
# print('5', nobody.species)
# print('6', somebody.species)
# del somebody.name
# print('7', somebody.name)
# Class using _init_ to initialise class
# class Person(object):
# species = 'Homo Sapiens'
# def __init__(self, name='Unknown', age=18):
# self.name = name
# self.age = age
# def talk(self):
# return 'Hello my name is {} age {}'.format(self.name, self.age)
# mark = Person('Mark', age=18)
# generic_voter = Person()
# generic_worker = Person(age=41)
# print(generic_worker.age)
# print(generic_voter.age)
# print(mark.talk())
# print(generic_worker.name)
# # In Python, it is not unusual to acces attributes directly
# mark.favourite_color = "green"
# print(generic_worker)
# del generic_worker.name
# # print(generic_worker.name)
# def person_str(self):
# return "Name: {0}, Age {1}".format(self.name, self.age)
# Person._str_ = person_str
# def person_repr(self):
# return "Name: {0}, Age {1}".format(self.name, self.age)
# Person._repr_ = person_repr
# print(mark)
# mark
# def person_eq(self, other):
# return self.age == other.age
# Person._eq_ = person_eq
# bob = Person("Bob", 33)
# bob == mark
class Person(object):
species = "Home sapiens"
def __init__(self, name="Unknown", age=18):
self.name = name
self.age = age
def talk(self):
return "Hello my name is {}.".format(self.name)
def __str__(self):
return "Name: {0}, age: {1}".format(self.name, self.age)
def __repr__(self):
return "person('{0}', '{1}')".format(self.name, self.age)
def __eq__(self, other):
return self.age == other.age
nobody = Person()
bob = Person('Bob', 18)
taz = Person('Taz', 51)
print(nobody.talk())
print(nobody.__str__())
print(nobody.__repr__())
print(nobody.__eq__(bob)) | true |
01623e4e549fd5463fed598b02fbd822e7f751f7 | tazman555/python-examples | /inheritance.py | 1,705 | 4.5625 | 5 | #!/bin/python
# Inheritance
# The every class inherits the object class fro example the Person inherits from ( sublclass of) the object class
class Person(object):
species = "Home sapiens"
def __init__(self, name="Unknown", age=18):
self.name = name
self.age = age
def talk(self):
return "Hello my name is {}.".format(self.name)
def __str__(self):
return "Name: {0}, age: {1}".format(self.name, self.age)
def __repr__(self):
return "person('{0}', '{1}')".format(self.name, self.age)
def __eq__(self, other):
return self.age == other.age
class Student(Person):
bedtime = 'Midnight'
def do_homework(self):
import time
print("I need to work.")
time.sleep(5)
print("Did I just fall sleep")
tyler = Student("Tyler", 19)
tyler.species
tyler.talk()
tyler.do_homework()
# To override behavior from the parent class creat a class function with the same name and super function
class Employee(Person):
def __init__(self, name, age, employer):
super(Employee, self).__init__(name, age)
self.employer = employer
def talk(self):
talk_str = super(Employee, self).talk()
return talk_str + " I work for {}".format(self.employer)
fred = Employee("Fred Flintsone", 55, "Slate Rock and Gravel Company")
print(fred.talk())
#python Polymorphism is a class with more than one ancestor, complicated
class StudentEmployee(Student, Employee):
pass
ann = StudentEmployee("Ann", 58, "Family Services")
print(ann.talk())
# Polymorphism means that different types respond to the same function
# bill = StudentEmployee("bill", 20) # does not work requires employee. As different t | true |
08510935a4e49188855457ec9d07a7b31d4af1fb | JadenTurnbull/Crash-Course-Python | /chap07/TryItYourself_p185.py | 998 | 4.15625 | 4 | #7-4
topping = ''
while True:
prompt = 'What toppings do you want? '
topping = input(prompt)
if topping == 'quit':
break
else:
print(f"{topping} has been added on your pizza!")
#7-5
age = ''
prompt = "How old are you?"
age = int(input(prompt))
if age <= 3:
print("Ticket is free")
elif (age > 3) and (age < 12):
print("ticket is $10")
elif (age >= 12):
print("ticket is $12")
#7-6
topping = ''
while True:
prompt = 'What toppings do you want? '
topping = input(prompt)
if topping == 'quit':
break
else:
print(f"{topping} has been added on your pizza!")
topping = ''
active = True
while active:
prompt = 'What toppings do you want? '
topping = input(prompt)
if topping == 'quit':
active = False
else:
print(f"{topping} has been added on your pizza!")
topping = ''
active = True
while topping != 'quit':
prompt = 'What toppings do you want? '
topping = input(prompt)
print(f"{topping} has been added on your pizza!")
#7-7
x = 1
while x <= 5:
print(x)
| true |
fdf74406c04a59ca4e4a10e29af647ad53d9c25d | rafalwilk4ti1/Projekt2020 | /TheArtOfDoing-basic/Basic Data Types/Miles per Hours Hours Conversion App.py | 313 | 4.15625 | 4 | # Basic Data types Challenge 2: Miles Per Hour Conversion App
print("Hello, this is The MIles Per Hour Conversion App")
speed_mls = float(input("Your speed in miles per hour: "))
speed_mps = speed_mls*0.4474
speed_mps = round(speed_mps,2)
print("Your speed in meters per second is " + str(speed_mps) + ".")
| true |
a81fa97e70e0965f1cd3e67b3532a71195eb1b08 | rafalwilk4ti1/Projekt2020 | /TheArtOfDoing-basic/While Loops/Prime Number App.py | 2,926 | 4.125 | 4 | import time
import datetime
import random
# While Loops Challenge 28: Prime Number App
print("Welcome to The Prime Number App")
flag = True
while flag:
print("\nEnter 1 to determine if a specific number is prime.")
print("Enter 2 to determine all prime numbers within a set range.")
choice = input("\nEnter your choice 1 or 2: ")
if choice=="1":
number = int(input("\nEnter a number to determine if it is prime or not: "))
if number%number==0 and number%1==0:
print(str(number) +" is prime")
prime_status = True
choice_again = input("Would you like to run the program again(y/n):")
if choice_again.startswith("y"):
continue
elif choice_again.startswith("n"):
print("Thank you for using the program. Have a nice day ")
break
else:
prime_status = False
print(str(number)+"is not prime! ")
choice_again = input("Would you like to run the program again(y/n):" )
if choice_again.startswith("y"):
print("YES")
continue
elif choice_again.startswith("n"):
print("Thank you for using the program. Have a nice day ")
break
elif choice == "2":
rang_1 = int(input("Enter the lower bound of your range: "))
rang_2 = int(input("Enter the upper bound of your range: "))
primes = []
start_time = time.time()
for num in range(rang_1,rang_2+1):
if num > 1:
prime_status = True
for i in range(2,num):
if num % i == 0:
prime_status = False
break
else:
prime_status = False
if prime_status:
primes.append(num)
end_time = time.time()
delta_time = round(start_time - end_time , 6)
for nume in primes:
print(nume)
print("Calculations took a "+str(delta_time)+" total of seconds. ")
print("The following numbers between " + str(rang_1) + " and " + str(rang_2) + " are prime")
print("Press enter to continue")
input()
choice = input("Would you like to run the program again (y/n): ")
if choice.startswith("y"):
continue
elif choice.startswith("n"):
print("Thank you for using The Program. Have a nice day.")
flag = False
else:
print("This is not a valid option.")
choice = input("Would you like run the program again (y/n): ")
if choice.startswith("y"):
continue
elif choice.startswith("n"):
print("\nThank you for using the program. Have a nice day. ")
flag = False
| true |
91c4f448a91cc5cd2733e618fef7d7c5d99f7f4a | nanasson6928/coding-for-class | /week-01-python/03-data-type-2.py | 1,252 | 4.3125 | 4 | # 목록 list, tuple
# 사전 dict - dictionary
# 집합 set
list []
print("list")
list_a = [1,2,3]
print(list_a)
print(type([1,2,3]))
# index는 0부터 시작한다.
print(list_a[0])
print(list_a[1])
print(list_a[2])
# # slice (리스트를 자름)
print(list_a[0:1])
print(list_a[0:2])
#
list_a.append(4)
print(list_a)
list_a.remove(2)
print(list_a)
list_a.clear()
print(list_a)
# tuple (1,)
print("tuple")
tuple_a = (1,2,3)
print(tuple_a)
print(type((tuple_a)))
# tuple_a.append(4)은 실행 안됨
# tuple은 한 번 생성 후 내부 값 변경 불가
# dict (map) {}
# key & value : 키와 그를 설명하는 값으로 분류
dict_a = {
"apple" : "a type of fruits",
"pen" : "a thing to write"}
print(dict_a)
print(dict_a["apple"]) # dict_a의 apple의 값을 알려달라
# edit value
dict_a["pen"] = "something to write"
print(dict_a)
# set set([])
# 일종의 집합
# list, tuple, dict과 달리 특징 없음
set_a = set([1,2,3])
set_b = set([2,4,6])
print(set_a)
print(set_b)
# 집합 - 교집합, 합집합, 차집합, 여집합
# set은 중복을 제거해준다.
# (list는 값은 값을 중복해서 넣을 수 있다.)
# 교집합
print(set_a & set_b)
# 합집합
print(set_a | set_b)
# 차집합
print(set_a - set_b)
| false |
c7fd582d48f542e5772198874d2cc752a848bf98 | saurabh59/coffee-machine | /stage4.py | 1,606 | 4.15625 | 4 | print("""The coffee machine has:
400 of water
540 of milk
120 of coffee beans
9 of disposable cups
550 of money""")
print()
print("Write action (buy, fill, take):")
s = input()
if s == "buy":
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:")
coffee_option = int(input())
print()
if coffee_option == 1:
print("""The coffee machine has:
150 of water
540 of milk
104 of coffee beans
8 of disposable cups
554 of money""")
elif coffee_option == 2:
print("""The coffee machine has:
50 of water
465 of milk
100 of coffee beans
8 of disposable cups
557 of money""")
elif coffee_option == 3:
print("""The coffee machine has:
200 of water
440 of milk
108 of coffee beans
8 of disposable cups
556 of money""")
elif s == "fill":
print("Write how many ml of water do you want to add:")
water_fill = int(input())
print("Write how many ml of milk do you want to add:")
milk_fill = int(input())
print("Write how many grams of coffee beans do you want to add:")
coffee_fill = int(input())
print("Write how many disposable cups of coffee do you want to add:")
cups_fill = int(input())
print()
print("The coffee machine has:")
print(400 + water_fill, "of water")
print(540 + milk_fill, "of milk")
print(120 + coffee_fill, "of coffee beans")
print(9 + cups_fill, "of disposable cups")
print("550 of money")
elif s == "take":
print("I gave you $550")
print()
print("""The coffee machine has:
400 of water
540 of milk
120 of coffee beans
9 of disposable cups
0 of money""")
| true |
751e6b1f5e42fa639f2b53b0d2f71872136779be | ericchou-python/programming-python | /ch16/ex16_1.py | 287 | 4.125 | 4 | #!/usr/bin/env python
class Time(object):
"""Represents the time of day.
attributes: hour, minute, second
"""
def print_time(x):
print("%.2d:%.2d:%.2d" % (x.hour, x.minute, x.second))
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
print_time(time)
| true |
be2a228d45b7368fb260d9128d272493c7493fbb | ericchou-python/programming-python | /ch14/1 | 839 | 4.15625 | 4 | #!/usr/bin/env python
import os
# example from http://www.doughellmann.com/PyMOTW/os/index.html#module-os
root = raw_input("Enter the root of the dirctory you want to walk> ")
#The function walk() traverses a directory recursively and for each directory
#generates a tuple containing the directory path, any immediate sub-directories
#of that path, and the names of any files in that directory.
for dir_name, sub_dirs, files in os.walk(root):
print '\n', dir_name
# list comprehension with subdirectories
sub_dirs = ['%s/' % n for n in sub_dirs ]
# Mix the directory contents together
contents = sub_dirs + files
contents.sort()
for c in contents:
print '\t%s' % c
# Another way of looking
for dir_name, sub_dirs, files in os.walk(root):
print dir_name
print sub_dirs
print files
| true |
ce2eee88f346f0962c1a31c7238fd26f3854745c | ericchou-python/programming-python | /ch5/ex5_5.py | 640 | 4.15625 | 4 | #!/usr/bin/env python
from swampy.TurtleWorld import *
def draw(t, length, n):
if n == 0:
return
angle = 50
fd(t, length*n)
lt(t, angle)
draw(t, length, n-1)
rt(t, 2*angle)
draw(t, length, n-1)
lt(t, angle)
bk(t, length*n)
world = TurtleWorld()
bob = Turtle()
bob.delay = 0.01
#fd and bk for forward and backward
#lt and rt for left and right turns.
#each Turtle is holding a pen, either down or up; if the pen is down,
#the Turtle leaves a trail when it moves.
#The functions pu and pd stand for pen up and pen down.
# Execution of different functions
draw(bob, 2, 5)
wait_for_user()
| true |
bf8ae77674f27373c6cf0778d6da3c7fd777942f | aronnax77/python_uploads | /insertion_sort.py | 769 | 4.125 | 4 | """ Author: Richard Myatt
Date: 15 February 2018
The function below represents an implementation of the 'insertion sort'
algorithm. This is demonstrated with the list [33, 20, 12, 31, 2, 67]
but should work with any other list.
"""
def insertionSort(l):
"""
An implementation of insertion sort
"""
result = l[:]
lengthData = len(result)
start = 1
while start <= lengthData - 1:
if result[start] < result[start - 1]:
value = result.pop(start)
# find insertion point
for i in range(start):
if result[i] > value:
result.insert(i, value)
break
start += 1
return result
print(insertionSort([33, 20, 12, 31, 2, 67]))
| true |
a938e1caa6d4b423c0baf8a21cb60b2f4b4a5d9f | aronnax77/python_uploads | /alg#015_belong.py | 1,509 | 4.125 | 4 | """
belong.py
Author: Richard Myatt
Date: 21 January 2018
This is an exercise which mirrors a question set for JS. Return the lowest
index at which a value (second argument) should be inserted into an array
(first argument) once it has been sorted. The returned value should be a number.
For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater
than 1 (index 0), but less than 2 (index 1).
Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has
been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and
greater than 5 (index 1).
Test cases:
getIndexToIns([10, 20, 30, 40, 50], 35) should return 3.
getIndexToIns([10, 20, 30, 40, 50], 30) should return 2.
getIndexToIns([40, 60], 50) should return 1.
getIndexToIns([3, 10, 5], 3) should return 0.
getIndexToIns([5, 3, 20, 3], 5) should return 2.
getIndexToIns([2, 20, 10], 19) should return 2.
getIndexToIns([2, 5, 10], 15) should return 3.
Test case 2 of the above is used in the code below. Please feel free to substitute
any of the other test cases or one of your own.
"""
def getIndexToIns(arr, num):
arrCopy = arr
arrCopy.sort()
index = 0
if num <= arrCopy[index]:
return 0
elif num > arrCopy[len(arrCopy) - 1]:
return len(arrCopy)
while index < len(arrCopy) - 1:
if num > arrCopy[index] and num <= arrCopy[index + 1]:
return index + 1
else:
index += 1
print(getIndexToIns([10, 20, 30, 40, 50], 30))
| true |
b8d17ac00051e667f9b7d7ff23b6d676b7b9ed7f | aronnax77/python_uploads | /permutations.py | 1,642 | 4.40625 | 4 | """
Author: Richard Myatt
Date: 28 January 2018
The code below provides a function 'permutations(str)' which will return a list
of the permutations of the letters in the string provided as an argument to the
function. If there are n letters in the string then the number of permutations
is given by n! so that for strings in excess of four characters the list becomes
large.
The example below returns a list of the permutations of the string 'abc' and
returns ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'].
Please feel free to substiture any other string of your choosing.
"""
# function which will return the permutations of the string 'str'. Please note
# that the startIndex should be left at its default value.
def permutations(str, startIndex = 0):
result = []
i = startIndex
if startIndex == len(str) - 1:
result.append(str)
return result
else:
while(i < len(str)):
newStr = swap(str, startIndex, i)
for each in permutations(newStr, startIndex + 1):
result.append(each)
str = swap(str, startIndex, i)
i += 1
return result
# swap is a helper function for the function peremutations and swaps the two
# characters of str whose indecies are given by first and second. If both
# indecies are the same str is returned in its original form
def swap(str, first, second):
if first == second:
return str
else:
tempStr = list(str)
temp = tempStr[first]
tempStr[first] = tempStr[second]
tempStr[second] = temp
return ''.join(tempStr)
print(permutations('abc'))
| true |
9e2406e2f1b7a8c3af069c7f06b5fcaee1bc44d6 | AlexRodriguezZA/PILAS---Ejercicios | /Ejer14.py | 911 | 4.125 | 4 | from pila import Pila
#Realizar un algoritmo que permita ingresar elementos en una pila, y que estos queden ordenados de forma creciente.
#Solo puede utilizar una pila auxiliar como estructura extra, no se pueden utilizar métodos de ordenamiento.
pila = Pila()
pilaAux = Pila()
for i in range(0,6):
numero = int(input("Ingrese un numero: "))
if pila.pila_vacia():
pila.apilar(numero)
else:
if numero>=pila.elemento_cima():
pila.apilar(numero)
else:
while (not pila.pila_vacia()) and (pila.elemento_cima() > numero):
x = pila.desapilar()
pilaAux.apilar(x)
pila.apilar(numero)
while not pilaAux.pila_vacia():
z = pilaAux.desapilar()
pila.apilar(z)
#Mostramos los elementos
while not pila.pila_vacia():
y = pila.desapilar()
print(y)
| false |
98c417a0ecc678f946318033eb6a58bf5ae952cd | annewstine/AutomateTheBoringStuff | /madLibs.py | 1,490 | 4.5 | 4 | #! python3
# Creates a Mad Libs program that reads in text files and lets the user add
# their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
# appears in the text file.
import re
def madLibs(ADJECTIVE, NOUN, VERB, NOUN2):
# TODO: write and open starter text file
madLibsFile = open('madLibs.txt', 'w')
madLibsFile.write('The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.')
madLibsFile.close()
madLibsFile = open('madLibs.txt')
content = madLibsFile.read()
madLibsFile.close()
#print(content) #use this line to test
# TODO: Substitute user text for words in text file and print
NOUNregex = re.compile(r'NOUN')
newContent = NOUNregex.sub(NOUN, content, 1)
ADJregex = re.compile(r'ADJECTIVE')
newContent = ADJregex.sub(ADJECTIVE, newContent, 1)
VERBregex = re.compile(r'VERB')
newContent = VERBregex.sub(VERB, newContent, 1)
newContent = NOUNregex.sub(NOUN2, newContent, 1)
print(newContent)
# TODO: Save output as text file
outputFile = open('madLibsOutput.txt', 'w')
outputFile.write(newContent)
outputFile.close()
#Collect user input
print('Enter an ADJECTIVE.')
ADJECTIVE = input()
print('Enter a NOUN.')
NOUN = input()
print('Enter a VERB.')
VERB = input()
print('Enter another NOUN.')
NOUN2 = input()
#Run the program based on user input
madLibs(ADJECTIVE, NOUN, VERB, NOUN2)
| true |
667cdc6ed38ca08ed873e3616d4ecf9f67f0778e | annewstine/AutomateTheBoringStuff | /printTable.py | 782 | 4.3125 | 4 | """Write a function named printTable() that takes a list of lists of strings and displays it in a
well-organized table with each column right-justified. Assume that all the inner lists will
contain the same number of strings."""
tableData = [['apples', 'oranges', 'cherries', 'banana'],['Alice', 'Bob', 'Carol', 'David'],['dogs', 'cats', 'moose', 'goose']]
def printTable(tableData):
colWidths = [0] * len(tableData)
#columns = len(tableData)
# rows = len(tableData[0])
x = max(tableData, key = len)
longest = max(x, key = len)
global rowWidth
rowWidth = len(longest)
for y in range(len(tableData[0])):
for x in range(len(tableData)):
print(tableData[x][y].rjust(rowWidth, ' '), end=' ')
print()
printTable(tableData)
| true |
f4f6d46d8f091ea9be994a1456f5280bbc488320 | ThomasTanghj/ds-class-intro | /python_basics/class02/exercise_6.py | 1,844 | 4.21875 | 4 | '''
Edit this file to complete Exercise 6
'''
def calculation(a, b):
'''
Write a function calculation() such that it can accept two variables
and calculate the addition and subtraction of it.
It must return both addition and subtraction in a single return call
Expected output:
res = calculation(40, 10)
print(res)
>>> (50, 30)
Arguments:
a: first number
b: second number
Returns:
sum: sum of two numbers
diff: difference of two numbers
'''
# code up your solution here
def triangle_lambda():
'''
Return a lambda object that takes in a base and height of triangle
and computes the area.
Arguments:
None
Returns:
lambda_triangle_area: the lambda
'''
def sort_words(hyphen_str):
'''
Write a Python program that accepts a hyphen-separated sequence of words
as input, and prints the words in a hyphen-separated sequence after
sorting them alphabetically.
Expected output:
sort_words('green-red-yellow-black-white')
>>> 'black-green-red-white-yellow'
Arguments:
hyphen_str: input string separated by hyphen
Returns:
sorted_str: string in a hyphen-separated sequence after
sorting them alphabetically
'''
# code up your solution here
def perfect_number():
'''
Write a Python function to check whether a number is perfect or not.
A perfect number is a positive integer that is equal to the sum of
its proper positive divisors. Equivalently, a perfect number is a number
that is half the sum of all of its positive divisors (including itself).
Example: 6 is a perfect number as 1+2+3=6. Also by the second definition,
(1+2+3+6)/2=6. Next perfect number is 28=1+2+4+7+14. Next two perfect
numbers are 496 and 8128.
Argument:
number: number to check
Returns:
perfect: boolean, True if number is perfect
'''
# code up your answer here
if __name__ == '__main__':
pass | true |
549b90bdf284fd8ed5d8692485cefc4449e12d8d | ParisRohan/Python_Projects | /translation.py | 255 | 4.15625 | 4 | def translate(phrase):
result=""
for alphabet in phrase:
if alphabet in "AEIOUaeiou":
result+="$"
else:
result+=alphabet
return result
phrase=input("Please enter a phrase: ")
print(translate(phrase))
| true |
079d558de95f4650e766e308d04b68f86c1a62fc | ParisRohan/Python_Projects | /max_occurrence.py | 483 | 4.28125 | 4 | #Program to print maximum occurrence of a character in an input string along with its count
def most_occurrence(string_ip):
count={}
max_count=0
max_item=None
for i in string_ip:
if i not in count:
count[i]=1
else:
count[i]+=1
if count[i]>max_count:
max_count=count[i]
max_item=i
return max_item,max_count
string_ip=input("Enter a string")
print(most_occurrence(string_ip)) | true |
0cc2433f0fe85d6fc1e00d67927110f33ab0fe74 | ParisRohan/Python_Projects | /TUT_importfn/findmax.py | 256 | 4.125 | 4 | import utilityfn
Number=[] #get user input for list
n=int(input("Enter total number of elements within the list: "))
for i in range(0,n):
user_ip=int(input(f"Enter number {i}: "))
Number.append(user_ip)
print(utilityfn.find_max(Number)) | true |
cb6522d8dbe40df1fc115a9fc9fb94fb162bff7f | KajalSund/Basics_python | /in_and_iterations.py | 957 | 4.125 | 4 | #in keyword and iteration in dictioanry
user_info = {
'name' : 'Daljit',
'age' : 18,
'fav_sport' : ['basketball', 'vollyball'],
'fav_tune' : ['morning', 'bird charm']
}
#check if key exist in dictionary
# if 'name' in user_info:
# print("present")
# else:
# print("not present")
#check if value exist in dictionary--->values method
# if 20 in user_info.values():
# print('present')
# else:
# print('not present')
#loop in dictionary
# for i in user_info:
# print(user_info[i])
# user_info_values = user_info.values()
# print(user_info_values)
# print(type(user_info_values))
# user_info_keys = user_info.keys()
# print(user_info_keys)
# print(type(user_info_keys))
#items method
user_info_items = user_info.items()
print(user_info_items)
print(type(user_info_items))
for key, value in user_info.items():
print(f"key is {key} and value is {value}") | false |
77c031507de4a7f1850692a57126eb3bafd7148a | KajalSund/Basics_python | /functions.py | 638 | 4.125 | 4 | # def is_even(num):
# if num%2 == 0:
# return True
# return False
# n = int(input("enter any number "))
# print(is_even(n))
# #greater num
# def greater(num1, num2):
# if num1 > num2:
# return num1
# elif num2 > num1:
# return num2
# else:
# print("both are equal")
# n1 = int(input("enter number 1: "))
# n2 = int(input("enter number 2: "))
# print(greater(n1, n2))
def greater(a, b):
if a > b:
return a
return b
def greatest(a, b, c):
bigger = greater(a, b)
return greater(bigger, c)
print(greatest(12,300,44)) | false |
71c8673ab3d39ce5b6dbabfbf95e0af0f69a8601 | programmer-anvesh/Hacktoberfest2021 | /gridTraveler.py | 833 | 4.1875 | 4 | #The problem is to count number of possible possible paths from top left to bottom right in m x n grid where you can either move right or move down.
#The problem falls under category of Dynamic Programming
#Time Complexity: O(n^2) # using the two loops
#Space Complexity: O(n^2) # utilizing the table
'''
Solution submitted by: Ansh Gupta (@ansh422)
Date: 2/10/2021
'''
def gridTraveler(m,n):
table=[[0 for _ in range(n+1)] for _ in range(m+1)]
table[1][1]=1
for i in range(m+1):
for j in range(n+1):
if j+1 <= n:
table[i][j+1]+=table[i][j]
if i+1 <= m:
table[i+1][j]+=table[i][j]
return table[m][n]
if __name__ == "__main__":
m,n=map(int,input().split()) # input here storing the dimensions of grid
ans=gridTraveler(m,n)
print(ans)
| true |
05a31a3098e67d7c27c9ed0aafc44decce991684 | tigervanilla/Daily_Coding_Problem | /37.py | 798 | 4.46875 | 4 | '''
This problem was asked by Google
The power set of a set is the set of all its subsets.
Write a function that, given a set, generates its power set
For example, given the set {1, 2, 3},
it should return { {}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3} }
'''
def powerSet(arr, ss):
''' Recursive solution '''
if not arr:
print('{' + ss + ' }', end=', ')
return
powerSet(arr[1:], ss)
powerSet(arr[1:], ss + ' ' + str(arr[0]))
def powerSet2(arr):
''' Iterative solution '''
n = len(arr)
for i in range(2**n):
subset = '{'
for j in range(n):
if i & (1 << j) != 0:
subset = subset + ' ' + str(arr[n-1-j])
subset += ' }'
print(subset, end=' ')
# Driver code:
powerSet2([1, 2, 3])
print()
| true |
2b0377ffaf23d92019e46da4c339880e9dade47d | tigervanilla/Daily_Coding_Problem | /46.py | 1,620 | 4.15625 | 4 | '''
This problem was asked by Amazon.
Given a string, find the longest palindromic contiguous substring.
If there are more than one with the maximum length, return any one.
For example, the longest palindromic substring of "aabcdcb" is "bcdcb".
The longest palindromic substring of "bananas" is "anana".
'''
def longestPalindromSubstring(S):
n = len(S)
# matrix[i][j] is True iff S[i..j] is palindrom
matrix = [[False]*n for i in range(n)]
# Single character is a pallindrom
for i in range(n):
matrix[i][i] = True
longestPalindrom = S[0]
longestPalindromLength = 1
# Check substrings of length = 2
for i in range(n-1):
if S[i] == S[i+1]:
matrix[i][i+1] = True
longestPalindrom = S[i:i+2]
longestPalindromLength = 2
else:
matrix[i][i+1] = False
# Check substrings of length > 2
for k in range(3, n+1): # checking substrings of length k ie 3 to n
for i in range(n-k+1):
for j in range(i+k-1, n):
if S[i] == S[j] and matrix[i+1][j-1]:
matrix[i][j] = True
if k > longestPalindromLength:
longestPalindrom = S[i:j+1]
longestPalindromLength = k
else:
matrix[i][j] = False
return (longestPalindromLength, longestPalindrom)
# Driver Code:
testcases = ['GPFKFUG', 'aabcdcb', 'banana']
for tc in testcases:
print(longestPalindromSubstring(tc))
'''
Reference:
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
'''
| true |
4be9795e523fabba1d472bbaabd6f6b6c76dab4e | maiareynolds/Unit-4 | /stringIntersect.py | 314 | 4.125 | 4 | #Maia Reynolds
#3/30/18
#stringIntersect.py - letters in both words
def stringIntersect(word1,word2):
final=""
word1=word1.lower()
word2=word2.lower()
for ch in word1:
if ch in word2 and ch not in final:
final+=ch
return final
print(stringIntersect("Mississippi","Pennsylvania")) | true |
f948f3a0d8bdfa5a446a8c93c0bae92f5d289e1e | MonicaDianeC/loan_calculator_program_projects | /Constantino_ProgProj_2.py | 2,923 | 4.53125 | 5 | # Name: Monica-Diane Constantino
# Date: 10/6/20
# Description: Loan Calculator 2.0 Programming Project #2
# TO DO:
# 1. create a function that asks the user for a loan amount
# 2. create a function that asks the user for the term (in months) of the loan
# 3. create a function that determines the interest based on loan amount and monthly term
# 4. create a function that calculates the monthly payment
# 5. in main(), call and initialize these functions and call calc_monthly_pay() from loan_calculator module
# format and print these values
# run program at least 21 times for error checking
# functions
# gets the loan amount
def get_loan():
loan = float(input("Please enter a loan amount that is at least $500: $"))
while loan < 500:
loan = float(input("Invalid amount. \nPlease re-enter a loan amount that is at least $500: $"))
return loan
# get the monthly term
def get_term():
term = int(input("Please enter the monthly term (6 to 48 months): "))
while term < 6 or term > 48:
term = int(input("Invalid monthly term. \nPlease re-enter a monthly term that is between 6 to 48 months: "))
return term
# determine interest rate
def get_interest(amount, months):
if amount >= 500 and amount <= 2500:
if months >= 6 and months <= 12:
rate = 8
elif months >= 13 and months <= 36:
rate = 10
elif months >= 37 and months <= 48:
rate = 12
elif amount >= 2501 and amount <= 10000:
if months >= 6 and months <= 12:
rate = 7
elif months >= 13 and months <= 36:
rate = 8
elif months >= 37 and months <= 48:
rate = 6
elif amount >= 10001:
if months >= 6 and months <= 12:
rate = 5
elif months >= 13 and months <= 36:
rate = 6
elif months >= 37 and months <= 48:
rate = 7
return rate
# calculate the monthly payment
def calc_monthly_pay(whole_num_rate, amount_of_loan, num_months):
rate_applied = whole_num_rate / 1200
calculation = (rate_applied * amount_of_loan) / (1 - ((1 + rate_applied) ** -num_months))
return calculation
# main function
def main():
# loan calculation values
loan_amount = get_loan()
monthly_term = get_term()
interest_rate = get_interest(loan_amount, monthly_term)
monthly_payment = calc_monthly_pay(interest_rate, loan_amount, monthly_term)
# format headings and data
column_list = ["Loan Amount", "Monthly Term", "Interest Rate", "Monthly Payment"]
for headings in column_list:
print(headings, end = "\t")
message = "${:5.2f} \t {} months\t{:>5}%\t\t${:5.2f}".format(loan_amount, monthly_term, interest_rate, monthly_payment)
print('\n',message)
print(" ")
main()
| true |
72055db67ff15ed56ae6323cd580211062751fc4 | s-macias/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,493 | 4.3125 | 4 | #!/usr/bin/python3
"""function that divides all elements of a matrix.
"""
def matrix_divided(matrix, div):
"""function that divides all elements of a matrix
Args:
matrix: list of integers or floats
Raises:
TypeError exception
Message matrix must be a matrix (list of lists) of integers/floats
TypeError exception
Message Each row of the matrix must have the same size
TypeError exception
Message div must be a number
ZeroDivisionError exception
Message division by zero
TypeError
Message matrix must be a matrix (array of arrays of integers/floats)
Returns:
new_matrix
"""
if isinstance(div, (int, float)) is False:
raise TypeError("div must be a number")
elif div == 0:
raise ZeroDivisionError("division by zero")
for i in matrix:
if type(i) is not list:
raise TypeError("matrix must be a matrix (list of lists) of" +
" integers/floats")
elif len(matrix[0]) != len(i) or len(matrix[0] == 0):
raise TypeError("Each row of the matrix must have the same size")
for j in i:
if isinstance(j, (int, float)) is False:
raise TypeError("matrix must be a matrix (list of lists) of" +
" integers/floats")
new_matrix = []
new_matrix = [[round((j/div), 2) for j in i] for i in matrix]
return new_matrix
| true |
d6521a0058b67c2854971945b5ec863fbc081576 | s-macias/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 338 | 4.4375 | 4 | #!/usr/bin/python3
"""reads a text file (UTF8) and prints it to stdout"""
def read_file(filename=""):
"""function that reads a text file (UTF8) and prints it to stdout.
Args:
filename: file to read
"""
with open(filename, encoding="utf-8") as MyFile:
for line in MyFile:
print(line, end="")
| true |
4ba5cc8871f3a016d0ef250c50fcfa6c1bdb421d | s-macias/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,708 | 4.59375 | 5 | #!/usr/bin/python3
"""Write a class Square that defines a square"""
class Square:
"""optional initialization with size=0 which a positive int"""
def __init__(self, size=0, position=(0,0)):
"""initilializes with size 0 and position at (0,0)"""
self._size = size
self._position = position
@property
def size(self):
"""method to retrieve size"""
return size
@size.setter
def size(self, value):
"""method to set size"""
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self._size = value
@position
def position(self):
"""method that returns position"""
return position
@position.setter
def position(self, value):
"""method to set position"""
if type(value) is not tuple:
raise TypeError("position must be a tuple of 2 positive integers")
elif type(value[0]) is not int or type(value[1]) is not int:
raise TypeError("position must be a tuple of 2 positive integers")
elif value[0] < 0 or value[1] < 0:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self._position = value
def area(self):
"""method that returns area of the square"""
return (self._size**2)
def my_print(self):
"""method that prints a square"""
if size is 0:
print()
for i in range(value[0], value[0] + size):
for j in range(value[1], value[1] + size):
print("#", end="")
print()
| true |
f95a48afcc2e7cbcd9873a6888df2b8ca7512011 | PixonFrost/20-Python | /Unit Converter.py | 1,451 | 4.28125 | 4 | # Converts various units between one another. The user enters the type of unit being entered, the type
# of unit they want to convert to and then the value. The program will then make the conversion
#* Celcius to F = * 9 / 5 + 32
#* F to C = - 32 * 5 / 9
#* GBP to USD = * 1.4
#* USD to GBP = / 1.4
loop = True
while loop == True:
print("""Please enter the type you want to convert, followed by the type you want to convert to and then the amount you wish to convert
Cel to Far | Far to Cel
GBP to USD | USD to GBP
""")
print
convert1 = input("1st > ")
convert2 = input("2nd > ")
convert3 = int(input("num > "))
#* temperature
if (convert1.lower() == "c"):
if (convert2.lower() == "f"):
convert4 = convert3 * 9 / 5 + 32
print(str(convert4) + "f")
loop = False
elif (convert1.lower() == "f"):
if (convert2.lower() == "c"):
convert4 = convert3 - 32 * 5 / 9
print(str(convert4) + "c")
loop = False
#* currency
elif (convert1.lower() == "gbp"):
if (convert2.lower() == "usd"):
convert4 = convert3 * 1.4
print("$" + str(convert4))
loop = False
elif (convert1.lower() == "usd"):
if (convert2.lower() == "gbp"):
convert4 = convert3 / 1.4
print("£" + str(convert4))
loop = False | true |
5e0553c5e84ecd51056164c803d968728e7e6b7f | usama78941/Danial-Liang-Books-Exercies | /chapterFive/exer_7.py | 710 | 4.15625 | 4 | # (Financial application: compute future tuition) Suppose that the tuition for a university
# is $10,000 this year and increases 5% every year. In one year, the tuition
# will be $10,500. Write a program that computes the tuition in ten years and the
# total cost of four years’ worth of tuition after the tenth year.
def tuition_calculator():
tuition = 10000
four_years = 0
for i in range(1, 15):
tuition = (tuition * 5) / 100 + tuition
if i < 11:
print("Tuition fee for year ", str(i), "is: %d" % tuition)
else:
four_years += tuition
print("The total tuition fee after 10 years of four years would be: %d" % tuition)
tuition_calculator()
| true |
9b8d52dfd4fd4260cdf4508cccc471337cfb1cb7 | Oyekunle-Mark/Algorithms | /recipe_batches/recipe_batches.py | 1,367 | 4.25 | 4 | #!/usr/bin/python
def recipe_batches(recipe, ingredients):
"""Determines the amount of meals that could be make out of a given ingredient
Arguments:
recipe {dict} -- the recipe
ingredients {dict} -- the provided ingredients
Returns:
int -- the maximum amount of meals possible
"""
# Grab the amount of recipe and ingredient provided
recipe_amount = recipe.values()
ingredients_amount = ingredients.values()
# will hold the ratio of ingredient provided and required
batches = []
# if an ingredient is missing return 0
if len(recipe_amount) != len(ingredients_amount):
return 0
# compare recipe to ingredient
for rec, ing in zip(recipe_amount, ingredients_amount):
ratio = ing // rec
# if any ingredient is short of required amount return 0
if ratio == 0:
return 0
batches.append(ratio)
return min(batches)
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = {'milk': 100, 'butter': 50, 'flour': 5}
ingredients = {'milk': 132, 'butter': 48, 'flour': 51}
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(
batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| true |
45c806aa10d2ff8a7897f78e7fc652f6d375485e | lyes1/Machine_Learning_model_deployment | /module/utils.py | 1,023 | 4.125 | 4 |
# This piece of code is inspired from: http://blog.tkbe.org/archive/python-calculating-the-distance-between-two-locations/
# It calculate the "crow flies" distance between two locations
import math
features = ['trip_distance', 'day_pickup', 'hour_pickup', 'minute_pickup', "pickup_longitude", "dropoff_longitude", "pickup_latitude", "dropoff_latitude"]
target = 'trip_duration_log'
def cosrad(n):
"Return the cosine of ``n`` degrees in radians."
return math.cos(math.radians(n))
def distance(row):
"""Calculate the distance between two points on earth.
"""
lat1 = row['pickup_latitude']
long1 = row['pickup_longitude']
lat2 = row['dropoff_latitude']
long2 = row['dropoff_longitude']
earth_radius = 6371 # km
dLat = math.radians(lat2 - lat1)
dLong = math.radians(long2 - long1)
a = (math.sin(dLat / 2) ** 2 +
cosrad(lat1) * cosrad(lat2) * math.sin(dLong / 2) ** 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = earth_radius * c
return d
| true |
b12da2d4db4de9228a27bf42f5d8aeb666a3cf88 | SeanyPollard/com404 | /01-basics/04-repetition/01-while-loop/01-simple/bot.py | 203 | 4.28125 | 4 | #Ask user for number of cables to remove
cables = int(input("How many cables should I remove?\n"))
#While more than 0 cables, keep removing
while cables > 0:
print("Removed cable.")
cables -= 1
| true |
a145f406018939300dfcbecc9e6f94beb9dd17c9 | anokhramesh/Class-Example.py | /Example2init and self.py | 311 | 4.125 | 4 | # Example2 of init and self in python
class Rectangle:
def __init__(self,height,width):
self.height = height
self.width=width
rect1 = Rectangle(20,60)
rect2 = Rectangle(50,40)
print("Area of rect1 is=",rect1.height*rect1.width)
print("Area of rect2 is=",rect2.height*rect2.width) | true |
11cb9c08a48443ad394fb46b7cff18db81d79d22 | jb2718/python_practice | /treehouse/conditional.py | 573 | 4.1875 | 4 | first_name = input("What is your first name? ")
print("Hello,", first_name)
if first_name == "JB":
print(first_name, "is learning Python")
elif first_name == "Roald":
print(first_name, "is learning with felow students in the Community!")
else:
# This is for younger readers who may not be able to read
age = int(input("How old are you? "))
if age <= 6:
print("Wow, you're {}! If you're confident with your reading already you should start learning to program!".format(age))
print("You should totally learn Python, {}!".format(first_name)) | true |
554fb4afeb7d1e727a6b69c80a433322c31fb4f7 | Debbiie-creator/ProjectEuler | /Problem5.py | 763 | 4.15625 | 4 | # We need to start of by defining the gcd of 2 numbers as it is easier and straight-forward
# after which we will find the lcm by multiplying the two numbers and dividing by the gcd
def Gcd(a, b):
if a > b:
num1 = a
num2 = b
else:
num1 = b
num2 = a
r = num1 % num2
while r != 0:
num1, num2 = num2, r
r = num1 % num2
return num2
def Lcm(a, b):
n = (a * b)/Gcd(a, b)
return n
#Now that we can find lcm of two numbers, we can go ahead and find the lcm of multiple numbers by iteration
def LCM(l=[]):
m = Lcm(l[0], l[1])
for i in range(2, len(l)):
m = Lcm(m, l[i])
return int(m)
#Finally we can find the lcm of the 20 numbers
l = [a for a in range(1,20)]
print(LCM(l))
| true |
9c1f471e0adcee190122d932d9ebff66d6a40f8f | Gilbert-Gb-Li/Artificial-Intelligence | /f1_libs/arg_parse.py | 1,136 | 4.5625 | 5 | """
参数解析
https://zhuanlan.zhihu.com/p/56922793
"""
import argparse
def main():
"""
# 使用步骤:
1、创建ArgumentParser()对象。
2、调用add_argument()方法添加参数。
3、调用parse_args()解析添加的参数。
# 参数:
default:没有设置值情况下的默认参数
required:表示这个参数是否一定需要设置
type:参数类型
choices:参数值只能从几个选项里面选择
help:指定参数的说明信息
nargs: 设置参数在使用可以提供的个数
N 参数的绝对个数(例如:3)
'?' 0或1个参数
'*' 0或所有参数
'+' 所有,并且至少一个参数
"""
parser = argparse.ArgumentParser(description="Demo of argparse")
parser.add_argument('-n', '--name', default=' Li ')
parser.add_argument('-y', '--year', default='20')
args = parser.parse_args()
print(args)
name = args.name
year = args.year
print('Hello {} {}'.format(name, year))
if __name__ == '__main__':
main()
| false |
dbd54872ed81091510d9f0b99e61b2d54dc89c5c | Elektra-2/python_crash_course_2nd | /python_work/Chapter3/Exer8.py | 493 | 4.21875 | 4 | # Exer 8
# # Creating a list of nice places to visit
places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
# putting the list into alphabetic order
print(sorted(places_to_visit))
# putting the list back to its original order
print(places_to_visit)
# putting the list backwards
places_to_visit.reverse()
print(places_to_visit)
# putting the list into alphabetic order permanently
places_to_visit.sort()
# printing list length
print(len(places_to_visit))
| true |
eb2585cc2c10cf3817e596c0812d57132dd61fc0 | Elektra-2/python_crash_course_2nd | /python_work/Chapter5/exe1_alien_color.py | 314 | 4.25 | 4 | # Alien Colors #1: Imagine an alien was just shot down in a game.
# Create a variable called alien_color and assign it a value of 'green', 'yellow', or 'red'.
alien_color = 'green'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
else:
print('Congratulations! You won 5 points!')
| true |
8371eec0da12d2803469071debfa4917d458123d | shan1697-shan/Data_Structure_Using_Python | /stack1.py | 1,801 | 4.5 | 4 | # We have created a python file
# What stack does it---- First in Last out
class Stack:
top=-1
# here we define a variable with initial value -1 this will point the top value of the stack
# Since now stack is empty so the top is at -1
arr=[]
# Now we take a list where we will store the stack values
# here we are defining a function to take input into the stack
def inst(self,data,n):
# data will be the value to be inserted in the Stack and n will be the length ofthe stack
if self.top<n:
self.arr.append(data)
self.top+=1
print("Data has been inserted to the stack.")
else:
print("Stack is Full.")
def disp(self):
# this function will display the stack
if len(self.arr)==0:
print("Stack is empty")
else:
print("Stcak is:")
for i in self.arr[::-1]:
# since stack follows first in last out so here we will show last value first
print(i)
def popitem(self):
if len(self.arr)==0:
print("Stack is Empty.")
else:
val=self.arr.pop()
print(val," has been poped.")
if __name__ == '__main__':
obj = Stack()
l = int(input("Enter the length of the Stack:"))
while True:
choice = int(input("Enter 1 to push a data into the stack\n2 to pop a data from the stack\n3 to Display\n"
"4 to exit."))
if choice==1:
dta = input("Enter a Data to push into the Stack.")
obj.inst(dta,l)
elif choice==2:
obj.popitem()
elif choice==3:
obj.disp()
elif choice==4:
break
else:
print("Wrong choice!! Try Again")
| true |
4d520c63a6304d2021530e6ddf3c987f3b641175 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/74_isolated_or_grouped.py | 858 | 4.21875 | 4 | """
https://edabit.com/challenge/B6M8jqcq3nP4gDPEi
Isolated or Grouped?
Write a function that extracts the max value of a number in a list. If there are two or more max values, return it as a list, otherwise, return the number. This process could be relatively easy with some of the built-in list functions but the required approach is recursive.
Examples
iso_group([31, 7, 2, 13, 7, 9, 10, 13]) ➞ 31
iso_group([1, 3, 9, 5, 1, 7, 9, -9]) ➞ [9, 9]
iso_group([97, 19, -18, 97, 36, 23, -97]) ➞ [97, 97]
iso_group([-31, -7, -13, -7, -9, -13]) ➞ [-7, -7]
iso_group([-1, -3, -9, -5, -1, -7, -9, -9]) ➞ [-1, -1]
iso_group([107, 19, -18, 79, 36, 23, 97]) ➞ 107
"""
def iso_group(lst):
if lst.count(max(lst))==1: return max(lst)
else:
a=[]
for i in range(lst.count(max(lst))):
a.append(max(lst))
return(a) | true |
956bcdba6343528db45da262bc46779c8049df86 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/126_validate_subsequences.py | 875 | 4.28125 | 4 | """
https://edabit.com/challenge/Z2mhqFLe9g9ouZY64
Validate Subsequences EXPERT
Given two non-empty lists, write a function that determines whether the second list is a subsequence of the first list.
For instance, the numbers [1, 3, 4] form a subsequence of the list [1, 2, 3, 4], and so do the numbers [2, 4].
Examples
is_valid_subsequence([1, 1, 6, 1],[1, 1, 1, 6]) ➞ False
is_valid_subsequence([5, 1, 22, 25, 6, -1, 8, 10], [22, 25, 6]) ➞ True
is_valid_subsequence([1, 2, 3, 4], [2, 4]) ➞ True
"""
def is_valid_subsequence(lst, sequence):
for i in sequence:
if i in lst: lst = lst[lst.index(i) + 1:]
else:return False
return True
#is_valid_subsequence([1, 1, 6, 1],[1, 1, 1, 6]) #➞ False
#is_valid_subsequence([5, 1, 22, 25, 6, -1, 8, 10], [22, 25, 6]) #➞ True
is_valid_subsequence([1, 2, 3, 4], [2, 4]) #➞ True | true |
6adb0516ebc3630d7772fed1cd0ab12a0df70ed4 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/42_find_pattern_write_function.py | 419 | 4.15625 | 4 | """
Find the Pattern and Write the Function
By looking at the inputs and outputs below, try to figure out the pattern and write a function to execute it for any number.
Examples
func(3456) ➞ 2
func(89265) ➞ 5
func(97) ➞ 12
func(2113) ➞ -9
"""
def func(num):
a=(list(str(num)))
b = len(a)
count = 0
for i in a:
count = count + (int(i)-b)
return count
func(89265) #➞ 5 | true |
4024c9f3e0b6c0dbdb1c4e913b1c591cc63ae078 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/18_look_and_say_sequence.py | 1,884 | 4.28125 | 4 | """
Look-and-Say Sequence
Create a function that takes in two positive integers start and n and returns a list of the first n terms of the look-and-say sequence starting at the given start.
Each term of the look-and-say sequence (except for the first term) is created from the previous term using the following process.
Start with a term in the sequence (for example, 111312211):
111312211
Split it into subsequences of consecutive repeating digits:
111 3 1 22 11
Count the number of digits in each subsequence:
three 1, one 3, one 1, two 2, two 1
Turn everything into digits:
3 1, 1 3, 1 1, 2 2, 2 1
Now combine everything into one number:
3113112221
So 3113112221 is the next term in the sequence after 111312211.
Examples
look_and_say(1, 7) ➞ [1, 11, 21, 1211, 111221, 312211, 13112221]
look_and_say(123, 4) ➞ [123, 111213, 31121113, 1321123113]
look_and_say(70, 5) ➞ [70, 1710, 11171110, 31173110, 132117132110]
Notes
Your output should be a list of integers.
"""
def look_and_say(start, n):
a=[]
txt = str(start)
result= [int(txt)]
for k in range(0,n-1):
a=[]
txt = str(result[k])
while len(txt)>0:
s = txt[0]
for i in range(1,len(txt)):
if txt[i] in s:
s+=txt[i]
else:
break
a.append(s)
txt = txt[len(s):]
b=[]
for i in range(len(a)):
b.append(str(len(a[i])))
b.append(str(a[i][0]))
txt = "".join(b)
result.append(int(txt))
return (result)
#look_and_say(111312211, 2) #, [111312211, 3113112221]
#look_and_say(1, 7) #➞ [1, 11, 21, 1211, 111221, 312211, 13112221]
look_and_say(123, 4) #➞ [123, 111213, 31121113, 1321123113]
#look_and_say(70, 5) #➞ [70, 1710, 11171110, 31173110, 132117132110] | true |
d1b9e09867f9597f20189904f18e161427530704 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EARLIER/27_sort_the_string.py | 957 | 4.125 | 4 | """
Sort the String
Create a function that takes a string consisting of lowercase letters, uppercase letters and numbers and returns the string sorted in the same way as the examples below.
Examples
sorting("eA2a1E") ➞ "aAeE12"
sorting("Re4r") ➞ "erR4"
sorting("6jnM31Q") ➞ "jMnQ136"
Notes
N/A
"""
def sorting(s):
a="azertyuiopqsdfghjklmwxcvbn"
u = sorted(list(a.upper()))
l= sorted(list(a.lower()))
n ="0123456789"
b = []
for i in range(len(u)):
if l[i] in s:
b.append(l[i])
if u[i] in s:
b.append(u[i])
for i in range(len(n)):
if n[i] in s:
b.append(n[i])
return ("".join(b))
sorting("eA2a1E") #➞ "aAeE12"
#sorting("Re4r") #➞ "erR4"
#sorting("6jnM31Q") #➞ "jMnQ136"
#sorting("f5Eex") #, "eEfx5")
#sorting("846ZIbo") #, "bIoZ468")
#sorting("2lZduOg1jB8SPXf5rakC37wIE094Qvm6Tnyh") #, "aBCdEfghIjklmnOPQrSTuvwXyZ0123456789")
| false |
402db4882c255a55f9b3de547e48eaa20d957755 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/91_parabolic_jumps.py | 1,432 | 4.625 | 5 | """
https://edabit.com/challenge/MFFuPFnjT8ihniKtL
Parabolic Jumps
When a bug jumps to a height y, its position can be plotted as a quadratic function with x as the time,
and y as the vertical distance traveled.
For example, for a bug that jumps 9 cm up and is back on the ground after 6 seconds, its trajectory can be plotted as:
bug jump quadratic plot
Create a function that, given the max height of a vertical jump in cm and the current time in milliseconds,
returns the current position of the bug rounded to two decimal places, and its direction ("up" or "down").
If the bug is already back on the ground, return 0 for the position and None for the direction.
Examples
bug_jump(9, 1000) ➞ [5, "up"]
bug_jump(9, 4000) ➞ [8, "down"]
bug_jump(9, 5500) ➞ [2.75, "down"]
bug_jump(9, 7000) ➞ [0, None]
Notes
Time and position both start at 0.
You only need to translate the parabola (you don't need to scale it).
"""
def bug_jump(height, time):
t = time /1000
# y = x**2 / 4 , https://www.futurelearn.com/courses/maths-linear-quadratic/0/steps/12114
x = 2 * (height ** 0.5)
if 0 < t < x/2:
return [round((-t**2+t*x),2), "up"]
elif x/2 < t < x:
return [round((-t**2+t*x),2), "down"]
else:
return [0, None]
bug_jump(9, 1000) #➞ [5, "up"]
#bug_jump(9, 4000) #➞ [8, "down"]
#bug_jump(9, 5500) #➞ [2.75, "down"]
#bug_jump(9, 7000) #➞ [0, None] | true |
e469e0b5dc0ac71a067cf1bf13c68ac2b9d0a5b5 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EARLIER/01_rearrange_the_number.py | 551 | 4.1875 | 4 | """
Rearrange the Number
Given a number, return the difference between the maximum and minimum numbers that can be formed when the digits are rearranged.
Examples
rearranged_difference(972882) ➞ 760833
# 988722 - 227889 = 760833
rearranged_difference(3320707) ➞ 7709823
# 7733200 - 23377 = 7709823
rearranged_difference(90010) ➞ 90981
# 91000 - 19 = 90981
Notes
N/A
"""
def rearranged_difference(num):
return (int("".join(sorted(list(str(num)),reverse = True)))) - int("".join(sorted(list(str(num)))))
rearranged_difference(3320707) | true |
74475aa19454875dec312e74e2ffc54460e36519 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/132_sorted_list_of_words.py | 1,508 | 4.15625 | 4 | """
https://edabit.com/challenge/pGRAtBbwSMjpXNGnP EXPERT
Sorted List of Words
The function is given a list of words and a new alphabet (English letters in different order). Determine if the list of words is sorted lexicographically. The words consist of lower case letters.
Examples
is_sorted(["hello", "edabitlot"], "hlabcdefgijkmnopqrstuvwxyz") ➞ True
is_sorted(["word", "world", "row"], "worldabcefghijkmnpqstuvxyz") ➞ False
is_sorted(["apple", "app"], "abcdefghijklmnopqrstuvwxyz") ➞ False
is_sorted(["deceased", "folks", "can", "vote"], "abdefghijklmnopqrstcuvwxyz") ➞ True
Notes
N/A
"""
def is_sorted(words, alphabet):
#if words == []:
#return True
for i in range(len(words)-1):
text1, text2 = words[i], words[i+1]
if len(words[i]) > min(len(text1), len(text2)):
if words[i+1] == words[i][0:min(len(text1), len(text2))]:
return False
for j in range(min(len(text1), len(text2))):
if alphabet.find(words[i][j]) > alphabet.find(words[i+1][j]):
if all(words[i][k] == words[i+1][k] for k in range(j)):
return False
return True
is_sorted(["hello", "edabitlot"], "hlabcdefgijkmnopqrstuvwxyz") #➞ True
is_sorted(["word", "world", "row"], "worldabcefghijkmnpqstuvxyz") #➞ False
#is_sorted(["apple", "app"], "abcdefghijklmnopqrstuvwxyz") #➞ False
#is_sorted(["deceased", "folks", "can", "vote"], "abdefghijklmnopqrstcuvwxyz") #➞ True | true |
4e26e254970e902d6b138a87386020d7852f0c0c | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/115_golomb_sequence.py | 975 | 4.15625 | 4 | """
https://edabit.com/challenge/LhAgbJ7nv3EDSLuYa
Golomb Sequence
The Golomb sequence is uniquely defined by the following rules:
All terms are positive integers.
No term is smaller than any previous term.
The nth term is equal to the total number of times that the integer n appears within the sequence.
Write a function that returns the first n terms of the Golomb sequence as a list.
Examples
golomb(1) ➞ [1]
golomb(8) ➞ [1, 2, 2, 3, 3, 4, 4, 4]
golomb(10) ➞ [1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
1 appears once; 2 appears twice; 3 appears twice; 4 appears 3 times; 5 will appear 3 times in the full sequence, etc.
Notes
The tests will consist of random inputs between 1 and 1000 inclusive.
If stuck, see resources tab for more information and hints.
"""
def golomb(n):
m, a=1001, [0, 1, 2, 2]
for k in range(3, m):a+=[k for i in range(1, a[k] + 1)]
return a[1:n+1]
#golomb(8) #➞ [1, 2, 2, 3, 3, 4, 4, 4]
golomb(10) #➞ [1, 2, 2, 3, 3, 4, 4, 4, 5, 5] | true |
3bd0d226f5c824f001c9f65e80d7c86136ecf3b3 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/52_harshad_number.py | 885 | 4.21875 | 4 | """
Recursion: Harshad Number
A number is said to be Harshad if it's exactly divisible by the sum of its digits. Create a function that determines whether a number is a Harshad or not.
Examples
is_harshad(75) ➞ False
# 7 + 5 = 12
# 75 is not exactly divisible by 12
is_harshad(171) ➞ True
# 1 + 7 + 1 = 9
# 9 exactly divides 171
is_harshad(481) ➞ True
is_harshad(89) ➞ False
is_harshad(516) ➞ True
is_harshad(200) ➞ True
Notes
You are expected to solve this challenge via recursion.
You can check on the Resources tab for more details about recursion.
A non-recursive version of this challenge can be found here
"""
def is_harshad(n):
a,b=list(str(n)), []
for i in a: b.append(int(i))
if n%sum(b) == 0 :return True
else: return False
is_harshad(481) #➞ True
#is_harshad(89) #➞ False
#is_harshad(516) #➞ True
#is_harshad(200) #➞ True
| true |
5e9da6e9c9f9dfec24a825fc6d2068b7b757171f | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/19_how_many_digits_between.py | 924 | 4.53125 | 5 | """
How Many Digits between 1 and N
Imagine you took all the numbers between 0 and n and concatenated them together into a long string. How many digits are there between 0 and n? Write a function that can calculate this.
There are 0 digits between 0 and 1, there are 9 digits between 0 and 10 and there are 189 digits between 0 and 100.
Examples
digits(1) ➞ 0
digits(10) ➞ 9
digits(100) ➞ 189
digits(2020) ➞ 6969
Notes
The numbers are going to be rather big so creating that string won't be practical.
"""
def digits(number):
return (sum([(10**(x+1) - 10**x) * (x+1) for x in range(len(str(number))-1)]) + (number-10**(len(str(number))-1))*(len(str(number))))
#digits(1), 0)
#digits(10), 9)
#digits(100) #, 189)
#digits(2020) #, 6969)
#digits(103496754) #, 820359675)
#digits(3248979384) #, 31378682729)
#digits(122398758003456), 1724870258940729)
digits(58473029386609125789) #, 1158349476621071404669) | true |
9abb23be71129526aff9e315eacf6a78c9a96fe1 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EARLIER/42_a_long_long_time.py | 565 | 4.375 | 4 | """
A Long Long Time
Create a function that takes three values:
h hours
m minutes
s seconds
Return the value that's the longest duration.
Examples
longest_time(1, 59, 3598) ➞ 1
longest_time(2, 300, 15000) ➞ 300
longest_time(15, 955, 59400) ➞ 59400
Notes
No two durations will be the same.
"""
def longest_time(h, m, s):
a, b, c = h*3600, m*60, s
if max(a,b,c) == a:
return h
elif max(a,b,c) == b:
return m
elif max(a,b,c) == c:
return s
longest_time(1, 59, 3598)
#longest_time(15, 955, 59400) #➞ 59400 | true |
e8ae2dee0df96b338ab1b63bf3f5f6fdc8e3a8e7 | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EARLIER/33_solve_a_linear_equation.py | 707 | 4.34375 | 4 | """
Solve a Linear Equation
Create a function that returns the value of x (the "unknown" in the equation). Each equation will be formatted like this:
x + 6 = 12
Examples
solve("x + 43 = 50") ➞ 7
solve("x - 9 = 10") ➞ 19
solve("x + 300 = 100") ➞ -200
Notes
"x" will always be in the same place (you will not find an equation like 6 + x = 12).
Every equation will include either subtraction (-) or addition (+).
"x" may be negative.
"""
def solve(eq):
a= eq.split(" ")
if a[1] == "+":
return int(a[4]) - int(a[2])
if a[1] == "-":
return int(a[4]) + int(a[2])
#solve("x + 43 = 50") #➞ 7
solve("x - 9 = 10") #➞ 19
#solve("x + 300 = 100") #➞ -200
| true |
c464479d143b99fe18083debd6f1ee3af66b972b | UoM-Podcast/helper-scripts | /lib/input_output/read_file.py | 398 | 4.125 | 4 | def read_file(file_path):
"""
Return the content of a file as a string without newlines.
:param file_path: The path to the file
:type file_path: str
:return: File content
:rtype: str
"""
file_string = ''
with open(file_path, 'r', newline='') as file:
for line in file:
file_string = file_string + line.rstrip('\n')
return file_string
| true |
d17b334a91cb29ef644a7988440563cd7b670357 | Changelynx/tp-doomsday-rule | /doomsday/date.py | 1,734 | 4.15625 | 4 | def is_valid_date(date) -> bool:
# checks if the date is in the YYYY-MM-dd format and if it is real
date = str(date)
if len(date) != 10:
print("YYYY-MM-dd format must contain 10 characters")
return False
if len(date.split('-')) != 3:
print("YYYY, MM & dd must be separated by hymens")
return False
year, month, day = date.split('-')
if not (year + month + day).isnumeric():
print("YYYY, MM & dd must be numerics")
return False
year, month, day = int(year), int(month), int(day)
return is_coherent_date(year, month, day)
def is_coherent_date(year: int, month: int, day: int) -> bool:
# checks if the date can exist
if year < 1583:
print("Year must be earlier than 1583")
elif month <= 0 or month > 12:
print("Month must be between 1 and 12")
elif day < 0:
print("Day must be positive")
elif day > day_count_in_month(month, year):
print("Day too high")
else:
return True
return False
def is_leap_year(year: int) -> bool:
# checks if the year is leap
if(year % 400 != 0):
return year % 4 == 0 if year % 100 != 0 else False
return True
def day_count_in_month(month: int, year: int) -> int:
# returns the number of days in a given month
# in this list, from index 0 to index 6 included are the 31 days months
# from index 7 to 10 included are the 30 days months
# and index 11 is February
month_descending_list = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2]
if month_descending_list.index(month) <= 6:
return 31
if month_descending_list.index(month) <= 10:
return 30
return 29 if is_leap_year(year) else 28
| true |
42acbb7800916cb06a89c7f96db78a34a1d1e3a8 | monicaneill/Module-4-Question | /Power_of_two.py | 550 | 4.25 | 4 | #The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers
def is_power_of_two(n):
#check if numb can be divided by 2 w/o remainder
while n%2 == 0 and n!= 0: #the divisions by 0 were causing the infinite loop, fixed with and statement
n = n/2
#if after dividing by 2 the number is 1, it's a power of 2
if n==1:
return True
return False
print(is_power_of_two(0))
print(is_power_of_two(1))
print(is_power_of_two(8))
print(is_power_of_two(9))
| true |
55f7dd0231f1077f8643a7951d9a3acefde35f20 | SamRicha/CS101 | /Lesson22/QuizTen.py | 617 | 4.34375 | 4 | # Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
# Base Case: '' => True
# Recursive Case: if first and last characters don't match => False
# if they do match, is the middle a palindrome?
def is_palindrome(word):
if word == '':
return True
else:
if word[0] == word [-1]:
new_word = word[1:-1]
return is_palindrome(new_word)
else:
return False
print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True
| true |
1f299471abec400f4bd3eeaa1672c959d80a32a8 | shiqi0128/My_scripts | /test/practise/function/return.py | 1,853 | 4.125 | 4 | def name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + middle_name + last_name
else:
full_name = first_name + last_name
return full_name.title()
a = name('jimi ', 'yoyo ', 'haha ')
print(a)
a = name('jimi ', 'haha ')
print(a)
def name(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
a = name("jimi", "haha")
print(a)
def name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name: ")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
a = name(f_name, l_name)
print("\nHello, " + a + "!")
8-6城市名
def city_country(name, country):
c = name + ',' + country
return c.title()
a = city_country("beijing", "China")
print(a)
a = city_country("new york", "america")
print(a)
8-7专辑
def make_album(singer_name, type_name, count=""):
a = {'singer_name': singer_name, 'type_name': type_name}
if count:
a['count'] = count # 添加字典中的键—值对
return a
b = make_album(singer_name="张杰", type_name="逆战", count=10)
print(b)
8-8 用户的专辑
def make_album(singer_name, type_name):
a = {'singer_name': singer_name, 'type_name': type_name}
return a
while True:
print("\n请输入歌手姓名: ")
print("(enter 'q' at any time to quit)")
print("\n请输入专辑名称: ")
print("(enter 'q' at any time to quit)")
s_name = input("singer_name: ")
if s_name == 'q':
break
t_name = input("type_name: ")
if t_name == 'q':
break
b = make_album(s_name, t_name)
print(b) | false |
d1e46740461a3b72e96c20ed5a7e8d723a02bd57 | Domin-Imperial/Domin-Respository | /1-python/python/classes.py | 2,481 | 4.15625 | 4 | class Person:
# any instance method in python needs "self" as the first parameter
# constructor
def __init__(self, name):
# private
self.__identifier = name
# not private
self.name = name
def print_name(self):
print(self.name)
# a lot of the behavior of global built-in functions
# is based on double-underscore (dunder) methods that you can override here
def __str__(self):
return f'({self.name})'
# used by ==
def __eq__(self, other):
return self.__identifier == other.__identifier
# print(f'__name__ is {__name__}')
# anything in this condition, only runs if the module is being directly run
# (as opposed to imported)
if __name__ == '__main__':
# basic OO idea:
# writing code, we find that some pieces of data
# are always used together
student_ids = [1, 2, 3]
student_names = ['bob', 'tim', 'fred']
# rather than accidentally associating that data, let's use data structures
# intelligently to keep it organized together
student_info = [(1, 'bob'), (2, 'tim'), (3, 'fred')]
# combine data and associated behavior into one unit called an object
# encapsulation - combining these things into one unit
# that controls access/its own rules about that stuff
# classes are templates for making new objects
# in other languages, you can't tack on new instance variables (aka fields)
# besides the ones defined by the class. you can in python
fred = Person('fred')
fred.job = 'trainer'
# print(fred.__name)
fred.print_name()
Person.print_name(fred) # equivalent to above line
print(fred)
str(fred)
print(f'-- {fred} --')
print(fred == Person('fred'))
# do they refer to the same object
print(fred is Person('fred'))
# a namespace is a context where variables live
# the way that python interprets any name of a variable/etc
# like fred, Person, print, str, etc
# LEGB namespaces
# first, it checks the local namespace
# then, any enclosing namespaces,
# then, the global namespace,
# then, the built-in namespace (print, str)
var = 5 # global
if True:
var2 = 5 # global
# in python, functions and classes have their own namespaces
def func():
var = 6 # enclosing (relative to func2)
def print():
pass
def func2():
var = 7 # local
# print = 5
print(var)
# id = 5
# map
# filter
func()
var == 5
| true |
56af2176082995263ca2c1c44a2916a256a02725 | ryanhoang15/Python | /Rectangle.py | 1,188 | 4.21875 | 4 | class rectangle:
def __init__(self, h=1.0, w=1.0):
self.height = h
self.width = w
# def setRect(self,h,w):
# self.height = h
# self.width = w
def getWidth(self):
return self.width
def getHeight(self):
return self.height
def getArea(self):
return self.height * self.width
def getPerimeter(self):
return (2 * self.height) + (2 * self.width)
print("Stats of the Rectangle with no Arguments")
rect1 = rectangle()
print("Width: " + str(rect1.getWidth()))
print("Height: " + str(rect1.getHeight()))
print("Area: " + str(rect1.getArea()))
print("Perimeter: " + str(rect1.getPerimeter()))
print("\nStats of the Second Rectangle")
rect2 = rectangle(40, 4)
print("Width: " + str(rect2.getWidth()))
print("Height: " + str(rect2.getHeight()))
print("Area: " + str(format(rect2.getArea(), ".2f")))
print("Perimeter: " + str(rect2.getPerimeter()))
print("\nStats of the Third Rectangle")
rect3 = rectangle(35.9, 3.5)
print("Width: " + str(rect3.getWidth()))
print("Height: " + str(rect3.getHeight()))
print("Area: " + str(format(rect3.getArea(), ".2f")))
print("Perimeter: " + str(rect3.getPerimeter()))
| false |
e9041c4cb153564a6374f602356f6fa4d5a93392 | ryanhoang15/Python | /9.17 Lab Ch 9: Random numbers in a list.py | 681 | 4.15625 | 4 | import random
list_1 = []
i = 0
while i < 10:
num = random.randint(0, 99)
list_1.append(int(num))
i = i + 1
print("Every other element of the random list (keep the first element):", end=" ")
for i in range(len(list_1)):
if list_1[i] % 2 != 0:
print(list_1[i], end=" ")
print()
print("The value of elements that are even:", end=" ")
for i in list_1:
if i % 2 == 0:
print(i, end=" ")
print()
print("Elements in reverse order:", end=" ")
for i in list_1[::-1]:
#range(len(len(list_1)-1,-1,-1) is another way to do it
print(i, end=" ")
print()
list_1.sort()
print("Elements sorted:", end=" ")
for i in list_1:
print(i, end=" ")
| true |
4f5958308bda280ad12b021bf771b6eeb5b505eb | ryanhoang15/Python | /4.14 Lab Ch04: Remove the trailing "$" sign.py | 507 | 4.15625 | 4 | a_string=input("Enter a string consisting of alphabetic characters with \"$\": \n")
'''
for i in range (len(a_string)-1,-1,-1):
if a_string[i]=="$":
if i==0:
a_string = string[:i]
break
else:
a_string = a_string[:i+1]
break
print(a_string)
'''
# for i in range (len(a_string)-1,-1,-1):
# if a_string[i]!="$":
# print(a_string[:i+1])
# break
while a_string.endswith("$"):
a_string = a_string[:len(a_string)-1]
print(a_string)
| false |
cf28a4d10b8312127925b6ae2b733ff1bdee2f95 | Deego88/pands-project | /Speciestest.py | 499 | 4.125 | 4 | #Ricahrd Deegan
# Ask user for input of three variables.
x = float(input("Please enter petal_lenght: "))
y = float(input("Please enter petal_width: "))
#Isolate Setosa measurements first taking largets petal lenght value.
#Isolate Virsicolor measurements second, everything else is likely veriginica.
if x <= float(1.9):
print("species is setosa")
elif x > float(1.9) and x <= float(4.8):
print("species is likely virsicolor ")
else:
print("species is likely virginica")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.