blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ac349eb4da08279d11d242bf2bb67556729f4393 | zeirn/Exercises | /Week 4 - Workout.py | 815 | 4.21875 | 4 | x = input('How many days do you want to work out for? ') # This is what we're asking the user.
x = int(x)
# These are our lists.
strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings']
cardio = ['Running', 'Swimming', 'Biking', 'Jump rope']
workout = []
for d in range(0, x): # This is so that 'd' (the day) stays within the range of 0 and whatever x is.
# 'z' and 'z2' are the exercises in the lists.
z = strength[d % len(strength)] # The number of days divided by the length of the number of items in the
z2 = cardio[d % len(cardio)] # list strength/cardio. z is the answer to the first equation. z2 is answer to other.
workout.append(z + ' and ' + z2) # This adds these two answers to the end of the workout list.
print('On day', d+1, (workout[d]))
| true |
3186c75b82d1877db3efe13a8a432355503ec9f3 | TMcMac/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 526 | 4.28125 | 4 | #!/usr/bin/python3
"""This will get a line count on a text file"""
def number_of_lines(filename=""):
"""
A function to get a line count on a file
parameters - a file
"""
line_count = 0
with open(filename, 'r') as f:
"""
Opens the file as f in such as way that
we don't need to worry about f.close()
"""
for line in f:
"""
we'll loop through the file one list at a time
"""
line_count += 1
return line_count
| true |
5c8df2051d971311883b58f15fbf17a1987655fd | TMcMac/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 831 | 4.46875 | 4 | #!/usr/bin/python3
"""Defines class square and takes in a size to intialize square"""
class Square():
"""Class Square for building a square of #s"""
def __init__(self, size=0):
"""Initializes an instance of square"""
self.size = size
def area(self):
"""Squares the size to get the area"""
return (self.__size ** 2)
@property
def size(self):
"""Just a call to get the size of a side"""
return self.__size
@size.setter
def size(self, value):
"""Sets the size of the square"""
if type(value) != int or float: # If its not an int or a flt
raise TypeError("size must be a number")
elif value < 0: # If it is a neg number
raise ValueError("size must be >= 0")
else:
self.__size = value
| true |
6985fbb424941dc0c0736f334e4ab35fe944c74e | kurrier/pytest1 | /math2.py | 1,207 | 4.15625 | 4 | #!/usr/bin/python
print "Python Calculator\n"
nonum = "Error: no number"
firstnum = "What is the first number?"
secnum = "What is the second number?"
def division(n1,n2):
div = n1/n2
print "%d divided by %d is: %d" % (n1, n2, div)
return div
def multiply(n1,n2):
mult = n1 * n2
print "%d multiplied by %d is: %d" % (n1, n2, mult)
return mult
def addition(n1,n2):
add = n1 + n2
print "%d added to %d is: %d" % (n1, n2, add)
return add
def subtraction(n1,n2):
subt = n1 - n2
print "%d subtracted by %d is: %d" % (n1, n2, subt)
return subt
num1 = raw_input(firstnum)
if len(num1) > 0 and num1.isdigit():
num1 = int(num1)
else:
print nonum
exit()
num2 = raw_input(secnum)
if len(num2) > 0 and num2.isdigit():
num2 = int(num2)
else:
print nonum
exit()
print("")
print "Addition (add), Division (div), Multipication? (mult)?, or Subtraction (sub): ",
ask = raw_input()
if ask == "add":
addition(num1,num2)
elif ask == "div":
division(num1,num2)
elif ask == "mult":
multiply(num1,num2)
elif ask == "sub":
subtraction(num1,num2)
else:
print("Wrong choice!\n")
exit()
print("")
| false |
6191e450436393fc4ac30c36d1e16665b9cebdb2 | wahahab/mit-6.0001 | /ps1/ps1c.py | 1,204 | 4.21875 | 4 | # -*- coding: utf-8 -*-
import math
from util import number_of_month
SCALE = 10000
if __name__ == '__main__':
months = 0
current_savings = 0
portion_down_payment = .25
r = .04
min_portion_saved = 0
max_portion_saved = 10000
best_portion_saved = 0
semi_annual_raise = .07
total_cost = 1000000
it_count = 0
start_salary = float(input('Enter the starting salary: '))
while months != 36 and max_portion_saved > min_portion_saved + 1:
best_portion_saved = (min_portion_saved + max_portion_saved) / 2
months = number_of_month(portion_down_payment, total_cost, current_savings,
start_salary, float(best_portion_saved) / SCALE, r, semi_annual_raise)
it_count += 1
if months > 36:
min_portion_saved = best_portion_saved
elif months < 36:
max_portion_saved = best_portion_saved
if (max_portion_saved == SCALE and min_portion_saved == SCALE - 1):
print 'It is not possible to pay the down payment in three years.'
else:
print 'Best savings rate: ', float(best_portion_saved) / SCALE
print 'Steps in bisection search: ', it_count
| true |
bc9a56767843484f90d5fe466adee8c1289a9052 | JohanRivera/Python | /GUI/Textbox.py | 1,360 | 4.125 | 4 | from tkinter import *
raiz = Tk()
myFrame = Frame(raiz, width=800, height=400)
myFrame.pack()
textBox = Entry(myFrame)
textBox.grid(row=0,column=1) #grid is for controlate all using rows and columns
#Further, in .grid(row=0, column=1, sticky='e', padx=50) the comand padx o pady move the object, in this case
#50 pixels to este, this direction can changed with the comand sticky
#Besides, the color and others features of the text box can changed
passBox = Entry(myFrame)
passBox.grid(row=1,column=1)
passBox.config(show='*')#this line is for changed the characters with a character special
""" Text Box to comments"""
commentsBox = Text(myFrame,width=10,height=5) #Form to create the comment box
commentsBox.grid(row=2,column=1)
scrollVertical = Scrollbar(myFrame,command=commentsBox.yview) # Form to make a scroll in the comment box
scrollVertical.grid(row=2,column=2,sticky='nsew') # the command nsew is what the scroll it have the same size
#that comment box
commentsBox.config(yscrollcommand=scrollVertical.set) #For the scroll
myLabel = Label(myFrame, text = 'Ingrese el nombre: ')
myLabel.grid(row=0,column=0) #grid is for controlate all using rows and columns
myPass = Label(myFrame, text = 'Ingrese contraseña: ')
myPass.grid(row=1,column=0)
myComments = Label(myFrame, text = 'Comentarios: ')
myComments.grid(row=2,column=0)
raiz.mainloop() | true |
21d92cf2e0027b977d30c7f7af3383d0331e1ed0 | baejinsoo/TIL | /4th/파이썬/python_programming_stu/Practice/prac_2.py | 577 | 4.125 | 4 | # # 일반적인 함수 정의
# def add(x, y):
# return x + y
#
#
# print(add(10, 20))
#
# # 람다식 사용
# my_add = lambda x, y: x + y
# print(my_add(10, 34))
#
# square = lambda x: x ** 2
# print(square(4))
#
# multi = lambda x, y: x * y
# print(multi(40, 3))
#
# division = lambda x, y: x / y
# print(division(50, 5))
my_arr = [1, 2, 3, 4, 5]
my_arr2 = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, my_arr)
print(list(result))
result = list(map(lambda x: x * 2, my_arr))
print(result)
result = list(map(lambda x, y: (x + y) * 6, my_arr, my_arr2))
print(result)
| false |
7e67906a790f004df57e8eed1a38fd0de53a1a25 | Shaileshsachan/Algoexpert_problem_solution | /sorting/selection_sort.py | 552 | 4.21875 | 4 | def SelectonSort(list1):
print(f'Unsorted Array: {list1}')
for i in range(len(list1) - 1):
min_index = i
for j in range(i+1, len(list1)):
if list1[j] < list1[min_index]:
min_index = j
if list1[i] != list1[min_index]:
list1[i], list1[min_index] = list1[min_index], list1[i]
return (list1)
if __name__ == "__main__":
n = int(input(f'Enter the length of number to sort: '))
list1 = [int(input("Enter the number: ")) for _ in range(n)]
print(SelectonSort(list1))
| false |
0b4d0a0812579e02606085ed5eb59145f57eaa03 | PhurbaGyalzen/Gyalzen | /exercise2/4.py | 361 | 4.28125 | 4 | number_1=int(input('number_1:'))
number_2=int(input('number_2:'))
number_3=int(input('number_3:'))
if number_3 > number_2 and number_3 > number_1:
print(f"{number_3} is greatest.")
elif number_2 > number_3 and number_2 > number_1:
print(f"{number_2} is greatest.")
elif number_1 > number_2 and number_1 > number_3:
print(f"{number_1} is greatest.")
| false |
42bb143238a706d20b33822544bacab53aab5d98 | egene-huang/python-learn | /test-all/pyclass/access.py | 2,128 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
## 访问控制
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def toString(self):
print('我是%s,我%s岁了.' %(self.name,self.age))
p = Person('palm',25)
p.toString() ## 我是palm,我25岁了.
## 可以随意修改 这个对象的属性值
p.name = '王八蛋'
p.age = 12345
p.toString() ## 我是王八蛋,我12345岁了.
## 显然数据 被随意的破坏了
## 在python中,定义私有变量使用 __ [双下划线], 如
print('---------------- 对象属性私有化')
class PrivPerson(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
def toString(self):
print('我是%s,我%s岁了.' %(self.__name,self.__age))
pp = PrivPerson('palm','26')
pp.__name = '王八蛋'
pp.__age = 12345
pp.toString() ## 我是palm,我26岁了.
print(pp.__name) ## 王八蛋
print(pp.__age) ##12345
## 这里修改对象属性值没有成功
## 所以 对象属性私有化需要使用 双下划线 [__]作为属性变量名的前缀, 这样 __开头的属性只有对象内部可以访问,外部不可以访问
## 我发现,这样也只是保证了通过对象方法访问对象属性的时候是正确的,从外部直接访问依然是不正确的.所以在权限控制这块,依然没有java严谨.
## 这种机制只能防止君子
## 不过这已经算是一个保障了, 保障了对象内部的状态是正确的
## 同java一样 可以新增 get /set方法 来达到对象属性获取和修改正确, 如此也可以对象参数进行校验
## _x 和 __x 都是私有变量 只是后者约束性更强,前者只是约定,是可直接访问的
## 在python中,属性私有化 是把私有变量名称改变了,所以不能访问 所以我们从外面改变私有变量,其实只是动态的新增了属性 完全是幻觉
## _PrivPerson__name == __name
## 我算是明白了,pytho中权限设置基本是摆设,你若要强上 谁也拦不住你, 所以全靠自觉, 难道pythoner自觉性真的很强? 能强忍住不上, 我服!
| false |
820a54904cce0d1da89522eebfd0247017a801bc | egene-huang/python-learn | /test-all/pyclass/cls.py | 2,797 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
## 在学习面向对象的时候, 我自做聪明误认为 __init__就是python class的构造方法, 其实不是
## 查阅资料得知, 在执行 p = Person('测试',23)这行代码的时候, 首先调用的是 __new__这个类方法
## __init__这个是实例方法,是在实例构造完成后 使用来处理实例属性值等类似工作的 地一个参数self 就是__new__构造出来的实例
# __ new__(cls, *args, **kwargs) 创建对象时调用,返回当前对象的一个实例;注意:这里的第一个参数是cls即class本身
#
# __ init__(self, *args, **kwargs) 创建完对象后调用,对当前对象的实例的一些初始化,无返回值,即在调用__new__之后,根据返回的实例初始化;
# 注意,这里的第一个参数是self即对象本身
class Person(object):
def __new__(cls,name,age):
print('实例化Person 调用 __new__')
print('属性值',name,age)
## 注意,这里调用的是父类的 __new__构造方法, object是没有我们自定义的属性的,所以,这里 不能 object.__new__(cls,name,age) 这是错误的
return object.__new__(cls)
def __init__(self,name,age):
print('调用 __init__')
self._name = name
self._age = age
def __str__(self):
print('我是%s,我%s岁了' %(self._name,self._age))
p = Person('小张',24)
## 打印日志如下:
# 实例化Person 调用 __new__
# 属性值 小张 24
# 调用 __init__
## 所以 在实例化一个对象的时候 有限调用的是 __new__ 然后接着调用 __init__ 如果 我们覆盖了 __new__ 但是没有返回值 则 __init__ 不会被调用。
## 在 覆盖 __new__ 方法的时候注意不能形成系循环 比如 在Person#__new__中, return Person.__new__(cls) 或者 子类.__new__(cls) 因为子类实例化一定会先实例化父类的 形成死循环
## 当然也可以在 __new__方法中返回其他类的实例, 那么之后不会调用自己的__init__ 而是调用__new__返回实例的__iniit方法
p.__str__()
print('----------------我是分割线----------------------------------')
class Dog(object):
def __init__(self,name):
print('Dog __init__被调用')
self._name = name
def __str__(self):
print('我是%s' %self._name)
class Student(object):
'''重新定义构造方法'''
def __new__(cls,name):
print('调用 Student __new__')
return Dog(name) ## 返回 Dog实例
# return Dog.__new__(cls) ## 这样依然返回 Student实例
def __init__(self,name):
print('Student __init__被调用')
self._name = name
def __str__(self):
print('我是%s' %self._name)
stu = Student('学生')
print()
| false |
5f004bd21d1553a87a446be505865cba2acd19a7 | JustinCThomas/Codecademy | /Python/Calendar.py | 2,021 | 4.125 | 4 | """This is a basic CRUD calendar application made in Python"""
from time import sleep, strftime
NAME = "George"
calendar = {}
def welcome():
print("Welcome", NAME)
print("Opening calendar...")
sleep(1)
print(strftime("%A %B %d, %Y"))
print(strftime("%H:%M:%S"))
sleep(1)
print("What would you like to do?")
def start_calendar():
welcome()
start = True
while start:
user_choice = input("Enter one of the following: \n A to Add: \n U to Update: \n V to View: \n D to Delete: \n X to exit: \n")
user_choice = user_choice.upper()
if user_choice == "V":
if len(calendar.keys()) == 0:
print("The calendar is currently empty.")
else:
print(calendar)
elif user_choice == "U":
date = input("What date? ")
update = input("Enter the update: ")
calendar[date] = update
print("Calendar updated!")
print(calendar)
elif user_choice == "A":
event = input("Enter event: ")
date = input("Enter date (MM/DD/YYYY): ")
if len(date) > 10 or int(date[6:]) < int(strftime("%Y")):
print("Please enter the date in the proper (MM/DD/YYYY) format")
try_again = input("Try Again? Y for Yes, N for No: ")
try_again = try_again.upper()
if try_again == "Y":
continue
else:
start = False
else:
calendar[date] = event
print("Event successfully added!")
print(calendar)
elif user_choice == "D":
if len(calendar.keys()) == 0:
print("The calendar is currently empty. There is nothing to delete!")
else:
event = input("What event?")
for date in calendar.keys():
if event == calendar[date]:
del calendar[date]
print("Event deleted!")
print(calendar)
break
else:
print("You entered a non-existent event!")
elif user_choice == "X":
start = False
else:
print("Invalid command")
break
start_calendar()
| true |
603eca56497eacb11201e688b496dc85e92f3c81 | penroselearning/pystart_code_samples | /Student Submission Isha Reddy.py | 1,061 | 4.125 | 4 | print('Student Grade Calculator')
student_scores = []
try:
student_scores = [input("Enter Student Name: "),
(int(input("Enter English Score (Max 100): \n")),
int(input("Enter Math Score (Max 100): \n")),
int(input("Enter Chemistry Score (Max 100): \n")),
int(input("Enter Physics Score (Max 100): \n")),
int(input("Enter Geography Score (Max 100): \n")),)]
except ValueError:
print("Kindly provide the correct Scores")
else:
avg = (student_scores[1][0] + student_scores [1][1] + student_scores [1][2] + student_scores [1][3] + student_scores [1][1])/5
print()
if avg >= 90:
grade = 'A'
elif avg >= 80 and avg < 90:
grade= 'B'
elif avg >= 70 and avg < 80:
grade= 'C'
elif avg >= 60 and avg < 70:
grade= 'D'
elif avg >= 50 and avg < 60:
grade = 'E'
elif avg < 50:
grade = 'F'
else:
print("Sorry something went wrong.")
print(f'Your final grade is: {grade}') | false |
765d21e3ef208f0a197c71a5b1543f71fd7aa4dc | penroselearning/pystart_code_samples | /16 Try and Except - Division.py | 415 | 4.125 | 4 | print('Division')
print('-'*30)
while True:
try:
dividend = int(input("Enter a Dividend:\n"))
divisor = int(input("Enter a Divisor:\n"))
except ValueError:
print("Sorry! You have not entered a Number")
else:
try:
result = dividend/divisor
except ZeroDivisionError:
print("Division by Zero has an Undefined Value")
else:
print(f'The quotient is {result}')
break | true |
4c95d508fe4cbcdd35f32a1c7fd10ff63315a2d0 | penroselearning/pystart_code_samples | /10 For Loop - Remove Vowels from a Word.py | 297 | 4.3125 | 4 | longest_word='pneumonoultramicroscopicsilicovolcanoconiosis'
new_word_without_vowels=''
vowels=['a','e','i','o','u']
for letter in longest_word:
if letter not in vowels :
new_word_without_vowels += letter
print(f'The worlds longest word without vowels - {new_word_without_vowels.upper()}') | false |
6716efaf012f7ed75775f9dca8dad3593c5a4773 | venkatakaturi94/DataStructuresWeek1 | /Task4.py | 1,271 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
list_tele_marketers=[]
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
list_from =[]
list_to =[]
for to in texts:
list_from.append(to[0])
list_to.append(to[1])
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
list_from_call =[]
list_to_call =[]
for to1 in calls:
list_from_call.append(to1[0])
list_to_call.append(to1[1])
for x in list_from_call:
if ((x not in list_to_call) and (x not in list_from) and (x not in list_to)):
list_tele_marketers.append(x)
print("These numbers could be telemarketers:")
no_duplicates = sorted(set(list_tele_marketers))
for j in no_duplicates:
print(j)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
| true |
c4c760f5840cd67678114569f3fe0cc890f501ac | codeguru132/pythoning-python | /basics_lists.py | 526 | 4.34375 | 4 | hat_list = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat.
# Step 1: write a line of code that prompts the user
# to replace the middle number with an integer number entered by the user.li
hat_list[2] = int(input("ENter a number here: ..."))
# Step 2: write a line of code that removes the last element from the list.
del hat_list[-1]
# Step 3: write a line of code that prints the length of the existing list.
print("\nLength of the list is: ...", len(hat_list))
print(hat_list)
| true |
32e14721978cac96a0e1c7fe96d1e7088f928658 | rciorba/plp-cosmin | /old/p1.py | 1,246 | 4.21875 | 4 | #!/usr/bin/python
# Problem 1:
# Write a program which will find all such numbers which are divisible by 7 but
# are not a multiple of 5, between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a
# single line.
# to nitpick: min and max are builtin functions, and you should avoid using these names for variables
def numbers(min, max):
# result = []
# for number in xrange(min, max):
# you want to go to max+1, xrange(1, 3) gives you [1, 2]
for number in xrange(min, max + 1):
if number % 7 == 0 and number % 5 is not 0:
# result.append(number)
yield number # if you use yield you get a generator, and we don't need to build
# up the list in memory; think of it as a sort of lazy list
# yield is like having a function "return" a value then continue to execute
# return result
# printed_result = ""
# for number in numbers(2000, 3200):
# printed_result = "{} {},".format(printed_result, number)
# print printed_result[:-1]
# just use the join method of the string type, pass it a list of strings and no
# more trailing comma to handle
print ",".join(
[str(num) for num in numbers(2000, 3200)]
)
| true |
a57e1fe462002e2797275191cba5b2ebd0d2cfc5 | ak45440/Python | /Replace_String.py | 667 | 4.1875 | 4 | # Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string,
# if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string.
# Sample String : 'The lyrics is not that poor!'
# 'The lyrics is poor!'
# Expected Result : 'The lyrics is good!'
# 'The lyrics is poor!'
def aparece(frase):
Snot = frase.find('not')
Spoor = frase.find('poor')
if Spoor > Snot and Spoor > 0 and Snot > 0:
frase = frase.replace(frase[Snot:Spoor+4], 'good')
return frase
else:
return frase
frase = input('Digite uma frase: ')
print(aparece(frase))
| true |
55ce803bd9272354d37b9adb0398bfa6abcf0bd5 | ChennakeshavaNT/Python-Programming | /Turtle_Graphics/ChessBoard/chessboard.py | 1,676 | 4.21875 | 4 | #this code prints a chessboard using turtle graphics
#Input: No Input
#output: Chessboard representaion
import turtle
ck = turtle.Turtle()
#Creation of a turtle named ck
ck.clear()
ck.forward(80)
ck.left(180)
ck.forward(80)
ck.right(180)
#iterative Approach is used
for a in range(4):
ck.pendown()
for i in range(5):
ck.pendown()
#prints (_ ) 4 times starting from towards the left
for j in range(4):
ck.forward(10)
ck.penup()
ck.forward(10)
ck.pendown()
#changes turtle direction
ck.left(90)
ck.forward(1)
ck.left(90)
ck.penup()
#prints (_ ) 4 times starting from towards the Right
for k in range(4):
ck.forward(10)
ck.pendown()
ck.forward(10)
ck.penup()
ck.right(90)
ck.forward(1)
ck.right(90)
ck.pendown()
ck.penup()
ck.pendown()
for b in range(5):
##prints ( _) 4 times starting from towards the Right
for c in range(4):
ck.forward(10)
ck.pendown()
ck.forward(10)
ck.penup()
ck.left(90)
ck.forward(1)
ck.left(90)
ck.pendown()
#prints ( _) 4 times starting from towards the left
for k in range(4):
ck.forward(10)
ck.penup()
ck.forward(10)
ck.pendown()
ck.right(90)
ck.forward(1)
ck.right(90)
ck.penup()
ck.pendown()
ck.forward(80)
ck.penup()
#moves the turtle away from the chess board representation
ck.forward(30)
| false |
41126620e671d2c5298381eeda1f0a67b8f6a560 | Wei-Mao/Assignments-for-Algorithmic-Toolbox | /Divide-and-Conquer/Improving QuickSort/quicksort.py | 2,645 | 4.5 | 4 | # python3
from random import randint
from typing import List, Union
def swap_in_list(array, a, b):
array[a], array[b] = array[b], array[a]
def partition3(array: List[Union[float, int]] , left: [int], right: [int]) -> int:
"""
Partition the subarray array[left,right] into three parts such that:
array[left, m1-1] < pivot
array[m1, m2] == pivot
array[m2+1, right] > pivot
The above is also the loop invariant, which should hold prior to the loop and
from iteration to iteration to ensure the correctness of the algorithm.(right
is replaced by the loop variable i - 1)
Args:
array(List[Union[float, int]]): Reference to the original array.
left(int): Left index of the subarray.
right(int): Right index of the subarray.
Returns:
m1[int], m2[int]: array[m1,..., m2] == pivot and in their final positions.
Time Complexity: O(right - left)
Space Complexity: O(1)
"""
pivot_idx = randint(left, right)
pivot = array[pivot_idx]
# print(pivot)
# Move the pivot to the start of the subarray.
swap_in_list(array, left, pivot_idx)
# loop invariant:
# array[left, m1-1] < pivot if m1 > left or empty if m1=left
# array[m1, m2] == pivot
# array[m2+1, i-1] > pivot if i > m2 + 1 or empty
m1, m2 = left, left
for i in range(left + 1, right + 1):
if array[i] < pivot:
swap_in_list(array, i, m1)
m1 += 1
m2 += 1
swap_in_list(array, i, m2)
elif array[i] == pivot:
m2 += 1
swap_in_list(array, i, m2)
return m1, m2
def randomized_quick_sort(array, left, right):
"""
Time Complexity: O(nlogn) on average and O(n^2) in the worst case.
Space Complexity: O(logn) in worst case
"""
while left < right:
m1, m2 = partition3(array, left, right)
# array[left, m1-1] < pivot
# array[m1, m2] == pivot
# array[m2+1, right] > pivot
if (m1 - left) < (right - m2):
randomized_quick_sort(array, left, m1-1)
left = m2 + 1
else:
randomized_quick_sort(array, m2+1, right)
right = m1 - 1
if __name__ == '__main__':
input_n = int(input())
elements = list(map(int, input().split()))
assert len(elements) == input_n
randomized_quick_sort(elements, 0, len(elements) - 1)
print(*elements)
# input_array = [randint(-10, 10) for _ in range(6)]
# input_array.append(input_array[0])
# print(input_array)
# m1, m2 = partition3(input_array, 0, 6)
# print(input_array)
# print(f"m1 {m1} and m2 {m2}")
| true |
669c96051159e28260689b5bee2f33c71e4ef8b6 | SEugene/gb_algo | /hw_07_01.py | 1,128 | 4.1875 | 4 | """
Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами
на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована
в виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
from random import randint
def bubble_sort(array):
for idx in range(1, len(array)):
counter = 0
for idx_2 in range(len(array) - idx):
if array[idx_2] > array[idx_2 + 1]:
array[idx_2], array[idx_2 + 1] = array[idx_2 + 1], array[idx_2]
counter += 1
if counter == 0:
break
return array
array_to_sort = [randint(-100, 100) for _ in range(15)]
print(f'Первоначальный массив: {array_to_sort}')
print(f'Отсротированный массив: {bubble_sort(array_to_sort)}')
| false |
26ab13287b1ea07319831266fe190de1762bb084 | pombredanne/Revision-Scoring | /revscores/languages/language.py | 591 | 4.125 | 4 | class Language:
"""
Constructs a Language instance that wraps two functions, "is_badword" and
"is_misspelled" -- which will check if a word is "bad" or does not appear
in the dictionary.
"""
def __init__(self, is_badword, is_misspelled):
self.is_badword = is_badword
self.is_misspelled = is_misspelled
def badwords(self, words):
for word in words:
if self.is_badword(word): yield word
def misspellings(self, words):
for word in words:
if self.is_misspelled(word): yield word
| true |
10fed729debcd5ba51cfa9da23c2a6e548f6a0ac | kunalrustagi08/Python-Projects | /Programming Classroom/exercise7.py | 920 | 4.21875 | 4 | '''
We return to the StringHelper class, here we add another static method called
Concat, this method receives a single parameter called Args, which is a
"Pack of parameters", which means that we can pass as many parameters as we
want, then, within this function there will be A variable called Curr that
will be initialized as an empty string, and using a for iterator, the
"Parameters Pack" will be traversed and each parameter will be concatenated
to Curr variable, after the for it must return the value of the Curr variable.
'''
class StringHelper:
@staticmethod
def reverse(originalStr: str):
return str(originalStr[::-1])
@staticmethod
def concat(*args):
curr = ''
for arg in args:
curr += arg
return curr
print(StringHelper.concat('Hello'))
print(StringHelper.concat('Hello', 'Hector'))
print(StringHelper.concat('Hello', ' ', 'Hector'))
| true |
580438f74309cbffd7841166b374f8814c04eea3 | kunalrustagi08/Python-Projects | /Programming Classroom/exercise3.py | 1,441 | 4.46875 | 4 | '''
Create a class called Calculator. This class will have four static methods:
Add()
Subtract()
Multiply()
Divide()
Each method will receive two parameters: "num1" and "num2" and will return the
result of the corresponding arithmetic operation.
Example: The static addition method will return the sum of num1 and num2. Then,
you must choose numbers of your preference and perform an operation with them
for each method, for example, you can choose 10 and 50 to make the sum.
Print the result of each method.
'''
class Calculator:
@staticmethod
def add(num1, num2):
sum = num1 + num2
return sum
@staticmethod
def subtract(num1, num2):
dif = num1 - num2
return dif
@staticmethod
def multiply(num1, num2):
prod = num1 * num2
return prod
@staticmethod
def divide(num1, num2):
quo = format((num1 / num2), '.2f')
return quo
@staticmethod
def int_divide(num1, num2):
int_quo = num1 // num2
return int_quo
@staticmethod
def remainder(num1, num2):
rem = num1 % num2
return rem
print(f'Sum is {Calculator.add(10,50)}')
print(f'Difference is {Calculator.subtract(50, 30)}')
print(f'Product is {Calculator.multiply(1,0)}')
print(f'Division equals {Calculator.divide(10,3)}')
print(f'Integer Division equals {Calculator.int_divide(10,3)}')
print(f'Remainder equals {Calculator.remainder(10,3)}')
| true |
130d9e5dd29b1f817b661e9425ffe278ccc44e8d | rebht78/course-python | /exercises/solution_01_04.py | 347 | 4.125 | 4 | # create first_number variable and assign 5
first_number = 5
# create second_number variable and assign 5
second_number = 5
# create result variable to store addition of first_number and second_number
result = first_number + second_number
# print the output, note that when you add first_number and second_number you should get 10
print(result) | true |
39e669b95b5b08afdab3d3b16cb84d673aecbf8e | ctsweeney/adventcode | /day2/main.py | 2,106 | 4.375 | 4 | #!/usr/bin/env python3
def read_password_file(filename: str):
"""Used to open the password file and pass back the contents
Args:
filename (str): filepath/filename of password file
Returns:
list: returns list of passwords to process
"""
try:
with open(filename, "r") as f:
# Return list of passwords to perform password logic on
contents = f.readlines()
return contents
except FileNotFoundError:
print("File %s not found" % filename)
def check_password1(data):
"""Used to check the password policy one problem
Args:
data (str): A list object containing all the passwords that we want to check against policy
"""
TOTAL = 0
for password in data:
DATA = password.split()
RANGE = DATA[0].split('-')
POLICY_LETTER = DATA[1].replace(':', '')
POLICY_MIN = int(RANGE[0])
POLICY_MAX = int(RANGE[1])
PASSWORD = DATA[2]
LIMIT = 0
for letter in PASSWORD:
if letter == POLICY_LETTER:
LIMIT += 1
if LIMIT >= POLICY_MIN and LIMIT <= POLICY_MAX:
TOTAL += 1
return str(TOTAL)
def check_password2(data):
"""Used to check the password policy two problem
Args:
data (str): A list object containing all the passwords that we want to check against policy
"""
TOTAL = 0
for password in data:
DATA = password.split()
RANGE = DATA[0].split('-')
POLICY_LETTER = DATA[1].replace(':', '')
POLICY_MIN = (int(RANGE[0]) - 1)
POLICY_MAX = (int(RANGE[1]) - 1)
PASSWORD = list(DATA[2])
if PASSWORD[POLICY_MIN] == POLICY_LETTER or PASSWORD[POLICY_MAX] == POLICY_LETTER:
if PASSWORD[POLICY_MIN] != PASSWORD[POLICY_MAX]:
TOTAL += 1
return str(TOTAL)
PASSWORD_DATA = read_password_file('passwords.txt')
print(check_password1(PASSWORD_DATA) +
" passwords that meet password policy one")
print(check_password2(PASSWORD_DATA) +
" passwords that meet password policy two")
| true |
5cb50cc07e8cb2a28b8ed06a403dd8d69db1a33d | isailg/python_notes | /condition.py | 293 | 4.1875 | 4 | # age = int(input("Type your age: "))
# if age > 18:
# print("You are of age")
# else:
# print("You are a minor")
number = int(input("Type a number: "))
if number > 5:
print("Greater of 5")
elif number == 5:
print("Equal to 5")
elif number < 5:
print("Less than 5")
| false |
017a3268e5de015c8f0c25045f44ae7a4ffe7a50 | dky/cb | /legacy/fundamentals/linked-lists/03-08-20/LinkedList.py | 1,893 | 4.1875 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
# We always have a dummy node so the list is never empty.
self.head = Node("dummy")
self.size = 0
def __str__(self):
out = ""
cur = self.head.next
while (cur):
out += str(cur.item) + "/"
cur = cur.next
return out
# Description: Insert a node at the front of the LinkedList
def insertFront(self, item):
# H => 1 => 2 # insert 3
# H => 3 => 1 => 2
# Store H => 1, now head = 1
prevNext = self.head.next
# Insert a new node item ex: 3, this would replace 1 with 3.
self.head.next = Node(item)
# Set the next pointer of the new node to point to 1, which was the
# previous head.
self.head.next.next = prevNext
# increment the size
self._size += 1
def insertLast(self, item):
# Since we cannot just insert at the end of a singly linked list we
# have to iterate to the end to insert an item.
# keep track of node we are on
cur = self.head
# This can also be while (cur.next)
while (cur.next is not None):
cur = cur.next
cur.next = Node(item)
self._size += 1
# Description: Remove a node from the beginning.
def removeBeginning(self):
# No idea what assert is?
assert (self.size() > 0)
# H => 1 => 2 # removeBeginning
# H => 2
# H => 1, Now, set it to point to 2.
self.head.next = self.head.next.next
self._size -= 1
def size(self):
return self._size
if __name__ == "__main__":
# test cases
linkedList = LinkedList
for i in range(1, 6):
# print(i)
linkedList.insertFront(i)
| true |
105e9536a5a82cde5cf7c204e0d3316ceab5867d | dky/cb | /legacy/educative/lpfs/functions-as-arguments.py | 470 | 4.28125 | 4 | """
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
"""
def calculator(operation, n1, n2):
return operation(n1, n2) # Using the 'operation' argument as a function
# 10, 20 = args
print(calculator(lambda n1, n2: n1 * n2, 10, 20))
"""
print(calculator(multiply, 10, 20))
print(calculator(add, 10, 20))
"""
| false |
9390e6095c6140ba0117bfd18fb63844189d7a68 | abhijnashree/Python-Projects | /prac1.py | 218 | 4.28125 | 4 | #Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 == 0):
#print odd characters
print(i[index])
| true |
e0c62280d0a17510b152d5aff2671bc89e0de4d4 | DevOpsStuff/Programming-Language | /Python/PythonWorkouts/NumericTypes/run_timings.py | 488 | 4.125 | 4 | #!/usr/bin/env python
def run_timing():
"""
Asks the user repeatedly for numberic input. Prints the average time and number of runs
"""
num_of_runs = 0
total_time = 0
while True:
one_run = input('Enter 10 Km run time: ')
if not one_run:
break
num_of_runs += 1
total_time += float(one_run)
average_time = total_time / num_of_runs
print(f'Average of {average_time}, over {num_of_runs} runs')
run_timing()
| true |
ad810639d9f0b8b4545b3641e6bd0c0cd976f916 | aswathyp/TestPythonProject | /Sessions/2DArray.py | 910 | 4.25 | 4 | # Two-Dimensional List
a = [[1,2], [3,4], [5,6]]
# Via Indices
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
print('\n')
# Via Elements
for row in a:
for element in row:
print(element, end=' ')
print('\n')
# Generate 2D
n = 3
m = 4
arr = [[0] * m] * n #doesn't create a memory for the n rows
arr[0][2] = 5
print('2D: ', arr, sep='\n')
a = [[0] * m for i in range(n)] # Generator contruct and creates memory of 2D list
for i in range(n):
b.append([0] * m) # Creates a memory and assign the sub-list
# Input 2D Array
rows = int(input('Enter number of rows: '))
arrList = []
for i in range(rows):
print('Reading ', i , 'th row: ')
arrList.append([int(j) for j in input().split()])
print(i, 'th row is: ', arrList[i])
print('Array List:', arrList, sep=' ')
arrList = [[int(j) for j in input.split() if j!=-1] for i in range(n)] | false |
1aa76c29644208c7094733bfbb3a876c1ffb9b83 | aswathyp/TestPythonProject | /Assignments/Loops/2_EvenElementsEndingWith0.py | 362 | 4.1875 | 4 |
# Even elements in the sequence
numbers = [12, 3, 20, 50, 8, 40, 27, 0]
evenElementCount = 0
print('\nCurrent List:', numbers, sep=' ')
print('\nEven elements in the sequence: ')
for num in numbers:
if num % 2 == 0:
print(num, end=' ')
evenElementCount = evenElementCount + 1
print('\n\nTotal Count of Even Numbers: ', evenElementCount)
| true |
e0fe9a4a068ebbdd0956bbfc525f83551b75b2b0 | gowtham9394/Python-Projects | /Working with Strings.py | 788 | 4.40625 | 4 | # using the addition operator without variables [String Concatenation]
name = "Gowtham" + " " + "Kumar"
print(name)
# using the addition operator with variables
first_name = "Gowtham"
last_name = "Kumar"
full_name = first_name + " " + last_name
print(full_name)
# using the new f strings [after python 3.6]
print( f"Hello {full_name}")
# using indexes to print each element
word = "Computer"
print( word [0])
print( word [1])
print( word [2])
print( word [3])
print( word [4])
print( word [5])
print( word [6])
print( word [7])
print( word [-0])
print( word [-1])
print( word [-2])
print( word [-3])
print( word [-4])
print( word [-5])
print( word [-6])
print( word [-7])
# using string slicing to print each element
print(word [0:1])
print(word [0:8])
print( word[ 0 : 5 : 3 ] ) | true |
f9bfecf22f03336080907a61c1f21adc95668396 | pinnockf/project-euler | /project_euler_problem_1.py | 490 | 4.3125 | 4 | '''
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def main(threshold):
multiples = []
for number in range(threshold):
if number % 3 is 0 or number % 5 is 0:
multiples.append(number)
return sum(multiples)
if __name__ == '__main__':
assert main(10) is 23
print(main(1000))
| true |
b56e0272c2632b3b85657535568dc242c7504b62 | shefali-pai/comp110-21f-workspace | /exercises/ex05/utils.py | 1,572 | 4.28125 | 4 | """List utility functions part 2."""
__author__ = "730466264"
# Define your functions below
from typing import List
def main() -> None:
"""Entry of function."""
list_1: List[int] = [1, 3, 5]
list_2: List[int] = [1]
a_list: List[int] = [1, 2, 3, 4, 5]
number_1: int = 1
number_2: int = 4
print(only_evens(list_1))
print(sub(a_list, number_1, number_2))
print(concat(list_1, list_2))
def only_evens(list_1: List[int]) -> List[int]:
"""Finding evens in a list."""
i: int = 0
even_list: List[int] = []
while i < len(list_1):
if list_1[i] % 2 == 0:
even_list.append(list_1[i])
i += 1
return even_list
def sub(a_list: List[int], number_1: int, number_2: int) -> List[int]:
"""Making a new list with some list items."""
new_list: List[int] = []
if len(a_list) == 0 or number_1 > len(a_list) - 1 or number_2 <= 0:
return new_list
if number_1 < 0:
number_1 = 0
if number_2 > len(a_list):
number_2 = len(a_list)
i: int = number_1
while i >= number_1 and i < number_2:
new_list.append(a_list[i])
i += 1
return new_list
def concat(list_1: List[int], list_2: List[int]) -> List[int]:
"""Putting two lists together."""
i: int = 0
concat_list: List[int] = []
while i < len(list_1):
concat_list.append(list_1[i])
i += 1
i = 0
while i < len(list_2):
concat_list.append(list_2[i])
i += 1
return concat_list
if __name__ == "__main__":
main()
| false |
3654c2a1ca8756660b6da99b2d571c6a508a9568 | shefali-pai/comp110-21f-workspace | /exercises/ex07/data_utils.py | 2,561 | 4.15625 | 4 | """Utility functions."""
__author__ = "730466264"
from csv import DictReader
def read_csv_rows(filename: str) -> list[dict[str, str]]:
"""Read the rows of a csv into a 'table'."""
result: list[dict[str, str]] = []
file_handle = open(filename, "r", encoding="utf8")
csv_reader = DictReader(file_handle)
for row in csv_reader:
result.append(row)
file_handle.close()
return result
def column_values(table: list[dict[str, str]], column: str) -> list[str]:
"""Produce a list[str] of all values in a single column."""
result: list[str] = []
for row in table:
item: str = row[column]
result.append(item)
return result
def columnar(row_table: list[dict[str, str]]) -> dict[str, list[str]]:
"""Transform a row-oriented table to a column-oriented table."""
result: dict[str, list[str]] = {}
first_row: dict[str, str] = row_table[0]
for column in first_row:
result[column] = column_values(row_table, column)
return result
def head(tbl: dict[str, list[str]], rw_nmbr: int) -> dict[str, list[str]]:
"""Creating a dictionary from the table."""
return_dict: dict[str, list[str]] = {}
if rw_nmbr >= len(tbl):
return tbl
for clmn in tbl:
n_list: list[str] = []
i: int = 0
while i < rw_nmbr:
n_list.append(tbl[clmn][i])
i += 1
return_dict[clmn] = n_list
return return_dict
def select(clmn_tbl: dict[str, list[str]], clmn: list[str]) -> dict[str, list[str]]:
"""Creating a table from columns from an original column table."""
return_dict: dict[str, list[str]] = {}
for key in clmn:
return_dict[key] = clmn_tbl[key]
return return_dict
def concat(dict_1: dict[str, list[str]], dict_2: dict[str, list[str]]) -> dict[str, list[str]]:
"""Producing a table made out of columns from 2 tables from columns."""
return_dict: dict[str, list[str]] = {}
for key in dict_1:
return_dict[key] = dict_1[key]
for key in dict_2:
if key in return_dict:
return_dict[key] += dict_2[key]
else:
return_dict[key] = dict_2[key]
return return_dict
def count(values: list[str]) -> dict[str, int]:
"""Counting the frequency of values."""
return_dict: dict[str, int] = {}
for key in values:
if key in return_dict:
value_present: int = return_dict[key]
return_dict[key] = value_present + 1
else:
return_dict[key] = 1
return return_dict | true |
57b07d75c2d81356bab342880380353f6debbc25 | meginks/data-structure-notes | /Queues/queues.py | 2,152 | 4.15625 | 4 | class ListQueue:
def __init__(self):
self.items = []
self.size = 0
def enqueue(self, data):
"""add items to the queue. Note that this is not efficient for large lists."""
self.items.insert(0, data) #note that we could also use .shift() here -- the point is to add the new thing at index 0 to mimic a queue
self.size += 1
def dequeue(self):
"""removes an item from the queue"""
data = self.items.pop()
self.size -= 1
return data
class StackBasedQueue:
"""this is a stack-based queue"""
def __init__(self):
self.inbound_stack = []
self.outbound_stack = []
def enqueue(self, data):
"""adds item to the incoming stack"""
self.inbound_stack.append(data)
def dequeue(self, data):
if not self.outbound_stack:
while self.inbound_stack:
self.outbound_stack.append(self.inbound_stack.pop())
return self.outbound_stack.pop()
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = None
self.prev = None
def __str__(self):
return str(self.data)
class NodeBasedQueue:
"""a doubly linked list that behaves like a queue"""
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def enqueue(self, data):
new_node = Node(data, None, None)
if self.head is None:
self.head = new_node
self.tail = self.head
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
self.count += 1
def dequeue(self):
# current = self.head -- book example included this line, but I don't really understand why because it doesn't matter?
if self.count == 1:
self.count -= 1
self.head = None
self.tail = None
elif self.count > 1:
self.head = self.head.next
self.head.prev = None
self.count -= 1
| true |
319d2d9261047ba9218b7b696fb33ad7fc1895a3 | neelindresh/try | /VerificationFunctions.py | 2,729 | 4.1875 | 4 | import numpy as np
import pandas as pd
import operator
def check_column(df, ops, first_mul, col_name, oper, value):
'''
This function will return the list of valid and invalid rows list after performing the operation
first_mul * df[col_name] oper value ex: [ 1*df['age'] >= 25 ].
'''
valid_rows_list = []
invalid_rows_list = []
for i, row in enumerate(df[col_name]):
if ops[oper](first_mul*row, value):
valid_rows_list.append(i)
else:
invalid_rows_list.append(i)
return valid_rows_list, invalid_rows_list
def values_in(df,col_name, inp_list):
'''
This function will iterate the df[col_name] and checks if all the values in df[col_name] are in inpu_list.
This returns the valid_rows_list which contains indexes of all rows which are in inp_list and
invalid_rows_list which contains indexes of all rows which are not in inp_list
'''
valid_rows_list = []
invalid_rows_list = []
if 'float' in str(df[col_name].dtype):
inp_list = list(map(float, inp_list))
elif 'int' in str(df[col_name].dtype):
inp_list = list(map(int, inp_list))
for i, value in enumerate(df[col_name]):
if value in inp_list:
valid_rows_list.append(i)
else:
invalid_rows_list.append(i)
return valid_rows_list, invalid_rows_list
def compare_columns(df,ops,col_name1, col_name2, oper, first_mul=1, sec_mul=1):
'''
This function returns the list of indexes of rows which satisfy and doesn't satisfy the condition
[first_mul*col_name1 op1 sec_mul*col_name2] ex: [1*mayRevenue >= 1.5*aprilRevenue].
'''
valid_rows_list = []
invalid_rows_list = []
for i in range(len(df[col_name1])):
if ops[oper](first_mul*df[col_name1][i], sec_mul*df[col_name2][i]):
valid_rows_list.append(i)
else:
invalid_rows_list.append(i)
return valid_rows_list, invalid_rows_list
def check_not_null(df, oper, col_name):
'''
This function will check for the null in df[col_name] and returns the list of indexes which is not equal to null
and the list of list of indexes which is equal to null
'''
valid_rows_list = []
invalid_rows_list = []
for i, value in enumerate(df[col_name]):
if oper=='!=' and not(pd.isnull(value)):
valid_rows_list.append(i)
elif oper=='==' and pd.isnull(value):
valid_rows_list.append(i)
else:
invalid_rows_list.append(i)
return valid_rows_list, invalid_rows_list
| true |
d8d791d01895b3a173b4d8003b2e2b648905b3da | AlirezaTeimoori/Unit_1-04 | /radius_calculator.py | 480 | 4.125 | 4 | #Created by: Alireza Teimoori
#Created on: 25 Sep 2017
#Created for: ICS3UR-1
#Lesson: Unit 1-04
#This program gets a radius and calculates circumference
import ui
def calculate_circumferenece(sender):
#calculate circumference
#input
radius = int(view['radius_text_field'].text)
#process
circumference=2*3.14*radius
#output
view['answer_lable'].text = "Circumference is: " + str(circumference) + "cm"
view = ui.load_view()
view.present('sheet')
| true |
a06ef912a2f2ffaa962b974f273f8d465d3dfe7f | daikiante/python_Udemy | /python_basic/lesson_002.py | 620 | 4.25 | 4 | # helpコマンド 関数、ライブラリの機能が表示される
# import math
# print(help(math))
# '' "" \n ==> 改行
print('say "I don\'t know"')
print('hello \n how are you')
# インデックスとスライス
word = 'Python'
print(word[0])
print(word[1])
print(word[-1])
print(word[0:2])
print(word[2:5])
print('----------------------------')
'''
インデックスの更新
Python ==> Jython
word[0] = 'J' だとエラーになる
word = 'J' + word[1:] <===これで解決
'''
word = 'J' + word[1:]
print(word)
# インデックスの長さ len()
n = len(word)
print(n) | false |
e2c0ea3f0638d3d181a0d291eb488839f1596001 | Yasin-Yasin/Python-Tutorial | /005 Conditionals & Booleans.py | 1,415 | 4.375 | 4 | # Comparisons
# Equal : ==
# Not Equal : !=
# Greater Than : >
# Less Than : <
# Greater or Equal : >=
# Less or Equal : <=
# Object Identity : is
# if block will be executed only if condition is true..
if True:
print("Conditinal was true")
if False:
print("Conditinal was False")
# else
language = 'Java'
if language == 'Python':
print("Language is Python")
else:
print('No Match')
# elseif -elif
if language == 'Python':
print("Language is Python")
elif language == 'Java':
print("Language is Java")
elif language == 'Javascript':
print("Language is Javascript")
else:
print('No Match')
# BOOLEAN - and or not
user = "Admin"
logged_in = True
if user == 'Admin' and logged_in:
print("Admin Page")
else:
print("Bad Creds")
# not
if not logged_in:
print("Please Log In")
else:
print("Welcome")
# is
a = [1,2,3]
b = [1,2,3]
print(a == b)
b = a # Now a is b will be true.
print(id(a))
print(id(b))
print(a is b) # Comparing identity : id(a) == id (b)
print(id(a) == id(b))
# False Values : Below Condition will be evaluated as False
# False
# None - will be Flase
# Zero of any numeric type
# Any empty sequence, for example, "", (), []
# Any empty mapping, for example, {}
condition = 'Test'
if condition:
print("Evaluated to True")
else:
print("Evaluated to False") | true |
f17feb86a3277de3c924bcecb2cc62dee8801e1b | Yasin-Yasin/Python-Tutorial | /014 Sorting.py | 1,686 | 4.28125 | 4 | # List
li = [9,1,8,2,7,3,6,4,5]
s_li = sorted(li)
print("Sorted List\t", s_li) # This function doesn't change original list, It returns new sorted list
print('Original List\t', li)
li.sort() # sort method sort original list, doesn't return new list, this method is specific to List obj
print('Original List, Now Sorted\t', li)
# Reverse Sorting
li1 = [9,1,8,2,7,3,6,4,5]
s_li1 = sorted(li1, reverse=True)
li1.sort(reverse=True)
print("Sorted Reverse List\t", s_li1)
print("Sorted Reverse Original List\t", li1)
# Tuple
tup = (9,1,8,2,7,3,6,4,5)
s_tup = sorted(tup)
print('Sorted Tuple\t', s_tup) # It will return list
# Dictionary
di = {'name' : 'Corey', 'Job' : 'Programming', 'age' : None, 'OS' : 'Mac'}
s_di = sorted(di) # It will return sorted list of keys
print("Sorted Dic", s_di)
# Key parameter with sorted function
li2 = [-6,-5,-4,1,2,3]
s_li2 = sorted(li2)
print(s_li2)
s_li2 = sorted(li2, key=abs)
print(s_li2)
# Sort Employee Object by name, age , Salary,
class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
# str representation of class instance/object
def __repr__(self):
return f'{(self.name, self.age, self.salary)}'
e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)
employees = [e1, e2, e3]
def e_sort(emp):
return emp.name
s_employees = sorted(employees, key=e_sort)
# s_employees = sorted(employees, key=lambda emp:emp.name)
# Amother way to do above thing is
# from operator import attrgetter
# s_employees = sorted(employees, key=attrgetter('salary'))
print(s_employees) | true |
074ac0d3a6836dbf02831280eb8cd55adb3a508d | ZHANGYUDAN1222/Assignment2 | /place.py | 1,282 | 4.3125 | 4 | """
1404 Assignment
class for functions of each place
"""
# Create your Place class in this file
class Place:
"""Represent a Place object"""
def __init__(self, name='', country='', priority=0, v_status=''):
"""Initialise a place instance"""
self.name = name
self.country = country
self.priority = priority
self.v_status = v_status
if self.v_status == False:
self.v_status = 'n'
elif self.v_status == True:
self.v_status = 'v'
def __str__(self):
"""Return string representation of place object"""
return "{} in {} priority {}, visited = {}".format(self.name, self.country, self.priority, self.v_status)
def mark_visited(self):
"""Return visited for unvisited place"""
self.v_status = 'v'
return self.v_status
def mark_unvisited(self):
"""Return unvisited for visited place"""
self.v_status = 'n'
return self.v_status
def isimportant(self):
"""Return T if priority <=2, vise reverse"""
if self.priority <= 2:
# print('{} is important'.format(self.name))
return True
else:
# print('{} is not important'.format(self.name))
return False
| true |
79144ad6f7efd0fcdc7d3fe20e04a881cb1b544a | Diwyang/PhytonExamples | /demo_ref_list_sort3.py | 1,206 | 4.40625 | 4 | # A function that returns the length of the value:
#list.sort(reverse=True|False, key=myFunc)
#Sort the list descending
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
#Sort the list by the length of the values:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars)
#Sort a list of dictionaries based on the "year" value of the dictionaries:
# A function that returns the 'year' value:
def myFunc1(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc1)
print(cars)
#Sort the list by the length of the values and reversed:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
print(cars)
#Sort the list by the length of the values and reversed:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
print(cars) | true |
ba6e01baaa2b69497ede48f24737831c8d35fa68 | Diwyang/PhytonExamples | /Example4.py | 531 | 4.21875 | 4 | # My Example 3
"""There are three numeric types in Python:
int - Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
float - Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
complex - Complex numbers are written with a "j" as the imaginary part
Variables of numeric types are created when you assign a value to them."""
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
| true |
a6158f2bf6ce87e6213cb5de60d4b82d9cd5000c | guoguozy/Python | /answer/ps1/ps1b.py | 648 | 4.21875 | 4 | annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(
input('Enter the percent of your salary to save, as a decimal: '))
total_cost = float(input('Enter the cost of your dream home: '))
semi_annual_raise = float(input('Enter the semiannual raise, as a decimal: '))
current_savings = 0.0
month = 0
while current_savings < (total_cost*0.25):
if month != 0 and month % 6 == 0:
annual_salary += annual_salary*semi_annual_raise
current_savings = (current_savings*0.04)/12 + \
annual_salary/12*portion_saved+current_savings
month = month+1
print('Number of months:%s\n'% month)
| true |
123f44d763fe59334151321a24a1c3a3cf7b284c | Ret-David/Python | /IS 201/Concept Tests/CT05_David_Martinez.py | 689 | 4.21875 | 4 | # David Martinez
# Write a pseudo code to design a program that returns the # of occurrences of
# unique values but sorted from the list. For example, with the input list
# [1, 2, -2, 1, 0, 2, 4, 0], the program should provide the output as follows:
# unique value (# of occurrences)
# -2(1)
# 0(2)
# 1(2)
# 2(2)
# 4(1)
#==============================
#-------------- my seudo code ----------------
# create an empty output dictionary
# for step through input_list, use set for dupes
# count through values and identify dupes
# append duplicates and count to output_dict
# for step through keys of sorted dictionary
# print format for screen output
| true |
879206042b294d5da53faf0c85858394a2e7b28e | Ret-David/Python | /IS 201/Module 1/HOP01.py | 1,789 | 4.34375 | 4 | # HOP01- David Martinez
# From Kim Nguyen, 4. Python Decision Making Challenge
# Fix the program so that the user input can be recognized as an integer.
# Original Code
guess = input("Please guess a integer between 1 and 6: ")
randomNumber = 5
if (guess == randomNumber):
print("Congrats, you got it!")
else:
print("Oops, goodluck next time!")
# Corrected code identifying guess and randomNumber as integers.
guess = input("Please guess a integer between 1 and 6: ")
randomNumber = 5
if (int(guess) == int(randomNumber)):
print("Congrats, you got it!")
else:
print("Oops, goodluck next time!")
# ------------------------------
# From Kim Nguyen, 5. While loop
# Fix the program so that the it only allows three guesses.
# Original Code
attempt = 0
randomNumber = 5
while attempts <= 3:
guess = input("Please guess a integer between 1 and 6: ")
if (guess == randomNumber):
print("Congrats, you got it!")
else:
print("Oops, goodluck next time!")
attempts += 1
# Corrected code that allows for only three guesses.
# I found that you could either set the variable attempt to 1
# or you can change the while attempts to <= 2.
attempts = 1
randomNumber = 5
while attempts <= 3:
guess = input("Please guess a integer between 1 and 6: ")
if (guess == randomNumber):
print("Congrats, you got it!")
else:
print("Oops, goodluck next time! Attempt #", attempts)
attempts += 1
# or you can change the while attempts to <= 2.
attempts = 0
randomNumber = 5
while attempts <= 2:
guess = input("Please guess a integer between 1 and 6: ")
if (guess == randomNumber):
print("Congrats, you got it!")
else:
print("Oops, goodluck next time! Attempt #", attempts)
attempts += 1
| true |
0d022905006e7bb3113a9726c9780b13eb55b544 | Ret-David/Python | /IS 201/Practical Exercises/PE05_David_Martinez_4.py | 1,725 | 4.34375 | 4 | # David Martinez
# Make two files, cats.txt and dogs.txt.
# Store at least three names of cats in the first file and three names of dogs in
# the second file.
# Write a program that tries to read these files and print the contents of the file
# to the screen.
# Wrap your code in a try-except block to catch the FileNotFound error, and print a
# friendly message if a file is missing.
while True: # while statement to loop through exception handling till a True value is produced
try: # run the following code block, test for errors
cat_file_open = open("PE05_David_Martinez_4_cats.txt", "r") # variable assigned to file
cat_file_open.readline() # read the lines of the file into the variable
for cats in cat_file_open: # for each cat name in the file
print(cats, end='') # print their name to screen, strip the new line
print("\n") # add a new line at the end of the names
cat_file_open.close() # close the open file
dog_file_open = open("PE05_David_Martinez_4_dogs.txt", "r") # variable assigned to file
dog_file_open.readline() # read the lines of the file into the variable
for dogs in dog_file_open: # for each dog name in the file
print(dogs, end='') # print their name to screen, strip the new line
print("\n") # add a new line at the end of the names
dog_file_open.close() # close the open file
break # exit this while statement
except FileNotFoundError: # if an file name is produced, print the following message
print("Your code needs a valid file name or path, please.")
break # exit this while statement
| true |
92acf42a33fefc55d10db64cb4a2fd7856bc21de | Ret-David/Python | /IS 201/Concept Tests/CT09_David_Martinez.py | 616 | 4.375 | 4 | # David Martinez
# Write a pseudo code to design a program that returns I-th largest value
# in a list. For example, with the input list [3, 2, 8, 10, 5, 23]
# and I = 4, the program prints the value 5 as it is 4 th largest value.
# ========== My Pseudo Code ==========
# >> 5 is in index 4 position but is the 3rd largest value
# >> largest value is in index 5 position
# variable = input list values
# variable = I-th largest value
# variable = unsorted output for index position I-th
# variable = sorted output for nth largest value
# print I-th value
# print nth value
# print largest value in index location
| true |
5e7b828d0d74462a10fefbbee34d14c3f29f4c0c | ChloeDumit/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,674 | 4.28125 | 4 | #!/usr/bin/python3
""" Write the class Rectangle that inherits from Base"""
from .rectangle import Rectangle
"""
creating new class
"""
class Square(Rectangle):
""" class Square """
def __init__(self, size, x=0, y=0, id=None):
"initializes data"
self.size = size
super().__init__(self.__size, self.__size, x, y, id)
@property
def size(self):
""" getter """
return self.__size
@size.setter
def size(self, value):
"""size setter"""
if (type(value) is not int):
raise TypeError("width must be an integer")
if value <= 0:
raise ValueError("width must be > 0")
self.__size = value
def __str__(self):
"""override str"""
return ("[Square] ({}) {}/{} - {}".format(self.id,
self.x, self.y, self.__size))
def update(self, *args, **kwargs):
""" update arguments """
attributes = ["id", "size", "x", "y"]
if args and len(args) != 0:
for arg in range(len(args)):
if arg == 0:
super().update(args[arg])
elif arg < len(attributes):
setattr(self, attributes[arg], args[arg])
else:
for key, value in kwargs.items():
if key == 'id':
super().update(value)
else:
setattr(self, key, value)
def to_dictionary(self):
""" returns a dictionary of a class """
dic = {'id': self.id,
'size': self.__size,
'x': self.x,
'y': self.y
}
return dic
| true |
015e8232f2a297ecc7e8d0ebe7a25038125f13eb | dyfloveslife/SolveRealProblemsWithPython | /Practice/student_teacher.py | 1,166 | 4.15625 | 4 | class Person(object):
"""
return Person object
"""
def __init__(self, name):
self.name = name
def get_details(self):
"""
return string include person's name
"""
return self.name
class Student(Person):
"""
return Student Object,include name,branch,year
"""
def __init__(self, name, branch, year):
Person.__init__(self, name)
self.branch = branch
self.year = year
def get_details(self):
"""
return string include student's details
"""
return "{} studies {} and is in {} year.".format(self.name, self.branch, self.year)
class Teacher(Person):
"""
return Teacher Object,use string list as arguments
"""
def __init__(self, name, papers):
Person.__init__(self, name)
self.papers = papers
def get_details(self):
return "{} teaches {}".format(self.name, ','.join(self.papers))
person1 = Person('Sanchin')
student1 = Student('Kushal', 'CSE', 2005)
teacher1 = Teacher('Prashad', ['c', 'c++'])
print(person1.get_details())
print(student1.get_details())
print(teacher1.get_details())
| false |
8a2cc39e3dd9799e46aa0bd8f8b922fad8c99d8a | hahaliu/LeetCode-Python3 | /654.maximum-binary-tree.py | 1,420 | 4.15625 | 4 | # ex2tron's blog:
# http://ex2tron.wang
# 我的思路:先求max,然后分成左右,最后左右分别递归
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
num_max = max(nums)
max_index = nums.index(num_max)
left, right = nums[:max_index], nums[max_index+1:]
tree = TreeNode(num_max)
tree.left = self.constructMaximumBinaryTree(left)
tree.right = self.constructMaximumBinaryTree(right)
return tree
# 别人的思路:遍历不递归,效率更好,但相比之下不好理解
# class Solution:
# def constructMaximumBinaryTree(self, nums):
# """
# :type nums: List[int]
# :rtype: TreeNode
# """
# node_stack = []
# for num in nums:
# node = TreeNode(num)
# while node_stack and num > node_stack[-1].val:
# node.left = node_stack.pop()
# if node_stack:
# node_stack[-1].right = node
# node_stack.append(node)
# return node_stack[0]
print(Solution().constructMaximumBinaryTree([3, 2, 1, 6, 0, 5]))
| false |
5592f8f04714d6862c6ac90e03e5a83d0c4cd814 | Aritiaya50217/CompletePython3Programming | /section13_Gui/lecture98_event.py | 765 | 4.125 | 4 | # Event Driven Programming การเขียนโปรแกรมตามลำดับเหตุการณ์
from tkinter import *
def leftClickButton(event):
print("Left Click !! ")
def rightClickButton(event):
print("Right Button !! ")
def doubleClickLeft(event):
print("DoubleClick Left !!")
def doubleClickRight(event):
print("DoubleClick Right !!")
main = Tk()
button = Button(main,text="My Button !!")
button.place(x=40,y=20)
# <Button-1> ปุ่มซ้าย
# <Button-2> ปุ่มกลาง
# <Button-3> ปุ่มขวา
button.bind('<Button-1>',leftClickButton)
button.bind('<Button-3>',rightClickButton)
button.bind('<Double-1>',doubleClickLeft)
button.bind('<Double-3>',doubleClickRight)
main.mainloop()
| false |
b12bbaf3e31c5362fd198c6512d76d858470ac8d | jinayshah86/DSA | /CtCI-6th-Edition/Chapter1/1_6/string_compression_1.py | 1,653 | 4.1875 | 4 | # Q. Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string 'aabcccccaaa' would become
# 'a2b1c5a3'. If the "compressed" string would not become smaller than the
# original string, your method should return the original string. You can
# assume the string has only uppercase and lowercase letter (a-z).
# Time complexity: O(N); N is the length of the string.
# Space complexity: O(N); N is the length of the string.
import unittest
def string_compression(string: str) -> str:
# Check for empty string
if not string:
return string
# Check for string with alphabets only
if not string.isalpha():
raise ValueError
compressed_str = []
char_count = 0
for index, character in enumerate(string):
char_count += 1
if (index + 1) >= len(string) or character != string[index + 1]:
compressed_str.append(character)
compressed_str.append(str(char_count))
char_count = 0
# Convert list to string
compressed_str = "".join(compressed_str)
return compressed_str if len(compressed_str) < len(string) else string
class TestStringCompression(unittest.TestCase):
def test_compress(self):
self.assertEqual(string_compression("aabcccccaaa"), "a2b1c5a3")
def test_uncompress(self):
self.assertEqual(string_compression("mickey"), "mickey")
def test_exception(self):
self.assertRaises(ValueError, string_compression, "a2b1c5a3")
def test_empty(self):
self.assertEqual(string_compression(""), "")
if __name__ == "__main__":
unittest.main()
| true |
bfb24a739c79bffb1f60dbb54481ceb9ecd13ceb | BoynChan/Python_Brief_lesson_answer | /Char7-Import&While/char7.1.py | 511 | 4.125 | 4 | car = input("What kind of car do you want to rent?: ")
print("Let me see if I can find you a "+car)
print("------------------------------")
people = input("How many people are there?: ")
people = int(people)
if people >= 8:
print("There is no free table")
else:
print("Please come with me")
print("------------------------------")
number = input("Input a number and i will tell you if this number integer times of 10: ")
number = int(number)
if number%10 == 0:
print("Yes")
else:
print("No")
| true |
529402a5a5de14174db8206be4d1d24cef30396b | veshhij/prexpro | /cs101/homework/1/1.9.py | 422 | 4.21875 | 4 | #Given a variable, x, that stores
#the value of any decimal number,
#write Python code that prints out
#the nearest whole number to x.
#You can assume x is not negative.
# x = 3.14159 -> 3 (not 3.0)
# x = 27.63 -> 28 (not 28.0)
x = 3.14159
#DO NOT USE IMPORT
#ENTER CODE BELOW HERE
#ANY CODE ABOVE WILL CAUSE
#HOMEWORK TO BE GRADED
#INCORRECT
s = str( x + 0.5 )
dot = s.find( '.' )
print s[:dot] | true |
3ebe34a84dced2da2dd210256e0213ba2fdf39a4 | Heez27/python-basics | /03/operator-logical.py | 804 | 4.28125 | 4 | # 논리연산자 (not, or, and)
a = 30
b1 = a <= 30
# not
# not True -> False
# not False -> True
b2 = not b1
# or(논리합)
# False or False -> False
# True or False -> True
# False or True -> True
# True or True -> True
b3 = (a <= 30) or (a >= 100)
# and(논리곱)
# False and False -> False
# True and False -> False
# False or True -> False
# True or True -> True
b4 = (a <= 30) and (a >= 100)
# b4 = 100 <= a <= 30
print(b1, b2, b3, b4)
# 논리식의 계산순서
print(True or 'logical')
print(False or 'logical')
print([] or 'logical')
print([10, 20] or 'logical')
print('operator' or 'logical')
print('' or 'logical')
print('' or 'logical')
print(None or 'logical')
s = 'hello world'
# if s is not '':
# print(s)
s and print(s)
s = ''
s and print(s)
print('--------------')
| false |
01ccaa78ebe6cc532d8caca853365d8d05f29b22 | francomattos/COT5405 | /Homework_1/Question_08.py | 2,021 | 4.25 | 4 | '''
Cinderella's stepmother has newly bought n bolts and n nuts.
The bolts and the nuts are of different sizes, each of them is from size 1 to size n.
So, each bolt has exactly one nut just fitting it.
These bolts and nuts have the same appearance so that we cannot distinguish a bolt from another bolt,
or a nut from another nut, just by looking at them.
Fortunately, we can compare a bolt with a nut by screwing them together, to see if the size of the bolt is too large,
or just fitting, or too small, for the nut. Cinderella wants to join the ball held by Prince Charming.
But now, her wicked stepmother has mixed the bolts, and mixed the nuts, and tells her that she can go to the ball unless she can find the largest bolt
and the largest nut in time. An obvious way is to compare each bolt with each nut, but that will take n2 comparisons (which is too long).
Can you help Cinderella to find an algorithm requiring only o(n2) comparisons? For instance, O(n) comparisons?
'''
def find_largest_match(nuts, bolts):
# Starting with first nut and bolt.
index_nuts = 0
index_bolts = 0
match = {
"nut": 0,
"bolt": 0
}
# Go through nuts and bolts but stop when you get to last one.
while index_nuts < len(nuts) and index_bolts < len(bolts):
# If one is smaller than the other.
# Set aside the smallest item and pick up another one
if nuts[index_nuts] < bolts[index_bolts]:
index_nuts += 1
elif bolts[index_bolts] < nuts[index_nuts]:
index_bolts += 1
else:
# If they are equal, mark as the match, set aside the nut and pick up another
match = {
"nut": nuts[index_nuts],
"bolt": bolts[index_bolts]
}
index_nuts += 1
return match
if __name__ == "__main__":
nuts = [0, 1, 2, 3, 4, 5, 6, 15, 7, 12, 8, 16, 9, 10, 14]
bolts = [8, 7, 6, 12, 5, 16, 9, 10, 15, 14, 4, 3, 2, 1, 0]
print(find_largest_match(nuts, bolts))
| true |
db0682bd8033187a2ec73514dd2d389fb30ff2d0 | wpiresdesa/hello-world | /stable/PowerOf2.py | 639 | 4.5625 | 5 | #!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Add this line today - 29/October/2018 11:08Hs
# Add another line (this one) today 29/October/2018 11:10Hs
# Add another line (this one) today 29?october/2018 11:18Hs
# Python Program to display the powers of 2 using anonymous function
# Change this value for a different result
terms = 10
# Uncomment to take number of terms from user
# terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
print("The total terms is:", terms)
for i in range(terms):
print("2 raised to power", i, "is", result[i])
| true |
88074bfed63c071d5aa3558c1a9fe1798b3af34c | frsojib/python | /Code with herry/07_tamplate.py | 225 | 4.4375 | 4 |
letter = ''' Dear <|NAME|>,
You're selected!
Date <|DATE|>
'''
name = input('Enter your name: ')
date = input('Enter date: ')
letter= letter.replace("<|NAME|>", name)
letter= letter.replace("<|DATE|>", date)
print(letter)
| false |
d974cd6b8c7f5e8ea7672f0e935acac30dbd82a9 | mleue/project_euler | /problem_0052/python/e0052.py | 840 | 4.15625 | 4 | def get_digits_set(number):
"""get set of char digits of number"""
return set((d for d in str(number)))
def is_2x_to_6x_permutable(number):
"""check if all numbers 2x, 3x, 4x, 5x, 6x contain the same digits as number"""
digits_set = get_digits_set(number)
multipliers = (2, 3, 4, 5, 6)
for m in multipliers:
if not get_digits_set(m*number) == digits_set:
return False
return True
def find_smallest_2x_to_6x_permutable():
"""return the smallest integer whose 2x, 3x, 4x, 5x, and 6x all contain
the same digits as the number itself"""
lower_thresh, upper_thresh = 10, 17
while True:
for n in range(lower_thresh, upper_thresh):
if is_2x_to_6x_permutable(n):
return n
lower_thresh *= 10
upper_thresh *= 10
if __name__ == '__main__':
print(find_smallest_2x_to_6x_permutable())
| true |
4ff167bec52d0c1ab4196536b6ec81be4f3d13fe | gunit84/Code_Basics | /Code Basics Beginner/ex20_class_inheritance.py | 1,288 | 4.34375 | 4 | #!python3
"""Python Class Inheritance... """
__author__ = "Gavin Jones"
class Vehicle:
def general_usage(selfs):
print("General use: transportation")
class Car(Vehicle):
def __init__(self):
print("I'm Car ")
self.wheels = 4
self.has_roof = True
def specific_usage(self):
print("Specific Use: commute to work, vacation with family")
class Motorcycle(Vehicle):
def __init__(self):
print("I'm MotorCycle")
self.wheels = 2
self.has_roof = False
def specific_usage(selfs):
print("For Cruising and having fun!")
# Calls the Car Class
carInfo = Car()
# Inherits the general usage function from Vehicle Class
carInfo.general_usage()
# Uses it's own specific method
carInfo.specific_usage()
# Calls the Motorcycle Class
motorcycleInfo = Motorcycle()
# Inherits from Vehicle class
motorcycleInfo.general_usage()
# Uses it's own class method
motorcycleInfo.specific_usage()
# Check the Instance and Issubclass of the Objects
# This Checks the Object is an Instance of a Class or subclass
# Checks to see if carinfo is the Object/Instance of the Car Class
print(isinstance(carInfo, Car))
# Checks to see if Class Car is the subclass (inherits) from the Vehicle class
print(issubclass(Car, Vehicle))
| true |
d10ced02db8f0c93bd026b745cf916c1519fe4ef | gunit84/Code_Basics | /Code Basics Beginner/ex21_class_multiple_inheritance.py | 572 | 4.46875 | 4 | #!python3
"""Python Multiple Inheritance Example... """
__author__ = "Gavin Jones"
class Father():
def skills(self):
print('gardening, programming')
class Mother():
def skills(self):
print("cooking, art")
# Inherits from 2 SuperClasses above
class Child(Father, Mother):
def skills(self):
Father.skills(self)
Mother.skills(self)
print("I love sports")
# The child object is Created from the class Child which inherits the methods from the Parent Classes
child = Child()
# Inherited from Father Class
child.skills()
| true |
12a7da2b3332e10ffd87ff76ba3a2125060083ef | wanggao1990/PythonProjects | /= Fishc bbs/43 魔法方法 算术运算2.py | 2,213 | 4.15625 | 4 |
# int()、float()、str()、len()、tuple()、list() 等函数调用时,就创建一个相应的实例
####### 算术运算符
##
## __add__(self, other) 定义加法的行为:+
## __sub__(self, other) 定义减法的行为:-
## __mul__(self, other) 定义乘法的行为:*
## __truediv__(self, other) 定义真除法的行为:/
## __floordiv__(self, other) 定义整数除法的行为://
## __mod__(self, other) 定义取模算法的行为:%
## __divmod__(self, other) 定义当被 divmod() 调用时的行为
## __pow__(self, other[, modulo]) 定义当被 power() 调用或 ** 运算时的行为
## __lshift__(self, other) 定义按位左移位的行为:<<
## __rshift__(self, other) 定义按位右移位的行为:>>
## __and__(self, other) 定义按位与操作的行为:&
## __xor__(self, other) 定义按位异或操作的行为:^
## __or__(self, other) 定义按位或操作的行为:|
class New_int(int): #覆盖原来的方法
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)
a = New_int('5');print(a);
b = New_int(3);print(a+b)
print()
####### 反运算
# arg1 op arg2, 当arg1不支持op,将执行arg2的反op运算
class Nint(int):
def __radd__(self,other):
return int.__sub__(self,other)
def __rsub__(self,other):
return int.__sub__(self,other) # self在前 执行 self-other
a = Nint(5);b=Nint(3)
print(a+b) # 结果8。 a 可以进行 __add__
print(1+b) # 结果2。 1不行, 因此执行 b的__radd__ ,这里已经重写为减法 即3-1
class Nint2(int):
def __radd__(self,other):
return int.__sub__(self,other)
def __rsub__(self,other):
return int.__sub__(other,self) # self在后 执行 other-self
a = Nint(5); print( 3 - a); # 反运算,5 - 3
a = Nint2(5); print( 3 - a); # 反运算,3 - 5
####### 增量算符
## += 、 -=、 /=、 *= 、...
####### 一元操作算符
## 正号 +x 、 负号 -x、 绝对值 abs(x)、 按位取反 ~x
####### 类型转换
## complex()、int()、float()、round()
| false |
98888d25ea574d342d4a9b3d79854bdb27f09447 | wanggao1990/PythonProjects | /= Fishc bbs/16 序列(str,list,tuple转换) 序列运算.py | 2,155 | 4.46875 | 4 | # list、tuple、str 统称 序列(能迭代)
# 1 通过索引获得
# 2 默认索引值都是从0开始
# 3 分片方法获得元素的集合
# 4 操作符 (重复 拼接 关系)
## str,tuple => list
# 不带参数 空列表
a = list(); print(a)
# str转list,str每个字符都成为list元素 ['1', 'a', '2', 'b', '3', 'c']
a='1a2b3c'; a= list(a); print(a)
# tuple转list,每个元素都成为list元素 [1, 1, 2, 3, 5, 8, 13, 21]
a=(1,1,2,3,5,8,13,21); a= list(a); print(a)
## str,list => tuple
a = tuple(); print(a)
a='1a2b3c'; a = tuple(a); print(a); # ('1', 'a', '2', 'b', '3', 'c')
a=[1,'abc',['x','y']]; a = tuple(a); print(a); # (1, 'abc', ['x','y'])
## tuple,list => str 直接加“”
a = str();print(a)
a= ['1', 'a', 2]; a = str(a); print(a); # 经过str(a) a = "[['1', 'a', 2]]" , 打印后不带""
a= [1,'abc',['x','y']]; a = str(a); print(a); # 同上 "[1, 'abc', ['x', 'y']]"
### len : str - 字符的个数; tuple,list -> 元素的个数
st = 'a2 c2m'; print(len(st)) # 6
tp = (1,'abc',['x','y']); print(len(tp)) # 3
ls = [1,'abc',['x','y']]; print(len(ls)) # 3
### max/min : 返回字符asic最大/小的值 (要求list和tuple中的元素类型相同)
print(max( 'x2 skc az8' )) # 'z'
print(max(['as','cx','xz'])) # 'xz' 元素是字符串,字符串比较最大
print(max( (1,42,123) )) # 123
print(min([2,4,-20,3,23,-9])) # -20
print(min(('as','cx','xz'))) # 'as'
### sum : 求和(序列元素只能是数值),可选参数附加
print(sum([2,4,-20,3,23,-9])) # 3
print(sum((2,4,-20,3,23,-9),8)) # 3+8 =11
### sorted: 排序(默认升序)
numbers = [21,-8,12,6,3,4,9,45]
print(sorted(numbers)); # 同 numbers.sort()
### reversed: 返回结果的迭代器,再用list构造
numbers = [21,-8,12,6,3,4,9,45]
print(list(reversed(numbers))); # 同 numbers.reverse()]
print(list(enumerate(numbers))); # 枚举,结果是list,元素是tuple,
### zip
a=[1,2,3,4,5,6,7,8];b=[4,5,6,7,8];
zip(a,b) # 打包 [(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
x,y = zip(*zip(a,b)) ; # 解包 x=[1,2,3,4,5],y=[4,5,6,7,8]
| false |
5b3ae06bb5ab6d7fbedf32e70113462324728453 | lilsweetcaligula/sandbox-online-judges | /leetcode/easy/number_of_segments_in_a_string/py/solution.py | 528 | 4.125 | 4 | #
# In order to count the number of segments in a string, defined as
# a contiguous sequence of non-space characters, we can use the
# str.split function:
# https://docs.python.org/3/library/stdtypes.html#str.split
#
# Given no parameters, the string is split on consecutive runs of
# whitespace and produce a list of segments. We simply return
# the length of the list.
#
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
| true |
80e5adbdcb0cf56f35ea9676103e5dad73771473 | lilsweetcaligula/sandbox-online-judges | /leetcode/easy/move_zeroes/py/solution.py | 1,633 | 4.125 | 4 | #
# We use a slow/fast pointer technique. The fast pointer (index) is running ahead,
# reporting whether the value it is pointing to is a zero value or not.
#
# If nums[fast] is not a zero value, we copy the value to nums[slow] and increment
# the slow pointer. This way, by the time the fast pointer reaches the end of the
# array we will have all non-zero values maintaining their initial order to the left
# of the slow pointer.
#
# At this point, some non-zero values to the right of the slow pointer that have
# been priorly copied, can linger. We must walk the slow pointer to the end of the
# array and overwrite all values with 0.
#
# The whole approach can be reminiscent of the Lomuto partitioning algorithm:
# https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
#
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = 0
fast = 0
while fast < len(nums):
# If nums[fast] is not 0, copy the value to nums[slow]
# and move the fast index a step further.
if nums[fast] != 0:
nums[slow] = nums[fast]
slow += 1
fast += 1
# All non-zero values have been placed to the left of the slow
# index now at this point. Fill the remainder of the array with
# zeros to overwrite whatever values could linger.
while slow < len(nums):
nums[slow] = 0
slow += 1
| true |
4733063008b4fc20e5876d956ed4f79c8519992a | LuAzamor/exerciciosempython | /crescente.py | 219 | 4.15625 | 4 | num1= int (input ("primeiro número: "))
num2= int (input ("segundo número: "))
num3= int (input ("terceiro número: "))
if num1 < num2 < num3:
print ("crescente")
else:
print ("não está em ordem crescente") | false |
155e3da4e2113cb57fa186f3f887ab42c3fe40d0 | marcoslorhanbs/PharmView | /DataBaser.py | 835 | 4.125 | 4 | import sqlite3
# conectando...
conn = sqlite3.connect('Data/Remedios.db')
# definindo um cursor
cursor = conn.cursor()
# criando a tabela (schema)
cursor.execute("""
CREATE TABLE IF NOT EXISTS Remedios (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
Nome TEXT NOT NULL,
Preco TEXT NOT NULL,
Categoria TEXT,
QuantidadeRemedio TEXT NOT NULL,
Horario TEXT NOT NULL,
QuantidadeUso TEXT NOT NULL,
Receita TEXT NOT NULL,
Validade TEXT NOT NULL
);
""")
print('Tabela criada com sucesso.')
# desconectando...
'''
# inserindo dados na tabela
cursor.execute("""
INSERT INTO Remedios (nome, preco)
VALUES ('Dipirona', '2,50')
""")
# gravando no bd
conn.commit()
print('Dados inseridos com sucesso.')
'''
| false |
f93a0e365415b56b37ddc49187da509706235061 | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Trees/Root_to_leaf_paths_binary_tree.py | 1,489 | 4.40625 | 4 | #1. Idea here is we want to return a list of strings which contains all of the root to leaf paths in the binary tree.
#2. So initialize a list (path_list) then we are going to make a recursive call function. In the function we will pass the root of the binary tree and a empty string which we will modify and add node values as we recurse.
#3. If the root is NOT none, we want to add that node value to our string, this will always begin from the ROOT of the binary tree. This will build our string of paths.
#4. Once we come accross a leaf our second condition will be met thus we know that if we hit a leaf we have reached the END of the path, so we have our root to leaf path, hence we should add that path to our path_list, not path_list will be global for inner function.
#5. Otherwise if we are not at a leaf, we still want to build our list and add the node value BUT we want to keep recursing down the tree until we hit the leaves, so we simply recurse left and right respectivley.
#6. Rememeber to pass the path + -> as this will build the string according to the desired output. Done!
def binaryTreePaths(self, root):
path_list = []
def recurse(root, path):
if root:
path += str(root.val)
if not root.left and not root.right:
path_list.append(path)
else:
recurse(root.left, path + "->")
recurse(root.right, path + "->")
recurse(root, "")
return path_list | true |
4c4b94ca6467f49e4d8309393d0b64723a85c59c | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Trees/Max_path_sum_in_binary_tree.py | 2,107 | 4.4375 | 4 | #1. Firstly, understand what the question wants. It wants the MAX PATH. Recall a path is a sequence or iteration of nodes in a binary tree where there are no cycles.
#2. Now, I want you to approach the recursion this way - "What work do I want to do at EACH node?" Well at each node we want to find the value of its left and right subtrees and take the MAX between those to subtrees as this SPECIFIC nodes path.
#3. No this is seen by our calls to left_subtree and right subtree, think of it as EACH node in the binary tree saying "hey I want the value of MY left subtree and MY right subtrees. If there negative, well I don't want em! Else I will gladly take em!".
#4. Then after we have found the MAX values of the node which we are currently looking at, imagine our node says this "OK, so this is MY value, and here is the value of my two children which may or may not be subtrees i don't really care, oh and they are not gonna be negative don't worry!"
#5. We then will record the max_path everytime! Think dp style.
#6. Finally we will return the current nodes MAX path! Now this is where you may mess up, Imagine this:
# 3
# \
# 5
# /
# 6
# / \
# 7 8
# * Now if your taking the max path of 5 well would you take the sum of BOTH 7 & 8 leaves? No because this is not a path! As to do so we would have a REPETITION! 6 would be repeated and we know that we cannot repeat any nodes in a path!
# * This is the reason WHY we have to take the maximum value between the left and right subtrees otherwise we get repetition and we DON'T have a valid path!
def maxPathSum(self, root: TreeNode) -> int:
max_path = root.val
def findMaxPath(root):
nonlocal max_path
if not root: return 0
left_subtree = max(findMaxPath(root.left), 0)
right_subtree = max(findMaxPath(root.right), 0)
max_path = max(max_path, root.val + left_subtree + right_subtree)
return root.val + max(left_subtree, right_subtree)
findMaxPath(root)
return max_path | true |
e864f950f6954159af078f6592af6e7d894202ad | violazhu/hello-world | /closure.py | 1,769 | 4.15625 | 4 | """ 实现计数器统计函数调用次数 """
# def createCounter():
# """ 方法1:list的原理类似C语言的数组和指针,不受作用域影响
# 直接改变值对应的地址。也就是说不是改变值的引用,而是永久改变值本身 """
# L=0
# def counter():
# L=+1
# return L
# return counter
def createCounter1():
""" 方法1:list的原理类似C语言的数组和指针,不受作用域影响
直接改变值对应的地址。也就是说不是改变值的引用,而是永久改变值本身 """
L=[0]
def counter():
print(L)
print(L[0])
L[0]+=1
return L[0]
return counter
def createCounter2():
""" 方法2:使用global扩大变量作用域 """
global n
n=0
def counter():
global n
n+=1
return n
return counter
def createCounter3():
""" 方法3:使用nonlocal声明内层函数变量,使其能修改外层函数的变量 """
n=0
def counter():
nonlocal n
n+=1
return n
return counter
def createCounter4():
""" 方法4:使用生成器在外层函数创建生成器对象,在内层函数调用next() """
def count_generator():
n=0
while True:
n+=1
yield n
# 调用生成器函数创建生成器对象一定要在外层函数进行
temp=count_generator()
def get_num():
return next(temp)
return get_num
# 测试:
counterA = createCounter1()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter1()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!') | false |
63bdbe4ccee706b12c9632d3c9e7054497660dbe | Multiverse-Mind/MIPT-programming-practic | /lab2/Упр 9.py | 512 | 4.125 | 4 | import turtle
from math import sin, pi
def polygon(n, r):
for i in range(n):
turtle.forward(2 * r * sin(2 * pi / (2 * n)))
turtle.left(180 - (((n - 2) * 180) / n))
turtle.shape('turtle')
turtle.penup()
r = 20
turtle.forward(r)
turtle.pendown()
for n in range(3, 13):
turtle.left(180 - (((n - 2) * 180) / (n * 2)))
polygon(n, r)
turtle.right(180 - (((n - 2) * 180) / (n * 2)))
turtle.penup()
turtle.forward(10)
turtle.pendown()
r += 10 | false |
12cbb9b004d8360c72ca0e797b88094b86037cdb | ctec121-spring19/programming-assignment-2-beginnings-JLMarkus | /Prob-3/Prob-3.py | 1,055 | 4.5 | 4 | # Module 2
# Programming Assignment 2
# Prob-3.py
# Jason Markus
def example():
print("\nExample Output")
# print a blank line
print()
# create three variables and assign three values in a single statement
v1, v2, v3 = 21, 12.34, "hello"
# print the variables
print("v1:", v1)
print("v2:", v2)
print("v3:", v3)
def studentCode():
# replace <name> with your name
print("\nJason's Output")
# print a blank line
print()
# replicate the assignment statement above, but use your own variable
# names and values
x1, x2, x3 = 13, 12.34, "howdy"
# print the values of the 3 variables
print("x1:", x1)
print("x2:", x2)
print("x3:", x3)
# Get 3 values from the user and assign them to the variables defined
# above. See the page in Canvas on Simulataneous Assignment
# BONUS POINTS for using the split() method
x1, x2, x3 = input("Enter 3 values: ").split()
print()
print("x1:", x1)
print("x2:", x2)
print("x3:", x3)
example()
studentCode() | true |
db0479a9cb64020a74d3226af0b38ebbda140e66 | joyonto51/Programming_Practice | /Python/Old/Python Advance/Practise/Factorial_by_Recursion.py | 347 | 4.21875 | 4 | def factorial(number):
if number == 0:
return 1
else:
sum = number * factorial(number - 1)
return sum
number=int(input("please input your number:"))
'''
num=number-1
num1= number
for i in range(num,0,-1):
sum=num1*i
print(num1,"*",i,"=",sum)
num1=sum
'''
print(factorial(number))
| true |
90d6f45188cd37274453b2b944ad5432de3a60d5 | sunshine55/python-practice | /lab-01/solution_exercise1.py | 2,140 | 4.1875 | 4 | def quit():
print 'Thank you for choosing Python as your developing tool!'
exit()
def choose(choices=[]):
while True:
choice = raw_input('Please choose: ')
if len(choices)==0:
return choice
elif choice in choices:
return choice
else:
print 'You must choose from one of the following: ', sorted(choices)
def main():
choice = '0'
screen_data = screens[choice]
while True:
display_output = screen_data[0]
print display_output
print '========================'
choice = choose(screen_data[1].keys())
action = screen_data[1][choice]
if type(action) is str:
# action is a string (a key)
screen_data = screens[action]
else:
# Execute action
action()
# keyed by the selection path
screens = {
'0':('''
WELCOME TO SIMPLE PYTHON MANUAL 1.0
Please choose a category:
1. Data types and related operations
2. Statement and syntax
3. Modules
q: Exit
''',{ '1':'2-1',
'2':'2-2',
'3':'2-3',
'q':quit
}),
'2-1':('''
1. Data types and related operations:
Which data type would you like to know more about?
a.String b.Int c.Float d.Complex e.Bool
f.FronzenSet g.Tuple h.Bytes
i.Bytearray i.List j.Set k.Dict l.Object
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit,
'a':'2-1-a',
'b':'2-1-b'
}),
'2-2':('''
2. Statement and syntax
Which syntax would you like to know more about?
a.Assignment b.Conditional c.Loops
d.Function e.Class f.Method
g.Exception
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit,
'a':'2-1-a',
'b':'2-1-b'
}),
'2-3':('''
3. Modules
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit
}),
'2-1-a':('''
Data types and related operations:
String:
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
2:BACK TO "Data types and related operations"
q: Exit
''',{ '1':'0',
'2':'2-1',
'q':quit
}),
'2-1-b':('''
Data types and related operations:
Int:
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
2:BACK TO "Data types and related operations"
q: Exit
''',{ '1':'0',
'2':'2-1',
'q':quit
})
}
if __name__ == '__main__':
main()
| true |
671443c555f412d1c03018de29760dbf5bb67f82 | nicap84/mini-games | /Guess the number/Guess the number.py | 2,218 | 4.125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#import simplegui
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# initialize global variables used in your code
num_range=100
aleatorio=0
inp_number=0
count=7
# helper function to start and restart the game
def new_game():
global aleatorio
aleatorio=random.randrange(0,num_range)
# define event handlers for control panel
def range100():
global num_range
num_range=100
global count
count=7
new_game()
print "New game. Range is from 0 to " +str (num_range)
print "Number if remaining guesses is " + str(count)
print ""
def range1000():
global num_range
num_range=1000
global count
count=10
new_game()
print "New game. Range is from 0 to 1000"
print "Number if remaining guesses is " + str(count)
print ""
def input_guess(guess):
global inp_number
inp_number=int(guess)
global count
count=count-1
print "Guess was " + str(inp_number)
print "Number of remaining guesses is " + str(count)
if count>0:
if inp_number < aleatorio:
print "Higher!"
print ""
elif inp_number >aleatorio:
print "Lower!"
print ""
elif inp_number == aleatorio:
print "Correct!"
print ""
if num_range==100:
range100()
else:
range1000()
elif count<=0:
print "You ran out of guesses. The number was " + str(aleatorio)
print ""
if num_range==100:
range100()
else:
range1000()
# create frame
frame=simplegui.create_frame ("Guess the number",200,200)
# register event handlers for control elements
frame.add_button ("Range is [0,100)", range100, 200)
frame.add_button ("Range is [0,1000)",range1000, 200)
frame.add_input ("Enter a guess", input_guess, 200)
range100()
frame.start()
# always remember to check your completed program against the grading rubric | true |
1df218be5a5e105a13eed8c63f469f4acddda353 | AnthonySimmons/EulerProject | /ProjectEuler/ProjectEuler/Problems/Problem20.py | 607 | 4.15625 | 4 |
#n! means n (n ? 1) ... 3 2 1
#For example, 10! = 10 9 ... 3 2 1 = 3628800,
#and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#Find the sum of the digits in the number 100!
def Factorial(num):
fact = num
for i in reversed(range(1, num)):
fact *= i
return fact
def SumOfDigits(num):
sum = 0
numStr = str(num)
for c in numStr:
sum += int(c)
return sum
def Solve():
num = 100
fact = Factorial(num)
sum = SumOfDigits(fact)
print("Factorial: {}, Sum: {}".format(fact, sum))
return sum | false |
f99b9d736330ed66277e98311ccfb3a07b984f9e | Louis95/oop-in-python | /Exception/OnlyEven.py | 595 | 4.125 | 4 | '''
While this class is effective for demonstrating exceptions in action, it isn't very good at its job.
It is still possible to get other values into the list using index notation or slice notation.
This can all be avoided by overriding other appropriate methods, some of which are double-underscore methods.
'''
class OnlyEven(list):
def append(self, integer):
if not isinstance(integer, int):
raise TypeError("Only integers can be added")
if integer % 2:
raise ValueError("Only even even numbers can be added")
super().append(integer)
| true |
77464bdc55273ce06381c5005b445a5e4c34f2a2 | jorgegarcia1996/EjerciciosPython | /Ejercicios Diccionarios/Ejercicio4.py | 700 | 4.15625 | 4 | # Suponga un diccionario que contiene como clave el nombre de una persona
# y como valor una lista con todas sus “gustos”.
# Desarrolle un programa que agregue “gustos” a la persona:
# Si la persona no existe la agregue al diccionario con una lista que contiene un solo elemento.
# Si la persona existe y el gusto existe en su lista, no tiene ningún efecto.
# Si la persona existe y el gusto no existe en su lista, agrega el gusto a la lista.
gustos={}
nombre = input("Nombre:")
while nombre!="*":
gusto=input("Gusto:")
lista_gustos=gustos.setdefault(nombre,gusto)
if lista_gustos!=gusto:
gustos[nombre].append(gusto)
nombre = input("Nombre:")
print(gustos) | false |
8a81a67dad68f690099e1e4f435c44a990b96ed4 | khadeejaB/Week10D2A2 | /questionfile.py | 749 | 4.3125 | 4 | #In this challenge, a farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three species:
chicken = 2
cow = 4
dog = 4
#The farmer has counted his animals and he gives you a subtotal for each species. You have to implement a script or function that returns the total number of legs of all the animals.
def animals(chicken_leg, cow_leg, dog_leg):
leg1 = chicken*chicken_leg
leg2 = cow * cow_leg
leg3 = dog * dog_leg
all_legs = leg1 + leg2 + leg3
return all_legs
#Example 1
print(animals(2, 3, 5))
#Example 2
#input(1, 2, 3) ➞ 22
#Example 3
#How many Chickens? 5
#How many Cows? 2
#How many Dogs? 8
#50 legs
#Create a python script to solve this problem.
| true |
359824127dd9b48c34a2df72f7f21fd85077d9ff | Armin-Tourajmehr/Learn-Python | /Number/Fibonacci_sequence.py | 950 | 4.28125 | 4 | # Enter a number and have the program generate
# The Fibonacci sequence number or the nth number
def Fibonacci_sequence(n):
'''
Return Fibonacci
:param n using for digit that user want to calculator Fibonacci:
:return sequence number as Fibonacci :
'''
# Initialization number
a = 1
b = 1
for i in range(n):
a, b = b, b + a
yield b
def ValidInput(n):
'''
Return True or False
:param n: Get number
:return: True if number will be correct or versa vise
'''
try:
number = int(n)
except ValueError:
print('Enter an integer')
else:
print('Wait.....')
return True
if __name__ == '__main__':
while True:
user = input('Please Enter a number: ')
if ValidInput(user):
n = int(user)
for i in Fibonacci_sequence(n):
print(i)
break
else:
continue
| true |
7d6df544ae614235cd5c0238cbfaaaaca8350e6b | Armin-Tourajmehr/Learn-Python | /Number/Get_pi.py | 864 | 4.21875 | 4 |
# Getting pi number
# Use Nilakantha formula
from time import sleep
# Calculate Pi Number
def calc_pi(num):
Pi = 3
op = 1
for n in range(num):
if n % 2 == 0 and n > 1:
yield Pi
Pi += 4 / ((n) * (n + 1) * (n + 2) * op)
op *= -1
def valid_number():
while True:
num = input('Enter a number for calculating Pi:\nHow many? ')
try:
number = int(num)
if number > 100:
print('Wait!!!!')
return number
else:
print('Please choose number more than 100')
continue
except ValueError:
print('Non negative number,Please try again!')
if __name__ == '__main__':
number = valid_number()
sleep(2)
PI = None
for i in calc_pi(number):
PI = i
print(PI)
| false |
c64ac69d915f54109e959d046f6317348650a460 | evan-nowak/other | /generic/date_range.py | 2,881 | 4.53125 | 5 | #!/usr/bin/env python
"""
#########################
Date Range
#########################
:Description:
Generates a date range based on starting/ending dates and/or number of days
:Usage:
Called from other scripts
:Notes:
The function needs exactly two of the three arguments to work
When providing the start and end dates, both will be in the resulting list
"""
def date_range(start=None, end=None, day_count=None):
"""
:Description:
Generates a date range
Generates a date range using two of the following: starting date, ending date, day count
:Params:
start: The starting date
type: str
format: YYYY-MM-DD
default: None
end: The ending date
type: str
format: YYYY-MM-DD
default: None
day_count: The number of days in the range
type: int
default: None
returns: Range of dates in ascending order
type: list
:Dependencies:
Python3
:Notes:
The function needs exactly two of the arguments to work
:Example:
date_range(start='2018-01-01', end='2018-02-01')
"""
from datetime import datetime, timedelta
# If start is provided, validate format
if start is not None:
try:
start = datetime.strptime(start, '%Y-%m-%d')
except Exception:
raise Exception('Please provide dates in the following format: YYYY-MM-DD')
# If end is provided, validate format
if end is not None:
try:
end = datetime.strptime(end, '%Y-%m-%d')
except Exception:
raise Exception('Please provide dates in the following format: YYYY-MM-DD')
# If day_count is provided, validate format
if day_count is not None:
try:
day_count = int(day_count)
except Exception:
raise Exception('Day count must be a number')
# Create date range using start/end dates
if (start is not None) and (end is not None) and (day_count is None):
dates = [datetime.strftime(start + timedelta(days=n), '%Y-%m-%d') for n in range(int((end - start).days) + 1)]
# Create date range using start date and day count
elif (start is not None) and (day_count is not None) and (end is None):
dates = [datetime.strftime(start + timedelta(days=n), '%Y-%m-%d') for n in range(day_count)]
# Create date range using end date and day count
elif (end is not None) and (day_count is not None) and (start is None):
dates = [datetime.strftime(end - timedelta(days=n), '%Y-%m-%d') for n in range(day_count)][::-1]
else:
raise Exception('Please provide exactly 2 arguments')
print('{0} - {1}'.format(dates[0], dates[-1]))
return dates
if __name__ == '__main__':
print(__doc__)
| true |
0a5f2461b362405b244867ba8a8b44c21a363e51 | ferdiansahgg/Python-Exercise | /workingwithstring.py | 493 | 4.34375 | 4 | print("Ferdi\nMIlla")
print("Ferdi\"MIlla")
phrase = "Ferdiansah and MilleniaSaharani"
print(phrase.upper().isupper())#checking phrase is uppercase or not, by functioning first to upper and check by function isupper
print(len(phrase))#counting the word
print(phrase[0])#indexing the character
print(phrase.index("F"))#phasing the parameter
print(phrase.replace("Ferdiansah","FerdiGanteng"))#Replace the character, first that i wanna to replace by comma(,) and you put in that you wanna replace | true |
d17d862ebd5e5f3705a868607c7c255fe4b44dce | yaseen-ops/python-practice2 | /13while_loop.py | 276 | 4.1875 | 4 | i = 1
while i <= 5:
print(i)
# i = i + 1
# OR
i += 1
print("Done with Loop")
print("---------------------------------")
i = 1
while i <= 5:
print(i)
if i == 4:
print("Loop gonna end")
# i = i + 1
# OR
i += 1
print("Done with Loop")
| false |
53255ace53f8e0265529c46a5bcacee089a7d404 | Patrick-Ali/PythonLearning | /Feet-Meters.py | 381 | 4.15625 | 4 | meterInches = 0.3/12
meterFoot = 0.3
footString = input("enter feet: ")
footInt = int(footString)
inchString = input("enter inches: ")
inchInt = int(inchString)
footHeightMeters = meterFoot*footInt
inchHeightMeters = meterInches*inchInt
heightMeters = round(footHeightMeters + inchHeightMeters, 2)
print("You are about: " + str(heightMeters) + " meters tall.")
| true |
21bd8642f4b1c392d4dc764373f03a4347a73fe7 | OsProgramadores/op-desafios | /desafio-04/Nilsonsantos-s/python/xadrez.py | 2,240 | 4.125 | 4 | """
Autor: Nilsonsantos-s
Propósito: Desafio 4
"""
def verifica_string(numero):
"""
:param numero: Exclui qualquer número que não se encaixe
no padrão correto.
:return: retorna um número no padrão.
"""
contador_de_erros = 0
dicionario = {1: numero.isnumeric(), 2: len(numero) == 8,
3: '7' not in numero and '8' not in numero and '9' not in numero}
if False in dicionario.values():
while False in dicionario.values():
contador_de_erros += 1
avisodado = False
if contador_de_erros % 3 == 0:
avisodado = True
aviso()
if not dicionario[3]:
if avisodado is False:
print('*Só pode haver dígito menor que 7')
numero = input(f'Linha {contador}- ')
elif not dicionario[1]:
if avisodado is False:
print('*Somente números são aceitos')
numero = input(f'Linha {contador}- ')
elif not dicionario[2]:
if avisodado is False:
print('*As linhas precisam ter 8 dígitos')
numero = input(f'Linha {contador}- ')
dicionario[1] = numero.isnumeric()
dicionario[2] = len(numero) == 8
dicionario[3] = '7' not in numero and '8' not in numero\
and '9' not in numero
return numero
def aviso():
"""
Um aviso sobre o que deve ser preenchido nas linhas.
"""
print('ATENÇÃO:\n-As linhas precisam ter 8 dígitos')
print('-Só pode haver dígito menor que 7')
print('-Somente números são aceitos')
aviso()
lista = []
for contador in range(1, 9):
for string in [input(f'Linha {contador}- ')]:
string = string.replace(' ', '')
lista.append(verifica_string(string))
fragmento = []
for numeros in lista:
fragmento += numeros
pecas = {'Peão': fragmento.count('1'), 'Bispo': fragmento.count('2'),
'Cavalo': fragmento.count('3'), 'Torre': fragmento.count('4'),
'Rainha': fragmento.count('5'), 'Rei': fragmento.count('6')}
for key, value in pecas.items():
print(f'{key}: {value} peça(s)')
| false |
96bd7cf3b01c88c7faa2c6eeaaa0fb469c6d4eb5 | OsProgramadores/op-desafios | /desafio-03/edipocba/python/desafio-03.py | 844 | 4.1875 | 4 | """Algoritmo para identificação de números
palíndromos em um intervalo de valores digitados pelo usuário."""
def palindromo(vi, vf):
"""Função que identifica quais números são
palíndomos em um intervalor de valores."""
for numero in range(vi, vf+1):
aux = str(numero)
if aux == aux[::-1]:
print("{}".format(aux))
valorInicial = 1
valorFinal = 0
while(valorInicial > valorFinal or valorFinal < 0 or valorInicial < 0):
valorInicial = int(input("digite um número inicial: "))
valorFinal = int(input("digite um número final: "))
if valorInicial > valorFinal:
print("POR FAVOR, DIGITE UM NÚMERO INICIAL MENOR QUE O NÚMERO FINAL.")
elif valorInicial < 0 or valorFinal < 0:
print("POR FAVOR, NÃO DIGITE NÚMEROS NEGATIVOS")
palindromo(valorInicial, valorFinal)
| false |
95b1186e9ed087445b4bf5346b5c6eee221df1b4 | OsProgramadores/op-desafios | /desafio-02/bessavagner/python/desafio02_osprimos.py | 1,836 | 4.25 | 4 | """Desafio 02 de https://osprogramadores.com/desafios
Escreva um programa para listar todos os números primos
entre 1 e 10000, na linguagem de sua preferência.
"""
import argparse
def seive_eratosthenes(num) :
"""Uses the seiv of Eratosthenes to map primes.
The returned list is a mask of True/False values,
with True elements indexes corresponding
to prime numbers.
Check https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Args:
num (int): Maximum numbers to look for primes
Returns:
list: maks of prime numbers
"""
mask = [True for dumb in range(num + 1)]
mask[0], mask[1] = False, False
for i in range(2, int(num**0.5) + 1):
for j in range(2*i, num + 1, i):
mask[j] = False
return mask
def primes_generator(num, seive=seive_eratosthenes):
"""Generator of prime numbers.
Args:
num (int): Maximum numbers to look for primes of
seive (callable, optional):
a sieve to generate a mask map of primes.
It must return a list of True/False values,
where True indexes corresponds to a prime.
Defaults to seive_eratosthenes.
Yields:
int: prime number
"""
mask = seive(num)
for index, elem in enumerate(mask):
if elem:
yield index
def main():
"""Main module's function. Shows primes from 2 up to N.
"""
description = "List N primes starting from 2."
parser = argparse.ArgumentParser(description=description)
parser.add_argument('number', metavar='N', nargs=1, type=int,
help='integer up to wich primes will be listed')
arg = parser.parse_args()
primes = [str(prime) for prime in primes_generator(arg.number[0])]
print(' '.join(primes))
if __name__ == '__main__':
main()
| false |
a092e63cdfed3394aae4902d689b13140d1e42b9 | sarahsweeney5219/Python-Projects | /dateDetectionRegex.py | 1,663 | 4.75 | 5 | #date detection regex
#uses regular expression to detect dates in the DD/MM/YYYY format (numbers must be in min-max range)
#then tests to see if it is a valid date (based on number of days in each month)
import re, calendar
#creating the DD/MM/YYYY regex
dateRegex = re.compile('(3[01]|[12][0-9]|0?[1-9])\/(0?[1-9]|1[012])\/([12][0-9][0-9][0-9])')
#asking user to input text
print('Please enter either a single date, a series of dates, or a body of text with dates contained in it.')
text = input()
matches = []
for groups in dateRegex.findall(text):
date = '/'.join([groups[0], groups[1], groups[2]])
matches.append(date)
print(matches)
if len(matches) > 0:
print('These are the DD/MM/YYYY formatted dates in your input:')
for match in matches:
print(match)
print('We will now proceed to see if they are valid days (according to the number of days in a month')
validDates = []
for match in matches:
if match[3:5] in ['05', '06', '09', '11']:
if int(match[0:2]) <= 30:
validDates.append(match)
elif match[3:5] == '02':
#check to see if leap year
if calendar.isleap(int(match[6:10])) == True:
if int(match[0:2]) <= 29:
validDates.append(match)
else:
if int(match[0:2]) <= 28:
validDates.append(match)
else:
if int(match[0:2]) <= 31:
validDates.append(match)
print("Of your inputted dates, the following are valid:")
for validDate in validDates:
print(validDate)
else:
print('There were no dates in your input.')
| true |
0c468539c35d7cb5043d109dc2955c9d7c71112c | dheidenr/ipavlov_course | /coursera/DS/tutor.py | 1,653 | 4.21875 | 4 |
# Так было бы в 2-й версии python: print 'Hello'
print('Hello')
# Во втором python необходимо самостоятельно привести одно из пременных деления к float
# в третьем автоматически при делении получается тип float
print(10/2)
ll = []
ll.append(1)
print(ll)
ll.insert(0, 3)
print(ll)
ll.pop()
print(ll.pop())
print('Hello, world!'.replace(' ', '_'))
for i in range(10):
print(i, ) # Во втором питоне можно написать "print 1," - это выведет через пробел не с переносом строки
w = (x for x in range(10)) # Создали генератор
print(type(w))
# my generator
def downist(num):
w = 10
print(w)
while num > 0:
yield num
num -= 1
gena = downist(5)
# num = next(gena)
# num = next(gena)
# num = next(gena)
l = [4]
for _ in gena:
print('downist num:', _)
pass
# hash(l)
l = []
object_tuple = (l, l)
l.append(666)
# object_set = {(l, l), ('test tuple',), 2}
l.append('asdf')
# print(object_tuple)
def printer(**kwargs):
# print(kwargs)
for key, value in kwargs.items():
# print('{}:{}'.format(key, value))
print(f'{key} : {value}')
d = dict({
'hi': 666
})
printer(a=10, b=120)
printer(**d)
def foo(*args, **kwargs): pass
l = [1, 2, 3]
def int_to_str_list(numbers):
return list(map(str, numbers))
# def squarify(a):
# return a ** 2
#
# print(list(map(squarify(), range(5))))
print(int_to_str_list(l))
kartej = (1, 'asdf', 3)
print(', '.join({}.get('2'))) | false |
e3f79676946c1033ea1fe9d58bfbd310ff011a69 | mashd3v/inteligencia_artificial | /Inteligencia Artificial y Machine Learning/Python/Básico/013 - Tuplas.py | 976 | 4.65625 | 5 | # Tuplas
'''
En Python, una tupla es un conjunto ordenado e inmutable de elementos del mismo o diferente tipo.
Las tuplas se representan escribiendo los elementos entre paréntesis y separados por comas. Una tupla puede no contener ningún elemento, es decir, ser una tupla vacía.
Funciones que aplican a tuplas:
- len
- max
- min
- sum
- any
- all
- sorted
Métodos que aplican a tuplas:
- index
- count
'''
# Definiendo tuplas
tupla_1 = (11, 2, 30, 4, 52, 6, 70, 8, 9, 100)
print(f'Longitud de la tupla: {len(tupla_1)}')
print(f'Maximo de la tupla: {max(tupla_1)}')
print(f'Minimo de la tupla: {min(tupla_1)}')
print(f'Suma de los valores de la tupla: {sum(tupla_1)}')
print(f'Tupla ordenada: {sorted(tupla_1)}')
# La diferencia del recorrido de una lista y una tupla, es que la tupla sera mas rapido
print('\nRecorrido de una tupla')
for elemento in tupla_1:
print(elemento)
| false |
668ad30aa1f83949b47022cfab2e8f92a3938af3 | dishant888/Python-Basics | /questions/FarToCel.py | 214 | 4.15625 | 4 | #Convert Fahrenheit to Celcius
#F to C
f = float(input('Enter Fahrenheit: '))
print('%.2f'%eval('(f-32)*5/9'),' Celcius')
#C to F
c = float(input('Enter Celcius: '))
print('%.2f'%eval('(c*9/5)+32'),' Fahrenheit') | false |
76330f9dfd49d09599509e9909d2ef0715eeb9c3 | JeffreybVilla/100DaysOfPython | /Beginner Day 13 Debugging/debugged.py | 1,709 | 4.1875 | 4 | ############DEBUGGING#####################
# # Describe Problem
# def my_function():
# """
# Range function range(a, b) does not include b.
# 1. What is the for loop doing?
# The for loop is iterating over a range of numbers.
#
# 2. When is the function meant to print 'You got it'?
# If i is 20, then we print 'You got it'.
#
# 3 What are your assumptions about i?
# i is an arbitrary letter to keep track of iterations.
# i is initially = to 1, then 2, 3, etc.
# When i is 20. We print.
# """
# for i in range(1, 20 + 1):
# if i == 20:
# print("You got it")
# my_function()
# # Reproduce the Bug
# from random import randint
# dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
# dice_num = randint(0, 5)
# #The sixth number is causing the error.
# #Setting it to 6 will reproduce the error.
# #dice_num = 6
# print(dice_imgs[dice_num])
# # Play Computer
# year = int(input("What's your year of birth? "))
# if year > 1980 and year < 1994:
# print("\nYou are a millenial.")
# elif year >= 1994:
# print("\nYou are a Gen Z.")
# # Fix the Errors
# age = int(input("How old are you? "))
# if age > 18:
# print(f"You can drive at age {age}.")
# #Print is Your Friend
# pages = 0
# word_per_page = 0
# pages = int(input("Number of pages: "))
# #print(pages)
# word_per_page = int(input("Number of words per page: "))
# #print(word_per_page)
# total_words = pages * word_per_page
# print(total_words)
#Use a Debugger
#appending part wasnt in for loop
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item)
print(b_list)
mutate([1,2,3,5,8,13])
| true |
c0b096fa60b91b859fac13c0bf6a804116140dfc | hlainghpone2003/SFU-Python | /Sets.py | 2,214 | 4.15625 | 4 | #Sets
includes a data type for sets.
Curly braces or the set() fuction can be used to create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) #show that duplicates have been removed
'orange' in basket # fast member testing
'crabgrass' in basket
Demonstrate set operation on unique letter form two words
a = set('abracadabra')
b = set('alacazam')
a #unique letter in a
a - b #letter in a but not in b
a | b #letter in a or b or both
a & b #letter in both a and b
a ^ b #letter in a or b but not both
>>> a - b
{'r', 'b', 'd'}
>>> a | b
{'l', 'd', 'm', 'a', 'c', 'r', 'b', 'z'}
>>> a & b
{'c', 'a'}
>>> a ^ b
{'l', 'd', 'm', 'b', 'r', 'z'}
x = set('23802348')
y = set('57839012')
>>> x - y
{'4'}
>>> y - x
{'5', '1', '7', '9'}
>>> x | y
{'1', '3', '9', '0', '8', '7', '4', '5', '2'}
>>> x & y
{'8', '2', '3', '0'}
>>> x ^ y
{'1', '9', '7', '4', '5'}
fruits = {"apple", "banana", "cherry", "orange", "kiwi", "lemon", "mango"}
print("cherry" in fruits)
a = {x for x in 'abracadabra' if x not in 'abc'}
a
---------
>>>Dictionaries
#Dictionaries
#Another useful data type built into Python is the dictionaries
tel = {'jack' : 4098, 'sape':4139}
tel['sape']
tel['guide'] = 4127
list(tel) #change
sorted(student) #Alphabet sorting
'MgOo' in student
'MaMa' not in student
dict([('sape', 4139), ('guide',4127), ('jack',4098)])
dict(sape=4139, guide= 4127, jack= 4098)
{x: x**2 for x in (2,4,6)}
{2: 4, 4: 16, 6: 36}
>>> for x in 2, 4, 6:
... print(x,x**2)
...
2 4
4 16
6 36
>>> for x in 2, 4, 6:
... print(x,':',x**2)
...
2 : 4
4 : 16
6 : 36
{x: x**3 for x in (10, 20, 30, 40, 50) }
{10: 1000, 20: 8000, 30: 27000, 40: 64000, 50: 125000}
-----------
When looping through dictionaries
>>> knights = {'gallahad': 'the pure', 'robin':'brave', 'sape': 4355}
>>> for k, v in knights.items():
... print(k,v)
...
gallahad the pure
robin brave
>>> for k, v in knights.items():
... print(k,v)
...
gallahad the pure
robin brave
sape 4355
>>> for x, y in enumerate(['tic','tac', 'toe']):
... print(x, y)
...
0 tic
1 tac
2 toe | true |
2be5ff41a0dd3029786f149dd7674ead6a9f07f1 | titojlmm/python3 | /Chapter2_Repetition/2_01_RockPaperScissors.py | 1,346 | 4.25 | 4 | import random
# This program plays the game known as Rock-Paper-Scissors.
# Programmed by J. Parker Jan-2017
print("Rock-Paper_Scissors is a simple guessing game.")
print("The computer will prompt you for your choice, ")
print("which must be one of 'rock', 'paper', or 'scissors'")
print("When you select a choice the computer will too (it ")
print("will not cheat) and the winner is selected by three ")
print("simple rules: rock beats scissors, paper beats ")
print("rock, and scissors beat paper. If a tie happens")
print("then you should play again.")
# Computer selection
i = random.randint(1, 3)
if i == 1:
choice = "rock"
elif i == 2:
choice = "paper"
else:
choice = "scissors"
print("Rock-paper-scissors: type in your choice: ")
player = input()
if player == choice:
print("Game is a tie. Please try again.")
else:
if player == "rock":
if choice == "scissors":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
elif player == "paper":
if choice == "rock":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
elif player == "scissors":
if choice == "paper":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
else:
print("Option ", player, " is not valid. Please choose among rock, paper or scissors")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.