blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
796531ea77eaec4ece9afdfdcde2ab94bdac913c | domingomartinezstem/QC | /SymmetricKeyEncryption.py | 720 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 21:41:05 2018
@author: domin
"""
#this works!
def encrypt(sentence):
result = []
for letter in sentence:
l= ord(letter)
result.append(l)
print("encrypted message")
for numbers in result:
print(numbers, end='')
print("", end='')
print()
decrypt(result)
def decrypt(result):
end_string=""
for numbers in result:
l=int(numbers)
l=l
l=chr(l)
end_string=end_string + l
print("Your decrypted message")
print(end_string)
def main():
s=input("input a sentence for encryption: ")
encrypt(s)
if __name__=='__main__':
main() | true |
e104f9ebfb10a9d46c3d633b354732e2bb6cec47 | amobiless/Assessment | /04_number_checker_v2.py | 731 | 4.1875 | 4 | # Integer checker - more advanced
def calculate():
valid = False
while not valid:
try:
num = float(input("Enter participant's time: "))
if isinstance(num, float):
valid = True
return num
except ValueError:
print("That is not a number")
time = calculate()
print(f"The test number is {time}")
# Check for valid string input - eg name
def string_checker(question):
error = "Can't be a number or blank\n"
while True:
to_test = input(question)
if not to_test.isalpha():
print(error)
continue
else:
return to_test
name = string_checker("Please enter participant name: ")
| true |
f7d88e43d87cac893ff58334f062d48875dc4599 | OlyaBakay/UCU-blockchain-lesson1 | /point_prime.py | 1,781 | 4.25 | 4 | class Point:
"""
Class Point represents a point on crypto curve y^2 = x^3 + ax + b
"""
def __init__(self, x, y, a, b, mod):
if (y ** 2 - x ** 3 - a * x - b) % mod != 0:
raise ValueError('Incorrect values')
self.x = x
self.y = y
self.a = a
self.b = b
self.mod = mod
def __add__(self, other):
"""
A method should modify the self-instance.
:param other:
:return:
"""
if self.x == other.x and self.y == other.y:
return self.__prod2()
elif self.x == other.x:
return "Point is at infinity"
# slope = (other.y - self.y) * self.__inv(other.x - self.x)
slope = (other.y - self.y) * self.__inv2(other.x - self.x)
x_res = (slope ** 2 - self.x - other.x) % self.mod
y_res = (slope * (self.x - x_res) - self.y) % self.mod
return Point(x_res, y_res, self.a, self.b, self.mod)
def __inv(self, num):
for i in range(self.mod):
if num * i % self.mod == 1:
return i
def __inv2(self, num):
return pow(num, self.mod - 2, self.mod)
def __prod2(self):
slope = (3 * (self.x ** 2) + self.a) / (2 * self.y)
x_res = (slope ** 2 - 2 * self.x) % self.mod
y_res = (slope * (self.x - x_res) - self.y) % self.mod
return Point(x_res, y_res, self.a, self.b, self.mod)
def __str__(self):
return "Point: x: {0}, y: {1}".format(self.x, self.y)
if __name__ == "__main__":
q = Point(0, 1, 1, 1, 7)
p = Point(2, 2, 1, 1, 7)
print(p + q)
print("Hooray. Test 1 passed")
q = Point(195, 652, 1, 1, 997)
p = Point(995, 514, 1, 1, 997)
print(p + q)
print("Hooray. Test 2 passed")
| false |
c234b405bf139ce2fdc17c10911b2b94c42d8787 | calel95/testes | /class_exemplo.py | 1,933 | 4.125 | 4 | # EXEMPLO 1
class calculadora:
def __init__(self,n1 , n2): #define os parametros, por padrao o self tem que ter, o init que inicia a class
self.a = n1
self.b = n2
def soma(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def div(self):
return self.a / self.b
def mult(self):
return self.a * self.b
if __name__ == '__main__':
calculadora = calculadora(20,4)
print(calculadora.soma())
print(calculadora.sub())
print(calculadora.div())
print(calculadora.mult())
#************************************************************************************************************
# EXEMPLO 2
class calculadora2:
def __init__(self): #funciona sem o metodo init tbm, pois ele esta vazio
pass
def soma(self,a,b):
return a + b
def sub(self,a,b):
return a - b
def div(self,a,b):
return a / b
def mult(self,a,b):
return a * b
if __name__ == '__main__':
calculadora2 = calculadora2()
print(calculadora2.soma(10,2))
print(calculadora2.sub(5,3))
print(calculadora2.div(100,2))
print(calculadora2.mult(10,5))
#******************************************************************************************************************
# EXEMPLO 3
class televisao:
def __init__(self):
self.ligada = False
self.canal = 2
def power(self):
if self.ligada == True:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
self.canal = self.canal + 1
def diminui_canal(self):
self.canal = self.canal - 1
if __name__ == '__main__':
tv = televisao()
print(tv.ligada)
tv.power()
print(tv.ligada)
tv.power()
print(tv.ligada)
print(tv.canal)
tv.aumenta_canal()
tv.aumenta_canal()
tv.aumenta_canal()
print(tv.canal) | false |
2603bdce02bdd5e69c983226dedb98ea04b17f00 | hqs2212586/startMyPython3.0 | /第三章-文件操作和函数/函数/高阶函数.py | 803 | 4.25 | 4 | '''
高阶函数:一个函数就可以接收另一个函数作为参数(变量可以指向函数,函数的参数能接收变量)
满足以下任意条件可以判断是高阶函数:
1、接受一个或多个函数作为输入
2、return返回另外一个函数
'''
# 下述例子说明变量可以指向函数
'''
def calc(x):
return x*x
f = calc
print(f(2))
'''
# 下述例子说明函数的参数能接收变量
def func(x,y):
return x+y
def calc(x):
return x
n = func
print(calc(n))
# 输出:<function func at 0x101a62ea0>
# 下述例子是函数返回函数
def func2(x,y):
return abs,x,y # abs()函数求绝对值;返回结果包含一个函数的函数就是高阶函数
res = func2(3,-10)
print(res[0](res[1]+res[2]))
# 输出结果:7 | false |
d5f30ca89e69fb7b4afb8d4e3688d89aeaff1354 | hqs2212586/startMyPython3.0 | /第五章-面向对象/8 练习.py | 1,027 | 4.3125 | 4 | """
练习1:编写一个学生类,产生一堆学生对象
要求:
有一个计算器(属性),统计总共实力了多少个对象
"""
class Student: # 类名头字母大写
school = 'whu'
count = 0
def __init__(self, name, age, sex): # 为对象定制对象自己独有的特征
self.name = name
self.age = age
self.sex = sex
# self.count += 1 # 每个对象都是1,无法实现累加,student类的count一直都是0
Student.count += 1
def learn(self):
print('%s is learning' % self.name)
def eat(self):
print('%s is eating very happy!' % self.name)
stu1 = Student('alex', 'male', 38) # 实例化一次就触发一次__init__
stu2 = Student('jinxing', 'female', 48)
stu3 = Student('egon', 'male', 18)
print(Student.count)
print(stu1.count)
print(stu2.count)
print(stu3.count)
print(stu1.__dict__)
print(stu3.__dict__)
"""
3
3
3
3
{'name': 'alex', 'age': 'male', 'sex': 38}
{'name': 'egon', 'age': 'male', 'sex': 18}
""" | false |
195b0a84417fe61bae217a07c9c9167b8a2f5273 | hqs2212586/startMyPython3.0 | /第五章-面向对象/6 补充说明.py | 815 | 4.5 | 4 | """
补充说明:
1、站的角度不同,定义出的类截然不同
2、现实中的类并不完全等于程序中的类,比如现实中的公司类,往往会在程序中拆分为部门类,业务类等;
3、有时为了编程的需求,程序中也可能会定义现实中不存在的类,比如策略类(现实中不存在,但在程序中却非常常见的类)
"""
class student:
school = 'whu'
# python当中一切皆对象,在python3中统一了类和类型的概念
print(list)
print(dict)
print(student)
"""
<class 'list'>
<class 'dict'>
<class '__main__.student'>
"""
l1 = [1, 2, 3]
l2 = list([1, 2])
l1.append(4) # 对象调用绑定方法append
list.append(l2, 4) # list类的方法append来对对象添加元素
print(l1, l2)
"""
[1, 2, 3, 4] [1, 2, 4]
""" | false |
0c1c743294fcbc3af4bfc97eb8ccda73c7f33f2f | hqs2212586/startMyPython3.0 | /第五章-面向对象/19 封装的意义.py | 1,672 | 4.25 | 4 | # 一、封装数据属性:明确地区分内外,控制外部对隐藏属性的操作行为
# class People:
# def __init__(self, name, age):
# self.__name = name
# self.__age = age
#
# def tell_info(self):
# print('Name:<%s> Age:<%s>' % (self.__name, self.__age))
#
# def set_info(self, name, age):
# if not isinstance(name, str):
# print('名字必须是字符串类型')
# return
# if not isinstance(age, int):
# print('年龄必须是数字类型')
# return
# self.__name = name
# self.__age = age
#
#
# p = People('egon', 18)
#
# # p.tell_info()
# """
# Name:<egon> Age:<18> # 封装数据,开放接口给外部访问
# """
#
# # p.set_info('Egon', 38) # 修改数据只能通过接口来完成,可以通过接口完成各种限制
# # p.tell_info()
# """
# Name:<Egon> Age:<38>
# """
#
# # p.set_info(123, 38)
# """
# 名字必须是字符串类型
# """
# p.set_info('egon', '38')
# p.tell_info()
# """
# 年龄必须是数字类型
# Name:<egon> Age:<18>
# """
# 二、封装方法的目的:隔离复杂度
class ATM:
def __card(self):
print('插卡')
def __auth(self):
print('输入取款金额')
def __input(self):
print('输入取款金额')
def __print_bill(self):
print('打印账单')
def __take_money(self):
print('取款')
def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
a = ATM()
a.withdraw()
"""
插卡
输入取款金额
输入取款金额
打印账单
取款
""" | false |
96445bb7a92516766a7c289064aa613eb6557d2f | hqs2212586/startMyPython3.0 | /第五章-面向对象/24 反射.py | 982 | 4.28125 | 4 | # 反射:通过字符串映射到对象的属性
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
print('%s is talking' %self.name)
obj=People('egon', 18)
print(obj.name) # obj.__dict__('name')
obj.talk()
hasattr(obj, 'name') # 判断obj内有没有name属性,obj.name # obj.__dict__['name']
print(hasattr(obj, 'name')) # 输出:True
print(hasattr(obj, 'talk')) # obj.talk
"""
True
True
"""
getattr(obj, 'name', None) # 拿到一个对象的属性
print(getattr(obj, 'name'))
print(getattr(obj, 'namesadwd', None)) # 设置default=None
print(getattr(obj, 'talk')) # 拿到方法属性
"""
egon
None
<bound method People.talk of <__main__.People object at 0x10401af60>>
"""
setattr(obj, 'sex', 'male') # 修改对象属性 obj.sex='male'
print(obj.sex)
"""
male
"""
delattr(obj, 'age') # 删除对象属性 del obj.age
print(obj.__dict__)
"""
{'name': 'egon', 'sex': 'male'}
""" | false |
e817977014fc2fec163f0df739ba34ccf728c24b | trohit920/leetcode_solution | /python/521. Longest Uncommon Subsequence I.py | 1,662 | 4.21875 | 4 | # Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
#
# A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
#
# The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
#
# Example 1:
# Input: "aba", "cdc"
# Output: 3
# Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
# because "aba" is a subsequence of "aba",
# but not a subsequence of any other strings in the group of two strings.
# Note:
#
# Both strings' lengths will not exceed 100.
# Only letters from a ~ z will appear in input strings.
class Solution(object):
def findLUSlength(self, a, b):
i = 0
if a == "" and b == "":
return -1
elif len(a) ==0:
return len(b)
elif len(b) == 0:
return len(a)
while i < len(a) and i < len(b) and len(a) == len(b):
if a[i] != b[i] or a[-(1 + i)] != b[-(1 + i)]:
return (max(len(a), len(b)))
else:
return -1
i = i + 1
return (max(len(a), len(b)))
if __name__ == '__main__':
s = Solution()
print "Solution : " + str(s.findLUSlength('shivam',''))
| true |
e8a0f8465b56dd066ed0dbb4258653ce948e9d4d | trohit920/leetcode_solution | /python/TopInterviewQuestionEasy/others_easy/Hamming Distance.py | 1,525 | 4.21875 | 4 | '''
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
'''
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x1 = self.helper(x)
y1 = self.helper(y)
count = 0
if len(x1) > len(y1):
count = self.helper_new(x1,y1)
elif len(x1) < len(y1):
count = self.helper_new(y1,x1)
else:
i = 0
while i<len(x1):
if x1[i] + y1[i] == 1:
count = count + 1
i = i + 1
return count
def helper_new(self,x1,y1):
i = 0
count = 0
while i < len(y1):
if x1[i] + y1[i] == 1:
count = count + 1
i = i + 1
while i < len(x1):
if x1[i] == 1:
count = count + 1
i = i + 1
return count
def helper(self,x):
temp = []
while x:
if x % 2 == 0:
temp.append(0)
else:
temp.append(1)
x = x // 2
return temp
s = Solution()
print(s.hammingDistance(1,3)) | true |
0d082ed58b1c6623993a08ad21fec121e813c406 | YongHoonJJo/Python | /Lang_J2P/Tuple.py | 498 | 4.21875 | 4 | ### How to make Tuple ###
t1 = ()
t2 = (1, ) # only one element
t3 = (1, 2, 3)
t4 = 1, 2, 3
t5 = ('a', 'b', ('ab', 'cd'))
# It is impossible to delete or to replace elements.
t = (1, 2, 'a', 'b')
# del t[0] (error)
# t[0] = 'c' (error)
### Indexing, Slicing, Operator ###
t = (1, 2, 'a', 'b')
# t[0] : 1
# t[3] : 'b'
# t[1:] : (2, 'a', 'b')
tt = (3, 4)
ttt = t + tt
#print(ttt) : (1, 2, 'a', 'b', 3, 4)
tt = tt * 3
#print(tt) : (3, 4, 3, 4, 3, 4)
### The others are similar to List. ###
| false |
dc3a60a000dae627cab5834261378e83d263b258 | Horatio123/PythonProgram | /firstTest/hello.py | 1,113 | 4.28125 | 4 | print ("hello python world")
class Student:
pass
student1 = Student()
print (student1)
student1.name = "horatio"
print (student1.name)
class Employee:
def __init__(self, first='Tom', last='Gates', pay=1000):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@baimahu.com'
def fullname(self):
return '{}, {}'.format(self.first, self.last)
employee1 = Employee("Alex", "Jobs", 5000)
employee2 = Employee()
employee3 = Employee('Jerry')
print (employee1.email)
print ('{}, {}'.format(employee1.first, employee1.last))
print employee1.fullname()
print employee2.fullname()
print employee3.fullname()
print Employee.fullname(employee1)
def fun(*args, **kwargs):
for arg in args:
print arg
for item in kwargs.items():
print item
print fun('pig', 'dog', name='Tom')
# class Company:
# def __init__(self, *args, **kwargs):
#
# def fullname(self):
# for arg in self:
# print arg
#
#
# company1 = Company('name', 'location', name='xiao')
# print company1.fullname()
| false |
bce300aea98561a98bb61d797445903c8c1d0bca | Schachte/Learn_Python_The_Hard_Way | /Excercise_33/Excercise_33.py | 621 | 4.40625 | 4 | ################################
######### Excercise 33##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Gain exit conditional input from the user
print 'Loop Count?' #Count number of times user would like to loop through string format
exit_conditional = raw_input('>>')
exit_conditional = float(exit_conditional) #Convert exit_conditional string into a float
count = 1
while (count <= exit_conditional):
print 'Current count is at: %d' %(count) #Display the data
count = count + 1 #Count increments to make sure the loop stops at the appropriate position
| true |
163bc5411b58de28c9fb80339d01f5b23629c056 | Schachte/Learn_Python_The_Hard_Way | /Excercise_29/Excercise_29.py | 735 | 4.71875 | 5 | ################################
######### Excercise 29##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Implement a what if statement for python to execute certain code under certain condition
'''
Initial Assignments to children and adults
'''
adults = 30
children = 40
'''
Using basic if-else statements
'''
if adults > children:
print 'Adults are greater!'
else:
print 'Children are greater!'
adults += 10 #Increment the initial pre-defined value of the adults to change the program output
if adults > children:
print 'Adults are greater!'
elif adults < children:
print 'Children are greater!'
else:
print 'Children and adults are equal in quantity'
| true |
d2a7dc9657d3c03124364566d5357cfb366e9728 | Schachte/Learn_Python_The_Hard_Way | /Excercise_39/Excercise_39.py | 1,285 | 4.46875 | 4 | ################################
######### Excercise 39##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Description:
#Working with dictionaries in Python
#Mapping multiple items to elements in a list. Each element is a key.
#Example
dict_info = {
'States': ['Arizona', 'Masachusetts', 'California'],
'Cities': ['Tempe', 'Boston', 'Silicon Valley'],
'College': ['Arizona State University', 'Harvard University', 'Stanford University']
}
count = 0
for each_college in dict_info:
information = '''
The college %s is located in %s, %s.
''' %(dict_info['College'][count], dict_info['Cities'][count], dict_info['States'][count])
#College, Abbreviated State, City
print information
print '-' * 100
count = count + 1
#Print out each state without using a counter
state_abbreviations = {
#Create a mapping of relevant states with abbrviated counter-part
'Arizona': 'AZ',
'California': 'CA',
'Massachusetts': 'MA'
}
#For loop to iterate through each state to explain it's respected abbreviation
for each_state in state_abbreviations:
format = '''
The state %s has an abbreviation as %s.
''' %(each_state, state_abbreviations[each_state])
print format
print '-' * 100
| true |
570c634276f332186e724395acf46982be490a0f | Schachte/Learn_Python_The_Hard_Way | /Excercise_32/Excercise_32.py | 2,218 | 4.4375 | 4 | ################################
######### Excercise 32##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Objective:
#Build a loop that adds data into a list and then have python print the data using string formatter
'''
loop_data = [] #Instantiate an empty list to store user data in
loop_count = raw_input("Enter the number of elements you would like to iterate through in the loop:")
loop_count = float(loop_count) #Convert user string (loop_count) into a float to read numbers
count = 1 #Store the initial count to properly track the progress of the user count
while (count <= loop_count):
loop_data.append(count)
print 'The current element is: %d' %(count) #String format to print the user data from the list
count = count + 1 #Increment the count by one to track the current adding progress of the data
'''
#Now we are going to do a loop with a list to store names of people in class
user_list = [] #Defining an empty user list to store user_input users into a python list
#Function to add people into a list using raw_input and lists in Python
def new_user():
user_name = raw_input("Enter the name of the user that you would like to add into the list: ")
user_list.append(user_name)
print user_name + ' was appended to the list successfully!'
return user_list
add_user = True
while (add_user == True):
boolean_add_user = raw_input('Would you like to add a user into the class list?')
boolean_add_user = boolean_add_user.lower()
if boolean_add_user == 'yes':
#If the loop is made True by user input of Yes, then call the add_user function to add another person to the list
add_user = True
user_list = new_user()
elif boolean_add_user == 'no': #Exit the loop by changing the value of the boolean
add_user = False
else:
print 'Please enter a valid input for the program to read!'
final_user_option = raw_input("Would you like to view the class list or exit the program? V/E")
if final_user_option == "V":
for each_item in user_list:
print 'The first student is: %s' %each_item
elif final_user_option == "E":
print 'Exiting program!'
| true |
4af768058ec3159db5565e0bcfd1f6bdd2d6a86a | DavinderSohal/Python | /Activities/Activity_9/Exercise2.py | 679 | 4.59375 | 5 | # Create a dictionary with keys ‘firstname’, ‘lastname’ and ‘age’, with some values assigned to each
# Add an additional key ‘address’ to the dictionary
# Print out the list of keys of your dictionary
# Create a ‘name’ key with the value as a string containing both first and last name keys. Is it possible to do this
# without typing in your name once again? If so make the modification, and when done remove the two other older keys.
my_dict = {'firstname': 'Davinder', 'lastname': 'Sohal', 'age': 24}
my_dict['address'] = 'My address'
print(list(my_dict.keys()))
my_dict['name'] = my_dict.pop('firstname') + " " + my_dict.pop('lastname')
print(my_dict)
| true |
8adf5bc896807610f51ac9496e2ed64fdf8c2235 | DavinderSohal/Python | /Activities/Activity_6/Exercise2.py | 1,068 | 4.34375 | 4 | # Create the following python program:
# This program will display a mark table to the user, depending on its input.
# The columns represents the subjects.
# The rows represents the students.
# Algorithm to input data from the user:
# o Ask the user how many subjects (columns) is necessary.
# o Ask the user how many students (rows) is necessary.
# o For each student, loop and ask a mark for each subject
no_of_subjects = int(input("Enter # of subjects: "))
no_of_students = int(input("Enter # of students: "))
marks = [[None for subject in range(0, no_of_subjects)] for student in range(0, no_of_students)]
for student in range(0, no_of_students):
for subject in range(0, no_of_subjects):
marks[student][subject] = input(f"student {student + 1} subject {subject + 1}: ")
print(f"Marks for the {no_of_students} students\n")
for student in range(0, no_of_students):
print(f"Student {student + 1}: ", end = "")
for subject in range(0, no_of_subjects):
print(marks[student][subject], end = " ")
print("")
| true |
773b2d7e700e82c2205b4f0a41b1c813b510452d | DavinderSohal/Python | /Activities/Activity_2/split.py | 752 | 4.40625 | 4 | # Exercise: Using the following sentence:
# “The quick brown fox jumps over the lazy dog”,
# convert this string into a list and then find the index of the word dog and sort the list of terms/words in
# ascending order. Print out the first two elements of this sorted list. Additionally, as a bonus, try to reverse
# the list of words using the slice operation.
# Hint: Use split() method!
string = "The quick brown fox jumps over the lazy dog"
string_list = string.split()
print("\nList: ", string_list)
print("\nIndex of \"dog\": " + str(string_list.index("dog")))
string_list.sort(key = str.lower)
print("\nSorted List: ", string_list)
print("\nFirst two elements: ", string_list[0:2])
print("\nReversed List: ", string_list[::-1])
| true |
efa9da8b6523c80bca5f9dfc9c34af4157a57cce | DavinderSohal/Python | /Activities/Activity_11/Exercise1.py | 414 | 4.3125 | 4 | # Create an empty class called Car.
#
# Create a method called initialize in the class, which takes a name as input and saves it as a data attribute.
#
# Create an instance of the class, and save it in a variable called car.
#
# Call the initialize method with the string “Ford".
class Car:
def initialize(self, name):
self.data = name
print(self.data)
car = Car()
car.initialize("ford")
| true |
4e8fe4ef896f9bd4a7546a1cfa61ff11e0a2143a | DavinderSohal/Python | /Activities/even/even.py | 229 | 4.1875 | 4 | def even_number(number):
try:
if number % 2 == 0:
print("This entered number is even")
except:
print("The number entered by you is not even")
num = input("Enter the number")
even_number(num)
| true |
54adb4c74bdfcd80e96fdef01e7ac94c3f38602e | DavinderSohal/Python | /Activities/Activity_4/Exercise1.py | 409 | 4.28125 | 4 | # Create a string with your firstname, lastname and age, just like in the first week of the class, but this time using
# the string formatting discussed on the previous slides – and refer to the values by name, the output should be
# similar to the following:
# Name:
# Age:
print("Name: {first_name} {last_name} \nAge: {age}".format(
first_name = "Davinder",
last_name = "Sohal",
age = 24))
| true |
6584a6355434917aca87047cd83addc6e3c5d997 | DavinderSohal/Python | /Explanations/10-Regex/nonGreedy.py | 305 | 4.28125 | 4 | # Example of greedy regex
import re
txt = 'Hello World'
pattern1 = re.compile("([A-Za-z]+).*([A-Za-z]+)") # greedy
pattern2 = re.compile("([A-Za-z]+).*?([A-Za-z]+)") # not greedy
print(pattern1.match(txt).groups()) # ==> ('Hello', 'd')
print(pattern2.match(txt).groups()) # ==> ('Hello', 'World')
| false |
6a3522904f129a5980912a88d1793ac71b38045c | Chetana-Nikam/python | /Python Udemy Course/WhileLoop.py | 301 | 4.28125 | 4 | #While Loop
#i=0
#while i<5:
# print(i) # infinite times loop will exist because i=0 always less than 5
i=0
while i<5:
print(i)
i += 1
i=0
while i<=10:
i += 1
if i==6:
break
print(i)
i=0
while i<=10:
i += 1
if i==6:
continue
print(i)
| false |
aeda5f94162716a34fb7808246727645197b8a5c | Chetana-Nikam/python | /Python Udemy Course/Function.py | 876 | 4.25 | 4 | # function - It is block of code and it will work only when we call it
def myfun():
print("I am Function")
myfun() # Function call
def myfun(name, age):
print(f"My name is {name} and my age is {age}")
myfun('Chetana', 21)
myfun('Google', 20)
def myfun(*name): # * indicats arbitary argument
print(f"My name is {name[1]}")
myfun('Chetana', 'Manisha', 'Prakash')
# def myfun(name):
# print(f"My name is {name}")
# myfun() # if we didnt pass anything when function is calling then it will gives error so we have to pass one default value in function
def myfun(name='Chetana'):
print(f"My name is {name}")
myfun()
def myfun(name):
for i in name:
print(i)
name=('Chetana', 'Manisha', 'Prakash')
myfun(name)
def myfun(x):
return x*x
print(myfun(8))
print(myfun(5))
| true |
60ebc2b61f6e2d949fdb22b41ca77d7e5de3bb99 | cs-fullstack-2019-fall/python-arraycollections-b-cw-marcus110379 | /cw.py | 2,002 | 4.1875 | 4 | # Create a function with the variable below. After you create the variable do the instructions below that.
# # ```
# # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"]
# a) Print the 3rd element of the numberList.
# b) Print the size of the array
# c) Delete the second element.
# d) Print the 3rd element.
def problem1():
variableBelow()
def variableBelow():
arrayForProblem1 = ["Kenn", "Kevin", "Erin", "Meka"]
print(arrayForProblem1[2])
print(len(arrayForProblem1))
arrayForProblem1.remove("Kevin")
print(arrayForProblem1[2])
problem1()
## Problem 2:
##### We will keep having this problem until EVERYONE gets it right without help
#Create a function that has a loop that quits with ‘q’. If the user doesn't enter 'q', ask them to input another string.
def loop():
userInput = input("enter a string ")
while userInput != "q" : # if userinput is not equal to "q" loop continues
userInput = input("enter another string ")
loop()
# Problem 4:
#Create an array of 5 numbers. <strong>Using a loop</strong>, print the elements in the array reverse order. <strong>Do not use a function</strong>
numList = [] # !! : this array is empty
for eachElement in range(5): # !! : you should be altering you range
numList.append(eachElement)
print(numList[:: -1]) # !! : wrong
## Problem 5:
# Create a function that will have a hard coded array then ask the user for a number. Use the userInput to state how many numbers in an array are higher, lower, or equal to it.
def problem5():
higher = 0
numbers = [1,5,20, 40, 50]
userInput = int(input("enter a number"))
for eachElement in numbers:
if userInput > numbers[0]: # !! : you are only checking the value of the first array in the item
higher = higher +1
print( str(higher) + " higher") # !! : your printing this for every iteration
elif userInput < numbers[0]:
print("lower")
else:
print("equal to")
problem5()
| true |
6557645116815000d065cf2aca60415229417617 | rkang246/data-regression | /Plot Data/plot_data.py~ | 1,915 | 4.125 | 4 | #!/usr/bin/env python2
#
# ======================================================
# Program: plot_data.py
# Author: Robert Kang
# (rkang246@gmail.com)
# Created: 2018-08-01
# Modified 2018-08-01
# ------------------------------------------------------
# Use: To plot a set of data and connect each data point
# with a simple line.
# ======================================================
#
import matplotlib.pyplot as plt
def readData(data_file):
"""
Reads the data from the input file
Args:
data_file: A file in csv format with
"x,y,std" for each row
Returns:
A 2D list x_y_std such that x_y_std[0] contains the
x-values of the data_file, x_y_std[1] contains
the y-values of the data_file, and x_y_std[2] contains
the standard deviation of the data_file.
"""
fp = open(data_file)
x_y_std = [[], [], []]
for line in fp:
line = line.strip()
line = line.decode('utf-8-sig').encode('utf-8')
row = line.split(',')
x_y_std[0].append(float(row[0]))
x_y_std[1].append(float(row[1]))
x_y_std[2].append(float(row[2]))
return x_y_std
def plot(x_values, y_values, std, title):
"""
Plots a set of data with error bars.
Args:
x_values: A float array of x-values
used for error bar purposes
y_values: A float array of y-values
used for error bar purposes
std: The standard deviation error.
title: The string graph title
Returns:
none
"""
plt.plot(x_values, y_values, color='blue')
plt.errorbar(x_values, y_values, yerr=std, fmt='o')
plt.title(title)
plt.xlabel("Time (Minutes)")
plt.ylabel("Length (Microns)")
plt.grid(True)
plt.show()
def main(data_file, title):
read_data = readData(data_file)
x_values = read_data[0]
y_values = read_data[1]
std = read_data[2]
plot(x_values, y_values, std, title)
if __name__ == "__main__":
main('sample data/wt.csv', "Wildtype Cilium Regrowth")
main('sample data/pf18.csv', "PF18 Cilium Regrowth")
| true |
9d54db62c0dbed116593bbba257b400bef643cf3 | vinodyadav7490/PythonPractice | /palindrome.py | 724 | 4.21875 | 4 | '''
what is palindrome
if string and its reverse is same then we call the string as palindrome
'''
def palindromeUsingList(s):
ps = s[::-1]
if ps == s:
return True
else:
return False
def palindromeUsingBuiltInFn(s):
ps = ''.join(reversed(s))
if ps == s:
return True
else:
return False
return
def palindromeUsingForLoop(s):
ps=''
ln =len(s)
for i in range(ln):
ps += s[ln -1 - i]
if ps == s:
return True
else:
return False
return
s = "rekha"
print("Is '%s' a palindrome" %s)
print("Using List: %s "%palindromeUsingList(s))
print("Using Built in fn: %s "%palindromeUsingBuiltInFn(s))
print("Using for loop: %s "%palindromeUsingForLoop(s)) | false |
b70c21ffd48778f8b30c0673d7bb474c7023d77d | Golgothus/Python | /Ch2/yourName.py | 565 | 4.25 | 4 | # Beginning of the end.
# I'm embarking on my journey to learn Python
# These comments will always be in the beginning of my programs
# Enjoy, Golgothus
# Ch. 2 While Statements
name = ''
while name.lower() != 'your name':
# Above statment makes the users input and forces it to all lower case
print('Please type \'your name\'.')
name = input()
print('Thank you.')
print('')
print('-----')
print('')
# Break Statements
while True:
print('Please type your name.')
name = input().lower()
if name == 'your name':
break
print('Thanks!')
| true |
5534c84906fc2bb54970d85a825749ec942088f1 | Golgothus/Python | /Ch4/tupleListExamples.py | 658 | 4.21875 | 4 | #! /usr/bin/python3
# tuples are made using () not []
print('an example of a tuple is as follows:')
print('(\'banana\',\'eggs\',\'potato\').')
print('an example of a list is as follows:')
print('[\'banana\',\'eggs\',\'potato\'].')
exampleTuple = ('eggs','potato')
exampleList = ['eggs','potato']
type(exampleTuple)
type(exampleList)
# Reference to magic methods and iteration of variables
# https://www.freecodecamp.org/news/int-object-is-not-iterable-python-error-solved/
print('Output the magic methods available for Tuple data types:')
print(dir(exampleTuple))
print('Output the magic methods avialable for List data types:')
print(dir(exampleList)) | true |
99d4bc94b4876f5e8579cecde7a4dd475ffa93b8 | Golgothus/Python | /Ch5/validate_chess_board.py | 2,503 | 4.71875 | 5 | #! /usr/bin/python
'''
In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid.
A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h';
that is, a piece can’t be on space '9z'.
The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'.
This function should detect when a bug has resulted in an improper chess board.
https://en.wikipedia.org/wiki/Algebraic_notation_(chess)
'''
import string
chessBoard = {}
ALPHABET = string.ascii_lowercase
def test_make_board():
'''Creates a dictionary as reference for the \'physical\' board.'''
for row in range(8,0,-1):
print()
for column in range(0,8,1):
print(f'{ALPHABET[column]}{row} | ',end='')
def make_board():
'''Creates the list item which will be fed into the KeyList for the Chess Board dictionary variable.'''
key_list = []
for row in range(8,0,-1):
for column in range(0,8,1):
key_list.append(ALPHABET[column]+str(row))
return key_list
def chess_board_dict():
'''Creates the dictionary variable and assigns its KeyList values.'''
for d in make_board():
chessBoard[d] = None
return chessBoard
#def add_dict():
# '''Takes the value and assigns to the associated key pairing from the chessBoard dictionary.'''
def is_valid_chess_board(chessBoardDict):
'''
A valid board will have exactly:
- one black king and exactly one white king
Each player can only have:
- 16 pieces, out of the 16, 8 will be pawns
- all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'.
'''
check_pieces(chessBoardDict)
check_position(chessBoardDict)
def check_pieces(pieces):
'''Checkes pieces are valid.'''
count = {}
for piece in pieces:
count.setdefault(piece,0)
count[piece] = count[piece] + 1
print(count)
def check_position(pieces):
'''Checks the placement is valid.'''
print(chess_board_dict())
test_make_board()
#is_valid_chess_board(chess_board_dict)
check_pieces(chessBoard)
| true |
e8deec66e76c130a49e88029d373b61ef49f24c2 | rahulrpatil/coding-interview-bootcamp | /python/fizzbuzz/index.py | 564 | 4.40625 | 4 | # Write a program that console logs the numbers
# from 1 to n. But for multiples of three print
# 'fizz' instead of the number and for the multiples
# of five print 'buzz'. For numbers which are multiples
# of both three and five print 'fizzbuzz'.
# Example
# fizzBuzz(5);
# 1
# 2
# fizz
# 4
# buzz
def fizzBuzz(n):
for i in range(1, n+1):
if(i%3==0 and i%5==0):
print("fizzbuzz")
elif(i%3==0):
print("fizz")
elif(i%5==0):
print("buzz")
else:
print(i)
fizzBuzz(15)
| false |
4e14b565661cad000f21cb9cfadd6b2d09771ad3 | JN1995/Programming-Languages | /python for Beginner/Most_used_Built_in_Functions_and_List_Comprehension.py | 1,663 | 4.5 | 4 | ## Commonly used Built-in functions in Python
# 1) Range function
# 2) Enumerate
# 3) zip
# 4) in
# 1) Range function
for num in range(10):
print(num)
for num in range(3,10):
print(num)
for num in range(0,11,2):
print(num)
my_list = [1,2,3,4,5,6,7,8,9,10]
range(10)
list(range(10))
list(range(1,11))
## 2) Enumerate
# it gives back us an index count and object itself
word = "Batman"
for letter in word:
print(letter)
for item in enumerate(word):
print(item)
# It gives the output as tuples
# And we know the tuple unpacking from for loop
for a,b in enumerate(word):
print(a,b)
for a,b in enumerate(word):
print(a)
print(b)
print("\n")
## 3) zip
list1 = [1,2,3,4,5]
list2 = ["a","b","c","d","e"]
list3 = ["a","b","d"]
zip(list1, list2)
zip(list1, list3)
for item in zip(list1, list2):
print(item)
for a,b in zip(list1, list2):
print(a,b)
for item in zip(list1, list2, list3):
print(item)
for a,b,c in zip(list1, list2, list3):
print(b)
# it will zip the items acc to shortest list
# and ignore else
## 4) in
"a" in [1,2,3]
"a" in [1,2,3, "a"]
"s" in "school"
"s" in "School"
"k1" in {"k1":100, "k2":200, "k3":300}
d = {"k1":100, "k2":200, "k3":300}
100 in d.keys()
100 in d.values()
## List comprehensions in python
my_string = "Spartans"
for letters in my_string:
print(letters)
my_list = []
for letter in my_string:
my_list.append(letter)
my_list
my_list = [letter for letter in my_string]
my_list
list1 = [asdf for asdf in range(10)]
list1 | true |
ad79810cbd5671b8ad6307d8d1b2dd0adfed9567 | JN1995/Programming-Languages | /python for Beginner/function/Lambda Expression.py | 1,294 | 4.28125 | 4 | ## Map, Filter and Lambda Expressions
# 1) map function
# 2) filter function
# 3) lambda expression
# 4) lambda expression with map and filter function
# Map function
def cal_square(n):
return n*n
cal_square(4)
my_num = [1,2,3,4,5]
map(cal_square, my_num)
list(map(cal_square, my_num))
for items in map(cal_square, my_num):
print(items)
def len_char(c):
return len(c)
my_char = ["Apple", "Banana", "Mushroom"]
list(map(len_char, my_char))
for items in map(len_char, my_char):
print(items)
## Filter function
def even_num(n):
return n % 2 == 0
my_num = [1,2,3,4,5,6,7,8,9,10]
list(filter(even_num, my_num))
for items in filter(even_num, my_num):
print(items)
## Lambda Expressions
# Stem 1
def cal_square(n):
return n*n
cal_square(3)
# Step 2
def cal_square(n):return n*n
cal_square(4)
# Step 3
cal_square = lambda n:n*n
cal_square(5)
my_list = [1,2,3,4,5]
list(map(cal_square, my_list))
list(map(lambda n:n*n, my_list))
# Step 1
def even_num(n):
return n % 2 == 0
# Step 2
def even_num(n):return n % 2 == 0
# Step 3
even_num = lambda n:n % 2 == 0
my_list = [1,2,3,4,5,6,7,8,9,10]
list(filter(lambda n:n % 2 == 0, my_list))
| false |
ec8560d4b6c63653d71fbfe6fe094e4cb1aaf198 | JN1995/Programming-Languages | /python for Beginner/datatype/List's.py | 1,224 | 4.375 | 4 | ## List's ##
# 1) concatenation
# 2) Define empty list
# 3) Indexing in list
# 4) Editing the list's
# 5) Add list into list
# 6) Python in-build functions with the list's
my_list = ["Hello", 100, 23.47]
print(my_list)
second_list = ["one", "two", "three"]
print(second_list)
print(my_list, second_list)
# 1) concatenation
new_list = my_list + second_list
print(new_list)
# 2) Define empty list
empty_list = []
print(empty_list)
# 3) Indexing in list
students = ["Robert", "Chris", "Katarina", "Scarlett"]
students
students[0]
students[2]
students[-1]
students[0:2]
# 4) Editing the list's
# Replace values
students[0] = "Sam"
students
# Add values
students.append("Paul")
students
# Remove values
students.remove("Scarlett")
students
list1 = ["one", "two", "three", "four", "five"]
list1
list1.pop()
list1.pop(0)
list1
# 5) Add list into list
color = ["Red", "Green", "Blue", "Violet"]
color
age = [21, 23, 25, 27]
age
color.extend(age)
color
# 6) Python in-build functions with the list's
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd
numbers
print(sorted(numbers))
len(numbers)
max(numbers)
min(numbers)
| true |
5ded636ffafb656e05509d03e6d272fc3323e43f | phaustin/eoas_nbgrader | /Notebooks/python/NotebookStudent4.py | 934 | 4.40625 | 4 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.2.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# Question 1
#
# a) pyplot can produce polar graph. The format to use the method is objectname.method(variable1, variable2). Enter a statement in the cell below that will create a polar graph. Please run the code with your statement to display the graph.
#
#
# %% {"nbgrader": {"schema_version": 3, "solution": true, "grade": true, "locked": false, "task": false, "points": 1, "grade_id": "cell-a98f885f7f0fb08f"}}
import numpy as np
import matplotlib.pyplot as plt
cos = np.cos
pi = np.pi
a = 5
e = 0.3
theta = np.linspace(0,2*pi, 360)
r = (a*(1-e**2))/(1+e*cos(theta))
##enter your statement here##
plt.show()
| true |
662701aaf99b8b5fed985c3ebcf20018f373c82d | alenavee/cs102 | /homework01/caesar.py | 1,322 | 4.5 | 4 | def encrypt_caesar(plaintext) -> str:
"""
Encrypts plaintext using a Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
"""
ciphertext = ''
shift = 3
for ch in plaintext:
if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
if ord('Z') < ord(ch) + shift < ord('a') or ord(ch) + shift > ord('z'):
ciphertext += chr(ord(ch) + shift - 26)
else:
ciphertext += chr(ord(ch) + shift)
else:
ciphertext += ch
return ciphertext
def decrypt_caesar(ciphertext) -> str:
"""
Decrypts a ciphertext using a Caesar cipher.
>>> decrypt_caesar("SBWKRQ")
'PYTHON'
>>> decrypt_caesar("sbwkrq")
'python'
>>> decrypt_caesar("Sbwkrq3.6")
'Python3.6'
>>> decrypt_caesar("")
''
"""
plaintext = ''
shift = 3
for ch in ciphertext:
if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
if ord('Z') < ord(ch) - shift < ord('a') or ord(ch) - shift < ord('A'):
plaintext += chr(ord(ch) - shift + 26)
else:
plaintext += chr(ord(ch) - shift)
else:
plaintext += ch
return plaintext
| false |
b5e14aa7c7d4fe50bb56b8b83de4e00afa91d8e3 | Alex-HK-Code/Mini-Database-Exercise | /main.py | 503 | 4.15625 | 4 | books = [] #this is used to store new inputs
while(True):
user_selection = input("Enter '1' to add a new book | Enter '2' to view all books | Enter '3' to quit the program\n")
if(user_selection == str(0)): #str(0) == '0'
break
if(user_selection == str(1)): #str(1) == '1'
book_name = input("Enter Book Name\n")
books.append(book_name)
elif(user_selection == str(2)): #str(2) == '2'
for book in books: #books is a list, each iteration handles an element as book
print(book)
| true |
a71d6595e324adbed8851eea163ad68550a11c1f | Varun901/Small-Projects | /McMaster GPA Calculator.py | 961 | 4.3125 | 4 | from operator import mul
def sum_func(units, grades):
""" For product below you can also use the following commands:
1. [a*b for a,b in zip(a,b)]
2. import numpy as np
product = np.multiply(units,grades)
"""
product = map(mul,units,grades)
sum_product = sum(product)
return sum_product
def num_func(units):
total_units = sum(units)
return total_units
def avg_func(sum_product, total_units):
cumulative_GPA = sum_product / total_units
return cumulative_GPA
def main():
course_units = [int(x) for x in input("Enter your course units, each one separated by a space: ").split()]
course_grades = [int(x) for x in input("Enter your course grades in the same order as your units, each one separated by a space: ").split()]
sum_product = sum_func(course_units,course_grades)
total_units = num_func(course_units)
gpa = avg_func(sum_product, total_units)
print ("The student's GPA is %.1f." % (gpa))
main() | true |
06c6af3f560ea8d3f428aa85bdfa8d188c6a9124 | yzziqiu/python-class | /labs/lab2-payment-modi.py | 1,374 | 4.15625 | 4 | # lab2
# algebraic equation
# payment = (((1+rate)^years)*principal*rate/(1+rate)^years-1)
# use variables and two decimal places
# find out annual and monthly payment
principal_in = ((raw_input('Please enter the amount you borrowed:')))
# enter with dollar sign
principal = float(principal_in.replace('$',''))
#print principal
rate_in = ((raw_input('Please enter the interest rate:')))
# enter with %
if rate_in.find('%') == -1:
rate = float(rate_in)
#print rate
else:
rate_hundred = float(rate_in.replace('%',''))
rate = float(rate_hundred/100)
#print rate
years = (input('Please enter the year you required to repay the loan:'))
#print years
#print("Annual payment is:")
print("Annual payment is:"+"{:.2f}".format((principal*((1+rate)**(years))*rate)/((1+rate)**years-1)))
# output
payment = (principal*((1+rate)**(years))*rate)/((1+rate)**years-1)
mon_payment = payment/12
print ("Monthly payment is:""{:.2f}".format(mon_payment))
print ("Total payment for life is:"+"{:.2f}".format(years*payment))
# input income
income = float((input('Please enter the annual income:')))
mon_income = float(income/12)
if mon_payment > mon_income:
if rate >= .05:
print("you should refinance")
else:
print("you should seek financial counseling")
else:
print("make sure to make all payment on time")
| true |
e8a7e98aa75a0e8e2ce1cabda5fb98732803e990 | yzziqiu/python-class | /notes/week2-notes.py | 1,644 | 4.21875 | 4 | # week2-notes
# python week2-notes.py
# array index print
test_string = "hello world"
print(test_string)
# hell
print('"{0}"'.format(test_string[0:4]))
#hell
print('"{0}"'.format(test_string[:4]))
#hello world
print('"{0}"'.format(test_string[0:]))
#hello world
print('"{0}"'.format(test_string[:]))
#ello worl
print('"{0}"'.format(test_string[1:10]))
#hello worl
print('"{0}"'.format(test_string[:10]))
#hello worl
# except the last one
print('"{0}"'.format(test_string[:-1]))
#hello wo
# excpet rld
print('"{0}"'.format(test_string[0:-3]))
#d
print('"{0}"'.format(test_string[-1:]))
#""
print('"{0}"'.format(test_string[-3:3]))
# conditional
name = input('please enter your name:')
if len(name) > 5:
print ('your name is too long!')
else:
print('your name is too short!')
print("------------------------")
if len(name) > 10 and name[:1].lower() == 'j':
print("your name is really long")
elif len(name) > 5 or name[0].lower() =='j':
print ('your name is too long!')
else:
print('your name is too short')
# oepration boolean
a = None
b = ''
print("{} is {}:{}".format(a, a, a is a))
print("{} == {}:{}".format(a, a, a == a))
print("{} is {}:{}".format(a, b, a is b))
print("{} is {}:{}".format(a, b, a is not a))
print("{} != {}:{}".format(a, b, a != a))
a= "abc"
b = "abcd"
print("{} is {}:{}".format(a, b, a is b))
print("{} == {}:{}".format(a, b, a == b))
print("{} == {}:{}".format(a, b[:3], a == b[:3]))
a= "[1,2,3]"
b = "[1,2,3,4]"
print("{} is {}:{}".format(a, b, a is b))
print("{} == {}:{}".format(a, b, a == b))
print("{} == {}:{}".format(a, b[:3], a == b[:3]))
print("{} is {}:{}".format(a, b[:3], a is b[:3]))
| false |
4c10480ed9277a02275d13d06a07902de5e15d6e | theskinnycoder/python-lab | /week8/b.py | 662 | 4.1875 | 4 | '''
8b. Write a program to convert the passed in positive integer number into its prime factorization form
'''
from math import sqrt
def get_prime_factorization_form(num):
ans_list = []
for factor in range(2, int(sqrt(num)) + 1):
count = 0
while num % factor == 0:
count += 1
num /= factor
if count > 0:
ans_list.append((int(factor), count))
# If still any prime factor is left
if num > 2:
ans_list.append((int(num), 1))
return ans_list
num = int(input('Enter any number : '))
print(f'The prime factorization form of {num} is : {get_prime_factorization_form(num)}') | true |
48514e765b3a19947c7056197e9bac63626c6a62 | theskinnycoder/python-lab | /week2/a.py | 418 | 4.1875 | 4 | '''
2a. Write a program to get the number of vowels in the input string (No control flow allowed)
'''
def get_number_of_vowels(string):
vowel_counts = {}
for vowel in "aeiou":
vowel_counts[vowel] = string.count(vowel)
return sum(vowel_counts.values())
input_string = input('Enter any string : ')
print(f'The number of vowels in {input_string} are : {get_number_of_vowels(input_string.lower())}') | true |
1ec4ab7cc18b0a158484a300fb3a6011d3ac6ff0 | brunozupp/TreinamentoPython | /aula7/teste3.py | 458 | 4.15625 | 4 | if __name__ == '__main__':
n1 = int(input('Número 1: '))
n2 = int(input('Número 2: '))
s = n1 + n2;
m = n1 * n2;
d = n1 / n2;
di = n1 // n2;
e = n1 ** n2
#print('A soma é {}, o produto é {}, e a divisão é {:.3f}'.format(s,m,d))
print('A soma é {}, \no produto é {}, e a divisão é {:.3f}'.format(s,m,d), end=" ") # para ficar na mesma linha usa o end
print('Divisão inteira {} e potência {}'.format(di,e)) | false |
6615d75240973f3f1596e8ebea0a58763ab31663 | brunozupp/TreinamentoPython | /exercicios/exercicio033.py | 532 | 4.1875 | 4 | if __name__ == '__main__':
num1 = int(input("Digite o número 1 = "))
num2 = int(input("Digite o número 2 = "))
num3 = int(input("Digite o número 3 = "))
if num1 >= num2 and num1 >= num3:
print(f"{num1} maior")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} maior")
else:
print(f"{num3} maior")
if num1 <= num2 and num1 <= num3:
print(f"{num1} menor")
elif num2 <= num1 and num2 <= num3:
print(f"{num2} menor")
else:
print(f"{num3} menor") | false |
c44c80c53f14499d0c65e63f469230a4996baa2e | brunozupp/TreinamentoPython | /aula17/teste1.py | 1,789 | 4.28125 | 4 | if __name__ == '__main__':
# LISTA SÃO MUTÁVEIS
num = [3, 2, 1, 4, 5]
print(num)
print("-" * 30)
num[2] = 6
print(num)
print("-" * 30)
num.append(7)
print(num)
print("-" * 30)
num.sort()
print(num)
print("-" * 30)
num.sort(reverse=True)
print(num)
print("-" * 30)
num.insert(0,74) # Na posição 0, insira o valor 74
print(num)
print("-" * 30)
num.pop() # sem nenhum parametro ele vai eliminar o último elemento
print(num)
print("-" * 30)
num.pop(1)
print(num)
print("-" * 30)
if 74 in num:
num.remove(74)
print(num)
print("-" * 30)
if 109 in num:
num.remove(709)
else:
print("NÃO ACHEI O NÚMERO 109")
print(num)
print("-" * 30)
num.append(2)
num.append(2)
print(num)
print("-" * 30)
num.remove(2) # vai remover apenas o primeiro 2 que ele encontrar
print(num)
print("-" * 30)
valores = []
valores.append(5)
valores.append(9)
valores.append(4)
for index,value in enumerate(valores):
print(f"Na posição {index} encontrei o valor {value}")
print("Cheguei no final")
print("-" * 30)
a = [2,3,4,7]
b = a # ambas as variáveis estão apontando para o mesmo espaço de memória
b[2] = 8 # então mudando aqui, a mudança vai refletir nas duas variáveis
print(f"Lista A: {a}")
print(f"Lista B: {b}")
print("-" * 30)
c = [2,3,4,7]
d = c[:] # com essa sintaxe vai criar uma cópia do array, vai ser duas caixas na memória diferentes que c e d vão apontar
d[2] = 8 # então mudando aqui, a mudança só vai refletir na lista apontada pela variável d
print(f"Lista C: {c}")
print(f"Lista D: {d}")
| false |
0c5e6f7b4958e48e90ffa1d5ea40c5a65c2fe990 | sarbajitmohanty/OOPS-Python | /Polymorphism.py | 688 | 4.15625 | 4 | class Students:
def __init__(self, fname, lname, email):
self.fname = fname
self.lname = lname
self.email = email
def fullName(self):
print(self.fname.capitalize() + " " + self.lname.capitalize())
class Teachers:
def __init__(self, fname, lname, email):
self.fname = fname
self.lname = lname
self.email = email
def fullName(self):
print(self.fname.capitalize() + " " + self.lname.capitalize())
student1 = Students("sarbajit", "mohanty", "abc.xyz@gmail.com")
student1.fullName()
student2 = Students("John", "doe", "pqr.def@gmail.com")
student2.fullName()
teacher1 = Teachers("emma", "stone", "emmastone@gmail.com")
teacher1.fullName() | false |
b77879c0e990b72f693b7a7e61ef41a4d97ce239 | AmilaSamith/snippets | /Python-data-science/lambda_functions.py | 848 | 4.15625 | 4 | # Lambda fuctions
"""
lambda syntax
----------------------------------------------------------------
lambda (inputs) : (output_expression)
"""
# Example 01
add = lambda x,y: x + y
print(add(4,6))
print((lambda x,y: x + y)(4,10))
# Example 02
ages = {"michel":50,"martha":45,"vince":18,"Hilton":23}
def getVal(item):
return item[1]
sortedList = sorted(ages.items(), key=getVal)
print(ages)
print(sortedList)
# Similar Lambda function
lambdaSorted = sorted(ages.items(), key= lambda item: item[1])
print(lambdaSorted)
# Example 03 : Filter data from a list
nums = [11,12,45,78,147,56,89,22,48,102]
# Get list of odd numbers
odds = filter(lambda num: num%2 == 1,nums)
print(list(odds))
# Example 04 : Perform an operation to each elemnt in a list
nums = [x for x in range(20)]
sqr = map(lambda x:x**2,nums)
print(list(sqr)) | false |
84f8f5df072c9e6bc9d026daada6f3ddf90eea47 | AmilaSamith/snippets | /Python-data-science/if_statement.py | 885 | 4.375 | 4 | # if statement
"""
Single if statement
----------------------------------------------------------------
if(condition):
(code to be executed if condition is True)
if-else statement
----------------------------------------------------------------
if(condition):
(code to be executed if condition is True)
else:
(code to be executed if condition is False)
elif statement
----------------------------------------------------------------
if(condition1):
(code to be executed if condition is True)
elif(condition2):
(code to be executed if condition1 is False and condition2 is True)
else:
(code to be executed all conditions are False)
"""
# simple example
num = 0
if (num == 0):
print("Number is zero")
elif(num>0):
print("Number is Positive")
else:
print("Number is Negative")
| true |
1d273a7086c4554096a9724085d304a21cfcaa53 | dim4o/python-samples | /dynamic-programming/max_sum_subsequence_non_adjacent.py | 1,004 | 4.28125 | 4 | def find_max_non_adjacent_subsequence_sum(sequence):
"""
Given an array of positive number, find maximum sum subsequence such that elements
in this subsequence are not adjacent to each other.
For better context see: https://youtu.be/UtGtF6nc35g
Example: [4, 1, 1, 4, 2, 1], max_sum = 4 + 4 + 1 = 9
Rule:
temp = incl
incl = max(incl, excl + sequence[i])
excl = temp
...
max_subseq = max(incl, excl)
:param sequence: the given sequence
:return: max subsequence sum
"""
incl = 0
excl = 0
for i in range(len(sequence)):
temp = incl
incl = max(incl, excl + sequence[i])
excl = temp
return max(incl, excl)
# test
print(find_max_non_adjacent_subsequence_sum(sequence=[1])) # 1
print(find_max_non_adjacent_subsequence_sum(sequence=[7, 8])) # 8
print(find_max_non_adjacent_subsequence_sum(sequence=[4, 1, 1, 4, 2, 1])) # 9
print(find_max_non_adjacent_subsequence_sum(sequence=[1, 2, 9, 10, 6, 7, 12])) # 28
| true |
fc264f6a5a5b7142c7ce9bc619af9e046d578777 | dim4o/python-samples | /dynamic-programming/total_ways_in_matrix.py | 838 | 4.125 | 4 | def calc_total_ways(rows, cols):
"""
Given a 2 dimensional matrix, how many ways you can reach bottom right
from top left provided you can only move down and right.
For better context see: https://youtu.be/GO5QHC_BmvM
Example with 4x4 matrix:
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20 -> the total number of ways is 20
:param rows: number of matrix rows
:param cols: number of matrix columns
:return: the total number of ways from top left to bottom right corner
"""
matrix = [[1]*cols for _ in range(rows)]
for i in range(1, rows):
for j in range(1, cols):
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
return matrix[rows - 1][cols - 1]
# test
print(calc_total_ways(4, 4)) # 20
print(calc_total_ways(4, 1)) # 1
print(calc_total_ways(4, 5)) # 35
| true |
0a8110b50e90fa492f518f18de598d79143a0d29 | dim4o/python-samples | /dynamic-programming/weighted_job_scheduling.py | 1,736 | 4.25 | 4 | def find_best_schedule(jobs):
"""
Given certain jobs with start and end time and amount you make on finishing the job,
find the maximum value you can make by scheduling jobs in non-overlapping way.
For better context see: https://youtu.be/cr6Ip0J9izc
Example:
(start_time, end_time, value)
(1,3, 5) (2, 5, 6) (4, 6, 5) (6, 7, 4) (5, 8, 11) (7, 9, 2) -> jobs
5 6 5 4 11 2 -> values
5 6 10 14 17 16 -> best_values
The maximum is 17 = 11 + 6
Rule:
if jobs[i] and jobs[j] are not overlapped:
values[i] = max(values[i], values[j] + jobs[i][2])
:param jobs: list of jobs
:return: the maximum value you can take from the jobs
"""
# sort the jobs by the end time
jobs = sorted(jobs, key=lambda job: job[1])
values = [jobs[i][2] for i in range(len(jobs))]
prev_arr = [-1] * len(jobs)
best_index = 0
i = 1
j = 0
while i < len(values):
while j < i:
# if the jobs are not overlapped
if jobs[j][1] <= jobs[i][0]:
values[i] = max(values[i], values[j] + jobs[i][2])
if values[i] > values[best_index]:
best_index = i
prev_arr[i] = j
j += 1
i += 1
j = 0
# reconstruct the best path
best_path = []
while best_index > -1:
best_path.append(jobs[best_index][2])
best_index = prev_arr[best_index]
return best_path
# test
max_path = find_best_schedule([(2, 5, 6), (4, 6, 5), (6, 7, 4), (7, 9, 2), (1, 3, 5), (5, 8, 11)])
print("{} -> {}".format(sum(i for i in max_path), max_path)) # 17 -> [11, 6]
| true |
de7cd735d609c6090ad37cc010ca0ee27992ab78 | dim4o/python-samples | /dynamic-programming/box_stacking.py | 2,675 | 4.34375 | 4 | def find_max_height(boxes):
"""
Given boxes of different dimensions, stack them on top of each other to get maximum height
such that box on top has strictly less length and width than box under it.
For better context see: https://youtu.be/9mod_xRB-O0
This algorithm is actually like "longest increasing subsequence" algorithm
:param boxes: list of boxes (l, w, h)
:return: list of boxes with maximum height
"""
# generates all possible boxes
all_boxes = []
for box in boxes:
# length width height
all_boxes.append((box[0], box[1], box[2]))
all_boxes.append((box[0], box[2], box[1]))
all_boxes.append((box[2], box[1], box[0]))
all_boxes = sorted(all_boxes, key=lambda b: b[0] * b[1], reverse=True)
# uses the longest increasing subsequence algorithm to find the maximum height
max_arr = []
indexes = [-1] * len(all_boxes)
for box in all_boxes:
max_arr.append(box[2])
best_index = -1
i = 1
j = 0
while i < len(all_boxes):
while j < i:
if is_on_top(all_boxes[j], all_boxes[i]):
max_arr[i] = max_arr[j] + all_boxes[i][2]
indexes[i] = j
if max_arr[i] > indexes[best_index]:
best_index = i
j += 1
i += 1
j = 0
# reconstruct the result
result = []
while best_index >= 0:
result.append(all_boxes[best_index])
best_index = indexes[best_index]
result.reverse()
return max_arr[best_index], result
def is_on_top(box_1, box_2):
"""
Checks whether a box is on top of another box
:param box_1: list representation of a box
:param box_2: list representation of a box
:return: whether box_2 is on top of box_1
"""
if (box_2[0] < box_1[0] and box_2[1] < box_1[1]) or (box_2[0] < box_1[1] and box_2[1] < box_1[0]):
return True
return False
def print_result(result):
print("Max height: {}, Boxes: {}".format(result[0], result[1]))
# test
print_result(find_max_height(((1, 2, 4), (3, 2, 5)))) # Max height: 11, Boxes: [(3, 5, 2), (3, 2, 5), (1, 2, 4)]
print_result(find_max_height(((2, 1, 4), (5, 2, 3)))) # Max height: 11, Boxes: [(5, 3, 2), (3, 2, 5), (2, 1, 4)]
print_result(find_max_height(((4, 6, 7), (1, 2, 3), (4, 5, 6), (10, 12, 32))))
# Max height: 60, Boxes: [(32, 12, 10), (10, 12, 32), (7, 6, 4), (6, 5, 4), (4, 5, 6), (3, 2, 1), (1, 2, 3)]
print_result(find_max_height(((7, 4, 6), (3, 1, 2), (6, 4, 5), (32, 10, 12))))
# Max height: 60, Boxes: [(32, 12, 10), (12, 10, 32), (7, 6, 4), (6, 5, 4), (5, 4, 6), (3, 2, 1), (2, 1, 3)]
| true |
5ff36bc06f94a32dab69de7398a305f891db2669 | greseam/module5_python_practice_SMG | /Module 5/mod5_hw1_task1_SMG.py | 647 | 4.28125 | 4 | ######
# String counter
#
# Sean Gregor
#
#desc: count the number of occurances in a string of characters for a specific character
######
def stringCounter():
userString = input("Please enter a string: ")
searchChar = input('Enter a charater of this string to know its position: ')
charCount = userString.count(searchChar) #counts the number of occurances
charPos = userString.find(searchChar) #finds the first position of character
print('Number of',"'",searchChar,"'",'in the string',"'",userString,"'",':',charCount)
print('It first occurs at position',charPos+1)
if __name__=="__main__":
stringCounter() | true |
7003780f6609399c2a290dcbba2f9a82be060a01 | MuhammadYossry/MIT-OCW-6-00sc | /ps1/ps1a.py | 1,132 | 4.53125 | 5 | # A program to calculate and print the credit card balance after one year if a person only pays the
# minimum monthly payment required by the credit card company each month.
balance = float(raw_input('Enter the outstanding balance on your credit card:'))
annual_interest_rate = float(raw_input('Enter the annual credit card interest rate as a decimal:'))
monthly_interest_rate = annual_interest_rate / 12.0
min_monthly_payment_rate = float(raw_input('Enter the minimum monthly payment rate as a decimal:'))
total_amount_paid = 0
for i in range(1,13):
print("Month %i" % (i,))
min_monthly_payment = min_monthly_payment_rate * balance
interest_paid = monthly_interest_rate * balance
principal_paid = min_monthly_payment - interest_paid
balance -= principal_paid
print("Minimum monthly payment: $%.2f" % (min_monthly_payment,))
print("Principle paid: $%.2f" % (principal_paid,))
print("Remaining balance: $%.2f" % (balance,))
total_amount_paid += principal_paid + interest_paid
print 'RESULT'
print "Total amount paid: $%.2f" % (total_amount_paid,)
print "Remaining Balance: $%.2f" % (balance,)
| true |
afd25e49906b4dcf0f76a84f2ca098fa6a927693 | venilavino/mycode | /palindrome_number.py | 235 | 4.3125 | 4 | num = raw_input("Enter any number: ")
rev_num = reversed(num)
# check if the string is equal to its reverse
if list(num) == list(rev_num):
print("Palindrome number")
else:
print("Not Palindrome number")
| true |
5bf7078e98af056f45d0601c42d643328fd930ce | Fargolee/practice | /3-列表简介/3.2.1-修改列表元素.py | 1,446 | 4.15625 | 4 | motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# 1、修改:利用索引赋值
# motorcycles[0] = 'ducati'
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['ducati', 'yamaha', 'suzuki']
# 2、list.append(a) 添加
# motorcycles.append('ducai')
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha', 'suzuki', 'ducai']
# 3、list.insert(index,a) 插入
# motorcycles.insert(0, 'ducati')
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['ducati', 'honda', 'yamaha', 'suzuki']
# 4、del list[index] 删除元素
# del motorcycles[0]
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['yamaha', 'suzuki']
# 5、list.pop()删除元素,并接着使用它的值
# popped_motorcycle = motorcycles.pop()
# print(motorcycles)
# print(popped_motorcycle)
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha']
# suzuki
# 6、弹出列表中任何位置的元素
# first_owned = motorcycles.pop(0)
# print('The first motorcycle I owned was a ' + first_owned.title())
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# The first motorcycle I owned was a Honda
# ['yamaha', 'suzuki']
# 7、list.remove() 根据值删除元素,并可以继续使用值
too_expensive = 'yamaha'
motorcycles.remove(too_expensive)
print(motorcycles)
print('\nA '+too_expensive.title()+' is too expensive for me.')
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'suzuki']
# A Yamaha is too expensive for me.
| false |
4a2ff55c0dbfb64e9500f13c939031c6241504f7 | pmazgaj/tuition_advanced | /biblioteki/Pozostałe/[1] Dekoratory/zadania/[DEKORATORY] [3] przypadki_użycia.py | 1,070 | 4.25 | 4 | def argument_test_natural_number(f):
""" Check, if given number is an integer, and then decorate with it, for factorial operation """
def helper(x):
if isinstance(x, int) and x > 0:
return f(x)
else:
raise Exception("Argument is not an integer")
return helper
@argument_test_natural_number
def factorial(n):
""" Calculate factorial for given number """
return 1 if n == 1 else n * factorial(n - 1)
for i in range(1, 10):
# print(i, factorial(i))
pass
# print(factorial(-1))
def call_counter(func):
"""
The following example uses a decorator to count the number of times a function has been called.
To be precise, we can use this decorator solely for functions with exactly one parameter:
"""
def helper(x):
helper.calls += 1
return func(x)
helper.calls = 0
return helper
@call_counter
def succ(x):
return x + 1
print(succ.calls)
for i in range(10):
succ(i)
pass
print("Calls of function {}: {}".format(succ.__name__, succ.calls))
| true |
e92fed1a1019b98e68ebcf5c5e4a5a3b3fd529a6 | Unkerpaulie/tyrone | /hangman/hangman.py | 1,602 | 4.1875 | 4 | import random
import time
# create list of words
words = ["ADVICE", "BREATHE", "COMPLAIN", "DELIVER", "EXAMPLE", "FORGETFUL", "GRADUATE", "HIBERNATE", "INFERIOR", "JUSTIFY"]
# choose a random word from the list
word = random.choice(words)
chances = 5
letters_guessed = []
letter = ""
def clear():
# prints a number of empty lines to look as if the screen is cleared
print("\n" * 40)
def display_word(letters):
# displays dashes for each letter of the word and fills in as letters are guessed
display = ""
for i in range(0, len(word)):
if word[i] in letters:
display += word[i]
else:
display += "-"
return display
# welcome user
print("Hello, Welcome to Hangman")
input("Press enter to begin...")
# main game loop
while chances > 0:
clear()
# only accept 1 letter input, store it as uppercase
if len(letter) == 1:
letters_guessed.append(letter.upper())
if letter.upper() in word:
print(f"Excellent! {letter.upper()} is in the word.")
else:
print(f"Sorry! {letter.upper()} is not in the word.")
chances -= 1
print(display_word(letters_guessed))
print(f"Chances left: {chances}")
# check if game won or lost
if chances == 0:
print(f"Sorry, you lost the game. The word was {word}")
break
elif "-" not in display_word(letters_guessed):
print("Great job! You got the word!")
break
else:
letter = input("Guess a letter: ")
print("Game Over") | true |
f27c46082da7df69872d5d588973a913192d8fd4 | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk19/fraction.py | 2,117 | 4.1875 | 4 | class Fraction:
def __init__(self, numerator=1, denominator=1, decimal=0.5, numerator2=0, denominator2=0):
self.numerator=numerator
self.denominator=denominator
self.decimal=decimal
self.numerator2=numerator2
self.denominator2=denominator2
def simplify(self):
'''
determines what the greatest common divisor is for 2 integers
@param lis=list containing integers to help sort them, meaning that this could be expanded by adding more variables in
@param i=minimum number of the integers that could be used as a starting point to count down from
@param fraction=reduced fraction as a string
returns fraction
'''
try:
lis=[int(self.numerator),int(self.denominator)]
i=min(lis)
if int(self.numerator)%i != 0 or int(self.denominator)%i != 0:
while int(self.numerator)%i!=0 or int(self.denominator)%i!=0:
i-=1
self.numerator=int(self.numerator)/i
self.denominator=int(self.denominator)/i
fraction=str(round(self.numerator))+"/"+str(round(self.denominator))
return fraction
except:
print("To infinity and beyond.")
def convertToFraction(self):
'''
converts a decimal to a fraction
@param length=number of significant figures
'''
try:
length=len(str(self.decimal).lstrip("0."))
self.numerator=10**length * float(self.decimal)
self.denominator=10**(len(str(self.decimal))-2)
except:
print("Unhandled exception in conversion.")
def getDecimal(self):
return self.decimal
def addFractions(self):
'''
adds two fractions together
'''
try:
self.numerator=self.numerator*self.denominator2
self.numerator2=self.numerator2*self.denominator
self.numerator=self.numerator+self.numerator2
self.denominator=self.denominator*self.denominator2
except:
print("Unhandled exception.")
| true |
eea921d913b7fe42cb4cc2c77f3cb3f126a783df | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk18/007_alphabeticalOrder.py | 786 | 4.21875 | 4 | def alphabeticalOrder(L):
'''
alphabeticalOrder()=checks to see if input list of letters has letters
in abc order
@param L=input list
'''
try:
abc=False
if len(L)==1:
abc=True
elif L[0]<=L[1]:
abc=alphabeticalOrder(L[1:])
return abc
except:
print("Unhandled exception.")
if __name__=="__main__":
def test_alphabeticalOrder():
'''
tests if list is in abc order
@param L=test list in abc order
@param LNot=test list not in abc order
prints whether list is in abc order
'''
L=["a","b","c"]
LNot=["a","c","b"]
print("Is the list in abc order: ", alphabeticalOrder(L))
print("Is the list in abc order: ", alphabeticalOrder(LNot))
test_alphabeticalOrder()
| true |
842c85348f7e451517ef5b13913fae33edbbb66c | haoknowah/OldPythonAssignments | /Gaston_Noah_nkn328_Hwk04/chapRev#6_lengthConversion.py | 1,248 | 4.46875 | 4 | def lengthConvertion():
'''
converts the units of miles, yards, feet, and inches to kilometers, meters, and
centimeters
@param m=miles
@param y=yards
@param f=feet
@param i=inches
@param ti=total inches
@param tmeters=total meters
@param km=kilometers
@param meters=meters
@param cm=centimeters
Note the commentary, also I remember you mentioning something about documentation
using #, but I don't remember what it was. Are you going to create some sort of
master documentation template that shows how we need to document our programs
'''
try:
m=int(input("Enter number of miles: "))
y=int(input("Enter number of yards: "))
f=int(input("Enter number of feet: "))
i=int(input("Enter number of inches: "))
print("Metric length: ")
print("Hamster wheels going full power.")
ti=63360*m+36*y+12*f+i
tmeters=ti/39.37
km=int(tmeters/1000)
meters=int(tmeters%1000)
cm=float(round(100*(tmeters%1), 1))
print("Done. After conversion it is: ")
print(km, "kilometers")
print(meters, "meters")
print(cm, "centimeters")
except:
print("Use Google.")
if __name__ =="__main__":
print(__name__)
lengthConvertion()
| true |
151287d178e0acd653ceb0bcfc9ded9508d04790 | singhwarrior/python | /python_samples/python-advance/01_oop/03_polymorphism/02_operator_overloading.py | 1,230 | 4.625 | 5 | # Operator Overloading
# There are multiple kinds of operators in Python
# For example : +, -, /, * etc. But what happens
# behind the scene is there is function called for
# every such operator. Like __add__, __sub__, __div__
# __mul__ etc. These are called "Magic Functions".
# We can also apply such kinds of operators for our
# objects by overriding the Magic Functions which is
# called Operator overloading.
class Complex:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x_new = self.x + other.x
y_new = self.y + other.y
return Complex(x_new, y_new)
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __str__(self):
return f"{self.x}+{self.y}i"
if __name__ == "__main__":
c1 = Complex(2,3)
c2 = Complex(4,5)
# Applying '+' operator on Complex Numbers is possible
# due to Operator overloading
c = c1+c2
print(c)
# Comparing two complex numbers using '==' is possible
# due to Operator overloading
if c1 == c2:
print("Equal")
else:
print("Unequal")
c3 = Complex(2, 3)
# Comparing two complex numbers using '==' is possible
# due to Operator overloading
if c1 == c3:
print("Equal")
else:
print("Unequal")
| true |
78a18efdd547fc5836c16269fd94e612c41337d4 | dustinrubin/FiLLIP | /alternatingCharacters/alternatingCharactersDustin.py | 417 | 4.15625 | 4 | #!/bin/python3
# Complete the alternatingCharacters function below.
def alternatingCharacters(string):
lastCharater = ''
deletedCharacters = 0
for charater in string:
if not lastCharater:
lastCharater = charater
continue
if lastCharater == charater:
deletedCharacters += 1
else:
lastCharater = charater
return deletedCharacters
| true |
4397a6dbfd69f8db91620efcdefb408d4218791a | 90sidort/exercises_Python | /domain_Name.py | 709 | 4.25 | 4 | # Description: https://www.codewars.com/kata/514a024011ea4fb54200004b/python
# Short task summary:
# Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
# domain_name("http://github.com/carbonfive/raygun") == "github"
# domain_name("http://www.zombie-bites.com") == "zombie-bites"
# domain_name("https://www.cnet.com") == "cnet"
# My solution:
import re
def domain_name(url):
if 'http' in url and 'www' not in url:
return (re.search('//(.*)', url).group(1)).split('.')[0]
elif 'www' in url:
return (re.search('www.(.*)', url).group(1)).split('.')[0]
else:
return url.split('.')[0] | true |
15cd9bee66293582f4ef789cd30527269b7d4a29 | 90sidort/exercises_Python | /the_Vowel_Code.py | 988 | 4.1875 | 4 | # Description: https://www.codewars.com/kata/53697be005f803751e0015aa
# Short task summary:
##Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:
##
##a -> 1
##
##e -> 2
##
##i -> 3
##
##o -> 4
##
##u -> 5
##
##For example, encode("hello") would return "h2ll4" There is no need to worry about uppercase vowels in this kata.
##
##Step 2: Now create a function called decode() to turn the numbers back into vowels according to the same pattern shown above.
##
##For example, decode("h3 th2r2") would return "hi there"
##
##For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.
# My solution:
def encode(st):
return st.replace('a', '1').replace('e', '2').replace('i', '3').replace('o', '4').replace('u', '5')
def decode(st):
return st.replace('1', 'a').replace('2', 'e').replace('3', 'i').replace('4', 'o').replace('5', 'u')
| true |
69d051a8ac8a5e58e710f1ce69b527537403abc6 | 90sidort/exercises_Python | /hydrate.py | 952 | 4.125 | 4 | # Description: https://www.codewars.com/kata/5aee86c5783bb432cd000018/python
# Short task summary:
##Welcome to the Codewars Bar!
##
##Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning.
##
##Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover.
##Example parties:
##Input 0:
##
##"1 beer"
##Output 0:
##
##"1 glass of water"
##Explaination 0:
##
##You drank one standard drink
##Input 1:
##
##"1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer"
##Output 1:
##
##"10 glasses of water"
##Explaination 1:
##
##You drank ten standard drinks
# My solution:
def hydrate(drink_string):
glasses = str(sum([int(x) for x in drink_string if x.isdigit()]))
return glasses + " glasses of water" if glasses != "1" else glasses + " glass of water"
| true |
73a57d6fa0dd8ca1ef3e795b4bd95cf07f942355 | rodcoelho/python-practice | /archived_problems/amazon_majority_element.py | 968 | 4.1875 | 4 | #!/usr/bin/env python3
# Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
# Output: For each test case the output will be the majority element of the array. Output "-1" if no majority element is there in the array.
def get_majority(s):
arr = s.split(" ")
arr = [int(x) for x in arr]
threshold = len(arr) / 2
max = {}
max_count = 1
for i in range(len(arr)):
if arr.count(arr[i]) > threshold:
if arr.count(arr[i]) > max_count:
max[arr.count(arr[i])] = arr[i]
max_count = arr.count(arr[i])
if max_count == 1:
return "-1"
else:
return str(max[max_count])
if __name__ == "__main__":
assert get_majority("3 1 3 3 2") == "3", 'error1'
assert get_majority("1 2 3") == "-1", 'error2'
print("TESTS PASSED")
| true |
3bc230e6df8bf0e597c4958bf9104cb9bc330a50 | rodcoelho/python-practice | /archived_problems/amazon_pythagorean_triplet.py | 940 | 4.125 | 4 | #!/usr/bin/env python3
import itertools
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
# Output: For each testcase, print True or False
def bool_py_triplet(s):
arr = s.split(" ")
arr = [int(x) for x in arr]
c2 = {}
for i in range(len(arr)):
c2[arr[i]*arr[i]] = arr[i]
found = False
combos = []
for comb in itertools.combinations(arr,2):
combos.append(comb)
for comb in combos:
if comb[0] * comb[0] + comb[1] * comb[1] in c2:
possible_match = c2[comb[0] * comb[0] + comb[1] * comb[1]]
if possible_match not in comb:
found = True
print("{a}^2 + {b}^2 = {c}^2".format(a=comb[0], b=comb[1], c=possible_match))
return found
if __name__ == "__main__":
assert bool_py_triplet("3 2 4 6 5") == True, 'error1'
print("TESTS PASSED")
| true |
7ec80a2f8c691162457acc19d2ac9c0c170a859b | rodcoelho/python-practice | /archived_problems/amazon_how_many_x.py | 1,396 | 4.28125 | 4 | #!/usr/bin/env python3
# Given an integer X within the range of 0 to 9, and given two positive integers as upper and lower bounds respectively, find the number of times X occurs as a digit in an integer within the range, excluding the bounds. Print the frequency of occurrence as output.
# Input:
# The first line of input is an integer T, denoting the number of test cases. For each test case, there are two lines of input, first consisting of the integer X, whose occurrence has to be counted. Second, the lower and upper bound, L and U which are positive integers, on the same line separated by a single space, respectively.
# Output:
# For each test case, there is only one line of output, the count of the occurrence of X as a digit in the numbers lying between the lower and upper bound, excluding them.
def find_how_many_x(digit, lower, upper):
count = 0
for i in range(lower + 1, upper):
for ele in list(str(i)):
if str(digit) == ele:
count += 1
return count
if __name__ == '__main__':
print("TESTS BEGIN")
assert find_how_many_x(3, 100, 250) == 35, 'error 1'
assert find_how_many_x(2, 10000, 12345) == 1120, 'error 2'
assert find_how_many_x(0, 20, 21) == 0, 'error 3'
assert find_how_many_x(9, 899, 1000) == 120, 'error 4'
assert find_how_many_x(1, 1100, 1345) == 398, 'error 5'
print("ALL TESTS PASS")
| true |
2a8cfb68d48ce33c6b19f724ede5390a4d49f08d | rodcoelho/python-practice | /cracking_coding_interview/ch_2/prob_5.py | 1,016 | 4.15625 | 4 | #!/usr/bin/env python3
import unittest
from linkedlist import CustomLL
"""Given a circular linked list, implement an algorithm which returns node at the beginning of the loop."""
class LLLoopDetector:
def __init__(self):
pass
def detect(self, ll):
one_step, two_step = ll.head, ll.head
while two_step and two_step.node_tail:
two_step = two_step.node_tail.node_tail
one_step = one_step.node_tail
if one_step is two_step:
break
one_step = ll.head
while two_step is not one_step:
two_step = two_step.node_tail
one_step = one_step.node_tail
return two_step.value
class TestLLLoopDetector(unittest.TestCase):
def setUp(self):
ll_list = [12,13,14,15,16,17,18]
self.ll = CustomLL()
for node_val in ll_list:
self.ll.add(node_val)
self.ll.head.node_head = self.ll.tail
self.ll.tail.node_tail = self.ll.head
def test_LLoopDetector_detect(self):
llld = LLLoopDetector()
self.assertEqual(llld.detect(self.ll), 12)
if __name__ == "__main__":
unittest.main() | true |
82649227d51d64e935b51ad69a50226991271fc8 | rodcoelho/python-practice | /archived_problems/keypad_typing.py | 943 | 4.5 | 4 | #!/usr/bin/env python3
# You are given a string S of alphabet characters and the task is to find its
# matching decimal representation as on the shown keypad.
# Output the decimal representation corresponding to the string. For ex: if
# you are given “amazon” then its corresponding decimal
# representation will be 262966.
_keypad = {
'a': 2,
'b': 2,
'c': 2,
'd': 3,
'e': 3,
'f': 3,
'g': 4,
'h': 4,
'i': 4,
'j': 5,
'k': 5,
'l': 5,
'm': 6,
'n': 6,
'o': 6,
'p': 7,
'q': 7,
'r': 7,
's': 7,
't': 8,
'u': 8,
'v': 8,
'w': 9,
'x': 9,
'y': 9,
'z': 9
}
def get_dec(word):
dec = ''
for char in word:
dec += str(_keypad[char])
return int(dec)
if __name__ == "__main__":
assert get_dec('geeksforgeeks') == 4335736743357, 'error 1'
assert get_dec('geeksquiz') == 433577849, 'error 2'
print("TESTS PASSED")
| true |
5433490f8d54b2ad207913346ec0d932cd01f14c | rodcoelho/python-practice | /archived_problems/majority_element.py | 540 | 4.21875 | 4 | #!/usr/bin/env python3
# Given an array A of N elements. Find the majority element in the array.
# A majority element in an array A of size N is an element that appears
# more than N/2 times in the array.
def get_majority(nums):
for num in nums:
if nums.count(num) > len(nums)/2:
return num
return -1
if __name__ == "__main__":
assert get_majority([3, 1, 3, 3, 2]) == 3, 'test 1'
assert get_majority([1, 2, 3]) == -1, 'test 2'
assert get_majority([]) == -1, 'test 3'
print("TESTS PASSED")
| true |
c8ebdb3d30eb502efd1fcd80b02fbaead158b245 | Janith123gihan/Python-Files | /function_demo_10.py | 511 | 4.25 | 4 | #recursion
#Recursive function
#a function call itself directly or indirectly
#A function A calls A or (A calls B and B calls A)
def _factorial(n) :
if n==0 or n==1 :
return 1
return n * _factorial(n-1)
def factorial_it(n) :
f = 1
for i in range(1, n+1) :
f *= 1
#end for
return f
print(_factorial(12))
#print(math.factorial(12))
m = 123
#print(f'from math module {m}! = {math.factorial(m)}')
#print(f'from_factorial {m}! = {_factorial(m)}')
| false |
fbab0d8a7401c74c927a633cffaf3ed7a7ff9f51 | varun531994/Python_bootcamp | /prime.py | 202 | 4.375 | 4 | #Prime numbers:
x = int(input("Enter the number:"))
if x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0:
print('Its not a Prime number!!')
else:
print(f'{x} is a prime number!')
| true |
74015d2bf08164f68a797dbde1cc600e92a04845 | varun531994/Python_bootcamp | /count_prime.py | 570 | 4.3125 | 4 | #Write a function to print out the number of prime numbers that exist upto and including the given number:
#0 and 1 are not considered prime
def count_primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes:
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
x = int(input('Enter the number:'))
if x > 0:
print(count_primes2(x))
else:
print('ERROR') | true |
6257bb325f69bf1a4c9299f3d7ea114599eb6f66 | Rptiril/pythonCPA- | /chapter-8-pracrtice-set_functions/pr1_greatestOf3.py | 296 | 4.3125 | 4 | # Write a program using the function to find the greatest of three numbers.
def greatest(n1,n2,n3):
if n1>=n2 and n1>=n3:
return n1
elif n2>=n1 and n2>=n3:
return n2
else:
return n3
print(greatest(3,5,12))
print(greatest(3,55,12))
print(greatest(23,5,12))
| true |
e84977e22dd05a1ec59ee27b0389e9bf86394ec1 | Rptiril/pythonCPA- | /chapter-7-practise_set-loops/pr_Q5_sumofNaturals.py | 207 | 4.21875 | 4 | # Write a program to find the sum of first n natural numbers using a while loop
sum = 0
i = 0
last = int(input("Enter the number till sum is wanted : "))
while(i <= last):
sum+=i
i+=1
print(sum) | true |
7b49d6ec8940e105410b31178fac3d06ad027544 | Rptiril/pythonCPA- | /chapter-6-practice-set_if_logical/pr_4_len.py | 253 | 4.28125 | 4 | # Write a program to find whether a given username contains less than 10 characters or not.
username = input("Enter your username : ")
if len(username) < 10:
print("username contains less than 10 characters.")
else:
print("username accepted.") | true |
287d026500c2fe0ef3f9e675d0aa309cd028fe88 | lcsllima/Data-Structure | /tuplas.py | 254 | 4.125 | 4 | """
(a, b, c) = (1, 2, 3)
print(c) # 3
print(b) # 2
"""
frutas = dict()
frutas['Laranjas'] = 4
frutas['Banana'] = 6
for (k, v) in frutas.items():
print(k, v)
tups = frutas.items()
print(tups) # Nos da uma tupla
print (('d', 'c') > ('b', 'c'))
| false |
30a1094ba833c3b5bf675709ec9a783b0cd1d627 | siddhanthramani/Data-Structures-and-Algorithms | /Using Python/Reading_lines_in_a_file/reading_single_lines.py | 1,760 | 4.4375 | 4 | import turtle
def main():
# creates a turtle graphic window to draw in
t = turtle.Turtle()
# the screen is used at the end of the program
screen = t.getscreen()
filename = input('Enter name of file to be opened : ')
file = open(filename, 'r')
for line in file:
# print(line) # tells us that \n is present in each line
# thus we strip it off
text = line.strip()
# to separate the fields
command_list = text.split(',')
if command_list[0] == 'goto':
x = float(command_list[1])
y = float(command_list[2])
width = float(command_list[3])
color = command_list[4].strip()
t.width = width
t.pencolor = color
t.goto(x, y)
elif command_list[0] == 'circle':
radius = float(command_list[1])
width = float(command_list[2])
color = command_list[3].strip()
t.width = width
t.pencolor = color
t.circle(radius)
elif command_list[0] == 'beginfill':
color = command_list[1].strip()
t.fillcolor(color)
t.begin_fill()
elif command_list[0] == 'endfill':
t.end_fill()
elif command_list[0] == 'penup':
t.penup()
elif command_list[0] == 'pendown':
t.pendown()
else:
print('Command not found in file : ', command_list[0])
# closes the file handler
file.close()
# hides the turtle that we used to draw the picture
t.ht()
# causes turtle screen to stay on till we mouse click
screen.exitonclick()
print('Program execution is complete. ')
if __name__ == "__main__":
main()
| true |
257b0735d0cbc8b15b87002abb0b56dc1dff37db | ManarJN/Automate-the-Boring-Stuff | /ch13_working_with_pdf_and_word/13.1_combine_pdfs.py | 831 | 4.125 | 4 | #! /usr/bin/env python3
# Automate the Boring Stuff
# Chapter 13 - Working with PDF and Word
# Combine PDFs - Combines all the PDFs in the current working directory
# into a single PDF.
import os
import PyPDF2
# gets all the PDF filenames
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF2.PdfFileWriter()
# loops through all the PDF files
for filename in pdfFiles:
# loops through all the pages (except the first) and adds them
for pageNum in range(1, pdfReader.numPages):
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# saves the resulting PDF to a file
pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close() | true |
809ab5a8fcad2a8d35e8fa6d171adb125f2459c1 | ManarJN/Automate-the-Boring-Stuff | /ch7_pattern_matching_with_regex/7.2_strong_password_detection.py | 1,297 | 4.65625 | 5 | #! /usr/bin/env python3
# Automate the Boring Stuff
# Chapter 7- Pattern Matching with Regex
# Strong Password Detection - Ensures a password is strong.
import re
# creates password regex
pwLowCase = re.compile(r'[a-z]') # checks for a lowercase letter
pwUpCase = re.compile(r'[A-Z]') # checks for an uppercase letter
pwNum = re.compile(r'\d') # checks for a number
pwSpace = re.compile(r'\s') # checks for spaces, tabs, or newline characters
# defines pw strength checker function on user input
def pwRegex(password):
strong = True
if len(password) < 8:
print('Your password must be at least 8 characters long.')
strong = False
if pwLowCase.search(password) is None:
print('Your password must contain a lowercase character.')
strong = False
if pwUpCase.search(password) is None:
print('Your password must contain an uppercase character.')
strong = False
if pwSpace.search(password) is not None:
print('Your password cannot contain spaces, tabs, or newline characters.')
strong = False
if strong: # if password passes above criteria
print('Your password is strong.')
# calls pw strength checker function
password = input('Please enter a password: ')
pwRegex(password)
| true |
1226e7ac786317695fcaa47a97c0b124308b04f4 | harrifeng/leet-in-python | /065_valid_number.py | 1,543 | 4.21875 | 4 | """
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should
gather all requirements up front before implementing one.
"""
import unittest
class MyTest(unittest.TestCase):
def test(self):
solution = Solution()
self.assertTrue(solution.isNumber("0"))
self.assertTrue(solution.isNumber(" 0.1 "))
self.assertFalse(solution.isNumber("abc"))
self.assertFalse(solution.isNumber("1 a"))
self.assertTrue(solution.isNumber("2e10"))
self.assertTrue(solution.isNumber("-1."))
self.assertTrue(solution.isNumber(" 005047e+6"))
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.strip()
s += '#'
i = 0
n1, n2, n3 = 0, 0, 0
if s[i] in ['+', '-']:
i += 1
while s[i].isdigit():
i += 1
n1 += 1
if s[i] == '.':
i += 1
while s[i].isdigit():
i += 1
n2 += 1
if n1 == n2 == 0:
return False # e has something on left
if s[i] in ['e', 'E']:
i += 1
if s[i] in ('+', '-'):
i += 1
while s[i].isdigit():
i += 1
n3 += 1
if n3 == 0:
return False # e has something on right
return s[i:] == '#'
| true |
9c6bf0b39e3227009d5046396f9367cb5f9e9ec7 | olaniyanjoshua/Joshua2 | /area_of_a_cylinder_by_Olaniyan_Joshua[1].py | 275 | 4.28125 | 4 | """
This program calculates the area of a cylinder
r is the radius of the cylinder
h is the height of the cylinder
"""
r=float(input("Enter the value of r:"))
h=float(input("Enter the value of h:"))
π=22/7
area=2*π*(r**2)+2*π*r*h
print("The area of the cylinder is",area)
| true |
8aafcbb854fdb84e59890dc14fd9cba79ece4448 | MarvinSilcGit/Alg | /Python/2018-2019/Exercício 7.1.py | 919 | 4.21875 | 4 | p = input("Digite um texto: ")
a = input("Digite outro texto: ")
if p.isalpha() == True and a.isalpha() == True:
if len(p) > len(a):
d = p.find(a, 0)
if d >= 0:
print("a posição encontrada foi a partir da %d° posição" % d)
else:
print("A string %s não foi encontrada em %s" % (a, p))
else:
d = a.find(p, 0)
if d >= 0:
print("A posição encontrada foi a partir da %d° posição" % d)
else:
print("A string %s não foi encontrada em %s" % (p, a))
elif p.isalpha() == False and a.isalpha() == False:
print("Não é permitido valores nulos")
elif p.isalpha() == False and a.isalpha() == True:
print("Digite somente strings no dois campos")
elif p.isalpha() == True and a.isalpha() == False:
print("Digite somente strings no dois campos")
| false |
e2a4f07d0dc2fed12cca426bd5a875edfce1fe15 | laboyd001/python-crash-course-ch4 | /my_pizza_your_pizza.py | 387 | 4.4375 | 4 | #add a new pizza to the list, add a different pizz to friends list, prove you have two lists
pizzas = ['cheese', 'peperoni', 'supreme']
friends_pizzas = pizzas[:]
pizzas.append('mushroom')
friends_pizzas.append('bbq')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friends favorite pizzas are:")
for pizza in friends_pizzas:
print(pizza)
| true |
02248233ec1aca43707b0710106f9e3b544b7f81 | YGragon/PythonSelfStudy | /test_case/case79.py | 627 | 4.3125 | 4 | # 题目:字符串排序。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# if __name__ == '__main__':
# str1 = input('input string:\n')
# str2 = input('input string:\n')
# str3 = input('input string:\n')
# print(str1,str2,str3)
# if str1 > str2 :
# str1,str2 = str2,str1
# if str1 > str3 :
# str1,str3 = str3,str1
# if str2 > str3 :
# str2,str3 = str3,str2
# print('after being sorted.')
# print(str1,str2,str3)
ls=[]
str1=input("string1:\n")
str2=input("string2:\n")
str3=input("string3:\n")
ls.extend([str1,str2,str3])
ls.sort()
print(ls) | false |
06cb80c8a2f44a1cb955fa474fc74857f43f5012 | erjohnyelton/Tkinter-Tutorial | /entry1.py | 315 | 4.125 | 4 | from tkinter import *
root = Tk()
e = Entry(root, width=50, bd=5)
e.pack()
e.insert(0, "Enter your name")
def myClick():
myLabel = Label(root, text="Hello " + e.get())
myLabel.pack()
myButton = Button(root, text = 'Click here', padx = 50, pady = 50, bd=5,command=myClick)
myButton.pack()
root.mainloop()
| true |
99b9dc56857d1cec6515dcb1c881219efa28224a | Nicomunster/INF200-2019-Exercises | /src/nicolai_munsterhjelm_ex/ex04/walker.py | 1,124 | 4.1875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Nicolai Munsterhjelm'
__email__ = 'nicolai.munsterhjelm@nmbu.no'
import random
class Walker:
def __init__(self, x0, h):
self.position = x0
self.home = h
self.steps = 0
def move(self):
self.position += random.choice((-1, 1))
self.steps += 1
def is_at_home(self):
if self.position == self.home:
return True
else:
return False
def get_position(self):
return self.position
def get_steps(self):
return self.steps
def walker_simulation(distances, n):
"""Simlutates a walker n times for each distance
in the 'distances' list."""
for distance in distances:
number_of_steps = []
for i in range(n):
walker = Walker(0, distance)
while not walker.is_at_home():
walker.move()
number_of_steps.append(walker.get_steps())
print(f"Distance: {distance} -> Path lengths: "
f"{sorted(number_of_steps)}")
if __name__ == "__main__":
distances = [1, 2, 5, 10, 20, 50, 100]
walker_simulation(distances, 5)
| true |
e7da60ad81ee7b373bbad1cadc7e3e20a111639f | spareribs/data-analysis | /Book_one/chapter2/demo/code/2-1 numpy_test.py | 664 | 4.125 | 4 | # -*- coding: utf-8 -*-
import numpy as np # 一般以np作为numpy的别名
a = np.array([2, 0, 1, 5]) # 创建数组
print(a, type(a)) # 输出数组[2 0 1 5] <class 'numpy.ndarray'>
print(a[:3], type(a[:3])) # 引用前三个数组(切片)[2 0 1] <class 'numpy.ndarray'>
print(a.min(), type(a.min())) # 输出a的最小元素0 <class 'numpy.int32'>
a.sort()
print(a, type(a)) # 将a的元素从小到大排序,此操作直接修改a,因此这时候a为[0 1 2 5] <class 'numpy.ndarray'>
b = np.array([[1, 2, 3], [4, 5, 6]]) # 创建二位数组
print(b * b, type(b * b)) # 输出数组的平方阵[[ 1 4 9],[16 25 36]] <class 'numpy.ndarray'>
| false |
24b4d7e444a55c375cefb55bda23401642f442ab | Zuimengxixia/Web_Selenium | /python学习/Chapter_4_list/4-3练习.py | 1,119 | 4.1875 | 4 | #数到20,使用一个for循环打印数字(包含20)
sums = range(1,21)
for suma in sums:
print(suma)
'''
#创建一个列表,其中包含数字1~1000000,用for打印出来
for sumaa in range(1,1000001):
print(sumaa)
'''
#创建一个列表1~1000000,使用min()和max()函数,在用sum()函数统计和
squares = []
for value in range(1,1000000):
square = value**1
squares.append(square)
print(min(squares))
print(max(squares))
print(sum(squares))
#通过range()指定第三个参数创建列表,打印出1~20之间的奇数
squares = list(range(1,20,2))
print(squares)
for square in squares:
print(square)
#创建一个列表,其中包含3~30以内能被3整除的数字,并用for打印出来
squares = []
for value in range(1,11):
square=value*3
squares.append(square)
print(squares)
#将同一个数字进行立方,并用for打印
squares = []
for value in range(1,10):
square=value**3
squares.append(square)
print(squares)
#使用列表解析生成一个列表,包含1~10的整数立方
squares = [value**3 for value in range(1,10)]
print(squares)
| false |
11213be3a997c4ac49923eb3ebd1f0c559339a82 | eunnovax/python_algorithms | /binary_tree/linked_list_from_tree.py | 1,710 | 4.15625 | 4 | class BTNode():
def __init__(self, data=0, left = None, right=None):
self.left = left
self.right = right
self.data = data
class BinaryTree(): # fills nodes left-to-right using queue
def __init__(self, data=0):
self.root = BTNode(data)
def insert(self, data):
if not self.root:
self.root = BTNode(data)
return
q = []
q.append(self.root)
# level order traversal until we find an empty place
while q:
temp = q[0]
q.pop(0)
# Insert node as the left child of the parent node.
if not temp.left:
temp.left = BTNode(data)
break
# If the left node is not null push it to the queue.
else:
q.append(temp.left)
# Insert node as the right child of the parent node.
if not temp.right:
temp.right = BTNode(data)
break
# If the right node is not null push it to the queue.
else:
q.append(temp.right)
class LinkedList():
def __init__(self, data=0, next=None):
self.data, self.next = data, next
def linked_list_from_tree(tree):
# base case
if not tree:
return []
if tree.left is None and tree.right is None:
return [tree.data]
left = linked_list_from_tree(tree.left)
right = linked_list_from_tree(tree.right)
return left + right # list concatenation
tree = BinaryTree(3)
tree.insert(21)
tree.insert(12)
tree.insert(5)
tree.insert(8)
tree.insert(0)
tree.insert(13)
tree.insert(73)
tree.insert(69)
print(linked_list_from_tree(tree.root))
| true |
f29e4742150e064dd40f431cbf96e5f1cb2712dc | Gabrielly1234/Python_WebI | / exercícios senquenciais/questao9.py | 225 | 4.125 | 4 | #Faça um Programa que peça a temperatura em graus Fahrenheit,
# transforme e mostre a temperatura em graus Celsius.
print("temperatura em Fahrenheit:")
temp=int(input())
c1= temp-32
c2= (c1*5)/9
print(c2," graus Celsius") | false |
8a1c26bd443a0ead4124c78a11469a130d996d33 | Gabrielly1234/Python_WebI | /estruturaDecisão/questao2.py | 257 | 4.125 | 4 | #Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
print("digite um número:")
num= int(input())
if (num>0):
print(num, "é positivo")
if (num<0):
print(num, "é negativo")
if (num==0):
print("neutro")
| false |
eddfb81c30b6cb9e808f60112cfc8ead1d3e86ad | lenablechmann/CS50xPsets | /pset6/readability.py | 836 | 4.21875 | 4 | # Computes the approximate grade level needed to comprehend some text.
from cs50 import get_string
import re
# Prompts user for text input.
text = get_string("Enter your text: ")
# Counting letters and words.
# Found here https://stackoverflow.com/questions/24878174/how-to-count-digits-letters-spaces-for-a-string-in-python
letters = sum(c.isalpha() for c in text)
words = sum(c.isspace() for c in text) + 1
# Counting sentences via . ! ? chars.
sentences = text.count('.') + text.count('!') + text.count('?')
# Main grade (float) calculation using the given formula
grade = round(0.0588 * ((float(letters) / (float(words))) * 100.0) - 0.296 * ((float(sentences) / (float(words))) * 100.0) - 15.8)
if grade > 0 and grade < 17:
print(f"Grade {grade}")
elif grade < 1:
print ("Before Grade 1")
else:
print("Grade 16+") | true |
186f3b8180e6cef24c5e14b53606b265e93af50c | mikeodf/Python_Line_Shape_Color | /ch4_prog_3_repositioned_star_polygon_1.py | 2,207 | 4.28125 | 4 | """ ch4 No.3
Program name: repositioned_star_polygon_1.py
Objective: Draw a series of stars each with their own start position.
Keywords: polygon, anchor point, star
============================================================================79
Comments:Each separate star is drawn relative to a pair variables,
x_anchor and y_anchor It simple to re-position different stars just
by reassigning the values of the anchor position.
Tested on: Python 2.6, Python 2.7,Python 3.2.3
Author: Mike Ohlson de Fine
"""
from Tkinter import *
#from tkinter import * # For Python 3.2.3 and higher.
root = Tk()
root.title('Star polygon repositioned')
cw = 300 # canvas width
ch = 100 # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)
# Green star, fixed to an anchor point.
x_anchor = 15
y_anchor = 50
canvas_1.create_polygon(x_anchor, y_anchor,
x_anchor + 20, y_anchor - 40,
x_anchor + 30, y_anchor + 10,
x_anchor, y_anchor - 30,
x_anchor + 40, y_anchor - 20,
fill="green")
# Red star, fixed to an anchor point.
x_anchor = 70
y_anchor = 70
canvas_1.create_polygon(x_anchor, y_anchor,
x_anchor + 20, y_anchor - 40,
x_anchor + 30, y_anchor + 10,
x_anchor, y_anchor - 30,
x_anchor + 40, y_anchor - 20,
fill="red")
# Blue star, fixed to an anchor point.
x_anchor = 200
y_anchor = 60
canvas_1.create_polygon(x_anchor, y_anchor,
x_anchor + 20, y_anchor - 40,
x_anchor + 30, y_anchor + 10,
x_anchor, y_anchor - 30,
x_anchor + 40, y_anchor - 20,
fill="blue")
root.mainloop()
| true |
ff27021cd885bd28af1946db9cb3e62932f0fdcc | mikeodf/Python_Line_Shape_Color | /ch6_prog_3_text_width_overflow_1.py | 1,096 | 4.5 | 4 | """ ch6 No.3
Program name: text_width_overflow_1.py
Objective: Draw text onto the canvas at a chosen location.
Keywords: canvas,text
============================================================================79
Comments: The text is written starting at co-ordinate location (x,y) = 200,20.
The "width=200" is the horizontal size of the writing area. The text column grows upwards with each
new line.
Tested on: Python 2.6, Python 2.7.3, Python 3.2.3
Author: Mike Ohlson de Fine.
"""
from Tkinter import *
#from tkinter import * # For Python 3.2.3 and higher.
root = Tk()
root.title("When Text Overflows.")
cw = 300 # canvas width
ch = 260 # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)
xy = 150, 100
canvas_1.create_text(xy, text=" TEXT LARGE, Arial 20 point. So what happens if we have not allowed sufficient width on one line?", fill='red', width=200, font='Arial 20')
root.mainloop()
| true |
64d5c404615ae84d6cf146c91d07e4e65bc16b82 | mikeodf/Python_Line_Shape_Color | /ch1_prog_3_line_styles_1.py | 1,511 | 4.21875 | 4 | """ ch1 No.3
Program name: line_styles_1.py
Objective: Four straight lines, different styles on a canvas.
Keywords: canvas, line, , color, dashed line, default
============================================================================79
Comments: When drawing lines you MUST specify the start and end points.
Different colors, line widths and styles have been used here.
Variable names are used instead of numerical values.
Tested on: Python 2.6, Python 2.7.3, Python 3.2.3
Author: Mike Ohlson de Fine
"""
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
from Tkinter import *
#from tkinter import * # For Python 3.2.3 and higher.
root = Tk()
root.title('Variations in line options')
cw = 500 # canvas width
ch = 200 # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="pink")
canvas_1.grid(row=0, column=1)
x_start = 10
y_start = 10
x_end = 400
y_end = 20
canvas_1.create_line(x_start, y_start, x_end, y_end, dash=(3,5), width = 3)
x_start= x_end
y_start= y_end
x_end= 10
y_end= 180
canvas_1.create_line(x_start, y_start, x_end, y_end, dash=(9,), width = 5, fill= "red")
y_end= 150
canvas_1.create_line(x_start, y_start, x_end, y_end, dash=(19,),width= 10, fill= 'yellow')
y_start= 0
# If not explicitly specified line style reverts to default width = 1,
# and default color = 'black'.
canvas_1.create_line(x_start, y_start, x_end,y_end)
root.mainloop()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.