blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
65268b86a2ed7ddfbf5f59db5e5b86577d3b9363 | jeffkwiat/minesweeper | /app.py | 2,961 | 4.125 | 4 | import random
class Minesweeper(object):
"""
Implementing a simple Minesweeper board.
"""
def __init__(self, width, height, number_of_mines):
self.width = width
self.height = height
self.number_of_mines = number_of_mines
self.board = self.generate_board()
self.flag_cells()
def get_coordinates(self):
""" Get coordinates for this board. """
coordinates = []
for x in range(self.height):
for y in range(self.width):
coordinates.append((x, y))
return coordinates
def generate_board(self):
""" Build out the initial board. """
# Generate the initial board with 0s.
board = [[0 for x in range(self.width)] for y in range(self.height)]
# Set up the mines and surrounding counts.
mines = random.sample(self.get_coordinates(), self.number_of_mines)
for x, y in mines:
board[x][y] = '*'
return board
def __repr__(self):
""" Print the object representation to the screen. """
return "<Minesweeper width:%s height:%s number_of_mines:%s>" % \
(self.width, self.height, self.number_of_mines)
def __str__(self):
""" Print the board to the console. """
result = ""
for row in self.board:
result += ''.join([str(x) for x in row]) + '\n'
return result
def count_mines(self):
""" Count the number of mines currently on the board. """
count = 0
for row in self.board:
for cell in row:
if cell == '*':
count += 1
return count
def _is_on_board(self, coordinate):
""" Return True if the coordinate is on the board. Else, False. """
x, y = coordinate
if (x >= 0 and x < len(self.board)) and (y >= 0 and y < len(self.board)):
return True
return False
def get_surrounding_cells(self, coord):
""" Return the surrounding (x, y) coords. """
surrounding = []
for x in range(coord[0] - 1, coord[0] + 2):
for y in range(coord[1] - 1, coord[1] + 2):
# Skip the current cell
if (x, y) == coord:
continue
try:
# If the surrounding coord is on the board, add it.
if self._is_on_board((x, y)):
surrounding.append((x, y))
except:
print('trying to access: %s, %s' % (x, y))
print(self)
return surrounding
def flag_cells(self):
""" Setup counts for all surrounding cells. """
for coordinate in self.get_coordinates():
for cell in self.get_surrounding_cells(coordinate):
if self.board[cell[0]][cell[1]] == '*':
continue
self.board[cell[0]][cell[1]] += 1 | true |
53e9e59370cad6cfcf69c3219783070f35df4f81 | GauravR31/Solutions | /Classes/Flower_shop.py | 1,883 | 4.15625 | 4 | class Flower(object):
"""docstring for ClassName"""
def __init__(self, f_type, rate, quantity):
self.type = f_type
self.rate = rate
self.quantity = quantity
class Bouquet(object):
"""docstring for ClassName"""
def __init__(self, name):
self.name = name
self.flowers = []
def add_flower(self):
f_type = raw_input("Enter the flower type(Rose, Lily, Lotus, Daisy) ")
if f_type == "Rose":
f_quantity = input("Enter the flower quantity ")
f = Flower(f_type, 10, f_quantity)
elif f_type == "Lily":
f_quantity = input("Enter the flower quantity ")
f = Flower(f_type, 8, f_quantity)
elif f_type == "Lotus":
f_quantity = input("Enter the flower quantity ")
f = Flower(f_type, 7, f_quantity)
elif f_type == "Daisy":
f_quantity = input("Enter the flower quantity ")
f = Flower(f_type, 9, f_quantity)
else:
print("Invalid flower type")
self.flowers.append(f)
def update_flower(self):
flag = 0
f_type = raw_input("Enter the flower type to remove ")
for i in range(0, len(self.flowers)):
if self.flowers[i].type == f_type:
f_quantity = input("Enter the new quantity(0 for none) ")
flag = 1
self.flowers[i].quantity = f_quantity
if flag == 0:
print("Flower not found")
def bouquet_details(self):
cost = 0
for f in self.flowers:
print("Type : {}\nRate : {}\nQuantity : {}\n".format(f.type, f.rate, f.quantity))
cost += (f.rate * f.quantity)
print("Total cost of the bouquet is {}".format(cost))
def main():
b = Bouquet("Bouquet1")
while True:
print("1. Add flower\n2. Update or remove flower\n3. Bouquet details\n4. Exit")
ch = input("Enter your choice ")
if ch == 1:
b.add_flower()
elif ch == 2:
b.update_flower()
elif ch == 3:
b.bouquet_details()
elif ch == 4:
break
else:
print("Invalid choice.")
if __name__ == '__main__':
main() | true |
ce97aff7408d5808d33756c8bb72e2910bbe77a4 | ngrq123/learn-python-3-the-hard-way | /pythonhardway/ex30.py | 732 | 4.34375 | 4 | # Initialise people to 30
people = 30
# Initialise cars to 40
cars = 40
# Initialise buses to 15
buses = 15
# If there are more cars then people
if cars > people:
print("We should take the cars.")
# Else if there are less cars then people
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
# If there are more buses than cars
if buses > cars:
print("That's too many buses.")
# Else if there are less buses than cars
elif buses < cars:
print("Maybe we could take the buses.")
else:
print("We still can't decide.")
# If there are more people than buses
if people > buses:
print("Alright, let's just take the buses.")
else:
print("Fine, let's stay home then.")
| true |
d61c6db3c3889e24794719d0d8e7c9a4c6a3732e | dkahuna/basicPython | /Projects/calcProgram.py | 241 | 4.5 | 4 | # Calculating the area of a circle
radius = input('Enter the radius of your circle (m): ')
area = 3.142 * int(radius)**2 # int() function is used to convert the user's input from string to integer
print('The area of your circle is:', area) | true |
5dbf3b63d6bb744d4a02aba9f41acd9ad64372c2 | dkahuna/basicPython | /FCC/ex_09/ex_09.py | 714 | 4.15625 | 4 | fname = input('Enter file name: ')
if len(fname) < 1 : fname = 'clown.txt'
hand = open(fname)
di = dict() #making an empty dictionary
for line in hand :
line = line.rstrip() #this line strips the white space on the right side per line of the file
words = line.split() #this line splits the text file into an array
# print(words)
for wds in words:
# idiom: retrieve/create/update counter
di[wds] = di.get(wds,0) + 1
# print(di)
#now to find the most common word
largest = -1
theWord = None
for k,v in di.items() :
if v > largest :
largest = v
theWord = k #capture and remember the largest 'key'
print('The most common word used is:', theWord, largest) | true |
f164802d0ebb45593969d7736755758c3c84b03d | Siddharth46/first | /classp.py | 703 | 4.3125 | 4 | class Movie:
'''this code is property of siddharth dixit'''
def __init__(self,movie, actor, femaleactor, ratings):
self.movie=movie
self.actor=actor
self.femaleactor=femaleactor
self.ratings=ratings
def info(self):
print("Move name {}".format(self.movie))
print("Male lead actor is {}".format(self.actor))
print("Female lead actor is {}".format(self.femaleactor))
print("Ratings of the movie is {}".format(self.ratings))
movies=[Movie("Raees", "Shahrukh khan", "Mahira khan", "7"),
Movie("Bajrangi Bhaijaan", "Salman khan", "Kareena Kapoor", "8"),
Movie("Airlift", "Akshay Kumar", "Nimrat Kaur", "7.5")]
for movie in movies:
movie.info()
print()
| false |
ecfe7da8cee6b57ab65108992a3c333f2e0dc283 | RustingSword/adventofcode | /2020/01/sol2.py | 315 | 4.125 | 4 | #!/usr/bin/env python3
def find_triple(nums, target=2020):
for first in nums:
for second in nums:
if (third := target - first - second) in nums:
return first * second * third
if __name__ == "__main__":
nums = set(map(int, open("input")))
print(find_triple(nums))
| true |
2abc3eda58ecfee7de0adc69143acad90c55bc4e | 981377660LMT/algorithm-study | /9_排序和搜索/经典题/自定义比较函数/数组组成最大数-拼接字典序最大.py | 920 | 4.25 | 4 | # 剑指 Offer 45. 把数组排成最小的数
from functools import cmp_to_key
from typing import List
# !给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
# 数组组成最大数(拼接最大序)
# cmp_to_key 将compare函数转换成key
def mergeSort(s1: str, s2: str) -> int:
"""拼接两个字符串,字典序最小"""
return -1 if s1 + s2 < s2 + s1 else 1
def toMax(nums: List[int]) -> str:
"""拼接最大序"""
arr = list(map(str, nums))
arr = sorted(arr, key=cmp_to_key(lambda s1, s2: mergeSort(s1, s2)), reverse=True)
return "".join(arr)
def toMin(nums: List[int]) -> str:
"""拼接最小序"""
arr = list(map(str, nums))
arr = sorted(arr, key=cmp_to_key(lambda s1, s2: mergeSort(s1, s2)))
return "".join(arr)
print(toMax([10, 1, 2])) # 2110
print(toMax([3, 30, 34, 5, 9])) # 9534330
| false |
accebf20a8b38eb27330f7ec76e02e9f5d7debae | 981377660LMT/algorithm-study | /19_数学/计算几何/圆形/最小圆覆盖.py | 2,550 | 4.125 | 4 | # 你需要用最少的原材料给花园安装一个 圆形 的栅栏,
# 使花园中所有的树都在被 围在栅栏内部(在栅栏边界上的树也算在内)。
# https://leetcode.cn/problems/erect-the-fence-ii/
# !最小圆覆盖 Welzl 算法(随机增量法)
# n<=3000
import random
from typing import List, Tuple, Union
EPS = 1e-8
def calCircle2(
x1: int, y1: int, x2: int, y2: int, x3: int, y3: int
) -> Union[Tuple[None, None, None], Tuple[float, float, float]]:
"""三点圆公式,求圆的圆心坐标(x,y)和半径r"""
a, b, c, d = x1 - x2, y1 - y2, x1 - x3, y1 - y3
a1 = (x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2) / 2
a2 = (x1 * x1 - x3 * x3 + y1 * y1 - y3 * y3) / 2
theta = b * c - a * d
if theta == 0:
return None, None, None
x0 = (b * a2 - d * a1) / theta
y0 = (c * a1 - a * a2) / theta
return x0, y0, ((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)) ** 0.5
def isCover(x1: int, y1: int, rx: float, ry: float, r: float) -> bool:
dist = ((x1 - rx) * (x1 - rx) + (y1 - ry) * (y1 - ry)) ** 0.5
return dist <= r or abs(dist - r) < EPS
def minimumEnclosingCircle(points: List[Tuple[int, int]]) -> List[float]:
"""请用一个长度为 3 的数组 [x,y,r] 来返回最小圆的圆心坐标和半径
答案与正确答案的误差不超过 1e-5
"""
random.shuffle(points)
n = len(points)
x0, y0 = points[0]
r = 0
for i in range(1, n):
x1, y1 = points[i]
if isCover(x1, y1, x0, y0, r):
continue
x0, y0, r = x1, y1, 0
for j in range(i):
x2, y2 = points[j]
if isCover(x2, y2, x0, y0, r):
continue
x0, y0, r = (
(x1 + x2) / 2,
(y1 + y2) / 2,
(((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5) / 2,
)
for k in range(j):
x3, y3 = points[k]
if isCover(x3, y3, x0, y0, r):
continue
candX, candY, candR = calCircle2(x1, y1, x2, y2, x3, y3)
if candX is not None and candY is not None and candR is not None:
x0, y0, r = candX, candY, candR
return [x0, y0, r]
if __name__ == "__main__":
# https://atcoder.jp/contests/abc151/tasks/abc151_f
n = int(input())
points = [tuple(map(int, input().split())) for _ in range(n)]
x, y, r = minimumEnclosingCircle(points)
print(r)
| false |
d7ab97a0b0acf6e66d0c184d3588f9673c525bfa | 981377660LMT/algorithm-study | /前端笔记/thirtysecondsofcode/python/python的typings/5_联合类型.py | 645 | 4.125 | 4 | from typing import Union
# 联合类型之联合类型会被展平
Union[Union[int, str], float] == Union[int, str, float]
# 在 3.10 版更改: 联合类型现在可以写成 X | Y
# StrOrInt = str | int
# Alternative syntax for unions requires Python 3.10 or newer
# 通常需要使用 isinstance ()检查来首先将联合类型缩小到非联合类型
def f(x: Union[int, str]) -> None:
x + 1 # Error: str + int is not valid
if isinstance(x, int):
# Here type of x is int.
x + 1 # OK
else:
# Here type of x is str.
x + 'a' # OK
f(1) # OK
f('x') # OK
f(1.1) # Error
| false |
37281e1e27482ad1847549fda1d6f38bcc5b8e5a | 981377660LMT/algorithm-study | /19_数学/模拟退火与爬山法/三分法求凸函数极值.py | 1,725 | 4.15625 | 4 | """
三分法求单峰函数的极值点.
更快的版本见: FibonacciSearch
"""
from typing import Callable
INF = int(4e18)
def minimize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最小值"""
res = INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 = left + diff
mid2 = right - diff
if fun(mid1) > fun(mid2):
left = mid1
else:
right = mid2
while left <= right:
cand = fun(left)
res = cand if cand < res else res
left += 1
return res
def maximize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最大值"""
res = -INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 = left + diff
mid2 = right - diff
if fun(mid1) < fun(mid2):
left = mid1
else:
right = mid2
while left <= right:
cand = fun(left)
res = cand if cand > res else res
left += 1
return res
def optimize(fun: Callable[[int], int], left: int, right: int, *, min: bool) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最值"""
return minimize(fun, left, right) if min else maximize(fun, left, right)
if __name__ == "__main__":
assert optimize(lambda x: x**2 + 2 * x, -1, 400, min=True) == -1
assert optimize(lambda x: 0, -1, 400, min=True) == 0
assert optimize(lambda x: x**2, -1, 40, min=False) == 1600
assert optimize(lambda x: x**2, -50, 40, min=False) == 2500
| false |
ae0ee943b022a73f8864057c6c12916615c5ca9d | hasanalpzengin/HummingDrone | /Question_1/fibonacci.py | 384 | 4.1875 | 4 | import sys
#recursive
def fibonacci(num):
if num < 2:
return num
else:
return fibonacci(num-1)+fibonacci(num-2)
if __name__ == "__main__":
#first parameter
try:
num = int(sys.argv[1])
output = fibonacci(num)
print("Fibonacci {} = {}".format(num ,output))
except:
print("Parameter should be integer value") | false |
ade6f9461899f60320e1ee0ceb3356dc1b78861b | jianyuecc/python_learn | /python函数的定义/Lambda形式/make_incrementor.py | 921 | 4.15625 | 4 | 出于实际需要,有几种通常在函数式编程语言例如 Lisp 中出现的功能加入到了
Python。通过 lambda 关键字,可以创建短小的匿名函数。这里有一个函数返回它
的两个参数的和: lambda a, b: a+b 。 Lambda 形式可以用于任何需要的函数对
象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数
定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从外部作用域引
用变量:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
上面的示例使用 lambda 表达式返回一个函数。另一个用途是将一个小函数作为参
数传递:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
| false |
7f5f33b40f1a8d3acc72c889bef1accf9432abb7 | rubenvdham/Project-Euler | /euler009/__main__.py | 833 | 4.4375 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def find_triplet_with_sum_of(number):
sum = number
number = int(number/2)
for a in range(1,number):
for b in range (a,number):
for c in range(b,number):
if (a**2 +b**2) == c**2:
if a+b+c == sum:
return a,b,c
def multiply(list):
answer = 1
for i in range (0,len(list)):
answer*=result[i]
return answer
if __name__ == '__main__':
result = find_triplet_with_sum_of(1000)
print("Triplet %s %s %s"%(result[0],result[1],result[2]))
print("product:%s"%(multiply(result)))
| true |
156ce2abce7f089a563208dd1947eb0276c00a20 | romeoalpharomeo/Python | /fundamentals/fundamentals/rock_paper_scissors.py | 1,670 | 4.5 | 4 | """
Build and application when both a user and computer can select either Rock, Paper or Scissors, determine the winner, and display the results
For reference:
Rock beats Scissors
Scissors beats Paper
Paper beats Rock
Part I
Compare user input agains computer choice and determine a winner
Part II
Compare user input agains computer choice and determine a winner. The winner will be the best 5 games, and end as soon at someone wins 3 games.
"""
player_win_count = 0
computer_win_count = 0
while player_win_count < 3 or computer_win_count < 3:
import random
computer_options = ['Rock', 'Paper', 'Scissors']
computer_choice = random.choice(computer_options)
player_choice = input('Rock, paper, scissors, shoot!: ')
if player_choice == computer_choice:
print("TIE!")
elif player_choice == "Rock":
if computer_choice == "Scissors":
print("Player wins!")
player_win_count += 1
else:
print("Player loses.")
computer_win_count += 1
elif player_choice == "Paper":
if computer_choice == "Rock":
print("Player wins!")
player_win_count += 1
else:
print("Player loses.")
computer_win_count += 1
elif player_choice == "Scissors":
if computer_choice == "Paper":
print("Player wins!")
player_win_count += 1
else:
print("Player loses.")
computer_win_count += 1
if player_win_count > computer_win_count:
print('Player won the game!')
else:
print('Computer won the game.') | true |
0e792822cb1faeda92a0c0fec8bb86901c40aa09 | anmolrajaroraa/CorePythonBatch | /largest-among-three.py | 1,385 | 4.46875 | 4 | # num1, num2, num3 = 12, 34, 45
# if (num1 > num2) and (num1 > num3):
# print("The largest between {0}, {1}, {2} is {0}".format(num1, num2, num3))
# elif (num2 > num1) and (num2 > num3):
# print("The largest between {0}, {1}, {2} is {1}".format(num1, num2, num3))
# else:
# print("The largest between {1}, {2}, {0} is {0}".format(num3, num1, num2))
num1, num2, num3 = 12, 34, 45
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest between {}, {}, {} is {}".format(num1, num2, num3, largest))
# num1, num2, num3 = input("1st: "), input("2nd: "), input("3rd: ")
# print(num1, num2, num3)
# numbers = input("Enter three numbers separated by a blank space: ")
# num1, num2, num3 = numbers.split()
# print("num1 is {}, num2 is {}, num3 is {}".format(num1, num2, num3))
'''
1. if-elif-else block
2. reduce repeating code as much as possible
3. 2 ways of printing strings using format()
- stating variables in order
print("The largest between {}, {}, {} is {}".format(num1, num2, num3, largest))
- stating indexes of variables between curly braces
print("The largest between {1}, {2}, {0} is {0}".format(num3, num1, num2))
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
nterms = 10
a = 0
b = 1
count = 2
while count < nterms:
code
0
1
1
2
3
5
8
13
21
34
'''
| true |
782019d56f35c65b24b5f26a682b0fb92ff7478b | davixcky/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 361 | 4.3125 | 4 | #!/usr/bin/python3
''' Add integer module '''
def add_integer(a, b=98):
''' Function that add to numbers '''
type_a, type_b = type(a), type(b)
if type_a != int and type_a != float:
raise TypeError('a must be an integer')
if type_b != int and type_b != float:
raise TypeError('b must be an integer')
return int(a) + int(b)
| false |
5a38d95fe9db58447d65605ddfef48559e6ae689 | angjerden/kattis | /pizza_crust/pizza_crust.py | 845 | 4.1875 | 4 | '''
George has bought a pizza. George loves cheese.
George thinks the pizza does not have enough cheese.
George gets angry.
George’s pizza is round,
and has a radius of R cm. The outermost C cm is crust,
and does not have cheese. What percent of George’s pizza has cheese?
Input
Each test case consists of a single line
with two space separated integers, R and C
.
Output
For each test case, output the percentage
of the pizza that has cheese.
Your answer must have an absolute or relative error of at most 10^6.
.
Limits
1≤C≤R≤100
'''
from sys import stdin
import math
line = stdin.readline()
line = line.split(' ')
r = int(line[0])
c = int(line[1])
r_cheese = r - c
area = math.pi * math.pow(r, 2)
area_cheese = math.pi * math.pow(r_cheese, 2)
percent_not_cheese = (area_cheese / area) * 100
print(percent_not_cheese)
| true |
14fc091ee12c9a6e841096e6e1e8f253863beeb3 | jeffbergcoutts/udacity-compsci | /lesson11.py | 1,373 | 4.53125 | 5 | '''
How to Manage Data
'''
# Quiz: Stooges
stooges = ['Moe', 'Larry', 'Curly']
# Quiz: Days in a Month
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
def how_many_days(month):
return days_in_month[month - 1]
print how_many_days(2)
print how_many_days(9)
# Quiz: Countries
countries = [['China','Beijing',1350],
['India','Delhi',1210],
['Romania','Bucharest',21],
['United States','Washington',307]]
print countries[1][1]
# Quiz: Relative Size
print countries[0][2]/countries[2][2]
# Quiz: Different Stooges
stooges = ['Moe','Larry','Curly']
stooges[2] = 'Shemp'
print stooges
# Yello Mutation
'''
Lists are mutatable. Changing the value of a list
effect any variable with that list. eg:
'''
p = ['H', 'E', 'L', 'L', 'O']
q = p
p[0] = 'Y'
print p, q
# known as aliasing
spy = [0,0,7]
agent = spy
print spy, agent
print agent[2]
spy[2] = agent[2] + 1
print agent[2]
'''
13: Quiz: Replace spy
'''
print "13: Quiz"
spy = [0,0,7]
def replace_spy(p):
p[2] = p[2] + 1
replace_spy(spy)
print spy
# p[2] = p[2] + 1 <-- this is a replacement statement, also changes spy
# a = a + 1 <-- this is an assignment statement, would not change spy if spy was "a"
print "17: Quiz"
p = [1,2]
q = [3,4]
p.append(q)
print p
q[1] = 5
print p
# this will change the list p as well because q is in p, we appened a reference to q
| false |
1e0e9f789c65d252092168bbf9d90f89092f0c17 | maryade/Personal-Learning-Python | /Udemy Python Practice programming Module 3.py | 918 | 4.46875 | 4 | # # Addition
# print(5+3)
#
# # Subtraction
# print(11-4)
#
# # multiplication
# print(22*5)
#
# # division
# print(6/3)
#
# # modulo
# print(9%5)
#
# # exponents
# print(2^4)
# print(6**2)
#
# # return integer instead of floating number
# print(11//5)
# print(451//5)
# assignment operation
x = 18
# print(x)
# to increase by 2 use
# x+=2 #x + 2 = 20
# print(x)
# to decrease by 2 use
# x-=2 #x - 2 = 16
# print(x)
# to multiply by 2 use
# x*=2 #x * 2 = 36
# print(x)
# to divide by 2 use
# x/=2 #x % 2 = 9
# print(x)
# combining the operators
# print( 3 + 4 -13 * (2+20) + 6 /2)
# boolean
# print(5==4)
# print(10==10)
# print(10!=4)
# print(4!=4)
# print(66>12)
# print(78>=77)
# print(True and True)
# print(1==1 and 2==4)
# print(1==1 or 2==3)
# print(True and False)
# print(True or False)
# x=10
# y = 10
# print(x is y)
# print(x is not y)
y = [1,4,6,7]
x = 1
print(x in y)
print(x not in y) | true |
d064c635389f767606f56ae246d695d7b1af6ecf | kevindsteeleii/HackerRank_InterviewPreparationKit | /00_WarmUpChallenges/jumpingOnClouds_2019_02_20.py | 1,712 | 4.28125 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.
For each game, Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided. For example, c = [0,1,0,0,0,1,0] indexed from 0...6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 1 and 5. She could follow the following two paths: 0->2->4->6 or 0->2->3->4->6. he first path takes 3 jumps while the second takes 4.
Function Description
Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.
jumpingOnClouds has the following parameter(s):
c: an array of binary integers
Input Format
The first line contains an integer (n),the total number of clouds. The second line contains (n) space-separated binary integers describing clouds ( c[i] ) where 0 <= i <= n.
Constraints
* 2 <= n <= 100
* c[i] /in {0,1}
* c[0] = c[n-1] = 0
"""
def jumpingOnClouds(c):
i = 0
jumps = 0
while i < len(c)-1:
# print(jumps)
try:
if c[i+2] == 0 or c[i+1] == 0:
i = i + 2 if c[i+2] == 0 else i + 1
jumps += 1
except:
jumps += 1
break
return jumps
if __name__ == '__main__':
print(jumpingOnClouds([0,1,0,1,0])) | true |
0915df88be07251462464e301bec6535ac91626d | tarjantamas/Virtual-Controller-CNN | /src/common/util.py | 1,590 | 4.5625 | 5 | def getArgumentParameterMap(argv):
'''
Maps arguments to their list of parameters.
:param argv: list of arguments from the command line
:return: a map which maps argument names to their parameters.
If the program is run in the following way:
python main.py --capturedata param1 param2 param3 --othercommand param1 param2
the return value will be:
{
'--capturedata': ['param1', 'param2', 'param3']
'--othercomand': ['param1', 'param2']
}
'''
argumentParameterMap = {}
i = 0
while i < len(argv):
arg = argv[i]
j = i + 1
if '--' in arg:
params = []
while j < len(argv) and '--' not in argv[j]:
params.append(argv[j])
j += 1
argumentParameterMap[arg] = params
i = j
return argumentParameterMap
def callWithParameters(function, params):
function(*params)
def isHigherThan(s1, s2):
'''
If s1 and s2 are base N string representations of numbers then this function behaves as a comparator.
:input s1: string to be compared
:input s2: string to be compared
:return: Returns True if s1's length is higher than s2's without scanning each character.
Returns False if s1's length is lower than s2's without scanning each character.
In other cases it compares the characters at each position of s1 and s2 until a position 'i' comes up
where s1[i] > s2[i] at which point it returns True. Returns False if no such position comes up.
'''
if len(s1) > len(s2):
return True
if len(s1) < len(s2):
return False
for i, j in zip(s1, s2):
if i > j:
return True
return False | true |
0cb1eb4245d4d82b15e885ab5b7374b0c419e6e0 | epc0037/URI-CS | /CSC110/Python Lists/HW3/problem1.py | 878 | 4.40625 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 3 - Problem 1
# This program will generate a list containing
# all the odd numbers between 100 and 500 except 227 and 355.
# create an empty number list & set the values we wish to remove from the list
numList = []
a = 227
b = 355
# for loop that goes from 100 to 500 (501 because it doesn't include the last value)
# if i in the range 100 to 500 has a remainder when divided by 2, i is added to the list
# the last statements are nested if statements which remove the values 227 and 355 from our list
for i in range(100,501):
if i % 2 != 0:
numList = numList + [i]
if a in numList:
numList.remove(a)
if b in numList:
numList.remove(b)
# final output that prints the list to the user, except 227 and 355
print(numList)
| true |
2869a4a804531ff82b8957a250082d0eaecfdd07 | epc0037/URI-CS | /CSC110/Python Functions/HW4/stocks.py | 2,179 | 4.25 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 4 - Problem 1
# This program will get create two lists for stock names and prices,
# which will be entered by the user using a loop. I will utilize 3 functions:
# the main function, the searchStock function and the printStock function.
def main():
# Create two empty lists for stock names and prices
stockNames = []
stockPrices = []
# variable to control the loop
end = "continue"
while end != "done":
#Get the stock name and prices
name = str(input("Enter the stock name you wish to add to the list: "))
price = int(input("Enter the price of the stock you added to the list: "))
print("\n")
# Append the name and prices to the lists
stockNames.append(name)
stockPrices.append(price)
# Prompt the user to continue the loop
print("If you wish to stop adding stocks, enter 'done' ")
end = str(input("Type 'continue' to add more stocks: "))
print("\n")
# Prompt the user to find a stock with its corresponding price in the list using functions
s = str(input("Enter a stock name you wish to search for in order to see which stocks are higher: "))
p = searchStock(s, stockNames, stockPrices)
printStock(p, stockNames, stockPrices)
# Function that returns the price of the searched stock
# I found an issue here at first in my code. I had an if-else statement
# but I realized I did not need the else, rather to just pull out the return
# and keep the indent even with the for loop. This seemed to solve my issue with
# the loop because it would return -1 when I wanted it to return the price from
# the stockPrices list.
def searchStock(s, stockNames, stockPrices):
for i in range(len(stockNames)):
if stockNames[i] == s:
return stockPrices[i]
return -1
# Function that prints all the stocks above the value of the searched stock
def printStock(p, stockNames, stockPrices):
for i in range(len(stockPrices)):
if stockPrices[i] > p:
print(stockNames[i])
else:
print()
main()
| true |
1f97e7a5f66552f012f3c95e05152ac9f9747640 | epc0037/URI-CS | /CSC110/Python Basics/HW2/problem3.py | 404 | 4.375 | 4 | #Evan Carnevale
#CSC 110 - Survey of Computer Science
#Professor Albluwi
#Homework 2 - Problem 3
TOTAL_BUGS = 0
DAYS = 1
while DAYS <= 7:
print("Day", DAYS, ": Did you collect a lot of bugs today?")
today_bug = int(input("Enter the number of bugs collected today"))
TOTAL_BUGS += today_bug
DAYS +=1
print('\n')
print("The total number of bugs collected in the week:", TOTAL_BUGS, "bugs.")
| true |
4d2057482e6711b76d94eaeff48d52ae787ca22e | GGMagenta/exerciciosMundo123 | /ex067.py | 413 | 4.125 | 4 | # Pegue um número e mostre a tabuada ate o usuario digitar um número negativo
while True:
numero = int(input('Digite um número inteiro e \033[1;32mpositivo\033[m: '))
if numero < 0:
break
for i in range(1, 11):
print(f'{numero} X {i} = {numero * i}')
i += 1
print('='*20)
print('Você digitou um número \033[1;31mnegativo\033[m, o programa será encerrado.')
| false |
70b9f0cd268f24ad8317f72514c54cf8e11a5b36 | GGMagenta/exerciciosMundo123 | /ex037.py | 1,016 | 4.15625 | 4 | # Pegue um numero e pergunte para qual base deseja converter
# 1 - Binário 2 - Octal 3 - Hexadecimal
n = int(input('Digite o número que deseja converter: '))
opcao = int(input('Digite \033[31m1\033[m para converter para \033[31mbinário\033[m, \033[32m2\033[m'
'para \033[32moctal\033[m, e \033[33m3\033[m para \033[33mhexadecimal\033[m: '))
if opcao == 1:
print('O número \033[31m{}\033[m em binário é {}'.format(n, '{0:b}'.format(n)))
# print('O número \033[31m{}\033[m em binário é {}'.format(n, bin(n)[2:]))
elif opcao == 2:
print('O número \033[32m{}\033[m em octal é {}'.format(n, '{0:o}'.format(n)))
# print('O número \033[32m{}\033[m em octal é {}'.format(n, oct(n)[2:]))
elif opcao == 3:
print('O número \033[33m{}\033[m em hexadecimal é {}'.format(n, '{0:x}'.format(n).upper()))
# print('O número \033[33m{}\033[m em hexadecimal é {}'.format(n, hex(n)[2:].upper()))
else:
print('{} não é uma opção valida.'.format(opcao))
| false |
db0c5a43933e5f1a257eaca2e3003a3a3cd7a40d | Nathansbud/Wyzdom | /Students/Suraj/quiz.py | 513 | 4.125 | 4 | students = ["Jim", "John", "Jack", "Jacob", "Joseph"]
grades = []
for student in students:
passed = False
while not passed:
try:
grade = float(input(f"Input a quiz grade for {student} (0-100): "))
if not 0 <= grade <= 100: raise ValueError()
grades.append(grade)
passed = True
except ValueError:
print("Grade must be a number between 0-100")
print(f"Max: {max(grades)} - Min: {min(grades)} - Avg: {sum(grades) / len(grades)}")
| true |
49f9fe9f6f2e695223c8c73ed60d7dc01a41d0ff | rajdharmkar/Python2.7 | /sortwordsinalbetorder1.py | 527 | 4.53125 | 5 | my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()# here separator is a space between words
print words
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
my_str = input("Enter a string with words separated by semicolon: ")
words = my_str.split(';')# here separator is a semicolon between words
print words
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
| true |
17e86708d5b2a0476756c63ab8d0cd12a77eba92 | rajdharmkar/Python2.7 | /initmethd1.py | 1,676 | 4.625 | 5 | class Human:
# def __init__(self): pass # init method initializing instance variables
#
# def __str__(): pass # ??
#
# def __del__(self): pass # ??...these three def statements commented out using code>> comment with line comment..toggles
def __init__(self, name, age, gender): # self means object in the init method inline comment example
# type: (object, object, object) -> object
self.name = name # creating and assigning new variable
self.age = age
self.gender = gender
def speak_name(self): # a method defined here with a print statement to execute as well
print "my name is %s" % self.name
def speak(self, text):
# def speak(text):; without self, we get nameerror...speaks take exactly one argument given two given; gave one arg but self is implied so two counted as given
print text
def perform_math(self, operation, *args):
print "%s performed math and the result was %f" % (self.name, operation(*args))
def add(a, b):#this is an example of function not an object method and is callable everywhere
return a + b
rhea = Human('Rhea', 20, 'female')
bill = Human('William', '24',
'male') # creating new object 'bill' which is an instance of class Human with variables assignment as well
# getting saying bill is not defined
print bill.name
print bill.age
print bill.gender
bill.speak_name()
bill.speak("Love")
rhea.perform_math(add, 34,45)
# method speak_name belongs to object 'bill' here; a method call?
# method diff from function and it can be called only from the object and it bound to the class
| true |
53ebcd324577f722da9407c61ea2adf9dc66bed1 | rajdharmkar/Python2.7 | /math/fibo.py | 1,296 | 4.28125 | 4 |
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b, # comma in print statement acts like NOT newline , all numbers are printed in one line..a row of numbers
# without comma or anything everytime there is a new line; we get a column of numbers
a, b = b, a+ b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result
# Executing modules as scripts
# ----------------------------
#
# When you run a Python module with ::
#
# python fibo.py <arguments>
#
# the code in the module will be executed, just as if you imported it, but with
# the ``__name__`` set to ``"__main__"``. That means that by adding this code at
# the end of your module::
if __name__ == "__main__":
import sys
fib ( int ( sys.argv[ 1 ] ) )
# you can make the file usable as a script as well as an importable module,
# because the code that parses the command line only runs if the module is
# executed as the "main" file::
#
# $ python fibo.py 50
# 1 1 2 3 5 8 13 21 34
# If the module is imported, the code is not run::
#
# >>> import fibo
# >>> | true |
16c0d9db5c7237b6f7dace39bdaf2b949d0b070e | rajdharmkar/Python2.7 | /assertXpl2.py | 2,214 | 4.40625 | 4 | class B: # class declaration with keyword class, class object B created
# class object; instance object; function object; method object
x = 10 # this is a class attribute
def __init__(self, name): # this is a __init__ method, also called a constructor that initializes default values of instance
# attributes ; self refers to the instance object
self.name = name
'''B.x is a class attribute'''
@property # using property decorator...property is a special kind of class attribute?
def foo(self): # this is a declaration of instance method?
"""
B.x is a property
This is the getter method
"""
print self.x
#@bar.setter
def bar(self, value):
"""
This is the setter method
where we can check if it's not assigned a value < 0
"""
if value < 0:
raise ValueError("Must be >= 0")
self.x = value
b = B('harris')# creation or instantiation of class into a instance object with parentheses after classname like function call
print b.name # accessing and printing an instance attribute
print B.x # accessing and printing an class attribute
print b.x # accessing a class attribute from instance?
print B.__dict__ # prints dictionary of class attributes
#print B.__dict()
print b.__dict__# prints dictionary of instance attributes
#print(b.foo()); foo not callable?
print b.foo # no need for parentheses for b.foo prints self.x which is obj.x = 10 and None?
#print b.bar(); parentheses cant be empty and unfilled; takes 1 arg
print b.bar(100)# returning None yes and 100 assigned to self.x or obj.x or b.x so print b.x prints 100
print b.x
#b.bar(-1)# raises valueError
print b.bar(-1) # raises no valueError...print statement without parentheses
print (b.bar(-1))# raises valueError
#b.x = -1
# Traceback (most recent call last):
# File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/assertXpl2.py", line 22, in <module>
# b.x = -1
# File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/assertXpl2.py", line 19, in x
# raise ValueError("Must be >= 0")
# ValueError: Must be >= 0
| true |
b20e8e5fc85924d740d9c0ea38f22e43fecf3147 | rajdharmkar/Python2.7 | /continueeX.py | 486 | 4.34375 | 4 | for val in "string":
if val == "i":
continue
print(val),
print("The end")
#The continue statement is used to skip the rest of the code inside a loop for
#the current iteration only. Loop does not terminate but continues on with the
#next iteration.
#Syntax of Continue
#continue
#We continue with the loop, if the string is "i", not executing the rest of
#the block. Hence, we see in our output that all the letters except "i" gets
#printed.
| true |
13bcc351d18826e483b62b4a7eb9e94f85cdb0c6 | rajdharmkar/Python2.7 | /Exception handling/NameError3.py | 684 | 4.5 | 4 | s = raw_input('Enter a string:') # raw_input always returns a string whether 'foo'/foo/78/'78'
# n =int(raw_input(prompt))); this converts the input to an integer
n = input("Enter a number/'string':")# this takes only numbers and 'strings'; srings throw errors ..it also evaluates if any numeric expression is given
p = input('Enter any numeric expression:')# if you enter for example 3+7*6 on prompt, input returns 45
print s
print n
print p
print (type(s))
print (type(n))
print(type(n))
# getting NameError if in n we input a string without quotes /
# wont get ValueError in this script which is getting type right but its value wrong for integer type if we input float | true |
d3db4014449d6b02a3c6a99d7101ffc793e87048 | rajdharmkar/Python2.7 | /usinganyorendswith1.py | 583 | 4.4375 | 4 | #program to check if input string endswith ly, ed, ing or ers
needle = raw_input('Enter a string: ')
#if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'):
# print('Is valid')
#else:
# print('Invalid')
if needle in ('ly', 'ed', 'ing', 'ers'):#improper code
print('Is valid')
else:
print ('invalid')
if 'ers' in needle:#doesnot mean endswith
print('Is valid')
else:
print('Invalid')
if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]):
print('Is valid')
else:
print('Invalid') | true |
2be6e85839802e5365e65ee47d09f914d388f198 | rajdharmkar/Python2.7 | /methodoverloading1.py | 606 | 4.25 | 4 | class Human:
def sayHello(self, name=None):
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
# Create instance
obj = Human()
# Call the method
obj.sayHello()
# Call the method with a parameter
obj.sayHello('Rambo')
#obj.sayHello('Run', 'Lola');TypeError takes at most 2 args given 3 args
#obj.sayHello('Run', 'Lola', "Run"); TypeError takes at most 2 args given 4 args
'''Output:
Hello
Hello Rambo
To clarify method overloading, we can now call the method sayHello() in two ways:
obj.sayHello()
obj.sayHello('Rambo')'''
| true |
825180decbe595ad5ec6b84511f97661ae28a121 | NANGSENGKHAN/cp1404practicals | /prac02/exceptions_demo.py | 1,046 | 4.53125 | 5 | try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
print("Denominator cannot be zero")
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.")
"""1.When will a ValueError occur?
A ValueError occur when a built-in operation or function receives an argument that
has the right type but am inappropriate value, and the situation is not described by a more precise exception such as
IndexError.
2.When will a ZeroDivision occur?
ZeroDivision occur when attempting to divide a number by zero.
3.Could you change the code to avoid the possibility of a ZeroDivisionError?
If you could figure out the answer to question 3, then make this change now.
Changing the code to avoid ZeroDivisionError.
""" | true |
9ac5ec423256abc74722ccf876114310e87aad6b | emanchas/Python | /Python/exam1IST140_Ed Manchas.py | 1,160 | 4.21875 | 4 | print ('This program converts fahrenheit to celsius \n')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
while user_temp < 0:
print ('Error! Temperature must be greater than 0 degrees!')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
print ('')
print ('Fahrenheit \t Celsius')
for user_temp in range (0, user_temp+1, 5):
Cel = (5/9) * user_temp - 17.8
print (user_temp, '\t', '\t', format (Cel, '.2f'))
print ('')
answer = input ('Input new temperature...Y/N? \n')
while answer == 'Y' or answer == 'y':
user_temp = int(input('Please input a temperature in Fahrenheit:'))
while user_temp < 0:
print ('Error! Temperature must be greater than 0 degrees!')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
print ('')
print ('Fahrenheit \t Celsius')
for user_temp in range (0, user_temp+1, 5):
Cel = (5/9) * user_temp - 17.8
print (user_temp, '\t', '\t', format (Cel, '.2f'))
print ('')
answer = input ('Input new temperature...Y/N? \n')
print ('')
print ('Thank you for using this program ^_^')
| true |
ead5340377ca5cf9e4cae2c2ae1da8e9ac0a1ffb | arydwimarta/python3-dummie | /lat6.py | 372 | 4.28125 | 4 | course = 'Python for Beginners 123'
print (len(course)) #menghitung jumlah huruf
print (course.upper())
print (course.lower())
#print(course)
print (course.find('o')) #find string become index
#print (course.replace('for','untuk'))
print (course.replace('o', 'a'))
print ('Python' in course) #in operator
print (course.title())
print (course.count('for')) #menghitung kata | false |
782af31d67c20f4b3b7d03b4ad283df4baa296fb | hoklavat/beginner-python | /08_Tuple.py | 344 | 4.125 | 4 | #08- Tuple
tuple1 = ()
print(type(tuple1))
tuple1 = (9)
print(type(tuple1))
tuple1 = (1, 2, 3, 4, 5)
print(type(tuple1))
print(tuple1[1])
#tuple1[1] = 0 Error: unmutable elements
(a, b, c, d, e) = tuple1
print(a)
print(len(tuple1))
print(max(tuple1))
print(min(tuple1))
print(tuple1 + (1 ,2 ,3))
print(tuple1 * 2)
print(tuple1[3:5])
del tuple1 | false |
fb80c96b9ea3a455cc9e5fe3daac41c59e64672b | EQ4/amplify | /src/amplify/utils.py | 643 | 4.46875 | 4 | import re
def natural_sort(string):
'''
This function is meant to be used as a value for the key-argument in
sorting functions like sorted().
It makes sure that strings like '2 foo' gets sorted before '11 foo', by
treating the digits as the value they represent.
'''
# Split the string into a list of text and digits, preserving the relative
# order of the digits.
components = re.split(r'(\d+)', string)
# If a part consists of just digits, convert it into an integer. Otherwise
# we'll just keep the part as it is.
return [(int(part) if part.isdigit() else part) for part in components]
| true |
599ff97346be71193c24c5818e5f2daf99cd6e04 | cfascina/python-learning | /exercices/built-in-functions/lambda-expression/main.py | 764 | 4.5625 | 5 | # Lambda expressions are anonymous functions that you will use only once.
# The following square() function will be converted into a lambda expression,
# step by step.
# Step 1:
# def square(number):
# result = number ** 2
# return result
# Step 2:
# def square(number):
# return number ** 2
# Step 3:
# def square(number): return number ** 2
# Step 4 (lambda expression):
# lambda number: number ** 2"
numbers = [1, 2, 3, 4, 5]
print("Results w/ lambda expression:")
for number in map(lambda number: number ** 2, numbers):
print(number)
# This code does exactly the same thing as the following, but we don't need to
# declare the function square(), since we will only use it once:
# for number in map(square, numbers):
# print(number)
| true |
ee4f50efcfb983282db6c7a1bedf8116508ebf55 | MDCGP105-1718/portfolio-Ellemelmarta | /Python/ex11.py | 780 | 4.1875 | 4 | from random import randint
x = int(randint (1,100))
#make user guess a number with input
guess = int(input("Guess a number between 1 - 100: "))
num_guesses = 1
#tell them higher or lower
while guess != x:
if guess > x and guess != x:
print ("wrong, too high")
guess = int(input("Guess again: "))
num_guesses += 1
#if statement to make sure the guess isnt equal to input and is higher than it to then tell the user
if guess < x and guess != x:
print ("wrong, too low")
guess = int(input("Guess again: "))
num_guesses += 1
#if statement to make sure the guess isnt equal to input and is lower than it to then tell the user
else:
print (f"Congratulations you got it in {num_guesses} guesses. Number = {x}")
| true |
b59bf1444ea96d25bb3aa233600e298f41df21e9 | ssavann/Python-Hangman-game | /Hangman.py | 1,754 | 4.34375 | 4 | #Build a hangman game
import random
import HangmanArt
import HangmanWords
#print ASCII art from "stages"
print(HangmanArt.logo)
end_of_game = False
#List of words
word_list = HangmanWords.word_list
#Let the computer generate random word
chosen_word = random.choice(word_list)
#to count the number of letter in the word
word_length = len(chosen_word)
#set lives to equal 6
lives = 6
#for test only
#print(f'Pssst, the solution is {chosen_word}.')
#Create blanks
display = []
for _ in range(word_length):
display += "_"
while not end_of_game:
guess = input("Guess a letter: ").lower()
#if user typed in the same letter before, we will let him know
if guess in display:
print(f"You've already guessed {guess}")
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
# print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
if letter == guess:
display[position] = letter
#get a track record of lives. If lives goes down to "zero", you lose.
if guess not in chosen_word:
print(f"You've guessed {guess}, that's not in the word. You lose a life.")
lives -= 1
if lives == 0:
end_of_game = True
print("You lose!")
print(f"{' '.join(display)}")
if "_" not in display:
end_of_game = True
print("You win!")
#print ASCII art from "stages"
print(HangmanArt.stages[lives])
"""
#A loop to guess each letter at every position
for char in chosen_word:
if char == guess:
display.append(guess)
else:
display.append("_")
print(display)
""" | true |
40139855c83eb27e635ba657b3e4e21adb7091ce | samiran163/Helloworld | /Operators.py | 606 | 4.40625 | 4 | #Arithmetic operators
num1 =10
num2 =20
print("num1+num2=",num1 + num2)
print("num1-num2=",num1 - num2)
print("num1*num2=",num1 * num2)
print("num1/num2=",num1 / num2)
print('5^3 =',5**3)
print("20 % 3 =", 20%3)
print("22/7=", 22//7)
print('3.8//2', 3.8//2)
#Assignment operator
num3 = num1 +num2
print(num3)
num3+=num2 #num3 =num3+num2
print(num3)
x=5
#x/=5
#print(x)
#x%=5
#print(x)
#x//=2
#print(x)
x**=5
print(x)
#Comparison Operator
print("Is num3 > num2 ?",num3 > num2)
print("Is num2 = num3 ?",num3 == num2)
print("Is num1 != num2 ?",num1 != num2)
#logical operator
x=True
y=False | false |
77f22ce39b1fee400eaf29861a4a5eca82ebf9a4 | LuiSteinkrug/Python-Design | /wheel.py | 1,400 | 4.21875 | 4 | import turtle
turtle.penup()
def drawCircle(tcolor, pen_color, scolor, radius, mv):
turtle.pencolor(pen_color) # not filling but makes body of turtle this colo
turtle.fillcolor(tcolor) # not filling but makes body of turtle this colo
turtle.begin_fill()
turtle.right(90) # Face South
turtle.forward(radius) # Move one radius
turtle.right(270) # Back to start heading
turtle.pendown() # Put the pen back down
turtle.circle(radius) # Draw a circle
turtle.penup() # Pen up while we go home
turtle.end_fill() # End fill.
turtle.home() # Head back to the start pos
def drawHexagon(side_length, pen_color):
polygon = turtle.Turtle()
polygon.pencolor(pen_color)
num_sides = 6
angle = 360.0 / num_sides
polygon.penup() # Pen up while we go home
polygon.left(120)
polygon.forward(side_length)
polygon.right(120)
polygon.pendown() # start drawing hexagon
for i in range(num_sides):
polygon.forward(side_length)
polygon.right(angle)
polygon.pencolor("white")
polygon.fillcolor("white")
polygon.penup()
polygon.home()
drawCircle("blue", "blue", "black", 200, 30)
print (" 2 ")
drawCircle("white", "white", "black", 150, 30)
drawHexagon(200, "white")
drawHexagon(150, "blue")
turtle.exitonclick() | true |
8f5136031e899e3662030a08fe9f11a1983bfc0b | pratikdk/ctci_dsa_solutions | /LinkedList/linked_list.py | 1,141 | 4.15625 | 4 | class Node():
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = self.tail = None
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def linkedList_builder(data):
llist = LinkedList()
#previous = None
for i in data:
if llist.head:
llist.tail.next = Node(i)
llist.tail = llist.tail.next
else:
llist.head = llist.tail = Node(i)
#previous = llist.head
return llist
def nodelist_builder(data):
head = None
tail = None
for i in data:
if head:
tail.next = Node(i)
tail = tail.next
else:
head = tail = Node(i)
return head
def printNodes(head):
while(head):
print(head.data)
head = head.next
if __name__ == "__main__":
llist = LinkedList()
first = Node(1)
second = Node(2)
third = Node(3)
llist.head = first
first.next = second
second.next = third
llist.printList()
| false |
325f52227fcdd352295be2352731b33cedaf2ba4 | urantialife/AI-Crash-Course | /Chapter 2/Functions/homework.py | 715 | 4.1875 | 4 | #Exercise for Functions: Homework Solution
def distance(x1, y1, x2, y2): # we create a new function "distance" that takes coordinates of both points as arguments
d = pow(pow(x1 - x2, 2) + pow(y1 - y2, 2), 0.5) # we calculate the distance between two points using the formula provided in the hint ("pow" function is power)
return d # this line means that our function will return the distance we calculated before
dist = distance(0, 0, 3, 4) # we call our function while inputting 4 required arguments, that are coordinates
print(dist) # we display thr calculated distance
| true |
6993f804ebd81a8fac2c2c2dcc7ba5a96d37e62d | saifsafsf/Semester-1-Assignments | /Lab 11/Modules2.py | 1,894 | 4.4375 | 4 | def strength(password):
'''Takes a password.
Returns its strength out of 10.'''
pass_strength = 0
# If length of password is Good.
if 16 >= len(password) >= 8:
pass_strength += 2
# If password has a special character
if ('$' in password) or ('@' in password) or ('#' in password):
pass_strength += 3
lower, upper, alpha, num = False, False, False, False
# If a letter(lower or upper) or a number is found
for a in password:
if a.islower():
lower = True
elif a.isupper():
upper = True
elif a.isdigit():
num = True
if a.isalpha():
alpha = True
# In case of alphanumeric
if num == True and alpha == True:
pass_strength += 3
# In case of lowercse & uppercase
if upper == True and lower == True:
pass_strength += 2
return pass_strength
def output(pass_strength, password):
'''Takes password & its strength
Returns Strength with appropriate comments.'''
# If strength exceeds 8
if pass_strength > 8:
# Storing password in a file
file = open('passwords.txt', 'a')
file.write(f'{password}\n')
file.close()
# Giving comments
print(f'\nStrength: {pass_strength}/10.\nYour password is STRONG!\n')
else:
# Giving comments
print(f'\nStrength: {pass_strength}/10.')
print(f'\nYour password is weak.\nTry adding atleast 1 symbol, 1 lowercase & 1 uppercase letter.')
print('\nAlso, make sure it\'s alphanumeric & has more than 8 characters but not more than 16.')
print('\nNow, Try Again.\n')
| true |
ce44b33c8e5d4c26ec7f67d09fff55e8d4623d9c | saifsafsf/Semester-1-Assignments | /Lab 08/task 1.py | 419 | 4.21875 | 4 | math_exp = input('Enter a mathematical expression: ') # Taking Input
while math_exp != 'Quit':
math_exp = eval(math_exp) # Evaluating Input
print(f'Result of the expression: {math_exp:.3}\n')
print('Enter Quit to exit the program OR') # Taking input for next iteration
math_exp = input('Enter another mathematical expression: ')
print('Program exited successfully.') # Exiting message
| true |
7196fac0553a675a33fe3cc7816876f40fa2966e | saifsafsf/Semester-1-Assignments | /Lab 08/AscendSort.py | 533 | 4.15625 | 4 | def ascend_sort(input_list):
'''ascend_sort([x])
Returns list sorted in ascending order.'''
for i in range(1, len(input_list)): # To iterate len(list)-1 times
for j in range((len(input_list))-i):
if input_list[j] > input_list[j+1]: # Comparing two consecutive values
interchange = input_list[j+1]
input_list[j+1] = input_list[j] # Sorting consecutive values in ascending order
input_list[j] = interchange
return input_list
| true |
bdf165162078678430c7db868bb38f2894b27f63 | saifsafsf/Semester-1-Assignments | /Assignment 3/Task 1.py | 780 | 4.1875 | 4 | import Maxim
import Remove # Importing modules
import Reverse
nums = input('Enter a natural number: ') # Taking input
if int(nums) > 0:
largest_num = str() # Defining variable before using in line 9
while nums != '':
max_num = Maxim.maxim(nums) # Using Maxim module
largest_num = max_num + largest_num # Storing in descending order
nums = Remove.remove_max(max_num, nums) # Removing the max_num for next iteration
print(f'\nThe Largest Number possible: {int(largest_num)}')
smallest_num = Reverse.reverse(int(largest_num)) # Reversing the largest number
print(f'The Smallest Number possibe: {smallest_num}\n')
else: # Natural Numbers only
print('Invalid Input... Natural Numbers only.')
| true |
ba2c1f8c3440bbcc652276ea22c025fdc6fae4d6 | ridinhome/Python_Fundamentals | /07_classes_objects_methods/07_01_car.py | 862 | 4.4375 | 4 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and demonstrate
changing the objects attributes.
'''
class Car():
def __init__(self,model,year,max_speed):
self.model = model
self.year = year
self.speed = max_speed
def accelerate(self):
self.speed += 5
def __str__(self):
return(f"The {self.model} is from {self.year} and has a maximum speed of {self.speed}.")
my_car1 = Car("BMW",2020,90)
my_car2 = Car("Toyota",2019,70)
print (my_car1)
print (my_car2)
my_car1.accelerate()
print (my_car1)
my_car2 = Car("Honda",2018,65)
print (my_car2)
| true |
3ca0df53a0db382f61549d00923829d0dc3b00be | ridinhome/Python_Fundamentals | /08_file_io/08_01_words_analysis.py | 1,565 | 4.4375 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
my_dict = {}
shortest_list = []
longest_list = []
def shortestword(input_dict):
'''Function to accept a dictionary, convert it to a tuple, sort it
and then return the sorted list as well as the length of the longest and shortest words'''
result_list = []
for key in input_dict:
tuple_to_add = key,input_dict[key]
result_list.append(tuple_to_add)
new_list = sorted(result_list, key= lambda item:item[1])
short_length = new_list[0][1]
list_length = len(new_list)-1
long_length = new_list[list_length][1]
return new_list, short_length, long_length
with open("words.txt","r") as fin:
'''Opens the file, reads the words and then passes them to a dictionary after stripping out new line characters.'''
for word in fin.readlines():
word = word.rstrip()
my_dict[word] = [int(len(word))]
sorted_list,shortest_length,longest_length = shortestword(my_dict)
for key,value in sorted_list:
'''Creates the list of the shortest words and the longest words.'''
if value == shortest_length:
shortest_list.append(key)
elif value == longest_length:
longest_list.append(key)
print ("The shortest words are: ",shortest_list)
print ("The longest words are:", longest_list)
print (f"The total number of words are: {len(sorted_list)}")
| true |
b644aa4a1d7e9d74a773a5e2b4dc095fac236ee2 | ridinhome/Python_Fundamentals | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 970 | 4.375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
Note: This lab might be challenging! Make sure to discuss it with your mentor
or chat about it on our forum.
'''
num_str = input ("Please enter a list of numbers:")
split_list = num_str.split()
num_list =[]
tuple_list = []
for i in range (0,len(split_list)):
num_list.append(int(split_list[i]))
num_list.sort()
if len(num_list) % 2 ==0:
for i in range (0,len(num_list)-1,2):
tuple_to_add = (num_list[i],num_list[i+1])
tuple_list.append(tuple_to_add)
else:
for i in range (0,len(num_list)-1,2):
tuple_to_add = (num_list[i],num_list[i+1])
tuple_list.append(tuple_to_add)
tuple_to_add = (num_list[len(num_list)-1],0)
tuple_list.append(tuple_to_add)
print (tuple_list) | true |
916c20052c18261dd5ef30d421b0e17b0e92d443 | ridinhome/Python_Fundamentals | /02_basic_datatypes/1_numbers/02_05_convert.py | 568 | 4.375 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
value_a = 90
value_b = 11.0
value_a_float = float(value_a)
print (value_a_float)
value_b_float = int(value_b)
print(value_b_float)
value_c = value_a // value_b
print(value_c)
c = input("Enter a value")
b = input("Enter another value")
cd = float(c) * float(b)
print(cd)
| true |
f7e6225cdf68f34263c7b0d22d96b3dd5da27632 | royopa/python-2 | /ex5.py | 464 | 4.15625 | 4 | maior = None
menor = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num=int(num)
except:
print('Invalid input')
else:
if menor is None:
menor= num
elif num < menor:
menor= num
if maior is None:
maior=num
elif num > maior:
maior =num
print("Maximum is", maior)
print('Minimum is', menor)
| false |
d4c0dbee1de20b3fae2f2ae80f74d105463d4c07 | akhilkrishna57/misc | /python/cap.py | 1,727 | 4.21875 | 4 | # cap.py - Capitalize an English passage
# This example illustrates the simplest application of state machine.
# Scene: We want to make the first word capitalized of every sentence
# in a passage.
class State (object):
def setMappedChar(self, c):
self.c = c
def getMappedChar(self):
return self.c
def setNextState(self, s):
self.s = s
def keepCurrentState(self):
self.s = self
def getNextState(self):
return self.s
class BeforeSentenceState (State):
'''We are ahead of a passage or
behind a full stop of a sentence but before the next one'''
def transit(self, c):
if c.isalpha():
self.setMappedChar(c.upper())
self.setNextState(InSentenceState())
else:
self.setMappedChar(c)
self.keepCurrentState()
class InSentenceState (State):
'''We are within a sentence'''
def transit(self, c):
if c == '.':
self.setMappedChar(c)
self.setNextState(BeforeSentenceState())
else:
self.setMappedChar(c)
self.keepCurrentState()
class Capitalizer (object):
def process(self, text):
result = ''
currentState = BeforeSentenceState()
for c in text:
currentState.transit(c)
result += currentState.getMappedChar()
currentState = currentState.getNextState()
return result
cap = Capitalizer()
print cap.process("""apple device owners can run official apps for Google Maps, \
Google Search, Gmail, Google's Chrome browser, Google Drive and more. \
they can get Microsoft-written apps for its Bing search service, \
its SkyDrive cloud-storage service, its OneNote note-taking service and more. \
and they can get a host of Amazon's apps, including several apps for Amazon's \
online store and apps for Amazon's cloud-based video and music steaming services.""") | true |
21ca29ba7a6e2a124a20291d11490a4eefabe4d3 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex8.py | 1,364 | 4.53125 | 5 | formatter = "{} {} {} {} " # this is the equivalent of taking a data of type str and creating positions (and blueprints?) for different arguments that will later be passed in and storing it in a variable called
#formatter
print(formatter.format(1, 2, 3, 4)) #The first argument being passed in and printed is of data type int (1,2,3,4) and they go into the 4 positions set by the {}
print(formatter.format("one", "two", "three", "four")) #The second argument being passed in and printed is of data type str ("one", "two"...) and they go into the 4 positions set by {}
print(formatter.format(True, False, False, True)) #The third argument being passed in and printed is of data type Boolean (True, False, False, True) and they go in the 4 positions set by {}
print(formatter.format(formatter, formatter, formatter, formatter)) #The fourth argument being passed in and printed is of data type var (pointing to a str with 4 {} so this will print 16 of them total)
print(formatter.format( #The fifth argument being passed in is of data type str and there are 4 strings being passed in, 1 string per position or {} and will print a total of 4 distinct {} on same line :)
"Small are your feet",
"And long is the road",
"Will measures more",
"Just shut up and code!"
))
#OK! I think I get what this is doing!
| true |
06efc287d6c51abc7851cbccbece718179a9e4a0 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex16.py | 1,368 | 4.3125 | 4 | from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (>C).")
print("If you do want that, hit RETURN.") #print statement doesn't ask for input. Only to hit the return key, which is what you would normally hit after entering user input. (or quit python--already built in--ctrl c)
input("?")
print("Opening the file...")
target = open(filename, 'w') #calls open and passes in the parameter filename and write mode and stores the opened file in write mode in the variable "target".
print("Truncating the file. Goodbye!")
target.truncate() #erased my whole file (no parameters) which said "This is a test file" or something like that
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ") #stores user input under these variable names: line1, line2, line3. Uses prompt: line 1:, line 2:, line 3::
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1) #write to the file, pass in the parameter line1--writes line 1 to the file.
target.write("\n") #write to the file, pass in the parameter new line, goes to next line
target.write(line2) #...etc
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close() #closes opened file which is in write mode
| true |
0ba974b7a198bea2c267cb0a1d87c719c6bef25e | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex15a.py | 1,171 | 4.65625 | 5 | filename = input("What's the name of the file you want to open?")
txt = open(filename) #the open command takes a parameter, in this case we passed in filename, and it can be set to our own variable. Here, our own variable stores an open text file. Note to self: (filename) and not {filename} because filename is already a variable label created in line 3.
print(f"Here's your file {filename}:")
print(txt.read()) #call a function on an opened text file named "txt" and that function we call is "read". We call "read" on an opened file. It returns a file and accepts commands. ****You give a FILE a command using dot notation.
close = txt.close
print(close)
print("Type the filename again:")
file_again = input("> ") #sets user input received at prompt "> " equal to variable called "file_again"
txt_again = open(file_again) #opens our sample txt file again and stores opened file in a variable called txt_again
print(txt_again.read()) #reads the file now stored under txt_again and prints it out again.
close = txt_again.close
print(close)
#********** This is an alternate version from the study drill. Using input only and not argv to open the file.
| true |
5801328332c67f3402892bab049ad7bcc2fa4514 | Giselii/numero-maior-e-menor | /033_NumeroMaioreMenor.py | 1,218 | 4.125 | 4 | #Faça um programa que leia três números e mostre qual é o maior e qual é o menor
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número:'))
n3 = int(input('Digite outro número: '))
#print('O maior número é {}'.format(max(n1, n2, n3)))
#print('O menor número é {}'.format(min(n1, n2, n3)))
if (n1 < n2) & (n1 < n3):
print('{} é o menor '.format(n1))
if (n2 < n3) & (n2 < n1):
print('{} é o menor'. format(n2))
if (n3 < n1) & (n3 < n2):
print('{} é o menor'.format(n3))
if (n1 == n2) & (n1 < n3):
print('{} e {} são menores'.format(n1, n2))
if (n1 == n3) & (n1 < n2):
print('{} e {} são menores'.format(n1, n3))
if (n2 == n3) & (n2 < n1):
print('{} e {} sáo menores'.format(n2, n3))
if (n1 == n2 == n3):
print('Os números são iguais')
if (n1 > n2) & (n1 > n3):
print('{} é maior'.format(n1))
if (n2 > n1) & (n2 > n3):
print('{} é maior'.format(n2))
if (n3 > n1) & (n3 > n2):
print('{} é maior'.format(n3))
if (n1 == n2) & (n1 > n3):
print('{} e {} são maiores'.format(n1, n2))
if (n1 == n3) & (n1 > n2):
print('{} e {} são maiores'.format(n1, n3))
if (n2 == n3) & (n2 > n1):
print('{} e {} são maiores'.format(n2, n3))
| false |
8c035e7b062f86d4c90b504d16f5f4fa29e5a3f1 | AliZet-to/Homework2 | /Task_3.py | 1,196 | 4.25 | 4 | # Data input
side_AB_len = float(input("Please input AB side length \n"))
side_BC_len = float(input("Please input BC side length \n"))
side_AC_len = float(input("Please input AC side length \n"))
# Verification for a triangle existence
if (side_AB_len + side_BC_len) > side_AC_len and (side_BC_len + side_AC_len) > side_AB_len and (side_AB_len + side_AC_len) > side_BC_len:
print("It is a triangle")
else:
print("It is not a triangle")
#Calculation workflow
p = 0.5 * (side_AB_len + side_BC_len + side_AC_len)
#The first Height calculation, Hbc
Hbc = ((p * (p - side_BC_len) * (p - side_AC_len) * (p - side_AB_len))**0.5 * 2) / side_BC_len
#The second Height calculation, Hac
Hac = ((p * (p - side_BC_len) * (p - side_AC_len) * (p - side_AB_len))**0.5 * 2) / side_AC_len
#The first Height calculation, Hab
Hab = ((p * (p - side_BC_len) * (p - side_AC_len) * (p - side_AB_len))**0.5 * 2) / side_AB_len
print("Hbc = ", Hbc)
print("Hac = ", Hac)
print("Hab = ", Hab)
if (Hab >= Hbc) and (Hab >= Hac):
print("The biggest height is Hab = ", Hab)
elif (Hbc >= Hab) and (Hbc >= Hac):
print("The biggest height is Hbc = ", Hbc)
else:
print("The biggest height is Hac = ", Hac)
| false |
d9d9b96ebb5380d242f5532e475bb0a3f7547a01 | Nixer/lesson01 | /dictionaries.py | 358 | 4.125 | 4 | my_dict = {"city": "Москва", "temperature": "20"}
print(my_dict["city"])
my_dict["temperature"] = str(int(my_dict["temperature"]) - 5)
for k, v in my_dict.items():
print(f"{k} : {v}")
if "country" in my_dict:
print(True)
else:
print(False)
print(my_dict.get("country", "Россия"))
my_dict["date"] = "27.05.2017"
print(len(my_dict))
| false |
63043be9d8b39e5caf053a06bd8129a27f0c4ffe | BSR-AMR-RIVM/blaOXA-48-plasmids-Microbial-Genomics | /scripts/printLine.py | 273 | 4.1875 | 4 | # quick code to print the lines that starts with >
import sys
FILE = sys.argv[1]
with open(FILE, 'r') as f:
count = 0
for line in f:
count =+ 1
if line.startswith(">"):
newLine = line.split(' ')
if len(newLine) < 3:
print(newLine)
print(count) | true |
b48bbe647eedb43c9e4adaa726842cfed8c38fd0 | Rythnyx/py_practice | /basics/reverseArray.py | 1,125 | 4.46875 | 4 | # The purpose of this excercise is to reverse a given list
exList = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g']
# The idea here is to simply return the list that we had but step through it backward before doing so.
# This however will create a new list, what if we want to return it without creating a new one?
def reverse_list(p_list):
return p_list[::-1]
# To make this work we need to keep track of indexes and step through the list ourselves
# whilst flipping elements with each other
def reverse_list_in_place(p_list):
# indexes
left = 0
right = len(p_list) -1
# When we pass the midpoint we have finished
while left < right:
# swap elements
temp = p_list[left]
p_list[left] = p_list[right]
p_list[right] = temp
# update indexes
left += 1
right -= 1
return p_list
#if __name__ == "__main__":
print("This is the result of a new reversed list being returned:\n\t" + str(reverse_list(exList)) + "\n")
print("This is the result of the same list being returned with inplace swapping:\n\t" + str(reverse_list_in_place(exList))) | true |
787bb5e6c13463126b80c1144ae7a19274aab61b | ebonnecab/CS-2-Tweet-Generator | /regular-challenges/dictionary_words.py | 1,176 | 4.125 | 4 | #an algorithm that generates random sentences from words in a file
#TO DO: refactor code to use randint
import random
import sys
# number = sys.argv[:1]
number = input('Enter number of words: ') #takes user input
''' removes line breaks, and appends the words from the file to the list, takes five words from the list object, stores them in an array,
and joins the array into a sentence before outputting it'''
def random_sentence():
words_list = [] #creates list object
with open('/usr/share/dict/words') as file: #accessing word file
text = file.read().split()
for word in text:
# words_list.append(word)
# rand_num = random.randint(0, len(text)-1)
# rand_word = words_list[rand_num]
# words_list.append(word)
word = word.strip()
words_list.append(word)
word_array = random.choices(words_list, k= int(number))
sentence = ' '.join(word_array) + '.'
sentence = sentence.capitalize()
return sentence
if __name__ == '__main__':
test = random_sentence()
print(test)
| true |
b7bd042233235ec6d6b753ae4588c96645f0759d | alisatsar/itstep | /Python/Lessons/class/reloadOperators.py | 1,053 | 4.21875 | 4 | class Newclass():
def __init__(self, base):
self.base = base
def __add__(self, a): #позволяет добавлять к объекту значение
self.base = self.base + a
def __mul__(self, b): #позволяет объетку быть умноженным
self.base = self.base * b
def __sub__ (self, c): #позволяет от объекта отнять
self.base = self.base - c
def __call__(self, newWord): #позволяет сделать объект как функцией
self.base = newWord
def __str__(self): #представляет объект в виде строки, (можно принтануть объект),
# а так возвращает адрес объекта
return "%s !!!" % self.base
obj1 = Newclass(10)
obj1 + 20
print(obj1)
obj1 - 20
print(obj1)
obj1 * 2
print(obj1)
obj2 = Newclass("Yes")
obj2 + "terday"
print(obj2)
obj2 * 4
print(obj2)
obj2("No")
print(obj2)
| false |
151172bdb8289efb3e3494a7c96db79c0d07de4c | kushrami/PythonProgramms | /LoanCalculator.py | 439 | 4.125 | 4 | CostOfLoan = float(input("Please enter your cost of loan = "))
InterestRate = float(input("Please enter your loan interst rate = "))
NumberOfYears = float(input("Please enter Number of years you want a loan = "))
InterestRate = InterestRate / 100.0
MonthlyPayment = CostOfLoan * (InterestRate * (InterestRate + 1.0) * NumberOfYears) / ( (1.0 + InterestRate) * NumberOfYears - 1.0)
print("Your Monthly Payment of loan is",MonthlyPayment) | true |
d5c46b1068f3fa7d34ef2ef5151c1c0a825c88f5 | derpmagician/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 253 | 4.3125 | 4 | #!/usr/bin/python3
""" Reads an utf-8 formated file line by line"""
def read_file(filename=""):
"""Reads an UTF8 formated file line by line """
with open(filename, encoding='utf-8') as f:
for line in f:
print(line, end='')
| true |
8fc8ff320c25de0b3b15537fbbee03749721a9c1 | Aliena28898/Programming_exercises | /CodeWars_exercises/Roman Numerals Decoder.py | 1,816 | 4.28125 | 4 | '''
https://www.codewars.com/kata/roman-numerals-decoder
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
Example:
solution('XXI') # should return 21
Courtesy of rosettacode.org
'''
#SOLUTION:
sol = 0
index = 0
def decode(roman, char, decimal):
global sol
global index
if char in roman and decimal != 1:
while index < len(roman) and roman[index] == char:
sol = sol + decimal
index += 1
if roman[index:].find(char) != -1:
if char in "MCX":
sol = sol + int(decimal * 0.9)
else:
sol = sol + int(decimal * 0.8)
index = index + 2
else:
while index < len(roman) and roman[index] == char:
sol = sol + decimal
index += 1
def solution(roman):
global sol
global index
sol = 0
index = 0
decode(roman, 'M', 1000)
decode(roman, 'D', 500)
decode(roman, 'C', 100)
decode(roman, 'L', 50)
decode(roman, 'X', 10)
decode(roman, 'V', 5)
decode(roman, 'I', 1)
return sol
#SAMPLE TESTS:
test.assert_equals(solution('XXI'), 21)
test.assert_equals(solution('MCMXC'), 1990)
test.assert_equals(solution('MMVIII'), 2008)
test.assert_equals(solution('MDCLXVI'), 1666)
test.assert_equals(solution('II'), 2)
| true |
24540c992ec687bd43c3b38674e1acef2f43dcb8 | Aliena28898/Programming_exercises | /CodeWars_exercises/Reversed Sequence.py | 298 | 4.25 | 4 | '''
Get the number n to return the reversed sequence from n to 1.
Example : n=5 >> [5,4,3,2,1]
'''
#SOLUTION:
def reverse_seq(n):
solution = [ ]
for num in range(n, 0, -1):
solution.append(num)
return solution
#TESTS:
test.assert_equals(reverse_seq(5),[5,4,3,2,1])
| true |
51bff2c710aa809cc0cf3162502a7acae518bf60 | AnaLuizaMendes/Unscramble-Computer-Science-Problems | /Task1.py | 1,011 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
# First create a set to hold all the unique numbers
nums = set()
def get_nums(list):
# For loop in text, to go throw each row in the doc
# Then, select the numbers in the first and second columns
# If it is not in nums adds to it, if it is ignore and continue
for row in list:
for num in row[0], row[1]:
nums.add(num)
return nums
get_nums(texts)
get_nums(calls)
# Get the len of nums to know how many unique numbers in the two documents
count = len(nums)
print(f"There are {count} different telephone numbers in the records.")
| true |
18ad26f5f5613336ece2a9affadceb7282ab0a75 | aaishikasb/Hacktoberfest-2020 | /cryptography system/Crypto_system.py | 729 | 4.3125 | 4 | def machine():
keys = "abcdefghijklmnopqrstuvwxyz !"
values = keys[-1] + keys[0:-1]
encrypt = dict(zip(keys, values))
decrypt = dict(zip(values, keys))
option = input(
"Do you want to encrypt or decrypt, press e for encrypt and d for decrypt?")
message = input("what is the message you wanna encrypt or decrypt?")
if (option.lower() == 'e'):
new_msg = ''.join([encrypt[i] for i in message])
# here we are changing the values of each alphabet according to the values associated with keys in dictionary!
elif (option.lower() == 'd'):
new_msg = ''.join([decrypt[i] for i in message])
else:
print("Enter the valid option ( e or d )")
return new_msg
print(machine())
| true |
9f3fb321ae20fef315b17c48aada33418a993ec0 | sindaakyil/python | /pythonsets.py | 646 | 4.1875 | 4 | fruits = {'orange','apple','banana'}
print(fruits)
for x in fruits :
print(x)
fruits.add('cherry') #listeye ekler
fruits.update(['mango','grape','apple'])# listeye belirlenen elemanları ekler
fruits.remove('mango') #listeden mangoyu siler
fruits.discard('apple') # listeden apple siler
fruits.clear #bütün listeyi siler
print(fruits)
myList = [1,2,3,4,4,5,5]
print(set(myList)) #tekrarlayan terimleri siler
print(myList)#listedeki bütün terimleri ekler
#value &referance types
# value types --- string number
x=5
y=25
x=y
y=10
print(x,y)
# referance types_list
a= ["apple","banana"]
b= ["apple","banana"]
a=b
b[0]="grape"
print(a,b) | false |
c0f8180687415dbc703433d7642329baedf9212f | MLHafizur/Unscramble-Computer-Science-Problems | /Task4.py | 1,528 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
def get_telemarketers(record_list):
text_num_list, caller_list, reciever_list = [], [], []
for record in record_list:
caller, reciever = record[0].strip(), record[1].strip()
if is_text(record):
text_num_list.extend([caller, reciever])
elif is_call(record):
caller_list.append(caller)
reciever_list.append(reciever)
else:
raise Exception('Type of the record not recognized')
telemarketer_set = (set(caller_list)
- (set(reciever_list)
| set(text_num_list)))
return sorted(telemarketer_set)
def is_text(record):
return len(record) == 3
def is_call(record):
return len(record) == 4
print('These numbers could be telemarketers:\n',
get_telemarketers(texts + calls))
| true |
99abf35d29cc6488acc5a7d230abd99688ca45ea | JKinsler/Sorting_Algorithms_Test | /merge_sort3.py | 1,508 | 4.15625 | 4 | """
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Merge sort
Sorting array practice
6/9/20
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sort an unsorted array in O(nlogn) time complexity
Developer notes: this is my favorite way to organize the merge sort algorithm
because I think it's easily readable.
"""
def merge_sort(arr):
"""
Divide a conquer sort method with O(nlog(n)) runtime
"""
# set the recursion base case
if len(arr) < 2:
return arr
# divide the list
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
"""
combine the two sorted lists into a single sorted list
"""
i_left = 0
i_right = 0
res = []
#interleave right and left into a list
while i_left < len(left) and i_right < len(right):
if left[i_left] < right[i_right]:
res.append(left[i_left])
i_left += 1
else:
res.append(right[i_right])
i_right += 1
# add remaining values from the left index
while i_left < len(left):
res.append(left[i_left])
i_left += 1
# add remaining values from the right index
while i_right < len(right):
res.append(right[i_right])
i_right += 1
return res
if __name__ == '__main__':
print(merge_sort([3, 1, 2]))
print(merge_sort([]))
print(merge_sort([8, 1, 35, 2, 16]))
| true |
e0c5fc3a55327871f16b450def694a6dd97a8e5f | JKinsler/Sorting_Algorithms_Test | /merge_sort2.py | 1,353 | 4.15625 | 4 | """
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Merge sort
Sorting array practice
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Sort an unsorted array in O(nlogn) time complexity
"""
def merge_sort(arr):
"""
decompose the array into arrays of length 1
recombine the arrays in a sorted manner, using the helper function
Developer notes:
This solution is not ideal because it uses 'pop(0)' in the helper function,
which adds O(n) run time.
"""
if len(arr) < 2:
print(f'returning arr: {arr}')
return arr
mid = len(arr)//2
lst1 = merge_sort(arr[:mid])
lst2 = merge_sort(arr[mid:])
return merge(lst1, lst2)
def merge(lst1, lst2):
"""combine two sorted arrays into a single sorted array"""
res = []
# add the lowest value to res
while len(lst1) > 0 or len(lst2) > 0:
# add the value of the remaining list if one list is empty
if lst1 == []:
res.append(lst2.pop(0))
elif lst2 == []:
res.append(lst1.pop(0))
# append the lesser value to res
elif lst1[0] < lst2[0]:
res.append(lst1.pop(0))
else:
res.append(lst2.pop(0))
return res
if __name__ == '__main__':
print(merge_sort([3, 1, 4])) | true |
9601cc0074e5f52b7af909d3c35bc35b55c65a8c | Daozhou155/python-learn | /a6.py | 659 | 4.15625 | 4 | # !/usr/bin/env python
# -*-coding:utf-8-*-
# author: zjr time:2019/8/18
# 列表元素提取
list1 = [1, 2, ['a', 'b'], 123]
print(list1[2][1])
# 列表元素计数,不能计算列表中的列表
list2 = [123, 456, 789, [123, 111]]
list2 *= 5
a = list2.count(123)
print(a)
# 列表元素位置
list3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list3.index(3, 0, 10))
# 列表反转
list3.reverse()
print(list3)
# 列表排序
list4 = [6, 2, 9, 24, 3, 75, 0, 48, 4]
list4.sort() # 从小到大
print(list4)
list4.sort(reverse=True) # 从大到小
print(list4)
# 列表分片
list5 = [1, 2, 3, 6, 5, 4]
list6 = list5[0:2]
print(list6)
| false |
5a5c10e83e60d200ed4a722f8a018e43014d628d | Benedict-1/mypackage | /mypackage/sorting.py | 1,561 | 4.34375 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order'''
count = 0
for idx in range(len(items)-1):
if items[idx] > items[idx + 1]:
items[idx],items[idx + 1] = items[idx + 1],items[idx]
count += 1
if count == 0:
return items
else:
return bubble_sort(items)
def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def quick_sort(items):
if len(items) <= 1:
return items
items = list(items)
pivot = items[-1]
new_list = [pivot]
count = 0
for i in range(len(items)-1):
if items[i]<pivot:
new_list = [items[i]]+ new_list
count+=1
else:
new_list = new_list + [items[i]]
return quick_sort(new_list[:count])+[pivot]+quick_sort(new_list[count+1:])
| true |
8242e2eb55ad59d6c17497e56df4cc150fc78a33 | jpchato/data-structures-algorithms-portfolio | /python/array_shift.py | 766 | 4.3125 | 4 | '''
Feature Tasks
Write a function called insertShiftArray which takes in an array and the value to be added. Without utilizing any of the built-in methods available to your language, return an array with the new value added at the middle index.
Example
Input Output
[2,4,6,8], 5 [2,4,5,6,8]
[4,8,15,23,42], 16 [4,8,15,16,23,42]
'''
import math
def insert_shift_array(array, value):
middle_index = math.ceil(len(array)/2)
end_piece = array[middle_index:len(array)]
start_piece = array[0:middle_index]
start_piece.append(value)
for item in end_piece:
start_piece.append(item)
print(start_piece)
return start_piece
if __name__ == "__main__":
insert_shift_array([2,4,6,8], 5)
insert_shift_array([4,8,15,23,42], 16) | true |
5332542eca544e73bb048cfeced7812d506d9943 | Ambush3/BMI-Calculator | /BMI calculator.py | 524 | 4.21875 | 4 | print("Lets find your BMI")
height = float(input("Enter your height in m: "))
weight = float(input("Enter your weight in kg: "))
bmi = weight/(height**2)
print("Your bmi is {0} and you are: ".format(bmi), end='')
if ( bmi < 18.5):
print("underweight.")
elif ( bmi >= 18.5 and bmi < 25 ):
print("normal weight.")
elif ( bmi > 25 and bmi < 30):
print("slightly overweight")
elif ( bmi > 30 and bmi < 35):
print("are obese.")
else:
( bmi > 35)
print("clinically obese.")
| false |
82f361fc9231541a923a2c071e14c9b8e6780f88 | cnagadya/bc_16_codelab | /Day_three/wordcount.py | 599 | 4.1875 | 4 | """ words function to determine the number of times a word occurs in a string"""
def words(input_string):
#dictionary template to display words as keys and occurances as values
words_dict = {}
#splitting string into list to enable iteration
words_list = input_string.split()
#iterate through the list to check for the words
for word in words_list:
#check if the word is a number
if word.isdigit():
word = int(word)
words_dict[word] = words_list.count(str(word))
print words_dict
words("one fish two fish red fish blue fish")
words('testing 1 2 testing') | true |
3ba5adf3dfceea19a2d84aa3e983951341f10e92 | elvisasante323/code-katas | /python_code/regex.py | 515 | 4.4375 | 4 | # Learning about regex
import re
# Search the string to see if it starts with 'The' and ends with 'Spain'
text = 'The rain in Spain'
expression = re.search('^The.*Spain$', text)
if expression:
print('We have a match!\n')
else:
print('There is no match!\n')
# Find all lower case characters alphabetically between 'a' and 'm'
expression = re.findall('[a-m]', text)
print(expression, '\n')
# Find all digit characters
text = 'That will be 59 dollars'
expression = re.findall('\d', text)
print(expression)
| true |
215950378bbcd2f020be5ebfb49cd5c7b5a9aa07 | cgisala/Capstone-Intro | /Lab1/Part2:_list_of_classes.py | 432 | 4.21875 | 4 | #Variable
choice = 'y' #Initializes choice to y
classes = [] #Declares an empty array
#Loops until the user enters 'n' for no
while(choice == 'y'):
semesterClass = input("Enter a class you are taking this semester: ")
classes.append(semesterClass)
choice = input("Do you want to add more y or n: ")
print('My classes for this semester:')
#Prints the answer in each line
for myClass in classes:
print(myClass) | true |
ad9431376cb21d18ca9d6fa272bd7ea4ae01572f | BrunoAlz/design-patterns-python-master | /structural/adapter/adapter_1.py | 2,244 | 4.28125 | 4 | """
Adapter é um padrão de projeto estrutural que
tem a intenção de permitir que duas classes
que seriam incompatíveis trabalhem em conjunto
através de um "adaptador".
"""
from abc import ABC, abstractmethod
class IControl(ABC):
@abstractmethod
def top(self) -> None: pass
@abstractmethod
def right(self) -> None: pass
@abstractmethod
def down(self) -> None: pass
@abstractmethod
def left(self) -> None: pass
class Control(IControl):
def top(self) -> None:
print('Movendo para cima...')
def right(self) -> None:
print('Movendo para direita...')
def down(self) -> None:
print('Movendo para baixo...')
def left(self) -> None:
print('Movendo para esquerda...')
class NewControl:
def move_top(self) -> None:
print('NewControl: Movendo para cima...')
def move_right(self) -> None:
print('NewControl: Movendo para direita...')
def move_down(self) -> None:
print('NewControl: Movendo para baixo...')
def move_left(self) -> None:
print('NewControl: Movendo para esquerda...')
class ControlAdapter:
""" Adapter Object """
def __init__(self, new_control: NewControl) -> None:
self.new_control = new_control
def top(self) -> None:
self.new_control.move_top()
def right(self) -> None:
self.new_control.move_right()
def down(self) -> None:
self.new_control.move_down()
def left(self) -> None:
self.new_control.move_left()
class ControlAdapter2(Control, NewControl):
""" Adapter Class """
def top(self) -> None:
self.move_top()
def right(self) -> None:
self.move_right()
def down(self) -> None:
self.move_down()
def left(self) -> None:
self.move_left()
if __name__ == "__main__":
# Control - Adapter Object
new_control = NewControl()
control_object = ControlAdapter(new_control)
control_object.top()
control_object.down()
control_object.left()
control_object.right()
print()
# Control - Adapter class
control_class = ControlAdapter2()
control_class.top()
control_class.down()
control_class.left()
control_class.right()
| false |
972c11fb7b7ed641e65d1038bc92f5e777aaa5ca | BrunoAlz/design-patterns-python-master | /behavioral/strategy/strategy_1.py | 2,073 | 4.1875 | 4 | """
Strategy é um padrão de projeto comportamental que tem
a intenção de definir uma família de algoritmos,
encapsular cada uma delas e torná-las intercambiáveis.
Strategy permite que o algorítmo varie independentemente
dos clientes que o utilizam.
Princípio do aberto/fechado (Open/closed principle)
Entidades devem ser abertas para extensão, mas fechadas para modificação
"""
from __future__ import annotations
from abc import ABC, abstractmethod
class Order:
def __init__(self, total: float, discount: DiscountStrategy):
self._total = total
self._discount = discount
@property
def total(self):
return self._total
@property
def total_with_discount(self):
return self._discount.calculate(self.total)
class DiscountStrategy(ABC):
@abstractmethod
def calculate(self, value: float) -> float: pass
class TwentyPercent(DiscountStrategy):
def calculate(self, value: float) -> float:
return value - (value * 0.2)
class FiftyPercent(DiscountStrategy):
def calculate(self, value: float) -> float:
return value - (value * 0.5)
class NoDiscount(DiscountStrategy):
def calculate(self, value: float) -> float:
return value
class CustomDiscount(DiscountStrategy):
def __init__(self, discount) -> None:
self.discount = discount / 100
def calculate(self, value: float) -> float:
return value - (value * self.discount)
if __name__ == "__main__":
twenty_percent = TwentyPercent()
fifty_percent = FiftyPercent()
no_discount = NoDiscount()
five_percent = CustomDiscount(5)
order = Order(1000, twenty_percent)
print(order.total, order.total_with_discount)
order = Order(1000, fifty_percent)
print(order.total, order.total_with_discount)
order = Order(1000, no_discount)
print(order.total, order.total_with_discount)
order = Order(1000, five_percent)
print(order.total, order.total_with_discount)
order = Order(1000, CustomDiscount(13))
print(order.total, order.total_with_discount)
| false |
f494a23aa5ae7dd8e7f87e521fad4779e62c5118 | BrunoAlz/design-patterns-python-master | /behavioral/template_method/template_method_2.py | 1,909 | 4.3125 | 4 | """
Template Method (comportamental) tem a intenção de definir
um algoritmo em um método, postergando alguns passos
para as subclasses por herança. Template method permite
que subclasses redefinam certos passos de um algoritmo
sem mudar a estrutura do mesmo.
Também é possível definir hooks para que as subclasses
utilizem caso necessário.
The Hollywood principle: "Don't Call Us, We'll Call You."
(IoC - Inversão de controle)
"""
from abc import ABC, abstractmethod
class Pizza(ABC):
""" Classe abstrata """
def prepare(self) -> None:
""" Template method """
self.hook_before_add_ingredients() # Hook
self.add_ingrentients() # Abstract
self.hook_after_add_ingredients() # Hook
self.cook() # Abstract
self.cut() # Concreto
self.serve() # Concreto
def hook_before_add_ingredients(self) -> None: pass
def hook_after_add_ingredients(self) -> None: pass
def cut(self) -> None:
print(f'{self.__class__.__name__}: Cortando pizza.')
def serve(self) -> None:
print(f'{self.__class__.__name__}: Servindo pizza.')
@abstractmethod
def add_ingrentients(self) -> None: pass
@abstractmethod
def cook(self) -> None: pass
class AModa(Pizza):
def add_ingrentients(self) -> None:
print(f'AModa - adicionando ingredientes: presunto, queijo, goiabada')
def cook(self) -> None:
print(f'AModa - cozinhado por 45min no forno a lenha')
class Veg(Pizza):
def hook_before_add_ingredients(self) -> None:
print('Veg - Lavando ingredientes')
def add_ingrentients(self) -> None:
print(f'Veg - adicionando ingredientes: ingredientes veganos')
def cook(self) -> None:
print(f'Veg - cozinhado por 5min no forno comum')
if __name__ == "__main__":
a_moda = AModa()
a_moda.prepare()
print()
veg = Veg()
veg.prepare()
| false |
57601ca144fda603bcd1822d4d1971873e23ddbc | SaiKrishnaBV/python-basics | /scopeOfVariable2.py | 656 | 4.34375 | 4 | '''
Understanding the concept of nonlocal variables(enclosed variables) inside nested functions
'''
z = 5
def in_func():
z = 10
print("In_func() --> local: z =",z)
def inner_func():
nonlocal z #to access enclosed variable instead of global variable
z+=1
print("Inner_func() --> z =",z)
def innermost_func():
#global z
#print("Innermost_func() --> global: z =",z)
nonlocal z
print("Innermost_func() --> nonlocal: z =",z)
innermost_func()
print("After CALL: Inner_func() --> nonlocal: z=",z)
inner_func()
print("After CALL: In_func() --> local: z=",z)
in_func()
print("After CALL: main() --> global: z=",z)
| false |
9e3b8d7aac17d3b5cef01341cc8452f9ac52cab6 | zrjaa1/Berkeley-CS9H-Projects | /Project2A_Power Unit Converter/source_to_base.py | 1,260 | 4.34375 | 4 | # Function Name: source_to_base
# Function Description: transfer the source unit into base unit.
# Function Input
# - source_unit: the unit of source, such as mile, cm.
# - source_value: the value in source unit.
# Function Output
# - base_unit: the unit of base, such as m, kg, L
# - base_value: the value in base unit.
def source_to_base(source_unit, source_value):
Distance = {'ft': 0.3048, 'cm': 0.01, 'mm': 0.001, 'mi': 1609.34, 'm': 1, 'yd': 0.9144, 'km': 1000, 'in': 0.0254};
Weight = {'lb': 0.453592, 'mg': 0.000001, 'kg': 1, 'oz': 0.0283495, 'g': 0.001};
Volume = {'floz': 0.0295735, 'qt': 0.946353, 'cup': 0.236588, 'mL': 0.001, 'L': 1, 'gal': 3.78541, 'pint': 0.473176};
if Distance.has_key(source_unit):
base_unit = 'm'
base_value = source_value * Distance[source_unit]
print base_unit, base_value
return base_unit, base_value
elif Weight.has_key(source_unit):
base_unit = 'kg'
base_value = source_value * Weight[source_unit]
print base_unit, base_value
return base_unit, base_value
elif Volume.has_key(source_unit):
base_unit = 'L'
base_value = source_value * Volume[source_unit]
print base_unit, base_value
return base_unit, base_value
else:
print 'Wrong source unit'
source_to_base('lb',100) | true |
3191972f08fb2d8e4a6292c5bdd59aabdcb51688 | alfonso-torres/data_types-operators | /strings&casting.py | 1,937 | 4.65625 | 5 | # Strings and Casting
# Let's have a look at some industry practices
# single and double quotes examples
greetings = 'hello world'
single_quotes = 'single quotes \'WoW\''
double_quotes = "double quotes 'WoW'" # It is more easier to use
print(greetings)
print(single_quotes)
print(double_quotes)
# String slicing
greetings = "Hello world!" # String
# indexing in Python starts from 0
# H e l l o w o r l d !
# 0 1 2 3 4 5 6 7 8 9 10 11
# how can we find out the length of this statement/string
print(len(greetings))
# We have a method called len() to find out the total length of the statement
print(greetings[0:5]) # out puts Hello starting from 0 to 4
print(greetings[6:11]) # out puts world starting from 6 to 10
# reverse indexing starts with -1
print(greetings[-1])
# Let's have a look at some strings methods
white_space = "Lot's of space at the end "
# strip() helps us delete all white spaces
print(len(white_space))
print(len((white_space.strip())))
Example_text = "here's Some texts with lot's of text"
print(Example_text.count("text"))
# counts the number of times the word is mentioned in the statement
print(Example_text)
print(Example_text.upper())
print(Example_text.lower())
print(Example_text.capitalize()) # capitalises first letter of the string
print(Example_text.replace("with", ","))
# will replace the world "with" , in this case
# Concatenation and Casting
# We use the symbol `+` to concatenate
First_name = "James"
Last_name = "Bond"
age = 99 # int
# print(First_name + " " + Last_name)
print(First_name + " " + Last_name + " " + str(age))
#print(Last_name)
agee = "99"
print(agee)
print(type(agee))
print(int(agee))
print(type(int(agee)))
x = "100"
y = "-90"
print(x + y) # 100-90 is printed
print(int(x) + int(y)) # 10 is printed
# F- String is an amazing magical formatting f
print(f"Your Fist Name is {First_name} and Last Name is {Last_name} and you are {age} old")
| true |
38322c01d2c410b06440fae9ce02faf2c8e045c4 | JamesPiggott/Python-Software-Engineering-Interview | /Sort/Insertionsort.py | 880 | 4.1875 | 4 | '''
Insertionsort.
This is the Python implementation of the Insertionsort sorting algorithm as it applies to an array of Integer values.
Running time: ?
Data movement: ?
@author James Piggott.
'''
import sys
import timeit
class Insertionsort(object):
def __init__(self):
print()
def insertionsort(self, unsorted):
for i in range(0, len(unsorted)):
for j in range(unsorted[i], 0, -1):
if unsorted[j] < unsorted[j - 1]:
swap = unsorted[j - 1]
unsorted[j - 1] = unsorted[j]
unsorted[j] = swap
def main():
unsorted = [7, 3, 8, 2, 1, 9, 4, 6, 5, 0]
insert = Insertionsort()
insert.insertionsort(unsorted)
print(unsorted)
if __name__ == "__main__":
# print(timeit.timeit("main()", setup="from __main__ import Insertionsort"))
main()
| true |
7a25d72e6a90603b908ec1e9d48f6c74c98d39b1 | ohveloper/python-alogorithm | /Inflearn/PreCourse/2depth_list.py | 309 | 4.125 | 4 |
a = [0] * 3
print(a)
# 2차원 list 만들기
b = [[0] * 3 for _ in range(3)]
print(b)
# 2차원 리스트 값에 접근
b[0][1] = 1
print(b)
b[1][2] = 2
print(b)
# 2차원 리스트를 표처럼 보이게 출력
for x in b:
print(x)
for x in b:
for y in x:
print(y, end=' ')
print() | false |
1bf9794ddf5f2cb1ef2c3c30725518fb8037e85e | ohveloper/python-alogorithm | /Inflearn/PreCourse/py_lambda.py | 308 | 4.1875 | 4 |
def plus_one(x):
return x+1
x = plus_one(1)
print(x)
# lambda 표현식으로 작성
plus_two = lambda x:x+2
print(plus_two(1))
# list와 map을 활용
a=[1,2,3]
print(list(map(plus_one,a)))
# list와 map에 lambda 활용
a=[1,2,3]
print(list(map(lambda x:x+2, a)))
print(list(map(int, ["1","2"]))) | false |
0c54a30b5564cf4fce07a4a22d90f2fee61fd27c | Caelifield/calculator-2 | /calculator.py | 1,170 | 4.21875 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# Replace this with your code
def calculator():
while True:
input_string = input('Enter string:')
token = input_string.split(' ')
oper = token[0]
try:
num1 = token[1]
except:
num1 = token[0]
try:
num2 = token[2]
except:
num2 = token[0]
#token is a list
if oper == 'q':
quit()
elif oper == "+":
print(add(int(num1),int(num2)))
elif oper == "-":
print(subtract(int(num1),int(num2)))
elif oper == "*":
print(multiply(int(num1),int(num2)))
elif oper == "/":
print(divide(int(num1), int(num2)))
elif oper == "square":
print(square(int(num1)))
elif oper == "cube":
print(cube(int(num1)))
elif oper == "pow":
print(power(int(num1),int(num2)))
elif oper == "mod":
print(mod(int(num1),int(num2)))
calculator() | true |
204462c7d2e433cbb38fd5d0d1942cda5303b939 | VIPULKAM/python-scripts-windows | /count_lines.py | 759 | 4.21875 | 4 |
file_path='c:\\Python\\pledge.txt'
def count_lines(handle):
'''
This function returns the line count in the file.
'''
offset = 0
for line in handle:
if line:
offset += 1
continue
return offset
def count_occurnace(handle, word):
'''
This function returns the word count in a given file
'''
count = 0
for line in handle:
if word in line:
count += 1
return word, count
with open(file_path) as f:
line_count = count_lines(f)
print(f"Total number of lines in '{file_path}':={line_count}")
with open(file_path) as f:
word_count = count_occurnace(f, "is")
count, word = word_count
print(f"For word \"{count}\" number of occurances are '{word}'") | true |
b6c9c3e78e9072babc666ddb7bf9a4e97bbbd0d6 | Telurt/python-fundamentos | /funcoes_primeira_classe_ordem.py | 935 | 4.4375 | 4 | """
Funções como objeto de primeira classe, são funçòes que se
comportam como qualquer tipo nativo de uma determinada linguagem
"""
def somar(a, b):
return a + b
def subtrair(a, b):
return a - b
# lista = [somar, subtrair]
# for funcao in lista:
# print(funcao(1,2))
# a = somar
# print(a(1,2))
"""
Funções de ordem superior são funções que recebem funções como
parâmetro(s) e/ou retornam funções como resposta
"""
carrinho_compras = [
{'produto': 'Fone de Ouvido', 'Preco': 500},
{'produto': 'Controle Xbox', 'Preco': 400},
{'produto': 'Celular', 'Preco': 800},
]
#print(carrinho_compras)
def calcular_desconto(lista, funcao):
total = 0
for produto in lista:
#print(produto['Preco'])
item_desconto = funcao(produto['Preco'], 10)
print(item_desconto)
total += item_desconto
print(f'total: {total}')
calcular_desconto(carrinho_compras, subtrair) | false |
854838cba4d9a2f2abddfb86bccd1237e9140a4c | jofro9/algorithms | /assignment1/question3.py | 2,458 | 4.1875 | 4 | # Joe Froelicher
# CSCI 3412 - Algorithms
# Dr. Mazen al Borno
# 9/8/2020
# Assignment 1
import math
# Question 3
class UnitCircle:
def __init__(self):
self.TARGET_AREA_ = 3.14
self.RADIUS_ = 1.
self.triangles_ = 4.
self.iter = 0
### member functions for use throughout code ###
# gamma function for pythagorean long side of right triangle formed by splitting the isosceles in half
def Gamma(self, alpha, beta):
return math.sqrt( (alpha ** 2) + (beta ** 2) )
# distance from centroid to the side calculated by gamma
def Altitude(self, gamma):
return math.sqrt( (self.RADIUS_ ** 2) - ((gamma / 2.) ** 2) )
# area of all of the isosceles trianlges for the current iteration,
# update the number of triangles for the next iteration
def TriangleArea(self, alpha, beta):
t_area = alpha * beta * self.triangles_
self.triangles_ *= 2
return t_area
def PrintTriangle(self, alpha, beta, gamma, area, altitude):
if self.iter == 0.:
triangles = 0
else:
triangles = self.triangles_
print(
"\nIteration #" + str(self.iter) + "\n" + "___________________________________\n"
"\nCurrent area: " + str(area) +
"\nNumber of triangles: " + str(int(triangles / 2)) +
"\nalpha: " + str(alpha) +
"\nbeta: " + str(beta) +
"\ngamma: " + str(gamma) +
"\naltitude: " + str(altitude)
)
self.iter += 1
# New unit Circle Object
unit_circle = UnitCircle()
### init values (0th iteration)
alpha = unit_circle.RADIUS_ * math.sqrt(2.) / 2. # straight distance to farthes inscribe geometry
beta = unit_circle.RADIUS_ - alpha
area = (2. * alpha) ** 2
gamma = 0.
altitude = 0.
unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude)
# 1st iteration, slightly different calculation than the rest
t_area = unit_circle.TriangleArea(alpha, beta)
area += t_area
gamma = unit_circle.Gamma(alpha, beta)
altitude = unit_circle.Altitude(gamma)
unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude)
while (unit_circle.TARGET_AREA_ - area) > 0.001:
beta = gamma / 2.
alpha = unit_circle.RADIUS_ - altitude
t_area = unit_circle.TriangleArea(alpha, beta)
area += t_area
gamma = unit_circle.Gamma(alpha, beta)
altitude = unit_circle.Altitude(gamma)
unit_circle.PrintTriangle(alpha, beta, gamma, area, altitude)
| true |
731beff49555f623448ce5cb13188586fa850201 | tabish606/python | /comp_list.py | 665 | 4.53125 | 5 | #list comprehension
#simple list example
#creat a list of squares
squares = []
for i in range(1,11):
squares.append(i**2)
print(squares)
#using list comprehension
squares1 = []
squares1 = [i**2 for i in range(1,11)]
print(squares1)
#NOTE : in list comprehension method the data is to be append in list is remeber and put in tha list with the loop conditons like above examples
#example2 print negative numbers
negative = [-i for i in range(1,11)]
print(negative)
#example 3 print first charcter of element
names = ['tabish', 'ansari','bigde', 'nawab']
first_char = [name[0] for name in names]
print(first_char)
| true |
077f37a82c31021b049710be0f385af0a202df8b | tabish606/python | /lamda.py | 610 | 4.15625 | 4 | #normal function
def add(a,b):
return a+b
print(add(4,3))
#lambda expression
add2 = lambda a,b : a+b #lambda function does not need name of function
print(add2(2,3))
multiply = lambda a,b : a*b
print(multiply(2,3))
# is even check
#def is_even(a):
# return a%2 == 0 #it return True if even else false
#print(is_even(8))
#print(is_even(9))
is_even2 = lambda a : a%2 == 0
print(is_even2(11))
print(is_even2(8))
#print last character
#def last_char(s):
# return s[-1]
#print(last_char("tabish"))
last_char2 = lambda s : s[-1]
print(last_char2("tabish")) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.