blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2bd31fe7ea63fe2aa2fbb3cb6d5a9a69770289f9 | sagarshah95/Unscrambled-Computer-Science-Problems | /Task2.py | 1,216 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
from collections import defaultdict
if __name__ == '__main__':
telephone_time = dict()
for call in calls:
for call_element in [0, 1]:
telephone_time[call[call_element]] += int(call[3])
print(telephone_time[call[call_element]])
max_call_time = 0
max_telephone_num = ''
for telephone in telephone_time:
if telephone_time[telephone] >= max_call_time:
max_call_time = telephone_time[telephone]
max_telephone_num = telephone
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(
max_telephone_num, max_call_time))
| true |
6f28949bbf8211e3916d50b4a11f34f60ecdd9e7 | sx0785/myPython | /4.Numbers.py | 559 | 4.1875 | 4 | '''
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
'''
#Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
#Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))
| true |
cb48333525a233aa614179d10531f8be81b7a9b8 | wangziyi0526/python_test | /test_two/range.py | 1,412 | 4.15625 | 4 | # range() 函数
# 如果你确实需要遍历一个数字序列,内置函数 range() 会派上用场。它生成算术级数:
# part1-1 在range()函数中传递一个参数的情况下
lists = []
for i in range(5):
lists.append(i)
print(lists) # 根据for循环把 利用range()内置函数生成的序列依次 push(append)进lists 列表中
print(lists)
# part1-2 在range()函数中传递两个参数的情况下
arry = []
for i in range(5,8):
arry.append(i)
print(arry)
print(arry)
# part1-3
ary = []
for i in range(1,10,3):
ary.append(i)
print(ary)
print(ary)
# 个人理解
# 传递一个参数的情况下默认区间是从0开始到传进的参数之间的值 但是不包含传进去的参数的值
# 传递两个参数的情况下第一个参数是区间开始的值,第二个参数是区间结束的值
# 传递三个参数的情况下前两个参数的意思见上一条, 第三个参数的意义 是在前两个参数区间内,以第三个参数的值
# 作为增长数值
# range() 函数 可以与len()函数进行配合使用
name = ['kobe', 'jordan', 'james', 'lakers']
for item in range(len(name)):
print(item, name[item])
# list()
array = list(range(5))
print(array)
for n in range(2,10):
print('开始')
print(n)
for x in range(2,n):
print(x)
if n%x == 0:
print("这是啥")
break
else:
print(n, '这又是啥')
| false |
84406c9a2458e392fef4e9f7d43c649c547d4d70 | venanciomitidieri/Exercicios_Python | /096 - Função que calcula área.py | 498 | 4.34375 | 4 | # Exercício Python 096 - Função que calcula área
# Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular
# (largura e comprimento) e mostre a área do terreno.
def area():
print('Controle de Terrenos')
print('---------------------')
l = float(input('LARGURA (m): '))
c = float(input('COMPRIMENTO (m): '))
d = l * c
print(f'A área de um terreno {l} x {c} é de {d} metros quadrados')
area()
| false |
fc378fc58631ecd5594ac77fadccd207f5d943ee | Mrinal18/August-LeetCoding-Challenge | /Week3/1.1 Non-overlapping Intervals.py | 2,302 | 4.1875 | 4 |
"""
Algorithm
The Greedy approach just discussed was based on choosing intervals greedily based on the starting points. But in this approach, we go for choosing points greedily based on the end points. For this, firstly we sort the given intervals based on the end points. Then, we traverse over the sorted intervals. While traversing, if there is no overlapping between the previous interval and the current interval, we need not remove any interval. But, if an overlap exists between the previous interval and the current interval, we always drop the current interval.
To explain how it works, again we consider every possible arrangement of the intervals.
Case 1:
The two intervals currently considered are non-overlapping:
In this case, we need not remove any interval and for the next iteration the current interval becomes the previous interval.
Case 2:
The two intervals currently considered are overlapping and the starting point of the later interval falls before the starting point of the previous interval:
In this case, as shown in the figure below, it is obvious that the later interval completely subsumes the previous interval. Hence, it is advantageous to remove the later interval so that we can get more range available to accommodate future intervals. Thus, previous interval remains unchanged and the current interval is updated.
Case 3:
The two intervals currently considered are overlapping and the starting point of the later interval falls before the starting point of the previous interval:
In this case, the only opposition to remove the current interval arises because it seems that more intervals could be accommodated by removing the previous interval in the range marked by AA. But that won't be possible as can be visualized with a case similar to Case 3a and 3b shown above. But, if we remove the current interval, we can save the range BB to accommodate further intervals. Thus, previous interval remains unchanged and the current interval is updated.
"""
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
end, cnt = float('-inf'), 0
for s, e in sorted(intervals, key=lambda x: x[1]):
if s >= end:
end = e
else:
cnt += 1
return cnt
| true |
6a843a7ffc41fbccff5ab70fb82e9ca6303fd263 | Adolfo-AB/algorithms-data-structures | /Fibonacci.py | 673 | 4.21875 | 4 | # Recursive approach
# def find_nth_fibonacci(n):
# if n == 0:
# print("Incorrect input")
# elif n == 1:
# return 0
# elif n == 2:
# return 1
# else:
# return find_nth_fibonacci(n-1) + find_nth_fibonacci(n-2)
# Dynamic programming approach
def find_nth_fibonacci(n, fib_array = {1:0, 2:1}):
if n in fib_array:
return fib_array[n]
fib_array[n] = find_nth_fibonacci(n-1, fib_array) + find_nth_fibonacci(n-2, fib_array)
return fib_array[n]
assert find_nth_fibonacci(1) == 0
assert find_nth_fibonacci(2) == 1
assert find_nth_fibonacci(3) == 1
assert find_nth_fibonacci(6) == 5
| false |
f38b0854b88afa5c95b584e7a60380502ab5491d | T-clown/python | /grammar/Class.py | 2,924 | 4.125 | 4 | #!/usr/bin/python3
"""
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods
"""
# 类定义
class People:
# 定义基本属性
name = ''
age = 0
# 定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
# 定义构造方法
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.__weight = weight
def speak(self):
print("%s 说: 我 %d 岁。体重:%d kg" % (self.name, self.age, self.__weight))
# 实例化类
p = People('mike', 20, 30)
p.speak()
# 单继承示例
class Student(People):
grade = ''
def __init__(self, n, a, w, g):
# 调用父类的构函
People.__init__(self, n, a, w)
self.grade = g
# 覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
s = Student('jack', 10, 60, 3)
s.speak()
# 另一个类,多重继承之前的准备
class Speaker():
topic = ''
name = ''
def __init__(self, n, t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))
# 多重继承
class Sample(Speaker, Student):
a = ''
def __init__(self, n, a, w, g, t):
Student.__init__(self, n, a, w, g)
Speaker.__init__(self, n, t)
test = Sample("Tim", 25, 80, 4, "Python")
test.speak() # 方法名同,默认调用的是在括号中排前地父类的方法
class Parent: # 定义父类
def myMethod(self):
print('调用父类方法')
class Child(Parent): # 定义子类
def myMethod(self):
print('调用子类方法')
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
super(Child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
"""
类的专有方法:
__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__ : 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 获得长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__truediv__: 除运算
__mod__: 求余运算
__pow__: 乘方
""" | false |
8cf80874a618ebed867a9f2bf9eb28cc9608ab2f | T-clown/python | /grammar/Tuple.py | 603 | 4.125 | 4 | """
元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号 ( ),列表使用方括号 [ ]
"""
tup1 = (1)
print(type(tup1))
tup2 = (1, 2)
print(type(tup2))
tup = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]: ", tup[0])
print("tup2[1:5]: ", tup[1:5])
print(len(tup))
print(max(tup))
print(min(tup))
list = [1, 2, 3]
tuple = tuple(list)
print(tuple)
print(id(tup))
print(id(tuple))
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
# 创建一个新的元组
tup3 = tup1 + tup2
print(tup3)
del tup3
# print(tup3)
| false |
11c2cfa4cdb8d053eb73860fb35faf07746d6e1b | zhangyu345293721/core | /leetcode/string/freq_alphabets_1309.py | 973 | 4.125 | 4 | # -*- coding:utf-8 -*-
'''
解析字符串
author:zhangyu
date:2020/1/12
'''
def get_char(sub_str: str):
'''
对字符串进行转换
Args:
sub_str: 输入字符串
Returns:
转换后字符
'''
if sub_str.__contains__('#'):
sub = sub_str[:-1]
num = int(sub)
return chr(num + 96)
return chr(int(sub_str) + 96)
def freqAlphabets(s):
'''
字符串转化
Args:
s: 输入字符串
Returns:
返回解析后字符串
'''
i = 0
result_str = []
while i < len(s):
if i + 2 < len(s) and s[i + 2] == '#':
sub_str = s[i: i + 3]
ch = get_char(sub_str)
result_str.append(ch)
i += 3
else:
ch = get_char(s[i])
result_str.append(ch)
i += 1
return ''.join(result_str)
if __name__ == '__main__':
s = "25#"
result = freqAlphabets(s)
print(result)
| false |
c51922eadd705efea0c4bd4b10faf5d67ea63174 | catherineuhs/Ch.03_Input_Output | /3.2_Trapezoid.py | 659 | 4.46875 | 4 | '''
TRAPEZOID PROGRAM
-------------------
Create a new program that will ask the user for the information needed to find the area of a trapezoid, and then print the area.
Test with the following:
base 1: 2 base 2: 3 height: 4 area: 10
base 1: 5 base 2: 7 height: 2 area: 12
base 1: 1 base 2: 2 height: 3 area: 4.5
base 1: 7 base 2: 2 height: 4 area: 18
'''
baseA=int(input("Whats the top base of the trapezoid?"))
baseB=int(input("Whats the bottom base of the trapezoid?"))
height=int(input("Whats the height of the trapezoid?"))
area=((baseA+baseB)/2 * height)
print("the area of the trapezoid is", area)
| true |
e5271f33f4a23db64dded15d5217caf278705850 | CyberRob27/python | /cs 631python/cs 631python.py.py | 2,805 | 4.34375 | 4 | '''
Robert Abel
Python Exercises
Dr. Scharff
'''
#1
print(5/3)
print (5%3)
print(5.0/3)
print(5/3.0)
print(5.2%3)
#2
''' print (2000.3 **200)'''
#above function is invalid
print(1.0+1.0-1.0)
print (1.0 +1.0e20-1.0e20)
print(float(123))
print(float('123'))
print(float('123.23'))
#3
'''print(int('123.23'))'''
'''print(int('123.23')'''
#above function is invalid
print(int(float('123.23')))
print(str(12))
print(str(12.2))
print(bool('a'))
print(bool(0))
print(bool(0.1))
#5
number_found = 0
x = 11
while number_found < 20:
if x % 5 == 0 and x % 7 == 0 and x % 11 == 0:
print(x)
number_found += 1
x+=1
#6
def is_prime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
def is_prime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
def prime_spitter(n):
while n > 0:
if is_prime(n):
print(n)
n-=1
else: n-=1
prime_spitter(7)
def is_prime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
def prime_spitter2(n):
counted = 0;
x = 2
while counted < n:
if is_prime(x):
counted+=1
print(x)
x+=1
else: x+=1
prime_spitter2(7)
#7
def list_printer(n):
for i in n:
print(i)
list_printer([1,2,3])
def list_printer(n):
n.reverse()
for i in n:
print(i)
list_printer([1,2,3])
def list_size(n):
counter = 0
for i in n:
counter+=1
return counter
print(list_size([1,2,3,4]))
#8
a = ["a","b","c"]
b = a
b[1] = "d"
print(b[1])
c = a[:]
c[2] = "e"
print(c)
def set_first_lem_to_zero(a):
a[0] = 0
return a
a = ["a","b","c"]
set_first_lem_to_zero(a)
print(a)
#9
def list_maker(a):
b = []
for i in a:
for x in i:
b.append(x)
return b;
list_maker([[1,3],[3,6]])
#10
#x = np.arange(0,2,0.1) # start,stop,step
#y = np.sin(x)**2 * np.power(np.e,np.power(-x,2))
#plt.plot(x,y, color='red', linewidth =3)
#plt.title("Sine Graph")
#plt.xlabel('x values from 0 to 2')
#plt.ylabel('sin^2(x - 2) e^(-x^2)')
#plt.show()
#11
def iteration(x):
z = 1;
for y in x:
z *=y
return z
iteration([1,2,3,4,5])
def recursive(x):
if (len(x)==1):
return x[0]
else:
return recursive([x[0]]) * recursive(x[1:])
recursive([1,2,3,4,5])
#12
def Fib(n):
if(n==0):
return 0
elif(n==1 or n==2):
return 1
else:
return Fib(n-1) + Fib(n-2)
Fib(14) | false |
845e45b6abb81a6b6552ae015542eb4d1cb67694 | Haliescarlet6/Complex-Python-Calculator | /Complex calculator.py | 1,499 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
num_1 = int(input("Enter your First Number : "))
Operation = str(input("Enter your Operation(In SYMBOLS): "))
num_2 = int(input("Enter your Second Number : "))
if Operation =="+":
result = num_1 + num_2
print("The Sum of the numbers is: ",result)
elif Operation =="-":
print("Do you want the result in negative form (yes/no) ?")
userans = str(input("Type yes or no: "))
if userans =="yes" or userans =="Yes":
if num_1 > num_2:
result = num_2 - num_1
print("Your result is",result)
elif num_1 < num_2:
result = num_1 - num_2
print("Your result is :",result)
if userans =="no" or userans =="No":
if num_1 > num_2:
result = num_1 - num_2
print("The result is :",result)
elif num_1 < num_2:
result = num_2 - num_1
print("The result is :",result)
elif Operation =="*":
result = num_1 * num_2
print("The result of their multiplication is :",result)
elif Operation =="/":
print("Which number should be the numerator ?")
userans2 = int(input("Type the number which should be the numerator : "))
if userans2 == num_1:
result = (num_1 / num_2)
print("The result is :" , result)
elif userans2 == num_2:
result = (num_2 / num_1)
print("The result is :" , result)
else:
print("ERROR")
print("TYPED INVALID NUMBER.")
# In[ ]:
| true |
141472c2e17d4d43e32235b7c9563cb55c3dd54b | rushikmaniar/RushikPython | /collegeExercise/exe10_Operators.py | 610 | 4.3125 | 4 | '''
Use of Operators
'''
print('\n\nAssisgnment Operator')
a = 2
print('a : ',a)
a += 2
print('a += 2',a)
a -= 2
print('a -= 2',a)
a *= 2
print('a *= 2',a)
a /= 2
print('a /= 2',a)
print('\n\n\nRelatonal Operator')
a = 10
b = 5
print('A : ',a)
print('B : ',b)
if(a < b):
print('\nA < B')
if(a <=b ):
print('A <= B')
if(a > b ):
print('A > B')
if(a >= b ):
print('A >= B')
if(a == b ):
print('A == B')
if(a != b ):
print('A != B')
print('\n\n\nMembership Operator')
list = (10,2,6,3)
if(2 in list):
print('2 in list ')
if(2 not in list):
print('2 not in list ')
| false |
b635a0b0211dea6ed7be519ed3b27ea3bd53ce87 | dspina79/lp3thw | /ex37/day3collection/loopsandcontinues.py | 283 | 4.1875 | 4 | # While Loops with Continues
def output_cubes_not_divisible_by_3(upper_range):
starter = 1
while starter < upper_range:
cube = starter ** 3
starter += 1
if cube % 3 == 0:
continue
print(cube)
output_cubes_not_divisible_by_3(100) | true |
4a76188ba0c5dcb0eea4b9903057b79c8562dc76 | dspina79/lp3thw | /ex18/ex18-introfunctions.py | 909 | 4.25 | 4 | # Names, Variables, Code, Functions
# function taking one or more arguments
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# function taking two definitive arguments
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# function with one argument
def print_one(arg1):
print(f"arg1: {arg1}")
# function with no arguments
def print_none():
print("Nothing was received.")
# basic calculations for practice
def add(x, y):
return x + y
def multiply(x, y):
return x * y
def print_add(x, y):
sum = add(x, y)
print(f"The sum of {x} and {y} is {sum}.")
def print_multiply(x, y):
product = multiply(x, y)
print(f"The product of {x} and {y} is {product}.")
print_two("Dean", "Anips")
print_two_again("Dean", "Phillips")
print_one("First!")
print_none()
# do the additional math
print_add(5, 6)
print_multiply(5, 6) | true |
870f31b01b1ad64cc571b27aa2122c92862bab0a | dspina79/lp3thw | /ex11/ex11-challenge.py | 432 | 4.1875 | 4 | # Additional Python Form
print("What is your favorite color?", end=' ')
favorite_color = input()
print(f"So you like {favorite_color}. What is another color you like?", end=' ')
second_color = input()
print("If you could like anywhere in the world, where would it be?", end=' ')
place = input()
print(f"""
So, you're favorite colors are {favorite_color} and {second_color}.
You would prefer to like in {place}.
That's nice.
""") | true |
fe7d188e2f1cc617803d56c11d574f4310537713 | dspina79/lp3thw | /ex24/ex24-practice.py | 1,330 | 4.1875 | 4 | # Practice of Learned Concepts
print("Let's practice everything.")
print('You\'d nee to know \'bout escapes with \\ that do:')
print('\n new lines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nore comprehend passion from institution
and requires an explanation
\n\t\twhere there is none.
"""
print("-------------")
print(poem)
print("-------------")
five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
def getupperlower(person_name):
return person_name.upper(), person_name.lower()
start_point = 10000
beans, jars, crates = secret_formula(start_point)
# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
print(f"We'd have {beans}, {jars} jars, and {crates} crates.")
start_point = start_point / 10
formula = secret_formula(start_point)
print("We can also do it this way (having an array of elements passed in)")
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
name = input("Enter your name: ")
results = getupperlower(name)
print("The uppercase of your name is {} and the lowercase is {}.".format(*results))
| true |
aa673572a7dc57cb6d54b8c67e80ca8fae937a41 | pulengmoru/simplecalculator_new | /calculator.py | 886 | 4.15625 | 4 | 1. add
2. subtract
3. multiply
4. divide
print("Select an peration to perform")
print("1. add")
print("2. subtract")
print("3. multipy")
print("4. divide")
operation = input()
if operation == "1":
num1 = input("enter first number")
num2 = input("enter second number")
print("the sum is" + str(int(num1) + int(num2)))
#addition
elif operation == "2":
num1 = input("enter first number")
num2 = input("enter second number")
print("the sum is" + str(int(num1) - int(num2)))
#subtract
elif operation == "3":
num1 = input("enter first number")
num2 = input("enter second number")
print("the sum is" + str(int(num1) * int(num2)))
#multiply
elif operation == "4":
num1 = input("enter first number")
num2 = input("enter second number")
print("the sum is" + str(int(num1) / int(num2)))
#divide
else:
print("invalid entry")
| false |
ecb1b19c84b2dda08968cc352069d54ee041427e | shaidazmin/Python-for-Data-Science | /KeyWord.py | 2,974 | 4.15625 | 4 | #assert - This keyword is used as the debugging tool in Python. It checks the correctness of the code.
# It raises an AssertionError if found any error in the code and also prints the message with an error.
a = 1
b = 0
a = True
b = False
# assert b!=0#
# print(a/b)
# def
# def my_func(a,b):
# c = a+b
# print(c)
#
# my_func(10,20)
# class Myclass:
# #Variables……..
# def function_name(self):
# #statements………
#continue
# a = 0
# while a < 4:
# a += 1
# if a == 2:
# continue
# print(a)
#break
# for i in range(5):
# if(i==3):
# break
# print(i)
# print("End of execution")
# If
# i = 18
# age = int(input("Your age : "))
# if (age < i):
# print("you are less than 18")
# else:
# print("Your 18")
# n = 11
# if(n%2 == 0):
# print("Even")
# else:
# print("odd")
#elif
# marks = int(input("Enter the marks:"))
# if(marks>=90):
# print("Excellent")
# elif(marks<90 and marks>=75):
# print("Very Good")
# elif(marks<75 and marks>=60):
# print("Good")
# else:
# print("Faield")
# del
# a=10
# b=12
# del a
# print(b)
# # a is no longer exist
# print(a)
#try, except
# a = 0
# try:
# b = 1/a
# except Exception as e:
# print(e)
# finally:
# print("Division is not possible")
# a=0
# b=5
# try:
# c = b/a
# print(c)
# except Exception as e:
# print(e)
# finally:
# print('Finally always executed')
#list
# list = [1,2,3,4,5]
# for i in list:
# print(i)
#while
# a = 0
# while (a < 5):
# print(a)
# a = a + 1
# import
# import math
# print(math.sqrt(30))
#as
# import calendar as cal
# print(cal.month_name[5])
#pass
# class my_class:
# pass
#
#
# def my_func():
# pass
#return
# def sum(a, b):
# c = a + b
# return c
#
#
# print("The sum is:", sum(25, 15))
#is
# x = 5
# y = 5
#
# a = []
# b = []
# print(x is y)
# print(a is b)
#
# for i in x:
# print(i)
# global
# def my_func():
# global a
# a = 10
# b = 20
# c = a + b
# print(c)
#
#
# my_func()
#
#
# def func():
# print(a)
#
#
# func()
# nonlocal
# def outside_function():
# a = 20
# def inside_function():
# nonlocal a
# a = 30
# print("Inner function: ",a)
# inside_function()
# print("Outer function: ",a)
# outside_function()
# lambda
# a = lambda x : x**2
# for i in range(1,6):
# print(a(i))
# yield
# def fun_Generator():
# yield 1
# yield 'Hello Coder'
# yield 'Hello Coder'
# yield 'Hello Coder'
# yield 'Hello Coder'
# yield 'Hello Coder'
# yield 'Hello Coder'
# yield 3
# yield 3
# yield 3
# yield 3
# Driver code to check above generator function
# for value in fun_Generator():
# print(value)
# with
# with open('file_path', 'w') as file:
# file.write('hello world !')
# None
def return_none():
a = 10
b = 20
c = a + b
x = return_none()
print(x) | true |
6c385f2f9920adc9ff2ce7599c59bd4c7c7e0f40 | Teinaki/dev-practicals | /04-practical/04-practical/q3.py | 954 | 4.21875 | 4 | # Use the Stack class from question 1 and the input function
# to reverse a string provided by a user.
class Stack:
def __init__(self):
self._stack = []
def push(self, item):
self._stack.append(item)
def pop(self):
return self._stack.pop()
def peek(self):
return self._stack[len(self._stack)-1]
def empty(self):
return self._stack == []
def size(self):
return len(self._stack)
def display(self):
""" This is not a standard stack method and is just
included here for convenience.
"""
print(self._stack)
def main():
stack = Stack()
print('Enter text to reverse: ')
user_input = input()
n = len(user_input)
for i in range(0,n,1):
stack.push(user_input[i])
reverse = ""
for i in range(0,n,1):
reverse += stack.pop()
print(reverse)
if __name__ == '__main__':
main() | true |
766e44ba8bd2eaa776b9733ad81644d2706b78a7 | Teinaki/dev-practicals | /13-practical/13-iterators/13-practical/q1.py | 1,018 | 4.34375 | 4 | # Answer the questions in the comments below.
lst = [1, 2, 3, 4, 5]
itr0 = iter(lst)
itr1 = iter(lst)
print(f'Are our list iterators the same?: {itr0 is itr1}')
# Explain the output of the print above.
#itr0 and itr1 are different objects so this output is false
itr2 = iter(itr1) # What if we call iter() on an Iterator?
print(f'Looking at repeated calls to iter(): {itr2 is itr1}')
# Explain the output of the print above.
#itr2 equals the same object as iter(itr1) so it is true
print('Some output from various calls to next():')
print(f'first next(itr0): {next(itr0)}')
print(f'second next(itr0): {next(itr0)}')
# The above calls to next() on itr0 don't effect the
# call to next on itr1 below. That's fine; it's what we
# generally expect.
print(f'next(itr1): {next(itr1)}')
print(f'next(itr2): {next(itr2)}')
# But the last call to next() on itr2 does seem to be effected
# by the previous call on itr1. Why?
# because itr2 is the same object as iter(itr1) so it will effect the same list iterator
| true |
2dff472e4e8e0a46cfe8476668ba217f655e593b | jasonsinger16/PFB2017_problemsets | /Python_probset2/ps2_7.py~ | 854 | 4.40625 | 4 | #!/usr/bin/env python3
# Tests a value given on the command line.
# Evaluates that value against a logical expression and reports whether the result of the logical test is True or False.
import sys
print('')
print('')
print("Testing if the value entered, " + sys.argv[1] + ", is True or Not True...")
print('')
if sys.argv[2] == "number":
if float(sys.argv[1]):
print("Value is considered True by Python3")
# elif float(sys.argv[1]):
# print("Value is considered True by Python3")
else:
print("Value is considered Not True (normally known as False) by Python3")
print('')
print('')
print('')
else:
if sys.argv[1]:
print("Value is considered True by Python3")
else:
print("Value is considered Not True (normally known as False) by Python3")
print('')
print('')
print('')
| true |
6b237e9eba2414a9a42e6eddae4b4b5d08088dbf | jasonsinger16/PFB2017_problemsets | /Python_probset2/ps2_8.py | 912 | 4.5625 | 5 | #!/usr/bin/env python
# Determines if a value
# 1) is positive or negative
# 2) if positive, is bigger or smaller than 50
# 3) if smaller than 50, is even or odd
# 4) if larger than 50, is divisible by 3.
# sys.argv[1]
import sys
num = int(sys.argv[1])
if ((abs(num) + num) > 0):
print("number is positive")
if num < 50:
print("number is smaller than 50")
if num%2 == 0:
print("number is even")
else:
print("number is odd")
elif num > 50:
print("number is larger than 50")
if num%3 == 0:
print("number is divisible by 3")
else:
print("number is not divisible by 3")
else:
print("number must be 50")
elif num == 0:
print ("number must be 0")
else:
print("number is negative")
if num%2 == 0:
print("number is even")
else:
print("number is odd")
| true |
d5e1985679fef8698c3303d28ddfe7b48d04b818 | willspencer16/hello_world | /loops_start.py | 1,372 | 4.21875 | 4 |
def main():
x = 0
# Defining a while loop:
while (x<5):
print(x)
x = x+1
# This will print x until its value is 5,
# as a while loop executes a block of code
# while a particular condition evaluates true.
# Defining a for loop:
for x in range(5, 10):
print(x)
# This prints numbers 5 to 9 as Python
# for loops are iterators and x represents the
# individual value within the range.
# Using a for loop over a collection:
days=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for d in days:
print(d)
# This prints each string (d) in the days array.
# Using a break statement:
for x in range(5, 10):
if (x==7): break
print(x)
# This prints 5 and 6, then terminates the
# loop as x equals 7.
# Using a continue statement:
for x in range(5, 10):
if (x % 2 == 0): continue
print(x)
# This prints 5, 7 and 9, as the continue
# statement only allows the print function to
# to come into play when x is divisible by 2.
# Using a loop with an index variable:
days=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for i,d in enumerate(days):
print(i, d)
# This prints the index of the member of the
# collection in question and the actual member.
if __name__ == "__main__":
main() | true |
16905befd1fe7f42381338bfce4458dd1ee0d9b4 | MrRobo-t/Python-assignment | /city_distance.py | 1,537 | 4.25 | 4 | from decimal import Decimal
from math import radians, sin, cos, sqrt, atan2
class DistanceMeasurement:
def city_distance(self, city1, city2):
'''
description: This function calculates differnce between latitudes and longitudes of 2 cities and returns an
output in KM with 2 decimal places. The R value denotes earth's radius in KMs
:param city1: Coordinates of first city
:param city2: Coordinates of second city
:return distance: difference in distance bewteen 2 cities in Km
'''
R = 6373.0
city1_coord = city1.split(",")
city2_coord = city2.split(",")
city1_lat = radians(Decimal(city1_coord[0].split(" ")[0]))
city1_long = radians(Decimal(city1_coord[1].strip().split(" ")[0]))
city2_lat = radians(Decimal(city2_coord[0].split(" ")[0]))
city2_long = radians(Decimal(city2_coord[1].strip().split(" ")[0]))
difference_lat = city2_lat - city1_lat
difference_long = city2_long - city1_long
a = sin(difference_lat / 2) ** 2 + cos(city1_lat) * cos(city2_lat) * sin(difference_long / 2) ** 2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
differnce_btw_cities = R * c
return round(differnce_btw_cities, 2)
city1 = "51.5074 N, 0.1278 W"
city2 = "48.8566 N, 2.3522 E"
dm = DistanceMeasurement()
print("City 1:" + str(city1))
print("City 2:" + str(city2))
print("City 1 and City 2 are " + str(dm.city_distance(city1, city2)) + " km apart") | true |
b917c614ed7b778bd5d28c3096e3dba0b4ac600c | Divya192/divyathoughts | /reverse writing.py | 889 | 4.375 | 4 | # Program to show various ways to
# read data from a file.
# Creating a file
file1 = open('geek.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
file1 = open('geek.txt', 'r+')
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(1)
print("Output of Readline function is ")
print(file1.readline())
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
print()
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
| true |
e456a0fb42733c86920aa236027efc7f4b7c33fa | rahulkanhirode/Python-Workshop | /all day exercises.py | 1,834 | 4.1875 | 4 | print("hello world!!")
n = -10
if n < 5:
print("n is less than five")
elif n == 5:
print("n is equal to five")
else:
print("n is greater than five")
n = 10
if n < 5:
print("n is less than five")
elif n == 5:
print("n is equal to five")
else:
print("n is greater than five")
n = 5
if n < 5:
print("n is less than five")
elif n == 5:
print("n is equal to five")
else:
print("n is greater than five")
import math
import random
pi = math.pi
print ("The Pi value is ", pi, "and the type is", type(pi))
i = 50
if i < 50:
print(" i is less than 50")
elif i >50:
print("i is greater than 50")
else:
print("i is equals to 50")
i = random.randint(0, 100)
if i < 50:
print("i is less than 50")
elif i >50:
print("i is greater than 50")
else:
print("i is equals to 50")
picked_fruit = random.choice(['orange', 'strawberry', 'banana'])
if picked_fruit == 'orange':
print("The fruit picked is ", picked_fruit, " and its colour is orange")
elif picked_fruit == 'strawberry':
print("The fruit picked is ", picked_fruit, " and its colour is red")
elif picked_fruit == 'banana':
print("The fruit picked is ", picked_fruit, " and its colour is yellow")
def mul_two_num (a,b):
c = a*b
return = c
mul_two_num()
print c
print("next")
n = -10
if n < 5:
print("n is less than five")
elif n == 5:
print("n is equal to five")
else:
print("n is greater than five")
print("next")
names = ["chris", "iftach", "jay"]
for name in names:
print(name)
print("next")
fruit_inventory = {"apples": 5, "pears": 2, "oranges": 9}
for fruit in fruit_inventory:
print(fruit)
print("next")
list(fruit_inventory.items())
[('oranges', 9), ('apples', 5), ('pears', 2)]
for fruit in fruit_inventory.items():
print(fruit)
print("next") | true |
f03ed656c48436c61eeb0ccb6cbe0a30ca11ea6e | gol3tron/ProjectEuler | /Problem9.py | 690 | 4.125 | 4 | #A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
#a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
import math
for b in range(5,1000):
for a in range(4,b):
test_c = math.sqrt(a**2 + b**2)
if (test_c%int(test_c)==0):
c = test_c
if (a + b + c == 1000):
solution = a*b*c
print("a is :"+str(a))
print("b is :"+str(b))
print("c is :"+str(c))
print("solution is :"+str(solution))
break
| true |
4c3f345d720e4988cba09d3413f48d77a820e7fa | rebecca-u/Python_tasks | /Task 1-Guess a number.py | 856 | 4.53125 | 5 | #this program will ask the user for their name and ask them to think of a random number.
import random #use the import random library to be able to use random numbers
myName = input("Hi! What is your name?") #this is the variable which is for the users name.
number = random.randint(1,10) #variable containing the random number
print("Well, " + myName + " I am thinking of a number between 1 and 10.")
guess = int(input("Can you guess the number I am thinking of?"))#user needs to guess a number and input it.
if guess == number:
print("Good job, "+ myName + "you are correct.") #if their guess is correct
else:
print("oh no! That is the wrong answer, " + myName +" better luck next time!")#if guess is wrong
#at the end the program will show what the correct number was.
print("The computer number was", number)
| true |
31cfbd631a36dec7bebba4bc4b1f1c3d16ee0815 | Polyhistor/Algorithms | /Numerial Algorithms/Rotate a 2D array.py | 350 | 4.21875 | 4 | # Rotating a 2d array by 90 degree
def array_rotator(arr, n):
new_arr = []
for i in reversed(range(n)):
for j in reversed(range(n)):
new_arr.append(arr[j][i])
return new_arr
arr = [[1,2,3],[4,5,6],[7,8,9]]
ans = array_rotator(arr,3)
ans2= [ans[x:x+3] for x in range(0,len(ans),3)]
ans2.reverse()
print(ans2)
| false |
6a6b2568a6678eefe99305d9d0f377f28406c962 | Polyhistor/Algorithms | /Linked-List/Selectionsort.py | 1,509 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = new_node
def display(self):
cur = self.head
list = []
while cur.next is not None:
cur = cur.next
list.append(cur.data)
return list
def append_first(self,data):
new_node = node(data)
new_node.next = self.head.next
self.head.next = new_node
def selectionsort(self, head):
new_list = linked_list()
while head.next is not None:
before_biggest = head
biggest = head.next
cur = head
while cur.next is not None:
if cur.next.data > biggest.data:
biggest = cur.next
before_biggest = cur
cur = cur.next
new_node = node(biggest.data)
new_list.append_first(new_node.data)
before_biggest.next = biggest.next
return new_list
new_list = linked_list()
new_list.append(1)
new_list.append(2)
new_list.append(4)
new_list.append(8)
new_list.append(1)
new_list.append(-5)
new_list.append(3)
ans = new_list.display()
# print(ans)
head = new_list.head
ans = new_list.selectionsort(head)
print(ans.display()) | false |
63c7c80e1642664c8a2a7cdb30602113ff776e80 | Akshay-Ruplag/Practice_Notebooks | /DP100/Python/92+-+Keyword+Arguments.py | 532 | 4.375 | 4 | # ---------------------------------------------------------------
# Keyword arguments in Python
#
# 1. Parameter names are used in the function call
# 2. The keys are mapped to the arguments
# 3. The position of the arguments does not matter
# ---------------------------------------------------------------
def myFunction(name, age):
print("My name is : ", name)
print("My age is : ", age)
return
myage = 27
myname = "John"
myFunction(age=myage, name=myname)
| true |
2d363632a3a4c949f0b00e52f55f169dbbf7c120 | AsherFor/TestTEst | /Binary-HexConverter.py | 2,028 | 4.375 | 4 | def converte_one (one_value):
# This loop uses functions built into python to demo decimal/hex/binary representations.
i = int(one_value)
print(" Decimal-----", i)
hex_string = hex((i))
hex_string_sliced = hex_string[2:]
print(" Hexadecimal-", hex_string_sliced.upper())
print(" | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |")
# this stores the var i as a string
binary_string = bin(i)
# formating the string to line up with line 21
binary_string_sliced =binary_string[2:]
while len(binary_string_sliced) < 8:
binary_string_sliced = str(0) + binary_string_sliced
print(binary_string_sliced.replace("", " | ")[1: -1])
print()
def converter0_256 ():
# This loop uses functions built into python to demo decimal/hex/binary representations.
for i in range (256):
print(" Decimal-----", i)
hex_string = hex((i))
hex_string_sliced = hex_string[2:]
print(" Hexadecimal-", hex_string_sliced.upper())
print(" | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |")
# this stores the var i as a string
binary_string = bin(i)
# formating the string to line up with line 21
binary_string_sliced =binary_string[2:]
while len(binary_string_sliced) < 8:
binary_string_sliced = str(0)+ binary_string_sliced
print(binary_string_sliced.replace("", " | ")[1: -1])
print()
def binary_hex():
# User inputs and function calls
print("This program will demonstrate Integer values 0-256, ")
print ("reperesented as Binary tables and Hexadecimal ")
print ("")
all_or_one = input("Convert Integer to HEX and Binary Y/N ?")
Run_all = ""
if all_or_one == "Y" or all_or_one == "y":
one_value = input("Convert an integer from 0-256 : ")
converte_one(one_value)
else:
Run_all = input("Show all 0-256 Hex and Binary values Y/N ?")
if Run_all == "Y" or Run_all == "y" :
converter0_256()
binary_hex()
| false |
682d9d535c4a91f62796637d3a8e59386fc25241 | reddymadhira111/Python | /programs/tuples.py | 1,853 | 4.5625 | 5 | '''
tuple=()
tuples are immutable
'''
#1. creating a tuple
t=(1,2,3.5,[1,2],'tmobile')
print(t)
print(type(t))
print(len(t))
#tuple() takes atmost one argument
print(tuple('bar'))
#tuple slicing
print(t[:3])
print(t[3][1])
#tuple operations
t1=t[0],t[2],t[3]
print(t1)
t3=(22,54,54,447)
print(max(t3))
print(min(t3))
print(t3.index(54)) #index()
print(t3.count(54)) #count()
a=1
b=3
a,b=b,a #swapping with tuple in one step
print(a,b)
for pair in enumerate(t3): #enumerate() :gives the pair of index and values
print(pair)
#1.concatination
t2=t+t1
print(t2)
#2.deleting
del t2
#3.cmp() method,python3 does not compare method
#operators:compares the first element in the tuple only
print((2,3)>(3,2))
print((3,4)>(2,99))
print((2,3)<=(3,4))
print((2,3)==(2,3))
#if tuple objects contain some mutable objects like list.we can change the mutable objects inside the tuple
t[3][1]=[3,4]
print(t)
#default collection type is tuple
x,y,z=1,2,3
print(x,y,z)
print(2,3<4,3)
#single element in a tuple
d=(1)
print(d,type(d)) #o/p: 1,int
d1=(1,)
print(d1,type(d1)) #o/p: 1,tuple
#example programs
#Write a Python program to create a tuple.
t=(1,2,3)
t1=tuple('123')
print(t,t1)
#Write a Python program to create a tuple with different data types
t=(1,1.2,[1,2],'str')
print(t)
#Write a Python program to count the elements in a list until an element is a tuple
l=[1,3,4,5,(6,),57]
c=0
for i in range(len(l)):
if type(l[i])==tuple:
print('touple found')
break
else:
c+=1
print(c)
#Write a Python program to sort a tuple by its float element.
t= [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
for i in range(len(t)):
if float(t[0][1])<float(t[1][1]):
t[0],t[1]=t[1],t[0]
elif float(t[0][1])<float(t[2][1]):
t[0],t[2]=t[2],t[0]
elif float(t[1][1])<float(t[2][1]):
t[1],t[2]=t[2],t[1]
print(t)
| true |
8bcfe68052d543c5ff85ba10f9828c0bd7c16c6d | bradpenney/learningPython | /IsOdd.py | 551 | 4.21875 | 4 | """
DetermineIfOdd Function
"""
# Determines if odd using modulo
def isOdd(num):
if (num % 2 == 0):
return "even"
if (num % 2 != 0):
return "odd"
# Gather input numbers from user
firstNum = int(input("Please enter a number: "))
secondNum = int(input("Please enter a number: "))
thirdNum = int(input("Please enter a number: "))
# Output results to user
print("\nThe first number is " + isOdd(firstNum))
print("The second number is " + isOdd(secondNum))
print("The third number is " + isOdd(thirdNum))
| true |
912124fed695bde9a2b24e50a01cf7be33c55e1c | mvits/Ejemplos-Python | /04_listas.py | 372 | 4.125 | 4 | l = [2,"tres",True,["uno",10]]
print (l)
l2 = l[1]
print (l2)
l3 = l[3][1]
print (l3)
l[2] = 123
print (l)
#Conteo
l4 = l[0:3]
print (l4)
#Salto
l5 = l[0:3:2]
print (l5)
#Salto y todos los elementos
l6 = l[1::2]
print (l6)
#Modificar Lista
l[0:2] = [4,3]
print (l)
l[0:2] = [4]
print (l)
# Acceder a la lista
l7 = l[-1]
l7 = l[-3]
print (l7) | false |
69a832759cb177e57156cde4aa7532176f71a5c8 | michaelzap94/mz-python | /Concurrency/Threads_Processes/6_queued_threads.py | 2,358 | 4.125 | 4 | # IF you want to execute operations sequentially -> don't use Threads, specially if modifying a Shared State
# IF you want to execute operations sequentially and use Threads -> Queuing system
import time, random, queue
from threading import Thread
counter = 0
# 2 Queues
job_queue = queue.Queue() # Things to be printed out
counter_queue = queue.Queue() # amounts by which to increase the counter
def increment_manager():
global counter
while True:
# Wait till item available and don't allow other Threads to run this
increment = counter_queue.get() # this waits until an item is available and locks the queue
time.sleep(random.random())
old_counter = counter
time.sleep(random.random())
counter = old_counter + increment # Increased counter
time.sleep(random.random())
# Add something to print to the job_queue
job_queue.put((f'New counter value {counter}', '------------'))
time.sleep(random.random())
counter_queue.task_done() # this unlocks the queue
def printer_manager():
while True:
# Wait till item available and don't allow other Threads to run this
for line in job_queue.get(): # this waits until an item is available and locks the queue
time.sleep(random.random())
print(line)
# this unlocks the queue
job_queue.task_done()
# printer_manager and increment_manager run continuously because of the `daemon` flag.
# daemon=True -> RUN forever along with Main Thread till some error
Thread(target=increment_manager, daemon=True).start()
Thread(target=printer_manager, daemon=True).start()
def increment_counter():
counter_queue.put(1)
time.sleep(random.random())
# Create 10 Threads-------------------------------------------------------
worker_threads = [Thread(target=increment_counter) for thread in range(10)]
# Start 10 Threads
for thread in worker_threads:
time.sleep(random.random())
thread.start()
# Now all Threads will run at the same time as the Main Thread,
# Therefore, we need to tell our Main Thread to wait for the new Threads to finish
# .join() -> make the Main thread wait for these Threads to finish
for thread in worker_threads:
thread.join()
# -------------------------------------------------------------------------
counter_queue.join() # wait for counter_queue to be empty to finish
job_queue.join() # wait for job_queue to be empty to finish | true |
4d7eb85696487513945bb83c56886942de137b23 | michaelzap94/mz-python | /OOP #2/multipleInheritance.py | 2,761 | 4.5625 | 5 | class Aquatic:
def __init__(self,name):
print("AQUATIC INIT!")
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self,name):
print("AMBULATORY INIT!")
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land!"
#THE FIRST CLASS WOULD HAVE PREFERENCE (from the MRO) AND ITS METHODS WILL BE USED in case another super class also has the same methods
# THE __init__ will call the FIRST CLASS(Ambulatory) only, as it has preference (from the MRO), HOWEVER. this class will still inherit the methods from SECOND CLASS(Aquatic)
class Penguin(Ambulatory, Aquatic):
def __init__(self,name):
print("PENGUIN INIT!")
super().__init__(name=name)
# IF we want to execute both __init__
# Ambulatory.__init__(self,name=name)
# Aquatic.__init__(self, name=name)
#=============================================================================
#MRO - ORDER in which classes have preference., 3 ways to find out:
print(Penguin.__mro__) # (<class '__main__.Penguin'>, <class '__main__.Ambulatory'>, <class '__main__.Aquatic'>, <class 'object'>)
print(Penguin.mro()) # [<class '__main__.Penguin'>, <class '__main__.Ambulatory'>, <class '__main__.Aquatic'>, <class 'object'>]
help(Penguin)
# Method resolution order:
# | Penguin
# | Ambulatory
# | Aquatic
# | builtins.object
#=============================================================================
jaws = Aquatic("Jaws")#AQUATIC INIT!
lassie = Ambulatory("Lassie")#AMBULATORY INIT!
captain_cook = Penguin("Captain Cook") #PENGUIN INIT!
#AMBULATORY INIT!
print(captain_cook.swim())#Captain Cook is swimming
print(captain_cook.walk())#Captain Cook is walking
print(captain_cook.greet())#I am Captain Cook of the land!
print(f"captain_cook is instance of Penguin: {isinstance(captain_cook, Penguin)}") #True
print(f"captain_cook is instance of Aquatic: {isinstance(captain_cook, Aquatic)}") #True
print(f"captain_cook is instance of Ambulatory: {isinstance(captain_cook, Ambulatory)}") #True
# jaws.swim() # 'Jaws is swimming'
# jaws.walk() # AttributeError: 'Aquatic' object has no attribute 'walk'
# jaws.greet() # 'I am Jaws of the sea!'
# lassie.swim() # AttributeError: 'Ambulatory' object has no attribute 'swim'
# lassie.walk() # 'Lassie is walking'
# lassie.greet() # 'I am Lassie of the land!'
# captain_cook.swim() # 'Captain Cook is swimming'
# captain_cook.walk() # 'Captain Cook is walking'
# captain_cook.greet() ##I am Captain Cook of the land!
| true |
7dc9e259d84f4354bc86539553ac65c6918ed789 | anyone21/Project-Euler | /gallery/Encryption-and-decryption/Problem-59/Problem-59.py | 2,425 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 18:23:23 2016
@author: wxt
"""
"""
Problem 59:
Each character on a computer is assigned a unique code and the preferred standard
is ASCII (American Standard Code for Information Interchange). For example,
uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII,
then XOR each byte with a given value, taken from a secret key. The advantage
with the XOR function is that using the same encryption key on the cipher text,
restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message,
and the key is made up of random bytes. The user would keep the encrypted message
and the encryption key in different locations, and without both "halves", it is
impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method
is to use a password as a key. If the password is shorter than the message, which
is likely, the key is repeated cyclically throughout the message. The balance
for this method is using a sufficiently long password key for security, but short
enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower case
characters. Using cipher.txt, a file containing the encrypted ASCII codes, and
the knowledge that the plain text must contain common English words, decrypt the
message and find the sum of the ASCII values in the original text.
"""
import itertools
from collections import Counter
def readcypher(filename):
with open(filename, 'r') as source:
data = source.readline().rstrip().split(',')
ascii = [int(s) for s in data]
return ascii
def decrypt(message, keylen, mostfreq = ' '):
"""
We'll decrypt the message using a simple frequency analysis.
"""
match = ord(mostfreq)
key = []
for i in xrange(keylen):
part = message[i::keylen]
c = Counter(part)
key.append(c.most_common(1)[0][0] ^ match)
ori = [m ^ k for m, k in itertools.izip(message, itertools.cycle(key))]
oritext = ''.join([chr(b) for b in ori])
return ''.join([chr(k) for k in key]), sum(ori), oritext
if __name__ == '__main__':
message = readcypher('p059_cipher.txt')
res = decrypt(message, 3) # ~651us
| true |
137fa04d36ce0d59c55b2b2929ca98d49a0ca752 | anyone21/Project-Euler | /gallery/Prime-number-related/Problem-41.py | 1,304 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 14:06:05 2016
@author: Xiaotao Wang
"""
"""
Problem 41:
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
# Here's is a trick to lower the upper bound
# A number is divisible by 3 if the digit sum of the number is divisible by 3.
# 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
# 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
# 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
import numpy as np
def findallprimes(maxnum):
Bool = np.ones(maxnum, dtype = bool)
Bool[0] = 0
maxiter = int(np.sqrt(maxnum))
for i in range(2, maxiter+1):
if Bool[i-1]:
# Sieve of Eratosthenes
Bool[np.arange(2*i-1, maxnum, i)] = False
return np.where(Bool)[0] + 1
def isPandigital(num):
digits = list(map(int, num))
digits.sort()
return digits == list(range(1, len(digits)+1))
def search(maxnum):
primeList = findallprimes(maxnum)
maxpan = 0
for i in primeList:
if isPandigital(str(i)):
if i > maxpan:
maxpan = i
return maxpan
if __name__ == '__main__':
print(search(7654321)) # ~3.86s
| true |
750c8d025c08d34589ecf0de1770d2d0248b8baa | naisanti/Batch17 | /Diccionarios.py | 1,521 | 4.375 | 4 | #se crea un diccionario con '{}', se divide mediante
#comas, se pueden agregar diccionarios en diccionarios y todo tipo
diccionario = { 'nombre': 'Carlos', 'edad' : 22, 'cursos':
['Python', 'Django']}
'''
print (diccionario)
print (diccionario['nombre']) #mandar llamar un elemento de la lista
print (diccionario['edad'])
#mandar llamar un elemento de la lista que esta dentro de un diccionario
print (diccionario['cursos'][0])
'''
#Otra forma de hacer diccionarios
dic = dict (nombre = 'Jorge', apellido = 'Sanchez', edad = 22)
print (dic)
print (dic['nombre'])
#Iterar en un diccionario
for key, value in diccionario.items():
print (key + ':' + str(value))
lista_cursos = diccionario ['cursos']
lista_cursos.append('Java')
print (lista_cursos)
print (diccionario)
#Número de elementos que tiene el diccionario
print (len(diccionario))
#Imprimir las llaves
print (diccionario.keys())
#Imoprimir valores
print (diccionario.values())
#Si no existe un valor, dame un valor por Default, que seria el que esta despues
#de la coma en este caso Juanito
print (diccionario.get("nombree", "Juanito"))
#Agregar elemento al diccionario con su clave : valor
diccionario['key']= 'value'
print (diccionario)
#eliminar un elemento, pero aqui no hay orden, por lo tanto se necesita poner cual quieres
#borrar
diccionario.pop('key')
print (diccionario)
#Duplicar diccionario
diccionario2 = diccionario.copy()
print (diccionario2)
#Añade elementos de un diccionario a otro
diccionario.update(dic)
print (diccionario)
| false |
bf4203ae62495651ab34d62b6cd6aecf3be4f524 | naisanti/Batch17 | /TrabajoEnClase2.py | 1,769 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
x = int (input ("ingresa un número entero X \n"))
y = int (input ("ingresa un número entero Y \n"))
n = int (input ("ingresa un número entero N \n"))
z = x % y
w = x - y
if z==0 :
print ("Es entero")
else :
print ("No es entero") #ej 1
if x > y :
print ("X es mayor")
elif x < y:
print ("Y es mayor")
else:
print ("Son iguales") #ej 2
if x > y :
print ("Pasaron " + str (w) + "años")
elif x < y:
print ("Faltan " + str (-w) + "años")
else:
print ("Estas en el año actual") #ej 3
if x > y > n:
print (str(x) + " es mayor que " + str (y) + " y mayor que " + str (n))
elif y > x > n:
print (str(y) + " es mayor que " + str(x) + " y mayor que " + str (n))
elif x > n > y:
print (str(x) + " es mayor que " + str (n) + " y mayor que " + str (y))
elif y > n > x:
print (str(y) + " es mayor que " + str(n) + " y mayor que " + str (x))
elif n > x > y:
print (str(n) + " es mayor que " + str(x) + " y mayor que " +str(y))
elif n > y > x:
print (str(n) + " es mayor que " + str(y) + " y mayor que " + str(x))
elif x == y == n:
print ("Son iguales")
else:
print ("vuelve a intentarlo perro") # ej 4
if x > y > n:
print (x)
elif y > x > n:
print (y)
elif x > n > y:
print (x)
elif y > n > x:
print (y) #agregar si son iguales en el ej 5 y el ejercicio extra
elif n > x > y:
print (n)
elif n > y > x:
print (n) # igaules 2
elif x == y == n:
print ("Son iguales")
else:
print ("vuelve a intentarlo perro") # ej 5
if (x > y and x > n):
print ("El numero mayor es " + str (x))
else:
if (y > x and y > n):
print ("El numero mayor es " + str (y))
else:
print ("El numero mayor es " + str (n))
| false |
d95ef179fd749757966d45b7d72b676041ffd601 | GiGiGan/python-git | /P59.py | 918 | 4.125 | 4 | # """This is the "P30.py" module,and it provides one function called
# print_lol() which prints lists that may or may not include nested lists."""
def print_lol(the_list, level):
# # This function takes a postional argument called "the_list", which is any
# # Python list(of, possibly, nested list.). Each data item in the provided list
# # is (recursively) printed to the screen on its owe line
# A second argument called "level" is used to insert tab-stops when a nested list is
# encountered.
# #選擇多行然後 command + / 就可以幫多行加#
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, leve+l)
else:
for tab_stop in range(level):
#通過LEVEL的值來控制使用的跳格數
print("t", end=")
#為縮排的美一層顯示一個TAB字母
print(each_item) | true |
a889c187691d2459dcc2fef56789cb4049034d0c | kbutler52/Teach2020 | /dic_add.py | 214 | 4.21875 | 4 |
list={'shop': 'fish', 'exercise': 'squats'}#dictionary- has a name and key
list['shop']='fruit'#this is how to add a item to a dictionary
things_todo=list['shop']#
print('I love to eat {}.' .format(things_todo))
| true |
13813940968bbf0905e75c7d3964e4983efb46a6 | kbutler52/Teach2020 | /ifColor.py | 401 | 4.28125 | 4 | #05-25-2020
blue = 10
red = 5
print(blue < red)#this will test check our if statement
print(not(blue < red))#this will check our elif statement
print(blue == red)#This will check our else statement
if (blue < red):#This will check our if statement
print(f"Blue is more that red {5}.")
elif(not(blue < red)):
print("Blue is %d more than red." %(5))
else:
print("Blue and Red are equal")
| true |
02caba71ef62369ed87ae84dba3591b150b90a84 | da-stoi/Polygon-Area-Calculator | /main.py | 1,407 | 4.25 | 4 | import math
#Getting your minimum, maximum, and side length.
min = input('What is the minimum # of sides?\n')
max = input('What is the maximum # of sides?\n')
sideLength = input('What is the side length?\n')
min = int(float(min))
max = int(float(max))
sideLength = int(sideLength)
if min < 3 :
print('Invalid minimum ammount. Must be greater than or equal to 3')
elif max < min :
print('Invalid maximum ammount. Must be greater than or equal to your minimum amount of',min)
elif sideLength <= 0 :
print ('Invalid side length. Must be greater than 0')
else :
print('Your minimum is:',min)
print('Your maximum is:',max)
print('Your side length is:',sideLength)
print ('Starting...')
for x in range(min, max+1):
singleAngleInt = ((x-2)*180)/x
singleAngleCenter = 180-singleAngleInt
singleTriangleHeight = ((sideLength/2)/(math.tan(math.radians(singleAngleCenter/2))))
halfSingleArea = ((sideLength/2)*(singleTriangleHeight))
totalArea = halfSingleArea*x
print ('~~~~~~~~~~~~~~~~~~~~~ ',x,'-gon ~~~~~~~~~~~~~~~~~~~~~')
print ('The interior angle of a',x,'-gon is: ',round(singleAngleInt, 2))
print ('The center angle of a',x,'-gon is: ',round(singleAngleCenter, 2))
print ('The total area of a',x,'-gon with a side length of',sideLength,'is: ', round(totalArea, 2))
print ('')
print ('~~~~~~~~~~~~~~~~~~~~~~-= End =-~~~~~~~~~~~~~~~~~~~~~~')
| true |
c2a4dec4087843d5f051dc53db41f912df7f3d22 | Peter-Abayomi/Python-Assignment-One | /check_numbers.py | 588 | 4.25 | 4 | def check_numbers(number):
if isinstance(number, list) == 0:
return "This is not a list"
if bool(number) is False:
return "The list is empty"
for item in number:
if not isinstance(item, int):
return "List contains no numbers"
number_list = []
for item in number:
if item % 2 == 0:
number_list.append(item)
return('There are no even numbers' if bool(number_list) is False else number_list)
list_of_number = [2, 3, 5, 7, 8, 4, 6, 12, 13, 14, 15, 16, 1, 17, 18, 20, 21]
print(check_numbers(list_of_number))
| true |
59c1ba1a7eaca1d052a194ea336f527e30d1225e | Braitiner/Exercicios-wiki.python | /EstruturaSequencial_Exercicio11.py | 703 | 4.34375 | 4 | # Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# o produto do dobro do primeiro com metade do segundo .
# a soma do triplo do primeiro com o terceiro.
# o terceiro elevado ao cubo.
n1 = int(input('Informe um número inteiro: '))
n2 = int(input('Informe um número inteiro: '))
n3 = float(input('Informe um número real: '))
equac1 = (n1**2) + (n2/2)
equac2 = (n1*3)+n3
equac3 = n3**3
print('O produto do dobro do primeiro número com metade do segundo número ={equac1}'
'\nA soma do triplo do primeiro número com o terceiro número ={equac2}'
'\nO terceiro número elevado ao cubo ={equac3}.'.format(equac1=equac1,equac2=equac2,equac3=equac3))
| false |
286435b219a1a5ff7b75fa1a756e8ffbf115c164 | Braitiner/Exercicios-wiki.python | /estrutura_de_repeticao_exercicio30.py | 696 | 4.125 | 4 | # O Sr. Manoel Joaquim acaba de adquirir uma panificadora e pretende implantar a metodologia da tabelinha, que já é um
# sucesso na sua loja de 1,99. Você foi contratado para desenvolver o programa que monta a tabela de preços de pães, de
# 1 até 50 pães, a partir do preço do pão informado pelo usuário, conforme o exemplo abaixo:
# Preço do pão: R$ 0.18
# Panificadora Pão de Ontem - Tabela de preços
# 1 - R$ 0.18
# 2 - R$ 0.36
# ...
# 50 - R$ 9.00
preco = float(input('Informe o preço do pão: R$ '))
print('_-'*15, '\nPanificadora Pão de Ontem', '\n', '_-'*15, '\nTabela de Preços', '\n', '_-'*15)
for c in range(1, 50 + 1):
print(f'{c:>3} - R$ {c*preco:>6.2f}')
| false |
34e6ce8b6794b8f640530a8cf7a448b5f5e7a4ae | sanjayjaras/DSC550 | /Week2/Exercise 3.1.1.py | 1,266 | 4.21875 | 4 | # Assignment 2.1
# Exercise 3.1.1
# Jaccard Similarities
# Author: Saurabh Biswas
# DSC550 T302
def Jaccard_Similarites(list1, list2):
'''
This function takes two list as input and calculates Jaccard Similarities
between them.
:param list1: set1
:param list2: set2
:return: Jaccard Similarity Value
'''
set1 = set(list1) # convert list1 into a set
set2 = set(list2) # convert list2 into a set
union1 = set.union(set1, set2) # get union of set1 and set2
intersection1 = set.intersection(set1, set2) # get intersection of set1 and set2
jac_sim_value = len(intersection1) / len(union1)
return jac_sim_value # return results
# invoke main program
if __name__ == '__main__':
# define three lists
list1 = [1,2,3,4]
list2 = [2,3,5,7]
list3 = [2,4,6]
js_12 = Jaccard_Similarites(list1, list2) # invoke the function
print('Jaccard similarities between set 1 and 2 is: {:.2f}'.format(js_12))
js_23 = Jaccard_Similarites(list2, list3) # invoke the function
print('Jaccard similarities between set 2 and 3 is: {:.2f}'.format(js_23))
js_13 = Jaccard_Similarites(list1, list3) # invoke the function
print('Jaccard similarities between set 1 and 3 is: {:.2f}'.format(js_13))
| true |
12fa6b7ec16cb610bf416ed88b7d42c8187435d1 | sanjayjaras/DSC550 | /Week2/Hypersphere Radius.py | 1,089 | 4.5 | 4 | # Assignment 2.1
# Hypersphere Radius
# Author: Saurabh Biswas
# DSC550 T302
# Import required libraries
import matplotlib.pyplot as plt
from scipy.special import gamma
from math import pi
def hs_plot(d):
'''This function accepts a list with dimensions and plot it against radius for volume 1'''
hyper_rad = [] # empty list to hold hypersphere radius
for n in d: # run a loop for d dimension to get a list of radius for unit volume
hyper_rad.append((((gamma(n/2+1))**(1/n))/pi**(1/2)*1**(1/2))) # hypersphere volume is 1
plt.plot(d, hyper_rad) # plot a graph between dimension and volume
plt.xlabel('Dimension') # x-axis label
plt.ylabel('Hypersphere Radius') # y-axis label
plt.title('Hypersphere Radius Plot') # Title of the graph
plt.show() # show the plot
# invoke main program
if __name__ == '__main__':
rad = [] # create an empty list of dimensions
for x in range(1, 101): # create a list of dimension from 1 to 100
rad.append(x)
hs_plot(rad) # invoke the function to plot dimension v/s radius graph
| true |
762040577475b57e0ce5d0c06098880f89285850 | lizzieturner/holbertonschool-low_level_programming | /0x1B-makefiles/5-island_perimeter.py | 892 | 4.1875 | 4 | #!/usr/bin/python3
""" Module 5-island_perimeter contains function island_perimeter """
def island_perimeter(grid):
"""
Finds perimeter of island described in grid
Args:
grid - list of list on integers
* 0 represents a water zone
* 1 represents a land zone
* one cell is a square with side length of 1
Return:
Perimeter of island
"""
count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
if i == 0 or grid[i - 1][j] == 0:
count += 1
if i == len(grid) - 1 or grid[i + 1][j] == 0:
count += 1
if j == 0 or grid[i][j - 1] == 0:
count += 1
if j == len(grid[i]) - 1 or grid[i][j + 1] == 0:
count += 1
return count
| false |
a015af7646623e48e2125af77ddf6b5255c45237 | yashbhujbal1/21-DAYS-PROGRAMMING-CHALLENGE-ACES | /linear_search day 9.py | 715 | 4.125 | 4 | #Linear search is a very simple search algorithm.
#In this type of search, a sequential search is made over all items one by one.
#Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the
#end of the data collection.
n=int(input("Enter the length of array: "))
print("Enter values in array : ")
a=[int(input()) for i in range(n)]
print("Array: ",a)
key=int(input("Enter the element to be search:" ))
found=0
for i in range(0,n):
if a[i]==key:
print("Element found at location:", i)
found=1
break
if not found:
print("Element not found")
#Time complexity : O(N)
#space complexity : O(n)
| true |
2c1d928944ea921b329db293c2550fba0df3dc6a | hufslion8th/Python-Basic | /Assignment1/chaewon-Lee/Chaewonlee.py | 605 | 4.21875 | 4 | # Max_weight = "최대 허용무게"
# Object1 = "첫번째 물건의 무게"
# Object2 : "두번째 물건의 무게"
# Current_Weight : "현재 허용무게"
#1번!!
Max_weight = 500
Object1 = float(input("첫번째 물건의 무게 : "))
Object2 = float(input("두번째 물건의 무게 : "))
Current_Weight = Max_weight - (Object1 + Object2)
print("현재 엘리베이터 허용 무게는 ", Current_Weight, "kg입니다.")
# print(num1-num2-num3)
#A =int(input("입력"))
print("■"*A)
#/rint("■ "*A)
#print("■ ■ ■ ■ ■"*A)
#address = "용인시 처인구 모현읍"
#print | false |
473e359211429c6e2694b561a095896025a224f6 | bseymour11/OneMonth-Python | /Week_1/math.py | 321 | 4.125 | 4 | # + plus
# - minus
# / divide
# * times
# ** exponentiation
# % modulo
# < less then
# > greater then
print("What is the answer to life, the universe, and everything?",
int((40+30-7)*2/3))
print()
print("Is it true that 5 * 2 > 3 * 4")
print(5*2 > 3*4)
print("What is 5 * 2?", 5 * 2)
print("What is 3 * 4?", 3 * 4) | false |
db3493b84f13ea17afef1083a47170c76a224055 | dp119/py_repo | /IntrvPrograms/JumpingOnTheClouds.py | 1,767 | 4.21875 | 4 |
# Jumping on the Clouds
# Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.
# Function Description
# Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.
# jumpingOnClouds has the following parameter(s):
# c: an array of binary integers
# Input Format
# The first line contains an integer n, the total number of clouds. The second line contains n space-separated binary integers describing clouds c[i] where 0 <= i < n.
# Sample Input 0
# 7
# 0 0 1 0 0 1 0
# Sample Output 0
# 4
# Explanation 0:
# Emma must avoid c[2] and c[5]. She can win the game with a minimum of 4 jumps
# Sample Input 1
# 6
# 0 0 0 0 1 0
# Sample Output 1
# 3
# Explanation 1:
# The only thundercloud to avoid is c[4]. Emma can win the game in 3 jumps
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
n = 7
c = [0, 0, 1, 0, 0, 1, 0]
def jumpingOnClouds(c):
counter = 0
x = 0
for i in c:
if x >= n-2:
counter = counter + 1
break
elif c[x+2] == 0:
counter = counter + 1
x = x + 2
if x == n-1:
break
else:
x = x + 1
counter = counter + 1
#print(x)
return counter
print(jumpingOnClouds(c))
| true |
a339f2d8e6df5127cee19537067d949107deda2a | ManaswiniKundeti/Python_Assignments | /OOP/pet.py | 828 | 4.28125 | 4 | #Class with attributes -- name : fluffy , species : dog
class Pet:
allowed_pets = ['cat','dog','fish','rabbit']
def __init__(self, name, species):
if species not in Pet.allowed_pets:
raise ValueError(f"You can't have a {species} pet!!")
self.name = name
self.speies = species
def set_species(self, species):
if species not in Pet.allowed_pets:
raise ValueError(f"You can't have a {species} pet!!")
self.species = species
cat = Pet("Blue","cat")
dog = Pet("Husky","dog")
# crocodile = Pet("Tony","crocodile")
print(cat.name)
# print(crocodile.species)
# we can change the dog species to tiger
# dog.species = "tiger" .... to stop the user from chnaging the species value to whatever he likes,
# we created a method called set species where the user can reset the species value only from the allowed values
| true |
7d94cd6d343ec526ca0c3841acd26c20af35a3f4 | Incapamentum/CHS-Programming | /2018-2019/Loops/loops.py | 1,420 | 4.3125 | 4 | # Created by Gustavo A. Diaz Galeas
#
# A programming assignment for the students enrolled in the AP CSP course
# at Colonial High School in Orlando, Florida.
#
# Purpose: To test the knowledge of students in the usage of for and while
# loops. Firstly, an infinite loop condition must be implemented using a while
# loop. Secondly, students are required to implement an iterative approach
# in finding the first 5 powers (i.e. first, second, third, etc) of a user
# inputted number. Thirdly, the program MUST keep a running count of the number
# of times a user inputs a number, exiting upon a certain condition.
#
# Initialization of counter that keeps track of number of times a user has
# entered something, not counting the exit condition
counter = 0
# Infinite loop condition
while 1:
n = input('Please enter a positive, non-zero number (enter -1 to exit): ')
# Condition to break out of the program
if n == -1:
print "The user has entered " + str(counter) + " numbers!"
print ""
dummy_input = raw_input('Press enter to end the program.')
break
# Increment counter to keep track of number of times the user has entered
# something
counter = counter + 1
# Condition to check for invalid inputs
if n <= 1:
print "Invalid input!"
print ""
continue
# Range -> 1, 2, 3, 4, 5
for x in range(1, 6):
power = n**x
print power
# Printing a newline.
print ""
| true |
07d551be573dccaf5ca763b1eb5845bea83069d4 | Incapamentum/CHS-Programming | /2018-2019/Fresh-Market-Markup/market_markup.py | 2,270 | 4.40625 | 4 | # Created by Gustavo A. Diaz Galeas
#
# A programming assignment for the students enrolled in the AP CSP course
# at Colonial High School in Orlando, Florida.
#
# Purpose: To further develop critical thinking skills in the creation of
# Python programs based on constraints and an end-result. Will test concepts
# already previously covered (loops), and provide new content to aid in the
# reinforcement of newly introduced data structures: lists and dictionaries
#
# Creating an inventory of items for the store using a dictionary data structure
inventory = {'milk': 2.99, 'bread': 3.00, 'egg': 0.09, 'chicken': 5.05, 'shrimp': 8.99, 'sirloin steak': 13.85}
# Creating an inventory list that contains all of the keys associated with the
# dictionary inventory
inventory_list = inventory.keys()
# Creating an empty list to be populated by user input
shopping_list = []
# Creating a total to keep a running total going
total = 0
# Welcome prompts
print "Welcome to Barg'n Shop!\n"
print "Here is our current inventory of items available to our shoppers: "
# Will print the items within the dictionary
for k, v in inventory.iteritems():
print str(k) + ": " + "$%.2f" % (v)
# Will populate the empty shopping list. Also contains conditional satements to
# check what the shopper would like to do.
while 1:
shopper_input = raw_input('\nWhat would you like to buy? (Type \'exit\' to checkout / Type \'cart\' to peak at your cart) ')
if (shopper_input == 'exit'):
break
elif (shopper_input == 'cart'):
print "Here is your cart: " + str(shopping_list)
continue
elif (not inventory.has_key(shopper_input)):
print "Sorry! Seems we do not have that item in stock."
continue
else:
shopping_list.append(shopper_input)
print "The " + shopper_input + " was successfully added to your cart!"
# Prompt to determine if the shopper has placed anything in their cart or not.
if (len(shopping_list) == 0):
print "\nThanks for dropping by!"
else:
print "\nCalculating your total!"
for x in range(len(shopping_list)):
total += inventory[shopping_list[x]]
print "Your total is: " + str(total) + "!"
print "Thank you for shopping with us!"
print ""
dummy_input = raw_input('Please press enter to exit.')
| true |
b4c72039a28ad24f722be824d3febc567e7e45f8 | CodeKul/Python-Weekend-11am-1pm-Sep-2019 | /PolyMorphism.py | 848 | 4.15625 | 4 | class SuperClass:
def __init__(self, a):
self.a = a
def display(self):
print("a:", self.a)
class Sub1(SuperClass):
def __init__(self, a, a1):
SuperClass.__init__(self, a)
self.a1 = a1
def display(self):
SuperClass.display(self)
print('a1:', self.a1)
def addValue(self, val):
self.a += val
self.a1 += val
class Sub2(SuperClass):
def __init__(self, a, a2):
SuperClass.__init__(self, a)
self.a2 = a2
def display(self):
SuperClass.display(self)
print('a2:', self.a2)
def addValue(self, val):
self.a += val
self.a2 += val
def add30(obj):
obj.addValue(30)
obj1 = Sub1(10, 100)
obj2 = Sub2(20, 200)
obj1.display()
obj2.display()
add30(obj1)
add30(obj2)
obj1.display()
obj2.display()
| false |
ec83ffcd0efd38898588a57cc6e254cb718d6663 | anirudh1666/Python | /Algorithms/Sorting/insertion_sort.py | 655 | 4.34375 | 4 | # Made by Anirudh Lakra
# Insertion sort.
# @params: array to sort and size of the array.
def insertion_sort(array, size):
for i in range(1, size):
key = array[i]
j = i - 1
# Until you reach start element or find element
# that is smaller than key. Insert key after smallest.
while j >= 0 and key < array[j]:
array[j+1] = array[j]
j -= 1
array[j+1] = key
def test_insertion_sort():
my_array = [0,-23,9,321,23.57,2]
size = 6
print("Unsorted: " + str(my_array))
insertion_sort(my_array, size)
print("Sorted: " + str(my_array))
test_insertion_sort()
| true |
d447d66e5266c59707907938d6ea81a61aacee73 | Vith-MCB/Phyton---Curso-em-Video | /Cursoemvideo/Exercícios/exer17 - Triangulo Retângulo.py | 532 | 4.125 | 4 | import math
#Primeira forma de resolver
"""c1 = float(input('Comprimento prim. cateto: '))
c2 = float(input('Comprimento seg. cateto: '))
hip = math.sqrt(c1**2+c2**2)
print('O comprimento da hipotenusa de um triângulo ret. com catetos {} e {} resulta: {:.2f}'.format(c1,c2,hip)"""
#Usando math.hypot
c1 = float(input('Comprimento prim. cateto: '))
c2 = float(input('Comprimento seg. cateto: '))
hp = math.hypot(c1, c2)
print('O comprimento da hipotenusa de um triângulo ret. com catetos {} e {} resulta: {:.2f}'.format(c1,c2,hp))
| false |
24895badcd030dfb45853f35b2f5b4bec2a38893 | Vith-MCB/Phyton---Curso-em-Video | /Cursoemvideo/Exercícios UFV/Lista 2/exer15 - Dia da semana.py | 734 | 4.125 | 4 | '''
num = int(input('Informe um número de 1 a 7: '))
if num > 7 or num <= 0:
print('Dia da semana inválido!')
else:
lista = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabado']
if lista[num-1] == 'Domingo' or lista[num-1] == 'Sabado':
print(lista[num-1])
else:
print('{}-Feira'.format(lista[num - 1]))
'''
num = int(input('Informe um número de 1 a 7: '))
if num > 7 or num <= 0:
print('Dia da semana inválido!')
if num == 1:
print('Domigo')
if num == 2:
print('Segunda-Feira')
if num == 3:
print('Terça-Feira')
if num == 4:
print('Quarta-Feira')
if num == 5:
print('Quinta-Feira')
if num == 6:
print('Sexta-Feira')
if num == 7:
print('Sábado')
| false |
9ac7e3940bc5bce4913b352f994e8519a02715eb | gcardosov/PythonAprendeOrg | /MateFin.py | 2,447 | 4.34375 | 4 |
"""Programa para hacer calculos financieros
1) Interes simple
2) Interes compuesto
3) Ecuaciones de valores equivalentes
4) Tasa efectiva
5) Tasas equivalentes
6) Anualidades simple ordinarias
7) Anualidades anticipadas simples
8) Tablas de amortizacion
9) Fondos de amortizacion
10) Salir
"""
i = True
ii = True
Si = True
No = False
#InteresSimple
def InteresSimple():
print "Puedes calcular monto, capital y el interes"
while i == True:
operacion == input ("\nCual quieres calcular? \n1)Monto \n2)Capital \n3)Interes\n")
if operacion == 1:
capital = input("Ingresa el valor del capital\n")
tiempo = input("Elige el tiempo en: \n1)Dias \n2)Semanas \n3)Meses\n4)anos\n")
if tiempo == 1:
CantidadTiempo = input("Ingresa la cantidad de dias:\n")
elif tiempo == 2:
CantidadTiempo = input("Ingresa la cantidad de semanas:\n")
elif tiempo ==3:
CantidadTiempo = input("Ingresa la cantidad de meses:\n")
elif tiempo == 4:
CantidadTiempo = input("Ingresa la cantidad de anos:\n")
else:
interes = input ("Ingresa el valor de la tasa de interes\n")
capitalizacion = input ("Cada cuanto es capitalizable: \n1)Dias \n2)Semanas \n3)Meses\n4)anos\n")
if capitalizacion == 1:
CantidadTiempo = input("\nIngresa la cantidad de dias")
elif capitalizacion == 2:
CantidadTiempo = input("\nIngresa la cantidad de semanas:\n")
elif capitalizacion ==3:
CantidadTiempo = input("Ingresa la cantidad de meses")
elif capitalizacion == 4:
CantidadTiempo = input("Ingresa la cantidad de anos")
#
print "\n*********Programa para hacer calculos financieros*********\n"
while i == True:
operacion = input("Elige la operacion que deseas hacer: \n1) Interes simple \n2) Interes compuesto \n3) Ecuaciones de valores equivalentes \n4) Tasa efectiva \n5) Tasas equivalentes \n6) Anualidades simples ordinarias \n7) Anualidades anticipadas simples \n8) Tablas de amortizacion \n9) Fondos de amortizacion \n10) Salir\n ")
if operacion == 1:
InteresSimple()
else:
print "Ingresa una opcion valida"
i = input("\nQuieres hacer otra operacion? \nSi \nNo\n ")
| false |
573ceb2316d6a327f4b13a64181965b50cd464ff | dobori/pallida-exam-basics | /uniquechars/unique_chars.py | 877 | 4.125 | 4 | # Create a function called `unique_characters` that takes a string as parameter
# and returns a list with the unique letters of the given string
# Create basic unit tests for it with at least 3 different test cases
# print(unique_characters("anagram"))
# Should print out:
# ["n", "g", "r", "m"]
def unique_characters(word):
try:
list_of_chars = []
if word == None:
word = 0
for letter in word:
if letter not in list_of_chars:
list_of_chars.append(letter)
elif letter in list_of_chars:
must_deleting = []
must_deleting.append(letter)
for deleting_letter in must_deleting:
if deleting_letter in list_of_chars:
list_of_chars.remove(deleting_letter)
return list_of_chars
except Exception:
return False
| true |
52bf98acce655591a19a634f0ff5825b0bf685d4 | alymithani/py-rsa | /code/rsa_demonstration.py | 1,973 | 4.375 | 4 | import rsa
import symmetric_cipher
def main():
print('Keys are generated using a prime integer pair. Enter a range to generate primes.')
min = int(input('Min: '))
max = int(input('Max: '))
p,q = rsa.random_prime(min,max), rsa.random_prime(min,max)
print('p and q values: ' + str(p) + ', ' + str(q))
print('Key pairs generating...')
public_key, private_key = rsa.generate_key(p,q)
print('Public key: ' + str(public_key))
print('Private key: ' + str(private_key))
print('The public key can only encrypt values, whereas the private key can only decrypt values.')
print('To send an encrypted message, an integer key can be used which would then be encrypted using the public key and sent with the message.')
print('Note: the integer key must have a value less than n, the product of p and q.')
key = symmetric_cipher.generate_random_key(public_key[0])
print('For example: let the key be: ' + str(key))
message = input('Enter a message to encrypt: ')
encrypted_message = symmetric_cipher.encrypt_string(message,key)
print('This message would be encrypted as "' + encrypted_message + '" using our key.')
print('Next, this integer key can be used with the RSA encryption scheme using th public key.')
encrypted_key = rsa.encrypt(key,public_key)
print('The key ' + str(key) + ' encrypted using the public key is ' + str(encrypted_key) + '.')
print ('This encrypted key and the encrypted message can be sent to the owner of the private key safely')
print('')
print('The owner of the private key can use it to decrypt the encypted key, and then use it on the cipher text:')
unencrypted_key = rsa.decrypt(encrypted_key,private_key)
print('Unencrypted key: ' + str(unencrypted_key) + '.')
Unencrypted_message = symmetric_cipher.decrypt_string(encrypted_message,unencrypted_key)
print('Unencrypted message: ' + Unencrypted_message + '.')
if __name__ == "__main__":
main()
| true |
f2bc3317fd42ac7a35c795c1edf56e3a68068fcb | amymhaddad/solve_it | /daily_coding_problem/string_mapping/string_mapping.py | 532 | 4.21875 | 4 | """
Determine whether there exists a one-to-one character mapping from one string s1 to another s2.
For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.
Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.
"""
s1 = "foo"
s2 = "bar"
def string_mapping(s1, s2):
if len(s1) != len(s2):
return False
set_length_s1 = len(set(s1))
set_length_s2 = len(set(s2))
return set_length_s1 == set_length_s2
print(string_mapping(s1, s2))
| true |
191b9919b14b2f12cb1613327e790e4639c3d941 | amymhaddad/solve_it | /oop/class_attributes/loan.py | 824 | 4.1875 | 4 | """
Create a Loan class. Each time someone creates a new Loan, it's
for a certain amount of money. That money is taken from the
bank's available assets.
l1 = Loan(500)
l2 = Loan(200)
l3 = Loan(700) # raises an exception -- ValueError to indicate no money
l1.repay(500)
l3 = Loan(700) # now it'll work, because the bank has sufficient funds
"""
class Loan(object):
bank_assets = 1000
def __init__(self, amount):
if Loan.bank_assets >= amount:
self.amount_owed = amount
Loan.bank_assets -= amount
else:
raise ValueError("Not enough money")
def repay(self, repay_amount):
self.amount_owed -= repay_amount
Loan.bank_assets += repay_amount
l1 = Loan(500)
l2 = Loan(200)
l1.repay(500)
print(Loan.bank_assets)
| true |
f40d4cbdf30b4025c3ab6bd5e91b39fba7a33496 | amymhaddad/solve_it | /leetcode/min_cost_climbing_stairs/min_cost_climbing_stairs.py | 907 | 4.1875 | 4 | """
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
"""
def min_cost_climb_stairs(cost):
len_costs = len(cost)
if len_costs == 1:
return cost[0]
total_counts = [0] * len_costs
total_counts[-1] = cost[-1]
total_counts[-2] = cost[-2]
for i in range(len_costs - 3, -1, -1):
total_counts[i] = min(
cost[i] + total_counts[i + 2], cost[i] + total_counts[i + 1],
)
if total_counts[0] > total_counts[1]:
return total_counts[1]
else:
return total_counts[0]
| true |
28f4f5ec84ee04948f2eb492bae9be1712ec1e4e | amymhaddad/solve_it | /bradfield/linear_ds/queue_as_stack.py | 904 | 4.25 | 4 | """
Implement a queue using stacks.Although this problem might seem contrived, implementing a queue using stacks is actually a common strategy in functional programming languages (such as Haskell or Standard ML) where stacks are much more convenient to implement “from scratch” than queues. Your solution should have the same interface as the queue implementation in algos, but use stacks instead of a list in the implementation.
"""
from stack import Stack
item = 1
class QueueAsStack(object):
def __init__(self):
self.s1 = Stack()
self.s2 = Stack()
def enqueue(self, item):
self.s1.push(item)
def dequeue(self):
if self.s2.is_empty():
while not self.s1.is_empty():
last_item = self.s1.pop()
self.s2.push(last_item)
return self.s2.pop()
q1 = QueueAsStack()
q1.enqueue(item)
print(q1.dequeue())
| true |
80a7b3c4fe4ec0051cce67b74e0e44d727f37e22 | amymhaddad/solve_it | /oop/defining_class_exercises/person_class.py | 749 | 4.28125 | 4 | """
Person class -- name, e-mail address, and phone number
Create several people, and iterate over them in a list
and print their names (similar to a phone book)
Change the e-mail address of one person, and show
that it has changed by printing your list a second time
"""
class Person:
def __init__(self, name, email, phone_number):
self.name = name
self.email = email
self.phone_number = phone_number
p1 = Person("bob", "bob@example.com", "123-45-6789")
p2 = Person("henry", "henry@example.com", "333-44-8989")
p3 = Person("jerry", "jerry@example.com", "121-55-6789")
all_people = [p1, p2, p3]
for person in all_people:
print(f"{person.name}")
p2.email = "henry_james@example.com"
for person in all_people:
print(f"{person.name}: {person.email}")
| true |
f3b89507867637eff996e731d74bdc8a6d790c32 | amymhaddad/solve_it | /reuven_lerner_problems/advanced_python_functions/exercise4.py | 1,194 | 4.40625 | 4 | """
(1) Write a function (make_pw_function) that takes a string of characters.
It'll return a function that takes an integer as input. When the
returned function is invoked, it returns a string composed of randomly
selected characters from the string, of the selected length.
For example:
alpha_pw_maker = make_pw_function('abcde')
symbol_pw_maker = make_pw_function('!@#$%')
print(alpha_pw_maker(5)) # returns 5-character password
print(alpha_pw_maker(10)) # returns 10-character password
print(symbol_pw_maker(5)) # returns 5-character password
print(symbol_pw_maker(10)) # returns 10-character password
"""
import random
def make_pw_function(chars):
def make_pw(number):
output = ""
for i in range(number):
output += random.choice(chars)
return output
return make_pw
alpha_pw_maker = make_pw_function("abcde")
symbol_pw_maker = make_pw_function("!@#$%")
print(alpha_pw_maker(5)) # returns 5-character password
print(alpha_pw_maker(10)) # returns 10-character password
print(symbol_pw_maker(5)) # returns 5-character password
print(symbol_pw_maker(10)) # returns 10-character password}}
| true |
bb879680baa5627cd70de7ea2a7b9e2ccec98363 | amymhaddad/solve_it | /leetcode/chars_odd_counts/chars_odd_counts.py | 446 | 4.21875 | 4 | """
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
"""
def generate_string(n):
if n == 1:
return "a"
elif n == 2:
return "ab"
elif n % 2 != 0:
return n * "a"
else:
return (n - 1) * "a" + "b"
| true |
b584c06c8081ca37370a1514a7a68d45d1f20973 | amymhaddad/solve_it | /reuven_lerner_problems/advanced_python_functions/exercise3.py | 1,316 | 4.3125 | 4 | """
(1) Write a function ("report_card") that produces a generic report
card for a student. (The return value will be a string that can be
printed for all to see.) The function will take one mandatory
positional argument, the name of the student.
The keyword arguments will represent the names of the different
courses that the student has taken. Each course will have a
different name, and the value associated with each keyword
argument will be the student's grade.
The returned string should print the name of the student, as well
as courses they took, individual grades in those courses, and then
their average grade.
For example, invoking:
report_card('Eve', English=95, Math=90, History=75, Science=86)
will return a string like the following:
Eve:
English 95
Math 90
History 75
Science 86
Average 86.5
Note that you don't need the formatting to look just like this.
"""
def report_card(name, **kwargs):
total = 0
result = ""
result += f"{name}:\n"
for k, v in kwargs.items():
result += f"\t{k:<10} {v}\n"
total += int(v)
result += f"\tAverage {total / len(kwargs)}"
return result
print(report_card("Eve", English=95, Math=90, History=75, Science=86))
| true |
be06e7e1c9d9f318edc6be4928553549d835fc9a | amymhaddad/solve_it | /leetcode/attendance/attendance.py | 1,033 | 4.15625 | 4 | """
You are given a string representing an attendance record for a student. The record only contains the following three characters:
'A' : Absent.
'L' : Late.
'P' : Present.
A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).
You need to return whether the student could be rewarded according to his attendance record.
Example 1:
Input: "PPALLP"
Output: True
"""
def check_record(record):
A = 0
left_ptr = 0
while left_ptr < len(record):
if record[left_ptr] == "P":
left_ptr += 1
continue
if record[left_ptr] == "A":
A += 1
if A > 1:
return False
left_ptr += 1
continue
rt_ptr = left_ptr
while rt_ptr < len(record) and record[rt_ptr] == "L":
rt_ptr += 1
total_absences = rt_ptr - left_ptr
if total_absences > 2:
return False
left_ptr = rt_ptr
return True
| true |
a77d882dd60a4019c2812e472e93a4af988117d0 | Hououin47/intro_python | /week_3/rabbit.py | 730 | 4.125 | 4 | '''method that assembles and prints the 'ascii-art' '''
def print_pic():
# define most used shapes for easy of typing out (spaces not included)
l_ear = '(\\'
r_ear = '/)'
face_1 = "( '')"
face_2 = '(,, )'
foot = '(")'
face_3 = "(\\'.'/)"
face_4 = '(" )'
# create F-string to print out. broken up in each line for ease of reading
pic = F" {l_ear}\\ {l_ear}{r_ear}""\n"
pic += F" {face_1} {l_ear}_{r_ear} {face_2} /{r_ear}" "\n" "\n"
pic += F"O{foot}{foot} {face_3} {foot*2}O {face_4}" "\n" "\n"
pic += F" {foot}_{foot} ()()o"
print(pic)
''' main method to run '''
def main():
print_pic()
if __name__ == '__main__':
main()
| true |
42c079fe21a0aa10733579b2c6f71423f63c0397 | Hououin47/intro_python | /week_2/perimeter.py | 1,003 | 4.15625 | 4 | def get_vals():
h1 = float(input("Enter height 1: "))
h2 = float(input("Enter height 2: "))
w1 = float(input("enter width 1: "))
w2 = float(input("Enter width 2: "))
price = float(input("Enter price per meter: "))
return (h1, h2, w1, w2, price)
def print_info(length, cost):
msg = F"The total fence required = {length:.2f} meters." "\n"
msg += F"The total price = R {cost:.2f}"
print(msg)
def calc(h1, w1, w2, price):
#because the outer lines add up to (h1-h2) the expression cancels h2 out
'''
h1 + w1 + x + w2 + h2 + w2 + x + w1
h1 + 2*w1 + 2*w2 + 2*x + h2
~let 2*x = (h1-h2)
h1 + 2*w1 + 2*w2 + (h1 - h2) + h2
2*h1 +2*w1 + 2*w2
2*(h1 + w1 + w2)
'''
length = 2*(h1+w1+w2)
cost = length*price
return length, cost
def main():
h1, h2, w1, w2, price = get_vals()
length, cost = calc(h1, w1, w2, price)
print_info(length, cost)
if __name__ == '__main__':
main()
| false |
0764c48b58aafcc8d3f114c9198f91d80b4b0b92 | Hououin47/intro_python | /week_2/exponent.py | 772 | 4.15625 | 4 | ''' CHEAT WAY call pow(a,b)'''
def exponent(a, b):
output = 1
for i in range(b):
output *= a
return output
def main():
base = None
power = None
while base == None:
base = input("please enter the base number: ")
if not str.isdigit(base):
base = None
print("Please onlt enter numbers")
else:
base = int(base)
while power == None:
power = input("please enter the power number: ")
if not str.isdigit(power):
power = None
print("Please onlt enter numbers")
else:
power = int(power)
ans = exponent(base, power)
print(F"{base} to the power of {power} is equal to {ans}")
if __name__ == '__main__':
main()
| true |
ab31dcbf0c0b53e40b1cf50807962aebb2cf05e1 | SubhamoySengupta/ds-python | /circularQueue/CircularQueue.py | 2,088 | 4.15625 | 4 | """ FIFO implementation of cicularQueue using circular linked list ADT
Methods for a queue Q are:
1. Q.enqueue(e) -- Add element e at the back of Q
2. Q.dequeue() -- Remove and return the final element from Q
3. Q.is_empty() -- Check if the queue Q is empty
4. Q.first() -- Return the first element of Q
4. len(Q) -- Return the length of Q
5. rotate() -- Rotate front element to the back of queue
"""
class CircularQueue:
"FIFO implementation of Circular Queue using circular linked list ADT"
"""~~~~~~~~~~~~~~~~~~~~ Linked List Node class ~~~~~~~~~~~~~~~~~~~~"""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next'
def __init__(self, element, next):
self._element = element
self._next = next
"""~~~~~~~~~~~~~~~~~~~~ Circular Queue Methods ~~~~~~~~~~~~~~~~~~~~"""
def __init__(self):
"""Initialize an empty circular queue"""
self._tail = None
self._size = 0
def __len__(self):
"""Return length of queue"""
return self._size
def is_empty(self):
"""Return True if queue is empty"""
return self._size == 0
def first(self):
"""
Return (but donot remove) the first element of the queue
Raise an execption if queue is empty
"""
if self.is_empty():
raise Empty('Queue is empty')
head = self._tail._next
return head._element
def dequeue(self):
"""
Remove and return the first element of the queue
Raise an execption if queue is empty
"""
if self.is_empty():
raise Empty('Queue is empty')
old_head = self._tail._next
if self._size == 1:
self._tail = None
else:
self._tail._next = old_head._next
self._size -= 1
return old_head._element
def enqueue(self, e):
""" Add an element to the back of queue"""
newest = self._Node(e, None)
if self.is_empty():
newest._next = newest
else:
newest._next = self._tail._next
self._tail._next = newest
self._tail = newest
self._size += 1
def rotate(self):
"""Rotate front element to the back of queue"""
if self._size > 0:
self._tail = self._tail._next
| true |
552331df54f68b7724cca8c90261a36a4129de83 | nelsonfigueroa/caesar-cipher-bruteforce | /shifter.py | 1,490 | 4.40625 | 4 | #Script to perform shift substitutions
textfile = input("Enter filename: ")
fh = open(textfile, "r") #read file
fh.seek(0)
#Read from file and save each line to array
lines = []
for line in fh:
line_array = line.split("\n")
lines.append(line_array[0]) #Add to lines[]
#print(line_array[0]) #Testing
fh.close()
#Open output file to save shifted texts
textfile = input("Enter filename to save shifted plaintexts: ")
fh = open(textfile, "w") #write to file
fh.seek(0)
#Initialize string to store shifted strings
shifted = ""
#Loop to go through each line in lines[] list
for line in lines:
print("Original: \n" + line)
#print(ord('Z')) #Testing
#print(chr((ord('Z') -25))) #Testing
#Split line into characters for easier shifting
letters = list(line)
#Loop to shift line by up to 25
for i in range(1, 26):
print("Shifting by..." + str(i)) #Testing
#Loop to go through each letter in each line and shift
for character in letters:
#Shift each letter and append to shifted string
if (ord(character) + i) > 90:
shifted += chr(ord(character) + i - 26) #make it A by subtracting 26
else:
shifted += chr(ord(character) + i)
#print(shifted) #Testing
#Save string to file
fh.write(shifted + "\n")
#Clear string for next iteration
shifted = ""
#answ = input("Press enter for next shift.") #Optional
fh.close()
| true |
28d8aeb9b3885cb1f2d7cfb4cbd51ea99c07b0a1 | dipakdash/python | /calendar_month.py | 397 | 4.40625 | 4 | # Write a Python program to print the calendar of a given month and year.
import calendar
month_list = {'january':1, 'february':2, 'march':3, 'april':4, 'may':5, 'june':6, 'july':7, 'august':8, 'september':9, 'october':10, 'november':11, 'december':12}
y = int(raw_input("Enter Calendar Year: ").strip())
m = int(raw_input("Enter Calendar Month (1 to 12): ").strip())
print calendar.month(y, m) | true |
a6d01b40ed6eeb49db52bda5d867ff310ff0b53e | dipakdash/python | /python_socratica/07_if_elif_else.py | 278 | 4.4375 | 4 | #!/usr/bin/python3
string = input("Enter a string of length 6: ")
if(len(string)<6):
print("Entered string length is less than 6.")
elif(len(string)>6):
print("Entered string length is more than 6.")
else:
print("Good. You entered a string exactly of length 6..")
| true |
b6fd1adba2b958a580e8dc1396b8ae4adfb0b8a8 | dipakdash/python | /practice1/yield_prime_number.py | 1,031 | 4.25 | 4 | #!/usr/bin/python
def list_primes(num):
for n in range(1, num+1):
if(len(list(list_factors(n))) == 2):
yield(n)
def list_factors(num):
for n in range(1, num+1):
if (num % n) == 0:
yield(n)
def get_next_prime(num):
num = num + 1
while(len(list(list_factors(num))) != 2):
num = num + 1
return num
def generate_primes(count):
primes = []
prime_temp = 2
if (count == 0):
return []
elif (count == 1):
return [2]
else:
while(len(primes) != count):
primes.append(prime_temp)
temp = get_next_prime(prime_temp)
prime_temp = temp
return(primes)
if __name__ == "__main__":
print(list(list_primes(int(input("List all prime numbers between (1, num). Enter a number: ")))))
print(get_next_prime(int(input("Given a number find the next prime number. Enter a number: "))))
print(generate_primes(int(input("Given a number n generate first n prime numbers. Enter a number: "))))
| true |
47c32b2961b6b89d5b122c1ae4b20630ee8d7b65 | GSantos23/Crash_Course | /Chapter4/Exercises/ex4_11.py | 1,188 | 4.71875 | 5 | # Exercise 4.11
"""
My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
(page 60). Make a copy of the list of pizzas, and call it friend_pizzas .
Then, do the following:
• Add a new pizza to the original list.
• Add a different pizza to the list friend_pizzas .
• Prove that you have two separate lists. Print the message, My favorite
pizzas are:, and then use a for loop to print the first list. Print the message,
My friend’s favorite pizzas are:, and then use a for loop to print the sec-
ond list. Make sure each new pizza is stored in the appropriate list.
"""
pizza_types = ['Pepperoni', 'Veggie', 'Meat']
message = " Pizza, is delicious"
for favorite in pizza_types:
print(favorite + message)
print("I really love pizza")
print()
friend_pizzas = pizza_types[:]
print(friend_pizzas)
# Add new pizza to pizza_types
pizza_types.append('Chicago')
#print(pizza_types)
# Add new pizza to friend_pizzas
friend_pizzas.append('New York')
#print(friend_pizzas)
# Print lists
print("\nMy favorite pizzas are: ")
for myPizzas in pizza_types:
print(myPizzas)
print("\nMy friend's favorite pizzas are: ")
for themPizzas in friend_pizzas:
print(themPizzas)
| true |
fcbf4677829b8c0b151dc88a726fd2fe03aa7d82 | GSantos23/Crash_Course | /Chapter3/Exercises/ex3_7.py | 2,076 | 4.375 | 4 | # Exercise 3.7
# Shrinking Guest List: You just found out that your new dinner table won’t
# arrive in time for the dinner, and you have space for only two guests.
# • Start with your program from Exercise 3-6. Add a new line that prints a
# message saying that you can invite only two people for dinner.
# • Use pop() to remove guests from your list one at a time until only two
# names remain in your list. Each time you pop a name from your list, print
# a message to that person letting them know you’re sorry you can’t invite
# them to dinner.
# • Print a message to each of the two people still on your list, letting them
# know they’re still invited.
# • Use del to remove the last two names from your list, so you have an empty
# list. Print your list to make sure you actually have an empty list at the end
# of your program.
dinner = ['Abraham Lincon', 'Linus Torvalds', 'Robert Tomasulo']
print(dinner[0])
print(dinner[1])
print(dinner[2])
print("The guest who can't make it is: " + dinner[2])
print()
dinner.remove('Robert Tomasulo')
#print(dinner)
dinner.append('Stephen King')
#print(dinner)
message = ", you are invited to the big dinner party"
print(dinner[0] + message)
print(dinner[1] + message)
print(dinner[2] + message)
print("\n\nHey everyone, I found a bigger table. :)")
dinner.insert(0,'Elon Musk')
dinner.insert(2,'Bill Gates')
dinner.append('Nikola Tesla')
#print(dinner)
message2 = ", you are invited to the new party"
print(dinner[0] + message2)
print(dinner[1] + message2)
print(dinner[2] + message2)
print(dinner[3] + message2)
print(dinner[4] + message2)
print(dinner[5] + message2)
print("Hi, sorry for bother you. I only have sace for two people :(")
#dinner.pop()
print("Sorry " + dinner.pop() + ". Next time for sure")
print("Sorry " + dinner.pop() + ". Next time for sure")
print("Sorry " + dinner.pop() + ". Next time for sure")
print("Sorry " + dinner.pop() + ". Next time for sure")
#print(dinner)
print(dinner[0] + " and " + dinner[-1] + " are still invited.")
# Now to remove everyone
dinner.remove('Abraham Lincon')
dinner.remove('Elon Musk')
print(dinner) | true |
225483d70b95e91d25b3919ced0009bd5e6076cf | GSantos23/Crash_Course | /Chapter2/Exercises/ex2_8.py | 432 | 4.28125 | 4 | # Exercise 2.8
# Number Eight: Write addition, subtraction, multiplication, and division operations that each result in the number 8.
# Be sure to enclose your operations in print statements to see the results. You should create four lines that look
# like this:
# print(5 + 3)
#
# Your output should simply be four lines with the number 8 appearing once on each line.
print(5 + 3)
print(10 - 2)
print(4 * 2)
print(80 / 10) | true |
d896394fc33bdb7e6381c762a86aebf3374d4c9c | GSantos23/Crash_Course | /Chapter7/Exercises/ex7_8.py | 826 | 4.34375 | 4 | # Exercise 7.8
"""
Deli: Make a list called sandwich_orders and fill it with the names of vari-
ous sandwiches. Then make an empty list called finished_sandwiches . Loop
through the list of sandwich orders and print a message for each order, such
as I made your tuna sandwich. As each sandwich is made, move it to the list
of finished sandwiches. After all the sandwiches have been made, print a
message listing each sandwich that was made.
"""
sandwich_orders = ['tuna', 'pastrami', 'blt', 'vegie', 'meatball']
finished_sandwiches = []
while sandwich_orders:
order = sandwich_orders.pop() # To retreive sandwich
print("I made your " + order.title() + " sandwich")
finished_sandwiches.append(order)
# Print all the sanwich orders
print("\nList of sanwich: ")
for subway in finished_sandwiches:
print(subway.title()) | true |
6bdd477c7bb3ccd1d6a926515be3b3c23cf230aa | GSantos23/Crash_Course | /Chapter3/Exercises/ex3_6.py | 1,349 | 4.6875 | 5 | # Exercise 3.6
# More Guests: You just found a bigger dinner table, so now more space is
# available. Think of three more guests to invite to dinner.
#
# • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print
# statement to the end of your program informing people that you found a
# bigger dinner table.
# • Use insert() to add one new guest to the beginning of your list.
# • Use insert() to add one new guest to the middle of your list.
# • Use append() to add one new guest to the end of your list.
# • Print a new set of invitation messages, one for each person in your list.
dinner = ['Abraham Lincon', 'Linus Torvalds', 'Robert Tomasulo']
print(dinner[0])
print(dinner[1])
print(dinner[2])
print("The guest who can't make it is: " + dinner[2])
print()
dinner.remove('Robert Tomasulo')
#print(dinner)
dinner.append('Stephen King')
#print(dinner)
message = ", you are invited to the big dinner party"
print(dinner[0] + message)
print(dinner[1] + message)
print(dinner[2] + message)
print("\n\nHey everyone, I found a bigger table. :)")
dinner.insert(0,'Elon Musk')
dinner.insert(2,'Bill Gates')
dinner.append('Nikola Tesla')
#print(dinner)
message2 = ", you are invited to the new party"
print(dinner[0] + message2)
print(dinner[1] + message2)
print(dinner[2] + message2)
print(dinner[3] + message2)
print(dinner[4] + message2)
print(dinner[5] + message2)
| true |
9dbd7819ad96e42666b7d2b78f901e9d5bd97690 | GSantos23/Crash_Course | /Chapter6/Exercises/ex6_9.py | 657 | 4.5625 | 5 | # Exercise 6.9
"""
Favorite Places: Make a dictionary called favorite_places . Think of three
names to use as keys in the dictionary, and store one to three favorite places
for each person. To make this exercise a bit more interesting, ask some friends
to name a few of their favorite places. Loop through the dictionary, and print
each person’s name and their favorite places
"""
favorite_places = {
'gerson': ['Ireland', 'Japan', 'England'],
'jessica': ['France', 'Italy'],
'pablo': ['Colombia'],
}
for person, places in favorite_places.items():
print(person.title() + "'s favorite places are: ")
for location in places:
print("\t" + location) | true |
813d5efcf6d009e48cd33699907ff38dc03b2486 | GSantos23/Crash_Course | /Chapter8/Exercises/ex8_5.py | 639 | 4.59375 | 5 | # Exercise 8.5
'''
Cities: Write a function called describe_city() that accepts the name of
a city and its country. The function should print a simple sentence, such as
Reykjavik is in Iceland . Give the parameter for the country a default value.
Call your function for three different cities, at least one of which is not in
the default country.
'''
def describe_city(citiy_name, country):
"""Display city name and country
city_name -> string, country -> string"""
print(citiy_name.title() + " is in " + country.title())
describe_city('reykjavik', 'Iceland')
describe_city('kiev', 'ukraine')
describe_city('guadalajara', 'mexico')
| true |
7a6ae1129a05e710b235e67abdc8d28bdaace3f9 | GSantos23/Crash_Course | /Chapter8/Exercises/ex8_8.py | 806 | 4.5625 | 5 | # Exercise 8.8
'''
Start with your program from Exercise 8-7. Write a while
loop that allows users to enter an album’s artist and title. Once you have that
information, call make_album() with the user’s input and print the dictionary
that’s created. Be sure to include a quit value in the while loop.
'''
def make_album(artist, album, tracks=''):
"""Display music album info
artist -> string
album -> string
tracks -> number"""
music = {'artist':artist, 'album':album}
if tracks:
music['tracks'] = tracks
return music
while True:
print("\nType your music knowledge.\nType 'q' to quit")
artist_name = input("Artist: ")
if artist_name == 'q':
break
album_name = input("Album: ")
if album_name == 'q':
break
information = make_album(artist_name, album_name)
print(information) | true |
c2bd76a3ca6a66666b44b13dd8ce9635597f27bf | GSantos23/Crash_Course | /Chapter6/Exercises/ex6_4.py | 1,114 | 4.53125 | 5 | # Exercise 6.4
"""
Glossary 2: Now that you know how to loop through a dictionary, clean
up the code from Exercise 6-3 (page 102) by replacing your series of print
statements with a loop that runs through the dictionary’s keys and values.
When you’re sure that your loop works, add five more Python terms to your
glossary. When you run your program again, these new words and meanings
should automatically be included in the output.
"""
glossary = {
'Dictionary': 'A collection of key-value pairs\n',
'Tuples': 'A list of items that cannot change\n',
'Lookup_Table': 'Array of data to map input values to output values\n',
'List_Comprehension': 'Combination of a for loop and list append\n',
'Simultaneous_Assigment': 'Alternative form of assigment statement\n',
'String': 'A series of characters\n',
'Float': 'Any number with a decimal point\n',
'Slice': 'Specific group of items on a list\n',
'Conditional_Test': 'An expression that can be True or False\n',
'Boolean_Expression': 'Another name for conditional test'
}
for terms, definitions in glossary.items():
print(terms)
print(definitions) | true |
487f430511c95680457a118a3377e1bca3181eb8 | GSantos23/Crash_Course | /Chapter11/Exercises/employee_pay.py | 880 | 4.4375 | 4 | # Exercise 11.13
'''
Employee: Write a class called Employee . The __init__() method should
take in a first name, a last name, and an annual salary, and store each of
these as attributes. Write a method called give_raise() that adds $5000 to
the annual salary by default but also accepts a different raise amount.
Write a test case for Employee . Write two test methods, test_give_
default_raise() and test_give_custom_raise() . Use the setUp() method so
you don’t have to create a new employee instance in each test method. Run
your test case, and make sure both tests pass.
'''
class Employee():
"""Collects employee data and annual salary,."""
def __init__(self, first, last, annual):
self.first = first.title()
self.last = last.title()
self.annual = annual
def give_raise(self, raise_value=5000):
"""Add $5000 to annual salary."""
self.annual += raise_value
| true |
2e75fa23dcf29a6fba4ff5789dac2a94135ce898 | marieli15/Curso-Phyton | /Ejercicios/ejercicios2.py | 1,122 | 4.34375 | 4 | listaNombre = ["Gerardo", "Damian", "Cesar"]
print(listaNombre)
#Agregar elementos a la listaNombre
listaNombre.append("Kenedy")
print(listaNombre)
#Ver elementos de la lista
print(listaNombre[0])
print(listaNombre[3])
print(listaNombre[0],",",listaNombre[1])
#
#ver elementos de la lista
newlista = listaNombre[0:2]
print(newlista)
newlista = listaNombre[0:6:4]
print(newlista)
newlista = listaNombre[1:6:4]
print(newlista)
#Agregar eleentos
listaNombre = (0,"Juan")
listaNombre = (3,"Irais")
print(listaNombre)
#borrar elementos
listaNombre.remove("Juan")
print(listaNombre)
listaNombre.remove("Cesar")
print(listaNombre)
#Buscar el indice del elemento de la lista
print(listaNombre.index("Carlos"))
print(listaNombre.index("Pepe"))
#Tuplas
tuplaNombres = ("Gerardo", "Cesar")
print(tuplaNombres)
print(tuplaNombres[0])
print(tuplaNombres[1])
#tuplaNombres.append("Carlos")
#tuplaNombres.
#regresando a lista
#ordenar lista
listaNumeros = [3,6,4,2,3,7,4,3,4,7]
nuevalista = sorted(listaNombre)
print(nuevalista)
print(listaNumeros)
print(sorted(listaNumeros))
| false |
d85d6ea48e88e9170bcb61534a0ebdbc8f84bc49 | bodik10/EulerSolving | /euler 030.py | 421 | 4.1875 | 4 | import myprofiler
def digitsPower(power, num):
digits = [int(digit)**power for digit in str(num)]
return sum(digits)
numbers = []
with myprofiler.profile():
for num in range(2, 6*9**5):
if num == digitsPower(5, num):
numbers.append(num)
print (numbers)
print ("Sum of all the numbers that can be written as the sum of fifth powers of their digits: %d" % sum(numbers)) | true |
602b177f85a7554f85a18ff0a64529d8b404eb5a | ryanaspears/VSA | /proj02_loops/proj02_01.py | 1,019 | 4.3125 | 4 | # Name:
# Date:
# proj02: sum
# Write a program that prompts the user to enter numbers, one per line,
# ending with a line containing 0, and keep a running sum of the numbers.
# Only print out the sum after all the numbers are entered
# (at least in your final version). Each time you read in a number,
# you can immediately use it for your sum,
# and then be done with the number just entered.
# Example:
# Enter a number to sum, or 0 to indicate you are finished: 4
# Enter a number to sum, or 0 to indicate you are finished: 5
# Enter a number to sum, or 0 to indicate you are finished: 2
# Enter a number to sum, or 0 to indicate you are finished: 10
# Enter a number to sum, or 0 to indicate you are finished: 0
# The sum of your numbers is: 21
input_sum = 0
var = 1
while var != 0:
input1 = raw_input("Enter a number to sum, or 0 to indicate you are finished: ")
input_sum = int(input1) + input_sum
if int(input1) == 0:
var = 0
print"The sum of your numbers is: " + str(input_sum)
| true |
b7cafc839afc4cdf21e1acb272100b1a1e736ba0 | juliagolder/unit6 | /revsereFile.py | 214 | 4.125 | 4 | #juliagolder
#5/16/18
#reverseFile.py
THEfile = input('What file would you like to reverse?')
file = open(THEfile)
L = []
for line in file:
L.append(line.strip())
L.reverse()
for item in L:
print(item) | true |
ff5bf3e6f8aaaa6fd9ee41459ecbdd8f2ba7de8f | komaldongare28/Data-Analysis-on-CO2-Emission | /Analysis.py | 2,624 | 4.28125 | 4 | """
Name: Python Data Analysis
Purpose: Maximum and Minimum emission in Country + Average emission in year
Algorithm:
Step 1: Take the input from user
Step 2: Extracting index of the year
Step 3: Creating the list of emission in year
Step 4: Performing the analysis
Step 5: Printing the data in required format using formatted string
"""
print("A Simple Data Analysis Program")
print()
emission_dict = {}
with open('Emissions.csv', 'r') as file:
for data in file.read().split('\n'):
emission_dict.update({data.split(',')[0]: data.split(',')[1:]})
print("All data from Emissions.csv has been read into a dictionary.", end='\n\n')
"""
Step 1: Take the input from user.
"""
input_year = input("Select a year to find statistics (1997 to 2010): ")
index_of = None
lines = []
"""
Step 2: Extracting index of the year
"""
# Loop through First VALUE of Dictionary and if year present in list then set index of VALUE as index_of
for item in next(iter(emission_dict.values())):
if input_year in item:
index_of = (item.index(input_year))
total = 0
i = 0
emissions_in_year = []
"""
Step 3: Creating the list of emission in year
"""
# Loop through VALUES of Dictionary
for value in emission_dict.values():
# For the first loop skip the code because in our case it contains Column Names and Years
if i != 0:
# Add VALUE of Emission to total
total += float(value[index_of])
# Append the value to emissions_in_year
emissions_in_year.append(list(emission_dict.values())[i][index_of])
i += 1
"""
Step 4: Performing the analysis
"""
# Let's try to understand this from inner Single Line loop. We converted String to float and created list, from this
# list we found the maximum and minimum float value, converted that into string and got the index of maximum and
# minimum emission country.
max_country_index = int(emissions_in_year.index(str(max(float(str_value) for str_value in emissions_in_year))))
min_country_index = int(emissions_in_year.index(str(min(float(str_value) for str_value in emissions_in_year))))
average_emissions = total / 195
# Using index value we got the Name of maximum and minimum country name
max_emission = list(emission_dict.keys())[max_country_index + 1]
min_emission = list(emission_dict.keys())[min_country_index + 1]
"""
Step 5: Printing the data in required format using formatted string
"""
print(f'In {input_year}, countries with minimum and maximum CO2 emission levels were: [{min_emission}] '
f'and [{max_emission}] respectively.')
print(f'Average CO2 emissions in {input_year} were {"%.6f" % round(average_emissions, 6)}')
print()
| true |
5f522d69ee01ed25d419d2d5935c3c82e42910e4 | LukeEsworthy/Chapter-5-Dictionary-Exercise | /dictionaryOfWords.py | 956 | 4.78125 | 5 | """
Create a dictionary with key value pairs to
represent words (key) and its definition (value)
"""
word_definitions = dict()
"""
Add several more words and their definitions
Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python"
"""
word_definitions["Struggle"] = "What people experience when beginning to code"
word_definitions["Elation"] = "What people experience when their code works successfully"
"""
Use square bracket lookup to get the definition of two
words and output them to the console with `print()`
"""
print("Elation:", word_definitions["Elation"])
print("Struggle:", word_definitions["Struggle"])
"""
Loop over the dictionary to get the following output:
The definition of [WORD] is [DEFINITION]
The definition of [WORD] is [DEFINITION]
The definition of [WORD] is [DEFINITION]
"""
for (key, value) in word_definitions.items():
print(f"The definition of {key} is {value}")
| true |
c7f1b7ad4b34dcc5d1cea47803c68dfb43ee5c46 | elango-ux/CodeTrainingProject | /Python/classusinstanceattribute.py | 1,136 | 4.1875 | 4 | class Point:
#4)class attribute
default_color = "red"
#constructor or magical method
def __init__(self, x, y):
self.x = x
self.y = y
# draw function inside class
def draw(self):
print(f"Point({self.x}, {self.y})")
#first letterof every word is capital
# class level attribute are shared across all instances of class if you change red to yellow then it affect all point object
Point.default_color = "YELLOW"
#1)point object have default attribute x,y,z which created by constructor or whichis used by all object created
#2) we can create attribute specific to point object
# all the attribute created x, y, z so for is called instances attribute
point.z = 10
point = Point(1, 2)
# 5)object refrence to access the default color attribute
print(point.default_color)
# 6) POINT CLASS to access the defaultcolor attribute
print(Point.default_color)
point.draw()
# 3)another Point class object have differnt set of value both object created are independent of each other thus this is called instanceattribue
another = Point(2, 4)
print(another.default_color)
another.draw() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.