blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
bee651095528b75cabc10603da35740455a85cb4
|
limapedro2002/PEOO_Python
|
/Lista_02/Pedro Lucas/exr1.py
| 1,310 | 3.5625 | 4 |
print ("RESPONDA APENAS COM SIM E NAO")
res1 = str(input("Telefonou para a vítima? 1/Sim ou 0/Não: "))
res2 = str(input("Esteve no local do crime? 1/Sim ou 0/Não: "))
res3 = str(input("Mora perto da vítima? 1/Sim ou 0/Não: "))
res4 = str(input("Devia para a vítima? 1/Sim ou 0/Não: "))
res5 = str(input("Já trabalhou com a vítima? 1/Sim ou 0/Não: "))
soma_respostas = res1 + res2 + res3 + res4 + res5
veredito = 0
if res1 == "nao":
veredito = veredito
elif res1 == "sim":
veredito = veredito + 1
if res2 == "nao":
veredito = veredito
elif res2 == "sim":
veredito = veredito + 1
if res3 == "nao":
veredito = veredito
elif res3 == "sim":
veredito = veredito + 1
if res4 == "nao":
veredito = veredito
elif res4 == "sim":
veredito = veredito + 1
if res5 == "nao":
veredito = veredito
elif res5 == "sim":
veredito = veredito + 1
if (soma_respostas == 0):
veredito == "Inocente"
if (soma_respostas == 1):
veredito == "Inocente"
if (soma_respostas == 2):
veredito == "Suspeito"
if (soma_respostas == 3):
veredito == "Cúmplice"
if (soma_respostas == 4):
veredito == "Cúmplice"
if (soma_respostas == 5):
veredito == "Assassino"
print("o interrogado é: %s"%veredito)
print("respostas dadas pelo interrogado: %s"%res1, res2, res3, res4, res5)
|
074f7381bd494349f59a3e06267dc9157e3426a0
|
Beatriceeei/introduction_to_algorithm
|
/chapter10/queue.py
| 1,336 | 3.859375 | 4 |
class Queue():
def __init__(self, max_size=20):
self.max_size = max_size
self.data = [-1]*max_size
self.head = 0
self.tail = 0
def incre(self, i):
if i >= self.max_size - 1:
return 0
return i+1
@property
def is_empty(self):
return self.tail == self.head
def enqueue(self,x):
if self.incre(self.tail) == self.head:
raise Exception("queue is full")
self.data[self.tail] = x
self.tail = self.incre(self.tail)
def dequeue(self):
if self.tail == self.head:
raise Exception("queue is empty")
r = self.data[self.head]
self.head = self.incre(self.head)
return r
def __str__(self):
if self.tail == self.head:
return str([])
if self.tail > self.head:
return str(self.data[self.head:self.tail])
else:
first_half = self.data[self.head:self.max_size]
second_half = self.data[:self.tail]
return str(first_half+second_half)
#
# queue = Queue()
# print queue
# for i in xrange(20):
# queue.enqueue(i)
# print i, queue,queue.head,queue.tail
#
# print queue.head, queue.tail
# print queue
# for i in xrange(20):
# print queue.dequeue(),queue,queue.head,queue.tail
# print queue
|
b9523b5037da679547637297dd854d1c2ae387c6
|
subbiahs84/LearnPython
|
/MyCode.py
| 108 | 3.765625 | 4 |
x = input("Enter the 1st Number ")
y= input("Enter the 2nd Number ")
s=x+y
print(s)
z=int(x)+int(y)
print(z)
|
0dedbe312006b5991ed7e7aac56a00186d0b1157
|
ramosemilio/COVIDualizations
|
/CSV_TOTAL_CASE_CHECKER.py
| 1,688 | 3.671875 | 4 |
#COVID CSV CHECKER v0.11
#By Emilio Ramos
from tkinter import filedialog
import tkinter
root = tkinter.Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",
title = "Select file",
filetypes = (("csv files","*.csv"),("all files","*.*")))
print (root.filename)
#POINT TO JHU .CSV WITH COVIV DATA
file_path = root.filename
#POINT TO JHU .CSV WITH COVIV DATA
file_path = root.filename
#FUNCTION TO READ .CSV FILE AND RETURN ROWS OF DATA
def read_data(path):
data_file = open(path,"r")
data_all = data_file.read().splitlines()
return data_all
#CREATE GLOBAL data_lines variable
data_lines = read_data(file_path)
#FUNCTION TO READ .CSV COLUMN HEADERS TO MAKE SURE DATA SCTRUCTURE HASN'T CHANGED
#SECOND TUPLE VALUE IS USED TO COMPARE TO MAKE SURE ALL LINES ARE SAME LENGTH
#AFTER PARSING AND DATA PROCESSING
def get_header_info():
return (data_lines[0], len(data_lines[0].split(",")))
#FUNCTION TO GET COUNTRY-LEVEL DATA
def check_lines():
#ITERATE OVER .CSV DATA
for line in data_lines:
#SPLIT ROW INTO LIST AFTER REPLACING COMMAS IN FULL PLACE NAMES
line = line.replace(", ", "|")
split_line = line.split(",")
#IF LIST == country_name ADD TO country_data
if len(split_line) > get_header_info()[1]:
print (line)
def get_deaths():
deaths_num = 0
death_lines = data_lines
del death_lines[0]
for line in death_lines:
split = line.split(",")
deaths_num = deaths_num + int(split[-1])
return deaths_num
check_lines()
print ("Entries= "+ str(get_header_info()[1]))
print ("Total Cases: "+str(get_deaths()))
|
e2e5897a1aaf40ace75aeb2a367c059799c62cea
|
seanchen513/leetcode
|
/greedy/0435_nonoverlapping_intervals.py
| 8,968 | 4.09375 | 4 |
"""
435. Non-overlapping Intervals
Medium
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
from typing import List
###############################################################################
"""
Solution 1: Greedy algo. Sort intervals by starting endpoint. Keep count of
number of intervals discarded.
Check if adjacent intervals overlap. If they do, keep the one with the
smaller right endpoint.
O(n log n): due to sorting. Loop is O(n).
O(1) extra space: for in-place sort.
"""
class Solution:
def eraseOverlapIntervals(self, a: List[List[int]]) -> int:
if not a:
return 0
a.sort()
n = len(a)
count = 0 # number of intervals discarded
last_endpt = a[0][1]
for i in range(1, n):
if a[i][0] < last_endpt: # overlap
count += 1
last_endpt = min(last_endpt, a[i][1])
else:
last_endpt = a[i][1]
return count
###############################################################################
"""
Solution 2: Greedy algo. Sort intervals by right endpoint. Keep count of
number of non-overlapping intervals.
Check if adjacent intervals overlap. If they don't overlap, keep the current
interval. If they overlap, then discard the current interval since it has a
greater right endpoint.
O(n log n): due to sorting. Loop is O(n).
O(1) extra space: for in-place sort.
"""
class Solution2:
def eraseOverlapIntervals(self, a: List[List[int]]) -> int:
if not a:
return 0
a.sort(key=lambda x: x[1])
n = len(a)
count = 1 # count of non-overlapping intervals
last_endpt = a[0][1]
for i in range(1, n):
if a[i][0] >= last_endpt: # no overlap
count += 1
last_endpt = a[i][1]
return n - count # number of intervals discarded
###############################################################################
"""
Solution 3: DP, sorting by left endpoints.
dp[i] = number of non-overlapping intervals up to interval i
dp[i] = max(dp[j]) + 1 for 0 <= j < i, where intervals i and j don't overlap
O(n^2) time: need a nested loop to check max(dp[j]).
O(n) extra space: for dp table.
"""
class Solution3:
def eraseOverlapIntervals(self, a: List[List[int]]) -> int:
if not a:
return 0
a.sort()
n = len(a)
dp = [1]*n # number of non-overlapping intervals up to interval i
for i in range(n):
mx = 0
for j in range(i):
if a[i][0] >= a[j][1]: # no overlap
mx = max(mx, dp[j])
dp[i] = mx + 1
return n - max(dp) # number of intervals discarded
###############################################################################
"""
Solution 4: DP, sorting by right endpoints.
dp[i] = number of non-overlapping intervals up to interval i
dp[i] = max(dp[i-1], 1 + max(dp[j])) for 0 <= j < i,
where intervals i and j don't overlap
There are 2 cases:
(1) Include interval i as a non-overlapping interval. Need to review prior
intervals j to check which ones don't overlap with interval i. Take the
max(dp[j]) of these and add 1 for interval i. Suffices to find the largest
such j by traversing backwards from i-1.
(2) Don't include interval i as a non-overlapping interval. Then the number
of non-overlapping intervals is just incremented by 1.
O(n^2) time: need a nested loop to check max(dp[j]).
O(n) extra space: for dp table.
"""
class Solution4:
def eraseOverlapIntervals(self, a: List[List[int]]) -> int:
if not a:
return 0
a.sort(key=lambda x: x[1])
n = len(a)
dp = [1]*n # number of non-overlapping intervals up to interval i
for i in range(n):
mx = 0
for j in range(i-1, -1, -1):
if a[i][0] >= a[j][1]: # no overlap
mx = max(mx, dp[j])
break
dp[i] = max(dp[i-1], 1 + mx)
return n - max(dp) # number of intervals discarded
###############################################################################
if __name__ == "__main__":
def test(arr, comment=None):
print("="*80)
if comment:
print(comment)
print()
print(f"\nintervals = {arr}")
res = sol.eraseOverlapIntervals(arr)
print(f"\nres = {res}")
sol = Solution() # greedy, sort by left endpoints
sol = Solution2() # greedy, sort by right endpoints
sol = Solution3() # DP, sort by left endpoints
sol = Solution4() # DP, sort by right endpoints
comment = "LC ex1; answer = 1"
arr = [[1,2],[2,3],[3,4],[1,3]]
test(arr, comment)
comment = "LC ex2; answer = 2"
arr = [[1,2],[1,2],[1,2]]
test(arr, comment)
comment = "LC ex3; answer = 0"
arr = [[1,2],[2,3]]
test(arr, comment)
comment = "LC test case; answer = 187"
arr = [
[
-100,
-87
],
[
-99,
-44
],
[
-98,
-19
],
[
-97,
-33
],
[
-96,
-60
],
[
-95,
-17
],
[
-94,
-44
],
[
-93,
-9
],
[
-92,
-63
],
[
-91,
-76
],
[
-90,
-44
],
[
-89,
-18
],
[
-88,
10
],
[
-87,
-39
],
[
-86,
7
],
[
-85,
-76
],
[
-84,
-51
],
[
-83,
-48
],
[
-82,
-36
],
[
-81,
-63
],
[
-80,
-71
],
[
-79,
-4
],
[
-78,
-63
],
[
-77,
-14
],
[
-76,
-10
],
[
-75,
-36
],
[
-74,
31
],
[
-73,
11
],
[
-72,
-50
],
[
-71,
-30
],
[
-70,
33
],
[
-69,
-37
],
[
-68,
-50
],
[
-67,
6
],
[
-66,
-50
],
[
-65,
-26
],
[
-64,
21
],
[
-63,
-8
],
[
-62,
23
],
[
-61,
-34
],
[
-60,
13
],
[
-59,
19
],
[
-58,
41
],
[
-57,
-15
],
[
-56,
35
],
[
-55,
-4
],
[
-54,
-20
],
[
-53,
44
],
[
-52,
48
],
[
-51,
12
],
[
-50,
-43
],
[
-49,
10
],
[
-48,
-34
],
[
-47,
3
],
[
-46,
28
],
[
-45,
51
],
[
-44,
-14
],
[
-43,
59
],
[
-42,
-6
],
[
-41,
-32
],
[
-40,
-12
],
[
-39,
33
],
[
-38,
17
],
[
-37,
-7
],
[
-36,
-29
],
[
-35,
24
],
[
-34,
49
],
[
-33,
-19
],
[
-32,
2
],
[
-31,
8
],
[
-30,
74
],
[
-29,
58
],
[
-28,
13
],
[
-27,
-8
],
[
-26,
45
],
[
-25,
-5
],
[
-24,
45
],
[
-23,
19
],
[
-22,
9
],
[
-21,
54
],
[
-20,
1
],
[
-19,
81
],
[
-18,
17
],
[
-17,
-10
],
[
-16,
7
],
[
-15,
86
],
[
-14,
-3
],
[
-13,
-3
],
[
-12,
45
],
[
-11,
93
],
[
-10,
84
],
[
-9,
20
],
[
-8,
3
],
[
-7,
81
],
[
-6,
52
],
[
-5,
67
],
[
-4,
18
],
[
-3,
40
],
[
-2,
42
],
[
-1,
49
],
[
0,
7
],
[
1,
104
],
[
2,
79
],
[
3,
37
],
[
4,
47
],
[
5,
69
],
[
6,
89
],
[
7,
110
],
[
8,
108
],
[
9,
19
],
[
10,
25
],
[
11,
48
],
[
12,
63
],
[
13,
94
],
[
14,
55
],
[
15,
119
],
[
16,
64
],
[
17,
122
],
[
18,
92
],
[
19,
37
],
[
20,
86
],
[
21,
84
],
[
22,
122
],
[
23,
37
],
[
24,
125
],
[
25,
99
],
[
26,
45
],
[
27,
63
],
[
28,
40
],
[
29,
97
],
[
30,
78
],
[
31,
102
],
[
32,
120
],
[
33,
91
],
[
34,
107
],
[
35,
62
],
[
36,
137
],
[
37,
55
],
[
38,
115
],
[
39,
46
],
[
40,
136
],
[
41,
78
],
[
42,
86
],
[
43,
106
],
[
44,
66
],
[
45,
141
],
[
46,
92
],
[
47,
132
],
[
48,
89
],
[
49,
61
],
[
50,
128
],
[
51,
155
],
[
52,
153
],
[
53,
78
],
[
54,
114
],
[
55,
84
],
[
56,
151
],
[
57,
123
],
[
58,
69
],
[
59,
91
],
[
60,
89
],
[
61,
73
],
[
62,
81
],
[
63,
139
],
[
64,
108
],
[
65,
165
],
[
66,
92
],
[
67,
117
],
[
68,
140
],
[
69,
109
],
[
70,
102
],
[
71,
171
],
[
72,
141
],
[
73,
117
],
[
74,
124
],
[
75,
171
],
[
76,
132
],
[
77,
142
],
[
78,
107
],
[
79,
132
],
[
80,
171
],
[
81,
104
],
[
82,
160
],
[
83,
128
],
[
84,
137
],
[
85,
176
],
[
86,
188
],
[
87,
178
],
[
88,
117
],
[
89,
115
],
[
90,
140
],
[
91,
165
],
[
92,
133
],
[
93,
114
],
[
94,
125
],
[
95,
135
],
[
96,
144
],
[
97,
114
],
[
98,
183
],
[
99,
157
]
]
test(arr, comment)
|
09994a52c008293fb3207e79c3075ad1b59d447d
|
Nana0606/basic-algorithms
|
/nowcoder/huawei_find_brothers_words.py
| 946 | 3.78125 | 4 |
# python3
# -*- coding: utf-8 -*-
# @Author : lina
# @Time : 2019/1/18 10:32
def isBrothers(element, target):
if element == target:
return False
if sorted(element) == sorted(target):
return True
if __name__ == '__main__':
contents = [elem for elem in input().split(' ') if elem != '']
total_number = int(contents[0])
candidate = contents[1:1+total_number]
target = contents[-2]
order = int(contents[-1])
brothers = []
for i in range(total_number):
if isBrothers(candidate[i], target):
brothers.append(candidate[i])
brothers_sort = sorted(brothers)
print("brothers_sort is::", brothers_sort)
print("order is::", order)
if order - 1 < len(brothers_sort): # 必须判断边界
print(str(len(brothers)), "\n", brothers_sort[order - 1])
else: # 注意输出格式:加换行
print(str(len(brothers)))
|
6533a61d24d6051c3ac584f574dd9127300879a0
|
daniel-lee-dl/Advent-2020
|
/Day 18/Day18.py
| 4,887 | 4.03125 | 4 |
from __future__ import annotations
from typing import List, Tuple
class IncorrectMath:
def __init__(self, problems):
self.problems: List[List[str]] = problems
self.answers: List[str] = []
# This function will accept two numbers and an operation ("+" or "*") and will either add or multiply the numbers
def _add_or_multiply_numbers(self, num1: str, num2: str, oper: str):
if oper == "+":
return int(num1) + int(num2)
if oper == "*":
return int(num1) * int(num2)
# If an operation (+ or *) is specified to be of higher priority, do those operations first
def _evaluate_priority_operations(self, problem: List[str], priOper: str):
index: int = 0
while index < len(problem):
if problem[index] == priOper:
problem[index - 1] = self._add_or_multiply_numbers(
num1=problem[index - 1],
oper=problem.pop(index),
num2=problem.pop(index),
)
index += 1
return problem
# If the problem has par, reduce everything within the par (including inner par)
# into a singe number, and return an updated problem (with no par included)
def _evaluate_parenthesis(self, problem: str, priOper: str):
par: List[str] = []
openBrackets: int = 0
closeBrackets: int = 0
# Extract the portion of the problem contained in par
while openBrackets != closeBrackets or openBrackets == 0:
var = problem.pop(0)
par.append(var)
if var == "(":
openBrackets += 1
elif var == ")":
closeBrackets += 1
# Because everything in par is guaranteed to have an opening bracket as
# its first element and a closing bracket as its last element, remove those from the list
par.pop(0)
par.pop(-1)
while len(par) != 1:
# If any additional brackets are found, recurseively call the function
if "(" in par:
par = par[: par.index("(")] + self._evaluate_parenthesis(
par[par.index("(") :], priOper
)
# If there are priority operations in par, evaluate those first
elif priOper in par:
par = self._evaluate_priority_operations(problem=par, priOper=priOper)
# For the first three items, which will be a number, an operation, and a second number,
# calculate the product and replace the first element with it
else:
par[0] = self._add_or_multiply_numbers(
num1=par[0],
oper=par.pop(1),
num2=par.pop(1),
)
return par + problem
def _solve_problem(self, problem, priOper):
index = 0
# Follow the following steps:
# Look at the first three variables from the equation at all times, which will be the set of (num, oper, num). Ex: 3 * 3
# If there is a par at any one of the num spots, call self._evaluate_parenthesis(),
# which will evaluate everything within the paranthesis and return a number
while index < len(problem):
if problem[index] == "(":
problem = problem[:index] + self._evaluate_parenthesis(
problem[index:], priOper=priOper
)
index += 1
# If a priority operation is specified, do the priority operations first
while len(problem) != 1:
if priOper in problem:
problem = self._evaluate_priority_operations(
problem=problem, priOper=priOper
)
else:
problem[0] = self._add_or_multiply_numbers(
num1=problem[0], oper=problem.pop(1), num2=problem.pop(1)
)
return problem[0]
def solve_all_problems(self, priOper: str = ""):
# For all problems in the list self.problems, call self._solve_problem
for problem in self.problems:
self.answers.append(self._solve_problem(problem=problem, priOper=priOper))
return self.answers
def load_file():
f = open("Day18Input.txt", "r")
problems: List[List[int]] = [
list(line.strip().replace(" ", "")) for line in f.readlines()
]
return problems
def main():
problemSolver = IncorrectMath(load_file())
print("Answer to Part 1: ", sum(problemSolver.solve_all_problems()))
problemSolver = IncorrectMath(load_file())
print(
"Answer to Part 2: ",
sum(problemSolver.solve_all_problems(priOper="+")),
)
if __name__ == "__main__":
(main())
|
a1d9ef833fc5bd5ec62de4f899345823686f133d
|
AndreySamolyak/HomeWork.Project
|
/Lesson5/execrises/flat.py
| 5,073 | 3.671875 | 4 |
#!/usr/bin/python3
""" Ремонт в квартире
Есть квартира (2 комнаты и кухня). В квартире планируется ремонт: нужно
поклеить обои, покрасить потолки и положить пол.
Подсказка: для округления вверх и вниз используйте:
import math
math.ceil(4.2) # 5
math.floor(4.2) # 4
Примечание: Для простоты, будем считать, что обои над окном и над дверью
не наклеиваются.
----------------
Дополнительно:
Сделать у объекта квартиры метод, выводящий результат в виде сметы:
[Комната: ширина: 3 м, длина: 5 м, высота: 2.4 м]
Обои 400x6=2400 руб.
Краска 1000x1=1000 руб.
Ламинат 800x8=6400 руб.
[Комната: ширина: 3 м, длина: 4 м, высота: 2.4 м]
Обои 400x5=2000 руб.
Краска 1000x1=1000 руб.
Ламинат 800x7=5600 руб.
[Кухня: ширина: 3 м, длина: 3 м, высота: 2.4 м]
Обои 400x4=1600 руб.
Краска 1000x1=1000 руб.
Ламинат 800x5=4000 руб.
---------------------------
Итого: 25000 руб.
"""
import math
class Materials:
def __init__(self, square, price):
self.square = square
self.price = price
def __str__(self):
return ('[Объект класса Materials: square=%s, price=%s]'
% (self.square, self.price))
class Wallpaper(Materials):
def __init__(self, width, height, price):
Materials.__init__(self, width * height, price)
self.weight = width
self.height = height
def __str__(self):
return ('[Объект класса Wallpaper: square=%s, price=%s, weight=%s, height=%s]'
% (self.square, self.price, self.weight, self.height))
class Paint(Materials):
def __init__(self, weight, consumption, price):
Materials.__init__(self, weight / consumption, price)
self.weight = weight
self.consumption = consumption
def __str__(self):
return ('[Объект класса Paint: square=%s, price=%s, weight=%s, consumption=%s]'
% (self.square, self.price, self.weight, self.consumption))
class Laminate(Materials):
def __init__(self, width, height, quantity, price):
Materials.__init__(self, width * height * quantity, price)
self.width = width
self.height = height
self.quantity = quantity
def __str__(self):
return ('[Объект класса Laminate: square=%s, price=%s, width=%s, height=%s, quantity=%s]'
% (self.square, self.price, self.width, self.height, self.quantity))
class Room:
def __init__(self, width, length, height, window_width, door_width):
self.width = width
self.length = length
self.height = height
self.window_width = window_width
self.door_width = door_width
def __str__(self):
return ('[Объект класса Room: width=%s, length=%s, height=%s, window_width=%s, door_width=%s]'
% (self.width, self.length, self.height, self.window_width, self.door_width))
def paintRoof(self, paint):
roof_square = self.width * self.length
return (roof_square / paint.square) * paint.price
def putLaminate(self, laminate):
floor_square = self.width * self.length
return (floor_square / laminate.square) * laminate.price
def glueWallpapers(self, wallpaper):
walls_square = (self.width - self.door_width) * self.height + (self.length - self.window_width) * self.height
return (walls_square / wallpaper.square) * wallpaper.price
def fullPrice(self, paint, laminate, wallpaper):
return self.paintRoof(paint) + self.putLaminate(laminate) + self.glueWallpapers(wallpaper)
class Flat:
def __init__(self, rooms):
self.rooms = rooms
def __str__(self):
return ('[Объект класса Flat: rooms=%s]'
% (self.rooms))
def addRoom(self, room):
self.rooms.append(room)
return self.rooms
def removeRoom(self, room):
self.rooms.remove(room)
return self.rooms
def countFullPrice(self, paint, laminate, wallpaper):
self.fullprice = 0
for room in self.rooms:
self.fullprice += room.fullPrice(paint, laminate, wallpaper)
return self.fullprice
a = Materials(12, 12)
b = Wallpaper(10, 0.6, 100)
c = Paint(5, 0.2, 50)
d = Laminate(0.2, 2, 10, 150)
e = Room(5, 3, 2.4, 1.4, 0.7)
f = Room(4, 4, 2.4, 1.4, 0.7)
print(a)
print(b)
print(c)
print(d)
print(e)
print(math.ceil(e.paintRoof(c)))
print(math.ceil(e.putLaminate(d)))
print(math.ceil(e.glueWallpapers(b)))
print(math.ceil(e.fullPrice(c, d, b)))
g = Flat([e, f])
print(g)
print(math.ceil(g.countFullPrice(c, d, b)))
|
4030bf1a7625a461153f6afc7dab977e27ab9e55
|
n-ill/blackjack
|
/blackjack_pygame.py
| 7,707 | 3.5 | 4 |
import blackjack
import pygame
class button():
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self, win, outline=None):
# Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)
if self.text != '':
font = pygame.font.SysFont('timesnewroman', 24)
text = font.render(self.text, 1, (0, 0, 0))
win.blit(text, (
self.x + int(self.width / 2 - text.get_width() / 2), self.y + int(self.height / 2 - text.get_height() / 2)))
def isOver(self, pos):
# Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
def draw_player_cards(a_screen, a_game):
player_card_offset = 0
for card in game.player_cards:
card_image = card_images[f"{card[0]}{card[1]}"]
card_resize = pygame.transform.scale(card_image, (125, 175))
screen.blit(card_resize, (435 + player_card_offset, 425))
player_card_offset += 25
def draw_dealer_cards(a_screen, a_game):
dealer_card_offset = 0
for card in game.dealer_cards:
card_image = card_images[f"{card[0]}{card[1]}"]
card_resize = pygame.transform.scale(card_image, (125, 175))
screen.blit(card_resize, (435 + dealer_card_offset, 5))
dealer_card_offset += 25
def draw_text(a_text, a_screen, x, y, a_width):
font = pygame.font.SysFont('timesnewroman', 22)
text = font.render(a_text, 1, (0,0,0))
pygame.draw.rect(a_screen, (0, 0, 0), pygame.Rect(x - 2, y - 2, 34, 34))
pygame.draw.rect(a_screen, (255,255,255), pygame.Rect(x,y, a_width,30))
a_screen.blit(text, (x,y))
def draw_inital_dealer_cards(screen, game):
dealer_card_offset = 0
card_image = card_images[
f"{game.dealer_cards[0][0]}{game.dealer_cards[0][1]}"] # first dealer card - second faced down
card_resize = pygame.transform.scale(card_image, (125, 175))
screen.blit(card_resize, (435 + dealer_card_offset, 5))
dealer_card_offset += 25
card_back = pygame.image.load('card_back.png').convert_alpha()
card_back_resize = pygame.transform.scale(card_back, (125, 175))
screen.blit(card_back_resize, (435 + dealer_card_offset, 5))
dealer_card_offset += 25
WIDTH = 999
HEIGHT = 679
card_images = {}
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Blackjack')
clock = pygame.time.Clock()
background = pygame.image.load('blackjack_table.jpeg')
for suit in ['S', 'C', 'H', 'D']: # spades, clubs, hearts, diamonds
for num in range(2, 11):
card_images[f"{num}{suit}"] = pygame.image.load(f'./card_images/{num}{suit}.png')
for face in ['J', 'Q', 'K', 'A']: # jack, queen, king, ace
card_images[f"{face}{suit}"] = pygame.image.load(f'./card_images/{face}{suit}.png')
button_deal = button((0, 255, 255), 800, 600, 50, 50, 'Deal')
button_hit = button((0, 255, 0), 200, 600, 50, 50, 'Hit')
button_stand = button((255, 0, 0), 275, 600, 50, 50, 'Stand')
button_play_again = button((200, 200, 200), 800, 500, 100, 50, 'Play Again')
game_over = False
while not game_over:
game = blackjack.Blackjack()
game.shuffle()
has_dealt = False
players_turn = True
running = True
done = False
while running:
screen.blit(background, (0, 0))
if not has_dealt:
button_deal.draw(screen, (0,0,0))
if has_dealt:
draw_player_cards(screen, game)
draw_text(str(game.player_total), screen, 500, 625, 30) # player's score
if players_turn:
if not done:
button_hit.draw(screen, (0, 0, 0))
button_stand.draw(screen, (0, 0, 0))
draw_inital_dealer_cards(screen, game)
else: # dealer's turn
draw_dealer_cards(screen, game)
game.calc_dealer_total()
draw_text(str(game.dealer_total), screen, 500, 205, 30) # dealer's score
if game.dealer_total < 17:
game.dealer_hit()
else:
done = True
if game.player_total == 21:
draw_text('Blackjack!', screen, 300, 475, 100)
draw_text('You Win!', screen, int(WIDTH / 2) - 25, int(HEIGHT / 2), 100)
done = True
elif game.player_total > 21:
draw_text('Bust!', screen, 350, 475, 50)
draw_text('You Lose!', screen, int(WIDTH / 2) - 25, int(HEIGHT / 2), 100)
done = True
else:
if game.dealer_total == 21:
draw_text('Blackjack!', screen, 300, 50, 100)
draw_text('You Lose!', screen, int(WIDTH/2) - 25, int(HEIGHT/2), 100)
done = True
elif game.dealer_total > 21:
draw_text('Bust!', screen, 350, 50, 50)
draw_text('You Win!', screen, int(WIDTH/2) - 25, int(HEIGHT/2), 100)
done = True
elif game.player_total == game.dealer_total:
draw_text('Tie!', screen, int(WIDTH / 2) - 25, int(HEIGHT / 2), 50)
done = True
else:
if done:
if game.player_total > game.dealer_total:
draw_text('You Win!', screen, int(WIDTH / 2) - 25, int(HEIGHT / 2), 100)
else:
draw_text('You Lose!', screen, int(WIDTH / 2) - 25, int(HEIGHT / 2), 100)
if done:
button_play_again.draw(screen, (0, 0, 0))
# events
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
running = False
game_over = True
# clicking buttons
if event.type == pygame.MOUSEBUTTONDOWN:
if button_deal.isOver(pos):
game.deal()
game.calc_player_total()
has_dealt = True
if button_hit.isOver(pos):
game.player_hit()
game.calc_player_total()
if button_stand.isOver(pos):
players_turn = False
if button_play_again.isOver(pos):
running = False
# hovering buttons
if event.type == pygame.MOUSEMOTION:
if button_deal.isOver(pos):
button_deal.color = (0,175,175)
else:
button_deal.color = (0, 255, 255)
if button_hit.isOver(pos):
button_hit.color = (0,175,0)
else:
button_hit.color = (0, 255, 0)
if button_stand.isOver(pos):
button_stand.color = (175,0,0)
else:
button_stand.color = (255, 0, 0)
if button_play_again.isOver(pos):
button_play_again.color = (120, 120, 120)
else:
button_play_again.color = (200, 200, 200)
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
f616c0692ab2182bbd4b74f6e2748bd09fbbdc45
|
Rowing0914/TF2_RL
|
/tf_rl/examples/PETS/test/property_test.py
| 350 | 3.6875 | 4 |
class Human:
def __init__(self, name="Norio"):
self.name = name
@property
def nickname(self):
return "_"+self.name+"_"
@property
def sayName(self):
print("Hi {}".format(self.name))
return "Hi {}".format(self.name)
if __name__ == "__main__":
me = Human()
print(me.nickname)
me.sayName
|
5f70ce0bcce55c3b28ea31ce48ae0b60d58336c4
|
maxdubakov/snake-ai
|
/views/game.py
| 6,275 | 3.546875 | 4 |
import sys
import random
import time
import pygame as p
from config import *
class Game:
def __init__(self, surface, color1, color2, replaying):
self._surface = surface
self._color1 = color1
self._color2 = color2
self._replaying = replaying
def draw_grid(self):
for y in range(0, int(GRID_HEIGHT)):
for x in range(0, int(GRID_WIDTH)):
if (x + y) % 2 == 0:
rect = p.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
p.draw.rect(self._surface, self._color1, rect)
else:
rect1 = p.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
p.draw.rect(self._surface, self._color2, rect1)
def replaying(self):
return self._replaying
class Snake:
def __init__(self, color, game):
self._color = color
self._game = game
self._length = 1
self._positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]
self._direction = random.choice([LEFT, UP, RIGHT, DOWN])
self._score = 0
self._done = False
self._eaten = False
self.init_moving()
self.update_moving()
def update_moving(self):
self.init_moving()
if self._direction == UP:
self.moving_up = True
elif self._direction == DOWN:
self.moving_down = True
elif self._direction == RIGHT:
self.moving_right = True
elif self._direction == LEFT:
self.moving_left = True
def init_moving(self):
self.moving_left = False
self.moving_right = False
self.moving_up = False
self.moving_down = False
def turn(self, direction, food, next_position=(0, 0)):
if self._length > 1 and (direction[0] * -1, direction[1] * -1) == self._direction:
self._done = True
else:
self._direction = direction
self.update_moving()
if self._game is not None:
self._game.draw_grid()
self.move(food, next_position)
def move(self, food, next_position=(0, 0)):
self.eat(food, next_position)
x, y = self._direction
new_pos = self.new(x, y)
if self.failed(new_pos):
self._done = True
else:
self._positions.insert(0, new_pos)
if len(self._positions) > self._length:
self._positions.pop()
def eat(self, food, next_position=(0, 0)):
if self.head_pos() == food.position():
self._length += 1
self._score += 1
food.spawn(self, self._game, next_position)
self._eaten = True
else:
self._eaten = False
def draw(self, surface):
for pos in self._positions:
r = p.Rect((pos[0], pos[1]), (GRID_SIZE, GRID_SIZE))
p.draw.rect(surface, self._color, r)
def handle_keys(self, food):
executed_turn = False
for event in p.event.get():
if event.type == p.QUIT:
p.quit()
sys.exit()
elif event.type == p.KEYDOWN:
executed_turn = True
if event.key == p.K_w:
self.turn(UP, food)
elif event.key == p.K_s:
self.turn(DOWN, food)
elif event.key == p.K_d:
self.turn(RIGHT, food)
elif event.key == p.K_a:
self.turn(LEFT, food)
elif event.key == p.K_j:
time.sleep(10)
if not executed_turn:
self.turn(self._direction, food)
def reset(self):
self._length = 1
self._positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]
self._direction = random.choice([UP, DOWN, LEFT, RIGHT])
self._score = 0
self._done = False
self._eaten = False
def head_pos(self):
return self._positions[0]
def new(self, x, y):
return (((self.head_pos()[0] + (x * GRID_SIZE)) % SCREEN_WIDTH),
(self.head_pos()[1] + (y * GRID_SIZE)) % SCREEN_HEIGHT)
@staticmethod
def check_exit(event):
if event.type == p.QUIT:
p.quit()
sys.exit()
def is_turned_into_itself(self, new):
return len(self._positions) > 2 and new in self._positions[2:]
def ran_into_x_border(self):
x, _ = tuple(self.head_pos())
return (x == 0 and self.moving_left) or \
(x == SCREEN_WIDTH - GRID_SIZE and self.moving_right)
def ran_into_y_border(self):
_, y = tuple(self.head_pos())
return (y == 0 and self.moving_up) or \
(y == SCREEN_HEIGHT - GRID_SIZE and self.moving_down)
def failed(self, direction):
return \
self.is_turned_into_itself(direction) or \
self.ran_into_x_border() or \
self.ran_into_y_border()
def positions(self):
return self._positions
def eaten(self):
return self._eaten
def done(self):
return self._done
def score(self):
return self._score
def length(self):
return self._length
def game(self):
return self._game
class Food:
def __init__(self, color, snake, position=(0, 0)):
self._position = (0, 0)
self._color = color
self.spawn(snake, snake.game(), position)
def spawn(self, snake, game, position):
if game is None or not game.replaying():
food_pos = Food.random_pos()
while food_pos in snake.positions():
food_pos = Food.random_pos()
self._position = food_pos
else:
self._position = position
def draw(self, surface):
r = p.Rect((self._position[0], self._position[1]), (GRID_SIZE, GRID_SIZE))
p.draw.rect(surface, self._color, r)
p.draw.rect(surface, self._color, r, 1)
@staticmethod
def random_pos():
return (random.randint(0, int(GRID_WIDTH - 1)) * GRID_SIZE,
random.randint(0, int(GRID_HEIGHT - 1)) * GRID_SIZE)
def position(self):
return self._position
|
41a2dd5ef69107860ae66b46df40c7ab6f78f9b9
|
brady-wang/mac_home
|
/python/sort_test/bubble_sort.py
| 697 | 3.84375 | 4 |
# *_*coding:utf-8 *_*
#对于一个长度为N的数组,我们需要排序 N-1 轮,每 i 轮 要比较 N-i 次。对此我们可以用双重循环语句,外层循环控制循环轮次,内层循环控制每轮的比较次数
def bubble_sort(sort_list,sort='asc'):
if len(sort_list) <= 0:
return []
count = len(sort_list)
sorted_list = sort_list
for i in range(0,count-1):
print('第%d趟排序:' % (i + 1))
for j in range(0,count-i-1):
if sorted_list[j] > sorted_list[j + 1] :
sorted_list[j], sorted_list[j + 1] = sorted_list[j + 1], sorted_list[j]
print(sorted_list)
list = [3,4,2,6,5,9]
bubble_sort(list)
|
39e095c88e4c0c42a10af0c2cb3bc874b11b322b
|
hal00alex/Python_Auto_Practice
|
/defWithCommandLine.py
| 543 | 3.75 | 4 |
import os
import sys
def one():
print "Creating file of one type\n"
def two():
print "Creating file of two type\n"
def three():
print "Creating file of three type\n"
def main():
print "Hello Master!\n"
#get file type from user
fileType = str(sys.argv[1])
if (fileType == "-1"):
one()
elif (fileType == "-2"):
two()
elif (fileType == "-3"):
three()
elif (fileType == "-help"):
print "Please run program with -1, -2, or -3\n"
else:
print "Invalid File Type Request"
print "Goodbye Master\n"
main()
|
a1d71faafd68f3f64e54b1a1ef89ce02b533a802
|
shichao-an/ctci
|
/chapter9/question9.5.py
| 1,696 | 4 | 4 |
from __future__ import print_function
"""
Write a method to compute all permutations of a string
"""
def get_permutations1(s):
"""
Append (or prepend) every character to each permutation of the
string which does not contain the current character
"""
if not s:
return ['']
else:
res = []
for i, c in enumerate(s):
rest_s = s[:i] + s[i + 1:]
rest_perms = get_permutations1(rest_s)
for perm in rest_perms:
res.append(perm + c)
return res
def insert_at(s, c, i):
return s[:i] + c + s[i:]
def get_permutations2(s):
"""
Insert the first (or last) character to every spot of each permutation
of the remaining string after this character
"""
if not s:
return ['']
else:
res = []
c = s[0]
rest_s = s[1:]
rest_perms = get_permutations2(rest_s)
for perm in rest_perms:
for i in range(len(perm) + 1):
ns = insert_at(perm, c, i)
res.append(ns)
return res
def get_permutations3_aux(s, cand, res):
"""Backtrack"""
if not s:
res.append(cand)
else:
for i, c in enumerate(s):
get_permutations3_aux(s[:i] + s[i + 1:], cand + c, res)
def get_permutations3(s):
res = []
cand = ''
get_permutations3_aux(s, cand, res)
return res
def _test():
pass
def _print():
s1 = 'abc'
r1 = get_permutations1(s1)
r2 = get_permutations2(s1)
r3 = get_permutations3(s1)
r1.sort()
r2.sort()
r3.sort()
print(r1)
print(r2)
print(r3)
if __name__ == '__main__':
_test()
_print()
|
7e1d9a7eb73d8ab179d884089b25365ea472a136
|
CurtisFord1997/Indian-Hills
|
/Python/Lab4/BugCollector.py
| 841 | 4.28125 | 4 |
#Curtis Ford 3/11/2020
#bug catcher program, asks for 7 days of bug catching and accumulates them.
def main():
bugs = init
bugs = inpt(bugs)
outpt(bugs)
def init(bugs):
bugs = 0 #initilizes bug accumulator
print("This program asks you for 7 days of bug catching.")
def inpt(bugs):
#inalid = True
for x in range(7): #runs 7 times
#while(inalid):
try:
bugs += int(input("How many bugs have you caught today?"))#asks the user how many bugs they caught that day and adds it to the bug accumulator.
#inalid = False
except ValueError:
#print("Error: Non-numeric please try again.")
bugs = 0
#invalid = True
print("You have caught",format(bugs,","),"bugs this week.")#prints how many bugs the person has caught over the course of 7days
|
0d48679aa1749c17a8376f577a673f1afb68c877
|
euyag/python-cursoemvideo
|
/Modulo 01/exercicos/d019.py
| 293 | 3.703125 | 4 |
print('===== DESAFIO 019 =====')
import random
n1 = str(input('primeiro aluno: '))
n2 = str(input('segundo aluno: '))
n3 = str(input('terceiro aluno: '))
n4 = str(input('quarto aluno: '))
list_alu = [n1, n2, n3, n4]
sorteado = random.choice(list_alu)
print(f'o aluno sorteado foi: {sorteado}')
|
f760869bdcafb22a4dbd912fcc973285f4963f52
|
barshanayak119/pythonFiles
|
/input_stops_when_blank.py
| 91 | 3.6875 | 4 |
#Input stops with non-integer input
x=input()
while x!="":
x = int(x)
x = input()
|
bf94536804868dc3c799d6b0441163db48e97274
|
sagarnikam123/learnNPractice
|
/hackerRank/tracks/languages/python/4_sets/12_checkSubset.py
| 1,743 | 3.75 | 4 |
# Check Subset
#######################################################################################################################
#
# You are given two sets A and B.
# Your job is to find whether set A is a subset of set B.
#
# If set A is subset of set B, print True.
# If set A is not a subset of set B, print False.
#
# Input Format
#
# The first line will contain the number of test cases T.
# The first line of each test case contains the number of elements in set A.
# The second line of each test case contains the space separated elements of set A.
# The third line of each test case contains the number of elements in set B.
# The fourth line of each test case contains the space separated elements of set B.
#
# Constraints
# 0 < T < 21
# 0 < Number of elements in each set < 1001
#
# Output Format
# Output True or False for each test case on separate lines.
#
# Sample Input
# 3
# 5
# 1 2 3 5 6
# 9
# 9 8 5 6 3 2 1 4 7
# 1
# 2
# 5
# 3 6 5 4 1
# 7
# 1 2 3 5 6 8 9
# 3
# 9 8 2
#
# Sample Output
# True
# False
# False
#
# Explanation
# Test Case 01 Explanation
# Set A = {1 2 3 5 6}
# Set B = {9 8 5 6 3 2 1 4 7}
# All the elements of set A are elements of set B.
# Hence, set A is a subset of set B.
#
# Note: More than 4 lines will result in a score of zero. Blank lines won't be counted.
#
#######################################################################################################################
for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted.
a = int(input()); A = set(input().split())
b = int(input()); B = set(input().split())
print(A.intersection(B) == A)
|
b8213cc5ab57f8436bbd2352559f64d6f134d295
|
Wasserratte/waitercaller
|
/passwordhelper.py
| 608 | 3.578125 | 4 |
import hashlib
import os
import base64
class PasswordHelper:
def get_hash(self, plain): #For registration a new user.
return hashlib.sha512(plain).hexdigest() #sha512 hash for the
#final hash we will store.
def get_salt(self):
return base64.b64encode(os.urandom(20)) #os.urandom creates a cryptographically string. base64 encodes it.
def validate_password(self, plain, salt, expected):
return self.get_hash(plain + salt) == expected #For the login process. Input passward and the salt we stored will
#be hashed and compared to the stored hash(expected)
|
188e8b1b7949e776f218de1fe86138e4a969ce80
|
HelenBai2002Tong/Cesium
|
/Projects&Assignments/BinaryTree.py
| 704 | 3.546875 | 4 |
class Tree:
def __init__(self,cargo,left=None,right=None):
self.cargo=cargo
self.left=left
self.right=right
def pre(k):
if k is None:
return
print(k.cargo,end=" ")
pre(k.left)
pre(k.right)
def inp(k):
if k is None:
return None
inp(k.left)
print(k.cargo,end=" ")
inp(k.right)
def post(k):
if k is None:
return
post(k.left)
post(k.right)
print(k.cargo,end=" ")
a1=Tree("a1")
a2=Tree("a2")
b1=Tree("b1")
b2=Tree("b2")
a=Tree("a",a1,a2)
b=Tree("b",b1,b2)
tree1=Tree("c",a,b)
tree = Tree("+", Tree(1), Tree("*", Tree(2), Tree(3)))
print("pre")
pre(tree)
print("\nin")
inp(tree)
print("\npost")
post(tree)
|
6ab2b1d6b0a4e2f78b4397bfe61e94224cefd6a8
|
jokemaan/web_spider
|
/re/re01.py
| 918 | 4.375 | 4 |
# -*- coding:utf-8 -*-
#------------------------
# be familiar with the regular expression
# a simple re module example used to match 'hello' substring
# the using steps:
# 1. compile the string form of regular expression to Pattern instance
# 2. use the Pattern instance to process the text and get the matching result
# 3. use the matching result(Match instance)to get information
import re
#将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”
pattern=re.compile(r'hello')
#use patterm match text,if there is no matching substring,return None
match1=pattern.match('hello world!')
match2=pattern.match('helloo world!')
match3=pattern.match('helllo world!')
if match1:
print match1.group()
else:
print 'match1 failed'
if match2:
print match2.group()
else:
print 'match2 failed'
if match3:
print match3.group()
else:
print 'match3 failed'
|
dc7696590d89dc346fa7a407519c45361c80483c
|
ArturKow66/python-zookeper
|
/Topics/Program with numbers/The sum of digits/main.py
| 76 | 3.734375 | 4 |
number = input()
_sum = 0
for i in number:
_sum += int(i)
print(_sum)
|
6044f962c9cb1a314bbf5ceddb6c3802463cf427
|
Kcpf/DesignSoftware
|
/Lista_alunos_ímpares_.py
| 350 | 3.6875 | 4 |
"""
Escreva uma função que recebe uma lista de nomes de alunos e devolve uma lista contendo somente os alunos nos índices ímpares, dividindo a turma em dois.
O nome da sua função deve ser alunos_impares.
"""
def alunos_impares(lista):
l = []
for c in range(len(lista)):
if c % 2 != 0:
l.append(lista[c])
return l
|
5f0d32469ffa9391088cbbe715b209ee3211c466
|
jngo102/ECE_203_Project
|
/main.py
| 10,788 | 3.78125 | 4 |
from Tkinter import *
import os
import pickle
# Class definition for main map
class Game:
def __init__(self, root):
self.root = root
self.root.title("Space Exploration")
self.canvas = Canvas(self.root, width=1280, height=720)
self.canvas.pack()
# Booleans that will be toggled based on mouse cursor position
self.BaofengGame = False
self.JasonGame = False
self.KathrinaGame = False
self.MohammadGame = False
self.RyanGame = False
self.cursorPos = 500 # Position of cursor when entering player name
self.playerName = [] # List of individual characters when entering player name
self.playerNameCanvas = [] # List of letters on canvas when entering player name
self.FPS = 60 # Number of frames per second that loop() function will run
self.lastIndex = -1 # Initial value of index that changes as player enters/deletes characters in name entry
# Initialization of background, background image, and background animation frame
self.backgroundImage = PhotoImage(file="images/comet/0.gif")
self.background = self.canvas.create_image(0, 0, image=self.backgroundImage, anchor='nw')
self.backgroundFrame = 0
# Initialization of Mercury, Mercury image, and Mercury animation frame
self.MercuryImage = PhotoImage(file="images/Mercury/0.gif")
self.Mercury = self.canvas.create_image(150, 150, image=self.MercuryImage)
self.MercuryFrame = 0
# Initialization of moons, moons image, and moons animation frame
self.moonsImage = PhotoImage(file="images/moons/0.gif")
self.moons = self.canvas.create_image(700, 250, image=self.moonsImage)
self.moonsFrame = 0
# Initialization of Neptune, Neptune image, and Neptune animation frame
self.NeptuneImage = PhotoImage(file="images/Neptune/0.gif")
self.Neptune = self.canvas.create_image(300, 500, image=self.NeptuneImage)
self.NeptuneFrame = 0
# Initialization of rocky, rocky image, and rocky animation frame
self.rockyImage = PhotoImage(file="images/rocky/0.gif")
self.rocky = self.canvas.create_image(1000, 550, image=self.rockyImage)
self.rockyFrame = 0
# Initialization of wormhole, wormhole image, and wormhole animation frame
self.wormholeImage = PhotoImage(file="images/wormhole/0.gif")
self.wormhole = self.canvas.create_image(1100, 200, image=self.wormholeImage)
self.wormholeFrame = 0
# Sets leaderboard text at bottom center of map; includes Boolean that toggles when mouse hovers over text
self.leaderboardText = self.canvas.create_text(640, 700, text="Leaderboard", fill='white', font=('Roboto', 20))
self.leaderboardOn = False
# Warning text used to tell players if their name is too long or not long enough
self.warningText = self.canvas.create_text(640, 500, text="", fill='white', font=('Roboto', 18))
self.canvas.itemconfig(self.warningText, state=HIDDEN)
# Text that tells player to enter name
self.namePrompt = self.canvas.create_text(300, 360, text="Enter your name:", fill='white', font=('Roboto', 24))
# Key bindings for entering/deleting characters when typing name and submitting it
self.root.bind('<Key>', self.enter_name)
self.root.bind('<BackSpace>', self.backspace)
self.root.bind('<Return>', self.start)
# Function bound to <BackSpace> event
def backspace(self, event):
if len(self.playerNameCanvas) > 0:
self.canvas.delete(self.playerNameCanvas[self.lastIndex])
del self.playerNameCanvas[self.lastIndex]
del self.playerName[self.lastIndex]
self.lastIndex -= 1
self.cursorPos -= 25
# Function bound to <Button-1> event
def click(self, event):
if os.name == 'nt':
prefix = ''
elif os.name == 'posix':
prefix = 'python '
if self.BaofengGame:
os.system('%sShipShipRevolution.py' % prefix)
elif self.JasonGame:
os.system('%sSpaceShooter.py' % prefix)
elif self.KathrinaGame:
os.system('%sAsteroidClicker.py' % prefix)
elif self.MohammadGame:
os.system('%sResourceQuest.py' % prefix)
elif self.RyanGame:
os.system('%sMultipleChoiceQuestions.py' % prefix)
elif self.leaderboardOn:
self.display_leaderboard()
# Leaderboard window opens when "Leaderboard" text on map is clicked on
def display_leaderboard(self):
self.leaderboard = Tk()
self.leaderboard.title("Leaderboard")
playerData = pickle.load(open("data/leaderboard.txt", 'rb'))
playerData.sort(key=lambda list: list[1], reverse=True)
Label(self.leaderboard, text="Leaderboard").grid(row=0, columnspan=2)
Label(self.leaderboard, text="Player").grid(row=1, column=0)
Label(self.leaderboard, text="Score").grid(row=1, column=1)
Label(self.leaderboard, text="-=-=-=-=-=-=-=-=-=-=-=-=-").grid(row=2, columnspan=2)
for player in playerData:
i = playerData.index(player)
playerName = player[0]
playerScore = player[1]
nameLabel = Label(self.leaderboard, text=playerName)
nameLabel.grid(row=i+3, column=0)
scoreLabel = Label(self.leaderboard, text=playerScore)
scoreLabel.grid(row=i+3, column=1)
if playerName == self.playerName:
nameLabel.config(font=('bold'))
scoreLabel.config(font=('bold'))
# Function bound to <Key> event
def enter_name(self, event):
if self.cursorPos >= 750:
self.canvas.itemconfig(self.warningText, text="You've reached the character limit.", state=NORMAL)
else:
if event.char.isalnum():
self.letter = self.canvas.create_text(self.cursorPos, 360, text=event.char, fill='white', font=('Roboto', 24))
self.playerNameCanvas.append(self.letter)
self.playerName.append(event.char)
self.cursorPos += 25
self.lastIndex += 1
# Function that loops to animate canvas objects
def loop(self):
self.backgroundFrame += 1
if self.backgroundFrame == len(os.listdir("images/comet")):
self.backgroundFrame = 0
self.backgroundImage = PhotoImage(file="images/comet/%d.gif" % self.backgroundFrame)
self.canvas.itemconfig(self.background, image=self.backgroundImage)
self.MercuryFrame += 1
if self.MercuryFrame == len(os.listdir("images/Mercury")):
self.MercuryFrame = 0
self.MercuryImage = PhotoImage(file="images/Mercury/%d.gif" % self.MercuryFrame)
self.canvas.itemconfig(self.Mercury, image=self.MercuryImage)
self.moonsFrame += 1
if self.moonsFrame == len(os.listdir("images/moons")):
self.moonsFrame = 0
self.moonsImage = PhotoImage(file="images/moons/%d.gif" % self.moonsFrame)
self.canvas.itemconfig(self.moons, image=self.moonsImage)
self.NeptuneFrame += 1
if self.NeptuneFrame == len(os.listdir("images/Neptune")):
self.NeptuneFrame = 0
self.NeptuneImage = PhotoImage(file="images/Neptune/%d.gif" % self.NeptuneFrame)
self.canvas.itemconfig(self.Neptune, image=self.NeptuneImage)
self.rockyFrame += 1
if self.rockyFrame == len(os.listdir("images/rocky")):
self.rockyFrame = 0
self.rockyImage = PhotoImage(file="images/rocky/%d.gif" % self.rockyFrame)
self.canvas.itemconfig(self.rocky, image=self.rockyImage)
self.wormholeFrame += 1
if self.wormholeFrame == len(os.listdir("images/wormhole")):
self.wormholeFrame = 0
self.wormholeImage = PhotoImage(file="images/wormhole/%d.gif" % self.wormholeFrame)
self.canvas.itemconfig(self.wormhole, image=self.wormholeImage)
self.root.after(1000/self.FPS, self.loop)
# Function bound to <Motion> event
def navigate(self, event):
if 40 <= event.x <= 260 and 35 <= event.y <= 265:
self.BaofengGame = True
elif 1020 <= event.x <= 1180 and 115 <= event.y <= 280:
self.JasonGame = True
elif 550 <= event.x <= 865 and 100 <= event.y <= 415:
self.KathrinaGame = True
elif 200 <= event.x <= 500 and 300 <= event.y <= 600:
self.MohammadGame = True
elif 920 <= event.x <= 1090 and 465 <= event.y <= 635:
self.RyanGame = True
elif 560 <= event.x <= 720 and 690 <= event.y <= 710:
self.canvas.itemconfig(self.leaderboardText, fill='red', font=('Roboto', 24))
self.leaderboardOn = True
else:
self.BaofengGame, self.JasonGame, self.KathrinaGame, self.MohammadGame,\
self.RyanGame, self.leaderboardOn = False, False, False, False, False, False
self.canvas.itemconfig(self.leaderboardText, fill='white', font=('Roboto', 20))
# Configuration of various canvas objects and player variables
def start(self, event):
if len(self.playerName) == 0:
self.canvas.itemconfig(self.warningText, text="You must have at least one character for your name.", state=NORMAL)
else:
try:
playerData = pickle.load(open("data/leaderboard.txt", 'rb'))
except:
playerData = []
uniqueNames = 0
playerName = ''.join(self.playerName)
for player in playerData:
player[2] = 0
if playerName == player[0]:
pass
else:
uniqueNames += 1
if uniqueNames == len(playerData):
self.canvas.itemconfig(self.namePrompt, state=HIDDEN)
self.canvas.itemconfig(self.warningText, state=HIDDEN)
for letter in self.playerNameCanvas:
self.canvas.itemconfig(letter, state=HIDDEN)
self.root.unbind('<Key>')
self.root.unbind('<Return>')
self.root.bind('<Motion>', self.navigate)
self.root.bind('<Button-1>', self.click)
self.playerName = ''.join(self.playerName)
playerData.append([self.playerName, 0, 1])
pickle.dump(playerData, open("data/leaderboard.txt", 'wb'))
self.loop()
else:
self.canvas.itemconfig(self.warningText, text="Someone has already chosen that name.", state=NORMAL)
root = Tk()
Project = Game(root)
root.mainloop()
|
b813e9973526cd43c67f99d760949d074970bae5
|
rodrigoacaldas/PeO-IFCE-2020
|
/acertePreco/acertePrecoHumanoVSMaquina.py
| 2,076 | 4 | 4 |
from random import randint
print("*********************************")
print("Bem vindo ao jogo de Adivinhação!")
print("*********************************")
numero_menor = numero_menor_maquina = 0
numero_maior = numero_maior_maquina = 100
numero_secreto = randint(numero_menor, numero_maior)
total_de_tentativas_humana = 0
total_de_tentativas_maquina = 0
acertou_humano = False
acertou_maquina = False
while not acertou_humano:
print("Tentativa Humana {} ".format(total_de_tentativas_humana))
chute_str = input("Digite um número entre {} de {} ".format(numero_menor, numero_maior))
print("Você digitou ", chute_str)
chute = int(chute_str)
if (chute < numero_menor or chute > numero_maior):
print("Você deve digitar um número entre {} e {}!".format(numero_menor, numero_maior))
continue
acertou = chute == numero_secreto
maior = chute > numero_secreto
menor = chute < numero_secreto
if (acertou):
print("Você acertou!")
break
else:
if (maior):
print("Você errou! O seu chute foi maior do que o número secreto.")
numero_maior = chute
elif (menor):
print("Você errou! O seu chute foi menor do que o número secreto.")
numero_menor = chute
total_de_tentativas_humana += 1
print("Fim do jogo Humano!")
def pesquisa_binaria(esquerda , direita):
chute = (esquerda + direita) // 2
return chute
while not acertou_maquina:
chute = pesquisa_binaria(numero_menor_maquina, numero_maior_maquina)
acertou = chute == numero_secreto
maior = chute > numero_secreto
menor = chute < numero_secreto
if (acertou):
break
else:
if (maior):
numero_maior_maquina = chute
elif (menor):
numero_menor_maquina = chute
total_de_tentativas_maquina += 1
print("Você descobriu o numero secreto em {} tentativas".format(total_de_tentativas_humana))
print("O computador descobriu o numero secreto em {} tentativas".format(total_de_tentativas_maquina))
|
dc2b41c5e65762f14e13105818901f36bd49fbad
|
MartrixG/2020-spring-database
|
/project1/test.py
| 744 | 3.53125 | 4 |
import pymysql
# 数据库参数
config = {
'host':'localhost',
'port':3306,
'user':'root',
'password':'root',
'database':'lab1',
'charset':'utf8',
'cursorclass':pymysql.cursors.Cursor,
}
# 连接数据库
db = pymysql.connect(**config)
try:
with db.cursor() as cursor:
sql = 'select * from professor;'
count = cursor.execute(sql) # 影响的行数
print(count)
result = cursor.fetchall() # 取出所有行
for i in result: # 打印结果
print(i)
db.commit() # 提交事务
except:
db.rollback() # 若出错了,则回滚
finally:
print("good bye")
|
8b7e44d8f57327d8492972c26985292487501aba
|
Vekteur/plogic
|
/src/layered_dict.py
| 2,236 | 3.515625 | 4 |
from abc import ABC, abstractmethod
class LayeredDict:
class Action(ABC):
@abstractmethod
def exec(self, d): pass
class SetAction(Action):
def __init__(self, key, value): self.key, self.value = key, value
def exec(self, d): d[self.key] = self.value
class PopAction(Action):
def __init__(self, key): self.key = key
def exec(self, d): d.pop(self.key)
def __init__(self, d = {}):
self.d = d
self._layers = []
self.pre_init()
self.add_layer()
def pre_init(self):
pass
def add_layer(self):
self._layers.append([])
def pop_layer(self):
for action in reversed(self._layers[-1]):
action.exec(self.d)
self._layers.pop()
def append_set_action(self, key):
self._layers[-1].append(LayeredDict.SetAction(key, self.d[key]))
def append_pop_action(self, key):
self._layers[-1].append(LayeredDict.PopAction(key))
def __getitem__(self, key):
return self.d[key]
def __setitem__(self, key, value):
if key in self.d:
self.append_set_action(key)
else:
self.append_pop_action(key)
self.d[key] = value
def pop(self, key):
self.append_set_action(key)
return self.d.pop(key)
def popitem(self):
for key in self.d: break
return key, self.pop(key)
def items(self):
return self.d.items()
def __len__(self):
return len(self.d)
class LayeredListOfDict:
def __init__(self, l):
self.l = l
self.l = list(map(LayeredDict, self.l))
self.updated_indices = []
self.add_layer()
def add_layer(self):
self.updated_indices.append(set())
def pop_layer(self):
for index in self.updated_indices[-1]:
self.l[index].pop_layer()
self.updated_indices.pop()
def __getitem__(self, index):
if index not in self.updated_indices[-1]:
self.l[index].add_layer()
self.updated_indices[-1].add(index)
return self.l[index]
if __name__ == '__main__':
d = {'a' : 1, 'b' : 2}
ld = LayeredDict(d.copy())
assert ld.d == d
ld.add_layer()
ld['c'] = 3
ld['b'] = -2
ld.pop('a')
assert ld.d == {'b' : -2, 'c' : 3}
ld.pop_layer()
assert ld.d == d
lld = LayeredListOfDict([d.copy(), {'b' : 2, 'c' : 3}])
lld.add_layer()
lld[1]['a'] = 1
assert lld.l[0].d == d and lld.l[1].d == {'a' : 1, 'b' : 2, 'c' : 3}
lld.pop_layer()
assert lld.l[0].d == d and lld.l[1].d == {'b' : 2, 'c' : 3}
|
a3e8ff41cbf63e4cbe4a1d16ae909191c2a391fe
|
cpe202spring2019/lab1-nschandr
|
/lab1_test_cases.py
| 1,565 | 3.609375 | 4 |
import unittest
from lab1 import *
# A few test cases. Add more!!!
class TestLab1(unittest.TestCase):
def test_max_list_iter(self):
"""add description here"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
max_list_iter(tlist)
t2 = []
self.assertEqual(max_list_iter(t2), None)
t3 = [1, 2, 3]
self.assertEqual(max_list_iter(t3), 3)
t4 = [0, -2]
self.assertEqual(max_list_iter(t4), 0)
self.assertEqual(max_list_iter([1]),1)
def test_reverse_rec(self):
self.assertEqual(reverse_rec([1, 2, 3]), [3, 2, 1])
t1 = None
with self.assertRaises(ValueError):
reverse_rec(t1)
self.assertEqual(reverse_rec([3]), [3])
self.assertEqual(reverse_rec([]), None)
def test_bin_search(self):
list_val =[0,1,2,3,4,7,8,9,10]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(4, 0, len(list_val)-1, list_val), 4 )
l1 = None
with self.assertRaises(ValueError):
bin_search(1,0,3,l1)
self.assertEqual(bin_search(0,0,3,[3,4,5,5]),None)
self.assertEqual(bin_search(1,0,4,[0,1,2,3,4]),1)
self.assertEqual(bin_search(4,0,5,[0,1,2,3,4,5]),4)
self.assertEqual(bin_search(0,0,3,[0,1,2,3]),0)
self.assertEqual(bin_search(1,0,0,[1]),0)
self.assertEqual(bin_search(1,0,0,[0]),None)
self.assertEqual(bin_search(1,2,3,[]),None)
if __name__ == "__main__":
unittest.main()
|
fee1e5b41576e58b7eecdca4764d834397257fdc
|
poohcid/class
|
/PSIT/25.py
| 605 | 4 | 4 |
"""Grade II"""
def main():
"""score statement return your level"""
score = float(input())
if score <= 100 and score >= 0:
if score >= 95:
print("A")
elif score >= 90:
print("B+")
elif score >= 85:
print("B")
elif score >= 80:
print("C+")
elif score >= 75:
print("C")
elif score >= 70:
print("D+")
elif score >= 65:
print("D")
elif score >= 60:
print("F+")
else:
print("F")
else:
print("ERR")
main()
|
75bfdb08450ba7c683fcb945663ddac89a14851f
|
mehrannoori/numerical-analysis
|
/root/fixed_point.py
| 345 | 3.84375 | 4 |
import math
# f(x)=3x^2-e^x=0
def f(x):
return 3*x*x - math.exp(x)
# f(x)=x-g(x)
# g(x)=sqrt(e^x/3) for [0,1]
def g(x):
return math.sqrt(math.exp(x)/3)
def res():
x0 = 1
x = 0
while True:
x = g(x0)
if abs( x0-x <= 0.001 ):
return g(x)
x0 = x
if __name__ == "__main__":
print(res())
|
ab21eae45278f99eb7177b1266e33f53662246d2
|
arifkhan1990/Competitive-Programming
|
/Data Structure/Queue/implementation/python/queue_implement_by_array.py
| 1,148 | 4 | 4 |
class Queue:
def __init__(self, max_size = 0):
self.size = max_size
self.arr = []
def enqueue(self, data):
if not self.isFull():
self.arr.append(data)
def dequeue(self):
if not self.isEmpty():
self.arr.pop(0)
def isEmpty(self):
return len(self.arr) == 0
def isFull(self):
return len(self.arr) == self.size
def front(self):
if not self.isEmpty():
return self.arr[0]
def rear(self):
if not self.isEmpty():
return self.arr[-1]
def Qusize(self):
return len(self.arr)
q = Queue(5)
n = int(input())
for i in range(n):
k = int(input())
q.enqueue(k)
print("Size of Queue = ", q.Qusize())
print("Queue is Full = ", q.isFull())
print("Queue is empty = ", q.isEmpty())
print("First element of queue = ", q.front())
print("Last element of queue = ", q.rear())
q.dequeue();
print("New First element of queue = ", q.front())
print("Queue element are :",end=' ')
while not q.isEmpty():
print(q.front(),end=' ')
q.dequeue()
print()
print("Queue is empty = ", q.isEmpty())
|
bb650482a6cddb56e8d13b43859cb23791554aa2
|
aggy07/Leetcode
|
/900-1000q/989.py
| 1,339 | 3.984375 | 4 |
'''
For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.
Example 1:
Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
'''
class Solution(object):
def addToArrayForm(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
arr_k = []
while K >0:
digit = K%10
K /= 10
arr_k.append(digit)
arr_k.reverse()
if len(arr_k) > len(A):
A, arr_k = arr_k, A
sum_arr = [0]*len(A)
i, j = len(A)-1, len(arr_k)-1
k = len(A) -1
digit_sum, carry = 0, 0
while j >= 0:
curr_sum = A[i] + arr_k[j] + carry
sum_arr[k] = (curr_sum%10)
carry = curr_sum//10
i -= 1
k -= 1
j -= 1
while i >= 0:
curr_sum = A[i] + carry
sum_arr[k] = (curr_sum%10)
carry =curr_sum//10
i -= 1
k -= 1
if carry:
sum_arr = [carry] + sum_arr
return sum_arr
|
7933f3e570ae0b69f569feadfb850ec1019f28bc
|
manoanjith/python
|
/27.py
| 102 | 3.5 | 4 |
g=input()
h=g.lstrip('-').replace('.','',1).isdigit()
if(h==True):
print("Yes")
else:
print("No")
|
35e3a9d4fbe278b393887943461494a10172d3e1
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2160/60866/253754.py
| 398 | 3.640625 | 4 |
def chufa(divended,divisor):
i=divended
j=0
if(divended*divisor<0):
if(divended<0):
i=-i
if(divisor<0):
divisor=-divisor
while(i>=divisor):
i=i-divisor
j=j+1
print(0-j)
return
while(i>=divisor):
i=i-divisor
j=j+1
print(j)
s=int(input())
t=int(input())
chufa(s,t)
|
203a2b957c8c8b780160ec701a07c2edfdb4d134
|
erauner12/python-for-professionals
|
/Chapter 1 Python Language Basics/1_5_Collection_Types.py
| 6,300 | 4.25 | 4 |
# Lists
# The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an
# array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid Python values. A
# list can be created by enclosing values, separated by commas, in square brackets
from collections import defaultdict
int_list = [1, 2, 3]
string_list = ['abc', 'defghi']
# A list can be empty:
empty_list = []
# The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language
mixed_list = [1, 'abc', True, 2.34, None]
# A list can contain another list as its element:
nested_list = [['a', 'b', 'c'], [1, 2, 3]]
# The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are
# zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:
names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']
print(names[0]) # Alice
print(names[2]) # Craig
# Indices can also be negative which means counting from the end of the list(-1 being the index of the last element).
# So, using the list from the above example:
print(names[-1]) # Eric
print(names[-4]) # Bob
# Lists are mutable, so you can change the values in a list:
names[0] = 'Ann'
print(names)
# Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric']
# Besides, it is possible to add and / or remove elements from a list:
# Append object to end of list with L.append(object), returns None.
names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']
names.append("Sia")
print(names)
# Outputs ['Alice', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']
# Add a new element to list at a specific index. L.insert(index, object)
names.insert(1, "Nikki")
print(names)
# Outputs ['Alice', 'Nikki', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']
# Remove the first occurrence of a value with L.remove(value), returns None
names.remove("Bob")
print(names) # Outputs ['Alice', 'Nikki', 'Craig', 'Diana', 'Eric', 'Sia']
# Get the index in the list of the first item whose value is x. It will show an error if there is no such item.
print(names.index("Alice")) # Out: 0
# Count length of list
print(len(names)) # Out: 6
# count occurrence of any item in list
a = [1, 1, 1, 2, 3, 4]
print(a.count(1)) # Out: 3
# Reverse the list
a.reverse()
[4, 3, 2, 1, 1, 1]
# or
a[::-1]
[4, 3, 2, 1, 1, 1]
# Remove and return item at index(defaults to the last item) with L.pop([index]), returns the item
print(names.pop()) # Outputs 'Sia'
# You can iterate over the list elements like below:
for element in names:
print(element)
# Tuples
# A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple cannot be changed
# nor the values be added to or removed from the tuple. Tuples are commonly used for small collections of values
# that will not need to change, such as an IP address and port. Tuples are represented with parentheses instead of
# square brackets:
ip_address = ('10.20.30.40', 8080)
# The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid
# Python valid.
# A tuple with only one member must be defined(note the comma) this way:
one_member_tuple = ('Only member',)
# or
one_member_tuple = 'Only member', # No brackets
# or just using tuple syntax
one_member_tuple = tuple(['Only member'])
# Dictionaries
# A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is
# separated by a comma and the key and value are separated by a colon. Here is an example:
state_capitals = {
'Arkansas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
}
print(state_capitals)
# To get a value, refer to it by its key:
ca_capital = state_capitals['California']
# You can also get all of the keys in a dictionary and then iterate over them:
for k in state_capitals.keys():
print('{} is the capital of {}'.format(state_capitals[k], k))
# Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to
# convert between JSON and dictionaries.
# set
# A set is a collection of elements with no repeats and without insertion order but sorted order. They are used in
# situations where it is only important that some things are grouped together, and not what order they were
# included. For large groups of data, it is much faster to check whether or not an element is in a set than it is to do
# the same for a list.
# Defining a set is very similar to defining a dictionary:
first_names = {'Adam', 'Beth', 'Charlie'}
# Or you can build a set using an existing list:
my_list = [1, 2, 3]
my_set = set(my_list)
name = "Adam"
# Check membership of the set using in:
if name in first_names:
print(name)
# You can iterate over a set exactly like a list, but remember: the values will be in an arbitrary, implementationdefined order.
# defaultdict
# A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been explicitly
# defined can be accessed without errors. defaultdict is especially useful when the values in the dictionary are
# collections(lists, dicts, etc) in the sense that it does not need to be initialized every time when a new key is used.
# A defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.
# For example, consider the following dictionary
state_capitals = {
'Arkansas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
}
# If we try to access a non-existent key, python returns us an error as follows
# state_capitals['Alabama']
state_capitals = defaultdict(lambda: 'Boston')
state_capitals['Arkansas'] = 'Little Rock'
state_capitals['California'] = 'Sacramento'
state_capitals['Colorado'] = 'Denver'
state_capitals['Georgia'] = 'Atlanta'
# If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston
print(state_capitals['Alabama'])
# and returns the created values for existing key just like a normal dictionary
print(state_capitals['Arkansas']) # 'Little Rock'
|
2d23450569225af07cbf061787aa06958cbca665
|
DylanBricar/CRBWork
|
/6eme/ex11.py
| 191 | 3.859375 | 4 |
a = 5
nb = int(input('Ecrire un nombre équivaut à 5 ou 26 :'))
print(nb)
if a == nb:
a = a + 5
print('a vaut = ' + str(a))
else:
print('Le nombre vaut ' + str(nb))
|
81cd73481e4fdc4e2fb66bbb230c3d396f3f5d25
|
jaishankarg24/Python-Pickling-and-Unpickling
|
/ex1.py
| 396 | 3.796875 | 4 |
#NON Persistent object/temporary object
class Student:
def __init__(self,name,age,marks): #constructor
self.name=name
self.age=age
self.marks=marks
def display(self): #instance method
print(f'name:{self.name}')
print(f'age:{self.age}')
print(f'marks:{self.marks}')
if __name__ == '__main__':
ref=Student(name='sachin',age=40,marks=70)
ref.display()
|
f2a0607ef0c581c2275bafd88cdc86c142341455
|
dongbo910220/leetcode_
|
/Dynamic Programming/1223. Dice Roll Simulation Medium.py
| 1,133 | 3.625 | 4 |
'''
https://leetcode.com/problems/dice-roll-simulation/
'''
class Solution(object):
def dieSimulator(self, n, rollMax):
"""
:type n: int
:type rollMax: List[int]
:rtype: int
"""
kMod = 1000000007
kMaxRolls = 15
dp = [[[0] * (kMaxRolls + 1) for _ in range(6)] for _ in range(n + 1)]
# print(dp)
for i in range(6):
dp[1][i][1] = 1
for i in range(2, n + 1):
for j in range(6):
for last_j in range(6):
for k in range(1, rollMax[last_j] + 1):
if last_j != j:
dp[i][j][1] = (dp[i][j][1] + dp[i - 1][last_j][k]) % kMod
elif k < rollMax[last_j]: # last_j == j
dp[i][j][k + 1] = dp[i - 1][last_j][k]
# sum(map(sum,a))
return sum(map(sum, dp[n])) % kMod
'''
Success
Details
Runtime: 1404 ms, faster than 34.48% of Python online submissions for Dice Roll Simulation.
Memory Usage: 20.4 MB, less than 80.46% of Python online submissions for Dice Roll Simulation.'''
|
250263a647a0924c9cb3ee09a3485b53c2af75bd
|
smurphy2230/csc-121-lesson14
|
/iteratorsAndGenerators.py
| 1,007 | 4.40625 | 4 |
# write a program to find the largest value of a sequence of random # numbers. A function n_random is defined and used to generate the # sequence, and the built-in function max is used to find the largest one
import random
def n_random(n):
random_list = []
for i in range(n):
num = random.randint(1, 1000000000)
random_list.append(num)
return random_list
n = int(input("How many random integers do you want? "))
max_n_random = max(n_random(n))
print(n, "random integers are generated")
print("The largest one is : ", max_n_random)
# the above code creates a list of 50,000 items. Using a generator
# eliminates the list, increasing performance and using fewer resources
def m_random(m):
for i in range(m):
num = random.randint(1, 1000000000)
yield num
m = int(input("How many random integers do you want this time? "))
max_m_random = max(m_random(m))
print(m, "random integers are generated")
print("The largest one is: ", max_m_random)
|
44ace9779c20f6ce312c39871aea591590a17856
|
jonbos/RomanNumerals
|
/src/number_util.py
| 636 | 3.921875 | 4 |
import math
#
#
def split_number_into_powers_of_ten(number):
"""
Splits an integer into an array of integers represnting each power of ten part
1234 -> [1000, 200, 30, 4]
"""
number_digits = [int(digit) for digit in str(number)]
digits_and_powers_of_ten = zip(number_digits, range(len(number_digits) - 1, -1, -1))
orders_of_ten = []
for digit_tuple in digits_and_powers_of_ten:
digit = digit_tuple[0] * (10 ** digit_tuple[1])
if digit > 0:
orders_of_ten.append(digit)
return orders_of_ten
def calculate_power_of_ten(number):
return math.floor(math.log10(number))
|
5d2f373a4282942306c6d7d87079af56a462d36f
|
wancy86/learn_python
|
/old/set_test.py
| 1,640 | 3.90625 | 4 |
# 1.找到重复的元素
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
if some_list.count(value) > 1:
if value not in duplicates:
duplicates.append(value)
print(duplicates)
# 输出: ['b', 'n']
# 2.找到重复的元素
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
# 输出: set(['b', 'n'])
# 过滤掉重复的元素
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set(iter(some_list))
print(duplicates)
# 输出: {'c', 'n', 'a', 'm', 'd', 'b'}
print([x for x in some_list if some_list.count(x) > 1])
# 差集
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
# 输出: set(['red'])
# 差集
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.difference(valid))
# 输出: set(['brown'])
# 你也可以用符号来创建集合,如:
a_set = {'red', 'blue', 'green'}
print(type(a_set))
# 输出: <type 'set'>
# 下面的会变成字典
a_set = {'red': '123'}
print(type(a_set))
# 输出: <class 'dict'>
# 三元运算符
is_fat = False
state = "fat" if is_fat else "not fat"
print(state)
state = 1 if is_fat else 0
print(state)
# 利用元素和数组实现
# 有风险慎用
state = (0, 1)[True]
print(state)
state = ['0-index','1-index'][True]
print(state)
# 这之所以能正常工作,是因为在Python中,True等于1,而False等于0,这就相当于在元组中使用0和1来选取数据。
|
93d73e2b29350c427fcc849dc5c98ce3a6e6a981
|
ChinnyEmeka/ScrabbleCode
|
/FindCombosNew.py
| 1,526 | 4.125 | 4 |
import itertools as it
def get_rack_powerset(s):
"""Return a list of characters that can be added to the board"""
for i in range(len(s)+1):
for combo in it.combinations(s,i):
yield "".join(combo)
def remove_duplicates(lst):
lst.sort()
i = len(lst) - 1
while i > 0:
if lst[i] == lst[i - 1]:
lst.pop(i)
i -= 1
return lst
def get_words(word_on_board, rack):
"""
Make all possible combinations of characters given a word on the board.
E.g. given word on board = odd, and rack = dly, can have oddly, dodd etc.
Can only make new words by adding to beginning or end of existing word.
"""
rack_powerset = get_rack_powerset(rack)
possible_words = []
for string_seq in rack_powerset:
append_front = string_seq + word_on_board
append_back = word_on_board + string_seq
possible_words.append(append_front)
possible_words.append(append_back)
return possible_words
def word_permutations(string):
if len(string) == 1:
return string
recursive_perms = []
for c in string:
for perm in permutations(string.replace(c,'',1)):
recursive_perms.append(c+perm)
return remove_duplicates(recursive_perms)
#print(list(get_rack_combos("dly")))
#print(word_permutations(""))
#print(remove_duplicates(["Chinny", "Chinny", "Alex", "Paul"]))
print(get_words("odd", "dly"))
|
3fafc5e0ad811b96e2458c5e2f96bb56bb76b836
|
vahidheydary706/tamrin4
|
/دوز.py
| 3,185 | 3.859375 | 4 |
import time
def show():
for i in range(3):
for j in range(3):
print(game[i][j], end=' ')
print()
def win1():
if game [0] [0] =='x' and game [0] [1] =='x' and game [0] [2] =='x':
print('player1 wins')
exit()
elif game [1] [0] =='x' and game [1] [1] =='x' and game [1] [2] =='x':
print('player1 wins')
exit()
elif game [2] [0] =='x' and game [2] [1] =='x' and game [2] [2] =='x':
print('player1 wins')
exit()
elif game [0] [0] =='x' and game [1] [0] =='x' and game [2] [0] =='x':
print('player1 wins')
exit()
elif game [0] [1] =='x' and game [1] [1] =='x' and game [2] [1] =='x':
print('player1 wins')
exit()
elif game [0] [2] =='x' and game [1] [2] =='x' and game [2] [2] =='x':
print('player1 wins')
exit()
elif game [0] [0] =='x' and game [1] [1] =='x' and game [2] [2] =='x':
print('player1 wins')
exit()
elif game [0] [2] =='x' and game [1] [1] =='x' and game [2] [0] =='x':
print('player1 wins')
exit()
print(f'time: {a}')
def win2():
if game [0] [0] =='o' and game [0] [1] =='o' and game [0] [2] =='o':
print('player2 wins')
exit()
elif game [1] [0] =='o' and game [1] [1] =='o' and game [1] [2] =='o':
print('player2 wins')
exit()
elif game [2] [0] =='o' and game [2] [1] =='o' and game [2] [2] =='o':
print('player2 wins')
exit()
elif game [0] [0] =='o' and game [1] [0] =='o' and game [2] [0] =='o':
print('player2 wins')
exit()
elif game [0] [1] =='o' and game [1] [1] =='o' and game [2] [1] =='o':
print('player2 wins')
exit()
elif game [0] [2] =='o' and game [1] [2] =='o' and game [2] [2] =='o':
print('player2 wins')
exit()
elif game [0] [0] =='o' and game [1] [1] =='o' and game [2] [2] =='o':
print('player2 wins')
exit()
elif game [0] [2] =='o' and game [1] [1] =='o' and game [2] [0] =='o':
print('player2 wins')
exit()
print(f'time: {a}')
game = [['_', '_', '_'],
['_', '_', '_'],
['_', '_', '_']]
show()
while True:
a = time.time()
# player1
print('player1')
while True:
row = int(input())
col = int(input())
if 0 <= row <= 2 and 0 <= col <= 2:
if game[row] [col] == '_':
game[row] [col] = 'x'
break
else:
print('Error!!! try again')
else:
print('Error!!! try again')
show()
win1()
# player2
print('player2')
while True:
row = int(input())
col = int(input())
if 0 <= row <= 2 and 0 <= col <= 2:
if game[row] [col] == '_':
game[row] [col] = 'o'
break
else:
print('Error!!! try again')
else:
print('Error!!! try again')
show()
win2()
|
7111730be6aa767e27ada04e3eafc8ae474e568f
|
oatovar/Artificial-Intelligence
|
/Problem Set 1/data_structures.py
| 1,043 | 3.890625 | 4 |
class Queue:
def __init__(self):
self.queue = list()
self.counter = 0
def __len__(self):
return len(self.queue)
def __str__(self):
str = ""
for state in self.queue:
str += state.name
return str
def getList(self):
return self.queue
def empty(self):
return len(self.queue) == 0
def pop(self):
if not self.empty():
return self.queue.pop(0)
else:
return "Queue is empty."
def insert(self, item):
if self.queue.append(item):
return True
else:
return False
class Stack:
def __init__(self):
self.stack = list()
def empty(self):
return len(self.stack) == 0
def pop(self):
if not self.empty():
return self.stack.pop()
else:
return "Stack is empty."
def insert(self, item):
if (self.stack.append(item)):
return True
else:
return False
|
0e112e3737857051466fe0a043877b691f9b243c
|
Bharti20/python_more_exercise
|
/strong_password.py
| 422 | 4.15625 | 4 |
password=input("enter the password")
if len(password)>=6 and len(password)<=16:
if "$" in password:
if "A" in password or "Z" in password:
if "2" in password or "8" in password:
print("strong password")
else:
print("weak password")
else:
print("weak password")
else:
print("weak password")
else:
print("weak password")
|
c32977b405362a9d234e5116231a32395353623c
|
charlyhackr/holbertonschool-higher_level_programming
|
/0x06-python-classes/103-magic_class.py
| 698 | 4.28125 | 4 |
#!/usr/bin/python3
import dis
import math
class MagiClass:
"""Represent a circle"""
def __init__(self, radius=0):
"""INitialize a magiClass. """
self.__radius = 0
if type(radius) is not int and type(radius) is not float:
raise TypeError("radius must be a number")
self.__radius = radius
@property
def radius(self):
"""Return the radius of the magicclass"""
return self.__radius
def area(self):
"""Return the area of magicclass"""
return self.__radius ** 2 * math.pi
def circumference(self):
"""Return the circumference of the magicclass"""
return 2 * math.pi * self.__radius
|
6bcce96aeb1e3abc71ca735d5a073378053b9a6d
|
raymondmar61/pythonoutsidethebook
|
/learnpythonthehardway.py
| 37,113 | 4.53125 | 5 |
#Learn Python The Hard Way, 3rd Edition .pdf
#http://learnpythonthehardway.org/book/
#Do Not Copy-Paste
#You must type each of these exercises in, manually. If you copy and paste, you might as well just not even do them. The point of these exercises is to train your hands, your brain, and your mind in how to read, write, and see code. If you copy-paste, you are cheating yourself out of the effectiveness of the lessons.
print("Exercise 1: A Good First Program") #print Exercise 1: A Good First Program
print("Hello World!") #print Hello World!
print("Exercise 2: Comments And Pound Characters") #print Exercise 2: Comments And Pound Characters
print("Why do I have to read code backwards? It's a trick to make your brain not attach meaning to each part of the code, and doing that makes you process each piece exactly. This catches errors and is a handy error checking technique.") #print Why do I have to read code backwards? It's a trick to make your brain not attach meaning to each part of the code, and doing that makes you process each piece exactly. This catches errors and is a handy error checking technique.
print("Exercise 3: Numbers And Math Using Comma Separate string and numbers",100+200) #print Exercise 3: Numbers And Math Using Comma Separate string and numbers 300
print(3+2) #print 5
print(3.0+2.0) #print 5.0
print(5-7) #print -1
print(7/4) #print 1.75
print("Drops the fractional part after the decimal",7//4) #print Drops the fractional part after the decimal 1
print(7.0/4.0) #print 1.75
print(75/4) #print 18.75
print((3+2)<(5-7)) #print False
print(10%2) #print 0
print("Exercise 4: Variables And Names")
cars = 100
spaceinacar = 4.0
drivers = 30
passengers = 90
carsnotdriven = cars - drivers
carsdriven = drivers
carpoolcapacity = carsdriven * spaceinacar
averagepassengersinacar = passengers / carsdriven
print("There are",cars,"cars available.") #print There are 100 cars available.
print("There are only",drivers,"drivers available.") #print There are only 30 drivers available.
print("There will be %d empty cars today." %carsnotdriven) #print There will be 70 empty cars today.
print("We can transport %.4f people today." %carpoolcapacity) #print We can transport 120.0000 people today.
print("We have {} to carpool today." .format(passengers)) #print We have 90 to carpool today.
print("We need to put about {} in each car." .format(averagepassengersinacar,".5f")) #print We need to put about 3.0 in each car.
print("Exercise 5: More Variables And Printing")
myname = "Zed A. Shaw"
myage = 35
myheight = 74
myweight = 180
myeyes = "blue"
myteeth = "white"
myhair = "brown"
print("Let's talk about %s" %myname) #print Let's talk about Zed A. Shaw
print("He's %d inches tall." %myheight) #print He's 74 inches tall.
print("He's {} pounds heavy." .format(myweight,"d")) #print He's 180 pounds heavy.
print("He's got %s eyes and %s hair." %(myeyes, myhair)) #print He's got blue eyes and brown hair.
print("His teeth are usually {} depending on the coffee." .format(myteeth)) #print His teeth are usually white depending on the coffee.
print("If I add {}, {}, and {}, I get {}." .format(myage, myheight, myweight, myage+myheight+myweight)) #print If I add 35, 74, and 180, I get 289.
print("Exercise 6: Strings And Text")
x = "There are %d types of people." %10
binary = "binary"
donot = "don't"
y = "Those who know %s and those who %s." %(binary, donot)
print(x) #print There are 10 types of people.
print(y) #print Those who know binary and those who don't.
print("I said: %r." %x) #print I said: 'There are 10 types of people.'. #RM: %r is for debugging which displays the raw data of the variable
print("I also said: '%s'." %y) #print I also said: 'Those who know binary and those who don't.'.
print("I also said: %s." %y) #print I also said: Those who know binary and those who don't..
hilarious = False
jokeevaluation = "Isn't that joke so funny?! %r"
print(jokeevaluation % hilarious) #print Isn't that joke so funny?! False
w = "This is the left side of . . . "
e = "a string with a right side."
print(w+e) #print This is the left side of . . . a string with a right side.
print("Exercise 7: More Printing")
print("Mary had a little lamb.") #print Mary had a little lamb.
print("Its fleece was white as %s." %"snow") #print Its fleece was white as snow.
print("And everywhere that Mary went") #print And everywhere that Mary went
print("."*10) #print ..........
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
print(end1+end2+end3+end4+end5+end6,end7+end8+end9+end10+end11+end12) #print Cheese Burger
print(end1+end2+end3+end4+end5+end6+end7+end8+end9+end10+end11+end12) #print CheeseBurger
number1 = 500
number2 = 743
print(number1,number2) #print 500 743
print(number1+number2) #print 1243
print("Exercise 8: Printing, Printing")
formatter = "%r %r %r %r"
print(formatter) #print %r %r %r %r
print(formatter %(1, 2, 3, 4)) #print 1 2 3 4
print(formatter %("one", "two", "three", "four")) #print 'one' 'two' 'three' 'four'
print(formatter %(True, False, False, True)) #print True False False True
print(formatter %(formatter, formatter, formatter, formatter)) #print '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
print(formatter %("I had this thing.","That you could type up right.", "But it didn't sing.", "So I said goodnight.")) #print 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
print("Exercise 9: Printing, Printing, Printing")
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFebMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days: ",days) #orint Here are the days: Mon Tue Wed Thu Fri Sat Sun
print("Here are the months:",months)
'''
Here are the months: Jan
FebMar
Apr
May
Jun
Jul
Aug
'''
print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
'''
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
'''
print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
'''
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
'''
print("Exercise 10: What Was That?")
tabby_cat = "\t I'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat) #print I'm tabbed in.
print(persian_cat) #print I'm split\n on a line.
print(backslash_cat) #print I'm \ a \ cat.
print(fat_cat)
"""
I'll do a list:
* Cat food
* Fishies
* Catnip
* Grass
"""
# while True:
# for i in ["/","-","|",",","\\","|"]:
# print("%s\r"%i,)
see = "Do you see?"
print("%s" %see) #print Do you see?
print("%r" %see) #print 'Do you see?'. %r prints out the raw representation including the original escape sequences.
print("Exercise 11: Asking Questions")
print("How old are you?"), #RM: tutorial says a comma at the end of the print line doesn't start a new line. It doesn't work.
#age = input()
age = 45
print("How tall are you?",)
#height = input()
height = 45
print("How much do you weight?",)
#weight = input()
weight = 45
print("So, you're %r old, %r tall and %r heavy." %(age, height, weight)) #print So, you're 45 old, 45 tall and 45 heavy.
print("Give me a number")
#inputnumber = int(input())
inputnumber = 45
print("The number is %r" %inputnumber) #print The number is 45
#instructor says input() has security problems. Use raw_input(). raw_input() doesn't work for python3.6.
print("Exercise 12: Prompting People")
#y = input("Name? ") #display Name? . Saves result into variable y.
y = "Raymond"
#age = input("How old are you? ")
age = (45)
#height = input("How tall are you? ")
height = (68)
#weight = input("How much do you weigh? ")
weight = (45)
print("So, you're %r old, %r tall and %r heavy." %(age, height, weight)) #print So, you're 45 old, 68 tall and 45 heavy.
print("Exercise 13: Parameters, Unpacking, Variables")
# from sys import argv
# script, first, second, third = argv
# #run python in Linux type the following: python3.6 first, 2nd, 3rd
# print("The script is called:", script) #print The script is called: learnpythonthehardway.py
# print("Your first variable is:", first) #print Your first variable is: first
# print("Your second variable is:", second) #print Your second variable is: 2nd
# print("Your third variable is:", third) #print Your third variable is: 3rd
print("Exercise 14: Prompting And Passing")
# username = input("What is your name? ")
# script = input("Share a favorite movie. ")
# like = input("Do you like yourself, %s? " %username)
# location = input("Where do you live, "+username+" ")
# computer = input("What kind of computer do you have? Desktop or laptop? ")
# print("""
# Alright, so you said %s about liking me.
# You live in %s. Not sure where that is.
# And you have a %s computer. Nice.
# """ %(like.lower(), location, computer.lower()))
print("Exercise 15: Reading Files")
#The keyword with closes the file once access to it is no longer needed. Notice how we call open() in this program but not close().
filename = "exercise15sample.txt"
with open(filename) as fileobject:
contents = fileobject.read()
print(contents) #print This is stuff I typed into a file.\n It is really cool stuff.\n Lots and lots of fun to have in here.
with open(filename) as fileobject:
contents = fileobject.read()
print(contents.rstrip()) #rstrip() method removes or strips any whitespace characters from the right side of a string.
with open(filename) as fileobject:
lines = fileobject.readlines() #readlines() method takes each line from the file and stores it in a list.
print(lines) #print ['This is stuff I typed into a file.\n', 'It is really cool stuff.\n', 'Lots and lots of fun to have in here.']
nospacesbetweenlines = ""
for line in lines:
print(line.rstrip())
nospacesbetweenlines += line.rstrip()
print(nospacesbetweenlines) #print This is stuff I typed into a file.It is really cool stuff.Lots and lots of fun to have in here.
print("Exercise 16: Reading And Writing Files")
#"r" read mode, "w" write mode, "a" append mode, "r+" read and write mode, default is read mode
filename = "exercise16sample.txt"
#write = input("Enter text for %s " %filename)
write = "howard jones"
with open(filename, "w") as fileobject:
fileobject.write(write)
fileobject.write("""
this is a test
okay a test
three lines
""")
print(fileobject) #print <_io.TextIOWrapper name='exercise16sample.txt' mode='w' encoding='UTF-8'>
with open(filename, "r") as fileobject:
contents = fileobject.read()
print(contents)
'''
howard jones
this is a test
okay a test
three lines
'''
print("Exercise 17: More Files")
#create text file exercise17sample.txt. Write the contents from Exercise 16 to text file text file exercise17sample.txt.
#The open() function automatically creates the file you’re writing to if it doesn’t already exist. However, be careful opening a file in write mode ('w') because if the file does exist, Python will erase the file before returning the file object.
filename = "exercise17sample.txt"
with open(filename, "w") as fileobject:
for chapter16contents in contents:
fileobject.write(chapter16contents)
with open(filename, "r") as fileobject:
contents = fileobject.read()
print(contents)
'''
howard jones
this is a test
okay a test
three lines
'''
print("Exercise 18: Names, Variables, Code, Functions")
def printtwo(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r" %(arg1, arg2))
printtwo("Zed",5) #print arg1: 'Zed', arg2: 5
def printtwoagain(arg1, arg2):
print("arg1: %r, arg2: %r" %(arg1, arg2))
printtwo("Zed2",52) #print arg1: 'Zed2', arg2: 52
def printone(arg1):
print("arg1: %r" %arg1)
printone("Zed3") #print arg1: 'Zed3'
def printnone():
print("I got nothin'.")
printnone() #print I got nothin'.
print("Exercise 19: Functions And Variables")
def cheeseandcrackers(cheesecount, boxesofcrackers):
print("You have %d cheeses!" %cheesecount)
print("You have",boxesofcrackers,"boxes of crackers")
cheeseandcrackers(20, 30) #return You have 20 cheeses!\n You have 30 boxes of crackers
amountofcheese = 10
amountofcrackers = 50
cheeseandcrackers(amountofcheese, amountofcrackers) #return You have 10 cheeses!\n You have 50 boxes of crackers
cheeseandcrackers(10+20, 5+6) #return You have 30 cheeses!\n You have 11 boxes of crackers
cheeseandcrackers(amountofcheese + 100, amountofcrackers + 200) #return You have 110 cheeses!\n You have 250 boxes of crackers
print("Exercise 19: Functions And Variables")
def cheeseandcrackers(cheesecount, boxesofcrackers):
print("You have %d cheeses!" %cheesecount)
print("You have",boxesofcrackers,"boxes of crackers!")
cheeseandcrackers(20,30) #return You have 20 cheeses!\n You have 30 boxes of crackers!
amountofcheese = 10
amountofcrackers = 50
cheeseandcrackers(amountofcheese, amountofcrackers) #return You have 10 cheeses!\n You have 50 boxes of crackers!
cheeseandcrackers(10+20, 5+6) #return You have 30 cheeses!\n You have 11 boxes of crackers!
cheeseandcrackers(amountofcheese+100, amountofcrackers + 1000) #return You have 110 cheeses!\n You have 1050 boxes of crackers!
print("Exercise 20: Functions And Files")
#"r" read mode, "w" write mode, "a" append mode, "r+" read and write mode, default is read mode
filename = "exercise20sample.txt"
#erase all text in exercise20sample.txt for a blank file
with open(filename, "w") as fileobject:
fileobject.write("")
def functionwrite(n):
name = "howard jones"
with open(filename, "a") as fileobject:
fileobject.write("%s %d\n" %(name, n))
for eachn in range(0,4):
functionwrite(eachn)
with open(filename, "r") as fileobject:
contents = fileobject.read()
print(contents)
print("Exercise 21: Functions Can Return Something")
def add(a, b):
print("Adding %d + %d" %(a,b))
return a+b
def subtract(a, b):
print("Subtracting",a,"-",b)
return a-b
def multiply(a, b):
print("Multiplying {} * {}" .format(a,b))
return a*b
def divide(a, b):
print("Dividing {} and {}" .format(a,b,".2f"))
return a/b
age = add(30,5) #return Adding 30 + 5
height = subtract(78,4) #return Subtracting 78 - 4
weight = multiply(90,2) #return Multiplying 90 * 2
iq = divide(100,2) #return Dividing 100 and 2
print("Age: %d, Height: %d, Weight %d, IQ: %d" %(age, height, weight, iq)) #print Age: 35, Height: 74, Weight 180, IQ: 50
print("Exercise 22: What Do You Know So Far?")
print("Exercise 23: Read Some Code")
print("Exercise 24: More Practice. RM: It's a review.")
print("Let's practice everything.") #print Let's practice everything.
print("You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")
'''
You'd need to know 'bout escapes with \ that do
newlines and tabs.
'''
poem = """
\t *paragraph indent \\t tab* The lovely world
with logic so firmly planted
cannot discern\nthe needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("----------")
print(poem)
print("-"*10)
'''
----------
*paragraph indent \t tab* The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation
where there is none.
----------
'''
five = 10 - 2 + 3 - 6
print("This should be five %s" %five) #print This should be five 5
print("This should be five",five) #print This should be five 5
print("This should be five {}" .format(five)) #print This should be five 5
def secretformula(started):
jellybeans = started * 500
jars = jellybeans // 1000
crates = jars // 100
return jellybeans, jars, crates
startpoint = 10000
beans, jars, crates = secretformula(startpoint)
print("With a starting point of: %d" %startpoint) #print With a starting point of: 10000
print("We'd have {} beans, {} jars, and {} crates." .format(beans, jars, crates)) #print We'd have 5000000 beans, 5000 jars, and 50 crates.
startpoint = startpoint /10
print("We can also do that this way:") #print We can also do that this way:
print("We'd have %d beans, %d jars, and %d crates." %(secretformula(startpoint))) #print We'd have 500000 beans, 500 jars, and 5 crates.
print("Exercise 25: Even More Practice")
def breakwordssplit(stuff):
words = stuff.split(" ")
return words
def sortwordssorted(words):
return sorted(words)
def printfirstwordpop(words):
word = words.pop(0)
return word
def printlastwordpop(words):
word = words.pop(-1)
return word
def sortsentencecallfunctions(sentence):
#call functions breakwordssplit and sortwordssorted
words = breakwordssplit(sentence)
return sortwordssorted(words)
def printfirstandlastcallfunctions(sentence):
#call functions breakwordssplit, printfirstwordpop, printlastwordpop
words = breakwordssplit(sentence)
print(printfirstwordpop(words))
print(printlastwordpop(words))
def printfirstandlastsortedcallfunctions(sentence):
#call functions breakwordssplit, sortwordssorted, printfirstwordpop, printlastwordpop. RM: break words first, sort words second.
words = breakwordssplit(sentence)
words = sortwordssorted(words)
print(printfirstwordpop(words))
print(printlastwordpop(words))
sentence = "All good things come to those who wait."
print(breakwordssplit(sentence)) #print ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
print(sortwordssorted(sentence)) #print [' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', 'A', 'a', 'c', 'd', 'e', 'e', 'g', 'g', 'h', 'h', 'h', 'i', 'i', 'l', 'l', 'm', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 's', 's', 't', 't', 't', 't', 'w', 'w']
print(sortwordssorted(breakwordssplit(sentence))) #print ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
print(printfirstwordpop(breakwordssplit(sentence))) #print All RM: pop is a function for lists.
print(printlastwordpop(breakwordssplit(sentence))) #print wait. RM: pop is a function for lists.
printfirstandlastcallfunctions(sentence) #print All\n wait.
printfirstandlastsortedcallfunctions(sentence) #print All\n who
test = "the quick brown fox jumped over the lazy dog"
print(test.split(" ")) #print ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
print(sorted(test.split(" "))) #print ['brown', 'dog', 'fox', 'jumped', 'lazy', 'over', 'quick', 'the', 'the']
print(test.split(" ").pop(0)) #print the
print("Exercise 26: Congratulations, Take A Test!")
#file saved exercise26learnpythonthehardway.txt
print("Exercise 27: Memorizing Logic")
'''
1 != 0 True
1 != 1 False
0 != 1 True
0 != 0 False
1 == 0 False
1 == 1 True
0 == 1 False
0 == 0 True
'''
print("Exercise 28: Boolean Practice")
print(True and True) #print True
print(1 and "top") #print top
print("top" and 1 and "la") #print la
print("top" or 1) #print top
print(1 or "top" or "la") #print 1
print(False and True) #print False
print(1==1 and 2==1) #print False
print("test" == "test") #print True
print(1==1 and 2!=1) #print True
print(True and 1==1) #print True
print(False and 0!=0) #print False
print(True or 1==1) #print True
print("test" == "testing") #print False
print(1!=0 and 2==1) #print False
print("test" != "testing") #print True
print("test" == 1) #print False
print(not (True and False)) #print True
print(not (1==1 and 0!=1)) #print False
print(not (10==1 or 1000 == 1000)) #print False
print(not (1!=10 or 3==4)) #print False
print(not ("testing" == "testing" and "Zed" == "Cool Guy")) #print True
print(1==1 and not ("testing"== 1 or 1==0)) #print True
print("chunky" == "bacon" and not (3==4 or 3==3)) #print False
print(3==3 and not ("testing" == "testing" or "Python" == "Fun")) #print False
print("Exercise 29: What If")
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!") #print Too many cats! The world is doomed!
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!") #print The world is dry!
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.") #print People are greater than or equal to dogs.
if people <= dogs:
print("People are less than or equal to dogs.") #print People are less than or equal to dogs.
if people == dogs:
print("People are dogs.") #print People are dogs.
print("Exercise 30: Else And If")
people = 30
cars = 40
buses = 15
if cars > people:
print("We should take the cars.") #print We should take the cars.
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide")
if buses > cars:
print("That's too many buses.")
elif buses < cars:
print("Maybe we could take the buses.") #print Maybe we could take the buses.
else:
print("We still can't decide.")
if people > buses:
print("Alright, let's just take the buses.") #print Alright, let's just take the buses.
else:
print("Find, let's stay home then.")
print("Exercise 31: Making Decisions")
#print("You enter a dark room with two doors. Do you go through door #1 or door #2?")
#door = int(input("You enter a dark room with two doors. Do you go through door #1 or door #2? "))
door = 1
if door == 1:
#bear = int(input("There's a giant bear here eating a cheese cake. What do you do? 1. Take the cake or 2. Scream at the bear? "))
bear = 1
if bear == 1:
print("The bear eats your face off. Good job!")
elif bear == 2:
print("The bear eats your legs off. Good job!")
else:
print("Well, doing %s is probably better. Bear runs away." %bear)
elif door == 2:
insanity = int(input("You stare into the endless abyss at Cthulu's retina.\n1. Blueberries.\n2. Yellow jacket clothespins.\n3. Understanding revolvers yelling melodies. "))
if insanity == 1 or insanity == 2:
print("Your body survives powered by a mind of jello. Good job!")
else:
print("The insanity rots your eyes into a pool of muck. Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
print("Exercise 32: Loops And Lists")
thecount = [1, 2, 3, 4, 5]
fruits = ["apples","oranges","pears","apricots"]
change = [1, "pennies",2,"dimes",3,"quarters"]
for number in thecount:
print("This is count %d" %number) #print This is count 1\n . . . This is count 5
for fruit in fruits:
print("A fruit of type: %s" %fruit) #print A fruit of type: apples\n . . . A fruit of type: apricots
for i in change:
print("I got %r" %i) #print I got 1\n I got 'pennies'\n . . . I got 3\n I got 'quarters'
addelements = []
for i in range (0,6):
print("Adding {} to the list." .format(i)) #print Adding 0 to the list.\n . . . Adding 5 to the list.
addelements.append(i)
for i in addelements:
print("Element was:",i) #print Element was: 0\n . . . Element was: 5
print("Exercise 33: While Loops")
i = 0
numbers = []
while i < 6:
print("At the top i is %d" %i)
numbers.append(i)
i = i + 1
print("Numbers now",numbers)
print("At the bottom i is %d", i)
'''
At the top i is 0
Numbers now [0]
At the bottom i is %d 1
...
At the top i is 5
Numbers now [0, 1, 2, 3, 4, 5]
At the bottom i is %d 6
'''
print("The numbers: ")
for num in numbers:
print(num) #print 0\n 1\n 2\n 3\n 4\n 5
print("Exercise 34: Accessing Elements Of Lists")
print("Programmers pull elements out of a lists consistently by an address or an index. Indices start at zero. The indices number is a cardinal number. Human translation is the ordinal number subtract one for the cardinal number; e.g. the third animal in the list is index second. ordinal == ordered 1st; cardinal == cards at random zero.")
animals = ["bear","python","peacock","kangaroo","whale","platypus"]
print("The animal at 1. "+animals[1])
print("The 3rd animal. "+animals[2])
print("The 1st animal. "+animals[0])
print("The animal at 3. "+animals[3])
print("The 5th animal. "+animals[4])
print("The animal at 2. "+animals[2])
print("The 6th animal. "+animals[5])
print("The animal at 4. "+animals[4])
print("Exercise 35: Branches And Functions")
from sys import exit
def goldroom():
try:
howmuchgold = int(input("This room is full of gold. How much do you take? "))
except ValueError:
dead("Man, learn to type a number. Learn to type an integer.")
else:
if howmuchgold < 50:
print("Nice, you're not greedy, you win")
exit(0)
else:
dead("You greedy bastard!")
def bearroom():
print("There is a bear here.\nThe bear has a bunch of honey.\nThe fat bear is in front of another door.")
bearmoved = False
while True:
nextmove = input("How are you going to move the bear? take honey, taunt bear, open door? ")
if nextmove == "take honey":
dead("The bear looks at you then slaps your face off.")
elif nextmove == "taunt bear" and not bearmoved:
print("The bear has moved from the door. You can go through now.")
bearmoved = True
elif nextmove == "taunt bear" and bearmoved:
dead("The bear gets pissed off and chews your leg off.")
elif nextmove == "open door" and bearmoved:
goldroom()
else:
dead("I got no idea what that means")
def cthulhuroom():
print("Here your see the great evil Cthulhu.\nHe, it, whatever stares at you and you go insane.")
nextmove = input("Do you flee for your life or eat your head? flee or head? ")
if nextmove == "flee":
start()
elif nextmove == "head":
dead("Well that was tasty!")
else:
cthulhuroom()
def dead(why):
print(why+" Good job!")
exit(0)
def start():
print("You are in a dark room.\nThere is a door to your right and left.")
nextmove = input("Which one do you take? right or left? ")
if nextmove == "left":
bearroom()
elif nextmove == "right":
cthulhuroom()
else:
dead("You stumble around the room until you starve.")
#start()
print("Exercise 36: Designing And Debugging")
print("Use a while-loop to loop forever, and that means probably never. However, sometimes rules are broken.")
print("Use a for-loop for all other kinds especially a fixed or limited number loops.")
print("Exercise 37: Symbol Review")
print("Exercise 38: Doing Things To Lists")
tenthings = "Apples Oranges Crows Telephone Light Sugar"
print("Wait, there's not 10 things in that list, let's fix that.")
stuff = tenthings.split(" ")
print(stuff) #print ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar']
morestuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
while len(stuff) != 10:
nextone = morestuff.pop() #pop() removes the last indexed item in a list
print("Adding",nextone)
stuff.append(nextone)
print("There's %d items now." %len(stuff))
print("There we got:",stuff) #print There we got: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
print(stuff[1]) #print Oranges
print(stuff[-1]) #print Corn
print(" ".join(stuff)) #print Apples Oranges Crows Telephone Light Sugar Boy Girl Banana Corn
print(stuff.pop()) #print Corn
print(" ".join(stuff)) #print Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
print("#".join(stuff[3:5])) #print Telephone#Light
print("Exercise 39: Dictionaries, Oh Lovely Dictionaries")
stuff = {"name":"Zed", "age":36, "height":6*12+2}
print(stuff["name"]) #print Zed
print(stuff["age"]) #print 26
print(stuff["height"]) #print 74
stuff["city"] = "San Francisco"
print(stuff) #print {'name': 'Zed', 'age': 36, 'height': 74, 'city': 'San Francisco'}
stuff[1] = "Wow"
stuff[2] = "Neato"
print(stuff) #print {'name': 'Zed', 'age': 36, 'height': 74, 'city': 'San Francisco', 1: 'Wow', 2: 'Neato'}
del stuff["city"]
del stuff[1]
del stuff[2]
print(stuff) #print {'name': 'Zed', 'age': 36, 'height': 74}
states = {"Oregon":"OR", "Florida":"FL", "California":"CA", "New York":"NY", "Michigan":"MI"}
cities = {"CA":"San Francisco", "MI":"Detroit", "FL":"Jacksonville"}
cities["NY"] = "New York"
cities["OR"] = "Portland"
print("NY State has: ", cities["NY"]) #print NY State has: New York
print("OR State has: ", cities["OR"]) #print OR State has: Portland
print("Michigan's abbreviation is: ",states["Michigan"]) #print Michigan's abbreviation is: MI
print("Florida's abbreviation is: ",states["Florida"]) #print Florida's abbreviation is: FL
print("Michigan has: ",cities[states["Michigan"]]) #print Michigan has: Detroit
print("Florida has: ",cities[states["Florida"]]) #print Florida has: Jacksonville
for state, abbrev in states.items():
print("%s is abbreviated %s " % (state, abbrev))
'''
Oregon is abbreviated OR
Florida is abbreviated FL
California is abbreviated CA
New York is abbreviated NY
Michigan is abbreviated MI
'''
for abbrev, city in cities.items():
print("%s has the city %s" %(abbrev, city))
'''
CA has the city San Francisco
MI has the city Detroit
FL has the city Jacksonville
NY has the city New York
OR has the city Portland
'''
for state, abbrev in states.items():
print("%s state is abbreviated %s and has city %s" %(state, abbrev, cities[abbrev]))
'''
Oregon state is abbreviated OR and has city Portland
Florida state is abbreviated FL and has city Jacksonville
California state is abbreviated CA and has city San Francisco
New York state is abbreviated NY and has city New York
Michigan state is abbreviated MI and has city Detroit
'''
state = states.get("Texas", "No Texas")
print(state) #print No Texas
texascity = cities.get("TX","Doesn't exist")
print(texascity) #print Doesn't exist
print("The city for the state TX is: %s" %texascity) #print The city for the state TX is: Doesn't exist
cities["TX"] = "Austin"
texascity = cities.get("TX","Doesn't exist")
print(texascity) #print Austin
print("The city for the state TX is: %s" %texascity) #print The city for the state TX is: Austin
print("Exercise 40: Modules, Classes, And Objects")
mystuff = {"apple":"I am apples"}
print(mystuff["apple"]) #print I am apples
import mystuff #RM: file mystuff.py
mystuff.apple() #print I am apples. apple() function from mystuff.py python file.
print(mystuff.tangerine) #print Living reflection of a dream. RM: tangerine = "Living reflection of a dream" defined in mystuff.py python file.
thing = mystuff.MyStuff() #MyStuff() class is in mystuff.py python file
thing.apple() #return I am classy applies in class MyStuff from mystuff.py python file.
print(thing.tangerine) #print And now a thousand years between
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def singmeasong(self):
for eachlyrics in self.lyrics:
print(eachlyrics)
happybirthdaylyrics = ["Happy birthday to you","I don't want to get sued","So I'll stop right there"]
happybirthday = Song(happybirthdaylyrics)
happybirthday.singmeasong() #return Happy birthday to you\n I don't want to get sued\n So I'll stop right there
bullsonparadelyrics = ["They rally around the family","With pockets full of shells"]
bullsonparade = Song(bullsonparadelyrics)
bullsonparade.singmeasong() #return They rally around the family\n With pockets full of shells
print("Exercise 41: Learning To Speak Object Oriented")
classworddrill = "Tell python to make a new kind of thing."
objectworddrill = "Two meanings: the most basic kind of thing and any instance of some thing."
instanceworddrill = "What you get when you tell Python to create a class."
defworddrill = "How you define a function inside a class."
selfworddrill = "Inside a functions in a class, self is a variable for the instance/object being accessed."
inheritanceworddrill = "The concept that one class can inherit traits from another class, much like you and your parents."
compositionworddrill = "The concept that a class can be composed of other classes as parts, much like how a car has wheels."
attributeworddrill = "A property classes have that are from composition and are usually variables."
isaworddrill = "A phase to say that something inherits from another, as in a salmon is-a fish."
hasaworddrill = "A phase to say that something is composed of other things or has a trait, as in a salmon has-a mouth."
class X1(object):
def __init__(self):
pass
def printsomething(self):
print("Make a class named X1 that is-an object.")
class X2(object):
def __init__(self, J):
self.jparameter = J
def printsomething2(self):
print("Class X2 has-a __init__ that takes self and J parameters.",self.jparameter)
class X3(object):
def M(self, J):
self.J = J
print("Class X3 has-a function named M that takes self and J parameters.",self.J)
foo = X1() #set foo to an instance of class X1.
foo.printsomething() #return Make a class named X1 that is-an object.
fooreturnmakeaclassnamedX1again = X1()
fooreturnmakeaclassnamedX1again.printsomething() #return Make a class named X1 that is-an object.
foo2 = X2("Jam")
foo2.printsomething2() #return Class X2 has-a __init__ that takes self and J parameters. Jam
foo3 = X3() #from foo3 get the M function and call it with parameters self, J in class X3.
foo3.M("Jelly") #return Class X3 has-a function named M that takes self and J parameters. Jelly
foo.K = X3 #from foo.K get the K attribute and set it to X3.
print("Exercise 42: Is-A, Has-A, Objects, and Classes")
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
def printdogname(self):
print(self.name+" is from class Dog(Animal).")
class Cat(Animal):
def __init__(self, name):
self.name = name
# class Employee(Person):
# def __init__(self, name, salary):
# super(Employee, self).__init__(name)
# #self.name = name
# self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
rover.printdogname() #return Rover is from class Dog(Animal).
# satan = Cat("Satan")
# mary = Person("Mary")
# mary.pet = satan
# frank = Employee("Frank", 120000)
# frank.pet = rover
flipper = Fish()
crouse = Salmon()
harry = Halibut()
print("Exercise 43: Basic Object Oriented Analysis And Design")
print("Exercise 44: Inheritance Vs. Composition")
#Inheritance indicates one class get most or all of its features from a parent class. E.g. class Foo(Bar) make a class Foo which inherits from Bar. Any instances of Foo also works of Bar. Actions on the child imply an action on the parent. Actions on the child override the action on the parent. Actions on the child alter the action on the parent.
class Parent(object):
def implicit(self):
print("Parent implicit()")
class Child(Parent):
#Child(Parent) inherits all behavior from Parent(object); e.g. if you put functions in a base class or parent class Parent(object) then all subclasses class Child(Parent) get the functions.
pass
dad = Parent()
son = Child()
dad.implicit() #return Parent implicit()
son.implicit() #return Parent implicit()
class Parent(object):
def override(self):
print("Parent override()")
class Child(Parent):
#Child(Parent) has its own override(self) function. son is an instance of Child or son = Child(). Child(Parent) overrides override(self) function.
def override(self):
print("Child override()")
dad = Parent()
son = Child()
dad.override() #return Parent override()
son.override() #return Child override()
class Parent(object):
def altered(self):
print("Parent altered()")
class Child(Parent):
def altered(self):
print("Child before parent altered()")
super(Child, self).altered() #get the Parent altered() from Parent(object) calling the altered() function
print("Child after parent altered()")
dad = Parent()
son = Child()
dad.altered() #return Parent altered()
son.altered() #return Child before parent altered()\n Parent altered()\n Child after parent altered()
class Parent(object):
def override(self):
print("Parent override()")
def implicit(self):
print("Parent implicit()")
def altered(self):
print("Parent altered()")
class Child(Parent):
def override(self):
print("Child override()")
def altered(self):
print("Child before parent altered()")
super(Child, self).altered()
print("Child after parent altered()")
dad = Parent()
son = Child()
dad.implicit() #return Parent implicit()
son.implicit() #return Parent implicit()
dad.override() #return Parent override()
son.override() #return Child override()
dad.altered() #return Parent altered()
son.altered() #return Child before parent altered()\n Parent altered()\n Child after parent altered()
class Parent(object):
def override(self):
print("Parent override()")
class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
def possession(self):
print(self.stuff)
def superwhat(self):
super(Child, self).__init__() #RM: I don't know the purpose of super(Child, self).__init__(). The most common use of super() is actually in __init__ functions in base classes. This is usually the only place where you need to do some things in a child, then complete the initialization in the parent.
super(Child, self).override()
dad = Parent()
dad.override() #return Parent override()
son = Child("pampers")
son.possession() #return pampers
son.override() #return Parent override()
son.superwhat() #return Parent override()
#RM: skipped Composition pages 146-148.
#RM: Satisifed skipped final exercises 45-52 because their projects game, input from browser, advanced user input.
|
49080b073b5479f376edf83be7300067cb3e4e0c
|
ZiyaoGeng/LeetCode
|
/functions/test_singly_linked_list.py
| 324 | 3.921875 | 4 |
from singly_linked_list import ListNode
# 创建单链表
def create_list(nums):
L = ListNode(0)
l = L
for i in nums:
l.next = ListNode(i)
l = l.next
return L.next
# 输出单链表的值
def print_list_val(l):
while l != None:
print(l.val, end='')
l = l.next
if l != None:
print('->', end='')
print()
|
c05dca87c77799504ba73618e8c407beb680fd39
|
ArkFreestyle/PythonDesignPatterns
|
/facade_pattern.py
| 1,495 | 3.546875 | 4 |
"""
The facade pattern is designed to provide a simple interface
to a complex system of components.
It's pretty similar to the adapter pattern, but here's the main difference:
- the facade is trying to abstract a simpler interface out of a complex one.
- the adapter is only trying to map one existing interface to another.
For eg: The requests library is a facade over the less readable HTTP library.
"""
import smtplib
import imaplib
class EmailFacade:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def send_email(self, to_email, subject, message):
if not "@" in self.username:
from_email = f"{self.username}@{self.host}"
else:
from_email = self.username
message = (f"From: {from_email}"
f"To: {to_email}\r\n"
f"Subject: {subject}\r\n\r\n{message}")
smtp = smtplib.SMTP(self.host)
smtp.login(self.username, self.password)
smtp.sendmail(from_email, [to_email], message)
def get_inbox(self):
mailbox = imaplib.IMAP4(self.host)
mailbox.login(bytes(self.username, 'utf8'), bytes(self.password, 'utf8'))
mailbox.select()
x, data = mailbox.search(None, 'ALL')
messages = []
for num in data[0].split():
x, message = mailbox.fetch(num, '(RFC822)')
messages.append(message[0][1])
return messages
|
699fe37ea0cd099d235be620eb1f93555e03d51b
|
mupastir/ImprvSkills
|
/problem_6.py
| 597 | 3.78125 | 4 |
'''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
num_sum_sq = int(0)
num_sq_sum = int(0)
for i in range(1, 101):
num_sq_sum += i * i
num_sum_sq += i
print(num_sum_sq * num_sum_sq - num_sq_sum)
|
0e0ca731755610aa2e146312bae2563036ca90fe
|
BhuwanSingh/Ode_to_Code-
|
/live.py
| 1,356 | 3.703125 | 4 |
import pyttsx3
import speech_recognition as sr
import json
import base64
import wavio
# Initialize the recognizer
r = sr.Recognizer()
# Function to convert text to
# speech
encode_string = open("audio.wav", "rb").read()
wav_file = open("temp.wav", "wb")
decode_string = base64.b64decode(encode_string)
wav_file.write(decode_string)
filename='temp.wav'
wavio.write(filename, temp, fs ,sampwidth=2)
#def SpeakText(command):
# Initialize the engine
# engine = pyttsx3.init()
# engine.say(command)
# engine.runAndWait()
# Loop infinitely for user to
# speak
while(1):
# Exception handling to handle
# exceptions at the runtime
try:
with sr.AudioFile(filename) as source:
# listen for the data (load audio to memory)
audio_data = r.record(source)
# recognize (convert from speech to text)
text = r.recognize_google(audio_data)
print(text)
text = text.lower()
f=open("output.txt","w+")
arr = text.split()
f.write(json.dumps(arr))
f.close()
print("Did you say " + text)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
print("unknown error occured")
|
1ab7c767dfc53f4042b997b19702dd1446f6e9e2
|
realhardik18/minor-projects
|
/number guesser.py
| 192 | 3.734375 | 4 |
import random
robo_num=random.randint(1,10)
user_num=int(input("guess a number between 1 and 10 herer: "))
if robo_num==user_num:
print("YESSS")
else:
print(f'nope it was {robo_num}')
|
9b31b05f1bcb1022a7618d3fda18310693a0ea23
|
COBETCKNN17/coding-dojo
|
/python/multiples-sum-avg/multiples-sum-avg.py
| 365 | 3.75 | 4 |
#Multiples
for i in range(1,1000):
if i % 2 == 1:
print i
for x in range(1,100000):
if i % 5 == 0:
print i
#Sum List
a = [1, 2, 5, 10, 255, 3]
vsum = 0
for x in a:
vsum+=x
print "Sum: ", vsum
#Average List
a = [1, 2, 5, 10, 255, 3]
vsum = 0
for x in a:
vsum+=x
vavg = vsum/len(a)
print "Sum: ", vsum
print "Avg: ", vavg
|
270e6ba49a716452f0e675144c41b523df74af0f
|
Joslu/Curso-Python
|
/5. Listas.py
| 469 | 3.953125 | 4 |
#Son parecidas a los arrays en otros lenguajes de rogramación
Mylista = [1,"Luis", 23, 10.5, True]
colors = ["blue","green","blue","red"]
#Forma de hacerlo con constructor
# Utilizando tupla para hacer una lista
Lista = list((2,3,4,5))
print(Lista)
#Crear lista con range)=
Fila = list(range(1,100))
print(Fila)
colors.append("black") #Agreagar un nuevo elemento a la lista colors
colors.extend(["brown", "pink"]) #Extienden la lista con otra lista
print(colors)
|
0b7947c7d0f95030eaf7d5ea20db67233bd91907
|
chenxu0602/LeetCode
|
/1568.minimum-number-of-days-to-disconnect-island.py
| 4,084 | 3.84375 | 4 |
#
# @lc app=leetcode id=1568 lang=python3
#
# [1568] Minimum Number of Days to Disconnect Island
#
# https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/description/
#
# algorithms
# Hard (50.75%)
# Likes: 158
# Dislikes: 94
# Total Accepted: 5.2K
# Total Submissions: 10.2K
# Testcase Example: '[[0,1,1,0],[0,1,1,0],[0,0,0,0]]'
#
# Given a 2D grid consisting of 1s (land) and 0s (water). An island is a
# maximal 4-directionally (horizontal or vertical) connected group of 1s.
#
# The grid is said to be connected if we have exactly one island, otherwise is
# said disconnected.
#
# In one day, we are allowed to change any single land cell (1) into a water
# cell (0).
#
# Return the minimum number of days to disconnect the grid.
#
#
# Example 1:
#
#
#
#
# Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
# Output: 2
# Explanation: We need at least 2 days to get a disconnected grid.
# Change land grid[1][1] and grid[0][2] to water and get 2 disconnected
# island.
#
#
# Example 2:
#
#
# Input: grid = [[1,1]]
# Output: 2
# Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0
# islands.
#
#
# Example 3:
#
#
# Input: grid = [[1,0,1,0]]
# Output: 0
#
#
# Example 4:
#
#
# Input: grid = [[1,1,0,1,1],
# [1,1,1,1,1],
# [1,1,0,1,1],
# [1,1,0,1,1]]
# Output: 1
#
#
# Example 5:
#
#
# Input: grid = [[1,1,0,1,1],
# [1,1,1,1,1],
# [1,1,0,1,1],
# [1,1,1,1,1]]
# Output: 2
#
#
#
# Constraints:
#
#
# 1 <= grid.length, grid[i].length <= 30
# grid[i][j] is 0 or 1.
#
#
#
# @lc code=start
import copy
class Solution:
def minDays(self, grid: List[List[int]]) -> int:
# def no_islands_recur(grid, i, j, m, n):
# if grid[i][j] == 0:
# return
# grid[i][j] = 0
# if i - 1 >= 0:
# no_islands_recur(grid, i - 1, j, m, n)
# if i + 1 < m:
# no_islands_recur(grid, i + 1, j, m, n)
# if j - 1 >= 0:
# no_islands_recur(grid, i, j - 1, m, n)
# if j + 1 < n:
# no_islands_recur(grid, i, j + 1, m, n)
# #find how many islands the given grid has
# def no_islands(grid):
# ret = 0
# m, n = map(len, (grid, grid[0]))
# for i in range(m):
# for j in range(n):
# if grid[i][j] == 1:
# ret += 1
# no_islands_recur(grid, i, j, m, n)
# return ret
# time = 0
# grid_copy = copy.deepcopy(grid)
# n = no_islands(grid_copy)
# if n != 1: return time
# time = 1
# for i in range(len(grid)):
# for j in range(len(grid[0])):
# grid_copy = copy.deepcopy(grid)
# grid_copy[i][j] = 0
# n = no_islands(grid_copy)
# if n != 1:
# return time
# time = 2
# return time
def dfs(grid, r, c, visited):
if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1 and (r, c) not in visited:
visited.add((r, c))
dfs(grid, r + 1, c, visited)
dfs(grid, r - 1, c, visited)
dfs(grid, r, c + 1, visited)
dfs(grid, r, c - 1, visited)
def countIslands(grid):
islands = 0
visited = set()
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 1 and (r, c) not in visited:
islands += 1
dfs(grid, r, c, visited)
return islands
if countIslands(grid) != 1:
return 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
grid[i][j] = 0
if countIslands(grid) != 1:
return 1
grid[i][j] = 1
return 2
# @lc code=end
|
a70b0794607e5e3e5e23284135e8896b78e84ced
|
emily-yu/hackerrank
|
/easy/arrays-ds.py
| 378 | 3.671875 | 4 |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
if len(a) == 0 or len(a) == 1:
return a
for i in range(len(a) // 2):
# print(i)
# print(len(a) - i)
a[i], a[len(a) - i - 1] = a[len(a) - i - 1], a[i]
return a
reverseArray([1, 4, 3, 2])
|
fc53661ab2ab452fe8dfadfb8fa83b38edce2212
|
nandanabhishek/LeetCode
|
/problems/1669. Merge In Between Linked Lists/sol.py
| 1,080 | 4.21875 | 4 |
# Approach-1 : What I thought
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
# Define 2 pointers
ptr1=list1
ptr2=list1
i=0
j=0
# Loop for pointer 1 to reach node just before a
while i!=a-1:
ptr1 = ptr1.next
i += 1
# Loop for pointer 2 to reach at node b
while j!=b:
ptr2 = ptr2.next
j += 1
# Connect list2 to the next of pointer1
ptr1.next = list2
# Traverse the list2 till end node
while list2.next!=None:
list2 = list2.next
# Assign the next of pointer 2 to the next of list2 i.e connect the remaining part of list1 to list2
list2.next = ptr2.next
# return final list i.e pointer which refers to the head of the final list
return list1
|
af4fffa425f93f4c2829777f2e83725cf51b162b
|
MatiasUK/blackjack
|
/bjgame.py
| 3,220 | 3.8125 | 4 |
# blackjack game
# Process
# Player Cards First (2)
# Dealer Cards Next (2)
# Display Player Cards to User
# Sum of the Dealer Cards
# Sum of the Player Cards
# Compare the sums of the cards between D v P
# If P card sum > 21 = BUST
# Loop If P card is <=21 = Twist or Stick (Try)
# P twists again - Check <=21 condition else, Stick.
# Check Dealers Cards
# Dealer compares his two cards with total sum of the player cards (14 - 19)
# Dealer >= Player Cards = Dealer Wins
# If Dealer cards >21 = BUST
import random
import time
global std_deck
def deal_and_display():
std_deck = [
# 2 3 4 5 6 7 8 9 10 J Q K A
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
]
c1 = std_deck.pop(random.randrange(len(std_deck)))
c2 = std_deck.pop(random.randrange(len(std_deck)))
print("Player has: " + str(c1) + " and " + str(c2) + "\nTotal = " + str(c1 + c2))
d1 = std_deck.pop(random.randrange(len(std_deck)))
d2 = std_deck.pop(random.randrange(len(std_deck)))
print("Dealer has: " + str(d1) + " and " + str(d2) + "\nTotal = " + str(d1 + d2))
player_total = c1 + c2
dealer_total = d1 + d2
while player_total <= 21:
c3 = std_deck.pop(random.randrange(len(std_deck)))
choice = input("Player total is: " + (str(player_total) + " - Would you like to [S]tick or [T]wist?: "))
if choice == "S":
print("Player has: " + (str(player_total)))
break
# Move onto Dealers Turn
elif choice == "T":
time.sleep(0.5)
print("New card is a " + str(c3))
player_total += c3
if player_total > 21:
print("Player has bust with " + str(player_total))
print("\nNEW GAME!\n")
deal_and_display()
while dealer_total <= 21:
d3 = std_deck.pop(random.randrange(len(std_deck)))
print("Dealer has: " + str(dealer_total))
time.sleep(2)
try:
if dealer_total < player_total:
print("Dealer draws")
time.sleep(1)
dealer_total += int(d3)
time.sleep(1)
print("New card is a " + str(d3))
except:
if dealer_total == 17:
print("Dealer sticks with 17")
break
if dealer_total > 21:
time.sleep(1)
print("Dealer busts with " + str(dealer_total))
print("\nNEW GAME!\n")
time.sleep(1)
deal_and_display()
if dealer_total >= player_total or player_total > 21:
time.sleep(1)
print("Dealer wins with " + str(dealer_total))
time.sleep(1)
print("\nNEW GAME!\n")
deal_and_display()
if (dealer_total > player_total) and (dealer_total <= 21):
time.sleep(1)
print("Dealer wins!")
print("\nNEW GAME!\n")
time.sleep(1)
deal_and_display()
deal_and_display()
|
8f06c61f9bd5ffc1f7dd8f8130535e532924f062
|
nefta1937/memoria
|
/src/int_posicion.py
| 6,695 | 3.84375 | 4 |
from io import open
import math
while (1):
print("Para mover de forma automática:1\nPara mover de forma manual: 2\nPara mover 2 robots: 3\nPara mover 3 robots: 4\n Para ordenar robots: 5")
L1 = input("Ingrese opción>>")
if L1 == '1':
print("Insertar coordenadas x,y")
x1 =input("x >>")
y1 = input("y >>")
RobMov = 0
robMov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/RobMov.txt","w")
robMov.write(str(RobMov))
robMov.close()
X1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X1.txt","w")
X1.write(str(x1))
X1.close()
Y1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y1.txt","w")
Y1.write(str(y1))
Y1.close()
elif L1 == '2':
print("Función de momento no disponible")
#print("Inserte robot que desea mover\n Azul: 1\n Naranjo: 2\n Verde: 3")
#RobMov = input("Robot >>")
#print("Insertar coordenadas x,y")
#x1 =input("x >>")
#y1 = input("y >>")
#robMov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/RobMov.txt","w")
#robMov.write(str(RobMov))
#robMov.close()
#X1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X1.txt","w")
#X1.write(str(x2))
#X1.close()
#Y1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y1.txt","w")
#Y1.write(str(y2))
#Y1.close()
elif L1 == '3':
print("Ha seleccionado mover 2 robot")
RobMov = 4
robMov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/RobMov.txt","w")
robMov.write(str(RobMov))
robMov.close()
'''RobMov1 = input("Robot 1 >>")
RobMov2 = input("Robot 2 >>")
Rob2Mov = int(RobMov1)+int(RobMov2)
rob2Mov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Rob2Mov.txt","w")
rob2Mov.write(str(Rob2Mov))
rob2Mov.close()'''
print("Insertar coordenadas x,y primer robot")
x1 =input("x >>")
y1 = input("y >>")
print("Insertar coordenadas x,y segundo robot")
x2 =input("x >>")
y2 = input("y >>")
X1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X1.txt","w")
X1.write(str(x1))
X1.close()
Y1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y1.txt","w")
Y1.write(str(y1))
Y1.close()
X2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X2.txt","w")
X2.write(str(x2))
X2.close()
Y2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y2.txt","w")
Y2.write(str(y2))
Y2.close()
elif L1 == '4':
print("Se moverán los 3 robots")
RobMov = 5
robMov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/RobMov.txt","w")
robMov.write(str(RobMov))
robMov.close()
print("Insertar coordenadas x,y primer robot")
x1 =input("x >>")
y1 = input("y >>")
print("Insertar coordenadas x,y segundo robot")
x2 =input("x >>")
y2 = input("y >>")
print("Insertar coordenadas x,y tercer robot robot")
x3 =input("x >>")
y3 = input("y >>")
X1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X1.txt","w")
X1.write(str(x1))
X1.close()
Y1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y1.txt","w")
Y1.write(str(y1))
Y1.close()
X2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X2.txt","w")
X2.write(str(x2))
X2.close()
Y2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y2.txt","w")
Y2.write(str(y2))
Y2.close()
X3 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X3.txt","w")
X3.write(str(x3))
X3.close()
Y3 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y3.txt","w")
Y3.write(str(y3))
Y3.close()
elif L1 == '5':
print("Se moverán los 3 robots")
RobMov = 5
robMov = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/RobMov.txt","w")
robMov.write(str(RobMov))
robMov.close()
print("Línea vertical: 1\n Línea Horizontal: 2\n Triangulo: 3")
TipLin = input("Opción >>")
pp = 1
if TipLin == '1':
x1 = 628
y1 = 200
x2 = 628
y2 = 400
x3 = 628
y3 = 600
elif TipLin == '2':
x1 = 200
y1 = 400
x2 = 620
y2 = 400
x3 = 1040
y3 = 400
elif TipLin == '3' :
x1 = 628
y1 = 150
x2 = 845
y2 = 525
x3 = 411
y3 = 525
else:
print("Opción no válida")
pp = 0
if pp == 1:
X1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X1.txt","w")
X1.write(str(x1))
X1.close()
Y1 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y1.txt","w")
Y1.write(str(y1))
Y1.close()
X2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X2.txt","w")
X2.write(str(x2))
X2.close()
Y2 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y2.txt","w")
Y2.write(str(y2))
Y2.close()
X3 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/X3.txt","w")
X3.write(str(x3))
X3.close()
Y3 = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/Y3.txt","w")
Y3.write(str(y3))
Y3.close()
else :
print("Opción ingresada no válida")
up = 1
pit = open("C:/Users/Neftali/Desktop/memoria parte final/Constantes/Movimiento/pit.txt","w")
pit .write(str(up))
pit .close()
|
2aa48627e78ecc771c821d4c514dd8109673ab84
|
Stopless-K/crawl
|
/multiprocess.py
| 1,131 | 3.53125 | 4 |
from multiprocessing import Process, Queue
class MP(object):
def __init__(self, thread_num, func, args):
self.thread_num = thread_num
self.func = func
self.result = []
self.args = args
self.t = [Process(target=self.f, args=(i, self.thread_num, len(self.args))) for i in range(self.thread_num)]
self.q = Queue()
def f(self, first, step, total):
print('[OPR] #%d work start..' % first)
result = []
for i in range(first, total, step):
res = self.func(**self.args[i])
if not res:
print('[SUC] #%d work done..' % first)
break
result.append(res)
print('[OPR] #%d sending data..' % first)
self.q.put(result)
print('[SUC] #%d all done..' % first)
def work(self):
for each in self.t:
each.start()
for i in range(self.thread_num):
self.result += self.q.get()
for each in self.t:
each.join()
print('[SUC] all process finished..')
print('[SUC] all work done..')
|
b86ad7e0b2772997271a2f02c8a496169f1a6ee5
|
Aasthaengg/IBMdataset
|
/Python_codes/p03455/s882125839.py
| 160 | 3.71875 | 4 |
a,b = map(int,input().split())
def answer(a: int ,b: int) ->int:
if a * b % 2 == 0:
return "Even"
else:
return "Odd"
print(answer(a,b))
|
ab976a0a26b5a870d3c878cf8071caec667af9b6
|
Nwagner22/motif-mark
|
/Scripts/fa_converter.py
| 1,023 | 3.859375 | 4 |
#!/usr/bin/env python
# coding: utf-8
import argparse
def get_args():
parser = argparse.ArgumentParser(description="A program to convert FASTA files into two lines per record")
parser.add_argument("-i", "--input", help="use to specify input file name", required=True, type = str)
parser.add_argument("-o", "--output", help="use to specify output file name", required=True, type = str)
return parser.parse_args()
args = get_args()
INPUT_FILE = args.input # assigning input file name as string to global varible
OUTPUT_FILE = args.output # assigning output file name as string to global varible
with open(OUTPUT_FILE, 'w') as outputFile:
with open(INPUT_FILE, 'r') as inputFile:
firstLine = inputFile.readline().strip()
outputFile.write(firstLine + "\n")
for line in inputFile:
line = line.strip()
if(line[0] == '>'):
outputFile.write("\n" + line + "\n")
else:
outputFile.write(line)
|
163e941f2372622f49716f5fa93f4384ac5d498a
|
ChaeSangJung/hankerrank_python
|
/Algorithms/easy/Implementation/desc_ord_Designer PDF Viewer.py
| 545 | 3.609375 | 4 |
https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
h = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7]
word = zaba
def designerPdfViewer(h, word):
n = len(word)
cnt = 0
result = 0
for i in range(n):
num = ord(word[i])-97
if(cnt <= h[num]):
cnt = h[num]
result = n*cnt
return result
ord
ord(c)는 문자의 유니코드 값을 돌려주는 함수이다.
※ ord 함수는 chr 함수와 반대이다.
>>> ord('a')
97
>>> ord('가')
44032
|
884a4361b5347470befc266ce78a8631fe897276
|
mabrenu/phyton_basico_2_2019
|
/Clase#2/Practica#2.py
| 614 | 3.859375 | 4 |
"""
Crear un código que calcule las soluciones de la ecuación cuadrática
de la fórmula aX2 + bx +c=0
"""
import math
#math.sqrt() raiz cuadrada
#elevado 2**2
a = float(input('Favor ingresar a'))
b = float(input(''
'Favor ingresar b'))
c = float(input('Favor ingresar c'))
discriminante =b**2 - 4*a*c
if discriminante <0:
raiz=math.sqrt(-discriminante) * complex(0,1) #meter el número complejo i
else:
raiz=math.sqrt(discriminante)
resultado = (-b+raiz)/ (2*a)
resultado2 = (-b-raiz)/ (2*a)
print('El resultado de las ecuaciones son:',resultado, resultado2)
|
1688c232317306f717174d6e86de704d06c783b6
|
MichaelOgunsanmi/dailyCodingChallenge
|
/July 2019/26th July 2019/pascalsTriangle.py
| 1,562 | 3.8125 | 4 |
# Source: https://leetcode.com/problems/pascals-triangle/
# Level: Easy
# Date: 26th July 2019
# Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
#
#
# In Pascal's triangle, each number is the sum of the two numbers directly above it.
#
# Example:
#
# Input: 5
# Output:
# [
# [1],
# [1,1],
# [1,2,1],
# [1,3,3,1],
# [1,4,6,4,1]
# ]
from typing import List
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
# method 1
if numRows <= 1:
return [[1]] * numRows
output = [[1]]
while numRows > 1:
numRows -= 1
new = [1]
index = 1
while index < len(output[len(output) - 1]):
new.append(output[len(output) - 1][index] + output[len(output) - 1][index - 1])
index += 1
new.append(1)
output.append(new)
return output
# #method 2
# if numRows <= 1:
# return [[1]] * numRows
#
# main = []
# count = 1
# while count <= numRows:
# output = []
#
# i = count
# j = 1
# while i >= j:
# output.append(self.genRec(i, j, main))
# j += 1
#
# main.append(output)
# count += 1
#
# return main
#
#
# def genRec(self, i, j, main):
# if j == 1 or i == j:
# return 1
#
# return main[i-2][j-2] + main[i-2][j-1]
|
a09a32b58183fefabf768b533821fff9bbec01ad
|
cuibinghua84/pydata
|
/python_crash_course/04-操作列表/4.4-使用列表的一部分.py
| 693 | 3.640625 | 4 |
# -*- coding: utf-8 -*-
"""
@author: 东风
@file: 4.4-使用列表的一部分.py
@time: 2019/10/30 10:59
"""
# 4.4.1 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
# 4.4.2 遍历切片
print("Here are the first three players on my team: ")
for player in players[:3]:
print(player.title())
# 4.4.3 复制列表
print()
my_foods = ['pizza', 'falafel', 'carrotcake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are: ")
print(my_foods)
print("\nMy friend's favorite foods are: ")
print(friend_foods)
|
512f01a1261eb1c96485dc9c80c20b5d387c5e0a
|
kabitakumari20/list_logical
|
/how_to_find_in_list_int_float_str.py
| 358 | 3.78125 | 4 |
list=[2, 3.5,4.3,"hello world", 5, 4.3]
empty1=[]
empty2=[]
empty3=[]
i = 0
while i<len(list):
if list[i]==str(list[i]):
empty1.append(list[i])
elif list[i]==int(list[i]):
empty2.append(list[i])
elif list[i]==float(list[i]):
empty3.append(list[i])
else:
print(i)
i+=1
print(empty1)
print(empty2)
print(empty3)
|
b4e1aafb5cdca7f371a81cbb5493c10149321262
|
jslee6091/python_basic
|
/exercise/list_dictionary.py
| 495 | 3.53125 | 4 |
one = {'id': '1', 'name': 'hong kildong', 'email': '[email protected]', 'hp_num': '010-2343-9870'}
two = {'id': '2', 'name': 'lee soonsin', 'email': '[email protected]', 'hp_num': '010-3333-5555'}
three = {'id': '3', 'name': 'jang youngsil', 'email': '[email protected]', 'hp_num': '010-7777-1234'}
four = {'id': '4', 'name': 'king sejong', 'email': '[email protected]', 'hp_num': '010-4567-0987'}
total_list = [one, two, three, four]
for idx, dicts in enumerate(total_list):
print(idx+1, '번째 keys : ', dicts.keys(), ', values : ', dicts.values())
|
aa29598e424e9f41efeb88b4e61f9203942047a3
|
qmnguyenw/python_py4e
|
/geeksforgeeks/python/python_all/131_14.py
| 2,630 | 4.3125 | 4 |
Python | Get random dictionary pair
Sometimes, while working with dictionaries, we can have a situation in which
we need to find a random pair from dictionary. This type of problem can come
in games such as lotteries etc. Let’s discuss certain ways in which this task
can be performed.
**Method #1 : Usingrandom.choice() + list() + items()**
The combination of above methods can be used to perform this task. The
choice function performs the task of random value selection and list
method is used to convert the pairs accessed using items() into a list over
which choice function can work.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Get random dictionary pair in dictionary
# Using random.choice() + list() + items()
import random
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Get random dictionary pair in dictionary
# Using random.choice() + list() + items()
res = key, val = random.choice(list(test_dict.items()))
# printing result
print("The random pair is : " + str(res))
---
__
__
**Output :**
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
**Method #2 : Usingpopitem()**
This function is generally used to remove an item from dictionary and remove
it. The logic why this function can be used to perform this task is that as
ordering in dictionary is random, any pair can be popped hence random.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Get random dictionary pair in dictionary
# Using popitem()
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Get random dictionary pair in dictionary
# Using popitem()
res = test_dict.popitem()
# printing result
print("The random pair is : " + str(res))
---
__
__
**Output :**
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
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
|
f542299f92dbb4025b54b1c6003d9e54d0856ab3
|
Gairaud/Karatsuba
|
/src/NumTypes/NaturalNumber.py
| 9,913 | 3.96875 | 4 |
"""
Authors:
1) Kevin Flores G
2) Philippe Gairaud
Num Class
"""
from AbstractNumber import *
class Num(AbstractNum):
def __init__(self, digits = 0, b = Default_base, is_comple = False):
"""
Initialize a Num object with digits, base and complement
The Num with digits = 345 has the next form
--> [0,...,0,3,4,5]
"""
self.base = b
self.is_complement = is_comple
self.creationBase(digits,self.base)
numberList = [int(x) for x in str(digits)]
if len(numberList) == 0: numberList = [0]
self.numDigits = len(numberList)
if self.numDigits > MAX_SIZE:
raise Exception("Overflow")
else:
self.num = [0] * MAX_SIZE
for y in range(MAX_SIZE - self.numDigits, MAX_SIZE):
self.num[y] = numberList.pop(0)
def __str__(self):
x = ""
if self.is_complement : y = ~self
else: y = self
for i in range(len(y)):
x += str(y[i])
if self.is_complement: return f"({type(self).__name__})(base = {self.base})(-{x})"
return f"({type(self).__name__})(base = {self.base})({x})"
def __repr__(self):
return self.__str__()
def __len__(self):
return self.numDigits
def __getitem__(self, key):
if key > self.numDigits:
raise Exception("Overflow")
return self.num[MAX_SIZE - (len(self) - key)]
def __add__(self, other):
"""Returns the sum of two Nums
-Example
+ [1,2,3]
[1,2,3]
_________
[2,4,6]
"""
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
else:
# Verifying sums -> "~Num + Num", "Num + ~Num", "~Num + ~Num"
if self.is_complement and other.is_complement: return ~(~self + ~other)
elif self.is_complement and not other.is_complement:
if ~self > other: return ~(~other - self)
elif not self.is_complement and other.is_complement:
if self < ~other: return ~(~self - other)
#-------------------------------------------------------------
result, result_num = [], 0
llevo = False
for x in range(MAX_SIZE-1, -1, -1):
sum = self.num[x] + other.num[x]
if llevo: sum += 1
if sum >= self.base:
result.append(sum - self.base)
llevo = True
else:
result.append(sum)
llevo = False
for i in range(len(result)): result_num += result[i]*10**i
return type(self)(result_num, self.base)
def __mul__(self, other):
"""Returns the multiplication of two Nums
-Example
* [1,3]
[4,5]
_________
+ [6,5]
[5,2]
_________
[5,8,5]
"""
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
else:
# Verifying multiplications -> "~Num * Num", "Num * ~Num", "~Num * ~Num"
if self.is_complement and not other.is_complement: return ~(~self*other)
elif not self.is_complement and other.is_complement: return ~(self*~other)
elif self.is_complement and other.is_complement: return ~self*~other
#-----------------------------------------------------------------------
result = []
llevo = False
total = type(self)(digits = 0, b = self.base)
zeros = [0]
c, carry = 0, 0
for x in range(MAX_SIZE-1, -1+c, -1):
result = []
result.extend(zeros*c)
for y in range (MAX_SIZE-1, -1+c, -1):
sum = self.num[y] * other.num[x]
if llevo: sum += carry
if sum >= self.base:
result.append(sum - (self.base * (sum//self.base)))
llevo = True
carry = sum // self.base
else:
result.append(sum)
llevo = False
c +=1
result = result[::-1]
total = total + type(self)("".join(str(i) for i in result), self.base)
return total
def __floordiv__(self, other):
"""Returns the division of two Nums
-Example
[1,0] // [2]
______________
[1,0] | [2]
|______
-[2]*[5] | [5]
_________|
[0] |
_________
return [5]
"""
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
else:
# Verifying divisions -> "~Num // Num", "Num // ~Num", "~Num // ~Num"
if self.is_complement and not other.is_complement: return ~(~self//other)
elif not self.is_complement and other.is_complement: return ~(self//~other)
elif self.is_complement and other.is_complement: return ~self//~other
#---------------------------------------------------------------------
result, num, enter = [0], '', False
for x in range(MAX_SIZE - self.numDigits, MAX_SIZE):
num += str(self.num[x])
aux_1 = type(self)(digits = num, b = self.base)
if aux_1 >= other:
if not enter: result = []
enter = True
while (x < MAX_SIZE):
multiply = 1
aux_2 = type(other)(digits = multiply, b = other.base) * other
while aux_2 <= aux_1:
multiply += 1
aux_2 = type(self)(digits = multiply, b = self.base) * other
result.append(multiply)
aux_3 = type(self)("".join(str(i) for i in result), self.base) * other
while aux_2 > aux_1 or aux_3 > self:
multiply -= 1
result[len(result)-1] = multiply
aux_2 = type(self)(digits = multiply, b = self.base) * other
aux_3 = type(self)("".join(str(i) for i in result), self.base) * other
x += 1
if x < MAX_SIZE :
aux_1 = aux_1 - aux_2
aux_1 = aux_1 << 1
aux_1 = aux_1 + type(self)(digits=self.num[x], b = self.base)
if enter: break
return type(self)("".join(str(i) for i in result), self.base)
def __sub__(self, other):
"""Returns the substarction of two Nums
-Example -Complement example
- [1,2,3] -[1,2,3]
[2,3] [2,0,0]
_________ _________
[1,0,0] [..,9,2,3]
"""
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
else:
result = self + ~other
if self < other: result.is_complement = True
return result
def __pow__(self, other):
"""
Raise a Num to the powe of other Num
-Example
[1,2]**[2]
"""
result = self
exponent = int("".join(str(i) for i in other.num))
for i in range (exponent-1):
result = result*self
return result
def multbyOneDigit(self,digit):
"""
Multiply a Num by a int
-Example
2* [2,3]
"""
result = self
for i in range (digit-1):
result = result+self
return result
def __invert__(self):
x = [ self.base - 1 - x for x in self.num ]
result = type(self)("".join(str(i) for i in x), self.base) + type(self)(1, self.base)
result.is_complement = False if self.is_complement else True
return result
def __eq__(self, other):
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
for x in range(MAX_SIZE-1,-1,-1):
if self.num[x] != other.num[x] : return False
return True
def __lt__(self, other):
Num.operateValidator(self,other)
if self.base != other.base:
raise Exception("Different Bases")
if (other.is_complement and not self.is_complement) or self == other: return False
if self.is_complement and not other.is_complement: return True
else:
if len(self) > len(other): return False
elif len(self) == len(other):
k, y = 0,0
for x in range(self.numDigits -1, -1, -1):
k += self.num[MAX_SIZE - x - 1]*10**x
y += other.num[MAX_SIZE - x - 1]*10**x
if k > y: return False
return True
def __lshift__(self, position):
# using multiplication
# return self * type(self)(digits = 10**position, b =self.base)
# To avoid calling the multiplication
self.num.extend([0]*position)
for x in range(position) : self.num.pop(0)
self.numDigits += position
return self
def __rshift__(self, position):
# using division
# return self // type(self)(digits = 10**position, b = self.base)
# To avoid calling the division
for x in range(position):
self.num.pop()
self.num.insert(0,0)
self.numDigits -= position
return self
|
f1d9196d8bc8a885df59f888ac2b88de84bf46be
|
EderBraz/URI---Solutions
|
/Py/1078.py
| 170 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 06:33:19 2018
@author: eder_
"""
n = int(input())
for i in range(1, 11):
print("{} x {} = {}".format(i,n, (i*n)))
|
2861be3571f35e7276c459f4de0b82a2924ac7ca
|
vinkrish/ml-jupyter-notebook
|
/playground.py
| 8,097 | 3.59375 | 4 |
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
print(a)
[1, 66.25, 333, 333, 1234.5]
del a[2:4]
print(a)
[1, 66.25, 1234.5]
del a[:]
print(a)
a = []
del a
# dictionary
result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
print(basket_items['apples'])
print(list(basket_items.items())
# [('apples', 4), ('oranges', 19), ('kites', 3), ('sandwiches', 8)]
for key in basket_items:
print(basket_items[key])
for custom_name in basket_items.values():
print(custom_name)
for key, value in basket_items.items():
print(key, value)
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for fruit, fruit_count in basket_items.items():
if fruit in fruits:
result += fruit_count
print(result)
# tuple
tuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
if "apple" in tuple:
print("Yes, 'apple' is in the fruits tuple")
# set
set = {"apple", "banana", "cherry"} or thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
for x in thisset:
print(x)
print("banana" in thisset)
set.add("orange")
# loop
headlines = ["Local Bear Eaten by Man",
"Legislature Announces New Laws",
"Peasant Discovers Violence Inherent in System",
"Cat Rescues Fireman Stuck in Tree",
"Brave Knight Runs Away",
"Papperbok Review: Totally Triffic"]
news_ticker = ""
for headline in headlines:
news_ticker += headline + " "
if len(news_ticker) >= 140:
news_ticker = news_ticker[:140]
break
print(news_ticker)
# zip
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points = []
for label, x, y, z in zip(labels, x_coord, y_coord, z_coord):
points.append("{}: {}, {}, {}".format(label, x, y, z))
for point in points:
print(point)
# zip list to dictionary
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
cast = dict(zip(cast_names, cast_heights))
print(cast)
# unzip
cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
names, heights = zip(*cast)
print(names)
print(heights)
# transpose matrix
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose)
# enumerate
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
for i, cas in enumerate(cast):
cast[i] = "{} {}".format(cas, str(heights[i]))
print(cast)
# list comprehension
multiples_3 = [num*3 for num in range(1,21)]
print(multiples_3)
[x*2 for x in range(9) if x%2==0]
a = [1, 0, 0, 2, 3, 0]
a_out = [1 if i == 0 else i for i in a]
print(a_out)
a = [1, 0, 0, 2, 3, 0]
a_out = all(i == 0 for i in a)
print(a_out)
# dictionary comprehension
users = [
(0, "user", "password"),
(1, "username", "1234"),
]
username_mapping = {user[1]: user for user in users}
userid_mapping = {user[0]: user for user in users}
print(username_mapping)
print(username_mapping["user"]) # (0, "user", "password")
# -- Collecting values --
head, *tail = [1, 2, 3, 4, 5]
print(head) # 1
print(tail) # [2, 3, 4, 5]
*head, tail = [1, 2, 3, 4, 5]
print(head) # [1, 2, 3, 4]
print(tail) # 5
# map
def addition(n):
return n+n
numbers = [1,2,3,4]
map(addition, numbers)
# filter with list comprehension
scores = {
"Rick Sanchez": 70,
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
passed = [name for name, score in scores.items() if score>=65]
print(passed)
# lambda
add = lambda x, y: x + y
print(add(1,2)) # (lambda x, y: x + y)(1,2)
def multiply(num):
return num * 3
sequence = [1,2,3]
res = [(lambda x: x * 3)(x) for x in sequence]
res = [multiply(num) for num in sequence] # use this for complicated list comprehension
res = list(map(multiply, sequence))
res = list(map(lambda x: x * 3, sequence))
# lambda with map
numbers = [
[34, 63, 88, 71, 29],
[90, 78, 51, 27, 45],
[63, 37, 85, 46, 22],
[51, 22, 34, 11, 18]
]
def mean(num_list):
return sum(num_list) / len(num_list)
averages = list(map(lambda num_list: sum(num_list) / len(num_list), numbers))
print(averages)
# lambda with filter
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]
def is_short(name):
return len(name) < 10
short_cities = list(filter(lambda name: len(name) < 10, cities))
print(short_cities)
# generator function
lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]
def my_enumerate(iterable, start=0):
index = start
for value in iterable:
yield index, value
index += 1
for i, lesson in my_enumerate(lessons, 1):
print("Lesson {}: {}".format(i, lesson))
# generator chunker solution 1
def chunker(iterable, size):
chunk_size = size
chunk_pointer = 0;
while chunk_pointer < len(iterable):
yield iterable[chunk_pointer: chunk_pointer + chunk_size]
chunk_pointer += chunk_size
for chunk in chunker(range(25), 4):
print(list(chunk))
# generator chunker solution 2
def chunker(iterable, size):
"""Yield successive chunks from iterable of length size."""
for i in range(0, len(iterable), size):
yield iterable[i:i + size]
for chunk in chunker(range(25), 4):
print(list(chunk))
# generator sequence
sq_list = [x**2 for x in range(10)] # this produces a list of squares
sq_iterator = (x**2 for x in range(10)) # this produces an iterator of squares
# unpacking
# The asterisk takes all the arguments and packs them into a tuple.
def multiply(*args):
print(args)
total = 1
for arg in args:
total = total * arg
return total
print(multiply(3, 5))
print(multiply(-1))
def add(x, y):
return x + y
# The asterisk can be used to unpack sequences into arguments too!
nums = [3, 5]
print(add(*nums)) # instead of add(nums[0], nums[1])
# Double asterisk packs or unpacks keyword arguments
def named(**kwargs):
print(kwargs) # {'name': 'Bob', 'age': 25}
named(name="Bob", age=25)
# or
details = {"name": "Bob", "age": 25}
named(**details)
def named(name, age):
print(name, age)
# Unpack dict into arguments. This is OK, but slightly more confusing. Good when working with variables though.
named(**{"name": "Bob", "age": 25})
# or
details = {"name": "Bob", "age": 25}
named(**details)
# file open
with open('C:/Users/Vinay/Python Workspace/Nanodegree/README.md', 'r') as f:
content = f.read()
print(content)
# looping in file
camelot_lines = []
with open("camelot.txt") as f:
for line in f:
camelot_lines.append(line.strip())
print(camelot_lines)
# csv
import unicodecsv
def read_csv(filename):
with open(filename, 'rb') as f:
reader = unicodecsv.DictReader(f)
return list(reader)
daily_engagement = read_csv('data/daily_engagement.csv')
def get_unique_students(data):
unique_students = set()
for data_point in data:
unique_students.add(data_point['account_key'])
return unique_students
unique_engagement_students = get_unique_student(daily_engagement)
len(unique_engagement_students)
# csv with Pandas
import pandas as pd
daily_engagement = pd.read_csv('data/daily_engagement.csv')
len(daily_engagement['account_key'].unique())
# Filling missing values
import pandas as pd
s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f'])
s = s1 + s2
print(s).dropna()
s_fill = s1.sum(s2, fill_value=0)
print(s_fill)
# If we want to extract column A from dataframe
df['A']
# more coloumns
df[['B', 'D']]
# Turn pandas DataFrames into NumPy arrays
numpy.array(df)
# To display image
%pylab inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('ml_map.png')
imgplot = plt.imshow(img)
plt.show()
|
3ba0aa112b821180c995c6bcf12db3ad01541700
|
prat31/Programming
|
/Python/justlearningman.py
| 628 | 4.125 | 4 |
import random
print('Hello there! Please enter your name : ', end=' ')
name = input()
print('Hello '+name+'. I have chosen a number for you between 1 and 10, try to guess it in 5 tries')
ans=random.randint(1, 10)
for i in range(5):
print('Enter your guess : ', end=' ')
guess=int(input())
if guess<ans :
print('Your guess is too low.')
elif guess>ans :
print('Your guess is too high.')
else :
break
if guess == ans :
print('Congratulations! You have guessed the correct number ' +str(ans))
else :
print('Sorry, your guesse are over. The answer is : '+str(ans))
|
935879bd5a1cf55648723394aa198ad31c5acc30
|
103328242/ICTPRG-Python
|
/pythonprograms/testagain.py
| 381 | 4.0625 | 4 |
while True:
menu = int(input('''
Hello, please select from the following options:
1. add new order
2. list orders
3. exit
'''))
if menu == 1:
name = input('What is your name?')
burger = input('How many burgers?')
fries = input('How many fries?')
coke = input('How many cokes?')
if menu == 2:
print('hello')
|
056b131040dd1bd99e279fa573ef0b1aa39bd5a2
|
elazafran/ejercicios-python
|
/Ficheros/ejercicio8.py
| 430 | 3.78125 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
8.Imprime por pantalla la longitud de la primera línea
del fichero datos
'''
def crearFichero():
nombreFichero = input("Introduzca nombre de fichero: ")
p = open(nombreFichero, "a")
p.write("Hola esto es un mensaje")
print(p)
p.close()
def leerFichero():
p = open("javi.txt", "r")
for i in p:
print(len(i))
break
leerFichero()
|
ca3a8226e005cf4ee6de8d74c391a22467599b53
|
Bryson14/Numerical_Methods
|
/src/assn2/driver.py
| 923 | 3.6875 | 4 |
from Algorithms import get_algorithm, parachutist
import sympy as sym
def valid_input():
user_input = -1
print("Enter a % error approximation to stop at: ")
while 100 > user_input < 0:
try:
user_input = float(input('-->:\t'))
except ValueError:
valid_input()
return user_input
if __name__ == "__main__":
x = sym.symbols('x')
eq1 = x*x*x*x*x - 10*x*x*x*x + 46*x*x*x - 90*x*x + 85*x - 31
eq2 = -3*x**3 + 20*x**2 - 20*x - 12
eq3 = parachutist(9.81, 36, 15, 10, x)
eq4 = 0.5*x**3 - 4*x**2 + 8*x - 1
eq5 = -3*x**3 + 20*x**2 - 20*x - 12
eqns = {
'1': eq1,
'2': eq2,
'3': eq3,
'4': eq4,
'5': eq5,
}
user_input = '?'
while user_input not in eqns:
for i in eqns:
print('|eqn', i , ': ', eqns[i], " | ")
print('Enter a number between 1 - 5 for the equation to solve')
user_input = input('-->\t')
func = get_algorithm()
print('Root =', func(eqns[user_input], x, valid_input()))
|
31b7d1e407eb179ddfdc9685c5733a4c3d3c0dca
|
chivitc1/pygamedemo
|
/pygame_demos/ball_moving.py
| 1,118 | 3.71875 | 4 |
import pygame, sys
pygame.init()
ball_file = 'images/intro_ball.gif'
size = width, height = 640, 480
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size, pygame.RESIZABLE, 32) #create a graphical window
ball = pygame.image.load(ball_file) #load our ball image
ball_rect = ball.get_rect()
pygame.display.set_caption("Hello")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT :
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
ball_rect = ball_rect.move(speed) # move the ball
if ball_rect.left < 0 or ball_rect.right > width:
speed[0] = -speed[0]
if ball_rect.top < 0 or ball_rect.bottom > height:
speed[1] = -speed[1]
screen.fill(black) # erase the screen by filling it with a black RGB color
screen.blit(ball, ball_rect) # copying pixel colors from one image to another
pygame.display.flip() # makes everything we have drawn on the screen Surface become visible, Pygame manages the display with a double buffer
pygame.time.wait(10)
|
22cc17837c3af5c9d9132cfbef5a368a34dbee5d
|
WishingLai/Python-crawler
|
/code/LinkedList.py
| 1,744 | 3.796875 | 4 |
import numpy as np
# Node declared
class Node(object):
def __init__(self, d, n=None):
self.data = d
self.next_node = n
def get_next(self):
return self.next_node
def set_next(self,n):
self.next_node =n
def get_data(self):
return self.data
def set_data(self,d):
self.data =d
class LinkedList(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size (self):
return self.size
def add(self, d):
new_node = Node (d, self.root)
self.root = new_node
self.size +=1
#def addtail(self, d)
def remove (self, d):
this_node = self.root
prev_node = None
while this_node:
if this_node.get_data() == d:
if prev_node:
prev_node.set_next(this_node.get_next())
else:
self.root = this_node
self.size -=1
return True
else:
prev_node = this_node
this_node = this_node.get_next()
return False # Data not found
def find(self,d):
this_node = self.root
while this_node:
if this_node.get_data() == d:
return d
else:
this_node = this_node.get_next()
return None
def show(self):
this_node = self.root
while this_node:
print(this_node.get_data())
this_node = this_node.get_next()
myList = LinkedList()
myList.add(5)
myList.add(8)
myList.add(12)
myList.show()
#myList.remove(8)
#print(myList.remove(12))
#print(myList.find(5))
#zeros = np.zeros((9,2))
#print(zeros)
|
ab232dfbf6421df6c495e8a0a084fcf72097a4e8
|
jehyn923/personal_projects
|
/Coding Test/Python/Programmers_전화번호 목록_New풀이.py
| 1,056 | 3.65625 | 4 |
#효율성 바꾸기
#배운점, 문자열을 sort하면 길이로 sorting 안됨
#문자열 key=len으로 문자열 길이대로 정렬 가능함
#내가 참고한 그 페이지는 문제가 있는 것이다.
#합쳐도 괜찮을 듯
def solution(phone_book):
answer = True
phone_dic = dict()
phone_book.sort(key=len)
for i in range(len(phone_book)-1):
try:
phone_dic[len(phone_book[i])][phone_book[i]] = 1
except:
phone_dic[len(phone_book[i])]=dict()
phone_dic[len(phone_book[i])][phone_book[i]] = 1
for k in phone_dic:
if k < len(phone_book[i+1]):
#기존의 문제풀이에서 list 자료구조를 dict로 만들어 O(N)에서 O(1)로 바꿈
if phone_dic[k].get(phone_book[i+1][:k]):
return False
return answer
print(solution(["119", "97674223", "1195524421"]))
print(solution(["123","456","789"]))
print(solution(["12","123","1235","567","88"]))
|
5da9e7f7af511be6bce338e98e0ea5072a765715
|
JKChang2015/Python
|
/w3resource/rex/Q022.py
| 200 | 3.828125 | 4 |
# -*- coding: UTF-8 -*-
# Q022
# Created by JKChang
# Tue, 29/08/2017, 13:31
# Tag:
# Description: 22. Write a Python program to find the occurrence and position of the substrings within a string.
|
b0e6395c8003e074294643c62e5c729fdf7377fb
|
AlexeyAG44/python_coursera
|
/week_3/5_ rounding_rus_rul.py
| 611 | 3.5625 | 4 |
# По российский правилам числа округляются до ближайшего целого числа,
# а если дробная часть числа равна 0.5,
# то число округляется вверх. Дано неотрицательное число x,
# округлите его по этим правилам.
# Обратите внимание, что функция round не годится для этой задачи!
import math
n = float(input())
n1 = n // 1
f_p = (n - n1) * 10
if f_p >= 5:
print(math.ceil(n))
else:
print(math.floor(n))
|
f634cdff20496f491625560b402654bc6536e30e
|
HumanKing991/Python_practice_problems
|
/Find a string.py
| 357 | 4.1875 | 4 |
def count_substring(string, sub_string):
return sum(1 for i in range(len(string))
if string.startswith(sub_string,i))
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
'''
Sample Input
ABCDCDC
CDC
Sample Output
2'''
|
e3ec7ebf73589c29d89178e97da960b158c88c23
|
aparajita2508/learning-python
|
/script/Exe28.py
| 574 | 4.34375 | 4 |
"""1. Solve each equality test:
3 != 4 is True
True and not ("testing" != "test" or "Python" =="Python")
"testing" != "test" is True
True and not (True or "Python" == "Python")
"Python" == "Python"
True and not (True or True)
Find each and/or in parentheses ():
(True or True) is True True and not (True)
Find each not and invert it
not (True) is False: True and False
Find any remaining and/or and solve them
True and False is False"""
print 3 != 4 and not ("testing" != "test" or "Python" == "Python")
print "test" and "test"
print "False" and "1"
print "True" and "1"
|
ee142c0fc689ebcac103e03de3c9ca33054df547
|
BBorisov95/python_fund_homeworks
|
/07. Water Overflow.py
| 192 | 3.796875 | 4 |
lines = int(input())
tank = 255
water = 0
for i in range(lines):
flow = int(input())
if water + flow > tank:
print('Insufficient capacity!')
else:
water += flow
print(water)
|
1aeadfcf717d5e5476da70fa59ee580c1f30c8d0
|
slayer-qin/Python-Crash-Course
|
/3-4~7 list.py
| 892 | 4.09375 | 4 |
from random import randint
MAXGUESTS = 3
guests = []
print("Now, you are going to have a party, Please input the names of you guests")
for i in range(MAXGUESTS):
name = input("Guest NO.%d>>> " % (i+1))
guests.append(name)
num = randint(1, MAXGUESTS)
print("Oh! %s can not come,so you need to invite another guest." % guests[num-1])
name = input("Name of new guest>>> ")
guests[num-1] = name
print("You just got a bigger table, you can invite three more guests.")
for i in range(MAXGUESTS):
name = input("Guest NO.%d>>> " % (MAXGUESTS+i+1))
guests.insert(0, name)
print("Sorry! You table will not be here in time. So you can only invite two guest!")
for i in range(4):
print("Sorry! %s, I'm regret to tell you that I can't invite you to join the party." % guests.pop())
for guest in guests:
print(guest + ", please have fun here.")
guests.clear()
print(guests)
|
6240effee00e0b0d5b54289b5d2258973c322a0a
|
nisharai26/pythonPractice
|
/ifOrEx.py
| 148 | 4.0625 | 4 |
def check_Day(day):
if day == "Saturday" or "Sunday":
print("Its weekend")
else:
print("Working Day!")
check_Day("Tuesday")
|
1fbff15401b15315a87965b21a6b03dff098dabe
|
kperkins411/Python_tutorials
|
/exceptions.py
| 380 | 3.65625 | 4 |
def divide(a,b):
try:
return a/b
except ZeroDivisionError as e:
raise ValueError('0 divisor') from e
try:
result = divide(1,0)
except ValueError as e:
print('ValueError:' + e.args[0])
else:
print('%.3f' %result)
try:
result = divide(1,2)
except ValueError as e:
print('ValueError:' + e.args[0])
else:
print('Result=%.3f' %result)
|
55dcfa86bef1f7a7e46c87d1676b8a563623ebb0
|
KC-Scout/PCC_CH_15_10_TIY
|
/die_visual.py
| 486 | 3.734375 | 4 |
from die import Die
import matplotlib.pyplot as plt
# Create a D6
die = Die()
# Make some rolls and store it in a list
results = []
for roll in range(10):
result = die.roll()
results.append(result)
print(results)
labels = []
frequencies = []
for value in range(1, die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
labels.append(str(value))
height = die.num_sides
plt.bar(labels, frequencies)
plt.xticks(labels)
plt.show()
|
f8a5defea16f5dbd217a19f2891e8c4c84f63bfd
|
DimaLevchenko/intro_python
|
/homework_7/task_1.py
| 548 | 4.375 | 4 |
# Написать функцию которая вернет строку введенную пользователем.
# Обернуть функцию в декоратор чтобы функция вместо строки целиком вернула список слов.
user_string = input('Enter string - ')
def decorate(func):
def str_to_list(*args, **kwargs):
return func(*args, **kwargs).split()
return str_to_list
@decorate
def show_the_string(string):
return string
print(show_the_string(user_string))
|
8bd76d6880b05766f4140d9f4fe6984bfbe8dd50
|
Kutbeddin/Negative-Meaning
|
/negative_meanıng.py
| 371 | 4.46875 | 4 |
#Define a function to take a word and return negative meaning.
Given a word, return a new word where "not " has been added to the front. However, if the word already begins with "not", return the string unchanged.
def not_string(word):
x=word.split()
if "değil" in x:
print(word)
else :
print("{} değil ".format(word))
not_string("kelime değil")
|
d48019ecb9df8e3bdbb1731693d0b028fa0b78b1
|
rhywbeth/HackerRank-Solutions-Python3
|
/HackerRank-Problem Solving-Between Two Sets
| 1,141 | 3.578125 | 4 |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getTotalX' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
# 2. INTEGER_ARRAY b
#
def getTotalX(a, b):
# Write your code here
m, n = len(a),len(b)
factors = []
final = []
for i in range(max(a),min(b)+1):
for ai in a:
if ((i%ai)==0):
factors.append(i)
factors = list(set([i for i in factors if factors.count(i)>(m-1)]))
print(factors)
for f in factors:
for bi in b:
if ((bi%f)==0):
final.append(f)
return(len(set([i for i in final if final.count(i)>(n-1)])))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
arr = list(map(int, input().rstrip().split()))
brr = list(map(int, input().rstrip().split()))
total = getTotalX(arr, brr)
fptr.write(str(total) + '\n')
fptr.close()
|
be90e448ff04a625dcec359bc4234209be83d77f
|
JerryCui/examples
|
/constant.py
| 562 | 4.15625 | 4 |
'''Illustrate a global constant being used inside functions.'''
PI = 3.14159265358979 # global constant -- only place the value of PI is set
def circle_area(radius):
"""circle area caculate"""
return PI*radius*radius # use value of global constant PI
def circle_circumference(radius):
"""circumference caculate"""
return 2*PI*radius # use value of global constant PI
def main():
"""constant"""
print('circle area with radius 5:', circle_area(5))
print('circumference with radius 5:', circle_circumference(5))
main()
|
83ce871b0e4eca81716f58b1b16b00a5489832f3
|
ian-everett/python-helper
|
/WordReveal/main.py
| 2,762 | 4.03125 | 4 |
'''
Reveals a word and the person can stop and guess it
'''
import random
import time
# alphabet
ALPHABET = ('abcdefghijklmnopqrstuvwxyz')
def get_random_word(words):
'''
returns a random word from a list of words or blank ''
if no words in list of words
'''
length = len(words)
if length > 1:
index = random.randint(0, length - 1)
return words[index].rstrip('\n')
return ''
def print_current_guess(word, current):
'''
Outputs the current word guess
'''
print("Guess Word: ", end='')
for letter in word:
if letter.lower() in current:
print(letter, end='')
elif letter == ' ':
print(' ', end='')
else:
print('%c' % '-', end='')
print('')
def show_drawn_letters(current):
'''
Ouputs the currently drawn letters
'''
# Display all the letters which have been
# drawn in alphabetical order
for item in sorted(current):
print("%c " % item, end='')
def get_current_state(word, current):
'''
Outputs the current game state and returns
wether the word has been gussed with True or
False if not yet.
'''
print_current_guess(word, current)
print('')
# Show all letters that have been picked thus far
if current != set():
show_drawn_letters(current)
print('')
# Check to see if we have matched all letters if
# so we we return True to stop cureent game.
if set(word.lower()).issubset(current):
return True
return False
def main():
'''
main entry point
'''
# Open given file for reading, list of words should
# be a word each line with a \n at the end
with open('./states.txt', 'r') as file:
words = file.readlines()
# Return a random word from that list of words
word = get_random_word(words)
# Preset alphabet set, we will slowly remove each
# letter as we randlonly select it.
# Chosen starts blank as it holds the letters drawn
alphabet = set(ALPHABET)
chosen = set()
# We have maxium 26 letters so get each of them randomly
for n_goes in range(len(ALPHABET)):
# Get next letter and remove it from list so we can't choose it again
letter = random.choice(tuple(alphabet))
alphabet.remove(letter)
# Add the next letter to the chosen set
chosen.add(letter)
# Show current state of game and if we have a match quit loop
if get_current_state(word, chosen):
print('Got a match took %d goes.' % (n_goes + 1))
break
time.sleep(2.0)
if __name__ == "__main__":
main()
|
57ae09f0670a4630330d0fd6b1d2cc9fb0cd47e7
|
zatserkl/learn
|
/python/decorator_recursive.py
| 1,846 | 3.8125 | 4 |
""" See details about functools.wraps and caching with lru_cache at Answer #3
https://stackoverflow.com/questions/43432956/how-a-decorator-works-when-the-argument-is-recursive-function
"""
import time
from functools import wraps
from functools import lru_cache
# def rclock(func):
# top = True
# @wraps(func)
# def clocked(*args):
# nonlocal top
# if top:
# top = False
# t0 = time.perf_counter()
# result = func(*args)
# elapsed = time.perf_counter() - t0
# name = func.__name__
# arg_str = ', '.join(repr(arg) for arg in args)
# print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result))
# else:
# result = func(*args)
# top = True
# return result
# return clocked
def clock(func):
@wraps(func) # provide doc of decorated function, not the decorator one
def clocked(*args):
''' Clocking decoration wrapper '''
t0 = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - t0
name = func.__name__
arg_str = ', '.join(repr(arg) for arg in args)
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result))
return result
return clocked
@lru_cache(None)
@clock
def factorial(n):
''' Recursive factorial '''
return 1 if n < 2 else n * factorial(n-1)
# Here because of use @wraps(func) in decorator-function 'clock'
# the factorial.__doc__ will return doc of decorated function 'factorial',
# not the doc of the decorator-function 'clock'
print("factorial.__name__, factorial.__doc__:")
print(factorial.__name__, factorial.__doc__)
print()
for n in range(3, 7):
print('%d! = %d' % (n, factorial(n)))
for n in range(3, 7):
print('%d! = %d' % (n, factorial(n)))
|
bf1ec59770fb854ea72467d9c0f27039b5ebdb64
|
nrollet/qpaieexport
|
/qpaieexport/mysqlconv.py
| 3,817 | 3.5625 | 4 |
import mysql.connector
def create_table_sqlgen(table_name, column_list):
"""
Generate the SQL syntax to create the table
table_name: table name string
column_list: tables values (each row is a list)
"""
columns = []
for item in column_list:
if item[1] == type(1) or item[1] == "integer": # integer
datatype = "INT"
elif item[1] == type(True) or item[1] == "boolean": # boolean
datatype = "INT"
elif item[1] == type(1.0) or item[1] == "float": # float
datatype = "FLOAT"
elif item[1] == type("A") or item[1] == "text": # text
datatype = "VARCHAR(100)"
elif item[1] == type(datetime.now()) or item[1] == "date":
datatype = "DATETIME"
else:
datatype = "VARCHAR(100)"
columns.append(item[0] + " " + datatype)
return "CREATE TABLE {} ({})".format(table_name, ", ".join(columns))
def fill_table_sqlgen(table_name, column_list):
columns = []
for item in column_list:
columns.append(item)
sql = """
INSERT INTO {} (
{})
VALUES (
{}
)
""".format(
table_name, ", ".join(columns), ", ".join(["%s"] * len(column_list))
)
return sql
class connect_msyql(object):
def __init__(self, params):
self.params = params
def connect(self):
try:
self.conn = mysql.connector.connect(**self.params)
self.cursor = self.conn.cursor()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return False
if self.conn.is_connected():
print("MySQL connected")
def disconnect(self):
print("I'm out")
self.conn.commit()
self.conn.close()
def create_table(self, table_name, column_list):
self.cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
sql = create_table_sqlgen(table_name, column_list)
print(sql)
self.cursor.execute(sql)
def fill_table(self, table_name, column_list, row_list):
sql = fill_table_sqlgen(table_name, column_list)
print(sql)
self.cursor.executemany(sql, row_list)
if __name__ == "__main__":
from datetime import datetime
params = {
"host": "10.0.0.117",
"user": "root",
"passwd": "rangit9562",
"database": "paie_odenval",
}
db = connect_msyql(params)
db.connect()
# data = (
# ("matricule", type(1), None, 10, 10, 0, True),
# ("nom", type("A"), None, 50, 50, 0, True),
# ("zedate", type(datetime(2000, 8, 2)), None, 53, 53, 0, True)
# )
# db.create_table("salaries", data)
# fill_data = [
# ["45", "CONDE FOUSSENI", datetime(2018, 7, 2, 0, 0)],
# ["46", "CHENIN SAMUEL", datetime(2018, 7, 9, 0, 0)],
# ["47", "BUFFARD LISE", datetime(2018, 8, 27, 0, 0)],
# ]
# # print(fill_table_sqlgen("salaries", ["matricule", "nom", "zedate"]))
# db.fill_table("salaries", ["matricule", "nom", "zedate"], fill_data)
from qpaietools import QueryPaie
o = QueryPaie()
o.connect("C:/Users/nicolas/Documents/Pydio/Sources/odenval_qpaie.mdb")
# db = connect_msyql()
data, columns = o.employes()
db.create_table("Employes", columns)
heads = [x[0] for x in columns]
print(heads)
db.fill_table("Employes", heads, data)
data, columns = o.bulletins()
db.create_table("Bulletins", columns)
heads = [x[0] for x in columns]
print(heads)
db.fill_table("Bulletins", heads, data)
db.disconnect()
# db.fill_table("Employes", columns, data)
# data, columns = o.bulletins()
# db.create_table("Bulletins", columns)
# db.fill_table("Bulletins", columns, data)
# o.disconnect()
|
213f16e1e6a944ec1b53a8adc353a6c504fb0a5b
|
Sivagnanam99/Python-Assessments-
|
/10.Split.py
| 160 | 3.84375 | 4 |
str1="Hai , Hello, I am Siva , Welcome To The World"
print("\n")
print("Original String... \n",str1)
print("After Spliting With Comma",str1.split(","))
|
a4ce761af96eae634c34c6aa4bb39f2a1512fdc1
|
joysjohney/Luminar_Python
|
/PythonPrograms/regularExpression/vriablecheck.py
| 398 | 3.703125 | 4 |
# Rule (20/08/2020)
# ====
# 1) First character is an alphabet and it should be with in a-k
# 2) Second number should be a digit and it must e divisible by 3 =>(3,6,9)
# 3) And the any number of character
from re import *
rule='[a-k][369][a-zA-Z0-9]*'
varname=input("Enter variable name : ")
matcher=fullmatch(rule,varname)
if(matcher !=None):
print("Valid")
else:
print("Invalid!")
|
19782a04a378f9e589c20b3ec1775e3c1cb1bd15
|
abelthf/algoritmos-y-estructura-de-datos
|
/Estructura_secuencial/ejercicio8.py
| 144 | 3.765625 | 4 |
# coding: utf-8
r = input("Ingrese radio de la base: ")
h = input("Ingrese altura: ")
vc = 3.14159 * r * r * h
print "El volúmen es: %s" % vc
|
7fb764326c073c50daf8fa6a17c536cfd9415766
|
ak-sergeev/Learn-Algorithms-and-data-structures
|
/Data-structures/Queue/Queue-Linked-List.py
| 2,931 | 3.984375 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.next_node = None
self.prev_node = None
def __str__(self):
return self.value
class Queue:
"""
Очередь на базе двунаправленного связного списка.
"""
def __init__(self, size):
self.top = Node(None)
self.first = None
self.size = size
self.length = 0
def enqueue(self, value):
"""
Добавляет элемент со значением value в очередь.
"""
new_node = Node(value)
# Вызываем исключение, если очередь заполнена.
if self.length == self.size:
raise OverflowError
# Вставялем элемент в начало.
# Связываем последний элемент в очереди с новым.
if self.top.next_node:
self.top.next_node.prev_node = new_node
# Связываем новый элемент со следующим (последним) и с top.
new_node.next_node = self.top.next_node
new_node.prev_node = self.top
# Связываем top с новым.
self.top.next_node = new_node
# Устанавливаем first, если это первая вставка.
if not self.first:
self.first = new_node
# Увеличиваем длину
self.length += 1
def dequeue(self):
"""
Извлекает элемент из очереди.
"""
# Если элемент есть, то получаем его значение.
if self.first:
value = self.first.value
# Смещаем указатель.
self.first = self.first.prev_node
# Удаляем последний элемент.
self.first.next_node = None
# Проверяем, не ссылается ли first на top.
# Если ссылается, то сбрасываем first.
if self.first.value is None:
self.first = None
# Уменьшаем длину
self.length -= 1
return value
return None
def count(self):
"""
Возвращает количество элементов в очереди.
"""
return self.length
def peek(self):
"""
Возвращает значение первого элемента очереди без его извлечения.
"""
if self.first:
return self.first.value
return None
def clear(self):
"""
Очищает очередь.
"""
self.first = None
self.top.next_node = None
self.length = 0
|
ebc9bf4f8fcf8e1f8e1a0c115875d20b7414d15f
|
Anastasia1807/111
|
/hw6/Ex5.py
| 204 | 4 | 4 |
list = [1, 2, 3, 4, 5, 6 , 8, 12, 15, 21, 25]
number = int (input('Enter number: '))
for i in range(len(list)):
if list[i]%number==0:
print(list[i])
else:
print("No multiples found")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.