blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
32a4459d5520da39a4a787015d390413c0725cc8 | cclauss/algorithms-data-structures | /linkedListMain.py | 2,524 | 3.890625 | 4 | """Implement Singly Linked List problems.
"""
__author__ = 'Xavier Collantes'
from LinkedList import Node
import copy
def main():
# Build lists
list_head = Node('genesis')
ptr = list_head
for b in range(50):
ptr.next = Node(b)
ptr = ptr.next
# Copy and create circular list
list_cir = copy.deepcopy(list_head)
cir_ptr = list_cir
while cir_ptr.next is not None:
cir_ptr = cir_ptr.next
cir_ptr.next = list_cir
#p(list_cir) # 1 Infinity Loop.... Cupertino California
# Check if linked list is circular.
print('CIR? %s' % is_circular(list_cir))
print('TO REVERSE: ')
p(list_head)
print('IN REVERSE: ')
p(Reverse(list_head))
print('Nth to the Last')
print(NthToLast(15, list_head))
def Reverse(in_head):
"""Reverse a linked list given a head.
Waaaay better answer that keeps fixed space.
"""
head = copy.deepcopy(in_head)
current = head
prev = None
next = None
while current:
next = current.next
current.next = prev
prev = current
current = next
return prev
def NthToLast(n, head):
"""Return the nth to last node value.
n: Nth to last node.
head: First node of linked list.
Return: Contents of last to Nth node.
"""
current = head
scout = current
for i in range(n - 1):
if scout.next == None:
return scout.data
else:
scout = scout.next
while scout.next:
current = current.next
scout = scout.next
return current.data
def reverseBad(head):
"""Reverse a linked list given a head.
Sub-par answer since this creates an intermediary linked
list.
"""
if head.data:
out_list = Node(head.data)
else:
return 'Error'
hptr = head
optr = out_list
print('head: ', head)
print('olist: ', out_list)
while hptr.next:
temp_node = Node(hptr.next.data)
temp_node.next = optr
optr = temp_node
hptr = hptr.next
print('optr: ', optr)
return optr
def is_circular(in_head):
head = copy.deepcopy(in_head)
p1 = head
p2 = head.next
while p2.next and p2.next.next is not None:
print('P1: %s' % p1.data)
print('P2: %s\n' % p2.data)
if p1 == p2:
print('Correctumundo: P1 %s P2 %s' % (p1.data, p2.data))
return True
else:
p1 = p1.next
p2 = p2.next.next
return False
def p(list_head):
"""Printing for linked lists.
"""
while list_head.next != None:
print(list_head.data, end=' -> ')
list_head = list_head.next
print(list_head.data, end=' -> None\n')
if __name__ == '__main__':
main()
|
1e806a48342d1deb558652a9a43675927201fd64 | pk5280/Python | /hr_TimeConversion.py | 385 | 3.578125 | 4 | def timeConversion(s):
t = s.split(':')
if s[-2:] == 'PM':
if t[0] != '12':
t[0] = str(int(t[0]) + 12)
else:
t[0] = '12'
else:
if t[0] == '12':
t[0] = '00'
newtime = ':'.join(t)
return str(newtime[:-2])
if __name__ == '__main__':
s = '12:24:54PM'
print('12:24:54PM')
print(timeConversion(s)) |
521485e1fadfa376a6242d603349078b866dbc88 | kiyoxi2020/leetcode | /code/leetcode-239.py | 1,228 | 3.921875 | 4 | '''
leetcode 239. 滑动窗口最大值
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sliding-window-maximum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
n = len(nums)
out = []
queue = collections.deque()
for i in range(k):
while(queue and nums[queue[-1]]<=nums[i]):
queue.pop()
queue.append(i)
out.append(nums[queue[0]])
for i in range(k, n, 1):
while(queue and queue[0]<i-k+1):
queue.popleft()
while(queue and nums[queue[-1]]<=nums[i]):
queue.pop()
queue.append(i)
out.append(nums[queue[0]])
return out
|
01b1090b01fa027571889fe82558817034faffc9 | Hdwig/Math | /Lesson_3.2.1.py | 368 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
a = 10
a2 = a ** 2
b = 2
b2 = b ** 2
xm = []
xp = []
yp = []
ym = []
for i in np.linspace(-10, 10, 1000):
x1 = i
xp.append(x1)
yp.append(math.sqrt(b2 - (x1 ** 2 * b2) / a2))
ym.append(-math.sqrt(b2 - (x1 ** 2 * b2) / a2))
plt.plot(xp, yp)
plt.plot(xp, ym)
plt.xlabel("x")
plt.ylabel("y")
|
a7b43ceb9fa210b1a053261cc7d103f184b83378 | SeemaSP/Python | /Day1/q2.py | 253 | 3.9375 | 4 | x=int(input('Enter rwo number:'))
y=int(input('Enter column number:'))
Matrix = [[0 for column in range(y)] for row in range(x)]
for i in range(len(Matrix[x-1])):
Matrix=[[i*a for a in range(y)] for i in range(x)]
print(Matrix)
|
78a1fdacdbb098827e122587069bf9cb7db27e4a | OGluffy/maryvillework | /mad-libber.py | 510 | 3.921875 | 4 | def main():
print('Madlib Maker')
def printRowRowRowYourBoat(punctuation):
print('{0}, {0}, {0} your boat, gently down the {1}, {2} '.format(verb, place, punctuation))
place = input('place: ')
verb = input('verb: ')
adverb = input('adverb: ')
verb2 = input('verb2: ')
printRowRowRowYourBoat('.')
print('{0}, {0}, {0}, {0}.'.format(adverb))
printRowRowRowYourBoat('!')
print('life is but a {0}'.format(verb2))
print()
main()
|
5958da59fb243dbb1fc1a512ddc4ba18bed94328 | Shubham-Nimase/My-Python-Programs | /Assignment 07/Q.01.py | 1,276 | 4.15625 | 4 | # Write a program which contains one class named as BookStore.
# BookStore class contains two instance variables as Name ,Author.
# That class contains one class variable as NoOfBooks which is initialise to 0.
# There is one instance methods of class as Display which displays name , Author and number of
# books.
# Initialise instance variable in init method by accepting the values from user as name and author.
# Inside init method increment value of NoOfBooks by one.
# After creating the class create the two objects of BookStore class as
# Obj1 = BookStore(“Linux System Programming”, “Robert Love”)
# Obj1.Display()
# # Linux System Programming by Robert Love. No of books : 1
# Obj2 = BookStore(“C Programming”, “Dennis Ritchie”)
# Obj2.Display()
# # C Programming by Dennis Ritchie. No of books : 2
class BookStore:
NoOfBooks = 0
def __init__(self,Name,Author):
self.Name = Name
self.Author = Author
BookStore.NoOfBooks = BookStore.NoOfBooks + 1
def Display(self):
print(self.Name,"by",self.Author,". No of Books :",self.NoOfBooks)
def main():
obj1 = BookStore("Linux System Programming","Robert Love")
obj1.Display()
obj2 = BookStore("C Programming","Dennis Ritchie")
obj2.Display()
if __name__=="__main__":
main() |
54cbb8174917dd7451419d5f7c5ed9d07ed2b262 | vothin/code | /代码/day2-3/A.ForDemo.py | 274 | 3.953125 | 4 | '''
for 变量 in 数列:
循环体
一条或者多条语句
else:
循环体
Python for循环可以 "遍历" 任何序列的项目,如一个列表或者一个字符串。
'''
str1 = 'Hello World'
for i in str1:
print(i, end='') |
fe205b6dfc9cfb715c0174afd84f4dd855da45c3 | eodnjs467/python | /python_basic/python_6day.py | 3,011 | 3.71875 | 4 | ##함수
## def 함수명(매개변수):
## 수행할 문장1
## 수행할 문장2 ...
def add(a, b):
return a + b
a, b = 3, 4
c = add(a, b)
print(c)
def add(a, b): ## a,b 는 매개변수
return a+b
print(add(3, 4)) ## 3, 4 는 인수
## 일반적인 함수
def add(a, b):
result = a+b
return result
def say():
return 'Hi'
a = say()
print(a)
##결괏값이 없는 함수
def add(a, b):
print("%d, %d 의 합은 %d 입니다," % (a, b, (a+b)))
add(3, 5)
a = add(3, 4)
print(a)
def say():
print('Hi')
say()
def add(a, b):
return a+b
result = add(a=3, b=7)
print(result)
## 여러 개의 입력값을 받는 함수 만들기
## def 함수이름(*매개변수):
## 수행할 문장 ...
def add_many(*args): ## *을 붙이면 입력값을 모두 모아서 튜플로 만들어 줌.
result = 0
for i in args:
result = result + i
return result
result = add_many(1, 2, 3)
print(result)
result = add_many(1,2,3,4,5,6,7,8,9,10)
print(result)
def add_mul(choice, *args):
if choice == "add":
result = 0
for i in args:
result = result + i
elif choice == "mul":
result = 1
for i in args:
result = result * i
return result
result = add_mul('add', 1, 2, 3, 4, 5)
print(result)
result = add_mul('mul', 1, 2, 3, 4, 5)
print(result)
## 키워드 파라미터 -> 매개변수 앞에 ** 붙이면 딕셔너리가 되고,
# key=value형태의 결괏값이 딕셔너리에 저장됨.
def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(a=1)
## 함수 리턴값은 언제나 하나!
def add_and_mul(a, b):
return a+b, a*b
result = add_and_mul(3, 4)
result
result1, result2 = add_and_mul(3, 4)
result1, result2
## return의 다른 쓰임새 return 단도긍로 써서 함수를 빠져나갈 수 있음.
def say_nick(nick):
if nick=="바보":
return
print("나의 별명은 %s 입니다." % nick)
say_nick('야호')
say_nick('바보')
## 매개변수에 초깃값 미리 설정하기
def say_myself(name, old, man=True):
print("나의 이름은 %s 입니다." % name)
print("나이는 %d 살 입니다." % old)
if man:
print("남자입니다.")
else:
print("여자입니다.")
say_myself("박응용", 27)
def say_intro(name, old, sex):
print("나의 이름은 %s 입니다." % name)
print("나이는 %d 살 입니다." % old)
if sex == 0:
print("남자입니다.")
else:
print("여자입니다.")
say_intro("대원", 25, 0)
a=1
def vartest(a):
a = a+1
vartest(a)
print(a)
## 함수 안에서 함수 밖의 변수를 변경하는 법
## return 사용하기
a = 2
def vartest(a):
a = a+1
return a
a = vartest(a)
print(a)
## global 명령어 사용하기
a = 1
def vartest():
global a
a = a+1
vartest()
print(a)
## lambda 함수
## lambda 매개변수1, 매개변수2, ... : 매개변수를 이용한 표현식
add = lambda a, b : a+b
result = add(3, 4)
print(result) |
a008c090384e7517ef0068aa6e8c81cccfabad0c | sanjanabalakrishna/Python-Scripts | /BasicPythonPractice/AverageWordLength.py | 422 | 4.125 | 4 | inp = open(input('Enter a file:'))
lst = []
sum = 0
#Create a list of the unique words in the file
for line in inp:
words = line.strip().split()
for word in words:
if word not in lst:
lst.append(word)
#Count number of words
Cnt = len(lst)
#Add the lengths of each word
for wrd in lst:
sum += len(wrd)
print('Average word length in the file is:',round(sum/Cnt))
|
0c3b2b2858016cf1737f5db49e6c6795c0889496 | abhisheknm99/APS-2020 | /54-Prime_factors.py | 241 | 3.828125 | 4 | import math
def prime_fact(n):
f=[]
flag=0
while(n%2==0):
flag=1
n//=2
if flag==1:
f.append(2)
for i in range(3,int(math.sqrt(n)+1)):
if n%i==0:
f.append(i)
n//=i
if n>2:
f.append(n)
return f
n=42
print(prime_fact(n)) |
eddb02806f9e3aab3140f01664670b96dda6ecdc | learninghadoop2/book-examples | /ch9/streaming/wc/python/reduce.py | 354 | 3.59375 | 4 | #!/bin/env python
import sys
count = 1
current = None
for word in sys.stdin:
word = word.strip()
if word == current:
count += 1
else:
if current:
print "%s\t%s" % (current.decode('utf-8'), count)
current = word
count = 1
if current == word:
print "%s\t%s" % (current.decode('utf-8'), count)
|
0f50ccad45d91384797355e5f82dc87bf3ea26f5 | anujvyas/Data-Structures-and-Algorithms | /Data Structures/3. Linked List/reverse_sll.py | 758 | 4.25 | 4 | # Reverse a given linkedlist
from singly_linked_list import Node, LinkedList
def reverseLinkedList(head):
# If linkedlist is empty
if head == None:
print('Cannot perform operation as linkedlist is empty!')
return head
# If linkedlist has only one node
if head.next == None:
return head
# If linkedlist has more than one nodes
front = head.next.next
back = head
head = head.next
back.next = None
while front != None:
head.next = back
back = head
head = front
front = front.next
head.next = back
return head
if __name__ == '__main__':
l = LinkedList()
l.append_node("A")
l.append_node("B")
l.append_node("C")
l.traverse()
l.head = reverseLinkedList(l.head)
l.traverse() |
5f3bf095e0427c0e2ab27f0f72c9baa3c88c542b | sarbar2002/hw2python | /main.py | 1,639 | 4.21875 | 4 | # Author: Sarthak Singh sxs6666@psu.print
#grade1 = (input(f"Enter your course 1 letter grade: "))
#credit1 = (input(f"Enter your course 1 credit: "))
def getGradePoint(grade):
if grade == "A":
return 4.0
elif grade == "A-":
return 3.67
elif grade == "B+":
return 3.33
elif grade == "B":
return 3.0
elif grade == "B-":
return 2.67
elif grade == "C+":
return 2.33
elif grade == "C":
return 2.0
elif grade == "D":
return 1.0
else:
return 0.0
def run():
grade_input1 = (input("Enter your course 1 letter grade: "))
credit_input1 = (input("Enter your course 1 credit: "))
print(f"Grade point for course 1 is: {getGradePoint(grade_input1)}")
grade_input2 = (input("Enter your course 2 letter grade: "))
credit_input2 = (input("Enter your course 2 credit: "))
print(f"Grade point for course 2 is: {getGradePoint(grade_input2)}")
grade_input3 = (input("Enter your course 3 letter grade: "))
credit_input3 = (input("Enter your course 3 credit: "))
print(f"Grade point for course 3 is: {getGradePoint(grade_input3)}")
GPA = (getGradePoint(grade_input1) * int(credit_input1) + getGradePoint(grade_input2) * int(credit_input2) + getGradePoint(grade_input3) * int(credit_input3)) / (int(credit_input1) + int(credit_input2) + int(credit_input3))
print(f"Your GPA is: {GPA}")
if __name__ == "__main__":
run()
#grade2 = (input(f"Enter your course 2 letter grade: "))
#credit2 = (input(f"Enter your course 2 credit: "))
#GPA = (gradepoint1 * credit1 + gradepoint2 * credit2 + gradepoint3 * credit3) / (credit1 + credit2 + credit3) |
ea8d6792e7f66a49eb58d214521aefd94d2b4c64 | sherutoppr/coding-python | /015_3sum.py | 1,092 | 3.640625 | 4 | '''Given an array nums of n integers, are
there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.'''
def threeSum(nums):
res = []
nums.sort()
i = 0
while i < len(nums):
j = i + 1
k = len(nums) - 1
while j < k:
curr_sum = nums[i] + nums[j] + nums[k]
if curr_sum == 0:
res.append([nums[i], nums[j], nums[k]])
k -= 1
while k > j and nums[k] == nums[k + 1]:
k -= 1
j += 1
while j < k and nums[j] == nums[j - 1]:
j += 1
elif curr_sum > 0:
k -= 1
while k > j and nums[k] == nums[k + 1]:
k -= 1
else:
j += 1
while j < k and nums[j] == nums[j - 1]:
j += 1
i += 1
while i < len(nums) - 2 and nums[i] == nums[i - 1]:
i += 1
return res
nums = [-1, 0, 1, 2, -1, -4]
print(threeSum(nums)) |
35a7175fbb7cee9db556c9e7b32655e6fa4a5f72 | ksmatsuda002960/sample | /python/basic/sqlite/ex1.py | 907 | 3.78125 | 4 | # -*- coding: utf-8
import sqlite3
# データベース開く
db = sqlite3.connect('C:/github/sample/python/sqlite/sarvant.db')
c = db.cursor()
# テーブル作成
c.execute('create table artoria (name text, atk int, hp int)')
# データ追加(レコード登録)
sql = 'insert into artoria (name, atk, hp) values (?,?,?)'
data = [('artoria', 11221, 15150),
('artoria alter', 10248, 11589),
('artoria lily', 7726, 10623),
('artoria lancer', 10995, 15606),
('artoria lancer alter', 9968, 11761),
('artoria swimwear', 11276, 14553),
('artoria santa alter', 9258, 11286),
('mystery heroine x', 11761, 12696),
('mystery heroine x alter', 11113, 14175)]
c.executemany(sql, data)
# コミット
db.commit()
# データ(レコード)取得
sql = 'select * from artoria'
for row in c.execute(sql):
print(row)
# クローズ
db.close()
|
f79980ebe43b471b530314e7c8635763786b3d73 | coding-regina/python_ds | /Guia06_NumPy/Ej_07.py | 787 | 3.78125 | 4 | import numpy as np
# 7. Crear una matriz de 10x10 con 1 en los bordes y 0 en el interior (con rangos de
# índices).
# 8. Crear una matriz de 5x5 con valores en los renglones que vayan de 0 a 4.
array08 = np.random.radint(0, 5, (5, 5))
print (array08)
print('')
# 10. Crear una matriz de 20x20 de valores aleatorios entre 1 y 100, luego indicar su
# media, su mediana, su moda y el desvío estándar. Los valores que den como
# resultado flotantes deben tener como máximo 2 decimales.
array10a = np.random.randint(0, 101, (20,20))
print(array10a)
print('')
# 14. Crear un arreglo de 4 elementos de entre 0 y 10, informar la cantidad de
# elementos que tiene y también cuántos bytes ocupa el arreglo.
array14 = np.random.randint(0, 11, (1,4))
print(array14)
|
7b42b5d28f9a9489f5390387316f3d07fb7f79e1 | bturcott/udemy | /s3_l26_files.py | 295 | 4.3125 | 4 | #Files Lesson
#Section 3 Lecture 26
#create simple text file named test_file.txt
f = open("test_file.txt")
#print f.read()
#Returns to top of file
f.seek(0)
#print f.read()
f.seek(0)
#print f.readlines()
#readlines stores all of the data in memory
for line in open('test_file.txt'):
print line |
7966d8bd5e38bc46d899c4a75cdde67a5c5aa8ac | 27hope/snehu | /checkalphbhet.py | 131 | 3.984375 | 4 | alph=str(input())
if((alph>='a' and alph<='z') or (alph>='A' and alph<='Z')):
print("Alphabet")
else:
print("No")
|
2e4fa087a05085487597ccb6c41b435bc46cdcab | bomendez/bomendez.github.io | /Checkers/moves.py | 2,042 | 3.875 | 4 | '''
Bo Mendez
This class handles possible moves in the game.
'''
class Moves:
'''
Class -- Moves
Responsible for maintaining the pieces.
Attributes:
start_location -- the location of a piece before a move
end_location -- the location of a piece after a move
capture_move -- whether a move is a capture move or not
capture_location -- a list containing the location of a piece
that can be captured
Methods:
'''
def __init__(
self, start_location, end_location, capture_move, capture_location):
'''
Constructor -- creates a new instance of Moves
Parameters:
start_location -- the location of a piece before a move, as a [row, col]
end_location -- the location of a piece after a move, as a [row, col]
capture_move -- whether a move is a capture move or not, a list of [row, col]
capture_location -- the [row, col] of the capture location
'''
self.start_location = start_location
self.end_location = end_location
self.capture_move = capture_move
self.capture_location = capture_location
def __repr__(self):
'''
Method -- __repr__
Creates a string representation of the Move
Parameter:
self -- The current Move object
Returns:
A string representation of the Move.
'''
return "start: {}, end: {}, capture: {}".format(
self.start_location, self.end_location, self.capture_move)
def get_start_end(self):
'''
Method -- get_start_end
Will get the start and end location of a Move
Parameter:
self -- The current Move object
Returns:
A list containing the start and end location of the Move
'''
return [self.start_location, self.end_location] |
f0d6ccb7b7305f682599112e2d44ffcfcd370a6e | AlexClowes/advent_of_code | /2020/10/use_all.py | 424 | 3.515625 | 4 | def main():
with open("adapters.txt") as f:
adapters = sorted(int(line.strip()) for line in f)
diffs = (a2 - a1 for a1, a2 in zip(adapters[:-1], adapters[1:]))
count_1 = adapters[0] == 1
count_3 = 1 + (adapters[0] == 3)
for d in diffs:
if d == 1:
count_1 += 1
elif d == 3:
count_3 += 1
print(count_1 * count_3)
if __name__ == "__main__":
main()
|
e8b49b203600e99e25cf8311c70a5446753ce095 | evcodes/Google_Advanced_Programming | /stringCompression.py | 1,311 | 3.75 | 4 | def decompress(s):
characters = []
numbers = []
brackets = []
final_string = ""
i = 0
while i < len (s):
if s[i] != "]":
if (s[i].isalpha()):
characters.append(s[i])
elif s[i].isdigit():
j = i
num = ""
j = s.index("[", i)
numbers.append(int (s[i:j]))
i = j-1
# in this case we need to keep track of open brackets.
elif s[i] == "[":
brackets.append(s[i])
# running into a closing bracket
elif s[i] == "]":
# if we have seen more than opening bracket,
# build the final string iteratively
if len(brackets) > 1 :
temp = ("".join(characters) * numbers.pop())
characters = []
characters.append(temp)
brackets.pop()
# only one more opening bracket, final string
elif len(brackets) == 1:
final_string += ("".join(characters) * numbers.pop())
characters = []
i+=1
return final_string
print(decompress('3[a]'))
print(decompress('3[abc]4[ab]c'))
print(decompress('4[3[a]b]'))
print(decompress('12[ab]')) |
6a9692b82ad903e3b9a082e2e2cccf45c30f4af1 | KenjaminButton/runestone_thinkcspy | /6_functions/6.2.functions_that_return_values.py | 956 | 4.75 | 5 | # 6.2. Functions that Return Values
'''
Most functions require arguments, values that control how the function does its job. For example, if you want to find the absolute value of a number, you have to indicate what the number is. Python has a built-in function for computing the absolute value:
'''
print(abs(5))
print(abs(-5))
print("\n--------------------")
# Power function
import math
print(math.pow(2, 3))
print(math.pow(7, 4))
'''
Note:
Of course, we have already seen that raising a base to an
exponent can be done with the ** operator.
'''
print("\n--------------------")
print(max(7, 11))
print(max(4, 1, 17, 2, 12))
print(max(3 * 11, 5 ** 3, 512 - 9, 1024 ** 0))
print("\n--------------------")
def square(x):
y = x * x
return y
to_square = input("Enter an integer: ")
to_square_int = int(to_square)
result = square(to_square_int)
print("The result of", to_square_int, "squared is", result)
print("\n--------------------")
|
111a5cfb974cdc471167c6547917c0892001e69d | ConquerorWolverine/Data_analysis | /Experiment1/list.py | 173 | 3.6875 | 4 | list1 = ['alex', 'egon', 'yuan', 'wusir', '666']
list1[4] = '999'
print(list1[4])
print(list1.index('yuan'))
list1.reverse()
print(list1[0])
print(list1[1])
print(list1[2])
|
8cb90942d4c664fcc99c68398868b0999f67a79f | Nooralwachi/adventofcode | /day2_password_part2.py | 446 | 3.609375 | 4 | def password_part2(file):
line=[]
wrong = 0
correct =0
f = open(file, "r")
line.append(f.read())
values=line[0].split("\n")
for value in values:
pw=value.split(" ")
letter= pw[1][0]
passw= pw[2]
min,max = pw[0].split("-")
if (letter ==passw[int(min)-1] or letter ==passw[int(max)-1]) and not (letter ==passw[int(min)-1] and letter ==passw[int(max)-1]):
correct +=1
print("correct",correct)
password_part2("input2.txt")
|
7dbaea82d02958f7f79320e9bc50a8b32af40225 | LeoImenes/SENAI | /1 DES/FPOO/Exercicios5/9.py | 62 | 3.578125 | 4 | a = input("Digite uma frase qualquer: ")
print(a.count("de")) |
4a897d763f106ad45453ef0589e932f1ddaf0101 | sreekanth-s/python | /old_files/average_of_list.py | 474 | 4.25 | 4 | ##
## A program which takes a series of inputs to add them to a list
## and give out the average of the numbers.
##
number_of_items=int(input("Enter a positive number of items that the list contains: "))
num_list=[]
sum=0
for i in range(number_of_items):
# print(i)
num_list.append(int(input("Enter the number of the list: ")))
sum=sum+(num_list[i])
print(round( (sum / len(num_list)), 3) , "is the average of all numbers in the list.")
#print(num_list)
|
e1b8c70d8f4fff88ea6efc44b8b8cb49dbaeee9e | dollarkid1/pythonProjectSemicolon | /app/bank/Bank.py | 1,122 | 3.828125 | 4 | class Bank:
accounts = []
def __init__(self, bank_name, pin):
self.pin = pin
self.bank_name = bank_name
def register(self, first_name, last_name, date_of_birth, phone_number):
pass
def login(self, account_number, pin):
pass
def deposit(self, balance, amount):
if amount > 0:
self.balance += amount
def withdraw(self, balance, pin, amount):
pass
if self.pin == pin:
if balance >= amount:
balance -= amount
else:
print("Invalid Pin")
def transfer(self, balance, pin, amount):
if self.pin == pin:
if balance >= amount:
balance -= amount
else:
print("invalid Pin")
def balance(self, balance, pin):
if self.pin == pin:
return self.balance()
else:
print("Invalid Pin")
def set_pin(self, pin):
self.pin = pin
def get_pin(self):
return self.pin
def change_pin(self, old_pin, new_pin):
if old_pin == self.pin:
self.pin = new_pin
|
445f3d9502e3ea5edb9a4f0fa4f132d5fec05606 | CAWilson94/advent_adventures_17 | /december_24/input_file_creator.py | 187 | 3.5 | 4 | def input_from_file(file_name):
""" getting output from file input """
file = open(file_name, "r")
output = None # use input as needed ...
file.close()
return output
|
538e683d6a0172584d0d26be823ecacd73ca9eb2 | drliebe/python_crash_course | /ch7/dream_vacation.py | 376 | 3.71875 | 4 | prompt = 'Where would you go on a dream vacation? '
prompt += "\n(enter 'quit' to stop): "
destinations = []
active = True
while active:
destination = input(prompt)
if destination == 'quit':
active = False
else:
destinations.append(destination)
print('\nDestinations of a Dream Vacation:')
for destination in destinations:
print(destination) |
e7714227efcd1fd44608e9afbb51ffb40f7d3cd1 | hujianli94/Python-code | /34.数据结构和算法/02.排序与搜索/01.冒泡排序.py | 446 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/10/28 14:44
# filename: 01.冒泡排序.py
def bubbleSort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
alist[i], alist[i + 1] = alist[i + 1], alist[i]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist) # [17, 20, 26, 31, 44, 54, 55, 77, 93]
|
35d228e40e65794af63930dd47922a996ef622bc | nramiscal/GitDemo | /basic13.py | 2,005 | 4.25 | 4 | '''
Shift Array Values Left
Given an array, move all values forward (to the left) by one index, dropping the first value and leaving a 0 (zero) value at the end of the array.
[1,2,3,4,5]
[2,3,4,5,5]
[2,3,4,5,0]
'''
def shiftArrayValsLeft(arr):
for i in range(len(arr)-1):
arr[i] = arr[i+1]
arr[len(arr)-1] = 0
return arr
print(shiftArrayValsLeft([1,2,3,4,5]))
'''
Square Array Values
Square each value in a given array, returning that same array with changed values.
'''
def squareArrayVals(arr):
for i in range(len(arr)):
arr[i] *= arr[i]
return arr
# print(squareArrayVals([1,2,3,4,5]))
'''
Return Odds Array 1-255
Create an array with all the odd integers between 1 and 255 (inclusive).
'''
def returnOddsArray1To255():
# newarr = []
# for i in range(1,256,2):
# newarr.append(i)
#
# return newarr
return list(range(1,256,2))
# print(returnOddsArray1To255())
'''
Print Max, Min, Average Array Values
Given an array, print the max, min and average values for that array.
'''
def printMaxMinAverageArrayVals(arr):
min = arr[0]
max = arr[0]
sum = 0
# for i in range(len(arr)):
# print(arr[i])
for val in arr:
if val < min:
min = val
elif val > max:
max = val
sum += val
return {
"max": max,
"min": min,
"avg": sum/len(arr)
}
# return f"min: {min}, max: {max}, avg: {sum/len(arr)}"
# print(printMaxMinAverageArrayVals([1,2,3,4,5]))
'''
Reverse an Array
'''
def reverseArray(arr):
i = 0
while i < len(arr)//2:
temp = arr[len(arr)-1-i]
arr[len(arr)-1-i] = arr[i]
arr[i] = temp
i += 1
return arr
# left = 0
# right = len(arr)-1
#
# while left < right:
# temp = arr[left]
# arr[left] = arr[right]
# arr[right] = temp
# left += 1
# right -= 1
#
# return arr
# print(reverseArray([1,2,3,4,5,6,7]))
|
b824af3176b43a128115f1dd8e31b07f86dc5327 | girishpillai17/class-work | /censor2.py | 352 | 3.828125 | 4 | def censor(text, word):
text = text.lower()
word = word.lower()
words = text.split()
star = "*" * len(word)
for badword in words:
if badword == word:
element = words.index(badword)
words.insert(element, star)
words.remove(badword)
result = " ".join(words)
print(result)
censor("get the fuck out of here", "fuck")
|
ed4959d2064a6e19ee6b7a49e026a50dfdfacb61 | sanika2106/if-else | /14link.py | 280 | 4.5 | 4 | # program to check triangle validity when angles are given
angle1=int(input("enter the number:"))
angle2=int(input("enter the number:"))
angle3=int(input("enter the number:"))
if(angle1+angle2+angle3==180):
print("triangle is valid")
else:
print("triangle is invalid")
|
f598d5ba53fabd9a0c420916e02f4438c41d8c81 | dls-controls/pymalcolm | /malcolm/core/future.py | 2,973 | 3.546875 | 4 | class Future:
"""Represents the result of an asynchronous computation.
This class has a similar API to concurrent.futures.Future but this
simpler version is not thread safe"""
# Possible future states (for internal use).
RUNNING = "RUNNING"
# Task has set the return or exception and this future is filled
FINISHED = "FINISHED"
def __init__(self, context):
"""
Args:
context (Context): The context to run under
"""
self._context = context
self._state = self.RUNNING
self._result = None
self._exception = None
def done(self):
"""Return True if the future finished executing."""
return self._state == self.FINISHED
def __get_result(self):
if self._exception:
raise self._exception
else:
return self._result
def result(self, timeout=None):
"""Return the result of the call that the future represents.
Args:
timeout: The number of seconds to wait for the result if the future
isn't done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
Raises:
TimeoutError: If the future didn't finish executing before the given
timeout.
Exception: If the call raised then that exception will be
raised.
"""
if self._state == self.RUNNING:
self._context.wait_all_futures([self], timeout)
return self.__get_result()
def exception(self, timeout=None):
"""Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
TimeoutError: If the future didn't finish executing before the given
timeout.
"""
if self._state == self.RUNNING:
self._context.wait_all_futures([self], timeout)
return self._exception
# The following methods should only be used by Task and in unit tests.
def set_result(self, result):
"""Sets the return value of work associated with the future.
Should only be used by Task and unit tests.
"""
self._result = result
self._state = self.FINISHED
def set_exception(self, exception):
"""Sets the result of the future as being the given exception.
Should only be used by Task and unit tests.
"""
assert isinstance(exception, Exception), f"{exception!r} should be an Exception"
self._exception = exception
self._state = self.FINISHED
|
1c983cc2b96cfcecf2a493658ca75f4545956da9 | siva4646/Private-Projects | /Python_Course/PROJECTS/Tic-Tac-Toe/Topics/Any and all/Prime numbers/main.py | 191 | 3.59375 | 4 | import math
i = 1
prime_numbers = []
for x in range(1, 1001):
if i % x == 1:
prime_numbers.append(x)
else:
prime_numbers.append(i)
i += 1
print(prime_numbers) |
2b71bd7f3a017321e71b9ef4dc96be0c1f8e8e9b | zjw-hunter/CFAB | /Module 3/Loops.py | 689 | 3.84375 | 4 |
myBool = True
while( myBool ):
print( "In the loop ")
myBool = False
counter = 0
print("\n\n\nStarting while loop")
while( counter < 10):
print("At count: ", counter)
counter += 1
print("End while Loop \n\n\n")
print("Starting for Loop")
for i in range(0, 10):
print("At value: ", i)
print( "End for loop \n\n\n")
myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Starting enhanced for loop")
for element in myArray:
print("At Value: ", element)
print("End of enhanced for loop")
myDict = { 0 : 'zero', 1 : 'one', 2: 'two' }
print("\n\n\nStarting dictonary loop")
for key in myDict:
print("The Key: ", key, " corresponds to value: ", myDict[key])
|
844d60958f6e8cdad9b4e5e1470b2db438a7ea4c | justenpinto/coding_practice | /interviewcake/stack/bracket_validator.py | 451 | 3.609375 | 4 | def is_valid_code(string):
BRACKETS = {'(': ')', '{': '}', '[': ']'}
CLOSERS = set(BRACKETS.values())
stack = []
for i in range(len(string)):
if string[i] in BRACKETS:
stack.append(string[i])
elif string[i] in CLOSERS:
if not stack:
return False
opener = stack.pop()
if BRACKETS[opener] != string[i]:
return False
return stack == [] |
f56c63e1823b2748467f0112390caeb45f3495dc | vaibhavg12/exercises | /python/exercises/arrays/house_robber.py | 1,712 | 3.5625 | 4 | """
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that
adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were
broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of
money you can rob tonight without alerting the police.
"""
def max_robbed_naive(houses, start=0, cache=None):
if len(houses) == 0:
return 0
if cache is None:
cache = {}
if start in cache:
return cache[start]
if start + 2 >= len(houses):
val = max(houses[start:])
else:
val = max(houses[start] + max((max_robbed_naive(houses, i, cache) for i in xrange(start + 2, len(houses)))),
max((max_robbed_naive(houses, i, cache) for i in xrange(start + 1, len(houses)))))
cache[start] = val
return val
def max_robbed(houses, lo=0, hi=None):
hi = hi or len(houses)
prev_yes, prev_no = 0, 0
for i in xrange(lo, hi):
prev_no, prev_yes = max(prev_yes, prev_no), houses[i] + prev_no
return max(prev_yes, prev_no)
def circular_max_robbed(houses):
if len(houses) == 1:
return houses[0]
return max(max_robbed(houses, 0, len(houses) - 1), max_robbed(houses, 1, len(houses)))
if __name__ == '__main__':
print max_robbed([1, 2])
print max_robbed([1, 1, 1])
print max_robbed([5, 1, 2, 6, 3])
print max_robbed([1, 5, 2, 6, 3, 8, 1, 9, 3, 2, 3, 6])
print max_robbed([2, 3, 2])
print circular_max_robbed([1, 1, 1])
|
2f2a9014c050cbd4be949ff62a1776aacdc2ad9e | calebkress/practice-python-scripts | /precourse_wk2d1/multicomb.py | 440 | 4.03125 | 4 | # A tool for calculating multi-step combinations
import math
steps = input("How many steps of combination are there? ")
result = 1
for x in range(0, steps):
n = input("What is your n value for step " + str(x + 1) + "? ")
k = input("What is your k value for step " + str(x + 1) + "? ")
comb = math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
result = result * comb
print("The result is " + str(result) + ".")
|
4a1c9faafefaf1228729492ec37f261ded948b71 | Niceblack/MATI_5_061_062_Examples | /Perl_Python/functional/sort.py | 170 | 3.703125 | 4 | a = range(10)
def compare(x,y):
return cmp(x%2, y%2)
print sorted(a, cmp=compare)
print sorted(a, cmp=lambda x,y: cmp(x%2, y%2))
print sorted(a, key=lambda x: x%2)
|
ec3f9918f9b302503865315475afcffef0825400 | martialmechie/project-euler-python-code | /1-25/19/sundays.py | 435 | 3.96875 | 4 | """
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
import time
start_time = time.time()
import datetime
count =0
for year in range(1901,2001):
for month in range(1,13):
day =1
cache = datetime.date(year,month,day)
if cache.weekday() == 6:
count+=1
print count
print("--- %s ms ---" %int(round((time.time() - start_time)*1000)))
|
a6e7966901655a3d4e7f2079b258185d97702c8b | jedzej/tietopythontraining-basic | /students/barecki_andrzej/lesson_03_functions/L3_calculator.py | 2,305 | 3.96875 | 4 | def input_validation():
while True:
try:
print('Set real number:')
val = float(input())
break
except ValueError:
print('ValueError: Incorrect real number!')
return val
def add(add_var_1, add_var_2):
return add_var_1 + add_var_2
def sub(add_var_1, add_var_2):
return add_var_1 - add_var_2
def mul(add_var_1, add_var_2):
return add_var_1 * add_var_2
def div(add_var_1, add_var_2):
try:
div_val = add_var_1 / add_var_2
except ZeroDivisionError:
print('Error: ZeroDivisionError')
div_val = None
return div_val
def power(add_var_1, add_var_2):
return add_var_1 ** add_var_2
def print_result(result):
print("Result is equal: {0}".format(result))
def help_menu():
print("Welcome to good organized calculator:")
print("Press selected option:")
print("a - add")
print("s - subtract")
print("m - multiply")
print("d - divide")
print("p - power")
print("h,? - help")
print("q - QUIT")
def main():
"""Main program function"""
help_menu()
while True:
option = input()
if option == "a":
"""add operation"""
p1 = input_validation()
p2 = input_validation()
print_result(add(p1, p2))
elif option == "s":
"""subtract operation"""
p1 = input_validation()
p2 = input_validation()
print_result(sub(p1, p2))
elif option == "m":
"""MULTIPLY"""
p1 = input_validation()
p2 = input_validation()
print_result(mul(p1, p2))
mul(p1, p2)
elif option == "d":
"""DIVIDE"""
p1 = input_validation()
p2 = input_validation()
print_result(div(p1, p2))
elif option == "p":
"""POWER"""
p1 = input_validation()
p2 = input_validation()
print_result(power(p1, p2))
elif option == "h" or option == "?":
"""HELP"""
help_menu()
elif option == "q":
"""GOOD BYE"""
break
else:
print('Incorrect selected option!')
help_menu()
if __name__ == "__main__":
main()
|
aba40de027082fd5c9da4bda36928c10c6566bda | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/149_13.py | 3,479 | 4.53125 | 5 | Python | Dictionary creation using list contents
Sometimes we need to handle the data coming in the list format and convert
list into dictionary format. This particular problem is quite common while we
deal with Machine Learning to give further inputs in changed formats. Let’s
discuss certain ways in which this inter conversion happens.
**Method #1 : Using dictionary comprehension +zip()**
In this method, we use dictionary comprehension to perform the iteration and
logic part, the binding of all the lists into one dictionary and with
associated keys is done by zip function.
__
__
__
__
__
__
__
# Python3 code to demonstrate
# Dictionary creation using list contents
# using Dictionary comprehension + zip()
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
# using Dictionary comprehension + zip()
# Dictionary creation using list contents
res = {key: {'name': name, 'age': age} for key, name, age
in
zip(keys_list, nested_name, nested_age)}
# print result
print("The dictionary after construction : " + str(res))
---
__
__
**Output :**
> The original key list : [‘key1’, ‘key2’]
> The original nested name list : [‘Manjeet’, ‘Nikhil’]
> The original nested age list : [22, 21]
> The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’},
> ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}
>
>
>
>
>
>
**Method #2 : Using dictionary comprehension +enumerate()**
The similar task can be performed using enumerate function that was
performed by the zip function. The dictionary comprehension performs the task
similar as above.
__
__
__
__
__
__
__
# Python3 code to demonstrate
# Dictionary creation using list contents
# using dictionary comprehension + enumerate()
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
# using dictionary comprehension + enumerate()
# Dictionary creation using list contents
res = {val : {"name": nested_name[key], "age": nested_age[key]}
for key, val in enumerate(keys_list)}
# print result
print("The dictionary after construction : " + str(res))
---
__
__
**Output :**
> The original key list : [‘key1’, ‘key2’]
> The original nested name list : [‘Manjeet’, ‘Nikhil’]
> The original nested age list : [22, 21]
> The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’},
> ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
73fac8bad3590df56242a554816778cb06fca2a6 | Changxin-Liu/Python-Practice | /a2_files/prediction.py | 16,037 | 3.953125 | 4 | """
Prediction model classes used in the second assignment for CSSE1001/7030.
WeatherPrediction: Defines the super class for all weather prediction models.
YesterdaysWeather: Predict weather to be similar to yesterday's weather.
"""
__author__ = "Changxin Liu 45245008"
__email__ = "changxin.liu@uqconnect.edu.au"
from weather_data import WeatherData
class WeatherPrediction(object):
"""Superclass for all of the different weather prediction models."""
def __init__(self, weather_data):
"""
Parameters:
weather_data (WeatherData): Collection of weather data.
Pre-condition:
weather_data.size() > 0
"""
self._weather_data = weather_data
def get_number_days(self):
"""(int) Number of days of data being used in prediction"""
raise NotImplementedError
def chance_of_rain(self):
"""(int) Percentage indicating chance of rain occurring."""
raise NotImplementedError
def high_temperature(self):
"""(float) Expected high temperature."""
raise NotImplementedError
def low_temperature(self):
"""(float) Expected low temperature."""
raise NotImplementedError
def humidity(self):
"""(int) Expected humidity."""
raise NotImplementedError
def cloud_cover(self):
"""(int) Expected amount of cloud cover."""
raise NotImplementedError
def wind_speed(self):
"""(int) Expected average wind speed."""
raise NotImplementedError
class YesterdaysWeather(WeatherPrediction):
"""Simple prediction model, based on yesterday's weather."""
def __init__(self, weather_data):
"""
Parameters:
weather_data (WeatherData): Collection of weather data.
Pre-condition:
weather_data.size() > 0
"""
super().__init__(weather_data)
self._yesterdays_weather = self._weather_data.get_data(1)
self._yesterdays_weather = self._yesterdays_weather[0]
def get_number_days(self):
"""(int) Number of days of data being used in prediction"""
return 1
def chance_of_rain(self):
"""(int) Percentage indicating chance of rain occurring."""
# Amount of yesterday's rain indicating chance of it occurring.
NO_RAIN = 0.1
LITTLE_RAIN = 3
SOME_RAIN = 8
# Chance of rain occurring.
NONE = 0
MILD = 40
PROBABLE = 75
LIKELY = 90
if self._yesterdays_weather.get_rainfall() < NO_RAIN:
chance_of_rain = NONE
elif self._yesterdays_weather.get_rainfall() < LITTLE_RAIN:
chance_of_rain = MILD
elif self._yesterdays_weather.get_rainfall() < SOME_RAIN:
chance_of_rain = PROBABLE
else:
chance_of_rain = LIKELY
return chance_of_rain
def high_temperature(self):
"""(float) Expected high temperature."""
return self._yesterdays_weather.get_high_temperature()
def low_temperature(self):
"""(float) Expected low temperature."""
return self._yesterdays_weather.get_low_temperature()
def humidity(self):
"""(int) Expected humidity."""
return self._yesterdays_weather.get_humidity()
def wind_speed(self):
"""(int) Expected average wind speed."""
return self._yesterdays_weather.get_average_wind_speed()
def cloud_cover(self):
"""(int) Expected amount of cloud cover."""
return self._yesterdays_weather.get_cloud_cover()
class SimplePrediction(WeatherPrediction):
"""A simple prediction model, based on 'n' days' weather."""
def __init__(self, weather_data, n):
"""
Parameters:
weather_data (WeatherData): Collection of weather data.
n(int): The number of the days input.
Pre-condition:
weather_data.size() > 0
If 'n' is greater than the number of days of weather data that is available, all of the available data is stored and used, rather than 'n' days.
"""
super().__init__(weather_data)
self._n = n
# Collect the weather data of selected days and decide the data size.
if self._n > self._weather_data.size():
self._ndays_weather = self._weather_data.get_data(self._weather_data.size())
self._days = self._weather_data.size()
else:
self._ndays_weather = self._weather_data.get_data(self._n)
self._days = self._n
def get_number_days(self):
"""(int) Number of days of data being used in prediction"""
return self._days
def get_rainfall_average(self):
"""(float) The average of past 'n' days' rainfall"""
total_rainfall = 0
counter = 0
while counter < self.get_number_days():
total_rainfall = total_rainfall + self._ndays_weather[counter].get_rainfall()
counter = counter + 1
rainfall_average = total_rainfall / counter
return rainfall_average
def get_high_temperature_list(self):
"""(list) List including all high temperatures of selected days."""
counter = 0
high_temperature_list = []
while counter < self.get_number_days():
high_temperature_list.append(self._ndays_weather[counter].get_high_temperature())
counter = counter + 1
return high_temperature_list
def get_low_temperature_list(self):
"""(list) List including all low temperatures of selected days."""
counter = 0
low_temperature_list = []
while counter < self.get_number_days():
low_temperature_list.append(self._ndays_weather[counter].get_low_temperature())
counter = counter + 1
return low_temperature_list
def get_humidity_average(self):
"""(float) The average of the past 'n' days' humidity"""
total_humidity = 0
counter = 0
while counter < self.get_number_days():
total_humidity = total_humidity + self._ndays_weather[counter].get_humidity()
counter = counter + 1
humidity_average = total_humidity / counter
return humidity_average
def get_cloud_cover_average(self):
"""(float) The average of the past 'n' days' cloud cover"""
total_cloud_cover = 0
counter = 0
while counter < self.get_number_days():
total_cloud_cover = total_cloud_cover + self._ndays_weather[counter].get_cloud_cover()
counter = counter + 1
cloud_cover_average = total_cloud_cover / counter
return cloud_cover_average
def get_wind_speed_average(self):
"""(float) The average of the past 'n' days' wind speed"""
total_wind_speed = 0
counter = 0
while counter < self.get_number_days():
total_wind_speed = total_wind_speed + self._ndays_weather[counter].get_average_wind_speed()
counter = counter + 1
wind_speed_average = total_wind_speed / counter
return wind_speed_average
def chance_of_rain(self):
"""(int) Percentage indicating chance of rain occurring."""
chance_of_rain = self.get_rainfall_average() * 9
if chance_of_rain > 100:
chance_of_rain = 100
return round(chance_of_rain)
def high_temperature(self):
"""(float) Expected high temperature."""
# Find the hightest temperature in selected days
highest_temperature = -999999.9
for high_temperature in self.get_high_temperature_list():
if high_temperature > highest_temperature:
highest_temperature = high_temperature
return highest_temperature
def low_temperature(self):
"""(float) Expected low temperature."""
# Find the lowest temperature in selected days
lowest_temperature = 999999.9
for low_temperature in self.get_low_temperature_list():
if low_temperature < lowest_temperature:
lowest_temperature = low_temperature
return lowest_temperature
def humidity(self):
"""(int) Expected humidity."""
return round(self.get_humidity_average())
def wind_speed(self):
"""(int) Expected average wind speed."""
return round(self.get_wind_speed_average())
def cloud_cover(self):
"""(int) Expected amount of cloud cover."""
return round(self.get_cloud_cover_average())
class SophisticatedPrediction(WeatherPrediction):
"""A complex prediction model, based on 'n' days' weather."""
def __init__(self, weather_data, n):
"""
Parameters:
weather_data (WeatherData): Collection of weather data.
n(int): The number of the days input.
Pre-condition:
weather_data.size() > 0
If 'n' is greater than the number of days of weather data that is available, all of the available data is stored and used, rather than 'n' days.
"""
super().__init__(weather_data)
self._n = n
# Collect the weather data of selected days and decide the data size.
if self._n > self._weather_data.size():
self._ndays_weather = self._weather_data.get_data(self._weather_data.size())
self._days = self._weather_data.size()
else:
self._ndays_weather = self._weather_data.get_data(self._n)
self._days = self._n
def get_number_days(self):
"""(int) Number of days of data being used in prediction"""
return self._days
def get_air_pressure_average(self):
"""(float) The average of past 'n' days' air pressure"""
total_air_pressure = 0
counter = 0
while counter < self.get_number_days():
total_air_pressure = total_air_pressure + self._ndays_weather[counter].get_air_pressure()
counter = counter + 1
air_pressure_average = total_air_pressure / counter
return air_pressure_average
def get_rainfall_average(self):
"""(float) The average of past 'n' days' rainfall"""
total_rainfall = 0
counter = 0
while counter < self.get_number_days():
total_rainfall = total_rainfall + self._ndays_weather[counter].get_rainfall()
counter = counter + 1
rainfall_average = total_rainfall / counter
return rainfall_average
def get_high_temperature_average(self):
"""(float) The average of the past 'n' days' high temperature"""
total_high_temperature = 0
counter = 0
while counter < self.get_number_days():
total_high_temperature = total_high_temperature + self._ndays_weather[counter].get_high_temperature()
counter = counter + 1
high_temperature_average = total_high_temperature / counter
return high_temperature_average
def get_low_temperature_average(self):
"""(float) The average of the past 'n' days' low temperature"""
total_low_temperature = 0
counter = 0
while counter < self.get_number_days():
total_low_temperature = total_low_temperature + self._ndays_weather[counter].get_low_temperature()
counter = counter + 1
low_temperature_average = total_low_temperature / counter
return low_temperature_average
def get_humidity_average(self):
"""(float) The average of the past 'n' days' humidity"""
total_humidity = 0
counter = 0
while counter < self.get_number_days():
total_humidity = total_humidity + self._ndays_weather[counter].get_humidity()
counter = counter + 1
humidity_average = total_humidity / counter
return humidity_average
def get_cloud_cover_average(self):
"""(float) The average of the past 'n' days' cloud cover"""
total_cloud_cover = 0
counter = 0
while counter < self.get_number_days():
total_cloud_cover = total_cloud_cover + self._ndays_weather[counter].get_cloud_cover()
counter = counter + 1
cloud_cover_average = total_cloud_cover / counter
return cloud_cover_average
def get_wind_speed_average(self):
"""(float) The average of the past 'n' days' wind speed"""
total_wind_speed = 0
counter = 0
while counter < self.get_number_days():
total_wind_speed = total_wind_speed + self._ndays_weather[counter].get_average_wind_speed()
counter = counter + 1
wind_speed_average = total_wind_speed / counter
return wind_speed_average
def chance_of_rain(self):
"""(int) Percentage indicating chance of rain occurring."""
# The first time to adjust rainfall average
if self._ndays_weather[-1].get_air_pressure() < self.get_air_pressure_average():
first_adjusted_rainfall_average = self.get_rainfall_average() * 10
else:
first_adjusted_rainfall_average = self.get_rainfall_average() * 7
# The second time to adjust rainfall average
wind_direciton_list = ["NNE", "NE", "ENE", "E", "ESE", "SE", "SSE"]
if self._ndays_weather[-1].get_wind_direction() in wind_direciton_list:
second_adjusted_rainfall_average = first_adjusted_rainfall_average * 1.2
else:
second_adjusted_rainfall_average = first_adjusted_rainfall_average
# Make sure the value of the chance of rain is not greater than 100
if second_adjusted_rainfall_average > 100:
chance_of_rain = 100
else:
chance_of_rain = second_adjusted_rainfall_average
return round(chance_of_rain)
def high_temperature(self):
"""(float) Expected high temperature."""
if self._ndays_weather[-1].get_air_pressure() > self.get_air_pressure_average():
high_temperature = self.get_high_temperature_average() + 2
else:
high_temperature = self.get_high_temperature_average()
return high_temperature
def low_temperature(self):
"""(float) Expected low temperature."""
if self._ndays_weather[-1].get_air_pressure() < self.get_air_pressure_average():
low_temperature = self.get_low_temperature_average() - 2
else:
low_temperature = self.get_low_temperature_average()
return low_temperature
def humidity(self):
"""(int) Expected humidity."""
if self._ndays_weather[-1].get_air_pressure() < self.get_air_pressure_average():
humidity = self.get_humidity_average() + 15
elif self._ndays_weather[-1].get_air_pressure() > self.get_air_pressure_average():
humidity = self.get_humidity_average() - 15
else:
humidity = self.get_humidity_average()
# Make sure the value of humidity is between 0 and 100
if humidity < 0:
humidity = 0
elif humidity > 100:
humidity = 100
return round(humidity)
def cloud_cover(self):
"""(int) Expected amount of cloud cover."""
if self._ndays_weather[-1].get_air_pressure() < self.get_air_pressure_average():
cloud_cover = self.get_cloud_cover_average() + 2
else:
cloud_cover = self.get_cloud_cover_average()
# Make sure the value of cloud cover is not greater than 9
if cloud_cover > 9:
cloud_cover = 9
return round(cloud_cover)
def wind_speed(self):
"""(int) Expected average wind speed."""
if self._ndays_weather[-1].get_maximum_wind_speed() > 4 * self.get_wind_speed_average():
wind_speed = self.get_wind_speed_average() * 1.2
else:
wind_speed = self.get_wind_speed_average()
return round(wind_speed)
if __name__ == "__main__":
print("This module provides the weather prediction models",
"and is not meant to be executed on its own.")
|
f5ee890596eaa9f618c4e19b53bfd95ece28b8fc | AndrewAct/DataCamp_Python | /Machine Learning for Time Series Data/4 Validating and Inspecting Time Series Models/03_Visualize_Regression_Coeffiients.py | 1,097 | 4.34375 | 4 | # # 7/1/2020
# Now that you've fit the model, let's visualize its coefficients. This is an important part of machine learning because it gives you an idea for how the different features of a model affect the outcome.
# The shifted time series DataFrame (prices_perc_shifted) and the regression model (model) are available in your workspace.
# In this exercise, you will create a function that, given a set of coefficients and feature names, visualizes the coefficient values.
def visualize_coefficients(coefs, names, ax):
# Make a bar plot for the coefficients, including their names on the x-axis
ax.bar(names, coefs)
ax.set(xlabel='Coefficient name', ylabel='Coefficient value')
# Set formatting so it looks nice
plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment='right')
return ax
# Visualize the output data up to "2011-01"
fig, axs = plt.subplots(2, 1, figsize=(10, 5))
y.loc[:'2011-01'].plot(ax=axs[0])
# Run the function to visualize model's coefficients
visualize_coefficients(model.coef_, prices_perc_shifted.columns, ax=axs[1])
plt.show() |
0b74e0399af1adb344c85edb31109aebbadad0e5 | PeterWolf-tw/ESOE-CS101-2016 | /homework02_b05505020.py | 1,549 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
x=17
number = int(x) #設定 number 這個變數的值為 2
print("number 的二進位表示法為:{0}".format(bin(number)))
def 十進位轉二進位(number):
answer = []
while number > 0:
位數 = int(number % 2)
answer.append(位數)
number = (number-位數)/2
answer.append("0b")
output = ""
for n in answer[::-1]:
output = output + str(n)
print(output)
十進位轉二進位(int(x))
class HW02:
def ch2(self):
#作業 2. 課本 Ch2. P2.19
self.Ch2P2_19a = "10"
self.Ch2P2_19b = "17"
self.Ch2P2_19c = "7" #"6"
self.Ch2P2_19d = "9" #"8"
#作業 3. 課本 Ch2. P2.20
self.Ch2P2_20a = "15" #"14"
self.Ch2P2_20b = "9" #"8"
self.Ch2P2_20c = "14" #"13"
self.Ch2P2_20d = "5" #"6"
#作業 4. 課本 Ch2. P2.22
self.Ch2P2_22a = "00010001 11101010 00100010 00001110"
self.Ch2P2_22b = "00001110 00111000 11101010 00111000"
self.Ch2P2_22c = "01101110 00001110 00111000 01001110"
self.Ch2P2_22d = "00011000 00111000 00001101 00001011"
def ch3(self):
#作業 5. 課本 Ch3. P3.28
self.Ch3P3_28a = "234"
self.Ch3P3_28b = "overflow" #"560"
self.Ch3P3_28c = "874"
self.Ch3P3_28d = "888"
#作業 6. 課本 Ch3. P3.30
self.Ch3P3_30a = "234"
self.Ch3P3_30b = "overflow" #"560"
self.Ch3P3_30c = "875"
self.Ch3P3_30d = "889"
|
4985a1b084c70ec0bca9960d17d340c6216ab50b | kakao100/atcoder | /practice/dast/test.py | 277 | 3.6875 | 4 | str = input()
if(len(str)%2 != 0):
print("No")
exit()
for i in range(len(str)):
if(i % 2 == 0):
if(str[i]!='h'):
print("No")
exit()
if(i % 2 == 1):
if(str[i]!='i'):
print("No")
exit()
print("Yes") |
a4bac9ea3a25f8b7d28b91a08fefdbe9edec2f3d | PaaruRa/Intro-to-ML-DAT4 | /assignments/04/danphe.py | 731 | 3.71875 | 4 | class Series:
"""One-dimensional named array.
Basically, a "smart" array.
Parameters
----------
values: list
list of data values
name: str
name of the Series
"""
def __init__(self, values, name=None):
# Code Here
pass
def mean(self):
# Code Here
pass
class DataFrame:
"""Two-dimensional tabular data structure.
Basically, a dictionary of `Series` objects.
Parameters
----------
data_dict: dict
dictionary of lists. The key is the column name.
So, dict['col'] is a list of values for the 'col' column
of the DataFrame.
"""
def __init__(self, data_dict):
# Code Here
pass
|
d4ed4456690036e2c7ad4afe462fe5062acb5f66 | DiaconescuRadu/diveinpython | /DiveInPython/src/AlienAccent.py | 828 | 3.59375 | 4 | '''
Created on 28 dec. 2016
@author: radi961
'''
from _functools import reduce
import re
from src import test
def iq_test(numbers_string):
numbers = re.findall('[0-9]+', numbers_string)
even_numbers = [number for number in numbers if (int(number) % 2) == 0]
odd_numbers = [number for number in numbers if (int(number) % 2) == 1]
if (len(even_numbers) == 1):
return numbers.index(even_numbers[0]) + 1
if (len(odd_numbers) == 1):
return numbers.index(odd_numbers[0]) + 1
return 1
def series_sum(n):
sum = float(0)
for count in range(n):
sum = sum + 1 / (1 + count * 3)
return "{:.2f}".format(sum)
if __name__ == "__main__":
test.assert_equals(series_sum(1), "1.00")
test.assert_equals(series_sum(2), "1.25")
test.assert_equals(series_sum(3), "1.39")
|
fddbf4812e2058333c37a860d96efc2779ca472e | kresnajenie/curriculum-python | /ExchangeRate/exchange_rate.py | 2,317 | 3.65625 | 4 | # Python program to get the real-time
# currency exchange rate
import exchange as exc
import pytz
import requests, json
import datetime
# Function to get real time currency exchange
def utc_to_local(utc_dt):
local_tz = pytz.timezone('Asia/Jakarta') #timezone jakarta
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) #function to change timezone
return local_tz.normalize(local_dt) # .normalize might be unnecessary
def aslocaltimestr(utc_dt):
return utc_to_local(utc_dt).strftime('%H:%M:%S WIB') #format the output strucutre of the date
def RealTimeCurrencyExchangeRate(from_currency) :
# importing required libraries
to_currency = "IDR"
# base_url variable store base url
base_url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE' # cara menggunakan api
api_key = "RCBPGO0BOZ6KLM1Q"
# main_url variable store complete url
main_url = base_url + "&from_currency=" + from_currency + "&to_currency=" + to_currency + "&apikey=" + api_key # query dari api pake api key
# get method of requests module
# return response object
req_ob = requests.get(main_url) # di query pake function requests
req_ob
# json method return json format
# data into python dictionary data type.
# result contains list of nested dictionaries
result = req_ob.json() # hasil dari query diformat ke bentuk json
a = result['Realtime Currency Exchange Rate'] #get the result dictionary
froms = a['1. From_Currency Code'] #outputs the from currency code from the 'a' dictionary
to = a['3. To_Currency Code'] #outputs the to currency code from the 'a' dictionary
times = a['6. Last Refreshed'] #outputs when the last time it refreshed from the 'a' dictionary
price_decimal = a['8. Bid Price'] #outputs bid price from the 'a' dictionary
precision = 3 #how many decimal number
price = str(
("{:.{}f}".format( float(price_decimal), precision ))
) #convert from many decimals to normal
formatfrom="%Y-%m-%d %H:%M:%S" #format date from this structure
formatto="%H:%M:%S UTC" #to this structure
time_utc = datetime.datetime.strptime(times,formatfrom) #using this function
time_wib = (aslocaltimestr(time_utc)) # convert using the fuction aslocaltimestr form utc to wib
ech = exc.Exchange(froms, to, time_wib, price) #inputs the parameters to the class
return ech
|
89b03d2c56bb2eba2eb2b5571167ef35dfa23c6b | akansh028/Data-Structures | /Arrays/array_advance.py | 371 | 3.96875 | 4 | # write a program to write the pointer can reach furthermost in an array
def array_advance(a):
i = 0
last = len(a) - 1
reach = 0
while i <= reach and reach < last:
reach = max(reach , a[i]+i)
i+=1
return reach >= last
a = [3, 3, 1, 0, 2, 0, 1]
print(array_advance(a))
A = [3, 2, 0, 0, 2, 0, 1]
print(array_advance(A)) |
9763e1b2c69c0ef6755f26fb4bceff1532ec7a66 | kiberjen/Learn-Python | /Эрик Мэтиз Изучаем Python/Ch2/2.7/2_7.py | 815 | 3.53125 | 4 | # Удаление пропусков: сохраните имя пользователя в переменной. Добавьте в начале и в конце несколько пропускоа.
# Проследите за тем, чтобы каждая служебная последовательность, "\t" и "\n", встречалась по крайней мере один раз.
# Выведите имя, чтобы были видны пропуски в начале и конце строки. атем выведите его снова с использованием
# каждой из функций удаления пропусков: lstrip(), rstrip() и strip().
nameEric = ' Eric '
print(nameEric)
print(nameEric.lstrip())
print(nameEric.rstrip())
print(nameEric.strip())
|
560dbf41f1f7514a28676b936ece8eb2dd16af1a | jmawloo/Applied-Data-Science | /1. Intro to Data Science/Prob_dist.py | 6,748 | 3.953125 | 4 | import pandas as pd
import numpy as np
"""DISTRIBUTIONS: Set of all possible random values
e.g. coin flipping heads + tails.
-Binomial distribution (2 outcomes)
-discrete (categories of heads/tails, no real numbers)
-evenly weighted (heads just as likely as tails)
e.g. Tornado events in Ann Arbor:
-Binomial Dist., discrete, evenly weighted (tornadoes are rare events).
"""
print(np.random.binomial(1, 0.5)) # run coin-flipping simulation once with 50% chance of landing heads (0).
print(np.random.binomial(1000, 0.5) / 1000) # See a number close to 0.5
# This is how to calculate the number of times the combined outcome of 20 flips is greater than 15 (15 heads).
x = np.random.binomial(20, .5, 10000) #10000 simulations of 20 coin flips, result gets stored in list.
print((x>=15).mean()) # Then we take only the values greater than/ equal to 15
tornadochance = 0.01/100
print(np.random.binomial(100000, tornadochance))
tornadochance = 0.01
tornadoevents = np.random.binomial(1,tornadochance,1000000)
consecutive = 0
for i in range(1, len(tornadoevents)-1): # exclude the first AND last day.
if tornadoevents[i] == 1 and tornadoevents[i-1] == 1:
consecutive += 1
print('{} tornadoes back to back in {} years'.format(consecutive,1000000/365), '\n')
#MORE DISTRIBUTIONS
"""
Uniform Distribution: Constant probability over observation time, with continuous plots. (flat horizontal line).
Normal (Gaussian) Distribution: Highest probability in middle of obs value, curving down on the sides (Bell curve).
-Mean (central tendency) is zero, Std. Dev (measure of variability): How bacly variables are spread out from mean.
-Expected Value: Mean value we'd expect to get if we performed an infinite number of trials.
PROPERTIES:
-Central Tendency: Mean, median, mode
-Variability: Standard Deviation, Interquartile range.
-Kurtosis: Sharpness of peak of freq-dist. curve/ (-/+ respectively mean more flat/sharp)
-Degrees of Freedom: Number of independent values/quantities that can be assigned to statistical dist.
-Modality: number of peaks in dist. (one = unimodal, two = bimodal).
"""
print(np.random.uniform(0,1)) #Any number between these values can be generated.
print(np.random.normal(0.75)) #0.75 is the mean value
dist = np.random.normal(0.75, size=1000)
print(np.sqrt(np.sum((np.mean(dist)-dist)**2)/len(dist))) # Formula for std. Dev
print(np.std(dist)) # also does the trick
import scipy.stats as stats
print(stats.kurtosis(dist)) # negative means more flat, positive more curved.
#Note we're measuring kurtosis of 1000 trials and not a single curve.
"""
Skewed Normal distributions are called Chi Squared dist. (argument is "degrees of freedom").
-Degrees of Freedom closely related to # of samples taken from normal population (significance testing).
-As degrees of freedom increase, dist is more CENTRED>
"""
print(stats.skew(dist))
chi_squared_df2 = np.random.chisquare(2, size=10000) #2 is degrees of freedom.
print(stats.skew(chi_squared_df2)) # skew of nearly 2 is quite large.
chi_squared_df2 = np.random.chisquare(5, size=10000)# resampling for D.o.F. to be 5
print(stats.skew(chi_squared_df2),'\n') # less skewed.
"""
Bimodal Distribution: A dist. that has two high points.(Gaussian Mixture Models).
-Happen regularly in Data Mining.
-Can be modelled with 2 normal dist., with diff parameters. (useful for clustering data).
"""
"""HYPOTHESIS TESTING
- Core Data analysis behind experimentation.
A/B Testing: The comparison of two similar conditions to see which one provides the better outcome.
Hypothesis: Testable Statement,
-Alternative Hyp.: our idea (e.g. difference between groups). <- Always more confident about our alt. Hypothesis.
-Null Hyp.: Alt. of our idea (e.g. no difference b/w groups).
e.g. whether (alt) or not (null) students who sign up faster for course materials perform better than their peers who sign up later.
"""
df = pd.read_csv('grades.csv')
print(df.head())
print(len(df))
early = df[df['assignment1_submission'] <= '2015-12-31']
late = df[df['assignment1_submission'] > '2015-12-31']
print(early.mean()) # Date time values ignored; pandas knows it's not a number.
print(late.mean()) #Those who submit late are almost equally as often as those submitting early.
"""
Critical Value alpha (a)
-Threshold as to how much chance one willing to accept.
-Typical values in social sciences = .1, .05, .01. Depends on what you're doing and the amount of noise in your data.
- Physics labs have much lower tolerance for alpha values.
- Lower-cost versus high cost: low interventions (e.g. email reminder) are convenient, but higher interventions
(e.g. calling the student) is more of a burden on both the student and institution (higher burden of proof, lower critical value alpha.
T-test: One way to compare averages of 2 different populations.
-Result includes a statistic and a p-value.
**Most statistical tests require data to conform to certain shape. Therefore check data 1st before applying any test.
"""
p_valstat = stats.ttest_ind(early['assignment1_grade'],late['assignment1_grade'])
print(p_valstat)
# since p_val is larger than 0.05 critical value, cannot reject null hypothesis (2 populations are the same). I.e. no statistically significant difference between THESE 2 samples (not all samples).
print(stats.ttest_ind(early['assignment2_grade'],late['assignment2_grade'])) #p_val still too large
print(stats.ttest_ind(early['assignment3_grade'],late['assignment3_grade'])) #Close, but still far beyond value.
"""
Generally the more t-tests run, the more likely we'll obtain a positive result.
-Called p-hacking/dredoing when u do many tests untol u find a statistically significant one; serious methodological issue.
-At a confidence level of 0.05, expect to find one positive result in 1 time out of 20 tests.
-Remedies:
-Bonferroni correction : tighten alpha value. (Threshold based on number of tests being run).
-Hold-out sets (i.e. is data generalizable? Form specific hypotheses based on isolated data sets, then run experiments based on more limiting hypothesis.
Used in Machine learning to build predictive models (cross-fold validation)
-Investigation pre-registration. Outline what to expect to find + why, and describe tests that would backup positive proof of this.
Register with 3rd party in academic circles (e.g. journal/board determining whether it's reasonable or not.) Then run
study and report results regardless of it being positive or not.
Experience larger burden in connecting to existing theory since must convince board of feasibility of testing hypothesis.
"""
|
5c678765ca8bb455d020a70bb1d00c79b2b211e5 | mag389/holbertonschool-machine_learning | /pipeline/0x00-pandas/2-from_file.py | 305 | 3.90625 | 4 | #!/usr/bin/env python3
""" create dataframe from file """
import pandas as pd
def from_file(filename, delimiter):
""" loads data from a file
filename: file to load from
delimiter: column separator
Returns: pd.DataFrame
"""
return pd.read_csv(filename, sep=delimiter)
|
a2d209567c6124ed18454fee26b899189c805b33 | asperaa/back_to_grind | /DP/300. Longest Increasing Subsequence_nlongn.py | 1,126 | 3.671875 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""300. Longest Increasing Subsequence [T - O(nlogn)]
"""
class Solution:
def lengthOfLIS(self, nums):
if not nums:
return 0
n = len(nums)
book = [0 for _ in range(n)]
length = 1
book[0] = nums[0]
for i in range(1, n):
if nums[i] < book[0]:
book[0] = nums[i]
elif nums[i] > book[length-1]:
book[length] = nums[i]
length += 1
else:
ceil_index = self.ceiling_in_sorted(book, 0, length-1, nums[i])
book[ceil_index] = nums[i]
return length
def ceiling_in_sorted(self, nums, left, right, target):
result = -1
while left <= right:
mid = left + (right-left) // 2
if nums[mid] == target:
return mid
elif target < nums[mid]:
result = mid
right = mid - 1
else:
left = mid + 1
return result
|
d37a2946c510b9456c746739f120a5995629e7b2 | xu6148152/Binea_Python_Project | /FluentPython/function_decorator_closures/closure_test.py | 929 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
class Averager():
def __init__(self):
self.series = []
def __call__(self, new_value):
self.series.append(new_value)
total = sum(self.series)
return total / len(self.series)
def test_arg():
avg = Averager()
print(avg(10))
print(avg(10.5))
print(avg(12))
def make_averager():
series = []
def averger(new_value):
series.append(new_value)
total = sum(series)
return total / len(series)
return averger
def test_make_averager():
avg = make_averager()
print(avg(10))
print(avg(10.5))
print(avg(12))
def make_averager_nonlocal():
count = 0
total = 0
def averager(new_value):
nonlocal count, total
count += 1
total += new_value
return total / count
return averager
if __name__ == '__main__':
test_make_averager()
|
e771080e38c0e72abe0554c06a3e49f39c3a2804 | vikasmunshi/euler | /projecteuler/019_counting_sundays.py | 1,015 | 3.984375 | 4 | #!/usr/bin/env python3.8
# -*- coding: utf-8 -*-
"""
https://projecteuler.net/problem=19
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Answer: 171
"""
from datetime import date
def sundays_on_first_of_month(start_year: int, end_year: int) -> int:
return sum(date(y, m, 1).isoweekday() == 7 for m in range(1, 13) for y in range(start_year, end_year + 1))
if __name__ == '__main__':
from .evaluate import Watchdog
with Watchdog() as wd:
result = wd.evaluate(sundays_on_first_of_month)(start_year=1901, end_year=2000, answer=171)
|
4012a4e59ea2b9ab52476b6616873e0ea8665453 | xili-h/PG | /ISU3U/python/unit 1/test 4 11.py | 118 | 3.765625 | 4 | burger = input('How many burger do you want? ')
pickles = int(burger)*3
print('You need',pickles,'slices of pickles.') |
bf220234cf760341950452bb1cacb5c218565ee7 | Awesome94/Algo_Python | /binsubtractdivide.py | 452 | 3.765625 | 4 | def solutions(S):
# write your code in Python 3.6
n = int(S)
steps = 0
while n > 0:
if n%2 == 0:
n = n/2
else:
n = n-1
steps+=1
return steps
print(solution('011100'))
def solution(S):
# write your code in Python 3.6
n = int(S, 2)
steps = 0
while n > 0:
if n%2 == 0:
n = n//2
else:
n = n-1
steps+=1
return steps |
3c11042f597fc20b2d18b92d01c1fc215826f5ea | DeepeshKr/simple-poker-card-test | /test.py | 9,143 | 3.640625 | 4 | import unittest
from poker import *
class TestSum(unittest.TestCase):
def test_values_returned(self):
"""
Test that it can sum a list of cards
"""
data = "aaakt"
result = validatehand(data)
self.assertEqual(result, 65)
def test_five_cards_returned(self):
"""
Test that it would pick only 5 cards
"""
data = "aaaktq3"
result = validatehand(data)
self.assertEqual(result, 65)
def test_no_double_star(self):
"""
Test that no double star is allowed
"""
data = "aaa**"
result = validatehand(data)
self.assertEqual(result, 0)
def test_four_of_kind(self):
"""
check if four of a kind
four-of-a-kind (4 cards of the same value: AAAA5)
"""
data = "AAAAK"
result = four_of_kind(data, 100)
# print('Test Result',result)
self.assertEqual(result, ['AAAAK', 'four-of-a-kind', 100000000000000, False, {1: 'K', 4: 'A'}])
def test_four_of_kind_star(self):
"""
check if four of a kind
four-of-a-kind (4 cards of the same value: AAAA5)
"""
data = "AAAA*"
result = four_of_kind(data, 100)
# print('Test Result',result)
self.assertEqual(result, ['AAAA*', 'four-of-a-kind', 100000000000000, True, {1: '*', 4: 'A'}])
def test_not_four_of_kind(self):
"""
check if four of a kind
four-of-a-kind (4 cards of the same value: AAAA5)
"""
data = "AAAKK"
result = four_of_kind(data, 100)
self.assertNotEqual(result, ['AAAAK', 'four-of-a-kind', 100000000000000])
def test_full_house(self):
"""
check if four of a kind
full house (3 of one, and 2 of another: KKKQQ)
"""
data = "AAAKK"
result = full_house(data, 100)
self.assertEqual(result, ['AAAKK', 'full-house', 1000000000000, [42, 26]])
def test_not_full_house(self):
"""
check if NOT four of a kind
full house (3 of one, and 2 of another: KKKQQ)
"""
data = "AAJKK"
result = full_house(data, 100)
self.assertNotEqual(result, ['AAAKK', 'full-house', 1000000000000, [42, 26]])
def test_straight(self):
"""
check if straight
straight (all 5 in sequential order: 6789T)
"""
data = "6789T"
result = straight(data, 100)
self.assertEqual(result, ['6789T', 'straight', 10000000000])
def test_straight_exception(self):
"""
check if straight
straight (all 5 in sequential order: 6789T)
Straights are compared by the highest card in the hand, except for A2345, in which case the 5 is considered the highest card in the straight.
"""
data = "A2345"
result = straight(data, 100)
self.assertEqual(result, ['A2345', 'straight', 537824])
def test_not_straight(self):
"""
check if NOT straight
straight (all 5 in sequential order: 6789T)
"""
data = "6789K"
result = straight(data, 100)
self.assertNotEqual(result, ['6789T', 'straight', 10000000000])
def test_three_of_a_kind (self):
"""
check if three-of-a-kind
three-of-a-kind (3 cards of the same value: KKK23)
"""
data = "KKK23"
result = three_of_a_kind(data, 100)
# print('Result Three of Kind', result)
self.assertEqual(result, ['KKK23', 'three-of-a-kind', 100000000])
def test_not_three_of_a_kind (self):
"""
check if NOT three-of-a-kind
three-of-a-kind (3 cards of the same value: KKK23)
"""
data = "KKJ23"
result = three_of_a_kind(data, 100)
self.assertNotEqual(result, ['KKK23', 'three-of-a-kind', 100000000])
def test_two_pair (self):
"""
check if two-pair
two pair (AA33J)
"""
data = "AA33J"
result = two_pair(data, 100)
self.assertEqual(result,['AA33J', 'two-pair', 1000000,[28, 11, 6]])
def test_not_two_pair (self):
"""
check if NOT two-pair
two pair (AA33J)
"""
data = "AA32J"
result = two_pair(data, 100)
self.assertNotEqual(result,['AA33J', 'two-pair', 1000000,[28, 11, 6]])
def test_pair (self):
"""
check if pair
pair (44KQA)
"""
data = "44KQA"
result = pair(data, 100)
self.assertEqual(result, ['44KQA', 'pair', 10000])
def test_not_pair (self):
"""
check if not pair
pair (44KQA)
"""
data = "43KQA"
result = pair(data, 100)
self.assertNotEqual(result, ['44KQA', 'pair', 10000])
def test_high_card (self):
"""
check if high card
high card (nothing else: A267J)
"""
data = "A267J"
result = high_card(data, 100)
self.assertEqual(result, ['A267J', 'high-card', 100])
def test_compare_cards_1 (self):
"""
test to compare_cards three-of-a-kind to full-house
AAAKT three-of-a-kind < 22233 full house
"""
data1 = "AAAKT"
data2 = "22233"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 AAAKT-three-of-a-kind) (Hand 2 22233-full-house)')
def test_compare_cards_2 (self):
"""
test to compare_cards straight to two-pair
2345* straight > KKJJ2 two pair
"""
data1 = "2345*"
data2 = "KKJJ2"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 2345*-straight) (Hand 2 KKJJ2-two-pair)')
def test_compare_cards_3 (self):
"""
test to compare_cards two-pair == two-pair
AAKKT two pair == AAKKT two pair
"""
data1 = "AAKKT"
data2 = "AAKKT"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Tie (Hand 1 AAKKT-two-pair) (Hand 2 AAKKT-two-pair)')
def test_compare_cards_4 (self):
"""
test to compare_cards two-pair == two-pair
KKKKA four-of-a-kind == KKKK* four-of-a-kind
"""
data1 = "KKKKA"
data2 = "KKKK*"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Tie (Hand 1 KKKKA-four-of-a-kind) (Hand 2 KKKK*-four-of-a-kind)')
def test_compare_cards_5 (self):
"""
test to compare_cards compare the highest pair first
When comparing two pair hands, compare the highest pair first, then the next pair. i.e. AA223 > KKQQT, since AA > KK.
"""
data1 = "AA223"
data2 = "KKQQT"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 AA223-two-pair) (Hand 2 KKQQT-two-pair)')
def test_compare_cards_6 (self):
"""
test to compare_cards compare the highest pair first
When the highest pair is a tie, move on to the next pair. i.e. AA993 > AA88K.
"""
data1 = "AA993"
data2 = "AA88K"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 AA993-two-pair) (Hand 2 AA88K-two-pair)')
def test_compare_cards_7 (self):
"""
test to compare_cards compare the highest pair first
Similarly, when comparing full house hands, the three-card group is compared first. AAA22 > KKKQQ
"""
data1 = "AAA22"
data2 = "KKKQQ"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 AAA22-full-house) (Hand 2 KKKQQ-full-house)')
def test_compare_cards_8 (self):
"""
test to compare_cards compare the highest pair first
In the case of ties, determine a winner by comparing the next highest card in the hand. i.e. AA234 < AA235 because AAs tie, 2s tie, 3s tie, but 4 < 5.
"""
data1 = "AA234"
data2 = "AA235"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 2 Wins (Hand 1 AA234-pair) (Hand 2 AA235-pair)')
def test_compare_cards_9 (self):
"""
test to compare_cards compare the highest pair first
In the case of ties, determine a winner by comparing the next highest card in the hand. i.e. AA234 > KK235.
"""
data1 = "AA234"
data2 = "KK235"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 1 Wins (Hand 1 AA234-pair) (Hand 2 KK235-pair)')
def test_compare_cards_10 (self):
"""
test to compare_cards compare the highest pair first
Straights are compared by the highest card in the hand, except for A2345, in which case the 5 is considered the highest card in the straight.
"""
data1 = "A2345"
data2 = "23456"
result = compare_cards(data1, data2)
self.assertEqual(result, 'Hand 2 Wins (Hand 1 A2345-straight) (Hand 2 23456-straight)')
if __name__ == '__main__':
unittest.main() |
81269ef7f63bd902522fa310239ba35061e1a1b9 | sourcery-ai-bot/Python-Curso-em-Video | /python_exercicios/ex112/utilidadescev/dado/__init__.py | 1,125 | 3.8125 | 4 | def leiaDinheiro(msg):
válido = False
while not válido: #Quando omitido, se considera como True. Nesse caso, enquanto não é True mantém o Loop.
entrada = str(input(msg)).replace(',','.').strip()
if entrada.isalpha() or entrada == '':
print(f'\033[0;31m ERRO: \"{entrada}\" é uma preço inválido!\033[m')
else:
válido = True
return float(entrada)
def leiaInt(msg):
ok = False #Declara o ok como Falso para validação no break do Loop While quando Verdadeiro
valor = 0 #Declara o valor para receber o input
while True:
n = str(input(msg))
if n.isnumeric(): #Teste se o valor é numérico. Quando é omitido o teste lógico é igual a True. Nesse caso, se n é numérico igual a True.
valor = int(n)
ok = True # ok recebe True para quebrar o loop na linha 16.
else:
print('\033[0;31mERRO! Digite um número inteiro válido.\033[m')
if ok: # Omitido o teste lógico, pressupõe que ok seja igual a True
break
return valor #Retorna o resultado da função |
3bef5477db8e706daa0ece355cc9f577c4cdbbfa | incememed0/python-notes | /12-for.py | 1,708 | 3.828125 | 4 | # author: Ercan Atar
# linkedin.com/in/ercanatar/
################################################
# #
# for DEĞİŞKEN in KOŞUL: #
# KOMUT #
# #
##########################
toplam=0
liste=[2,3,1,14,26,100]
for eleman in liste:
toplam+=eleman
print(f"eleman: {eleman}, Toplam: {toplam}") # print("eleman: {}, Toplam: {}".format(eleman,toplam))
print("----------------------")
# Çift elemanları bastırma
liste = [1,2,3,4,5,6,7,8,9]
for eleman in liste:
if eleman % 2 == 0:
print(eleman)
print("----------------------")
# Karakter dizileri üzerinde gezinmek
s = "Python"
for karakter in s:
print(karakter)
print("----------------------")
# Her bir karakterleri 3 ile çarpma
s = "Python"
for karakter in s:
print(karakter * 3)
print("----------------------")
# Listelerle aynı mantık
demet = (1,2,3,4,5,6,7)
for eleman in demet:
print(eleman)
print("----------------------")
# Listelerin için 2 boyutlu demetler
liste = [(1,2),(3,4),(5,6),(7,8)]
for eleman in liste:
print(eleman) # Herbir elemanın demet olduğu görebiliyoruz.
print("----------------------")
# Demet içindeki herbir elemanı almak için pratik yöntem
liste = [(1,2),(3,4),(5,6),(7,8)]
for (i,j) in liste:
print("i: {} , j: {}".format(i,j))
print("----------------------")
# Demet içindeki elemanları çarpalım.
liste = [(1,2,3),(4,5,6),(7,8,9),(10,11,12)]
for (i,j,k) in liste:
print(i * j * k)
print("---------- sözlükler ------------")
# Sözlük yapılarında sıklıkla kullanıyoruz.[ keys() , values() , items() ]
sozluk = {"bir":1,"iki":2,"üç":3,"dört":4}
print(sozluk)
for eleman in sozluk:
print(eleman)
for eleman in sozluk.values():
print(eleman)
for i,j in sozluk.items():
print(i,j)
|
dd2d92d7181a18c5be5eadcf4b5e46a71f002fea | tonyxiahua/CIS-41B-Python | /Lab1/scores.py | 2,981 | 3.90625 | 4 | #Lab1
#Author: Xia Hua
class Scores :
def __init__(self):
'''
a constructor that reads in data from the ile and stores it in an appropriate data structure.
The data structure is an instance variable.
Code check for ile open success and end the program with an error message if the ile open fails.
Extra Mission for Not using a loop
Use dictionary to contain different country data
'''
FILENAME = "input1.txt"
try:
with open(FILENAME) as f:
self._data = {data[0]:data[1:] #Collect Data throgh the files create dic files to put into
for data in zip(*[line.split() for line in f])} #Use zip command to put data into differnt country dictionary. Split the data by space or tab
if len(self._data) == 0 : #Check the input file is correct
raise EOFError(FILENAME + "is not a valid input file")
#exception handle
except EOFError as e:
raise SystemExit(e + "Please Check Valid Data inside?")
except IOError as e:
raise SystemExit(e + "IOError")
except FileNotFoundError:
raise SystemExit(FILENAME+"unable to access")
'''
Serves as a generator for the data.
It will return one country's name and corresponding scores with each next() call.
The order of the country being returned is alphabeical order based on country abbreviaion.
iterates all country from A-Z
return list of scores and country tuple
'''
def getOne(self):
for elem in sorted(self._data): # Generator of the type of the object
yield elem,list(self._data[elem]) # Using yield to make the object to country Solved by Dicussion Form Student help
'''
prints all countries and all corresponding scores
Each country and its scores are on one line of output
the print order is by descending order of the last score of each country
'''
def printByLast(self):
for elem in sorted(self._data, key = lambda elem : self._data[elem][-1], reverse = True): # use sorted to sort data sorted by the last score(biggest on the top)
print(elem + ":", ' '.join(self._data[elem])) # print by last score of each country take data from tuple form the class material
'''
prints the maximum and minimum of all the total scores of each country.
Solved by the help in the discussion form.
Created a list list to slove the question.
Create the sum of the score list in every country, use the max and min function to calculate the biggest and smallest score.
'''
def printMaxMin(self):
data = [sum([float(digit) for digit in self._data[elem]]) for elem in self._data]
print("max total:", max(data)) #Using Max to compare the Max sum in the dictionary
print("min total:", min(data)) #Using Min to compare the Min sum in the dictionary
|
7e45a1b885d00a7d4594b3b65ac685b157ec1cee | Som94/Python-repo | /29 july/Test 1.py | 1,903 | 3.65625 | 4 | #Super_sub_class_demo.py
class parallelogram: # this is super class
def __init__(self):
self.concept = 'xyz'
print ('i am inisde parallelogram class ')
# print ('this is MEANINGLESS .... ',self.length)
# print ('this is MEANINGLESS .... ',rectangle.length)
def get_details(self):
return self.concept
# IS a realtionship rectangle is sub class/derived class
class rectangle(parallelogram):
#this is class variable
maths_teacher = 'Dr Kumar' # visible anywhere in the program
@classmethod
def disp_maths_teacher_name(cls):
print ('the math teacher name is ', cls.maths_teacher)
def __init__(self,length=0,breadth=0):
super().__init__() # this is INVOKING THE super class init method()
self.length = length
self.breadth = breadth
self.concept = 'time and tide wait for none '
print ('location in RAM is ',id(self))
print ('SUB CLASS concept (data member) of rectangle class ',self.concept)
print ('SUPER CLASS concept of pllgm is ', super().get_details())
# AttributeError: type object 'super' has no attribute 'concept'
# print ('ERROR SUPER CLASS DIRECT var concept of pllgm is ', super.concept)
# super().__init__()
def change_teacher(self,nm):
rectangle.maths_teacher=nm
print ('before change ')
rectangle.disp_maths_teacher_name()
r1 = rectangle(10,15) # r1 ------> own copy of length,breadth,area,peri 2389289318990
r2 = rectangle(20,25) # r2 -------> its own copy of length,breadth,area,peri 2389289318555
r2.change_teacher('Dr Neeraj Sharma')
rectangle.maths_teacher='Prof Manoj Mehta'
print ('AFTER .....who was teaching maths to all the students ?? ')
rectangle.disp_maths_teacher_name()
r3 = rectangle()
r4 = rectangle(35)
|
cdd9f943517d52b66aa58b319f6c475e8d46a175 | Arvaesri/Python_OS | /Regex/Domain_change_qwikilabtest.py | 2,935 | 3.953125 | 4 | #!/usr/bin/env python3
# Analisar um arquivo CSV com uma lista de emails de varios dominios e criar um novo arquivo CSV com a
# lista de emails com domino antigo para o novo dominio ultilizando oque foi aprendido com arquivos
# regex e CSV
# A Lista de email foi dada no computador remoto
import re
import csv
def contains_domain(address, domain):
"""Returns True if the email address contains the given,domain,in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False
def replace_domain(address, old_domain, new_domain):
"""Replaces the old domain with the new domain in the received address."""
old_domain_pattern = r'' + old_domain + '$'
address = re.sub(old_domain_pattern, new_domain, address)
return address
def main():
"""Processes the list of emails, replacing any instances of the old domain with the new domain."""
old_domain, new_domain = 'abc.edu', 'xyz.edu'
csv_file_location = '<csv_file_location>'
report_file = '<path_to_home_directory>' + '/updated_user_emails.csv'
user_email_list = []
old_domain_email_list = []
new_domain_email_list = []
with open(csv_file_location, 'r') as f:
user_data_list = list(csv.reader(f))
user_email_list = [data[1].strip() for data in user_data_list[1:]]
for email_address in user_email_list:
if contains_domain(email_address, old_domain):
old_domain_email_list.append(email_address)
replaced_email = replace_domain(email_address,old_domain,new_domain)
new_domain_email_list.append(replaced_email)
email_key = ' ' + 'Email Address'
email_index = user_data_list[0].index(email_key)
for user in user_data_list[1:]:
for old_domain, new_domain in zip(old_domain_email_list, new_domain_email_list):
if user[email_index] == ' ' + old_domain:
user[email_index] = ' ' + new_domain
f.close()
with open(report_file, 'w+') as output_file:
writer = csv.writer(output_file)
writer.writerows(user_data_list)
output_file.close()
main()
# Resultado do arquivo com dominio trocado
# Full Name, Email Address
# Blossom Gill, blossom@xyz.edu
# Hayes Delgado, nonummy@utnisia.com
# Petra Jones, ac@xyz.edu
# Oleg Noel, noel@liberomauris.ca
# Ahmed Miller, ahmed.miller@nequenonquam.co.uk
# Macaulay Douglas, mdouglas@xyz.edu
# Aurora Grant, enim.non@xyz.edu
# Madison Mcintosh, mcintosh@nisiaenean.net
# Montana Powell, montanap@semmagna.org
# Rogan Robinson, rr.robinson@xyz.edu
# Simon Rivera, sri@xyz.edu
# Benedict Pacheco, bpacheco@xyz.edu
# Maisie Hendrix, mai.hendrix@xyz.edu
# Xaviera Gould, xlg@utnisia.net
# Oren Rollins, oren@semmagna.com
# Flavia Santiago, flavia@utnisia.net
# Jackson Owens, jackowens@xyz.edu
# Britanni Humphrey, britanni@ut.net
# Kirk Nixon, kirknixon@xyz.edu
# Bree Campbell, breee@utnisia.net
# Arquivo com o dominio antigo
# Full Name, Email Address
# Blossom Gill, blossom@abc.edu
# Hayes Delgado, nonummy@utnisia.com
# Petra Jones, ac@abc.edu
# Oleg Noel, noel@liberomauris.ca
# Ahmed Miller, ahmed.miller@nequenonquam.co.uk
# Macaulay Douglas, mdouglas@abc.edu
# Aurora Grant, enim.non@abc.edu
# Madison Mcintosh, mcintosh@nisiaenean.net
# Montana Powell, montanap@semmagna.org
# Rogan Robinson, rr.robinson@abc.edu
# Simon Rivera, sri@abc.edu
# Benedict Pacheco, bpacheco@abc.edu
# Maisie Hendrix, mai.hendrix@abc.edu
# Xaviera Gould, xlg@utnisia.net
# Oren Rollins, oren@semmagna.com
# Flavia Santiago, flavia@utnisia.net
# Jackson Owens, jackowens@abc.edu
# Britanni Humphrey, britanni@ut.net
# Kirk Nixon, kirknixon@abc.edu
# Bree Campbell, breee@utnisia.net |
7ca5fbf5c1b50d524290dfe9b01012596901cb70 | sssunda/solve_algorithms | /programmers/print_star.py | 142 | 3.5625 | 4 | def solution(m, n):
for _ in range(n):
print('*'*m)
if __name__ == '__main__':
m = 5
n = 3
solution(m, n)
|
c1597b97dffa6cdc2546830b0977395ed25eeb6d | MadSkittles/leetcode | /99.py | 707 | 3.734375 | 4 | from common import TreeNode
class Solution:
def recoverTree(self, root):
self.first, self.second, self.pre = None, None, None
def traverse(node):
if not node: return
traverse(node.left)
if self.pre and self.pre.val >= node.val:
if not self.first:
self.first = self.pre
self.second = node
self.pre = node
traverse(node.right)
traverse(root)
self.first.val, self.second.val = self.second.val, self.first.val
if __name__ == '__main__':
solution = Solution()
root = TreeNode.list2Tree([3, 4, 1, 5, 2])
solution.recoverTree(root)
print(root)
|
a8da73e51f835401692e007eeefb336f38c598f9 | Sholie/MergeConflict | /Clock/Clock/Main.py | 1,327 | 3.84375 | 4 | class Counter(object):
def __init__(self, name):
self._name = name
self._count = 0
def Increment(self):
self._count = self._count + 1
def Reset(self):
self._count = 0
def Value(self):
return self._count
class Clock(object):
def __init__(self):
self._hours = Counter("Hours")
self._minutes = Counter("Minutes")
self._seconds = Counter("Seconds")
def Reset(self):
self._hours.Reset()
self._minutes.Reset()
self._seconds.Reset()
def Tick(self):
if(self._seconds.Value() < 59):
self._seconds.Increment()
else:
self._seconds.Reset()
if(self._minutes.Value() < 59):
self._minutes.Increment()
else:
self._minutes.Reset()
if(self._hours.Value() < 23):
self._hours.Increment()
else:
self._hours.Reset()
def Read(self):
return str(self._hours.Value()).zfill(2) + ":" + str(self._minutes.Value()).zfill(2) + ":" + str(self._seconds.Value()).zfill(2)
i = 0
j = 0
c = Clock()
while i < 60:
i += 1
while j < 60:
j += 1
c.Tick()
print(c.Read()) |
f37e107de9e63bc65370b0126722c84f9af021ad | ioannispol/Py_projects | /maths/trig_calculator.py | 2,379 | 4.5 | 4 | """
A trigonometry calculator using Python
"""
import math as mt
import os
def right_angle():
"""Use Pythoagorian theorem to calculate, angles and sides of the triangle"""
while True:
os.system('cls')
print("*" * 40)
print("To calculate the Hypotenuse type 'hyp': ")
print("To calculate the Opposite type 'opo':")
print("To calculate the Adjacent type 'adj': ")
print("To exit type 'q': ")
print("*" * 40)
userInput = (str((input("Enter your option: ")))).lower()
# Calculate the hypotenuse of the triangle
# Todo: Make an integration and use the first user input to feed other options!
if userInput == 'hyp':
degrees = float(input("Enter the angle in degrees: "))
opposite = float(input("Enter the value of the opposite: "))
result = float(opposite * mt.sin(degrees))
print("The value of the Hypotenuse is: {:.3}".format(result))
elif userInput == 'opo':
degrees = float(input("Enter the angle in degrees: "))
hypotenuse = float(input("Enter the value of hypotenuse: "))
result = float(hypotenuse * mt.sin(degrees))
print(" The value of the Opposite is: {:.3}".format(result))
elif userInput == 'adj':
print("What are your data? Hypotenuse or Opposite? ")
data = str(input("For Hypotenuse type 'hyp' and Opposite type 'opo': "))
if data == 'hyp':
hypotenuse = float(input("Enter the value of hypotenuse: "))
theta = float(input("Enter the angle in degrees: "))
result = hypotenuse * mt.cos(theta)
print("The value of Adjacent is: {:.3}".format(result))
elif data == 'opo':
opposite = float(input("Enter the value of the opposite: "))
theta = float(input("Enter the angle in degrees: "))
result = abs(opposite / mt.tan(theta))
print("The value of Adjacent is: {:.3}".format(result))
else:
break
elif userInput == 'q':
break
else:
print("Invalid input!! Please try again")
print("Press Enter to quit")
return right_angle()
right_angle()
# Todo: create more options for trigonometry calculations
|
ea57e22c92749f47ce07da4883da4031dbb4b859 | woodie/coding_challenges | /dump_tree.py | 1,418 | 4.03125 | 4 | #!/usr/bin/env python
class Iterator:
def __init__(self, node):
self.stack = [node]
def next(self):
if self.has_next():
node = self.stack.pop()
for child in reversed(node.children):
self.stack.append(child)
return node
else:
return None
def has_next(self):
return len(self.stack) > 0
class Node:
def __init__(self, value, children=[]):
self.value = value
self.children = children
class Tree:
def __init__(self, root):
self.root = root
def to_s(self):
return Tree.to_string(self.root)
def print_out(self):
Tree.print_tree(self.root)
@staticmethod
def to_string(node):
memo = node.value + ": "
for sub in node.children:
memo += Tree.to_string(sub)
return memo
@staticmethod
def print_tree(node):
print (node.value + ":"),
for sub in node.children:
Tree.print_tree(sub)
# "ab"
# / \
# "ef" "gh"
# / | \ \
# "x" "y" "z" "p"
root = Node("ab", [Node("ef", [
Node("x"), Node("y"), Node("z")]),
Node("gh", [Node("p")])])
Tree.print_tree(root)
print
print Tree.to_string(root)
tree = Tree(root)
tree.print_out()
print
print tree.to_s()
iter = Iterator(root)
while(iter.has_next()):
print (iter.next().value + ":"),
print
"""
ab: ef: x: y: z: gh: p:
ab: ef: x: y: z: gh: p:
ab: ef: x: y: z: gh: p:
ab: ef: x: y: z: gh: p:
ab: ef: x: y: z: gh: p:
"""
|
5e31bed80a6511e0024103393b4224e8fe8ae954 | CableX88/Projects | /Python projects/Project 3 Test.py | 569 | 4.1875 | 4 | shell_list = ['Puka','Cone', 'Driftwood', 'Sea Glass','Starfish']
value_list =[]
college_friends = ['Alex']
for s in college_friends:
print("Hello",s,"! Please tell me how many different shells you collected:")
for shell in shell_list:
val = int(input("Enter how many shells collected:"))
value_list.append(val)
print(value_list)
##print(shell_list)
zipped_tup = list(zip(shell_list,value_list))
print(zipped_tup)
print(shell,':',val)
##shell_list = shell_list.copy()
print('\n')
|
d8cf7d28ca5c13e5780ae3f7730bfd78418377d9 | vparjunmohan/Python | /Basics-Part-I/program103.py | 153 | 4.21875 | 4 | 'Write a Python program to extract the filename from a given path.'
import os
fpath = input('Enter file path ')
print()
print(os.path.basename(fpath))
|
a376dc99ff8408ec085543f815c28dcef09aefab | jmullen2782/projects | /diceroll.py | 525 | 4.28125 | 4 | '''
Created on Dec 17, 2018
@author: jmullen19
'''
import random
roll = random.randint(1,6)
target=int(input('Please enter a valid number from 1 to 6:'))
while target<0 or target>6:
target=int(input('Please enter a valid number from 1 to 6:'))
again = int("Press enter to roll again")
while 1>=target>=6:
print('You rolled', roll)
again = int('Please enter to roll again')
while target==roll:
print('It took you', roll, 'tries to roll the target number.')
|
278fcef5dfdc817f6b615935576e437eefb3c6aa | MBartsch71/Python-CodeWars | /fibonacci_3.py | 219 | 3.75 | 4 | def fib_3(signature,n):
if n < 3:
return signature
else:
signature.append(signature[-3] + signature[-2] + signature[-1])
n -= 1
return fib_3(signature,n)
print(fib_3([1,1,1],10)) |
374d58ca09ceaea05799ee9a45ce51c08a7a9c5e | ralitsapetrina/Programing_fundamentals | /Objects_and_Classes/animals.py | 2,163 | 3.8125 | 4 | class Dog:
def __init__(self, name, age, num_legs):
self.name = name
self.age = age
self.legs = num_legs
def talk(self):
return 'I\'m a Distinguishedog, and I will now produce a distinguished sound! Bau Bau.'
def show_info(self):
return f'Dog: {self.name}, Age: {self.age}, Number Of Legs: {self.legs}'
class Cat:
def __init__(self, name, age, intelligence_quotient):
self.name = name
self.age = age
self.iq = intelligence_quotient
def talk(self):
return 'I\'m an Aristocat, and I will now produce an aristocratic sound! Myau Myau.'
def show_info(self):
return f'Cat: {self.name}, Age: {self.age}, IQ: {self.iq}'
class Snake:
def __init__(self, name, age, cruelty_coef):
self.name = name
self.age = age
self.cruel_coef = cruelty_coef
def talk(self):
return 'I\'m a Sophistisnake, and I will now produce a sophisticated sound! Honey, I\'m home.'
def show_info(self):
return f'Snake: {self.name}, Age: {self.age}, Cruelty: {self.cruel_coef}'
def create_an_animal(data_list, animal):
return animal(data_list[1], data_list[2], data_list[3])
def print_animals(animal_dict):
for value in animal_dict.values():
print(f'{value.show_info()}')
dogs_dict = {}
cats_dict = {}
snakes_dict = {}
animals_dicts_list = [dogs_dict, cats_dict, snakes_dict]
while True:
command_list = input().split()
if command_list[0] == 'I\'m':
break
if command_list[0] == 'talk':
for animal in animals_dicts_list:
if command_list[1] in animal.keys():
print(animal.get(command_list[1]).talk())
break
else:
if command_list[0] == 'Dog':
dogs_dict[command_list[1]] = create_an_animal(command_list, Dog)
elif command_list[0] == 'Cat':
cats_dict[command_list[1]] = create_an_animal(command_list, Cat)
elif command_list[0] == 'Snake':
snakes_dict[command_list[1]] = create_an_animal(command_list, Snake)
print_animals(dogs_dict)
print_animals(cats_dict)
print_animals(snakes_dict) |
6787877ed5bfa375497709217772f3323e4269d4 | AntonioEstela/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 223 | 3.890625 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
new_list = my_list.copy()
for pos in range(len(my_list)):
if new_list[pos] == search:
new_list[pos] = replace
return new_list
|
35a8ba23a82b4aa8b6f48deb4bb775ba73439d7d | vinayvarm/programs | /GreatestNumber.py | 290 | 4.125 | 4 | n1=int(input('enter number'))
n2=int(input('enter number'))
n3=int(input('enter number'))
if n1>=n2 and n1>=n3:
print("n1 is greatest", n1)
elif n2>=n3 and n2>=n1:
print("n2 is greatest",n2)
elif n1==n2 and n2==n3:
print('value are same')
else:
print("n3 is greatest",n3)
|
a1074e4904536a13128cdc5fddc1cb0b3767a9d6 | miguelmontiel30/Ejercicios_Python | /Clases en python/Edad.py | 354 | 3.90625 | 4 | print (''
)
print (' **** Calculador de edad ***** ')
print ('')
a=int(raw_input('Introduce tu Anio de nacimiento. '))
print ('')
b=int( raw_input ('Introduce el Anio actual. '))
print ('')
if a>1910 and a<b:
edad=b-a
print ('')
print ('Tu Anio de nacimiento es:'),a, ('Tu edad es: '),edad
else:
print ('Datos no validos') |
6ad733819c755e58d5e2e2a96b8690ee3af471b4 | underchemist/projecteuler | /python/sudopy.py | 13,848 | 4.125 | 4 | # Mon 24 Mar 2014 11:12:47 PM EDT
class Sudoku:
"""
An exercise in building a python class.
Sudoku
******
Generate solutions of sudoku puzzles from string and list inputs.
Totally unoptimized at this point!
solve() : Attempt to find solution to sudoku puzzle using basic
recursive backtracking algorithm. Return a new Sudoku instance of
the solved puzzle.
_from_string(puzzle_str) : Parse sudoku puzzle from string
reading left to right into list of list. The first nine characters
of the string correspond to the first row of the sudoku puzzle. Use
numbers 1-9 to represent values in the puzzle and a '.' to indicate
an empty grid point.
"""
def __init__(self, puzzle=None):
self.input_grid = ''
# leave as empty if no input provided
if isinstance(puzzle, str):
self.from_string(puzzle)
elif isinstance(puzzle, list):
self.from_list(puzzle)
else:
self.puzzle = None
def __str__(self):
if isinstance(self.puzzle, type(None)):
return repr(self)
else:
# output = '+-----+-----+-----+\n'
output = '+' + ('-' * 7 + '+') * 3 + '\n'
for i, row in enumerate(self.puzzle):
output += '| {0} {1} {2} '.format(self._is_zero(row[0]),
self._is_zero(row[1]),
self._is_zero(row[2]))
output += '| {0} {1} {2} '.format(self._is_zero(row[3]),
self._is_zero(row[4]),
self._is_zero(row[5]))
output += '| {0} {1} {2} |'.format(self._is_zero(row[6]),
self._is_zero(row[7]),
self._is_zero(row[8]))
output += '\n'
if (i + 1) % 3 == 0:
output += '+' + ('-' * 7 + '+') * 3 + '\n'
return output
# initial declarations and problem parameters
_NROWS = 9
_NCOLS = 9
def _is_zero(self, value):
if value:
return value
else:
return '.'
def _from_list(self, puzzle_lst):
# ensure proper conversion if input is list or list of lists
if all(isinstance(sublist, list) for sublist in puzzle_lst):
return puzzle_lst
# build list of list if input is flat
elif all(isinstance(val, int) for val in puzzle_lst):
return [puzzle_lst[i * 9: i * 9 + 9] for i in range(self._NROWS)]
else:
raise ValueError('incorrect input puzzle')
def _from_string(self, puzzle_str):
# converts string to list since read_from_list is workhorse
p = []
for i in range(self._NROWS):
row = puzzle_str[i * 9: i * 9 + 9]
p.append([int(val) if val != '.' else 0 for val in row])
return p
def _copy(self):
""" make deep copy of puzzle """
return [[val for val in lst] for lst in self.puzzle]
def _col(self, col):
""" return column from sudoku puzzle """
return [row[col] for row in self.puzzle]
def _along_row(self, pos_val):
""" check if move valid in row """
if pos_val[2] in (self.puzzle[pos_val[0]][:pos_val[1]] +
self.puzzle[pos_val[0]][pos_val[1] + 1:]):
return False
else:
return True
def _along_col(self, pos_val):
""" check if move valid in column """
col = self._col(pos_val[1])
if pos_val[2] in (col[:pos_val[0]] + col[pos_val[0] + 1:]):
return False
else:
return True
def _in_box(self, pos_val):
""" check if move valid in sub box """
block_row = pos_val[0] // 3 * 3
block_col = pos_val[1] // 3 * 3
block = [self.puzzle[r][c] for r in range(block_row, block_row + 3)
for c in range(block_col, block_col + 3)
if r != pos_val[0] or c != pos_val[1]]
if pos_val[2] in block:
return False
else:
return True
def _check_move(self, pos_val):
return (self._along_row(pos_val) and self._along_col(pos_val)
and self._in_box(pos_val))
# def _set_initial_state(self):
# init_state = set()
# for r in range(self._NROWS):
# for c in range(self._NCOLS):
# if self.puzzle[r][c]:
# init_state.add((r, c))
# return init_state
def _candidates(self, r, c):
candidates = []
for i in range(1, 10):
if self._check_move((r, c, i)):
candidates.append(i)
return candidates
def _unassigned(self, grid):
for r in range(self._NROWS):
for c in range(self._NCOLS):
if not grid[r][c]:
return (r, c)
return (-1, -1)
def _unassigned_with_least_candidates(self, grid):
min = (10, 10, 10) # impossible values... think of more pythonic way
for r in range(self._NROWS):
for c in range(self._NCOLS):
if not grid[r][c]:
n = len(self._candidates(r, c))
if n == 1:
return (r, c)
if n < min[2]:
min = (r, c, n)
if min != (10, 10, 10):
return min[:2]
else:
return (-1, -1)
def _naked_single(self, r, c):
candidates = self._candidates(r, c)
if len(candidates) == 1:
return candidates[0]
else:
return False
def _next(self, grid, r, c):
for i in range(1, 10):
if self._check_move((r, c, i)):
grid[r][c] = i
if self._solve(grid):
return True
grid[r][c] = 0
return False
def _apply_rules(self, grid):
moves = []
for r in range(self._NROWS):
for c in range(self._NCOLS):
naked_single = self._naked_single(r, c)
if naked_single:
moves.append((r, c, naked_single))
grid[r][c] = naked_single
if self._solve(grid):
return True
else:
for move in moves:
grid[move[0]][move[1]] = 0
return False
def _solve(self, grid):
""" use backtracking to solve sudoku """
r, c = self._unassigned_with_least_candidates(grid)
if r == -1 and c == -1:
return True
return self._next(grid, r, c)
def from_list(self, puzzle_lst):
self.puzzle = self._from_list(puzzle_lst)
def from_string(self, puzzle_str):
self.puzzle = self._from_string(puzzle_str)
self.input_grid = puzzle_str
def show(self):
print(self)
def is_valid(self, grid):
# check sudoku validity
for r in range(self._NROWS):
for c in range(self._NCOLS):
if grid[r][c]:
if not self._check_move((r, c, grid[r][c])):
return False
return True
def solve(self):
# make a copy
original = self._copy()
if self._solve(self.puzzle):
solution = Sudoku(self.puzzle)
self.puzzle = original
return solution
else:
print('no solution')
def _backtrack_sage(self, puzzle, n=3):
# Arrays sizes are n^4, and n^2, with 3n^2-2n-1 for second slot of peers, n = 4
i, j, count, level, apeer = 0, 0, 0, 0, 0
nsquare, npeers, nboxes = 0, 0, 0
grid_row, grid_col, grid_corner = 0, 0, 0
peers = [[]]
box = [[]]
available = [[]]
card = []
hint, symbol, abox = 0, 0, 0
feasible = 0
nfixed = []
fixed = [[]]
fixed_symbol = [[]]
process, asymbol, alevel, process_level, process_symbol = 0, 0, 0, 0, 0
# sanity check on size (types)
# n is "base" dimension
# nsquare is size of a grid
# nboxes is total number of entries
nsquare = n * n
nboxes = nsquare * nsquare
npeers = 3 * n * n - 2 * n - 1 # 2(n^2-1)+n^2-2n+1
# "Peers" of a box are boxes in the same column, row or grid
# Like the conflict graph when expressed as a graph coloring problem
for level in range(nboxes):
# location as row and column in square
# grids are numbered similarly, in row-major order
row = level // nsquare
col = level % nsquare
grid_corner = (row - (row % n)) * nsquare + (col - (col % n))
grid_row = row // n
grid_col = col // n
count = -1
# Peers' levels in same grid, but not the box itself
for i in range(n):
grid_level = grid_corner + i * nsquare + j
if grid_level != level:
count += 1
peers[level][count] = grid_level
# Peers' levels in the same row, but not in grid
for i in range(nsquare):
if (i // 3 != grid_col):
count += 1
peers[level][count] = row * nsquare + i
# Peers' levels in same column, but not in grid
for i in range(nsquare):
if (i // 3 != grid_row):
count += 1
peers[level][count] = col + i * nsquare
# Initialize data structures
# Make every symbol available initially for a box
# And make set cardinality the size of symbol set
for level in range(nboxes):
box[level] = -1
card[level] = nsquare
for j in range(nsquare):
available[level][j] = 0
# For non-zero entries of input puzzle
# (1) Convert to zero-based indexing
# (2) Make a set of size 1 available initially
for level in range(nboxes):
# location as row and column in square
# grids are numbered similarly, in row-major order
hint = puzzle[level] - 1
if hint != -1:
# Limit symbol set at the hint's location to a singleton
for j in range(nsquare):
available[level][j] = 1
available[level][hint] = 0
card[level] = 1
# Remove hint from all peers' available symbols
# Track cardinality as sets adjust
for i in range(npeers):
apeer = peers[level][i]
available[apeer][hint] += 1
if available[apeer][hint] == 1:
card[apeer] -= 1
# Start backtracking
solutions = []
level = 0
box[level] = -1
while (level > -1):
symbol = box[level]
if (symbol != -1):
# restore symbols to peers
for i in range(nfixed[level]):
alevel = fixed[level][i]
asymbol = fixed_symbol[level][i]
for j in range(npeers):
abox = peers[alevel][j]
available[abox][asymbol] -= 1
if available[abox][asymbol] == 0:
card[abox] += 1
# move sideways in search tree to next available symbol
symbol += 1
while (symbol < nsquare) and (available[level][symbol] != 0):
symbol += 1
if symbol == nsquare:
# fell off the end sideways, backup
level = level - 1
else:
box[level] = symbol
# Remove elements of sets, adjust cardinalities
# Descend in search tree if no empty sets created
# Can't break early at an empty set
# or we will confuse restore that happens immediately
feasible = True
fixed[level][0] = level
fixed_symbol[level][0] = symbol
count = 0
process = -1
while (process < count) and feasible:
process += 1
process_level = fixed[level][process]
process_symbol = fixed_symbol[level][process]
for i in range(npeers):
abox = peers[process_level][i]
available[abox][process_symbol] += 1
if available[abox][process_symbol] == 1:
card[abox] -= 1
if card[abox] == 0:
feasible = False
if card[abox] == 1:
count += 1
fixed[level][count] = abox
asymbol = 0
while (available[abox][asymbol] != 0):
asymbol += 1
fixed_symbol[level][count] = asymbol
nfixed[level] = process + 1
if feasible:
if level == nboxes - 1:
# Have a solution to save, stay at this bottom-most level
# Once Cython implements closures, a yield can go here
solutions.append([box[i] + 1 for i in range(nboxes)])
else:
level = level + 1
box[level] = -1
return solutions
|
7ca9712dc3e1936c91e208e5672ed47513005a8a | guna7222/CompletePythonDeveloper | /PythonBasics/tuple.py | 311 | 3.828125 | 4 | # Tuple
# A tuple is a collection which is ordered, unchangeable, and allow duplicate items.
weapons = ('hello', 'world', 'python')
print(weapons[1:2])
print('python' in weapons)
print(len(weapons))
# tuple methods
# count
print(weapons.count('python'))
# index
print(weapons.index('world'))
|
4fd20eb1a1ebe37cd95ccb1508e0e313bce93f94 | vijay-Jonathan/Python_Training | /bin/39_classes_encapsulation.py | 3,934 | 4.34375 | 4 | """
3 ways we can write programs
1) Without writing single function, we were able to write program
2) Scenario where we need to repeat the code, there we wrote functions
3) Some scenario, we need to write classes
In this section, we are discussing on point-3
3) Some scenario, we need to write classes
In what scenarios, writing class will be helpful
"""
print("Storing student data-Without using classes")
print("-"*40)
#------------------------------------
student_1_name = "Student-1"
student_1_sub1_marks = 70
student_1_sub2_marks = 80
student_2_name = "Student-2"
student_2_sub1_marks = 80
student_2_sub2_marks = 90
avg_sub1_marks = (student_1_sub1_marks + student_2_sub1_marks)/2
avg_sub2_marks = (student_1_sub2_marks + student_2_sub2_marks)/2
total_sub1_marks = student_1_sub1_marks + student_2_sub1_marks
total_sub2_marks = student_1_sub2_marks + student_2_sub2_marks
total_marks = student_1_sub1_marks + student_2_sub1_marks + student_1_sub2_marks + student_2_sub2_marks
print(" Student_1_name : ",student_1_name)
print(" Student_2_name : ",student_2_name)
print("avg_sub1_marks : ",avg_sub1_marks)
print("avg_sub2_marks : ",avg_sub2_marks)
print("total_sub1_marks : ",total_sub1_marks)
print("total_sub2_marks : ",total_sub2_marks)
print("total_marks : ",total_marks)
print("-"*40)
#------------------------------------
# If my college/classroom is having 100 students then
# We need to write name,sub1_marks,sub2_marks for all 100 people
# Can we use functions????
def my_func(n,m1,m2):
student_1_name = n
student_1_sub1_marks = m1
student_1_sub2_marks = m2
my_func("Student-1",70,80)
my_func("Student-2",80,90)
# Now how to compute
# 1) avg_sub1_marks
# 2) avg_sub2_marks
# 3) total_sub1_marks
# 4) total_sub2_marks
# 5) total_marks
# First approach will work, without any issues
# Second -way, where we wrote function above will not work.
# Because, once the function executed, all data stored inside the
# Function will be erased. In our case, since we are computing
# avg_sub1_marks, avg_sub2_marks, total_sub1_marks, total_sub2_marks,
# and total_marks. We need all students data should be stored in some
# variables, so that throughout the program we can make use of it.
#------------------------------------
print("Storing student data-using classes")
print("-"*40)
#------------------------------------
# Finally, we need all students data avaiable throught the program
class Student1:
name = "Student-1"
sub1_marks = 70
sub2_marks = 80
class Student2:
name = "Student-2"
sub1_marks = 80
sub2_marks = 90
avg_sub1_marks = (Student1.sub1_marks + Student2.sub1_marks)/2
avg_sub2_marks = (Student1.sub2_marks + Student2.sub2_marks)/2
total_sub1_marks = Student1.sub1_marks + Student2.sub1_marks
total_sub2_marks = Student1.sub2_marks + Student2.sub2_marks
total_marks = Student1.sub1_marks + Student2.sub1_marks + Student1.sub2_marks + Student2.sub2_marks
print(" Student_1_name : ",Student1.name)
print(" Student_2_name : ",Student2.name)
print("avg_sub1_marks : ",avg_sub1_marks)
print("avg_sub2_marks : ",avg_sub2_marks)
print("total_sub1_marks : ",total_sub1_marks)
print("total_sub2_marks : ",total_sub2_marks)
print("total_marks : ",total_marks)
print("-"*40)
#------------------------------------
# Without writing classes also we were able to store in a varaible.
# Then what advantage we got using class?
# ADVANTAGE : Encapsulation :
# - We were able to put each student data in seperate block.
# - We got privacy for each student data
#------------------------------------
# Class names Student1 and Student2 are 2 objects
# So, Student1 and Student2 - called CLASS OBJECTS
# variable inside each class : name, sub1_marks, sub2_marks are called CLASS VARIABLE
# all Student1 class varaibles stored inside Student1 object
# similarly, all Student2 class varaibles stored inside Student2 object
#------------------------------------ |
9d39b852ef101df99a0029664b9e3f13e38367e0 | udhayprakash/PythonMaterial | /python3/01_Introduction/m_semicoln_operator.py | 1,219 | 4.03125 | 4 | #!/usr/bin/python3
"""
Purpose: Multiple statements in same line
, logic separator
; statement completion operator
"""
print("Hello" "world")
print("Hello", "world")
print("Hello", 21312)
# print("Hello" 21312)
# SyntaxError: invalid syntax. Perhaps you forgot a comma?
print("Hello", 21312, 213, 123 + 123 - 3)
print()
# semicoln operator
# Method 1
num1 = 100
num2 = 200
sum_of_numbers = num1 + num2
print("Sum of Number:", sum_of_numbers)
# Method 2 using ; operator
num1 = 100; num2 = 200; sum_of_numbers = num1 + num2; print("Sum of Number:", sum_of_numbers)
# conclusion
# 1. ; is optional. Will not change anything
# 2. ; is important if we need write more than one statement in same line
# 3. Unnecessarily placing semicolon at end of statement will increase computation time
"""
python -c "print('hello world')"
python -c "num1 = 123; num2 = 300; sum_of_numbers = num1 + num2; print('Sum of Number:', sum_of_numbers)"
langauge
- scripting language Ex: batch, shell, ....
- General Purpose programming langauge Ex: c, c++, java,
Python is both scripting and General purpose programming language
.bat
cd dirctory1
cd subdirectory2
ping google.com > result.txt
"""
|
f7b15de5e73135519571b13d16a80f061fd962c5 | sifatmahmud/snake-water-gun-game-1.0-using-Python | /main.py | 2,849 | 3.796875 | 4 | try:
pc_point = 0
player_point = 0
roundn = 0
while roundn < 10:
roundn = roundn + 1
import random
list2 = ["snake", "water", "gun"]
list1 = random.choice(list2)
print("\n snake , water , gun")
inp1 = input("choose one of this : ") # user input
# if else statement start here
if list1 == "snake" and inp1 == "water":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "water" and inp1 == "snake":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "gun" and inp1 == "water":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "water" and inp1 == "gun":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "gun" and inp1 == "snake":
print("computer choice", list1)
print("computer won this round")
pc_point += 1
elif list1 == "snake" and inp1 == "gun":
print("computer choice", list1)
print("you won this round")
player_point += 1
elif list1 == "snake" and inp1 == "snake":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
elif list1 == "gun" and inp1 == "gun":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
elif list1 == "water" and inp1 == "water":
print("computer choice", list1)
print("both are winners this round")
pc_point += 1
player_point += 1
else:
print("your input maybe wrong ! please try again")
# finished code
print("you have finished", roundn, "round , and you have", 10 - roundn, "left")
if roundn == 10 and player_point < pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("Computer the winner of this game")
elif roundn == 10 and player_point > pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("You are the winner of this game")
elif roundn == 10 and player_point == pc_point:
print("\nGame is over")
print("your point =", player_point, "and compuer point =", pc_point)
print("Both are the winner of this game")
except Exception as k:
print(k)
|
c08103bc1027c34c9dc81b219a5a002f840b71a1 | AlSavva/Algorytms_and_data_structure | /Lesson3/task7_les3.py | 994 | 4.15625 | 4 | # В одномерном массиве целых чисел определить два наименьших элемента. Они
# могут быть как равны между собой (оба минимальны), так и различаться.
def gen_list(n, m, l):
"""Функция генерирует список заданной длинны l из случайных целых чисел в
диапазоне от n до m."""
from random import randint
return [randint(n, m) for _ in range(l)]
my_list = gen_list(-1, 10, 10)
print(my_list)
imin1 = 0
imin2 = 1
if my_list[imin1] > my_list[imin2]:
imin1, imin2 = imin2, imin1
for i in range(3, len(my_list)):
if my_list[i] < my_list[imin1]:
if my_list[imin1] < my_list[imin2]:
imin2 = imin1
imin1 = i
elif my_list[i] < my_list[imin2]:
imin2 = i
print(f'Минимальные элементы массива: {my_list[imin1]} и {my_list[imin2]}')
|
c1890a8b20e2b6ac71c14850036a50809ed71779 | akulaj9/classwork | /lesson_function.py | 972 | 3.84375 | 4 | import math
def hello(name):
print('Hello, %s!!!' % (name))
hello('world')
hello('Allce')
hello('Eugenia')
def pretty_print(value):
print('------------------------')
print('Value: %s' % value)
print('------------------------')
def rectangls_square(height, width):
result = height * width
return result
result1 = rectangls_square(10, 20)
pretty_print(result1)
def square_square(side):
return rectangls_square(side, side)
pretty_print(square_square(50))
def add_and_multiply(x, y):
result_add = x + y
result_mult = x * y
return result_add, result_mult, x**y
result2, result3, result4 = add_and_multiply(2, 3)
pretty_print(result2)
pretty_print(result3)
pretty_print(result4)
def celcius2faringeheit(degrees):
return degrees * 9/5 + 32
print("%.2f" % celcius2faringeheit(36.6))
result = round(celcius2faringeheit(36.6))
def circle_square(radius):
return math.pi * radius**2
print("%.2f" % circle_square(20))
|
b5ba90565268eaf46bdfcfa634c2af3aef4a9f43 | bweinberg42/enae380 | /Lab5/lab5.py | 986 | 3.5625 | 4 | import time
import easygopigo3 as easy
pig = easy.EasyGoPiGo3()
d_sensor = pig.init_distance_sensor()
def apply_phys_limit(d):
"""
Moves the PiGo forward until the IR distance sensor detects an obstacle
within the distance (mm) specified.
Parameters
__________
d : float
the distance measured by our sensor
Returns
-------
float
the last read distance of the obstacle
"""
dist = d_sensor.read_mm()
while (dist > d):
pig.forward()
dist = d_sensor.read_mm()
pig.stop()
return(dist)
def apply_time_limit(dt, speed):
"""
Moves the PiGo forward for a specified time (sec) and motor-speed (dps).
Parameters
__________
dt : float
the duration (s) for which to move forward
speed : int
the speed (dps) at which to move forward
"""
pig.set_speed(speed)
pig.forward()
time.sleep(dt)
pig.stop()
pass
|
e7af49af16f4d51b8aea10121ecce1321b252d11 | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill 3.2 Tamina.py | 336 | 4.28125 | 4 | #Given two non-zero integers, print "YES" if exactly one of them is positive and print "NO" otherwise.# -*- coding: utf-8 -*-
x = int( input ("Please enter a number: "))
y = int (input ("Please enter another number: "))
if (x > 0) and (y < 0):
print ("YES")
elif (x < 0) and (y > 0):
print ("YES")
else:
print ('No')
|
df25349601b2387581292b3f2ad907e2c043f3ba | steveSuave/practicing-problem-solving | /leetcode/permutations_of_distinct_integers.py | 468 | 3.5625 | 4 | # Given an array nums of distinct integers, return all the possible permutations.
# You can return the answer in any order.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ret = []
if len(nums)==0:
return [ret]
for element in nums:
for permutation in \
self.permute(list(filter(lambda e: e!=element, nums))):
ret.append([element]+permutation)
return ret
|
24c641004763757334929863f9a30e8aea7c10e2 | BankNatchapol/OpenCV-Basic-Funtions | /bluring.py | 751 | 3.6875 | 4 | import cv2 as cv
img = cv.imread('photos/nature.jpg')
cv.imshow('Original', img)
# blur is using average bluring method by average surrounding pixel.
avg = cv.blur(img, (7,7))
cv.imshow('Avg', avg)
# Gaussian blur is bluring using kernel weight, 0 is sigmaX is standard deviation in x direction value.
gauss = cv.GaussianBlur(img, (7,7), 0)
cv.imshow('Gaussian', gauss)
# Median blur is using median value in kernel size.
median = cv.medianBlur(img, 3)
cv.imshow('Median', median)
# Bilateral blur is bluring using d-> kernel size, sigmaColor-> number of pixel that consider when blur and sigmaSpace-> space that will random choose pixel to consider.
bilateral = cv.bilateralFilter(img, 9, 50, 40)
cv.imshow('Bilateral', bilateral)
cv.waitKey(0) |
5ff85f4d90ff1ad6c1185fc31df4e02f8c6eded3 | Arshdeep-kapoor/Python | /chapter7-ques07.py | 1,437 | 3.9375 | 4 | import math
class LinearEquation:
def __init__(self,a,b,c,d,e,f):
self.__a=a
self.__b=b
self.__c=c
self.__d=d
self.__e=e
self.__f=f
def getA(self):
return self.__a
def getB(self):
return self.__b
def getC(self):
return self.__c
def getD(self):
return self.__d
def getE(self):
return self.__e
def getF(self):
return self.__f
def isSolvable(self):
if ((self.__a*self.__d)-(self.__b*self.__c))==0:
return True
def getX(self):
if self.isSolvable():
print("The equation has no solution")
else:
print (((self.__e*self.__d)-(self.__b*self.__f))/((self.__a*self.__d)-(self.__b*self.__c)))
def getY(self):
if self.isSolvable():
print("The equation has no solution")
else:
result = (((self.__a*self.__f)-(self.__e*self.__c))/((self.__a*self.__d)-(self.__b*self.__c)))
print(result)
a = eval(input("enter the value of a"))
b = eval(input("enter the value of b"))
c = eval(input("enter the value of c"))
d = eval(input("enter the value of d"))
e = eval(input("enter the value of e"))
f = eval(input("enter the value of f"))
LinearEquation=LinearEquation(a,b,c,d,e,f)
LinearEquation.getX()
LinearEquation.getY() |
dd06af9c9348ce77cbe7af6b0f7a8fc6eb7cabdd | roudra323/100-Days-of-code-Python-pro-Bootcamp | /codes/Day-10/calc.py | 906 | 4.21875 | 4 | # Calculator
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def main(num1):
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation from the line above: ")
num2 = int(input("What's the second number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
print("You wanna continue with the current value: ")
x = input()
if x == 'y':
main(num1=answer)
else:
main(num1=int(input("What's the first number?: ")))
main(num1=int(input("What's the first number?: ")))
|
1736f4b1904d72173408b5b656d5110375f5c9d1 | satya-9blue/coding-practice | /sample.py | 62 | 3.640625 | 4 | num1=int(input())
num2=int(input())
num=num1+num2
print(num)
|
1d1d5f3e3aad68bd0a4efdc60ab66dbda36cc167 | Axel-One/1810530156-ujian-abj | /interfaces.py | 538 | 3.53125 | 4 | ulang = "ya"
while ulang == "ya" :
pilih = input("Input data Trunk Interface baru :")
if pilih == "yes" :
Interface = input("Masukan Hostname Switch : ")
file = open("db.interface.txt",'a')
file.write("\n"+"Masukan Hostname Switch :" + Interface)
Interface = input("Masukan nama interface :")
file = open("db.interface.txt",'a')
file.write("\n"+"Masukan nama interface :" + Interface)
else :
file = open("db.interface.txt",'r')
print(file.read())
break ; |
ef7e29401215ff13c0ebed4f705ee43ac0f7d653 | ivekhov/hexletpy | /functions/tasks_funcs/recursion.py | 1,775 | 4.6875 | 5 |
'''
В упражнении вам нужно будет реализовать две взаимно рекурсивные функции (то есть использующие косвенную рекурсию):
is_odd должна возвращать True, если число нечётное,
is_even должна возвращать True, если число чётное.
Для простоты считаем, что аргументы всегда будут неотрицательными.
Вы, конечно, можете реализовать функции независимыми. Но задание призывает попробовать именно косвенную рекурсию!
# P@$$Temp_2020
'''
def is_even(num):
if num == 0:
return True
if num == 1:
return False
return is_even(num % 2)
def is_odd(num):
if num == 1:
return True
if num == 0:
return False
return is_odd(num % 2)
######## bad
# def is_even_(num):
# if num == 0:
# return True
# if is_odd(num - 1):
# return False
# return is_even(num % 2)
# def is_odd(num):
# if num == 1:
# return True
# if is_even(num - 1):
# return False
# return is_odd(num % 2)
##############
# exxample
# def is_odd_x(number):
# return False if number == 0 else is_even(number - 1)
# def is_even_x(number):
# return True if number == 0 else is_odd(number - 1)
#######################################################3
def test_is_odd():
assert not is_odd(42)
assert is_odd(99)
def test_is_even():
assert not is_even(99)
assert is_even(42)
if __name__ == '__main__':
test_is_odd()
test_is_even()
print('Tests passed')
|
8aed12da18a5381e565f155e09e728faacc270cc | chan-alex/python-explorations | /pythonic_practice/slice_objects.py | 526 | 4.15625 | 4 | #!/usr/bin/env python3
print("start")
list_of_numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
# Sequence slices actually return Slice object.
# The 2 expression below are equivalent:
list_of_numbers[1:5]
# >>> list_of_numbers[1:5]
# [2, 3, 4, 5]
list_of_numbers[slice(1,5)]
# >>> list_of_numbers[slice(1,5)]
# [2, 3, 4, 5
# The useful thing about slice objects is that you can name them.
first_10 = slice(0,10)
next_10 = slice(10,20)
print(list_of_numbers[first_10])
print(list_of_numbers[next_10])
|
a2e524ae70e4083863dd9da96dc700efe6c99ebb | sasakishun/atcoder | /AGC/AGC028/A.py | 278 | 3.5625 | 4 | import math
def lcm(x, y):
return int((x * y) // math.gcd(x, y))
n, m = [int(i) for i in input().split()]
s = input()
t = input()
span = math.gcd(n, m)
for i in range(span):
if s[int(n/span)*i] != t[int(m/span)*i]:
print("-1")
exit()
print(lcm(n, m)) |
d296b1b839c2534ce6af36a9992b3b532d8b6196 | lekshmirajendran/assignment | /sam.py | 5,379 | 3.90625 | 4 | import sqlite3
conn=sqlite3.connect('stock.db')
cursor=conn.cursor()
# CREATE TABLE inventory (
# Item_id INTEGER,
# Item_name VARCHAR,
# );
print "1.add items\t2.delete item\t3.edit item details\t4.display"
opt=input()
if opt==1:
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
Item_id=raw_input("enter the item Id (Id must begin with a character. eg:I201):\t")
id_list=[]
Item_flag=0
for data in all_list_items:
id_list.append(data[0])
for i in range(0,len(id_list)):
if Item_id==id_list[i]:
Item_flag=1
if Item_flag==0:
print Item_id," is not in the item list so it is a new item"
Item_name=raw_input("enter the item name :\t")
Item_cost=raw_input("enter the item cost :\t")
Item_quantity=raw_input("enter the item quantity:\t")
Item_tax=raw_input("enter the item tax:\t")
perishable=raw_input("If the Item is perishable enter 1....else....0:\t")
Item_exp_date=raw_input("enter the item expiry date(DD/MM/YYYY):\t")
sql="INSERT INTO inventory_manage(Item_id,Item_name,Item_cost,Item_quantity,Item_tax,perishable,Item_exp_date)values(?,?,?,?,?,?,?)"
cursor.execute(sql,(Item_id,Item_name,Item_cost,Item_quantity,Item_tax,perishable,Item_exp_date))
else:
print Item_id, " is in the item list"
Item_cost=raw_input("enter the item cost :\t")
Item_quantity=raw_input("enter the item quantity:\t")
Item_tax=raw_input("enter the item tax:\t")
Item_exp_date=raw_input("enter the item expiry date (DD/MM/YYYY):\t")
sql="UPDATE inventory_manage SET Item_cost=?,Item_quantity=?,Item_tax=?,Item_exp_date=?"
cursor.execute(sql,(Item_cost,Item_quantity,Item_tax,Item_exp_date))
print Item_id," is inserted to the stock"
conn.commit()
#conn.close()
if opt==2:
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
Item_id=raw_input("enter the item Id (Item_id must begin with a character. eg:I201:\t")
id_list=[]
Item_flag=0
for data in all_list_items:
id_list.append(data[0])
for i in range(0,len(id_list)):
if Item_id==id_list[i]:
Item_flag=1
if Item_flag==0:
print Item_id, " is not in the item list so it cannot be deleted"
else :
print Item_id, " is in the item list"
sql="DELETE FROM inventory_manage WHERE Item_id=?"
cursor.execute(sql,(Item_id,))
dele=cursor.execute('select * from inventory_manage')
print "\n\n",Item_id," IS SUCCESSFULLY DELETED"
conn.commit()
if opt==3:
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
Item_id=raw_input("enter the item Id to be edited (Id must begin with a character. eg:I201):\t")
id_list=[]
Item_flag=0
for data in all_list_items:
id_list.append(data[0])
for i in range(0,len(id_list)):
if Item_id==id_list[i]:
Item_flag=1
if Item_flag==0:
print Item_id, " is not in the item list so it is a new item"
else:
print Item_id, " is in the item list"
edit_flag=1
while edit_flag==1:
print "What do you like to edit\n1.Item name\n2.Item cost\n3.Item tax\n4.Item quantity\n5.Item expiry date\npress 6 to exit"
choice=input()
if choice==1:
Item_name=raw_input("enter the item name :\t")
sql="UPDATE inventory_manage SET Item_name=? WHERE Item_id=?"
cursor.execute(sql,(Item_name,Item_id))
#print "The name of the Item with Id ",Item_id," is edited to ",Item_name
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
elif choice==2:
Item_cost=raw_input("enter the item cost :\t")
sql="UPDATE inventory_manage SET Item_cost=? WHERE Item_id=?"
cursor.execute(sql,(Item_cost,Item_id))
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
#print "The cost of the Item with Id ",Item_id," is edited to ",Item_cost
elif choice==3:
Item_tax=raw_input("enter the item tax :\t")
sql="UPDATE inventory_manage SET Item_tax=? WHERE Item_id=?"
cursor.execute(sql,(Item_tax,Item_id))
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
#print "The tax of the Item with Id ",Item_id," is edited to ",Item_tax
elif choice==4:
Item_quantity=raw_input("enter the item quantity :\t")
sql="UPDATE inventory_manage SET Item_quantity=? WHERE Item_id=?"
cursor.execute(sql,(Item_quantity,Item_id))
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
#print "The quantity of the Item with Id ",Item_id," is edited to ",Item_quantity
elif choice==5:
Item_exp_date=raw_input("enter the item expiry date (DD/MM/YYYY):\t")
sql="UPDATE inventory_manage SET Item_exp_date=? WHERE Item_id=?"
cursor.execute(sql,(Item_exp_date,Item_id))
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print all_list_items
#print "The expiry date of the Item with Id ",Item_id," is edited to ",Item_exp_date
else:
edit_flag=0
conn.commit()
if opt==4:
cursor.execute('select * from inventory_manage')
all_list_items=cursor.fetchall()
print "Item_id\t\tItem_name\tItem_cost\tItem_quantity\tItem_tax\tperishable\tItem_exp_date"
for data in all_list_items:
print data[0],"\t\t",data[1],"\t\t",data[2],"\t\t",data[3],"\t\t",data[4],"\t\t",data[5]
conn.commit()
conn.close()
|
0d2b90332c71e54725f517ea95330a8cf4794fdb | CHEHAKPATHAK25/107-Project | /student.py | 440 | 3.828125 | 4 | #importing modules
import pandas as pd
import plotly.express as px
#read csv data using pd module
dataframe = pd.read_csv("data.csv")
#selecting a particular student
#finding the mean of student of attempts in each level
#creating a graph
mean = dataframe.groupby(["student_id", "level"], as_index=False) ["attempt"].mean()
scatter_graph = px.scatter(mean, x="student_id", y="level", color="attempt", size="attempt")
scatter_graph.show() |
2467f6556c6553a6da7c349d47d3fbe233688bfb | MarkNahabedian/insteon_experiments | /singleton.py | 513 | 3.578125 | 4 | # Implementation of the singleton pattern. Taken from
# https://www.python.org/download/releases/2.2/descrintro/.
#
# Recomendation: Add a guard to any __init__ method to return
# immediately if the singleton instance has already been initialized.
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.