blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1ee2cd36967144cbf2fc7bceac39970507ced833 | yangwenbinGit/python_programe | /python_07/class_property.py | 1,074 | 4.46875 | 4 | # 实例属性和类属性
# 由于Python是动态语言,根据类创建的实例可以任意绑定属性。给实例绑定属性的方法是通过实例变量,或者通过self变量
class Student(object):
def __init__(self,name):
# 实例属性
self.name = name
# 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有
# 类属性
age = 30
name ='Yangwen bin'
s = Student('Bob')
print(s.name)
print(s.age)
print(Student.age)
s.name = 'Michael'
print(s.name)
del s.name
# print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
del Student.age
# print(Student.age) 删除了之后再调用就报错了
print(Student.name)
# 从上面的例子可以看出,在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性 | false |
e11ca1c34731399a6432b19bf89606110df4e3ab | yangwenbinGit/python_programe | /python_08/create_class_on_the_fly.py | 1,025 | 4.3125 | 4 | class Hello(object):
def hello(self,name='world'):
self.name = name
print('Hello,%s!!'%self.name)
h =Hello()
h.hello()
print(type(Hello)) # <class 'type'> Hello是一个class,它的类型就是type
print(type(h)) # <class '__main__.Hello'> 而h是一个实例,它的类型就是class Hello
# type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义
def fn(self,name='world'):
print('Hello,%s!!'%name)
Hello1 =type('Hello1',(object,),dict(hello=fn)) # # 创建Hello class
h1 =Hello1()
h1.hello()
print(Hello1.__name__) # 打印出类名 Hello1
# 要创建一个class对象,type()函数依次传入3个参数:
#
# class的名称;
# 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
# class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
| false |
da94819416e7a4a1d0afb66a2fba50469e51a458 | edawson42/pythonPortfolio | /listEvens.py | 277 | 4.125 | 4 | #make new list of even numbers only from given list
#
# Copyright 2018, Eric Dawson, All rights reserved.
def listEvens(list):
""" (list) -> list
Returns list of even numbers from given list
"""
evenList = [num for num in list if num % 2 == 0]
return evenList
| true |
6821026f59936fa4f20df8e9ed72f04be20105bf | KeisukeSugita/Design_Pattern | /State/nonState.py | 955 | 4.28125 | 4 | # Stateパターンを利用しない場合
# 状態によってif文で処理を分岐させる必要があるため、
# 状態の追加・削除を行いたいときはif文を書き換える必要がある
# 見通しが悪くなり、メンテナンスもしづらくなってしまう
UPPER = 'Upper'
LOWER = 'Lower'
SWAP = 'Swap'
DEFAULT = 'Default'
class TextWriter:
def __init__(self, text):
self.text = text
self.state = DEFAULT
def set_state(self, state):
self.state = state
def write(self):
if self.state is DEFAULT:
print(self.text)
elif self.state is UPPER:
print(self.text.upper())
elif self.state is LOWER:
print(self.text.lower())
elif self.state is SWAP:
print(self.text.swapcase())
text_writer = TextWriter('Writing Text')
text_writer.write()
text_writer.set_state(UPPER)
text_writer.write()
text_writer.set_state(LOWER)
text_writer.write()
text_writer.set_state(SWAP)
text_writer.write() | false |
27f36689b14dc824d0bd455fbbacf925ace550d0 | karkyra/Starting_out_with_python3 | /edabit/Last_Digit_Ultimate.py | 323 | 4.15625 | 4 | # Your job is to create a function, that takes 3 numbers: a, b, c and returns
# True if the last digit of a * b = the last digit of c. Check the examples below for an explanation.
def last_dig(a, b, c):
total = a * b
return str(total)[-1] == str(c)[-1]
print(last_dig(25, 21, 125))
print(last_dig(12, 215, 2142))
| true |
c9b0fd090d633c3dee917dd6847f79dfc91371ff | karkyra/Starting_out_with_python3 | /edabit/Find_the_Highest_Integer.py | 420 | 4.125 | 4 | # Create a function that finds the highest integer in the list using recursion.
# Please use the recursion to solve this (not the max() method).
def find_highest(lst):
# return sorted(lst)[-1]
if len(lst) == 1:
return lst[0]
else:
current = find_highest(lst[1:])
return current if current > lst[0] else lst[0]
print(find_highest([-1, 3, 5, 6, 99, 12, 2]))
print(find_highest([8]))
| true |
bc28cd89b6ee3a1faad2a948204c04010cafbc77 | karkyra/Starting_out_with_python3 | /edabit/Enharmonic_Equivalents.py | 420 | 4.125 | 4 | # Given a musical note, create a function that returns its enharmonic equivalent.
# The examples below should make this clear.
def get_equivalent(note):
d = {"Db": "C#", "Eb":"D#", "Gb":"F#", "Ab":"G#", "Bb":"A#"}
for k,v in d.items():
if note == k:
return v
elif note == v:
return k
print(get_equivalent("D#"))
print(get_equivalent("Gb"))
print(get_equivalent("Bb"))
| true |
f6bb7f7fcf292f512e9984696dc8151773259a30 | karkyra/Starting_out_with_python3 | /edabit/Buggy_Uppercase_Counting.py | 451 | 4.28125 | 4 | # In the Code tab is a function which is meant to return how many uppercase letters
# there are in a list of various words. Fix the list comprehension so that the code functions normally!
def count_uppercase(lst):
return sum([letter.isupper() for word in lst for letter in word])
print(count_uppercase(["SOLO", "hello", "Tea", "wHat"]))
print(count_uppercase(["little", "lower", "down"]))
print(count_uppercase(["EDAbit", "Educate", "Coding"]))
| true |
10052b78817f1280becd708cc2aa42a383ffc763 | karkyra/Starting_out_with_python3 | /edabit/Characters_and_ASCII_Code_Dictionary.py | 427 | 4.1875 | 4 | # Write a function that transforms a list of characters into a list of dictionaries, where:
#
# The keys are the characters themselves.
# The values are the ASCII codes of those characters.
# example to_dict(["a", "b", "c"]) ➞ [{"a": 97}, {"b": 98}, {"c": 99}]
def to_dict(lst):
return [{i: ord(i)} for i in lst]
print(to_dict(["a", "b", "c"]))
print(to_dict(["^"]) )
print(to_dict([]))
print(to_dict([" "]))
| true |
fa34f7934c15719235a12fd701d0ccac2d1284bc | karkyra/Starting_out_with_python3 | /edabit/Stupid_Addition.py | 718 | 4.375 | 4 | # Create a function that takes two parameters and, if both parameters are strings,
# add them as if they were integers or if the two parameters are integers, concatenate them.
# If the two parameters are different data types, return None.
# All parameters will either be strings or integers.
def stupid_addition(a, b):
if type(a) == int and type(b) == int:
return str(a) + str(b)
elif type(a) == str and type(b) == str:
return int(a) + int(b)
else:
return None
# if (type(a) == int and type(b) == str) or (type(a) == str and type(b) == int ):
# return None
print(stupid_addition(1, 2))
print(stupid_addition("1", "2"))
print(stupid_addition("1", 2))
| true |
846061fdcbea83a17bc21cf23cd36455acf13814 | karkyra/Starting_out_with_python3 | /edabit/International_Greetings.py | 856 | 4.375 | 4 | # Suppose you have a guest list of students and the country they are from, stored as key-value pairs in a dictionary.
# # GUEST_LIST = {
# "Randy": "Germany",
# "Karla": "France",
# "Wendy": "Japan",
# "Norman": "England",
# "Sam": "Argentina"
# }
#
# Write a function that takes in a name and returns a name tag, that should read:
#
# "Hi! I'm [name], and I'm from [country]."
#
# If the name is not in the dictionary, return:
#
# "Hi! I'm a guest."
GUEST_LIST = {
"Randy": "Germany",
"Karla": "France",
"Wendy": "Japan",
"Norman": "England",
"Sam": "Argentina"
}
def greeting(name):
for k, v in GUEST_LIST.items():
if k == name:
return "Hi! I'm {}, and I'm from {}.".format(k, v)
return "Hi! I'm a guest."
print(greeting("Randy"))
print(greeting("Sam"))
print(greeting("Monti"))
print(greeting("Wendy"))
| true |
93b9229c6f5016ba015902dc03b3ae266fc315f1 | JackCaff/WeeklyTask2-BMI- | /BMICalculation.py | 511 | 4.34375 | 4 | # Program will allow user to enter height in (CM) and weight in (KG) and calculate their BMI.
Weight = float(input("Enter your Weight in Kg: ")) #Allows user to enter Weight
Height = float(input("Enter your Height in Cm: ")) #Allows user to enter Height
Meters_squared = ((Height * Height) / 100) #Converts height entered in CM to Meters squared
BMI = (Weight / Meters_squared) * 100
new_BMI = round(BMI, 2) #Rounds BMI value too 2 decimals places
print("Your BMI is", new_BMI,) #Displays the users BMI
| true |
5604489e590bc0224b0bb9aa5db23293d9a89ea2 | umairgillani93/data-structures-algorithms | /coding_problems/sort_arr.py | 357 | 4.1875 | 4 | def sort(arr: list) -> list:
'''
Sorts the given arraay in ascending order
'''
while True:
corrected = False
for i in range(len(arr) -1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
corrected = True
if not corrected:
return arr
if __name__ == '__main__':
print(sort([10,9,8,11,2,1]))
| true |
f2378203319ab0d84940ac254ab24b7d047e0eae | schopr9/python-lone | /second_larjest.py | 519 | 4.28125 | 4 |
def second_largest(input_array):
"""
To find the largest second number in the array
"""
max_1 = input_array[0]
max_2 = input_array[1]
for i in range(1, len(input_array)):
if input_array[i] > max_1:
max_2 = max_1
max_1 = input_array[i]
elif input_array[i] > max_2 and input_array[i] != max_1:
max_2 = input_array[i]
elif max_1 == max_2:
max_2 = input_array[i]
return max_2
print second_largest([1, 3, 2, 5, 3, 3])
| true |
7410932a8f0c1b232a6cc12e393191775b6bdddb | NITHISH-DELL/my-captain-projects | /fibonacci.py | 341 | 4.34375 | 4 | #### Fibonacci numbers ####
def fibonacci(n):
print("the fibonacci numbers for",n,"numbers")
i=0
j=1
print(i)
print(j)
for x in range(n):
g=i+j
print(g)
i=j
j=g
n=int(input("enter the number to get the fibonacci value upto the n numbers"))
fibonacci(n)
| false |
d35591f10010cf1517a1243d6c0bb73ddd30a029 | AsFal/euler | /pb9.py | 719 | 4.15625 | 4 | def check_pythagorean_triplet(a,b,c):
if a*a + b*b == c*c:
return True
return False
def print_triplet(a,b,c):
print "(" + str(a) + ", " + str(b) +", " + str(c) + ")"
triplet_found = False
# because of a<b<c, the max value a can take is 332
for a in range(1, 333):
# after setting a constant value for a, we have these 2 conditions
# to connect b and c
# b<c
# b + c = 1000 -a
# by substituting the equation 2 into the first inequality, we get
# that
# b<floor(1000-a/2)
for b in range(2, (1000-a)//2 + 1):
if check_pythagorean_triplet(a,b, (1000-a)-b):
print a*b*(1000-a-b)
triplet_found = True
break
if triplet_found:
break
| false |
d26828c5f9c1d9490d1d397aa672c74f87f1e821 | malianxun/AID2011month2 | /select_server.py | 1,384 | 4.125 | 4 | """
基于select 方法的io 多路复用网络并发
重点代码!!
"""
from select import select
from socket import *
# 地址
HOST = "0.0.0.0"
PORT = 8888
ADDR = (HOST, PORT)
def main():
# tcp套接字 连接客户端
sock = socket()
sock.bind(ADDR)
sock.listen(5)
print("Listen the port %d" % PORT)
#防止IO处理过程中产生阻塞行为
sock.setblocking(False)
# 设置要监控的IO
rlist = [sock]
wlist = []
xlist = []
# 循环接收客户端连接
while True:
rs,ws,xs = select(rlist,wlist,xlist)
#逐个取值,分情况讨论
for r in rs:
if r is sock:
conffd,addr = r.accept()
conffd.setblocking(False)
print("Connect from",addr)
#将客户端套接字添加到监控列表
rlist.append(conffd)
else:
#连接套接字就绪
data = r.recv(1024).decode()
#客户端退出
if not data:
rlist.remove(r) #不再监控
r.close()
continue
print(data)
# r.send(b"ok")
wlist.append(r) #加入写列表
for w in ws:
w.send(b"ok")
wlist.remove(w)
if __name__ == '__main__':
main()
| false |
411c840c3eed902311543ed9aa459e952b6a7802 | oleksandr-nikitenko/python-course | /Lesson_26/task3.py | 817 | 4.15625 | 4 | """
# Extend the Stack to include a method called get_from_stack that searches and returns an element e
# from a stack. Any other element must remain on the stack respecting their order.
# Consider the case in which the element is not found - raise ValueError with proper info Message
# Extend the Queue to include a method called get_from_stack that searches and returns an element e
# from a queue. Any other element must remain in the queue respecting their order.
# Consider the case in which the element is not found - raise ValueError with proper info Message
"""
from stack import Stack
from queue import Queue
if __name__ == "__main__":
s = Stack()
q = Queue()
for i in range(50):
s.push(i)
q.enqueue(i)
print(s.get_from_stack(40))
print(q.get_from_queue(40)) | true |
e0a2336680d8b24bc1de0cabcb4aab1dd7135a3b | oleksandr-nikitenko/python-course | /Lesson_11/task1.py | 696 | 4.21875 | 4 | """Make a class called Person. Make the __init__() method take firstname, lastname, and age as parameters and add them
as attributes. Make another method called talk() which makes prints a greeting from the person containing, for example
like this: “Hello, my name is Carl Johnson and I’m 26 years old”."""
class Person:
""" A Person class"""
def __init__(self, firstname: str, lastname: str, age: int) -> None:
self.firstname = firstname
self.lastname = lastname
self.age = age
def talk(self) -> None:
print(f'Hello, my name is {self.firstname} {self.lastname} and I’m {self.age} years old')
obj = Person('Carl', 'Johnson', 26)
obj.talk()
| true |
5b3a41f5937f89cad7b16f7de0fa65b23bce89c1 | oleksandr-nikitenko/python-course | /Lesson_8/task3.py | 996 | 4.5625 | 5 | """
Create a function called make_operation, which takes in a simple arithmetic operator as a first parameter
(to keep things simple let it only be ‘+’, ‘-’ or ‘*’) and an arbitrary number of arguments (only numbers) as the
second parameter. Then return the sum or product of all the numbers in the arbitrary parameter. For example:
the call make_operation(‘+’, 7, 7, 2) should return 16
the call make_operation(‘-’, 5, 5, -10, -20) should return 30
the call make_operation(‘*’, 7, 6) should return 42
"""
from math import prod
def make_operation(operator: str, *args: int) -> int:
result = 0
if operator in ['+', '-', '*'] and all(isinstance(x, int) for x in args):
if operator == '+':
result = sum(args)
elif operator == '*':
result = prod(args)
elif operator == '-':
return args[0] - sum(args[1:])
else:
print('Unknown operator or arg is not int.')
result = 0
return result
| true |
4df63417fc4ed7d520b59f1fdcb72fe2100c2d17 | oleksandr-nikitenko/python-course | /Lesson_15/task3.py | 1,266 | 4.21875 | 4 | """
Write a decorator `arg_rules` that validates arguments passed to the function.
A decorator should take 3 arguments:
max_length: 15
type_: str
contains: [] - list of symbols that an argument should contain
If some of the rules' checks returns False, the function should return False and print the reason it failed; otherwise,
return the result.
"""
from functools import wraps
def arg_rules(type_: type, max_length: int, contains: list):
def arg_rules_dec(func):
@wraps(func)
def wrap(name):
err = []
if not isinstance(name, type_):
err.append(f'{name} is not {type_}')
if len(name) > max_length:
err.append(f'{name} > {max_length}')
err.extend(f'not found {i}' for i in contains if i not in name)
if len(err) == 0:
return func(name)
else:
print(err)
return False
return wrap
return arg_rules_dec
@arg_rules(type_=str, max_length=15, contains=['05', '@'])
def create_slogan(name: str) -> str:
return f"{name} drinks pepsi in his brand new BMW!"
assert create_slogan('johndoe05@gmail.com') is False
assert create_slogan('S@SH05') == 'S@SH05 drinks pepsi in his brand new BMW!'
| true |
7fd94e0622223864c7334ddcf48e60af82159700 | kikijtl/coding | /Candice_coding/Practice/Fibonacci_Sequence.py | 639 | 4.375 | 4 | '''
Output the nth number in the Fibonacci Sequence.
'''
def nthFibonacci_recursive(n):
if n == 1 or n == 2:
return 1
return nthFibonacci_recursive(n-1) + nthFibonacci_recursive(n-2)
def nthFibonacci_loop(n):
if n == 1 or n == 2:
return 1
previous = 1
current = 1
for i in xrange(3, n+1):
tmp = current + previous
previous = current
current = tmp
return current
if __name__ == '__main__':
n = 10
for n in xrange(1, 30):
a = nthFibonacci_loop(n)
b = nthFibonacci_recursive(n)
print a, b
assert a == b | false |
46412f98fa00fcf47357026805fa9deb87cd6c0c | kikijtl/coding | /Candice_coding/Cracking_the_Coding_Interview/Queue_by_2Stacks.py | 1,388 | 4.15625 | 4 | '''Implement a queue using two stacks.'''
class Queue:
def __init__(self):
self.max_size = 10
self.front = 0
self.end = 0
self.arr = [None]*self.max_size
self.tmp = []
def __repr__(self):
return '%s(%r)' %(self.__class__.__name__, self.arr)
def enqueue(self, element):
if (self.end - self.front) >= self.max_size:
print 'queue is full'
return 1
self.arr[self.end] = element
self.end += 1
return 0
def dequeue(self):
if self.end == self.front:
print 'queue is empty'
return None
if not self.tmp:
while self.arr:
self.tmp.append(self.arr.pop())
self.front += 1
return self.tmp.pop()
def is_empty(self):
return self.end == self.front
if __name__ == '__main__':
my_queue = Queue()
queue_data = [1,2,3,4,5,6,7,8,9,10,11]
for data in queue_data:
my_queue.enqueue(data)
while not my_queue.is_empty():
print my_queue.dequeue()
print my_queue
from collections import deque
q = deque([40,50,60])
for data in queue_data:
q.append(data)
while q:
q.popleft()
print q
| false |
5095d554baf1909bb9731bda65af7e04d25b3809 | kikijtl/coding | /Candice_coding/Leetcode/Permutations.py | 778 | 4.15625 | 4 | '''Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].'''
from copy import deepcopy
def permute(num):
n = len(num)
#count = [1] * n
cur_result = []
results = []
dfs(num,cur_result, results, n)
return results
def dfs(num, cur_result, results, n):
if not num:
results.append(deepcopy(cur_result))
return
for each_num in num:
cur_result.append(each_num)
idx = num.index(each_num)
new = num[:idx] + num[idx+1:]
dfs(new, cur_result, results, n)
cur_result.pop()
if __name__ == '__main__':
num = [0, 1]
print permute(num) | true |
6eba1e86149ce3c05dcd297215f5371e400d8d92 | kikijtl/coding | /Candice_coding/Leetcode/Closest_Binary_Search_Tree_Value.py | 1,333 | 4.15625 | 4 | # Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
#
# Note:
# Given target value is a floating point.
# You are guaranteed to have only one unique value in the BST that is closest to the target.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
if not root: return float('inf')
if target == root.val:
return root.val
elif target < root.val:
left = self.closestValue(root.left, target)
if abs(left-target) < root.val-target:
return left
else:
return root.val
else:
right = self.closestValue(root.right, target)
if abs(right-target) < target - root.val:
return right
else:
return root.val
if __name__ == '__main__':
root = TreeNode(1)
node = TreeNode(2)
root.right = node
target = 3.428571
print Solution().closestValue(root, target) | true |
c516bc3e2cde7d979b5155822f837f482c6e9a14 | kikijtl/coding | /Candice_coding/Leetcode/Implement_Stack_Using_Queues.py | 1,541 | 4.125 | 4 | import collections
class Stack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.q1 = collections.deque()
self.q2 = collections.deque()
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
if self.q2:
self.q2.append(x)
else:
self.q1.append(x)
def pop(self):
"""
:rtype: nothing
"""
if self.q1:
while self.q1:
tmp = self.q1.popleft()
if self.q1: self.q2.append(tmp)
else:
while self.q2:
tmp = self.q2.popleft()
if self.q2: self.q1.append(tmp)
def top(self):
"""
:rtype: int
"""
tmp = None
if self.q1:
while self.q1:
tmp = self.q1.popleft()
self.q2.append(tmp)
else:
while self.q2:
tmp = self.q2.popleft()
self.q1.append(tmp)
return tmp
def empty(self):
"""
:rtype: bool
"""
if self.q1 or self.q2:
return False
return True
if __name__ == '__main__':
mystack = Stack()
# mystack.push(1)
# mystack.push(2)
# print mystack.top()
# mystack.pop()
# print mystack.top()
# mystack.pop()
print mystack.empty()
| false |
fe7e219419804dcdb343c62dd89d3601d9802266 | Rafaellinos/learning_python | /structures_algorithms/recursion/recursion3.py | 282 | 4.3125 | 4 | """
reverse string by using
"""
def reverse_str(string):
return string[::-1]
def reverse(string):
print(string)
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
# print(reverse_str('hello'))
print(reverse('hello'))
| true |
ec6c262f7c755bc2b30890ffff5b7da629e9b44d | Rafaellinos/learning_python | /OOP/objects.py | 1,177 | 4.125 | 4 | #OOP
class PlayerCharcter:
"""
self represents the instance of the class.
With this keyword, its possible to access atributes and methods of the class.
When objects are instantiated, the object itself is passed into the self parameter.
"""
membership = True # class object attribute
# class attribute is not dynamic
def __init__(self, name="anonymous",age=0):
# init method is a special method or a dunder method
# automatically call when instantiate an object
if self.membership: # or could be PlayerCharcter.membership because its a class obj attribute
self.name = name # attributes
self.age = age
else:
print("Not a membership")
def run(self):
return f"{self.name} run"
# can't do PlayerCharcter.name because its not a class attribute, its refers to a instanceated object
player1 = PlayerCharcter("Cindy")
player2 = PlayerCharcter("Tom")
# instantiate, needs to give the init arguments
print(player1.name)
print(player2.name)
print(player1.run())
# help(player1) show the code
player1.membership = False
print(player1.membership) | true |
13a9e0c4334f1bbe6d0b89c69fe71a90d2b074f9 | Rafaellinos/learning_python | /basics/learning_lists.py | 1,694 | 4.125 | 4 | lista = [1,2,3,4]
lista.append(5)
lista2 = lista
print(lista2)
# If I try to copy the last on that way (lista2 = lista),
# any changes that I made on lista2 goes to lista aswell, because
# they are pointing to the same place in memory.
# the right way to copy a list, is lista2 = lista[:], or lista2 = lista.copy()
lista2.insert(1, 500) # insert a value on index
print(lista2)
lista2.extend(lista) #extends a list to a existing one
print(lista2)
removed_item = lista2.pop(1) #if no index given, remove the last item, also returns whatever u've removed.
print(removed_item)
print(lista2)
lista2.remove(500) #remove the first item found on parameter
print(lista2)
print(lista2.index(2)) # returns the index of the given value
print(2 in lista2) # returns True if found the item, if not, False
print(lista.count(2)) # count how much times the item appears on the list
lista2.sort() # organize the list. sorted(lista2) does the same thing, but without modify
print(lista2)
lista2.reverse() #revert the index, or can be lista[::-1] without modify the list
print(lista2)
lista2.clear() # clears the list. New in version 3.3
print(lista2)
print(lista)
print(list(range(100))) # add 0 to 99 in a list
test = " "
print(test.join(['hi','my','name','is','rafael'])) # joins each item on the list
list_unpacking = ['a','b','c','d','e','f']
a, b, c, *other, f = list_unpacking # *other unpack the rest of the items
print(type(other))
print(f"{a},{b},{c} and {other}, {f}")
#remove duplicates
list2 = [1,2,3,4,5,5]
list3 = []
for item in list2:
if not item in list3:
list3.append(item)
print(list2)
print(list3)
# OR can use set
print(set(list2))
list4 = list(set(list2))
print(list4) | true |
6d8cb09b90c7c9a7386e1210905b3005c51109bc | Rafaellinos/learning_python | /OOP/polymorphism.py | 688 | 4.1875 | 4 | """
Polymorphism:
Poly means many and morphism means forms, many form in other words.
In python means that objects can share the same names but work in diferent ways.
"""
class User:
def attack(self):
return "do nothing"
class Archer(User):
def __init__(self, name, arrows):
self.name = name
self.arrows = arrows
def attack(self):
print(User.attack(self))
return f"{self.name} uses {self.arrows} arrows"
####
archer1 = Archer("Robin", 30)
print(archer1.attack())
def player_attack(player):
print(player.attack())
player_attack(archer1) # in polymorphism, we can use objects by passing through classes and methods
| true |
adbe2258d207f05702157e8fa1e1182a32ad35d0 | Rafaellinos/learning_python | /functional_programming/reduce.py | 661 | 4.125 | 4 | from functools import reduce
my_list = [1,2,3]
def multiply_by2(item):
return item*2
def accumulator(acc, item):
print(acc, item)
return acc+item
# func item, acc
print(reduce(accumulator, my_list, 0)) # default = 0
# output
# 0 1
# 1 2
# 3 3
# 6
sum_total = reduce((lambda x,y: x+y), [1,2,3,4], 0)
print(sum_total) #10
"""
reduce gets the return number and store for the next iteration.
The first number is 0, default is 0
1. reduce((0+1), iterable, 0): returns 1
2. reduce((1+2), iterable, 1): returns 3
3. reduce((3+3), iterable, 3): returns 6
4. reduce((6+4), iterable, 6): returns 10
"""
| true |
3d6a633b77b2305a9f2bd3111645311ec6649881 | Rafaellinos/learning_python | /basics/learning_tuples.py | 600 | 4.40625 | 4 | """
Tuples are immutables, so you can't update, sort, add item etc
Usually more faster than lists.
Tuple only has two methods: count and index, but it works with len
"""
tuple2 = (1,2,3,4)
print(3 in tuple2)
new_tuple = tuple2[1:4]
print(new_tuple)
a, b, *other = tuple2 #unpacking tuple
print(other)
print(tuple2)
print(tuple2.index(2)) #seach by value, returns the index
print(tuple2[2]) #search by index, returns the value
tuple3 = ('1','2','3','4')
print(tuple3.index('3'))
a, b, *_ = tuple3
# underscore indicates to python that the variable will not be used.
print(a)
print(b) | true |
10b9250387e95708aab6cda408133fa0b157c3b2 | Rafaellinos/learning_python | /structures_algorithms/algorithms/leet_code_1528.py | 986 | 4.125 | 4 | """
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
Example 3:
Input: s = "aiohn", indices = [3,1,4,2,0]
Output: "nihao"
Example 4:
Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5]
Output: "arigatou"
Example 5:
Input: s = "art", indices = [1,0,2]
Output: "rat"
"""
from typing import List
def restoreString(s: str, indices: List[int]) -> str:
new_str = ""
c = 0
while c < len(s):
new_str += s[indices.index(c)]
c += 1
return new_str
print(restoreString(s="aiohn", indices=[3, 1, 4, 2, 0])) | true |
55abcf3f6a0916eeb2da275f5464c602c6a3a9b0 | Erick-INCS/FSDI_114_Algorithms_and_DataStructures | /linked_list/linked_list.py | 1,570 | 4.1875 | 4 | #!/usr/bin/env python3
""" linked list implementation """
class Node:
""" One directional node """
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
class LinkedList:
""" Data structure """
def __init__(self, val):
self.head = Node(val)
def __str__(self):
result = ""
tmp = self.head
while tmp:
result += str(tmp.val) + (' --> ' if tmp.next else '')
tmp = tmp.next
return result
def append(self, val, after_node=None):
""" add at element at the end or after specific node (by value) """
tmp = self.head
if not tmp:
return
while tmp.next and not(after_node is None and tmp.val == after_node):
tmp = tmp.next
another = tmp.next
tmp.next = Node(val)
tmp.next.next = another
def prepend(self, val):
""" add an alement at the begining """
nd = Node(val)
nd.next = self.head
self.head = nd
def remove(self, value):
""" remove and element """
nd = self.head
if not nd:
return
if nd.val == value:
self.head = nd.next
while nd.next:
if nd.next.val == value:
nd.next = nd.next.next
nd = nd.next
if __name__ == '__main__':
ts = LinkedList(6)
ts.append(10)
ts.append(21)
ts.append(12)
ts.append(33, 10)
ts.prepend(-1)
ts.remove(10)
print(ts)
| true |
c3491d075ad662a00b7c0683d4192835c9aae475 | agarw184/Data-Science | /PA04_final/problem2.py | 2,102 | 4.15625 | 4 | #perform a stencil using the filter f with width w on list data
#output the resulting list
#note that if len(data) = k, len(output) = k - width + 1
#f will accept as input a list of size width and return a single number
def stencil(data, f, width) :
#Fill in
#Initialising Variables
k = len(data)
w = width
num = 0
i = 0
out = []
r = []
while (i < (k - w + 1)):
temp = i
num = 0
r = []
while (num < w):
r.append(data[temp])
temp = temp + 1
num = num + 1
out.append(f(r))
i = i + 1
return out
#create a box filter from the input list "box"
#this filter should accept a list of length len(box) and return a simple
#convolution of it.
#the meaning of this box filter is as follows:
#for each element the input list l, multiple l[i] by box[i]
#sum the results of all of these multiplications
#return the sum
#So for a box of length 3, filter(l) should return:
# (box[0] * l[0] + box[1] * l[1] + box[2] * l[2])
#The function createBox returns the box filter itself, as well as the length
#of the filter (which can be passed as an argument to conv)
def createBox(box) :
def boxFilter(l) :
sum = 0
for i in range (len(box)):
sum = sum + (box[i] * l[i])
return sum
return boxFilter, len(box)
if __name__ == '__main__' :
def movAvg(l) :
if (len(l) != 3) :
print(len(l))
print("Calling movAvg with the wrong length list")
exit(1)
return float(sum(l)) / 3
def sumSq(l) :
if (len(l) != 5) :
print("Calling sumSq with the wrong length list")
exit(1)
return sum([i ** 2 for i in l])
data = [2, 5, -10, -7, -7, -3, -1, 9, 8, -6]
print(stencil(data, movAvg, 3))
print(stencil(data, sumSq, 5))
#note that this creates a moving average!
boxF1, width1 = createBox([1.0 / 3, 1.0 / 3, 1.0 /3])
print(stencil(data, boxF1, width1))
boxF2, width2 = createBox([-0.5, 0, 0, 0.5])
print(stencil(data, boxF2, width2))
| true |
be1d306f7c0840dcc7f5df2a4fc9285a81079b3f | LiaoTingChun/python_advanced | /ch3_abstract.py | 968 | 4.34375 | 4 | # abstract class
# 抽象類別不能生成實例, 只能被繼承
# class中包含一個以上abstract method, 即為abstract class
# 改寫type, 就是在寫metaclass
from abc import ABCMeta, abstractmethod, ABC # abstract base class
# 改用ABCMeta生成class
class Product(metaclass=ABCMeta):
@abstractmethod
def hi(self):
pass
@abstractmethod
def hi2(self):
pass
class Drink(Product):
def hi(self): # override
print('hi')
def hi2(self): # override
print('hi')
#p = Product()
#p = Drink()
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print('bark')
class Cat(Animal):
def make_sound(self):
print('meow')
class Person(Animal):
def make_sound(self):
print('hi')
d = Dog()
d.make_sound()
c = Cat()
c.make_sound()
s = Person()
s.make_sound()
for animal in [d, c, s]:
animal.make_sound() | false |
567ec46c085595c66571a67b0f6c7311a3d693e2 | SaraAnttila/day2-bestpractices-1 | /1a_e/animals/birds.py | 365 | 4.15625 | 4 | """
Package with types of birds
"""
class Birds:
def __init__(self):
"""
Construct this class by creating member animals
"""
self.members = ['Sparrow', 'Robin', 'Duck']
def printMembers(self):
print('Printing members of the Birds class')
for member in self.members:
print('\t{}'.format(member))
| true |
b59587c38765e23a5d821cc6d9560284ca88a71e | Jitha-menon/jithapythonfiles | /PycharmProject/fundamental_programming/Swapping/flow_of_controls/Looping_For Loop.py | 372 | 4.21875 | 4 | # For i in range (5):
# print('hello')
for a in range (2,8):
print (a)
# for in range with initial value final value and increment value
for i in range (1,10,2):
print (i)
#problem to find numbers between min and max range
min= int(input('enter the min num'))
max=int(input('enter the max num'))
for i in range(min,max):
print(i)
break | false |
d277b87aec7f8288dcb76b17a85b5eaef466a437 | Jitha-menon/jithapythonfiles | /PycharmProject/Regular Expressions/quantifier rule 2.py | 201 | 4.15625 | 4 | import re
x='a*' # counts all no:of data whether a is there or not it iterates
r='aaa abc dsd avf aaa avg'
matcher=re.finditer(x,r)
for match in matcher:
print(match.start())
print(match.group()) | false |
fcc9afc659b9b41084eef7c08d3da756e6f4fc33 | SRashmip/FST-M1 | /Python/Activities/Activity3.py | 787 | 4.15625 | 4 | user1 = input("What is player 1 name:")
user2 = input("What is player2 name:")
user1_answer = input(user1+ "Do you want to choose rock,paper or scissor" )
user2_answer = input(user2+"Do you want to choose rock,paper or scissor")
if user1_answer==user2_answer:
print("its tie")
elif user1_answer=='rock':
if user2_answer=='paper':
print("rock wins")
else:
print("paper wins")
elif user1_answer=='scissor':
if user2_answer=='paper':
print("scissor wins")
else:
print("paper wins")
elif user1_answer=='paper':
if user2_answer=='rock':
print("paper wins")
else:
print("scissor wins")
else:
print("wrong input! you have not entered rock,paper,scissor try again!")
| true |
c9e547c4ec6f2e42dc7703b372625705640860d8 | momado350/fun | /pythagoren_check.py | 684 | 4.3125 | 4 | # in this challenge we will check if a list is applicable to return a pythagoren triplets
# our assumptions
#[3,4,5] = True
# [4] = False
# [12,1,7,9]= False
# the code:
#create a function to check if list is pythagoren triplets
lst = [3, 4, 6]
def p_t(lst):
for i in range(len(lst)):
for j in range(i+1, len(lst)):
for k in range(j+1, len(lst)):
if lst[i]**2 + lst[j]**2 == lst[k]**2:
#return True
print("we got pythagoren triplet")
else:
#return False
print("we dont have it!")
#return False
p_t(lst)
| false |
d89c05ca8e67c947a11fca49a107b4f2dd34843b | RKKgithub/databyte_inductions | /CountryCodes_task.py | 606 | 4.375 | 4 | import csv
#take country codes as input
code1, code2 = input().split()
flag = False
#empty list to store country names
data = []
#open csv file and store data in a dictionary
with open(r"CSV_FILE_PATH_GOES_IN_HERE") as file:
reader = csv.DictReader(file)
#add country names in between the two country codes
for row in reader:
if row["Code"] == code1 or row["Code"] == code2:
flag = not flag
continue
if flag == True:
data.append(row["Name"])
#print country names in sorted order
for item in sorted(data):
print(item)
| true |
720d1526b00a45fbbcc8e76855b2514400954e31 | Hussein-Mansour/ICS3UR-Assignment-6B-python | /volume_of_rectangle.py | 1,166 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: Hussein Mansour
# Created on: Fri/May28/2021
# This program calculates the volume of rectangular prism
def volume_rectangular(length_int, width_int, height_int):
# this function calculates the volume of rectangular prism using return
# process
volume = length_int * width_int * height_int
# return
return volume
def main():
# this function this function call other functions
# input
print("To calculate the volume of rectangular prism:")
length_from_user = input("Enter the length (cm): ")
width_from_user = input("Enter the width (cm): ")
height_from_user = input("Enter the height (cm): ")
try:
length_int = int(length_from_user)
width_int = int(width_from_user)
height_int = int(height_from_user)
# call function
volume_rectangular(length_int, width_int, height_int)
# output
print(
"\nvolume = {0}cm³"
.format(volume_rectangular(length_int, width_int, height_int)))
except Exception:
print("\nInvalid Input!")
finally:
print("\nDone.")
if __name__ == "__main__":
main()
| true |
803b0a3be00d0659b0451d4c211a962f4491cd4c | x223/cs11-student-work-genesishiciano | /Word_Count.py | 866 | 4.3125 | 4 | text_input= raw_input("Write your text here") # The text that you are going to use
user_choice= raw_input("what word do you want to find? ") # the word that the person is looking for
text_input=text_input.lower()# change all of the inputs into lower case
text_input=text_input.replace(".", " ")# changes all of the '.' into spaces- so it won't affect the code
text_input= text_input.replace(",", " ")# changes all of the ',' into spaces - same reason as above
text_input=text_input.replace(";"," ")# changes all of the ';' into spaces - same reason as previously stated
text_input=text_input.split() # breaks apart the text that is given into a list
My_dictionary={} # empty list- in this list the values for Text_input will be inserted
for x in text_input:# This is a loop- which reapeated
My_dictionary[x]=text_input.count(x)
print My_dictionary[user_choice]
| true |
f719f7f80d4eb84bb5bda99663f9b34963a38c35 | gan-gan777/Python_Crash_Course | /04/4-11_Pizzas_you&me.py | 449 | 4.21875 | 4 | my_pizzas = ['Chicken', 'Durian', 'Beef']
friend_pizzas = my_pizzas[:]
my_pizzas.append('Double')
friend_pizzas.append('Mango')
print("My favorite pizza are:")
print(my_pizzas)
for my_pizza in my_pizzas:
print("I like " + my_pizza.lower() + " pizza.")
print("\nMy friend's favorite pizza are:")
print(friend_pizzas)
for friend_pizza in friend_pizzas:
print("My friend like " + friend_pizza.lower() + " pizza.")
print("I really love pizza.")
| false |
71c7612841b4e6c0fe29bee99d5d73cbbe027fe4 | krewper/Python_Commits | /misc_ops.py | 1,204 | 4.125 | 4 | #swapping variables in-place
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#Reversing a string
a = "Kongsberg Digital India"
print("Reverse is", a[::-1])
#Creating a single string from all the elements in a list
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
#chaining of comparision operators
n = 10
result = 1 < n <20
print(result)
result = 1>n <=9
print(result)
#printing file paths of imported modules
import numpy;
import requests;
print(numpy)
print(requests)
#using enums in python
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
#returning multiple values from a single function
def r():
return 1, 2, 3, 4
a, b, c, d = r()
print(a, b, c, d)
#finding the most frequent value in a list
test = [1, 2, 3, 4, 2, 2, 3, 2, 4, 1, 4, 4]
print(max(set(test), key = test.count))
#check the memory usage of an object
import sys
x = 1
print(sys.getsizeof(x))
#print string n times
n = 2;
a = "GeeksforGeeks";
print(a * n);
#checking if two words are anagrams
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek')) | true |
8af810deab946e1010252e63292d9653ba6b6b50 | Dream-Team-Pro/python-udacity-lab2 | /TASK-3.py | 694 | 4.46875 | 4 | # Task 3:
# You are required to complete the function maximum(x). where "x" is a list of numbers. the function is expected to return the highest number in that list.
# Example:
# input : [5,20,12,6]
# output: 20
# you can change the numbers in the list no_list but you are not allowed to change the variable names or edit any other code, please only complete the function's definition.
# _______________________________________________________________________________
no_list = [1,2,3,4]
def maximum(no_list):
#complete the function to return the highest number in the list
max = 0
for i in no_list:
if i > max:
max = i
return max
print(maximum(no_list))
| true |
e2d8abd1867efe72fc0222e00189922e542497db | freddywilliam/Pensamiento_Computacional | /Diccionarios/dict_com.py | 1,029 | 4.125 | 4 |
def run():
print('''
---------------------------------------------------
AQUI CREO MI DICCIONARIO
''')
dict = {
'david' : 18,
'pedro' : 20,
'sara' : 10,
'melissa' : 17,
}
print(dict)
print('''
---------------------------------------------------------
AQUI CREO UNA VARIABLE Y EN ELLA ASIGNO DEFINO:
name:age = Seria la estructura, en ella puedo agregar cosas como el ".capitalize".
for name, age in dict.items(): = Defino las partes que quiero que iteren dentro de dict.
if age > 18 = Quiero que solo iteractue los que sean mayores a 18.
''')
d = {
name.capitalize(): age
for name, age in dict.items()
if age >= 18
}
print('''
-------------------------------------------------------------
AQUI SOLAMENTE IMPRIMO LA VARIABLE "d" EN ELLA ESTA TODO EL PROCESO
''')
print(d)
if __name__ == '__main__':
run() | false |
2ce2e3f08b62ff843373991517e1af4cc2f230a7 | SaiNikhilD/Dogiparty_SaiNikhil_Spring2017 | /Assignment3/Question2_Part1.py | 1,030 | 4.21875 | 4 |
# coding: utf-8
# # Question2_Part1
# •Use 'employee_compensation' data set.
# •Find out the highest paid departments in each organization group by calculating mean of total compensation for every department.
# •Output should contain the organization group and the departments in each organization group with the total compensationfrom highest to lowest value.
# •Display a few rows of the outputuse df.head().
# •Generate a csv output.
# In[17]:
#Importing libraries
import pandas as pan
# In[18]:
#Reading csv file
df=pan.read_csv('employee_compensation.csv')
# In[19]:
#Grouping by Organization Group and Department
dfgrouped = df.groupby(['Organization Group', 'Department'],as_index=False)['Total Compensation'].mean()
# In[20]:
#Sorting in descending order
dfoutput= dfgrouped.sort_values(['Total Compensation'], ascending = [False])
# In[21]:
#printing few values using head
print(dfoutput.head())
# In[22]:
#Converting to csv
dfoutput.to_csv('Question2_Part1.csv',index=False)
# In[ ]:
| true |
e4a51691d1de70e5b932773a7f34f9e7531449d7 | njberejan/Palindrome | /palindrome_advanced.py | 818 | 4.28125 | 4 | import re
# def reversed_string(sentence):
# #recursive function to reverse string
# if len(sentence) == 0:
# return ''
# else:
# return reversed_string(sentence[1:]) + sentence[0]
def is_palindrome(sentence):
#uses iterative to solve, above function not called so commented out.
sentence = re.sub(r'[^A-Za-z0-9]', '', sentence).lower()
sentence_rev = sentence[::-1]
if sentence == sentence_rev:
return True
else:
return False
def main():
#main function which obtain input, removes chaff, and runs comparison function above
sentence = input("Please enter a sentence to determine if it is palindromic: ")
if is_palindrome(sentence):
print("Is a palindrome")
else:
print("Is not a palindrome")
if __name__ == '__main__':
main()
| true |
8e95b399682602881a79f1f0dc5cdc0688a74efe | sarahmbaka/Bootcamp_19 | /Day_4/MissingNumber/missing_number.py | 340 | 4.21875 | 4 | def find_missing(list1, list2):
"""Function that returns the difference between two lists"""
if not list1 and list2: # checks if list is empty
return 0
diff = list(set(list1) ^ set(list2)) # diff is the difference between the lists
if not diff:
return 0
return diff[0] #retrieve first item in the list
| true |
64b93a9f735a25f268123acf4474e0d8d1fd3738 | aruntom/python | /hit_the_target.py | 1,223 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 11:55:39 2017
@author: aruntom
"""
#Arun Tom
import turtle
SCREEN_WIDTH=600
SCREEN_HEIGHT= 600
TARGET_LLEFT_X=100
TARGET_LLEFT_Y=250
TARGET_WIDTH=25
FORCE_FACTOR=30
PROJECTILE_SPEED=1
NORTH=90
SOUTH=270
EAST=0
WEST=180
turtle.setup(SCREEN_WIDTH,SCREEN_HEIGHT)
turtle.hideturtle()
turtle.speed(0)
turtle.penup()
turtle.goto(TARGET_LLEFT_X,TARGET_LLEFT_Y)
turtle.pendown()
turtle.setheading(EAST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(NORTH)
turtle.forward(TARGET_WIDTH)
turtle.setheading(WEST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(SOUTH)
turtle.forward(TARGET_WIDTH)
turtle.penup()
turtle.goto(0,0)
turtle.setheading(EAST)
turtle.showturtle()
turtle.speed(PROJECTILE_SPEED)
angle=float(input("Enter the projectile's angle: "))
force=float(input("Enter the launch force (1-10): "))
distance=force * FORCE_FACTOR
turtle.setheading(angle)
turtle.pendown()
turtle.forward(distance)
if (turtle.xcor()>= TARGET_LLEFT_X and turtle.xcor() <= (TARGET_LLEFT_X + TARGET_WIDTH) and turtle.ycor()>= TARGET_LLEFT_Y and turtle.ycor() <= (TARGET_LLEFT_Y + TARGET_WIDTH)):
print("Target hit")
else:
print("You missed the target.")
| false |
b61106c9d0e72482f7320c6ae12374e98c989d66 | Riya258/PythonProblemSolvingCodeSubmission | /ps1b.py | 1,233 | 4.25 | 4 | # Name: Riya
# REG. NO.: BS19BTCS005
# Time spend: 2:30 hours
#Problem 2
#2.Paying Debt Off In a Year
"""
Write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months.
We will not be dealing with a minimum monthly payment rate.
"""
outstanding_balance = float(input("Enter the outstanding balance on your credit card: "))
annual_interest_rate = float(input("Enter the annual credit card interest rate as a decimal: "))
minimum_monthly_payment = 500
monthly_interest_rate = annual_interest_rate/12.0
number_of_months = 0
balance = outstanding_balance
#calculate fixed minimum monthly payment
while balance > 0:
balance = outstanding_balance
number_of_months = 0
minimum_monthly_payment = minimum_monthly_payment+500
while balance > 0 and number_of_months < 12:
balance = balance * (1 + monthly_interest_rate)- minimum_monthly_payment
number_of_months = number_of_months+1
print("RESULT")
print("Monthly payment to pay off debt in 1 year: Rs.",float(minimum_monthly_payment))
print("Number of months needed: ",number_of_months)
print("Balance: Rs. ",round(balance,2))
| true |
55ee6660ae1b673ef68b2e225012cc1de26e68c3 | NimalGv/Python-Programs | /MYSLATE/A2-Programs/Day-1/4.number_a_sum_of_two_primes.py | 770 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
1.Any even number greater than or equal to 4 can always be written as sum of two primes
even : even+even and odd+odd;
2.The odd number can be written as sum of two primes if the number-2 is a prime number, because
odd : odd+even and even+odd;
so, IsPrime(number-2)
Goldbach's conjecture
"""
import math
def is_prime(number):
for i in range(2,int(math.sqrt(number))+1):
if(number%i==0):
return False
return True
number=int(input())
if(number>=4 and number%2==0):
print("Can be written as sum of two primes")
elif(is_prime(number-2)):
print("Can be written as sum of two primes")
else:
print("Cannot be written as sum of two primes")
| true |
a1eb915db6312fe768536d0af922d02e569f476b | muhammadalie/python-think | /factorial.py | 251 | 4.21875 | 4 | def fact(n):
if type(n)==int:
print 'n is not integer'
return None
elif 0<=n<=2:return n
elif n<0:
print 'not defined,number is negative'
return None
return n*fact(n-1)
n=input('type your number: ')
print 'the factorial is ',fact(n)
| true |
82801a8c565f7c058270124cb270dd09b0213136 | felix1429/project_euler | /euler04.py | 1,058 | 4.21875 | 4 | # Largest palindrome from multiplying two three digit numbers
# 998001 is 999 * 999
# start at 998001 and iterate down until first palindrome
# then divide that palindrome by 999, 999 - 1, 999 - 2 etc until it
# divides evenly or runs out of numbers, in which case the next palindrome
# is moved to
def is_palindrome(number): #function that checks if number is a palindrome
number = str(number)
y = len(number)
x = 0
while True:
if number[x] == number[y - 1]:
pass
else:
return False
break
if x == y or y - x == 1:
return True
break
y -= 1
x += 1
done = False
for foo in range(998001,1,-1):
if is_palindrome(foo) == True:
the_number = foo
for diviser in range(999,int(the_number ** .5),-1):
if the_number % diviser == 0:
other_diviser = the_number / diviser
print(the_number)
done = True
break
if done == True:
break
| true |
bb974d1a1a6dd9b6653db0ebfb6f883d5bd6f4d6 | rajesh1994/lphw_challenges | /python_excercise/ex05.01.py | 779 | 4.125 | 4 | one_centimeter_equal_to = 0.393701 # Inches
# Getting the centimeter value from the user
centimeter = float(raw_input("Enter the centimeter value:"))
# Calculating the equalent inches by using centimeter value
inches_calculation = one_centimeter_equal_to * centimeter
# Printing the converted value in inches
print "The centimeter %f" %centimeter, "is equal to %f" %round(inches_calculation), "inches"
one_kg_equal_to = 2.20462 # Pounds
# Getting the kilogram value from the user
kilo_gram = float(raw_input("Enter the Kilogram value:"))
# Caculating the equlent pounds by using kilogram value
pound_calculation = one_kg_equal_to * kilo_gram
# Printing the converted value in pounds
print "The Kilogram %f" %kilo_gram, "is equal to %f" %round(pound_calculation), "pounds"
| true |
83de7ca67fdb04a015d4f0ee0dad0424a1a66e0f | nileshpandit009/practice | /BE/Part-I/Python/BE_A_55/assignment1_1.py | 245 | 4.125 | 4 | my_list = input("Enter numbers separated by spaces").split(" ");
total = 0;
for num in my_list:
try:
total += int(num)
except ValueError:
print("List contains non-numeric values\n")
exit(-1)
print(total)
| true |
c98bf8c90d9ac104f2cabc8669c7888ea8fa5fbe | bunnymonster/personal-code-bits | /python/learningExercises/ListBasics.py | 760 | 4.46875 | 4 | #This file demonstrates the basics of lists.
animals = ["rabbit","fox","wolf","snail"]
#prints the list
print(animals)
#lists are indexed like strings. slicing works on lists.
print(animals[0])
print(animals[1:2])
#all slices return a new list containing the requested items.
#lists support concatenation
animals + ["coyote","fish"]
print(animals)
#lists are mutable
animals[3] = "shark!"
print(animals)
#new items can be added to lists using append
animals.append("housefly")
print(animals)
#assignment to slices can be done. this can remove or change elements/
animals[2:3] = []
print(animals)
#clear list by replacing all elements with an empty list
animals[:] = []
print(animals)
#len also works on lists
cubes = [1,8,27,64,125]
print(len(cubes))
| true |
9bd76cf27d41a1e017011e2409c6ae68ffd41058 | bunnymonster/personal-code-bits | /python/learningExercises/ErrorsAndExceptions.py | 2,115 | 4.25 | 4 | import sys
#
#Errors and Exceptiosn
#
#Error handled with basic try except
try:
print(x)
except:
print('Error! x not defined.')
#multiple Exceptions may be handled by a single except
#by being listed in a tuple.
try:
print(x)
except (RuntimeError, TypeError, NameError):
print('Error!')
#a class C in an except clause are compatible with an exception e
#if the exception is the same class or a base class thereof.
#That is, e must be of type C or must be of type B where B is a base class of C.
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
#The preceding prints "B" "C" "D" in that order.
#IF the except classes were called reversed "D" "C" "B", then it would print
#"B" "B" "B" as B is the first base class of each of the exceptions B, C, and D
#
#Else
#
#The try statement has and else clause which follows all except clauses,
#and is used for code that must run when the try block does not raise any
#exceptions.
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
#
#Raising Exceptions
#
#Raise can be used to force a specific exception.
try:
raise NameError('HiThere')
except (NameError) as err:
print(err)
#
#Cleanup with finally
#
#The try statement has a finally clause which executes at the end of the try
#statement whether an exception occurs or not. IF an exception occurs, it is
#rethrown after the finally block code executes
try:
raise KeyboardInterrupt
finally:
print('Goodbye world is printed at the end of the try block.')
print('This file ends in an exception as this is the last code in the\n',
'file and its purpose is to demonstrate a finally block\n',
'running when an exception is thrown')
#some objects define standard cleanup actions that execute whether an error.
#e.g. the with clause for files.
| true |
aeb5387a37f4d61e2d9dbd67fa541a669312856e | praveen2896/python | /Assignment_op.py | 428 | 4.15625 | 4 | f_num=input("enter the number1")
print f_num
s_num=input("enter the number2")
print s_num
answer=f_num+s_num
answer += f_num
print "addition ",answer
answer -= f_num
print "subtraction ",answer
answer *= f_num
print "multiplication ",answer
answer /= f_num
print "division ",answer
answer %= f_num
print "modolo ",answer
answer ^=f_num
print "exponent ",answer
answer //=f_num
print "floor division ",answer
| false |
e196c243910c0b42dcee2195675ef2c7e393c703 | rupol/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 883 | 4.28125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
# return an array with the max value of each window (i to i + k)
def sliding_window_max(nums, k):
# create an array to save the max values in
result = [0] * (len(nums) - (k - 1))
# iterate through the array
for i in range(len(nums)):
# if i is k items from the end of the array
if i + k <= len(nums):
# slice out a window from i to i + k
window = nums[i:i+k]
# find the max of that subarray
result[i] = max(window)
return result
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(
f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
f14f5b7612a5ac16d08ac92b6766ea08659e8c92 | inickt/advent-of-code-2019 | /aoc/day01.py | 1,329 | 4.375 | 4 | """Day 1: The Tyranny of the Rocket Equation"""
from math import floor
def fuel_required(mass: float) -> float:
"""Find fuel required to launch a given module by its mass.
Take mass, divide by three, round down, and subtract 2.
Examples:
>>> fuel_required(12)
2
>>> fuel_required(14)
2
>>> fuel_required(1969)
654
>>> fuel_required(100756)
33583
:param mass: Mass of the module
:return: Fuel required
"""
return max(floor(mass / 3) - 2, 0)
def total_fuel_required(mass: float) -> float:
"""Find fuel required to launch a given module by its mass (including its fuel).
Examples:
>>> total_fuel_required(14)
2
>>> total_fuel_required(1969)
966
>>> total_fuel_required(100756)
50346
:param mass: Mass of the module
:return: Total fuel required
"""
if mass > 0:
fuel_needed = fuel_required(mass)
return total_fuel_required(fuel_needed) + fuel_needed
return 0
if __name__ == "__main__":
# run tests
import doctest
doctest.testmod()
with open("inputs/01.txt") as infile:
MASSES = [float(mass) for mass in infile.readlines()]
print("Part 1:", sum(fuel_required(mass) for mass in MASSES))
print("Part 2:", sum(total_fuel_required(mass) for mass in MASSES))
| true |
b25db4d630a000b0481c50402638811cb0106772 | thevarunnayak/pythonprograms | /basicprograms/Function Demo.py | 716 | 4.28125 | 4 | # Program to demonstrate functions
'''
print("WTC Namde!")
print("Ee Sala Cup Namde!")
print("Michael Vaughan is shit!")
'''
# To repeat this 10 times,
'''
for _ in range(10):
print("WTC Namde!")
print("Ee Sala Cup Namde!")
print("Michael Vaughan is shit!")
'''
'''
print("WTC Namde!")
print("Ee Sala Cup Namde!")
print("Michael Vaughan is shit!")
a=10
b=20
c=a+b
print(c)
print("WTC Namde!")
print("Ee Sala Cup Namde!")
print("Michael Vaughan is shit!")
d=200
e=300
f = d-e
print(f)
print("WTC Namde!")
print("Ee Sala Cup Namde!")
print("Michael Vaughan is shit!")
'''
def printall():
print("WTC Namde!")
print("Ee Sala Cup Namde!")
printall()
print(20+30)
printall()
print(100-200)
printall() | false |
8a007237f7cc4430ab0a1e10793e03f78fa19335 | Stubbycat85/csf-1 | /Hw-1/hw1_test.py | 1,615 | 4.3125 | 4 | # Name: ...
# Evergreen Login: ...
# Computer Science Foundations
# Programming as a Way of Life
# Homework 1
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should compute and
# print the answers to all the problems.
import math # makes the math.sqrt function available
import hw1_test
###
### Problem 1
###
print "Problem 1 solution follows:"
###
a = 1
b = -5.86
c = 8.5408
x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
y = ((-1)* b - math.sqrt(b**2-4*a*c))/2*a
print x
print y
###
### Problem 2
###
print "Problem 2 solution follows:"
print hw1_test.a
print hw1_test.b
print hw1_test.c
print hw1_test.d
print hw1_test.e
print hw1_test.f
###
### Problem 3
###
print "Problem 3 solution follows:"
print ((hw1_test.a and hw1_test.b) or (not hw1_test.c) and not (hw1_test.d or hw1_test.e or hw1_test.f))
###
### Collaboration
### Ahmed Ali, Kahea
# ... List your collaborators and other sources of help here (websites, books, etc.),
# ... as a comment (on a line starting with "#").
###
### Reflection
###
# ... Write how long this assignment took you, including doing all the readings
# homework took me 2hours to complete. it would have been alot harder but toutor Kahea was very helpful helping me.
# ... and tutorials linked to from the homework page. Did the readings, tutorials,
# ... and lecture contain everything you needed to complete this assignment?
# Yess it was very helpful. And the instructions where on point
| true |
b10d3f99b7fe131537dc62af61c93c92885a9776 | jhonatanmaia/python | /study/curso-em-video/14 - Funções.py | 2,195 | 4.21875 | 4 | '''
Funções = rotina
def = definição de função
def mostraLinha():
print('-'*30)
mostraLinha()
print('Sistema de Alunos')
mostraLinha()
Os parametros passado pelo usuario sao os parametros reais
e os parametros da funcao sao os parametros formais
def mensagem(msg):
print("-"*30)
print(msg)
print("-"*30)
def soma(a,b):
s=a+b
print(s)
soma(4,5)
Pode-se explicitar a entrada
soma(b=4,a=5)
-> Empacotamento de parametros
def contador(*num):
def contador(* num):
tam=len(num)
print(f'Recebi os valores {num} e são ao todos {tam} números')
for valor in num:
print(f'{valor} ',end='')
print('FIM')
contador(1,2,3,4,5,6)
def divisao(a,b):
print(a/b)
divisao(1,4)
def soma(a,b):
print(a+b)
# A função pode receber uma lista em vez de ser um dic
def dobra(lit):
pos=0
while pos<len(lit):
lit[pos]*=2
pos+=1
lista=[7,2,4,0,4]
dobra(lista)
print(lista)
# INTERACTIVE HELP
help(print) #Mostra toda documentação da função
# Pode ser usado apenas help() no console, para sair use o quit
print(input.__doc__) # outra forma de se fazer
'''
#DOCSTRING
# O manual para cada função
def contador(i,f,p):
"""
-> Faz uma contagem e mostra na tela.
:param i: inicio da contagem
:param f: fim da contagem
:param p: passo da contagem
:return: sem retorno
"""
c=i
while c<=f:
print(f'{c}',end='..')
c+=p
print('FIM')
help(contador)
# Parametros Opcionais
def somar(a,b,c=0):
# Se o valor de c não for passado então c vai assumir o valor de 0
s=a+b+c
print(f'A soma vale {s}')
somar(2,3)
def somar2(a=0,b=0,c=0):
s=a+b+c
print(f'A soma vale {s}')
# Escopo de Variáveis
def teste(b):
# Tudo declarado dentro da função e variavel local
# Não podera ser chamada fora dela
global a
a=8
# para a dentro da função ser o a global, deve se dizer global antes
b+=4
c=2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
# Area global das variaveis
a=5
teste(a)
print(f'A fora vale {a}')
def somar3(a=0,b=0,c=0):
s=a+b+c
return s
| false |
36444a7d22f2f3bae8a8bc1bec97a6772b45e713 | GhostGuy9/Python-Programs | /madlibs/Catcher/questions.py | 1,808 | 4.125 | 4 | import os
#Configure this Section
questions = [
"Type a Adverb",
"Type a Verb",
"Type a Verb in Past Tense",
"Type a Adjective",
"Type a Plural Noun",
"Fictional Character Name",
"Type a undesirable Noun",
"Type a Verb",
"Type a Noun",
"Type a Verb in Past Tense ending in \"S\"",
"Type a Plural Noun",
"Enter a Number(0 or Zero)",
"Type a Plural Noun",
"Type a Adjective",
"Type a Adjective",
"Type a Noun"
]
question_type = [
"Adverb",
"Verb",
"Verb",
"Adjective",
"Noun",
"Character",
"Noun",
"Verb",
"Noun",
"Verb",
"Noun",
"Number",
"Noun",
"Adjective",
"Adjective",
"Noun"
]
num_of_questions = 16
#For Loop - Don't Touch or Do, Full customizable stuff here
answers = []
question_num = 0
question = 0
debug = 0
#Question Loop - Don't Touch or you might break it.
while num_of_questions > question_num and debug == 0:
os.system('cls')
question_num = question_num+1
print(f"Question {question_num} of {num_of_questions}")
answer = input(question_type[question] + " | " + questions[question]+ ": ")
answers.insert(question, answer)
question = question + 1
while num_of_questions > question_num and debug == 1:
os.system('cls')
question_num = question_num+1
print(f"Question {question_num} of {num_of_questions}|Index: {question}")
answer = input(question_type[question] + " | " + questions[question]+ ": ")
answers.insert(question, answer)
question = question + 1
#End of Question Loop - Don't Touch or you might break it.
#Shows Story by clearing screen
story = open("madlibs/Catcher/madlib.txt").read().format(answers=answers)
os.system('cls')
print(f"Catcher in the {answers[6]}")
print("-----------")
print(story)
print()
| true |
c7466693f23dcb10b71277637b895e78f6c1a668 | neelamy/Algorithm | /DP/Way_to_represent_n_as_sum_of_int.py | 975 | 4.125 | 4 | # Source : http://www.geeksforgeeks.org/number-different-ways-n-can-written-sum-two-positive-integers/
# Algo/DS : DP
# Complexity : O(n ^2)
# Program to find the number of ways, n can be
# written as sum of two or more positive integers.
# Returns number of ways to write n as sum of
# two or more positive integers
def CountWays(n):
# table[i] will be storing the number of
# solutions for value i. We need n+1 rows
# as the table is consturcted in bottom up
# manner using the base case (n = 0)
# Initialize all table values as 0
table =[0] * (n + 1)
# Base case (If given value is 0)
# Only 1 way to get 0 (select no integer)
table[0] = 1
# Pick all integer one by one and update the
# table[] values after the index greater
# than or equal to n
for i in range(1, n ):
for j in range(i , n + 1):
table[j] += table[j - i]
return table[n]
# driver program
def main():
n = 7
print CountWays(n)
if __name__ == '__main__':
main() | true |
06da28be20b6763e571b7245bb559e042855353d | leilacey/LIS-511 | /Chapter 3/Guest List.py | 392 | 4.28125 | 4 | # 3-4 Guest List
dinner_guests = ['Kurt Cobain', 'Bill Gates', 'Eddie Veddar']
for guest in dinner_guests
print ("Would you like to have dinner with me " + guest + "?")
# 3-5 Changing Guest List
not_coming = "Bill Gates"
dinner_guests.insert(1, "Dave Grohl")
dinner_guests.remove(not_coming)
for guest in dinner_guests
print ("Would you like to have dinner with me " + guest + "?")
print (not_coming) | false |
ec8410a8e32b0f3ecd96490b352611b9e9a6dfe0 | cspfander/Module_6 | /more_functions/validate_input_in_functions.py | 1,260 | 4.5625 | 5 | """
Program: validate_input_in_functions.py
Author: Colten Pfander
Last date modified: 9/30/2019
The purpose of this program is to write a function score_input() that takes a test_name, test_score, and
invalid_message that validates the test_score, asking the user for a valid test score until it is in the range,
then prints valid input as 'Test name: ##'.
"""
def score_input(test_name, test_score=0, invalid_message="Invalid test score, try again!"):
"""
:param test_name: stores user input as a test name to print
:param test_score: stores a user input as a test score to print as well as be validated (optional)
:param invalid_message: optional message that displays an indicated string if the user has input an invalid score
:return: either returns a string with the Test_name : test_score or with an invalid_message for an invalid input
"""
try:
int(test_score)
except ValueError:
return "Invalid test score! Please use only numeric!"
if 0 <= test_score <= 100:
# return {test_name: test_score}
return str(test_name) + ": " + str(test_score)
else:
return invalid_message
if __name__ == '__main__':
# print(score_input("Unit 9", 85))
print(score_input("Unit 8", "i"))
| true |
556d13ca018fe2391fa65925fa52905ea2710219 | gandhalik/PythonCA2020-Assignments | /Task 3/7.py | 254 | 4.40625 | 4 | #7. Write a program to replace the last element in a list with another list.
# Sample data: [[1,3,5,7,9,10],[2,4,6,8]]
# Expected output: [1,3,5,7,9,2,4,6,8]
list1 = [1,3,5,7,9,10]
list2 = [2,4,6,8]
list1[-1:]=list2
print(list1)
| true |
c309e2fdf79e7ff8f27aa7c01ac4fe94d15fda8c | gandhalik/PythonCA2020-Assignments | /Task 4/3.py | 509 | 4.65625 | 5 | # Write a program to Python find out the character in a string which is uppercase using list comprehension.
# Using list comprehension + isupper()
# initializing string
test_str = input("The sentence is: ")
# printing original string
print("The original string is : " + str(test_str))
# Extract Upper Case Characters
# Using list comprehension + isupper()
res = [char for char in test_str if char.isupper()]
# printing result
print("The uppercase characters in string are : " + str(res))
| true |
44ed2cbea71e26cf87bebedb491deb1ea1e00574 | DRay22/COOP2018 | /Chapter08/U08_Ex06_PrimeLessEqual.py | 1,489 | 4.3125 | 4 | # U08_Ex06_PrimeLessEqual.py
#
# Author:
# Course: Coding for OOP
# Section: A2
# Date: 21 Mar 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: Name and Number
# Source: Python Programming
# Chapter: #
#
# Program Description
# This program will find prime numbers less or equal to n, a user inputted number
#
#
#
# Algorithm (pseudocode)
# main():
# introduce program
# get user's number
# call calculating function
# print output
# Calc():
# if n > 2:
# check if any numbers between 2 and math.sqrt(n) are evenly divisible by n (while)
# if there is one:
# add to list
# if there is not:
# run again
# if n < 2:
# add n to list
# return list
from random import *
import math
global list
global x
global ModN
def main():
global list
global x
global ModN
list = ' '
X = 1
fakeN = 2
print("fakeN", fakeN)
print("X", X)
N = int(input("What is the number that you would like to test? "))
while X <= math.sqrt(fakeN) and fakeN <= N:
ModN = fakeN%X
print(fakeN)
print("Mod", ModN)
if ModN != 0:
list = str(fakeN) + ', '
fakeN = fakeN + 1
print("New fakeN", fakeN)
X = 2
if ModN == 0:
X = X + 1
print("New X", X)
print("The numbers returned from this test are: {0}".format(list))
main()
| true |
61d62433a082758c56de60870e8b63ec97f2c397 | DRay22/COOP2018 | /Chapter04/U04_Ex07_CircleGraphics.py | 2,381 | 4.46875 | 4 | # U04_Ex07_CircleGraphics.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 29 Oct 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: Circle Graphics Ex07
# Source: Python Programming
# Chapter: #04
#
# Program Description
# This program will make a circle with a user specified radius and find where it intersects with a line on the y
# intercept.
#
#
# Algorithm (pseudocode)
# Import Graphics and the math library
# Introduce program
# Ask for input for radius, def as r
# Ask for y intercept of line def as y
# Set Coords -10, -10, 10, 10
# Make a circle at (0, 0) with a width of 1
# Make outline black
# Make Fill blue
# Draw circle
# Draw a horizontal line across the screen with y intercept
# LinX = +- math.sqrt(r**2 - y**2)
# LinY = y
# Draw two points of intersection in red
# Give points LinX, Lin Y for one line, and -1 * LinX, 1 * LinY
from graphics import *
import math
def main():
print("This program will draw a circle with a user specified radius and show where it will intercept with a line")
print("running across the graph at the Y Intercept, which is also user specified")
print("This graph will have the coordinates -10, -10 and 10, 10")
r = (int(input("what is the radius of the circle? ")))
y = (int(input("\nwhat is the y intercept? ")))
if y > r:
print("The circle will not intercept with the line")
else:
win = GraphWin("Circle Graphics.py", 400, 400)
win.setCoords(-10, -10, 10, 10)
Circ = Circle(Point(0, 0), r)
Circ.setOutline("black")
Circ.setFill("blue")
Circ.draw(win)
hline = Line(Point(-10, y), (Point(10, y)))
hline.setOutline("black")
hline.setFill("black")
hline.draw(win)
LinX = +- math.sqrt(r**2 - y**2)
LinY = y
Point1 = Point(LinX, LinY)
Point1.setOutline("red")
Point1.setFill("red")
Point1.draw(win)
Point2 = Point(-1 * LinX, 1 * LinY)
Point2.setOutline("red")
Point2.setFill("red")
Point2.draw(win)
P1X = Point1.getX()
P2X = Point2.getX()
print("The X value of the first intercept is", P1X)
print("The X value of the second intercept is", P2X)
input("\nPress ENTER to Continue")
win.close()
main()
| true |
dabc27a62b7c1b993cece699ae98f7cfe8b1d8a1 | DRay22/COOP2018 | /Chapter06/U06_Ex06_Area_of_Tri_Modular.py | 1,361 | 4.4375 | 4 | # U06_Ex06_Area_of_Tri_Modular.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 17 Jan 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: Area of Triangle 06
# Source: Python Programming
# Chapter: #06
#
# Program Description
# This program will find the area of a triangle through modular coding
#
#
#
# Algorithm (pseudocode)
# Func Input():
# get input for three sides then return in a list
#
# Func Calc():
# call input
# split three sides while assigning to variables
# make variable called s (sum of the sides): (side1 + side2 + side3)/2
# make variable called area (the area of the triangle): math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
# return area
#
# Func Print():
# call Calc
# print area of triangle
#
import math
def Input():
s1 = int(input('What is the length of the first side? '))
s2 = int(input('What is the length of the second side? '))
s3 = int(input('What is the length of the third side? '))
return s1, s2, s3
def Calc():
sides = Input()
side1 = sides[0]
side2 = sides[1]
side3 = sides[2]
s = (side1 + side2 + side3) / 2
area = math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
return area
def Print():
area = Calc()
print("The area is {0}".format(area))
Print()
| true |
6429e95316a74a6e65933c62d121395da234e974 | DRay22/COOP2018 | /Chapter04/U04_Ex09_CustomRectangle.py | 1,814 | 4.25 | 4 | # U04_Ex09_CustomRectangle.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 29 Oct 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: Custom Rectangle Ex09
# Source: Python Programming
# Chapter: #04
#
# Program Description
# This program will draw a rectangle based off of user mouse input and display the area and perimeter of it
#
#
#
# Algorithm (pseudocode)
# Introduce Program
# make graphics window
# set coords to 0, 0, 10, 10
# Get first click and X and Y values of it
# Get second click and X and Y values of it
# Make Rectangle based off of both click's values
# Set fill to red and outline to black
# Rectangle Length = X2 - X1
# Rectangle Width = Y1 - Y2
# Area: Rect length * Rect width
# Perimeter: length + width * 2
# Print both area and perimeter
# Ask for ENTER input
# Close graphics window
from graphics import *
def main():
print("This program will draw a rectangle based off of user mouse input and display the area and perimeter of it")
win = GraphWin("Rectangle")
win.setCoords(0, 0, 10, 10)
click1 = win.getMouse()
X1 = click1.getX()
Y1 = click1.getY()
win.checkMouse()
click2 = win.getMouse()
X2 = click2.getX()
Y2 = click2.getY()
Rect = Rectangle(Point(X1, Y1), (Point(X2, Y2)))
Rect.setOutline("black")
Rect.setFill("red")
Rect.draw(win)
RectLength = abs(X2 - X1)
RectWidth = abs(Y2 - Y1)
RectArea = RectLength * RectWidth
RectPerim = (RectLength + RectWidth) * 2
print("The width of the rectangle is", RectWidth, "and the length of the rectangle is", RectLength)
print("The area of the rectangle is:", RectArea, "The perimeter of the rectangle is:", RectPerim)
input("Press ENTER to close the window")
win.close()
main()
| true |
b2468f3a4cc6e93daeabb9b8fbda27b2049c86ff | avikram553/Basics-of-Python | /string.py | 458 | 4.34375 | 4 | str = 'Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:7]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
str=100
print(str)
#Reversing
str1 = "Hello Guys what's Up !!!"
print(str1)
print(str1[::-1]) | true |
ab9c2b816a1713a162ef9500f7c00927fd2edd9e | luohaha66/MyCode | /python/python_magic_method/repreesent_class.py | 2,434 | 4.4375 | 4 | """
In Python, there’s a few methods
that you can implement in your class definition to customize how built in functions that return
representations of your class behave
__str__(self) Defines behavior for when str() is called on an instance of your class.
__repr__(self) Defines behavior for when repr() is called on an instance of your class. The
major difference between str() and repr() is intended audience. repr() is intended to
produce output that is mostly machine-readable (in many cases, it could be valid Python
code even), whereas str() is intended to be human-readable.
__unicode__(self) Defines behavior for when unicode() is called on an instance of your class.
unicode() is like str(), but it returns a unicode string. Be wary: if a client calls str()
on an instance of your class and you’ve only defined __unicode__(), it won’t work. You
should always try to define __str__() as well in case someone doesn’t have the luxury of
using unicode.
__format__(self, formatstr) Defines behavior for when an instance of your class is used in
new-style string formatting. For instance, "Hello, 0:abc!".format(a) would lead to
the call a.__format__("abc"). This can be useful for defining your own numerical or
string types that you might like to give special formatting options.
__hash__(self) Defines behavior for when hash() is called on an instance of your class. It
has to return an integer, and its result is used for quick key comparison in dictionaries.
Note that this usually entails implementing __eq__ as well. Live by the following rule: a
== b implies hash(a) == hash(b).
__nonzero__(self) Defines behavior for when bool() is called on an instance of your class.
Should return True or False, depending on whether you would want to consider the instance to be True or False.
__dir__(self) : Defines behavior for when dir() is called on an instance of your class. This
method should return a list of attributes for the user. Typically, implementing __dir_-
_ is unnecessary, but it can be vitally important for interactive use of your classes if you
redefine __getattr__ or __getattribute__ (which you will see in the next section) or
are otherwise dynamically generating attributes.
7
"""
class RepDemo:
def __init__(self, value=''):
self.value = value
pass
def __str__(self):
return self.value
if __name__ == '__main__':
d = RepDemo('hello world')
print(str(d))
| true |
f08ec6439bfbcc2bef9ae906a869c157c60217ca | kjnevin/python | /09.Dictionaries P2/__init__.py | 1,231 | 4.1875 | 4 | fruit = {"Orange": "a sweet, orange citrus fruit",
"Apple": "Round fruit used to make cider",
"Banana": "Yellow fruit, used to make sandwiches",
"Pear": "Wired shaped fruit",
"Lime": "a sour green fruit"}
# while True:
# dict_keys = input("Please enter a piece of fruit: ")
# if dict_keys == 'quit':
# print("Enough")
# break
# print(fruit.get(dict_keys, "We don't have " + dict_keys))
#
# for snack in fruit:
# print("Yummy " + snack + ", "+ fruit[snack])
# for i in range(10):
# for snack in fruit:
# print(snack + " is " + fruit[snack])
#
# print('*' *50)
# order_keys = list(fruit.keys())
# order_keys.sort()
# order_keys = sorted(list(fruit.keys()))
# for f in order_keys:
# print(f + ' - ' + fruit[f])
#
# for f in sorted(fruit.keys()):
# print(f + " - " + fruit[f])
# print(fruit.keys())
# # fruit_keys = fruit.keys()
#
fruit["Tomato"] = "Great in a sandwich"
print(fruit.keys())
print(fruit)
print(fruit.items())
f_tuple = tuple(fruit.items())
print(f_tuple)
for snack in f_tuple:
item, description = snack
print(item + " is " + description)
print(dict(f_tuple)) | true |
83813a6fc6389bc8839f0eb52c5f318a9361c819 | MunavarHussain/Learning-Python | /Basics/io.py | 1,177 | 4.125 | 4 | '''
print() and input() are basic stdio write and read functions respectively.
let's see some examples to understand both functions, its usage and capabilities.
'''
print('hello world')
var = 10 # var is not a keyword in python
print('The value of variable var is',var)
'''
Output:
hello world
The value of variable var is 10
'''
'''
Note that a new line forms inbetween both print()s and a space is created after 'is' in second print statement by default.
all parameters of a print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
'''
print('No new line',end='')
print('No separator',var,sep='',flush=True)
'''No new lineNo separator10'''
''' The file parameter is the object where the values are printed and its default value is sys.stdout. flush doesnt has no common use case.'''
print('print var < {} > here'.format(var))
'''print var < 10 > here
same can be acheived by
'''
print(f'print var < {var} > here')
print('print var < %d > here' %var)
#Accepts all data types
n = input('enter a number')
'''
Extras:
int('10') - returns integer value 10
int('10+10') - returns value error
eval('10+10') - returns integer 20
'''
| true |
b73ae3d97ace11943c5ec19124c0370d840304ac | MunavarHussain/Learning-Python | /OOP/classes_instances.py | 1,544 | 4.1875 | 4 | #Tutorial 1 - Understanding classes and instances
'''Object oriented programming is a way of programming, that in its unique way allows us to group data based on objects.It is indeed inspired from real world.
In tutorial 1 we'll learn about class and instances.
Classes are blueprint associated with some data and functions. In OOP we call those attributes(variables) and methonds respectively.
Whereas Instances are a copy of a class that inherit attributes & methods of that class and also has its own attributes and methods.
Let's create a employee class to understand the concept.
'''
class Employee(): # To define a class the keyword itself is 'class' with classname starting with Captial Letter. For other naming conventions: https://www.python.org/dev/peps/pep-0008/#naming-conventions
def __init__(self,fname,lname,pay): #Its a constructor method, invoked whenever an object is created for this class. The keyword 'self' an instance of the class.
self.fname = fname
# object.<somename> = parameter
self.lname = lname
self.pay = pay
def fullname(self):
return f"{self.fname} {self.lname}"
if __name__ == "__main__":
emp1 = Employee('munavar','hussain',50000) # Creates an object of class employee
emp2 = Employee('ashraf','kutbudee',60000)
print(emp1.fname)
print(emp2.fname)
print(emp1.fullname())
#munavar
#ashraf
#munavar hussain
# Attributes and methods created so far are for instances not for the class. Hence,
# print(Employee.fname) throws error. | true |
b4b63b5670446d080a5de26eb6a6944737480559 | mjfeigles/technical_interview_practice | /arraysAndStrings/rotate_matrix.py | 1,239 | 4.15625 | 4 | #input: n x n matrix as 2D array
#output: the same matrix rotated 90 degrees
#Run instructions:
#python3 rotate_matrix.py matrix1
# Example matrix1: (can include spaces or not; must be n x n)
# [[1, 2], [3, 4]]
# [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
import sys
import math
def matrixRotate(matrix):
# convert input (string) to 2D array
matrix = matrix.translate(matrix.maketrans({"[":"", "]":"", " ":""})) #get rid of spaces and brackets from input
matrix = matrix.split(',')
n = math.sqrt(len(matrix))
if (n - int(n) != 0):
print("Matrix must be n x n")
return # matrix not n x n
n = int(n)
mtx = [[(int(matrix[i]) + (j*n)) for i in range(n)] for j in range(n)]
print(mtx)
if mtx is None or len(mtx[0]) == 0:
return
for i in range(n//2):
top, left = i, i
right, bottom = n-i-1, n-i-1
for j in range((n//(i+1))-1):
temp = mtx[top][left + j]
mtx[top][left + j] = mtx[bottom-j][left]
mtx[bottom-j][left] = mtx[bottom][right-j]
mtx[bottom][right-j] = mtx[top+j][right]
mtx[top+j][right] = temp
print(mtx)
if __name__ == "__main__":
matrixRotate(sys.argv[1])
| true |
b03687696d732833496fbee14822b706ea6f1aa9 | gaurishanker/learn-python-the-hard-way | /ex3.py | 675 | 4.3125 | 4 | #first comment
print("I will now count my chickens:")
#counting hens
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
#an expression it will be evaluated as first 1/4 = 0.25 then from left to write
# poit to note 1 + 4 % 2 is 1.
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6.0)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
print("5/7",5/7)
print("5.0/7.0",5.0/7.0)
| true |
95ca0c279386ff25f693abab8c1a57a83816b08b | zeroam/TIL | /algorithm/insertion_sort.py | 497 | 4.1875 | 4 | def insertion_sort(arr: list) -> None:
"""삽입 정렬 알고리즘
각 값이 어떤 위치에 가야할 지 찾음
:param arr: 정렬할 리스트
"""
for i in range(1, len(arr)):
element = arr[i]
j = i - 1
while j >= 0 and element < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = element
if __name__ == '__main__':
element_list = [8, 2, 3, 4, 7, 1, 5, 6, 9]
insertion_sort(element_list)
print(element_list) | false |
2ce129db9c61fc233a8fffa7508b612e0c079dcc | Souji9533/Mycode | /python/simpiy.py | 229 | 4.15625 | 4 | num = 'week'
print(type(num))
empty_list=list()
#empty_tuple=tuple[]
#empty_set=set{} #this is not empty set this is empty dictiory
student = {'name' : 'john', 'age' : 23, 'courses' :['cse','ece','eee']}
print(student['age']) | false |
f975cdbc75ee254825989d79556328ab5b7c9ae5 | 19sblanco/cs1-projects | /futureDay.py | 2,310 | 4.4375 | 4 | '''
requirement specification:
have user play a game of rock paper scissors against a
'random' computer
'''
'''
system anaysis:
user inputs
'''
'''
system design:
1. have user input 0, 1, or 2 (represents scissor, rock and paper) respectively
2. store number 1 as value
3. have computer randomly choose number between 0 and 2
4. store number 3 as computerValue
5. define value as rock paper or scissors based on what number it is
6. do the same as 5 but for the computerValue
7. compare user answer to computer answer to find out who won
8. print statement based on who won/lossed/draw
'''
# code
import random
print("Play rock, paper, scissors against a computer!")
print("scissors = 0, rock = 1, paper = 2")
# have user input 0, 1 or 2
value = int(input("Enter in a value: "))
# computer value
computerValue = random.randint(0, 2)
# redefine rock paper scissors
if value == 0:
value = "scissors"
elif value == 1:
value = "rock"
elif value == 2:
value = "paper"
if computerValue == 0:
computerValue = "scissors"
elif computerValue == 1:
computerValue = "rock"
elif computerValue == 2:
computerValue = "paper"
# impliment system analysis
# scissors
if value == "scissors":
if computerValue == "scissors":
print("You are " + value + " too. It is a draw")
elif computerValue == "rock":
print("You are " + value + ". You lossed")
elif computerValue == "paper":
print("You are " + value + ". You won")
# rock
if value == "rock":
if computerValue == "scissors":
print("The computer is " + computerValue + "." +" You are " + value + ". You won.")
elif computerValue == "rock":
print("The computer is " + computerValue + "." +" You are " + value + " too. Its a draw")
elif computerValue == "paper":
print("The computer is " + computerValue + "." +" You are " + value + ". You lossed")
# paper
if value == "paper":
if computerValue == "scissors":
print("The computer is " + computerValue + "." +" You are " + value + ". You lossed")
if computerValue == "rock":
print("The computer is " + computerValue + "." +" You are " + value + ". You won")
if computerValue == "paper":
print("The computer is " + computerValue + "." +" You are " + value + " too. Its a draw") | true |
aaf71b8b743424126b75802724ea47942bfa7df6 | LibbyExley/python-challenges | /FizzBuzz.py | 492 | 4.1875 | 4 | """
Write a program that prints the numbers from 1 to 100. If it’s a multiple of 3,
it should print “Fizz”. If it’s a multiple of 5, it should print “Buzz”.
If it’s a multiple of 3 and 5, it should print “Fizz Buzz”.
"""
numbers = list(range(1,101))
for number in numbers:
if number % 5 == 0 and number % 3 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
| true |
2895873d8b4e03ecd2a78284ab1978ee1725673f | MudassirASD/darshita..bheda | /.py | 261 | 4.21875 | 4 | n=int(input("Enter a number:"))
if n>0:
print("The number is positive")
elif n<0:
print("The number is negative:")
else:
print("The number is zero")
def n=int(input("Enter the 1st integer:"))
m=int(input("Enter the 2nd integer:")) | true |
5592f7ca20d84a53346ad430715aefa58daeda17 | ovjohn/masterPython | /12-Modulos/main.py | 1,093 | 4.125 | 4 | """
Modulos: Son funcionalidades ya hechas para reutilizar
En la documentacion de Python existen muchos modulos para ser consultadas y utilizadas.
Podemos conseguir modulos que ya vienen en el lenguaje,
modulos de internet o tambien podemos CREAR nuestros modulos
"""
#LLamando los Modulos
#import mimodulo #Importando mudolo propio
#from mimodulo import holaMundo
from mimodulo import *
#print(mimodulo.holaMundo("John")) #Utilizando el la funcion holaMundo del Modulo
#print(mimodulo.calculadora(2,4,False)) # Utilizando otra funcion
#print(holaMundo("Juan Jose"))
#Modulo fechas
import datetime
print(datetime.date.today())
fecha_completa = datetime.datetime.now()
print(fecha_completa)
print(fecha_completa.day)
print(fecha_completa.month)
print(fecha_completa.year)
print(fecha_completa.strftime("%d/%m/%Y, %H-%M-%S"))
#Modulo Matematica
import math
print("La Raiz cuadrada de 10 es:", math.sqrt(10))
print("Numero pi:", float(math.pi))
print("Rendondiar un numero:", math.ceil(12.457))
#Modulo Aleatorio
import random
print("Numero aleatorio entre 2 y 9 es:", random.randint(2,9))
| false |
8397c08437aedea80cd0ee729f98c9ffcbd17648 | bradandre/Python-Projects | /College/Homework Programs/November 25th/One.py | 899 | 4.375 | 4 | #Initial list creation
colors = ["red", "black", "orange"]
#Appending new items to the list
for c in ("yellow", "green", "blue", "indigo", "violet"):
colors.append(c)
#Removing the color black from the list
colors.remove("black")
#Outputting the third element
print("Third element: {0}".format(colors[2]))
#Outputting the length of the list
print("Length of the list: {0}".format(len(colors)))
#Outputting the first four elements of the list
print("First four list elements: {0}".format(colors[:4]))
#Outputting the last 3 elements of the list
print("Last three list elements: {0}".format(colors[-3:]))
#User chosen element
elements = int(input("What number do you want: "))
print("You have chosen: {0}".format(colors[elements]))
#Prints the entire list
print("Entire list: {0}".format(colors))
#Prints the entire list with spaces inbetween
for e in colors:
print(e, end=" ")
print("\n") | true |
54678d9ea9aa057adc9cb30b354902ee1905e203 | sokhij3/210CT-Coursework | /Question 10.py | 1,249 | 4.21875 | 4 | #Q - Given a sequence of n integer numbers, extract the sub-sequence of maximum length
# which is in ascending order.
l = input("Please input a list of integers: ")
lis = list(map(int, l)) #map() function makes each iterable in the list lis an int
def ascendingOrder(lis):
temp = []
maxSeq = [0]
for x, y in zip(lis, lis[1:]): #zip() function taken from stackoverflow as i needed
if x < y: #to find a way to compare an element of a list the with
temp.append(x) #the next element.
elif x >= y:
temp.append(x)
if len(temp) >= len(maxSeq):
maxSeq = temp
temp = []
elif len(temp) < len(maxSeq):
temp = []
if len(temp) >= len(maxSeq):
temp.append(y)
maxSeq = temp
temp = []
print(maxSeq)
ascendingOrder(lis)
'''if x<y then it is put in a temp array. happens until x>=y. Then temp array length
compared with maxSeq array. If temp>maxSeq then it replaces maxSeq and temp is emptied.
repeats until the biggest sequence of ascending order is found'''
| true |
53e4a8503866e93d0895a1d012f2bedc6855803e | munikarmanish/cse5311 | /algorithms/min_spanning_tree/prim.py | 768 | 4.1875 | 4 | """
Implementation of the Prim's algorithm to find the minimum spanning tree
(MST) of a graph.
"""
from data_structures.heap import Heap
def prim(G, root=None):
"""
Find the minimim spanning tree of a graph using Prim's algorithm. If root
is given, use it as the starting node.
"""
nodes = Heap([(float("inf"), n) for n in G.nodes])
parent = {n: None for n in G.nodes}
if root:
nodes[root] = 0
mst = set()
while nodes:
node = nodes.pop()[0]
if parent[node] is not None:
mst.add((parent[node], node))
for neigh, weight in G[node].items():
if neigh in nodes and weight < nodes[neigh]:
nodes[neigh] = weight
parent[neigh] = node
return mst
| true |
e4c25b4bf3e65511806a091af990dd9d6608b66f | Steven98788/Ch.08_Lists_Strings | /8.3_Adventure.py | 2,609 | 4.21875 | 4 | '''
ADVENTURE PROGRAM
-----------------
1.) Use the pseudo-code on the website to help you set up the basic move through the house program
2.) Print off a physical map for players to use with your program
3.) Expand your program to make it a real adventure game
'''
room_list=[]
current_room=0
inventory = []
done= False
#Rooms
room= ["Outside front",1,None,None,None]
room_list. append(room)
room= ["Living Room",None,2,3,None]
room_list. append(room)
room = ["kitchen",4,None,1,None]
room_list. append(room)
room=["play room",6,1,None,None]
room_list. append(room)
room=["dining area",None,None,5,2]
room_list. append(room)
room=["bedroom",None,4,6,None]
room_list. append(room)
room=['Bathroom',None,5,None,3]
room_list. append(room)
#end of rooms
playerName= input("What is your name?")
print("Hello",playerName.center(10))
#navigationsd
while not done:
print()
print("current room:",room_list[current_room][0])
print("Where to", playerName,"?")
direction = input("\n N for north \n E for east \n S for south \n W for west \n Q to quit \n ")
if direction.lower() == 'north' or direction.lower() == "n":
next_room = room_list[current_room][1]
if next_room == None:
print("You can't go that way.")
else:
current_room = next_room
elif direction.lower() == "west" or direction.lower() == "w":
next_room = room_list[current_room][2]
if next_room == None:
print("You can't go that way")
else:
current_room = next_room
elif direction.lower() == "east" or direction.lower() == "e":
next_room = room_list[current_room][3]
if next_room == None:
print("You can't go that way")
else:
current_room = next_room
elif direction.lower() == "south" or direction.lower() == "s":
next_room = room_list[current_room][4]
if next_room == None:
print("You can't go that way")
else:
current_room = next_room
elif direction.lower() == "q":
print("Thanks for playing!")
done = True
else:
print()
print("Invalid choice. Please try again.")
print()
continue
#End of navigation
if current_room == 1:
userInput=input("Would you like to interact with the clock \n i for interact or no to skip")
if userInput.lower() == "i":
print("the grandfather clock is moved by many gears")
elif userInput=="no":
continue
if current_room==2:
userInput=input("")
userInput.lower()=="i"
| true |
8139cd54762564ee4824367d4a1c96ff0a199c1c | thread13/shpy-1 | /demo00.py | 612 | 4.1875 | 4 | #!/usr/bin/python2.7 -u
import sys
# prints range between first two args and points at third arg if in range
a = sys.argv[1]
b = sys.argv[2]
c = sys.argv[3]
if (int(a) < int(b)):
while (int(a) <= int(b)):
# range up
if (int(a) == int(c)):
print str(a) + ' <<'
else:
print str(a)
a = (int(a) + 1) # increment
else:
# echo "$1 is not smaller than $2"
while (int(a) >= int(b)):
# range down
if (int(a) == int(c)):
print str(a) + ' <<'
else:
print str(a)
a = (int(a) - 1) # increment
| true |
745ba7865afa129f13720c0d8d2f98ad5ebcfb8e | carefing/PythonStudy | /basics/clock.py | 844 | 4.125 | 4 | """
Define Clock and show clock time
"""
import time
class Clock(object):
def __init__(self, **hms):
if 'hour' in hms and 'minute' in hms and 'second' in hms:
self._hour = hms['hour']
self._minute = hms['minute']
self._second = hms['second']
else:
tm = time.localtime(time.time())
self._hour = tm.tm_hour
self._minute = tm.tm_min
self._second = tm.tm_sec
def run(self):
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self):
return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)
if __name__ == "__main__":
# clock = Clock(hour=10, minute=15, second=22)
clock = Clock()
while True:
print(clock.show())
time.sleep(1)
clock.run() | false |
edfa5113c29949ee7567d472fc85021e395f8a13 | SKVollala/PYTHON_REPO | /experienceCalc.py | 717 | 4.25 | 4 | """
This program calculates the age/experience in years, months, and days format
Input:
Asks the user to enter a date in YYYY-MM-DD format
Output:
Calculates and prints the experience in years, months, and days
"""
from datetime import date
from dateutil.relativedelta import relativedelta
def exp_calc():
date_entry = input('Enter a date in YYYY-MM-DD format: ')
year, month, day = map(int, date_entry.split('-'))
from_date = date(year, month, day)
now = date.today()
r_delta = relativedelta(now, from_date)
print("Your experience is: {} years, {} months, and {} days".format(r_delta.years, r_delta.months, r_delta.days))
if __name__ == "__main__":
exp_calc()
| true |
6b99166a38563d7948c26b2fd571879a84c86b0b | mindnhand/Learning-Python-5th | /Chapter17.Scopes/nested_default_lambda.py | 756 | 4.15625 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------
# Usage: python3 nested_default_lambda.py
# Description: nested scope and default argument
#------------------------------------------
# nested scope rules
def func(): # it works because of the nested scope rules
x = 4
action = (lambda n: x ** n) # x remembered from enclosing def
return action
x = func()
print(x(2)) # prints 16, 4 ** 2
# passing default argument
def func1(): # it works because of the default value in argument passing
x = 4
action = (lambda n, x=x: x ** n) # pass default argument x=x
return action
x1 = func1()
print(x1(3))
| true |
835a6fde6e06b9253e64d2cdc22108df356abd07 | mindnhand/Learning-Python-5th | /Chapter34.ExceptionCodingDetails/2-try-finally.py | 1,169 | 4.15625 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------
# Usage: python3 2-try_finally.py
# Description: try-finally to do some cleanup jobs
#---------------------------------------
'''
When the function in this code raises its exception, the control flow jumps
back and runs the finally block to close the file. The exception is then
propagated on to either another try or the default top-level handler, which
prints the standard error message and shuts down the program. Hence, the
statement after this try is never reached. If the function here did not raise
an exception, the program would still execute the finally block to close the
file, but it would then continue below the entire try statement.
'''
class MyError(Exception):
pass
def stuff(file):
raise MyError('raise an Exception in stuff(file) function')
file = open('data', 'w') # Open an output file (this can fail too)
try:
stuff(file) # Raises exception
finally:
file.close() # Always close file to flush output buffers
print('Not reached') # Continue here only if no exceptions
| true |
e5b34e73ebee7acbfda4bfab71c5dbaf4e039943 | mindnhand/Learning-Python-5th | /Chapter31.DesigningWithClasses/converters.py | 2,457 | 4.21875 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------------
# Usage: python3 converters.py
# Description: compostion and inheritance
#---------------------------------------------
from streams import Processor
class Uppercase(Processor):
def converter(self, data):
return data.upper()
'''
Here, the Uppercase class inherits the stream-processing loop logic (and anything else
that may be coded in its superclasses). It needs to define only what is unique about it
—the data conversion logic. When this file is run, it makes and runs an instance that
reads from the file trispam.txt and writes the uppercase equivalent of that file to the
stdout stream:
c:\code> type trispam.txt
spam
Spam
SPAM!
'''
class HTMLize:
def write(self, line):
print('<PRE>%s</PRE>' % line.rstrip())
'''
But, as suggested earlier, we could also pass in arbitrary objects coded as classes that
define the required input and output method interfaces. Here's a simple example that
passes in a writer class that wraps up the text inside HTML tags:
'''
'''
If you trace through this example's control flow, you'll see that we get both uppercase
conversion (by inheritance) and HTML formatting (by composition), even though the
core processing logic in the original Processor superclass knows nothing about either
step. The processing code only cares that writers have a write method and that a method
named convert is defined; it doesn't care what those methods do when they are called.
Such polymorphism and encapsulation of logic is behind much of the power of classes
in Python.
'''
'''
For another example of composition at work, see exercise 9 at the end of Chapter 32
and its solution in Appendix D; it's similar to the pizza shop example. We've focused
on inheritance in this book because that is the main tool that the Python language itself
provides for OOP. But, in practice, composition may be used as much as inheritance
as a way to structure classes, especially in larger systems. As we've seen, inheritance
and composition are often complementary (and sometimes alternative) techniques.
'''
if __name__ == '__main__':
import sys
obj = Uppercase(open('trispam.txt'), sys.stdout)
obj.process()
# print to file
prog = Uppercase(open('trispam.txt'), open('trispamup.txt', 'w'))
prog.process()
htmlize = Uppercase(open('trispam.txt'), HTMLize())
htmlize.process()
| true |
35739c614d955ff51bc8013a63450ae242870584 | godsonezeaka/Repository | /PythonApp/stringFunctions.py | 854 | 4.375 | 4 | # String functions
myStr = 'HelloWorld'
# Capitalize
print(myStr.capitalize())
# Swap case
print(myStr.swapcase())
# Get length
print(len(myStr))
# Replace
print(myStr.replace('World', 'Everyone'))
#Count - allows you to count the number of occurrences of a substring in a given string
sub = 'l'
print(myStr.count(sub))
# Starts with and ends with
print(myStr.startswith('Hello'))
print(myStr.endswith('World'))
# Split to list
print(myStr.split())
# Find
print(myStr.find('e'))
print(myStr.find('z')) # Returns -1 if character not found
# Index
print(myStr.index('e')) # Same with a find but less safe because it gives error when char cant be found
# For example, print(myStr.index('x')) will give an error
# Is all alphanumeric
print(myStr.isalnum())
# Is all alphabetic
print(myStr.isalpha())
# Is all numeric
print(myStr.isnumeric())
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.