blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
54aafe26e9d3f45903d0034fc1acf73af72b25e0 | gfcharles/euler | /python/euler002.py | 624 | 3.734375 | 4 | """
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
"""
from common.euler_lib import fibonacci
from euler import euler_problem
@euler_problem()
def euler002(n: int | str) -> int:
return sum(val for _, val in fibonacci(seed=(1, 2), limit=int(n), filtering_by=is_even))
def is_even(x):
return x % 2 == 0
if __name__ == '__main__':
print(euler002(89))
print(euler002(4_000_000))
|
6466c540fe3fde11e8f4a646c6dcc5b5fb2d749a | lakshmick96/python-practice-book | /chapter_5/problem3.py | 392 | 3.796875 | 4 | #Write a function findfiles that recursively descends the directory tree for the specified directory and generates paths of all the files in the tree.
import os
def findfiles(dir_name):
for root, directories, filenames in os.walk(dir_name):
for filename in filenames:
print os.path.join(root,filename)
findfiles('/home/lakshmi/Documents')
|
9495ea5606cf06c11b83ca8e3887549a61ba44e8 | josemorenodf/ejerciciospython | /Bucle for/BucleFor7.py | 208 | 3.6875 | 4 | '''
En vez de una lista, se puede escribir una cadena, en cuyo caso la variable de control va tomando como valor cada uno de los caracteres
'''
for i in "AMIGO":
print(f"Dame una {i}")
print("¡AMIGO!") |
32d194c845a0f20fbd6e23f8bf977aae51173a30 | TigerKing-Cser/Person-Learning | /bicycles.py | 874 | 4.21875 | 4 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# 访问列表元素
print(bicycles[0])
print(bicycles[0].title())
# 修改元素列表
bicycles[0] = bicycles[0].title()
print(bicycles)
# 在列表中添加元素
## 在列表尾部添加元素
bicycles.append('ducati')
print(bicycles)
## 在列表插入元素
bicycles.insert(0, 'ducati')
print(bicycles)
# 从列表中删除元素
## 从列表中删除元素
del bicycles[0]
print(bicycles)
## 从列表尾部删除元素
pop_elm = bicycles.pop()
print(pop_elm)
print(bicycles)
## 根据值删除元素
bicycles.remove('cannondale')
print(bicycles)
# 使用sort对列表进行排序
arr = [10,9,8,7,6,5,4,3,2,1]
arr.sort()
print(arr)
arr.sort(reverse = True)
print(arr)
# 反转序列
bicycles.reverse()
print(bicycles)
# 查看序列长度
print(f'bicycles length: {len(bicycles)}')
|
95df35be127e3dabcaffd48320970ff72b7491bb | Yihang-Chen/data-structure-and-algorithm-in-python | /ch5栈和队列/后缀表达式求值.py | 813 | 3.546875 | 4 | from sstack import SStack
def suffix_exp_evaluation(line):
exp = line.split(' ')
operators = '+-*/'
st = SStack()
for x in exp:
if x not in operators:
st.push(float(x))
continue
if st.depth() < 2:
raise SyntaxError('操作数错误!')
b = st.pop()
a = st.pop()
if x == '+':
c = a + b
elif x == '-':
c = a - b
elif x == '*':
c = a * b
elif x == '/':
c = a / b
st.push(c)
if st.depth() != 1:
raise SyntaxError("操作数错误")
else:
return st.pop()
#------------------------------------------
if __name__ == "__main__":
print("Start testing.")
print(suffix_exp_evaluation('3 5 - 6 17 4 * + * 3 /')) |
370dcf1952b70c037d0d50bfdb2b91cc51be4559 | chandraharsha4807/PYTHON--CODING-PROBLEMS | /ORDER-MATRIX.py | 683 | 3.78125 | 4 |
n = input().split(" ")
rows = int(n[0])
col = int(n[1])
matrix = []
for i in range(0, rows):
matrix.append(sorted([int(col) for col in input().split()]))
#print((matrix))
# Create an empty list to store matrix values
temp = []
for i in range (rows):
for j in range(col):
temp.append(matrix[i][j])
#print(sorted(temp))
temp.sort()
# coping elements in temp to matrix[i][j]
k = 0
for i in range(rows):
for j in range(col):
matrix[i][j] = temp[k]
k += 1
#print(matrix)
for i in range(rows):
for j in range(col):
print(matrix[i][j], end = " ")
print(" ")
'''
3 3
1 20 3
30 10 2
5 11 15
1 2 3
5 10 11
15 20 30
''' |
0d494812b22df4244b0623c32e146a01063fdf8f | kayyali18/Python | /Python 31 Programs/Ch 10/Simple_GUI.py | 303 | 3.609375 | 4 | # Simple GUI
# Demonstrates creating a window
from tkinter import *
# create a root window
root = Tk ()
# modify the window
root.title ("Simple GUI") # sets the name of the title
root.geometry ("300x200") # sets the size in pixels
# kick off the window's event loop
root.mainloop ()
|
31d6ba8177c826d677088e31fb9bbcc34e70ae42 | mila-orishchuk/pythoncourse | /Lesson4/task6.py | 1,182 | 3.859375 | 4 |
'''
tasks
'''
number = int(input('Enter number: '))
for i in range(number):
if not i % 18 == 0 and not (50 <= i <= 80):
if i == 42:
print('Потому что')
else:
print(i)
'''
'''
attempts = 0
max_number = None
while attempts != 5:
user_input = input('Enter numbers: ')
if user_input.isnumeric():
if not max_number or max_number < int(user_input):
max_number = int(user_input)
attempts += 1
elif user_input.lower() == 'q':
break
else:
print('Invalid enter. Try again.')
continue
print(max_number)
'''
'''
def math_equ():
arguments = ['operand1', 'operator', 'operator2']
while True:
expression = []
for i in arguments:
userInput = (input (f'Enter {i}: '))
expression.append(userInput)
if userInput.lower() == 'q':
return
if expression[1] == '+':
print(int(expression[0]) + int(expression[2]))
elif expression[1] == '-':
print(int(expression[0]) - int(expression[2]))
else:
print('invalid operator')
math_equ() |
0334565f8ffd638b8a6e551c58247cdbbc8ff163 | mike6321/dataStructure_algorithm | /Homework04/Problem05.py | 1,305 | 3.734375 | 4 | class ArrayQueue:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def enqueue(self, item):
self.data.append(item)
def dequeue(self):
return self.data.pop(0)
def peek(self):
return self.data[0]
class Node:
def __init__(self, item):
self.data = item
self.left = None
self.right = None
class BinaryTree:
def __init__(self, r):
self.root = r
def bft(self):
q = ArrayQueue()
trav = []
#1. q에 루트를 add
if self.root:
q.enqueue(self.root)
#2. q가 빌때까지 루트를 돈다.
while not q.isEmpty():
#3. 들어있는 큐 빼기
node = q.dequeue()
#4. 뺀 큐 순회 배열에 append
trav.append(node.data)
#양방향이기때문에 왼,오 나누어 큐에 집에 넣기
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
#이러한 식으로 계속 넣다뺏다들 반복한다음 큐가 들어있지 않다면 리턴한다. [거의 공식]
return trav
def solution(x):
return 0 |
71aeae28f1a7fcc850f4e2ceff800eade8918c01 | aayushipriya03/Hacktober20fest21 | /Python/01_variable.py | 261 | 3.5625 | 4 | a_122 = '''harry'''
# a = 'harry'
# a = "harry"
b = 345
c = 45.32
d = True
# d = None
# Printing the variables
print(a)
print(b)
print(c)
print(d)
# Printing the type of variables
print(type(a))
print(type(b))
print(type(c))
print(type(d))
|
2953b7a18f8fee8ec3ca2b0bf7b5bb15ee5b4a29 | Tebazil12/advent-of-code2020 | /day6.py | 539 | 3.578125 | 4 | with open("input-day6", 'r') as f:
num_yeses = 0
current_answer = ''
for i, line in enumerate(f):
# print(i)
if line == '\n':
#stop and prcoess
list_answer = list(current_answer)
set_answer = set(list_answer)
num_yeses = num_yeses + len(set_answer)
# print(f"{list_answer} {set_answer} {len(set_answer)}")
current_answer = ''
else:
current_answer = current_answer + line.strip()
print(f"Num valid = {num_yeses}")
|
7260c27e17c2decc78c8f6c3cd09b021a3ecf7b6 | rajagoah/Python-Importing-From-Web | /ImportingFromWebExercise8.py | 520 | 3.625 | 4 | import requests
from bs4 import BeautifulSoup
#storing url in variable
url = 'https://www.python.org/~guido/'
#packaging, sending and receiving the response
r = requests.get(url)
#html_doc storing the html in text
html_doc = r.text
#converting to beauitfulsoup object
soup = BeautifulSoup(html_doc)
#finding all the tags 'a' to idenitfy the urls in hyperlinks
a_tags = soup.find_all('a')
#enumerating over the a_tags variable to extract the links within the href tag
for link in a_tags:
print(link.get('href')) |
04653c5b85ddf440a2af9f4e475231f4715de36a | guoyuantao/Data_Structure_and_Algorithm | /Stack/括号匹配.py | 1,341 | 4.125 | 4 | """
在数学运算中,括号需要是匹配的。编写程序判断括号是否匹配。
思路:
1. 初始化一个空栈
2. 遍历括号,如果是左括号,入栈
3. 如果是右括号,如果栈顶元素是左括号,则出栈,消去。
4. 当右括号仍存在,栈以空。或者栈不空,右括号扔存在。则不匹配。
"""
from Stack.stack import Stack
def parChecker(symbolString):
"""
简单括号是否匹配
:param symbolString: 括号字符串
:return: bool型,匹配:True,不匹配:False
"""
# 初始化一个栈
s = Stack()
# 是否匹配标志
balanced = True
# 下标
index = 0
# 遍历
while index < len(symbolString) and balanced:
# 取出字符
symbol = symbolString[index]
# 如果为左括号,则入栈
if symbol == '(':
s.push(symbol)
else:
# 当字符不为左括号,如果栈为空,则不匹配
if s.isEmpty():
balanced = False
# 如果栈不空,则将左括号出栈
else:
s.pop()
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
test_str1 = '((()))'
test_str2 = '((())'
print(parChecker(test_str1))
print(parChecker(test_str2))
|
c6329ee5c657d050856c8ae5e9e642f3084e56be | TobiasDemoor/LeetCode | /leet.932.py | 499 | 3.5 | 4 | from typing import List
class Solution(object):
def beautifulArray(self, n: int) -> List[int]:
ans = [1]
while len(ans) < n:
tmp1 = []
tmp2 = []
for i in ans:
aux = i*2-1
if aux <= n:
tmp1.append(aux)
aux = i*2
if aux <= n:
tmp2.append(aux)
ans = tmp1 + tmp2
return ans
sol = Solution()
print(sol.beautifulArray(4))
|
2c94cc3fd735f8a01cf08b39e27cf3278c6e06cb | hbagaria4998/Forsk2019 | /Day1/handson.py | 160 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 18:18:13 2019
@author: hbagaria
"""
num = 1
while num<1:
print(num)
num += 1
|
7e9f5c4c7cdd5987533b98ceeee635891ad05406 | woskar/automation | /gui/mouseNow.py | 1,782 | 4.3125 | 4 | #! usr/bin/env python3
# mouseNow.py - Displays the mouse cursor's current position.
'''
Project: Where is the mouse right now?
Being able to determine the mouse position is an important part of setting up
your GUI automation scripts. But it’s almost impossible to figure out the exact
coordinates of a pixel just by looking at the screen. It would be handy to have
a program that constantly displays the x- and y-coordinates of the mouse cursor
as you move it around.
At a high level, here’s what your program should do:
Display the current x- and y-coordinates of the mouse cursor.
Update these coordinates as the mouse moves around the screen.
This means your code will need to do the following:
Call the position() function to fetch the current coordinates.
Erase the previously printed coordinates by printing \b backspace characters to the screen.
Handle the KeyboardInterrupt exception so the user can press CTRL-C to quit.
'''
import pyautogui
print('Press Ctrl-C to quit.')
try:
while True:
# Get and print the mouse coordinates.
x,y = pyautogui.position()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
'''
# include for additional color information
pixelColor = pyautogui.screenshot().getpixel((x, y))
positionStr += ' RGB: (' + str(pixelColor[0]).rjust(3)
positionStr += ', ' + str(pixelColor[1]).rjust(3)
positionStr += ', ' + str(pixelColor[2]).rjust(3)
positionStr += ', ' + str(pixelColor[3]).rjust(3) + ')'
'''
print(positionStr, end='')
# \b erases the last printed character of the current line, doesn't go beyond \n
print('\b' * len(positionStr), end='', flush=True)
except KeyboardInterrupt:
print('\nDone.')
|
aea2dc100c814bfe2fec5828286a59c8ece4efa6 | tawanchaiii/01204111_63 | /ELAB06/lab06_05.py | 629 | 3.90625 | 4 | def mul_matrix(A,B) :
result = list()
m = len(A)
n = len(B[0])
for i in range(m):
b = []
for j in range(n):
b.append(0)
result.append(b)
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
return result
def print_matrix(A):
for i in range(len(A)):
for j in range(len(A[i])):
print(f'{A[i][j]:^6}', end = ' ')
print()
A = [[1,2,3],[4,5,6],[7,8,9]]
B = [[22,13,23],[54,43,21],[23,78,71]]
x = mul_matrix(A,B)
print_matrix(x) |
4b3bf86aac25fb535b63c6a5871a55476eb3d991 | sutt/ppd | /scratch/scratch4.py | 3,164 | 3.734375 | 4 | """
==================
Animated histogram
==================
This example shows how to use a path patch to draw a bunch of
rectangles for an animated histogram.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
import random, time
def setup_fig(**kwargs):
fig, ax = plt.subplots(1,kwargs.get('j', 1))
return fig, ax
def setup_hist(fig, ax,):
#fig, ax = plt.subplots(1,3)
# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
# here comes the tricky part -- we have to set up the vertex and path
# codes arrays using moveto, lineto and closepoly
# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
# CLOSEPOLY; the vert for the closepoly is ignored but we still need
# it to keep the codes aligned with the vertices
nverts = nrects*(1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
return ax, top, bottom, n, verts, patch
def main():
def animate_j(j):
# simulate new data coming in
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top[j] = bottom[j] + n
verts[j][1::5, 1] = top[j]
verts[j][2::5, 1] = top[j]
return [patch[j], ]
N = 3
fig, ax = setup_fig(j = N)
data = []
print 'SHOW THAT WE ONLY COME THRU HERE ONCE.'
# INIT GLOBALS
top = [None]*N
bottom = [None]*N
n = [None]*N
verts = [None]*N
patch = [None]*N
# SET GLOBALS FIRST TIME
for h in range(N):
ret = setup_hist(fig,ax[h])
ax[h] = ret[0]
top[h] = ret[1]
bottom[h] = ret[2]
n[h] = ret[3]
verts[h] = ret[4]
patch[h] = ret[5]
def animate_j_wrapper(i,fargs):
j = random.randint(0,N-1)
return animate_j(j)
print 'GOING INTO LOOP'
inp = 1
ani = animation.FuncAnimation(fig, animate_j_wrapper
,100
, repeat=False, blit=True)
plt.show(False) #neccesary for showing changes
print 'DONE, RETURNING FROM MAIN'
return ani
if __name__ == "__main__":
main()
#plt.show(False)
time.sleep(5)
#plt.show()
|
4429334f3bd2d9236096b12d7048d6a13f9637da | DinaShaim/GB_Algorithms_data_structures | /Les_1_HomeWork/les_1_task_1.py | 500 | 4.25 | 4 | #Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
print('Введите целое трехзначное число')
x = int(input('Число = '))
S = x % 10 + x // 10 % 10 + x // 100
P = (x % 10) * ((x // 10) % 10) * (x // 100)
print(f'Сумма чисел введенного числа = {S}')
print(f'Произведение чисел введенного числа = {P}') |
4cd5d9c893f28033e15b34b4d09e3e0660ee3dd8 | JoseJunior23/Iniciando-Python | /aprendendo_python/ex012.py | 394 | 3.625 | 4 | # leia o preço de um produto e mostre seu novo preço com 5% de desconto
i = (' Calcula desconto ')
print('{:-^175}'.format(i))
pr = float(input(' Entre com o valor do poduto : '))
des = pr * 0.05
vf = pr - des
print(' O valor inicial do produto é de ${}, com o descconto de 5% você pagará ${}.'.format(pr,vf))
f = (' Fim do Calcula Desconto ')
print('{:-^175}'.format(f)) |
db671c189b475b57cc425436c6f0850a7ac50b6a | shieh08/projeuler | /p003_largest_prime_factor.py | 698 | 3.984375 | 4 | # projecteuler.net/problem=3
# What is the largest prime factor of the number 600851475143
# Function to figure out prime or not.
def is_prime(n):
if n < 2:
return False
# Eliminate even numbers.
if not n & 1:
return False
# Check for each odd number up to sqrt of n.
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
# Set the target number here.
target_number = 600851475143
x = 1
while target_number > 1:
x += 1
# Check to see if x is a factor of target_number.
if target_number%x == 0:
if is_prime(x):
# Divide number by prime number to find other prime factors.
target_number = target_number/x
print(x)
|
5c736dcb9f246efb06097f218bec5bedf72334f9 | RaghavNitish/Unscramble-Computer-Science-Problems | /Task4.py | 1,340 | 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 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.
"""
total_list = []
#Creating a total set of calling phone numbers
for element in calls:
if element[0] not in total_list:
total_list.append(element[0])
#Removing the phone numbers from texts
for element1 in texts:
for i in range(2):
if element1[i] in total_list:
total_list.remove(element1[i])
#Removing the receiving phone numbers
for element2 in calls:
if element2[1] in total_list:
total_list.remove(element2[1])
#Printing in lexicographic order
total_list = sorted(total_list)
print("These numbers could be telemarketers: ")
for element3 in total_list:
print(element3)
|
386a47aebb998286008f42e0ea90f79789f1ad07 | Yengwa/PiPractice- | /dim.py | 893 | 3.5 | 4 | from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
button1=16
button2=12
LED1=22
LED2=18
GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(button2,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(LED1,GPIO.OUT)
GPIO.setup(LED2,GPIO.OUT)
pwm1=GPIO.PWM(LED1,1000)
pwm2=GPIO.PWM(LED2,1000)
pwm1.start(0)
pwm2.start(0)
bright=1
while(1):
if GPIO.input(button1)==0:
print "Button 1 was Pressed"
bright=bright/1.25
pwm1.ChangeDutyCycle(bright)
pwm2.ChangeDutyCycle(bright)
sleep(.25)
print "Your brightness is:" ,bright
if GPIO.input(button2)==0:
print "Button 2 was Pressed"
bright=bright*1.25
if bright=bright>100:
bright=100
print "You are at full brightness"
pwm1.ChangeDutyCycle(bright)
pwm2.ChangeDutyCycle(bright)
sleep(.25)
print "Your brightness is:" ,bright |
f697903eb75f728ebc9622ab8abe89234caf765a | cjb5799/DSC510Fall2020 | /THEOBALD_DSC510/THEOBALD_DSC510_Assignment 6.1.py | 1,434 | 4.4375 | 4 | #DSC510
#Week 6
#Programming Assignment Week 6
#Author Ammy Theobald
#10/11/2020
#Change#:1
#Change(s) Made: Initial Program
#Date of Change: 10/11/2020
#Author: Ammy Theobald
#Change Approved by: N/A
#Date Moved to Production: 10/11/2020
#Initial Greeting
name = input('What is your Name? \n')
print('Hello %s! Welcome to my Temperature Program!'%name)
#List Creation and Input
temperatures = [] #Empty List for Temperatures
stop_value = 999
print('')
print('Please enter your list of temperatures one at a time. Once finished, please enter 999.')
while True:
try:
user_input = float(input())
except ValueError:
print('Oops!!! You must enter a number. Try again.')
continue
if user_input == stop_value: #Finish program if stop_value is entered
break
temperatures.append(user_input) #Add user input to list if not the stop_value
minTemperature = min(temperatures) #Identify Min Temp
maxTemperature = max(temperatures) #Identify Min Temp
countTemp = len(temperatures) #Count number of Temps Entered
#Provide User with Output Results
print('')
print('The number of temperatures you entered was %d.' %countTemp)
print('')
print('The hottest (largest) temperature is %d. The coldest (smallest) temperature is %d.' %(maxTemperature, minTemperature))
print('')
print('Thank you for using my fun little Temperature Program. Have a nice day, %s!' %name)
|
6a368d826715b3d9ce69d0b9484abd57c1076a0d | lyvius2/python-dataAnalytics | /util.py | 167 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def sum_func(*args):
sum =0
for i in args:
sum += 1
return sum
def echo_func(say):
return "You said {0}".format(say) |
eeeb9f609eac475e12358c06d008dec07dec0073 | santoshjoshigithub/spark | /rdd/average_friends_by_age/average_friends_by_age.py | 2,204 | 3.65625 | 4 | # Problem: There is a file having fields as <id, name, age, num_of_friends). Write a spark program to find the averge number of friends for any given age.
# following modules are used to run spark in local windows.
import findspark
findspark.init()
findspark.find()
import pyspark
# import required modules for Spark to execute.
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("AvgNumOfFriendsByAge")
sc = SparkContext(conf=conf)
# following function wil extract the required fields from each row from the imported file in the RDD.
def parseRow(row):
fields = row.split(',')
age = int(fields[2])
num_of_friends = int(fields[3])
return (age, num_of_friends)
#get data from the file and store in a row RDD.
row = sc.textFile("C:/SparkCourse/fakefriends.csv")
# parse each row and extract the key value pair ithe age_friends RDD (age, number_of_friends)
age_friends = row.map(parseRow)
# for each row, first apply mapValues on each row and then reduceByKey
# mapValues - Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD’s partitioning.
# reduceByKey - reduceByKey(func, numPartitions=None, partitionFunc=<function portable_hash>)[source]
# Merge the values for each key using an associative and commutative reduce function.
# This will also perform the merging locally on each mapper before sending results to a reducer, similarly to a “combiner” in MapReduce.
# Output will be partitioned with numPartitions partitions, or the default parallelism level if numPartitions is not specified. Default partitioner is hash-partition.
totals_by_age = age_friends.mapValues(lambda x: (x,1)).reduceByKey(lambda x,y: (x[0]+y[0],x[1]+y[1]))
# Note: in the above example, reduceByKey will keep adding all the values of a particular key until all of the records pertaining to that key are processed.
#Important: reduceByKey is faster as it will not create new partitions.
average_by_age = totals_by_age.mapValues(lambda x: x[0] / x[1])
final_result = average_by_age.collect()
for result in final_result:
print(result)
|
2e8b138685cb7f1359ade25633553e09bc1805d1 | freelifedev/Course_Module1 | /drawing.py | 2,496 | 3.796875 | 4 | # import the necessary packages
import numpy as np
import cv2
# initialize our canvas as a 300*300 with 3 channels, Red, Green,
# and Blue, with a black background
canvas = np.zeros((800,1300,3), dtype="uint8")
#draw a gren line from the top-left corner of our canvas to the
# bottom-right
green = (0,255,0)
cv2.line(canvas, (0,0), (300,300), green)
cv2.imshow("Canvas", canvas)
# cv2.waitKey()
# now, draw a 3 pixel thick red lne from the top-right corner to the
# bottom-left
red = (0,0,255)
cv2.line(canvas, (300,0), (0,300), red,3)
cv2.imshow("Canvas", canvas)
# cv2.waitKey()
# draw a green 50*0 pixel square , starting at 10*10 and ending a 60*60
cv2.rectangle(canvas, (10, 10), (60,60), green)
cv2.imshow("Canvas",canvas)
# cv2.waitKey(0)
# draw another rectangle , this time we'll make it red and 5 pixels thick
cv2.rectangle(canvas, (50,200), (200,225), red , 5)
cv2.imshow("Canvas", canvas)
# cv2.waitKey(0)
# let's draw one last rectangle: blue and filled in
blue = (255,0,0)
cv2.rectangle(canvas, (200,50), (225,125), blue, -1)
cv2.imshow("Canvas", canvas)
# cv2.waitKey(0)
# reset our canvas and draw a white circle at the center of the canvas with
# increasing redii - from 25 pixels to 150 pixels
canvas = np.zeros((800, 300, 3), dtype="uint8")
(centerX, centerY) =(canvas.shape[1] /2, canvas.shape[0] /2)
white = (255, 255, 255)
for r in xrange(0,175,25):
cv2.circle(canvas, (centerX, centerY), r, white)
# show our work of art
cv2.imshow("Canvas", canvas)
# cv2.waitKey(0)
# let's go crazy and draw 25 random circles
for i in xrange(0,25):
# randomly generate a radius size between 5 and 200, generate a random
# color, and then pck a random point on ou canvas where the circle
# will be drawn
radius = np.random.randint(5, high=200)
color = np.random.randint(0, high=256, size=(3,)).tolist()
pt = np.random.randint(0, high=300, size=(2,))
# draw our random circle
cv2.circle(canvas, tuple(pt), radius, color, -1)
# show our materpiece
cv2.imshow("Canvas", canvas)
# cv2.waitKey(0)
# load the image of Adrian n Folorida
image = cv2.imread('florida_trip.jpg')
# draw a circle around my face, two filled in circles covering my ecyes, and
# a rectangle surrounding my mouth
cv2.circle(image, (168,188), 90, (0,0,255), 2)
cv2.circle(image, (150,164), 10 , (0,0,255), -1)
cv2.circle(image, (192,174), 10, (0,0,255), -1)
cv2.rectangle(image, (134,200), (186,218), (0,0,25), -1)
# show the output image
cv2.imshow('Output', image)
cv2.waitKey(0) |
4ec3bf7422420cbdef2184c20c35a66196421ca6 | leyap/python3-tutorial | /Python3Tutorial/digit.py | 93 | 3.8125 | 4 | a = 2
b = 3
print(a+b)
print(a*b)
#a^3
print(a**b)
print("0.1 + 0.2 = ")
print(0.1+0.2)
|
b4d635fea395532940c9b15530794d91195cb5d7 | AshBesada/Grocery-List | /IT-140-grocery_list.py | 1,956 | 4.1875 | 4 | # Create a dictionary
grocery_item = {}
# Create a list
grocery_history = []
# Variable used to check if the while loop condition is met
stop = False
# A while loop
# Initializes the list and asks the user for commands until he/she types 'q'.
while not stop:
# Accept input of the name of the grocery item purchased.
name = input('Item name:\n')
# Accept input of the quantity of the grocery item purchased.
quantity = input('Quantity purchased:\n') # Modifying values
# Accept input of the cost of the grocery item input (this is a per-item cost).
cost = input('Price per item:\n')
# Using the update function to create a dictionary entry which contains the name, number and price entered by the user.
# Adding key-value pairs
grocery_item = {'item_name': name, 'quantity': int(
quantity), 'cost': float(cost)}
# Add the grocery_item to the grocery_history list using the append function
# Adding data to a list
grocery_history.append(grocery_item)
# Accept input from the user asking if they have finished entering grocery items.
response = input(
'Would you like to enter another item?\nType \'c\' for continue or \'q\' to quit:\n')
if response == 'q':
stop = True
# Define variable to hold grand total called 'grand_total'
grand_total = float(0.00)
# Define a 'for' loop.
# index-based range loop
for item in grocery_history: # Accessing values in a list
# Calculate the total cost for the grocery_item.
item_total = item['quantity'] * item['cost']
# Add the item_total to the grand_total
grand_total += float(item_total)
print("%d %s @ $%.2f ea $%.2f" %
(item['quantity'], item['item_name'], item['cost'], item_total))
# Reset item_total
item_total = 0
# Print the grand total
print("Grand total: $%.2f" % grand_total)
# Pause program on screen until user hit the enter key.
input("Press \"Enter\" to close") |
3327157790815fc578cbfadf18c07c6a0f19b917 | jnhro1/CS_python | /민성,지훈/p57.py | 479 | 3.890625 | 4 | """
p57.py
정수 2개를 입력받아서 큰 수와 작은 수를 출력하는 프로그램
정수를 입력하세요 : 5
정수를 입력하세요 : 10
큰 수 : 10 작은 수 : 5
"""
num1 = int(input("정수를 입력하세요"))
num2 = int(input("정수를 입력하세요"))
if num1 == num2:
print("두 수가 같습니다")
elif num1 > num2:
print("큰 수 : %d 작은 수 : %d" %(num1,num2))
elif num1 < num2:
print("큰 수 : %d 작은 수 : %d" %(num2,num1)) |
037c65f101fd66bd312ab2283d77b7b5414edd5b | EuroPython/ep-tools | /eptools/finaid/fetch.py | 1,755 | 3.5625 | 4 |
"""
Functions to get the data Financial Aid submissions.
"""
from .data import finaid_submission_hdr
from ..gspread_utils import get_ws_data, find_one_row
def get_finaid_ws_data(api_key_file, doc_key, file_header=finaid_submission_hdr):
""" Return the content of the Google Drive spreadsheet
indicated by `doc_key`. `api_key_file` is the authentication
file needed to access the document.
The header of the data will be changed by `file_header`.
Be careful because this header must be known to other functions here.
Parameters
----------
api_key_file: str
Path to the Google credentials json file.
doc_key: str
Key for the document URL
file_header: list of str
List of ordered column names to rename the header of the spreadsheet
data.
Returns
-------
ws_data: pandas.DataFrame
"""
return get_ws_data(api_key_file, doc_key, ws_tab_idx=0, header=file_header, start_row=1)
def get_applicant(applicant_name, submissions, col_name="full_name"):
""" Return a dict with the data of the applicant given his/her name
and the content of the submissions form responses spreadsheet.
Parameters
----------
applicant_name: str
This value will be used to search in the `col_name` of
`finaid_ws_data`.
This function looks for any cell with a `lower`-ed string
that containts the `lower`-ed `applicant_name`.
submissions: pandas.DataFrame
Content of the submissions form responses spreadsheet.
col_name: str
Name of the column that holds the name of the applicants.
Returns
-------
applicant: dict
"""
return find_one_row(applicant_name, submissions, col_name=col_name)
|
510a5e9411d40ed05f1c344d34fd02fdd539ffaf | anjoy92/TwitterDataAnalytics | /Chapter4/centrality/SimpleGraph.py | 2,924 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Creates a simple retweeted graph network from the json file provided.
__author__ = "Shobhit Sharma"
__copyright__ = "TweetTracker. Copyright (c) Arizona Board of Regents on behalf of Arizona State University"
"""
import argparse
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(""))))
from Chapter4.centrality.TweetToGraph import TweetToGraph
import networkx as nx
import matplotlib.pyplot as plt
def main(args):
ttg = TweetToGraph()
parser = argparse.ArgumentParser(
description='''Creates a simple retweeted graph network from the json file provided. ''',
epilog="""TweetTracker. Copyright (c) Arizona Board of Regents on behalf of Arizona State University\n@author Shobhit Sharma""",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', nargs="?", default="../simplegraph.json",
help='Name of the input file containing tweets')
argsi = parser.parse_args()
# Get the input file name containing tweets from the command line argument
infile_name = argsi.i
# Create the tweet network using Networkx library from the tweet file mentioned
ttg.create_retweet_network(infile_name)
# Print the Network generated.
print ttg.graph
G = ttg.graph
nodes = {}
# Traverse the full network and create a nodes dictionary having key as the node name
# and value as the number of times it has occurred in the network.
# We are doing this to assign the size of the node according to its weight/occurrence
for (u, v, d) in G.edges(data=True):
print u, v, d
if u in nodes.keys():
if 'weight' in d.keys():
nodes[u] += d['weight']
else:
nodes[u] += 1
else:
if 'weight' in d.keys():
nodes[u] = d['weight']
else:
nodes[u] = 1
if v in nodes.keys():
if 'weight' in d.keys():
nodes[v] += d['weight']
else:
nodes[v] += 1
else:
if 'weight' in d.keys():
nodes[v] = d['weight']
else:
nodes[v] = 1
# Copy the nodes values/weights to the weights list
weights = [int(nodes[i]) for i in nodes]
# This creates the visualization network using spring layout and returns the position(x,y) of each node
pos = nx.spring_layout(G)
# Normalize the weights to create a good visualization. Also increase the value of 1000 to get bigger sized nodes.
normalized = [float(i) * 1000 / sum(weights) for i in weights]
# Draw the network using the matplotlib library. Networkx uses it internally.
nx.draw_networkx(G, pos, nodelist=nodes.keys(), node_size=normalized)
# Show the plotted network graph
plt.show()
if __name__ == "__main__":
main(sys.argv[1:])
|
ec029bd51cab77fd7f4ba6393825ed5f2aac2564 | preetiduhan/DataStructuresInPython | /ConstructUniqueBSTs.py | 1,000 | 3.546875 | 4 | class Solution(object):
def generateTrees(self, n):
if n==0:
return []
nums = [i for i in range(1,n+1)]
#given a list of nodes, gives UBST list for it
def treeList(L):
res = []
if L==[]:
return [None]
if len(L)==1:
l = [TreeNode(L[0])]
return l
#for each i, taking L[i] as root
for i in range(len(L)):
lessThanRoot = L[:i]
greaterThanRoot = L[i+1:]
leftNodesList = treeList(lessThanRoot)
rightNodesList = treeList(greaterThanRoot)
for t1 in leftNodesList:
for t2 in rightNodesList:
root = TreeNode( L[i] )
root.left = t1
root.right = t2
res.append(root)
return res
R = treeList(nums)
return R
|
f86f9259027249afabeec3bd43803eb45914d4bd | saurabhgupta2104/Coding_solutions | /LeetCode/Delete_Nodes_And_Return_Forest.py | 1,970 | 4.03125 | 4 | # https://leetcode.com/problems/delete-nodes-and-return-forest/
"""
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Constraints:
The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def travel(r, d, l, i):
if r is None:
return l
if l[i] == [] and r.val not in d:
l[i].append(r)
if r.val in d:
if r.left is not None:
l = travel(r.left, d, l+[[]], len(l))
if r.left.val in d:
r.left = None
if r.right is not None:
l = travel(r.right, d, l+[[]], len(l))
if r.right.val in d:
r.right = None
else:
if r.left is not None:
l = travel(r.left, d, l, i)
if r.left.val in d:
r.left = None
if r.right is not None:
l = travel(r.right, d, l, i)
if r.right.val in d:
r.right = None
return l
class Solution:
def delNodes(self, r: TreeNode, de: List[int]) -> List[TreeNode]:
d = set()
for i in de:
d.add(i)
if r is None:
return []
l = [[]]
l = travel(r, d, l, 0)
ans = []
for i in l:
if i:
ans.append(i[0])
return ans
|
8eefae95b9d0ace2c0adc9f8d69f9030c168d62c | xhaatemx/py4e-my-solutions | /file extract/extractCommonHours.py | 470 | 3.59375 | 4 | hours = []
common = {}
name = input("Enter file:")
if len(name) < 1 : name = "1.txt"
file = open(name)
# extract Senders Data
for line in file:
if not line.startswith('From '): continue
line = line.strip('From ').split()
# add each hour into a list
hours.append(line[4][: line[4].index(':')])
for h in hours:
if h not in common.keys(): common[h] = 1
else: common[h] += 1
common = dict(list(sorted(common.items())))
for (k, v) in common.items():
print(k, v)
|
93763cea8dcaf62a26d630652dca25e078cd8de6 | ronething/python-async | /async_overview/06/an_error.py | 522 | 4.125 | 4 | # -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
尽量不要传可变参数 list 可以被改变 因为是指针
"""
def add(a, b):
"""
+=背后的魔法方法是__iadd__
+背后的魔法方法是__add__
a = a + b 两者不同 += 直接修改本身 + 则是新声明一个 左边 a 和右边 a 无直接联系
"""
a += b
return a
a = 1
b = 2
c = add(a, b)
print(c) # 3
print(a, b) # 1 2
a = [1, 2, 3]
b = [4]
c = add(a, b)
print(c) # [1, 2, 3, 4]
print(a, b) # [1, 2, 3, 4] [4]
|
b2b24e7a88647b7b7fd39867e0e8f516a69a545b | cleo-guerra/Curso-Python-Essentials-C6 | /15_except_taller_GuerraCleopatra.py | 560 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 6 19:12:54 2021
@author: DELL
"""
def validarNumero(prompt, min, max):
while(True):
try:
print("ingrese un valor entre",min,"y",max)
x = int(input(prompt))
assert x >= min and x <=max
return x
except ValueError:
print('ingrese solo numeros')
except:
print("error, el valor debe estar dentro del rango")
v = validarNumero("ingrese un valor en el rango", -100,100)
print("el numero es: ", v) |
056ee794f68bdca3418da1347b3c1f2ad87ee65e | gregschmit/django-impression | /impression/tests/test_email_address.py | 914 | 3.515625 | 4 | """
This module is for testing the email address model.
"""
from django.test import TestCase
from ..models import EmailAddress
class EmailAddressTestCase(TestCase):
def test_constructor_properties(self):
"""
Test the custom constructor classmethod, ``get_or_create``.
"""
email = EmailAddress.get_or_create("[email protected]")[0]
self.assertEqual(email.email_address, "[email protected]")
def test_extract_display_email(self):
s = '"John C. Doe" <[email protected]>'
e = "[email protected]"
email = EmailAddress.extract_display_email(s)
self.assertEqual(email, e)
def test_email_case(self):
"""
Test that our constructor considers emails as case-insensitive.
"""
upper_email1 = EmailAddress.get_or_create("[email protected]")[0]
upper_email2 = EmailAddress.get_or_create("[email protected]")[0]
self.assertEqual(upper_email1, upper_email2)
|
67f1f5108aa05777390f11328fd1acfa0079930c | yangzongwu/leetcode | /archives/interview-prepare/amazon/The Maze.py | 3,428 | 4.4375 | 4 | '''
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down,
left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the
borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
Example
Example 1:
Input:
map =
[
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,1,0],
[1,1,0,1,1],
[0,0,0,0,0]
]
start = [0,4]
end = [3,2]
Output:
false
Example 2:
Input:
map =
[[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,1,0],
[1,1,0,1,1],
[0,0,0,0,0]
]
start = [0,4]
end = [4,4]
Output:
true
Notice
1.There is only one ball and one destination in the maze.
2.Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
3.The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of
the maze are all walls.
5.The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
'''
class Solution:
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: whether the ball could stop at the destination
"""
def hasPath(self, maze, start, destination):
# write your code here
if maze[start[0]][start[1]]==1:
return False
cur=[start]
used=[start]
while cur:
len_cur=len(cur)
for _ in range(len_cur):
loc=cur.pop(0)
row,column=loc[0],loc[1]
if row-1>=0 and maze[row-1][column]==0:
row-=1
while row>=0 and maze[row][column]==0:
row-=1
if [row+1,column] not in used:
cur.append([row+1,column])
used.append([row+1,column])
row,column=loc[0],loc[1]
if column-1>=0 and maze[row][column-1]==0:
column-=1
while column>=0 and maze[row][column]==0:
column-=1
if [row,column+1] not in used:
cur.append([row,column+1])
used.append([row,column+1])
row,column=loc[0],loc[1]
if row+1<len(maze) and maze[row+1][column]==0:
row+=1
while row<len(maze) and maze[row][column]==0:
row+=1
if [row-1,column] not in used:
cur.append([row-1,column])
used.append([row-1,column])
row,column=loc[0],loc[1]
if column+1<len(maze[0]) and maze[row][column+1]==0:
column+=1
while column<len(maze[0]) and maze[row][column]==0:
column+=1
if [row,column-1] not in used:
cur.append([row,column-1])
used.append([row,column-1])
if destination in cur:
return True
return False
|
28fc25b20f33bba1664f0186c2a8abfed0bcabda | Kanaderu/CircuitPython | /bundle/circuitpython-community-bundle-examples-20200224/examples/example3_crazy_color.py | 1,668 | 3.6875 | 4 | # This is example is for the SparkFun Qwiic Single Twist.
# SparkFun sells these at its website: www.sparkfun.com
# Do you like this library? Help support SparkFun. Buy a board!
# https://www.sparkfun.com/products/15083
"""
Qwiic Twist Example 3 - example3_crazy_color.py
Written by Gaston Williams, June 20th, 2019
Based on Arduino code written by
Nathan Seidle @ Sparkfun, December 3rd, 2018
The Qwiic Twist is an I2C controlled RGB Rotary Encoder produced by sparkfun
Example 3 - Crazy Color:
This program uses the Qwiic Twist CircuitPython Library to
control the Qwiic Twist RGB Rotrary Encoder over I2C to set
the knob color to an endless number of random colors.
"""
from time import sleep
import random
import board
import busio
import sparkfun_qwiictwist
# Create bus object using our board's I2C port
i2c = busio.I2C(board.SCL, board.SDA)
# Create twist object
twist = sparkfun_qwiictwist.Sparkfun_QwiicTwist(i2c)
print('Qwicc Twist Example 3 Crazy Color')
# Check if connected
if twist.connected:
print('Twist connected.')
else:
print('Twist does not appear to be connected. Please check wiring.')
exit()
print('Type Ctrl-C to exit program.')
# Turn off any color connections
twist.connect_color(0, 0, 0)
try:
while True:
print('Count: ' + str(twist.count))
if twist.pressed:
print('Pressed!')
# Generate a random rgb value
red = random.randint(0, 256)
green = random.randint(0, 256)
blue = random.randint(0, 256)
twist.set_color(red, green, blue)
sleep(0.1)
except KeyboardInterrupt:
pass
|
30c8c565d3da751b692faaddb3e42d3648dcff9c | Mike-Marble/Learning-Python | /EX/py4e_tutorials/ex_080.py | 1,099 | 4.34375 | 4 | # this program loops through the lines of the text file
# finds lines that start with 'from'
# splits those lines into a list
# and prints the word at associated list position
# opens file
fOpen = open('ex_071_text.txt')
# *** added after ***
emailList = []
# loops for each line in the file
for line in fOpen:
# strips white space from file
line = line.rstrip()
# skips blank lines
if line == "":
continue
# splits the lines into a list
words = line.split()
# finds lists that start with 'From'
if words[0] != 'From':
continue
# prints the words at associated list position
# print(words[1])
# *** Added After ***
# just for funsies - appended list items to another list inside the loop
if words[1] not in emailList:
emailList.append(words[1])
# when the loop is finished sorted the list
emailList.sort()
# loop to make printed lists not look like ass
for email in emailList:
print(email)
# in future could write code that removes duplicate entries in list, then sort and print
# nevermind... I wrote it on line 27
|
6a521b5e3c8a38b2db7748d8f172fb1fbdc37c4d | SeregaPro1/hello-world | /Lessons/scope.py | 419 | 3.65625 | 4 | # scope = the region that a variable is recognized
# A variable is only available from inside the region it is created.
# A global and lacally scope versions of a variable can be created.
name = 'Bro' # global scope(avaible inside and outside functions)
def display_name():
name = 'Code' # local scope (available only inside this function)
print(name)
display_name()
print(name) |
fd521e551db925236cbf815c7999b44383d16b83 | weddy3/TPP | /21_tictactoe/tictactoe.py | 4,002 | 3.9375 | 4 | #!/usr/bin/env python3
"""
Author : wil <wil@localhost>
Date : 2021-06-03
Purpose: Tic Tac Toe
"""
import argparse
import re
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Tic Tac Toe',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-b',
'--board',
help='Enter string state of board using ., O, and X',
metavar='board',
type=str,
default='.' * 9
)
parser.add_argument('-p',
'--player',
help='Indicate whether the player is X or O',
metavar='player',
type=str,
choices=['X', 'O']
)
parser.add_argument('-c',
'--cell',
help='Indicate what cell you want to take',
metavar='cell',
type=int,
choices=[int(number) for number in range(1, 10)]
)
args = parser.parse_args()
# check if board has exactly 9 chars of ., X, and O
board_char_match = re.search('^[XO.]{9}$', args.board)
if board_char_match == None:
parser.error(f'--board "{args.board}" must be 9 characters of ., X, O')
# ensure that both or none of cell and player are submitted
if any([args.player, args.cell]) and not all([args.player, args.cell]):
parser.error(f"Must provide both --player and --cell")
# ensure cell is supplied and board is not occupied where player wants to take
if args.cell and args.board[args.cell - 1] != '.':
parser.error(f'--cell "{args.cell}" already taken')
return args
def alter_board(board, player, cell):
"""Alter board string for player input"""
board = list(board)
# enter player letter in supplied cell
board[cell - 1] = player
return ''.join(board)
def format_board(board):
"""Print off the board"""
formatted_board = '-------------\n'
for index in range(0, len(board)):
# print player letter if present, else board index
value = index + 1 if board[index] == '.' else board[index]
formatted_board += f'| {value} '
if index == 2 or index == 5:
formatted_board += '|\n-------------\n'
if index == 8:
formatted_board += '|\n-------------'
return formatted_board
def find_winner(board):
"""Determine if there is a winner or not"""
winning_indicies = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
# check to see if 3 matching letters in winning indicies that are not '.'
for indicies in winning_indicies:
if '.' != board[indicies[0]] == board[indicies[1]] == board[indicies[2]]:
# since these three chars above match,
# retrieve one and that will be winning player
return f'{board[indicies[0]]} has won!'
return 'No winner.'
# --------------------------------------------------
def main():
"""Handle what combo of args are present and print boards and winner"""
args = get_args()
# board is always present and if player is present, cell has to be
# so we only need to check if player is true
if args.player:
# if move is supplied, mutate board and check for winner
mutated_board = alter_board(args.board, args.player, args.cell)
print(format_board(mutated_board))
print(find_winner(mutated_board))
else:
# if only args.board, print the board and any winner
print(format_board(args.board))
print(find_winner(args.board))
# --------------------------------------------------
if __name__ == '__main__':
main()
|
e13a8046bf822fcb07b4d263cec597fe1aaccbd0 | DiasVitoria/Python_para_Zumbis | /Lista de Exercícios I Python_para_Zumbis/Exercicio5.py | 246 | 3.8125 | 4 |
prod = float(input("Informe o valor total da compra: "))
desc = float(input("Informe a porcentagem do desconto: "))
porcprod = desc / 100
valordesc = prod * porcprod
valortotal = prod - valordesc
print('Valor total a pagar: ',valortotal)
|
d123186b69b0b3b66cff4522ebdc15109c29282f | BTS-413/1.Hafta | /16701042/kimlikoperatoru.py | 268 | 3.71875 | 4 | #is isleci
a=5
b=5
"""
if a is b:
print("aynı") is isleci a ve b'nin id numaralarını kontrol eder.
"""
"""
if a==b:
print("aynı") ==(eşit eşit) a ve b nin değerlerini kontrol eder.
"""
#id fonksiyonu
a=5
b=5
print(id(a))
print(id(b))
print(id(5))
|
3d7945af557b78b1d95a882700db093705617e19 | jguecaimburu/euler | /ex46e.py | 2,450 | 3.71875 | 4 | """
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime
and twice a square?
"""
from euler_snippets import get_primes_in_big_limit
import numpy as np
class BreakGoldbach():
def __init__(self, primes_limit, square_limit):
self.primes_limit = primes_limit
self.square_limit = square_limit
def set_primes_in_limit(self):
self.primes = list(get_primes_in_big_limit(self.primes_limit,
fragmentation=1000))
print("Primes set from %d to %d"
% (self.primes[0], self.primes[-1]))
def set_double_of_square_list(self):
def double_sq(int):
return 2 * (int ** 2)
square_range = list(range(1, self.square_limit))
self.double_sq = list(map(double_sq, square_range))
print("Double squares set from %d to %d"
% (self.double_sq[0], self.double_sq[-1]))
def sum_primes_and_squares(self):
array_of_primes = np.array(self.primes).reshape((len(self.primes), 1))
transposed_squares = np.array(self.double_sq) \
.reshape(1, (len(self.double_sq)))
sum_of_elements = array_of_primes + transposed_squares
self.sum = sorted(np.unique(sum_of_elements))
print("Sum of arrays done.")
def get_answer(self):
prime_gen = (p for p in self.primes)
sum_gen = (s for s in self.sum)
prime = 0
sum_int = 0
for odd in range(3, self.primes_limit, 2):
while prime < odd:
prime = next(prime_gen)
if prime != odd:
while sum_int < odd:
sum_int = next(sum_gen)
if sum_int != odd:
return odd
def break_goldbach(self):
self.set_primes_in_limit()
self.set_double_of_square_list()
self.sum_primes_and_squares()
return self.get_answer()
# Getting primes...
# Fragmentation set to 1000
# Primes set from 2 to 99991
# Double squares set from 2 to 1996002
# Sum of arrays done.
# CPU times: user 1.35 s, sys: 202 ms, total: 1.56 s
# Wall time: 1.46 s
# 5777
# Sum of arrays breaks memory for big input
|
9313877802c897ccdbe07808ebe20c00822a1e3d | cuimin07/cm_offer | /11.旋转数组的最小数字.py | 691 | 4.0625 | 4 | '''
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
'''
#答:
class Solution:
def minArray(self, numbers: List[int]) -> int:
i, j = 0, len(numbers) - 1
while i < j:
m = (i + j) // 2
if numbers[m] > numbers[j]: i = m + 1
elif numbers[m] < numbers[i]: j = m
else: j -= 1
return numbers[i]
|
645e43ca3dfb7b9de7d12738804177bf3e114bb5 | Virjanand/LearnPython | /022_partialFunctions.py | 559 | 4.40625 | 4 | # Partial functions
# Derive a function to a function with fewer parameters and fixed values
from functools import partial
def multiply(x, y):
return x * y
# create a new function that multiplies by 2
dbl = partial(multiply, 2)
print(dbl(4))
# values will be replaced from left
# Exercise: replace first 3 variables, so that it returns 60
# with only one input parameter
def func(u,v,w,x):
return u*4 + v*3 + w*2 + x
#Enter your code here to create and print with your partial function
partial_func = partial(func, 5, 10, 3)
print(partial_func(4)) |
4cb000ddb86bc5cace90a9f2525bc0e759c903fe | dmitrii1991/Python-my-works | /basic_algorithm/Fibonacci/recursuon_decor.py | 325 | 3.515625 | 4 | def memo(f):
cache = {}
def inner(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return inner
@memo
def fib(x):
assert x >= 0
return x if x <= 1 else fib(x - 1) + fib(x - 2)
def main():
n = int(input())
print(fib(n))
if __name__ == "__main__":
main()
|
1ac417e5fb0a373b46364624d1b5e3b8f04b4f92 | SakyaSumedh/eulerProblem | /10001_prime_number.py | 545 | 4.0625 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
from math import sqrt
number = 10001
prime_list = [2]
def check_prime(prim_list, value):
sqrt_value = sqrt(value)
for prime in prim_list:
if prime > sqrt_value:
break
if value % prime == 0:
return False
return True
value = 3
while len(prime_list) < number:
if check_prime(prime_list, value):
prime_list.append(value)
value += 2
prime_list.insert(0, 1)
print(prime_list[number])
|
712bf738d2fabdab5849c9485dd90ea11e353d95 | Sonima-S/work-work-python- | /names.py | 172 | 3.734375 | 4 | names = ['sonee','niku','puru','santu','anu','prateek','arunema','omu','sudeep','ram']
names_with_e = [x for x in names if 'e' in x]
print 'names with e are:', names_with_e |
a01a780602bafb1dff4d99da46805ea269363c3c | jlopezh/PythonLearning | /co/com/test/scopeExamples.py | 1,175 | 4.34375 | 4 | """Explain LEGB rule"""
"""Local and Global scopes"""
a_var = 'global value'
def a_func():
a_var = 'local value'
print(a_var, '[ a_var inside a_func() ]')
a_func()
print(a_var, '[ a_var outside a_func() ]')
print("=" * 20)
"""concept of the enclosed (E) scope. Following the order 'Local -> Enclosed -> Global'"""
a_var = 'global value'
def outer():
a_var = 'enclosed value'
def inner():
a_var = 'local value'
print(a_var)
inner()
outer()
a_var = 'global value'
def outer():
a_var = 'local value'
print('outer before:', a_var)
def inner():
nonlocal a_var
a_var = 'inner value'
print('in inner():', a_var)
inner()
print("outer after:", a_var)
outer()
print("=" * 20)
"""LEGB - Local, Enclosed, Global, Built-in"""
a_var = 'global variable'
def len(in_var):
print('called my len() function')
l = 0
for i in in_var:
l += 1
return l
def a_func(in_var):
len_in_var = len(in_var)
print('Input variable is of length', len_in_var)
a_func('Hello, World!')
print("=" * 20)
"""Scope in Loops"""
i = 1
print([i for i in range(5)])
print(i, '-> i in global') |
55021d0744a53dd0e23dd44406d27bfa8b822b1a | astreltsov/firstproject | /Eric_Matthes_BOOK/DICTIONARY/6_9_Favorite_places.py | 315 | 3.765625 | 4 | favorite_places = {
'oleg': ['crete', 'santa cruz', 'snegiri'],
'anna': ['zug', 'miami', 'samara'],
'nick': ['spb', 'kiev', 'varshava']
}
for name, locations in favorite_places.items():
print(f"\n{name.title()}'s favorite places are: ")
for location in locations:
print(f"\t{location}")
|
39c9f0c7ddc4c54b7f31b0212ae5696a865d94b4 | silkyg/python-practice | /Assignment_1_input_output_operators_data_type/Calculate_area_of_a_circle.py | 179 | 4.34375 | 4 | #program to find area of a circle , where Radius is taken from user
import math
r=int(input("Enter radius of the circle :"))
Area= math.pi *r*r
print("Area of circle is ->",Area ) |
03c2725edb4560c5a91a85c54b2e092d01bcc134 | digoreis/code-interview | /hash-array-string/1.3-urlify/main.py | 478 | 4.1875 | 4 | # Write a method to replace all spaces in a string with %20. You may assume that the string has
# sufficient space at the end to hold the addictional characters, and that you are given the `true`
# length of the string.( Note: if implementing in Java, please use a character array so that you
# can perfom this operation in place)
def urlify(url):
newText = ""
for c in url:
newText += c if c != " " else "%20"
return newText
print(urlify("aaa bbb c")) |
f50281e664b9aa21bf11b86fbc3d9b5085d07efd | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-21.py | 511 | 3.953125 | 4 | # Create an empty dictionary. Allow 4 friends to enter their
# favourite languages as values and use keys as their names. Assume that
# the name are unique.
favlang = {}
a = input("Enter your favourite language Sharthok : ")
b = input("Enter your favourite language Auddry : ")
c = input("Enter your favourite language Imran : ")
d = input("Enter your favourite language Cathy : ")
favlang["Sharthok"] = a
favlang["Auddry"] = b
favlang["Imran"] = c
favlang["Cathy"] = d
print(favlang)
|
a5f4b44259e649e7094354067e9c97687a568937 | arnabs542/BigO-Coding-material | /review/beverages_topo_sort.py | 1,671 | 3.765625 | 4 | from queue import PriorityQueue
def dfs(src):
visited[src] = True
for u in graph[src]:
if not visited[u]:
dfs(u)
result.append(beverages_ls[src])
# print('Intermediate result: ', result)
def topological_sort(graph, result):
for i in range(n):
if not visited[i]:
dfs(i)
result.reverse()
# print('done: ', result)
def topological_sort_kahn(graph, result):
indegree = [0]*n
zero_indegree = PriorityQueue()
for u in range(n):
for v in graph[u]:
indegree[v] += 1
for i in range(n):
if indegree[i] == 0:
zero_indegree.put(i)
while not zero_indegree.empty():
u = zero_indegree.get()
result.append(beverages_ls[u])
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
zero_indegree.put(v)
if __name__ == '__main__':
case = 0
while True:
try:
n = int(input())
case += 1
beverages_ls = []
graph = [[] for i in range(n)]
visited = [False] * n
result = []
for i in range(n):
beverages_ls.append(input())
m = int(input())
for e in range(m):
temp_ls = list(input().split())
bev1 = beverages_ls.index(temp_ls[0])
bev2 = beverages_ls.index(temp_ls[1])
graph[bev1].append(bev2)
# print('Case {0}: {1}'.format(case, graph))
topological_sort_kahn(graph, result)
print('Case #{0}: Dilbert should drink beverages in this order:'.format(case), end=' ')
# for res in result:
# print(res, end=' ')
print(*result, end = '')
print('.')
print()
temp = input()
except EOFError as e:
# print(e)
break
|
1b5f4f53ee9869f1c1cbceaeedd6b6c2d5a19261 | MartyVos/V2ALDS_Week1 | /2-getNumbers.py | 805 | 4.03125 | 4 | # getNumbers(s)
# This function returns all the numbers in a string
# Parameters:
# s: str
# A string with numbers
#
# Return:
# lst: list of ints
# A list with the extracted numbers
def getNumbers(s):
st = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
lst = []
tmp = ""
for x in list(s):
if x in st:
tmp += x
else:
if tmp != "":
lst.append(int(tmp))
tmp = ""
if tmp is not "":
lst.append(int(tmp))
return lst
# Testing with a string with numbers
print(getNumbers('een123zin45 6met-632meerdere+7777getallen12'))
# Testing with a string without numbers
print(getNumbers('een zin zonder meerdere getallen'))
# Testing with a empty string
print(getNumbers(''))
|
17548a1b587f96448eb701a7ee4f47f693c8a9da | cavandervoort/Udemy-Python-Course | /Milestone Project 1 (Tic Tac Toe)/TicTacToe_2_Player.py | 3,073 | 3.8125 | 4 | import time
import IPython
def did_player_win(board, letter):
for row in range(3):
if board[row][0] == board[row][1] == board[row][2] == letter:
return True
for column in range(3):
if board[0][column] == board[1][column] == board[2][column] == letter:
return True
if board[0][2] == board[1][1] == board[2][0] == letter:
return True
elif board[0][0] == board[1][1] == board[2][2] == letter:
return True
else:
return False
def display(board):
IPython.display.clear_output()
count = 0
for row in board:
row_nice = '|'.join(row)
print(row_nice)
count += 1
if count <3:
print('-----')
print('')
def player_turn(board):
display(board)
# get player input
open_check = 0
while open_check == 0:
# get row input
row = ''
row_fail = ''
while type(row) !=int:
row = input(f"Please {row_fail}enter a row number (1, 2, or 3): ")
if row == '1' or row == '2' or row == '3':
row = int(row)
else:
row_fail = 'try a little harder to '
# get column input
column = ''
column_fail = ''
while type(column) !=int:
column = input(f"Please {column_fail}enter a column number (1, 2, or 3): ")
if column == '1' or column == '2' or column == '3':
column = int(column)
else:
column_fail = 'try a little harder to '
player_move = (row-1,column-1)
if board[player_move[0]][player_move[1]] == ' ':
return player_move
else:
print("Sorry, this square is not open. Please try a little harder to find an open square.")
def play_again():
play_again = ''
while play_again not in ['YES','NO']:
play_again = input('Would you like to play again? (Yes or No) ').upper()
if play_again == "YES":
return 'YES'
elif play_again == 'NO':
print('Thanks for playing! I hope you had as much fun as I did!')
return 'NO'
else:
print("Fine, I'll ask again.")
def play_tic_tac_toe():
is_new_game = 'YES'
print("Welcome to Chris' tic tac toe game!")
while is_new_game == 'YES':
play_game()
is_new_game = play_again()
def play_game():
# empty board before the first turn
board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
turn = 0
letter = ''
while turn <= 8:
if turn%2 == 0:
letter = 'X'
else:
letter = 'O'
new_move = player_turn(board)
board[new_move[0]][new_move[1]] = letter
if did_player_win(board, letter) == True:
display(board)
print(f'Player {letter} has won the game.')
return # 'test'
turn += 1
else:
display(board)
print("Cat's game. Meeeeeeeooowwwwww.")
play_tic_tac_toe()
|
a0ad460471c4924633611ad7a04e213ef6b74f23 | radhika5208/Elevator | /dynamic.py | 1,540 | 3.75 | 4 | #import Adafruit_BBIO.GPIO as g
import sys
import time as t
dp=0
max1=5
def upward(dp,tp):
for i in range(tp+1):
pin="P9_"+str(11+dp+i)
print "Floor No: "+str(dp+i)
#g.setup(pin,g.OUT)
#g.output(pin,g.HIGH)
t.sleep(1)
#g.setup(pin,g.OUT)
#g.output(pin,g.LOW)
#g.setup(pin,g.OUT)
#g.output(pin,g.HIGH)
print "Reached To Floor"
t.sleep(3)
#g.setup(pin,g.OUT)
#g.output(pin,g.LOW)
def downword(dp,tp):
for i in range(tp+1):
pin="P9_"+str(11+dp-i)
#g.setup(pin,g.OUT)
#g.output(pin,g.HIGH)
print "Floor No: "+str(dp-i)
t.sleep(1)
#g.setup(pin,g.OUT)
#g.output(pin,g.LOW)
#g.setup(pin,g.OUT)
#g.output(pin,g.HIGH)
print "Reached To Floor"
t.sleep(3)
#g.setup(pin,g.OUT)
#g.output(pin,g.LOW)
while 1:
choice=map(int,raw_input("Enter your choice:"))
if(dp<=(max1/2)):
for item in choice:
item=int(item)
choice.sort()
print choice
length=len(choice)
for j in range(0,length):
dp=choice[j]
else:
for item in choice:
item=int(item)
choice.sort(reverse=True)
print choice
length=len(choice)
for j in range(0,length):
if(choice[j]>max):
print "WRONG INPUT...!"
elif(choice[j]==dp):
print "You are at same floor"
elif(choice[j]>dp):
tp=choice[j]-dp
upward(dp,tp)
dp=choice[j]
elif (choice[j]<dp | choice[j]<=max):
tp=dp-choice[j]
downword(dp,tp)
dp=choice[j]
g.cleanup()
|
839b62e12e2601922082e799cd555edd9d3a7a3a | sidneyarcidiacono/interview_prep_2 | /linked_list.py | 668 | 4.09375 | 4 | """Implement our linked list."""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, item):
new_node = Node(item)
if self.head is None:
self.head = new_node
if self.tail is not None:
self.tail.next = new_node
self.tail = new_node
new_node.next = None
def find(self, item):
current = self.head
while current.data[0] != item:
current = current.next
if current.data[0] == item:
return current
|
bafc86a5ed3cdebf0369eb590dca091254b1f0fe | zhouchengrui/COMS4701_AI | /hw1_search/treeNode.py | 2,937 | 4.1875 | 4 | #!/usr/bin/env python3
class TreeNode(object):
"""
This class represents the search tree node
"""
def __init__(self, state, parent_move = None, parent = None):
self.state = state
self.parent_move = parent_move
self.parent = parent
self.cost = parent.cost + 1 if parent else 0
self.heuristics = self.__get_manhattan_dis()
self.tot_cost = self.cost + self.heuristics
def get_neighbors(self, reverse = False):
"""
get the neighbors(children) of the current node
:param reverse: boolean
:return: list
"""
neighbor = []
zero_index = self.state.index(0)
zero_row, zero_col = zero_index // 3, zero_index % 3
if zero_row > 0:
up_neighbor = list(self.state)
up_neighbor[zero_index], up_neighbor[zero_index - 3] = \
up_neighbor[zero_index - 3], up_neighbor[zero_index]
neighbor.append(TreeNode(tuple(up_neighbor), 'Up', self))
if zero_row < 2:
down_neighbor = list(self.state)
down_neighbor[zero_index], down_neighbor[zero_index + 3] = \
down_neighbor[zero_index + 3], down_neighbor[zero_index]
neighbor.append(TreeNode(tuple(down_neighbor), 'Down', self))
if zero_col > 0:
left_neighbor = list(self.state)
left_neighbor[zero_index], left_neighbor[zero_index - 1] = \
left_neighbor[zero_index - 1], left_neighbor[zero_index]
neighbor.append(TreeNode(tuple(left_neighbor), 'Left', self))
if zero_col < 2:
right_neighbor = list(self.state)
right_neighbor[zero_index], right_neighbor[zero_index + 1] = \
right_neighbor[zero_index + 1], right_neighbor[zero_index]
neighbor.append(TreeNode(tuple(right_neighbor), 'Right', self))
return neighbor if not reverse else neighbor[::-1]
def __get_manhattan_dis(self):
"""
get manhanttan distance
:return: int
"""
cost = 0
for i, v in enumerate(self.state):
if v != 0:
cost += abs(i % 3 - v % 3) + abs(i // 3 - v // 3)
return cost
def __str__(self):
"""
for debug use
:return:
"""
return str(self.state)
def __lt__(self, other):
"""
comparator function for heapq
:param other: the other node
:return: boolean
"""
order = {'Up':1,
'Down':2,
'Left':3,
'Right':4}
if self.tot_cost == other.tot_cost:
return order[self.parent_move] < order[other.parent_move]
return self.tot_cost < other.tot_cost
if __name__ == "__main__":
node1 = TreeNode((8,0,4,2,6,3,5,1,7))
node2 = TreeNode((8,6,4,0,2,3,5,1,7))
# print (node1.tot_cost, node2.tot_cost)
|
f2afd53886e8c277e9f49847e8bd69fad9b0d420 | peqadev/python | /doc/practices/12.data_types_strings_modifiers.py | 518 | 4.21875 | 4 | # Modificadores de cadenas
a =" Hello, World! "
print(a.upper()) # HELLO, WORLD!
print(a.lower()) # hello, world!
print(a.strip()) # Hello, World! (Elimina todos los espacios en blanco)
print(a.lstrip()) # Hello, World! (Elimina los espacios en blanco a la izquierda)
print(a.rstrip()) # Hello, World! (Elimina los espacios en blanco a la derecha).
print(a.replace("H", "J")) # Jello, World! (Reemplaza todas las letras que encuentre)
print(a.strip().split(" ")) # ['Hello,', 'World!'] (Retorna una lista)
|
4a6d2bf606de9327bf53dbb408df1027ea5e9c59 | Sunqk5665/Python_projects | /算法练习/PTA/python蓝桥/第1周/04-输出10个不重复的英文字母.py | 796 | 4.21875 | 4 | # 要求:随机输入一个字符串,把最左边的10个不重复的英文字母(不区分大小写)挑选出来。
# 如没有10个英文字母,显示信息“not found”
# String模块 ascii_letters 和 digits 方法:ascii_letters是生成所有字母,
# 从a-z和A-Z,digits是生成所有数字0-9
from string import digits # 所有数字
from string import ascii_letters as al #所有字母
def prt(s): # 筛选函数
re='' #
for i in s:
if i in al and i.lower() not in re and i.upper() not in re: # 判断字符是否是字母并且是否重复,并筛选出来
re += i
return re
st = input().translate(str.maketrans('','',digits)) # 去除字符串中所有的数字
re = prt(st)
if len(re)<10:
print("not found")
else:
print(re[:10]) |
d2d95e4c1af0668a79b4229494a020ddf92af7ab | mzivi/elgoog | /leetcode/001_two_sum.py | 1,109 | 3.90625 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
#
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
#
# Example:
#
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(1, len(nums)):
for j in range(i):
if target == nums[i] + nums[j]:
return j, i
raise Exception('No solution found.')
def twoSumHash(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, v in enumerate(nums):
if target - v in lookup:
return lookup[target - v], i
lookup[v] = i
raise Exception('No solution found.')
if __name__ == '__main__':
print(twoSum([2, 7, 11, 15], 9))
print(twoSum([3, 2, 4], 6))
print(twoSumHash([2, 7, 11, 15], 9))
print(twoSumHash([3, 2, 4], 6))
|
a43187a9a5ff3986c89f835ccf4e390ecbe51aa8 | MurilloFagundesAS/Exercicios-Resolvidos-Curso-em-Video | /Ex063-Fibonacci.py | 228 | 3.828125 | 4 | n = int(input('Digite quantos termos da Sequência de Fibonacci você deseja ver: '))
x = 0
a = 0
b = 1
print(f'{a} {b} ', end='')
while x != n+1:
soma = a + b
print(f'{soma} ', end='')
a = b
b = soma
x += 1 |
de9b81bb4b9d4245a4f947452713301cedcf17e3 | eidgahadi/Homework2 | /Time_conversion.py | 399 | 3.859375 | 4 | time = input().split(":")
hours = int(time[0])
minutes = time[1]
seconds = time[2][:2]
ap = time[2][2:]
if ap == "PM" and hours != 12:
hours += 12
elif ap == "PM" and hours == 12:
hours = 12
elif ap == "AM" and hours == 12:
hours = 0
if hours < 10:
hourString = "0" + str(hours)
else:
hourString = str(hours)
print(hourString + ":" + minutes + ":" + seconds) |
f91d53cdf044934f5a131ef37ff875734bf53155 | armanshafiee/allback | /math henese.py | 4,639 | 3.65625 | 4 | print("num2=1=>edame,,,num2=0=>by by")
for z in range(999):
print("1)+")
print("2)-")
print("3)*")
print("4)/")
print("5)mokeab")
print("6)mokeab mostatil")
print("7)heram kaf moraba")
print("8)kore")
print("9)heram kaf mosalas")
print("10)makhrot")
print("11)ostovane")
print("0)exit")
a=str(input('num :'))
if a=="1":
avaly=float(input("avaly"))
dovomy=float(input("dovomy"))
hasel=avaly+dovomy
print(hasel)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="2":
avaly=float(input("avaly"))
dovomy=float(input("dovomy"))
hasel=avaly-dovomy
print(hasel)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="3":
avaly=float(input("avaly"))
dovomy=float(input("dovomy"))
hasel=avaly*dovomy
print(hasel)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="4":
avaly=float(input("avaly"))
dovomy=float(input("dovomy"))
hasel=avaly/dovomy
for i in range (85):
print("jasem")
print("hanoz")
print("zendas")
q=(999999999999999999/999999999)-1
print(q)nt(hasel)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="5":
zel=float(input("zel:"))
v=zel**3
print("/////////////////////////////////////")
print("V=",v)
Sl=4*(zel**2)
print("Sl=",Sl)
St=6*(zel**2)
print("St",St)
d=zel*(3**0.5)
print("d",d)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="6":
tool=float(input("tool:"))
arz=float(input("arz:"))
ertefa=float(input("ertafa:"))
print("/////////////////////////////////////")
v=tool*arz*ertefa
print("V=",v)
Sl=2*(tool*ertefa+arz*ertefa)
print("Sl",Sl)
St=Sl+2*(tool*arz)
print("St=",St)
d=(tool**2+arz**2+ertefa**2)**0.5
print("d=",d)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="7":
zel=float(input("zel:"))
h=float(input("h:"))
hp=float(input("hp:"))
print("/////////////////////////////////////")
Sb=zel**2
v=(Sb*h)/3
print("V=",v)
Sl=4*((hp*zel)/2)
print("Sl",Sl)
St=Sl+Sb
print("St",St)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="8":
r=float(input("r:"))
print("/////////////////////////////////////")
s=4*3.14*r**2
print("S",s)
v=r/3*s
print("V",v)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="9":
zel=float(input("zel:"))
h=float(input("h:"))
hp=float(input("hp:"))
print("/////////////////////////////////////")
Sb=zel*hp
v=(Sb*h)/3
print("V=",v)
Sl=3*((hp*zel)/2)
St=Sl+Sb
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="10":
#zel=float(input("zel:"))
h=float(input("h:"))
r=float(input("r:"))
print("/////////////////////////////////////")
Sb=r**2*3.14
v=1/3*Sb*h
print("v=",v)
l=(h**2+r**2)**0.5
St=3.14*r*l
print("St=",St)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="11":
r=float(input("r:"))
h=float(input("h:"))
print("/////////////////////////////////////")
Sb=r**2*3.14
v=Sb*h
print("V=",v)
Pb=2*3.14*r
Sl=Pb*h
print("Sl=",Sl)
St=Sl+2*Sb
print("St=",St)
num2=int(input("num2:"))
if num2==1:
y=0
elif num2==0:
break
elif a=="0" :
break
print("by") |
808603a128dba73cdaa9165e08b983b482a1e501 | kleyow/webapp2_boilerplate | /forms/custom_validators.py | 768 | 3.53125 | 4 | import decimal
import re
from wtforms import ValidationError
class DecimalPlaces(object):
"""Validates the number of decimal places entered in a field."""
def __init__(self, min=2, max=2, message=None):
self.min = min
self.max = max
self.message = message
def __call__(self, form, field):
if not isinstance(field.data, decimal.Decimal):
raise ValidationError('Expected decimal.Decimal, got %s.'
% type(field.data))
regex = r'^\d+(\.\d{%d,%d})?$' % (self.min, self.max)
if not re.match(regex, field.raw_data[0]):
message = self.message or ('Field must have at between %d and %d '
'decimal places.' % (self.min, self.max))
raise ValidationError(message)
|
cb59c684d88f5c2fcdccb067370357bdfe127af6 | clopez5313/PythonCode | /Lists/Middle.py | 154 | 3.703125 | 4 | def middle(theList):
length = len(theList)
return theList[1:length-1]
tList = ['a','b','c','d']
nList = middle(tList)
print(nList)
#print(tList)
|
50b58fbfdc1ee9be5a5ab0780e6f7d39daae8057 | SalmaFarghaly/cross-word | /util.py | 841 | 3.5625 | 4 |
import heapq
class Node():
def __init__(self, state,cost):
self.state = state
self.cost=cost
def __lt__(self, other):
return self
def __le__(self,other):
return self
def __gt__(self, other):
return self
def __ge__(self, other):
return self
def __print__(self):
print(self.state,self.cost)
class PriorityQueue():
def __init__(self):
self.frontier = []
def push(self, priority, x):
heapq.heappush(self.frontier, (-priority, x))
def pop(self):
_, x = heapq.heappop(self.frontier)
return x
def empty(self):
return len(self.frontier) == 0
def contains_state(self,state):
return any(node[1].state == state for node in self.frontier)
def __print__(self):
pass
|
f75b6a117749ce635dedb6f6c2b24fa419cfb72e | ByketPoe/gmitPandS | /week10-objects/timesheetentry.py | 493 | 3.65625 | 4 | # timesheetentry.py
# The purpose of this program is to enter data into time sheets.
# author: Emma Farrell
import datetime as dt
class Timesheetentry:
def __init__(self, project, start, duration):
self.project = project
self.start = start
self.duration = duration
def __str__(self):
return self.project +':'+ str(self.duration)
if __name__ == '__main__':
ts = dt.datetime(2021,3,19,16,20)
test = Timesheetentry('test', ts, 60)
print(test)
|
435608237a4c2b9ba79eb7cb73d1bb3754ca2c69 | erauner12/python-scripting | /Linux/Python_Crash_Course/chapter_code/chapter_06_dictionaries/reference/aliens.py | 546 | 4.1875 | 4 |
# we will be putting a dictionary inside of a list
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# change the properties of the first 3 aliens
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 6 aliens.
for alien in aliens[:6]:
print(alien)
print("...")
|
e32e4c511f1940ee10a702f87df6a3da9b8184af | sreenidhimohan/sreenidhi | /number.py | 123 | 3.984375 | 4 | i=int(input("enter the number"))
if(i>0):
print("positive number")
elif(i<0):
print("negative number")
else:
print("zero")
|
e8f42fe26b8fee2cdefff69d9ee05e6fa9c8a18e | AnneOkk/Alien_Game | /settings.py | 1,075 | 3.859375 | 4 | class Settings:
"""A class to store all the settings for the game"""
def __init__(self):
"""Initialize the game's settings"""
#Screen settings
# create a display window on which we'll draw graphical ship
self.screen_width = 1200
self.screen_height = 800
# (1200, 800) defines dimensions -> assigned to self.screen, so it is available = SURFACE
# each alien etc is its own surface!
# self.screen_height = 800
## --> screen settings are not needed any longer when we use the FULLSCREEN mode!
self.bg_color = (190, 200, 230) #each color ranges from 0 to 255; (255, 0, 0) is red,
#(0, 255, 0) is green and (0, 0, 255) is blue; this color is here assigned to self.bg_color
self.ship_speed = 4.0 # now when the ship moves, it's position is adjusted by 1.5 pixels rather than 1
# Bullet settings:
self.bullet_speed = 1.0
self.bullet_width = 15
self.bullet_height = 26
self.bullet_color = (190, 0, 0)
self.bullets_allowed = 10
|
21e3eba7f84540c0ce018a3c5379fce687fe65f7 | zhazhijibaba/zhazhijibaba_programming_lessons | /programming_lesson2/compute_pi_monte_carlo.py | 660 | 3.890625 | 4 | # Compute pi value by Monte Carlo sampling
# circle area within a square with unit length
# pi = Area / r^2
# Area = Area of the square * number of points within circle / total number of points
# Area of the square = 4 * r^2
# pi = 4.0 * number of points within circle / total number of points
import random
import math
# number of points for sampling
N = 100000
A = 0
r = 1.0
r2 = 1.0 * 1.0
for i in range(N):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
if x * x + y * y < r2:
A += 1
pi = 4.0 * A / N
print "{0} samples, calculated pi value = {1} with error {2} compared to math.pi {3}".format(N, pi, abs(pi - math.pi), math.pi)
|
71bb53b624ce1940d037468920c1e77e809b068b | ThistleBlue22/CountAndLength | /main.py | 2,446 | 3.765625 | 4 | from wordCount import wordcount
from lineCount import linecount
from meanWordLength import meanwordlen
import argparse
def main(doc, calctype):
try:
# the below code checks the
if calctype == "wordcount":
wc = wordcount(doc=doc)
print("Word Count:", wc, "\n")
elif calctype == "linecount":
lc = linecount(doc=doc)
print("Line Count:", lc, "\n")
elif calctype == "meanwordlength":
mwl = meanwordlen(doc=doc)
print("Mean Word Length:", mwl, "\n")
# the above checks the passed type argument and runs the equivalent code snippet
else:
wc = wordcount(doc=doc)
lc = linecount(doc=doc)
mwl = meanwordlen(doc=doc)
print("Word Count:", wc, "\nLine Count:", lc, "\nMean Word Length:", mwl)
# simply runs all the individual components at once, printing the results to the console
except TypeError as e: # ensures that an error is thrown when passing a wrong extension value
print("Please enter only a file with extensions of .txt or .md")
except FileNotFoundError as e: # ensures that the error is caught if a incorrect path name is run on the file
print("Please check the file path and try again")
except UnicodeDecodeError as e:
print("Please only supply text based documents. Note: Some Microsoft Word documents, including .docx extensions"
" have issues running through the program, please try pasting the contents of the document into a .txt"
" file and trying again")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Word Count, Line Count and Mean Word Length calculator"
)
parser.add_argument( # picks up on the file passed and helps enter it into the program
"-d",
"--document",
help="For the text document"
)
parser.add_argument( # intended to give the user options of one of the three, or all of them by default
"-m",
"--mode",
choices=["wordcount", "linecount", "meanwordcount", "all"],
default=["all"],
help="Choice of which calculation to do. Accepted args include 'wordcount', "
"'linecount', 'meanwordlength' and 'all'"
)
args = parser.parse_args()
main(args.document, args.mode) # passes the arguments given to main, to run the program(s)
|
6ba66782689daf236d285102ede6aaf270ec512f | Javierzs/Algoritmosyprogramacion-Grupo2Ciclo4 | /Semana6/1332.py | 325 | 3.609375 | 4 | n=int(input())#casos de prueba
c=0#contador
while True:
if(c==n):
break
c=c+1
palabra=input("")
tamaño=len(palabra)
if(tamaño==5):
print("3")
elif(palabra[0]=="t" and palabra[1]=="w" or palabra[0]=="t" and palabra[2]=="o"or palabra[1]=="w" and palabra[2]=="o"):
print("2")
else:
print("1")
|
e407972e07cefd0a1ed3ede24f796d6adb3327ac | amidoge/Python-2 | /ex092.py | 611 | 4.4375 | 4 | #Is a number prime?
'''
-Greater than 1
-Only divisible by one and itself
-Return True if prime, False if not
-Only runs in the main file
'''
def prime_or_not(number):
#loop that runs until half the number
if number > 1:
if number == 2:
return True
else:
for i in range(2, number // 2):
if number % i == 0: #if it can (integer) divide without any remainders
return False
return True
return False
if __name__ == '__main__':
num = int(input("Number: "))
function = prime_or_not(num)
print(function) |
07a4f9a0fd0ce8af74f527a4a1c970d89c820fdf | BreadSocks/adventofcode2017-python | /day01/Day 1 Challenge 1.py | 398 | 3.515625 | 4 | data = open("input.txt").read()
example1 = "1122"
example2 = "1111"
example3 = "1234"
example4 = "91212129"
total = 0
input = data
for index, character in enumerate(input):
if index == len(input) - 1:
if character == input[0]:
total += int(character)
else:
continue
elif character == input[index + 1]:
total += int(character)
print total
|
c459325e7faf43e5e3e9e06fa08fe05e8799c8cc | Gzigithub/markup | /Python/algorithm/quick_sort(快速排序).py | 709 | 3.765625 | 4 | # 快速排序法
# 递归思想,sum()函数即是如此思想计算
# 计算速度的快慢取决于基准值的选取
def quick_sort(array):
# 基线条件:为空或者只包含一个元素的数组是‘有序’的
if len(array) < 2:
return array
# 递归条件
else:
# 设定基准值
pivot = array[0]
# 由所有小于等于基准值的元素构成的子数组
less = [i for i in array[1:] if i <= pivot]
# 由所有大鱼基准值的匀速构成的子数组
greeter = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greeter)
print(quick_sort([10,4,6,8]))
|
459f902d7c79b669b70ba73a8f42c6a12301732d | th9195/PythonDemo01 | /MyFuncation.py | 1,297 | 3.9375 | 4 |
#空方法
def fun():
pass
def my_abs(number):
'''
自定义abs
:param number: int 或者 float
:return: abs 绝对值
'''
#参数判断 #函数出错友好提示
if not isinstance(number,(int,float)):
raise TypeError("只能输入int 和 float 类型")
if number >= 0:
return number
else:
return -number
def getNames():
'''
返回多个值
:return: 返回多个值时返回的事一个tuple元组
'''
return "Tom1","Tom2"
#默认参数
# n = 2 就是默认参数
def power(x,n=2):
'''
x 的 n 次方
:param x: 底数
:param n: 指数
:return: x的n次方后的值
'''
return x**n
#可变参数
# *numbers
#N个数求和
def my_sum(*numbers):
print(type(numbers))
sum = 0
for i in numbers:
sum += i
return sum
#关键字参数
#**kw 关键字参数
#**kw 是一个dict字典的类型
# def student(name,age,**kw):
# print("name:",name,"age:",age,"others:",kw)
# print(type(kw))
# 命名关键字参数
# *,city 就是一个必须有一个参数是city,在传入参数的时候就是一个普通的关键字参数(字典)
def student(name,age,*,city):
print("name:", name, "age:", age, "city:", city)
print(type(city))
|
32e75a5aa8da2e030edbc33c8d99eb2c90dd493f | shahpriyesh/PracticeCode | /GrpahQuestions/CourseSchedule2.py | 403 | 3.59375 | 4 | from collections import defaultdict
class CourseSchedule2:
def courseSchedule2(self, numCourses, prerequisites):
# map course -> list of prerequisites
hmap = defaultdict(list)
for prereq in prerequisites:
hmap[prereq[0]].append(prereq[1])
# keep a list of taken classes
taken = []
for course, prereqList in hmap.items():
pass |
4c39b92209937c3ca1f7b6102c9b5a71d7484772 | ccmb501/Code-Rev | /CodeRev.py | 764 | 3.921875 | 4 | BuildingDict = {
"mosher":{"spider man": "066",
"doctor strange": "123",
"peter quill": "234",
"iron man": "066",
"incredible hulk": "456",
"black widow": "090",
"hawk eye": "270"
}
}
userNameInput = input("Please enter your name: ")
userRoomInput = str(input("Please enter your room number: "))
userBuildingInput = str(input("Please enter your hall building name: "))
userNameInput = str.lower(userNameInput)
userBuildingInput = str.lower(userBuildingInput)
if userBuildingInput in BuildingDict:
if userNameInput in BuildingDict["mosher"]:
if userRoomInput == BuildingDict["mosher"][userNameInput]:
print("true")
else:
print("false")
|
5afe76de8a5e48ff3ce956f934d00a2ac004c435 | harshitaJhavar/Neural-Networks-and-its-Applications-Deep-Learning- | /Question2_5.py | 1,484 | 4.15625 | 4 | ##Solution for Question 2.5
##Source code for stopping criterion
## Let us solve it for exercise 2.3- Gradient Descent
##Question 2.3 Gradient Descent Source Code
from math import pow
## Initiating number of iterations to 0.
Number_of_Iterations = 0
## Defining the value of precision
precision = 1/1000000
## Limiting number of iterations to be at max 1000.
maxIterations = 1000
## Defining the given function
def f( x,y ):
return (20*pow(x,2)+ 0.25*pow(y,2))
## Defining the first order partial derivative with respect to x
def firstPartialDerivative_fx(x,y):
return (40*x)
## Defining the first order partial derivative with respect to y
def firstPartialDerivative_fy(x,y):
return (0.5*y)
# Starting point as given
x=-2
y=4
#Learning rate as given
epsilon=0.04
#Gradient Descent
while True:
print (x,y,f(x,y))
xNew = x - epsilon * firstPartialDerivative_fx(x,y)
yNew = y - epsilon * firstPartialDerivative_fy(x,y)
if abs(xNew-x) < precision and abs(yNew-y) < precision:
break
x=xNew
y=yNew
Number_of_Iterations += 1
##Putting a check if the number of iterations cross the maximum iterations value
if Number_of_Iterations > maxIterations:
print("There are many iterations. You might want to change the value of the epsilon.")
break
if Number_of_Iterations < maxIterations:
print("The number of iterations required by this function to minimize were ",Number_of_Iterations)
print("\nThe given function converges to minimum at x = ",x," and y= ",y)
|
1bd20857eba027790b118f02f8eaa81dc321adce | PeterSharp-dot/dot-files | /python-projects/primes-generator/p_gen.py | 845 | 3.984375 | 4 | #!/usr/bin/env python
def primesGen(max):
primes = []
l = 3
# Lista nieparzystych aż do max
while l <= max:
if (l % 2 == 1):
primes.append(l)
l += 1
# import pdb; pdb.set_trace()
# Odsiewamy te z dzielnikiem
for i in primes:
if i > 3:
for j in primes:
if (i > j) and (i % j == 0):
primes.remove(i)
break
# Z jakiś dziwnych powodów jeszcze raz musimy odsiać
for i in primes:
if i > 3:
for j in primes:
if (i > j) and (i % j == 0):
primes.remove(i)
break
# Dodajemy do począku listy
primes.insert(0,2)
primes.insert(0,1)
print(primes)
inp = int(input("Podaj zakres: "))
primesGen(inp)
|
2881ca279c67790a2d67ebbd9d67a94a402a2e42 | Labs17-RVNav/rvnav-ds | /Rv_Flask/utils/geometry.py | 933 | 4 | 4 | from math import radians, cos, sin, asin, sqrt
class Geometry:
def __init__(self):
self.init()
def get_med_coordinate(lon1, lat1, lon2, lat2):
lat_med = (lat1+lat2) / 2
lon_med = (lon1+lon2) / 2
return lat_med, lon_med
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def km_to_mile(distance):
distance = distance *0.621371
return distance |
fe877605ead1810bedaad9ba24cbc29217af1cc3 | rishabh0071/JUMBLED_WORD_GAME | /jumbled_word_game.py | 1,739 | 3.640625 | 4 | import tkinter
from tkinter import *
import random
from tkinter import messagebox
answers = [
"python",
"java",
"swift",
"canada",
"india",
"mexico",
"legend",
"dragon",
"well",
"king"
]
words = [
"nptoyh",
"avja",
"wfsit",
"cdanaa",
"aidin",
"ixocem",
"delegn",
"nodgra",
"lewe",
"inkg",
]
num = random.randrange(0,10,1)
def res():
global words,answers,num
num = random.randrange(0,10,1)
lb1.config(text=words[num])
e1.delete(0,END)
def default():
global words,answers,num
lb1.config(text=words[num])
def checkans():
global words,answers,num
var = e1.get()
if var == answers[num]:
messagebox.showinfo("Success","this is a correct answer")
res()
else:
messagebox.showerror("ERROR","this is not correct ")
e1.delete(0, END)
root=tkinter.Tk()
root.geometry("330x400")
root.title("Jumbled")
root.configure(background="black")
lb1= Label(
root,
text="Your here",
font=("Verdana",18),
bg="#000000",
fg="#ffffff",
)
lb1.pack(pady=30,ipady=10,ipadx=10)
ans1 = StringVar()
e1=Entry(
root,
font=("Verdana",16),
textvariable = ans1,
)
e1.pack(ipady=5,ipadx=5)
btncheck = Button(
root,
text="check",
font=("Comic sans ms", 16),
width=16,
bg="grey",
fg="dark green",
command=checkans,
)
btncheck.pack(pady=40)
btnreset=Button(
root,
text="Reset",
font=("Comic sans ms", 16),
width=16,
bg="grey",
fg="red",
command=res,
)
btnreset.pack()
default()
root.mainloop() |
97ed0e9e7cb9aa35b933c8c72e9fbb146a8a71ec | mnizhadali-afg/PythonCourse | /ch05/GeneratorExpression.py | 123 | 3.78125 | 4 | numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
for value in (x ** 2 for x in numbers if x % 2 != 0):
print(value, end=' ') |
71ba3be9cdb1fb1a5288c001716fd2278c1325e0 | iamnst19/python-advanced | /Fundamentals_First/Functions/return.py | 1,351 | 4.1875 | 4 | cars = [
{'make': 'AUDI', 'model': 'Q2 Dsl', 'mileage': 19896, 'price': 17800},
{'make': 'AUDI', 'model': 'A6 SW Dsl', 'mileage': 87354,'price': 52000},
{'make': 'SKODA', 'model': 'Fabia', 'mileage': 90613, 'price': 11000},
{'make': 'AUDI', 'model': 'A4 SW Dsl', 'mileage': 47402, 'price': 93000},
{'make': 'VOLKSWAGEN', 'model': 'Touran', 'mileage': 28588, 'price': 87000},
{'make': 'AUDI', 'model': 'A4 Dsl', 'mileage': 66053, 'price': 62000},
]
def calculated_mpg(car): # you can add as many as parameters you want
mpg = car["mileage"] / car["price"]
return mpg # here the function ends and none of the code evaluated after this
def car_name(car):
name = f"{car['make']} {car['model']}"
return name
def print_car_info(car):
name = car_name(car)
mpg = calculated_mpg(car)
print(f"{name} does {mpg} mpg miles per gallon")
for car in cars:
mpg = print_car_info(car) # we can call the fuction here without returning as we have already printed it above, printing this will
#show the None for name and mpg
# if the print_Car_info was returned instead of printed then we could have printed in the function call
#################
# divide 2 numbers
def divide(x,y):
if y ==0:
return "You tried to divide by zero"
else:
return x / y
ans = divide(6,3)
print(ans) |
82110073b33ca9e06b82ac93bbcb966ee8f6bd0d | Super-Rookie/testproject | /practice projects/Somelikeithoth CYOA.py | 3,956 | 4.03125 | 4 | import random
player_hp = 50
enemy_hp = 10
boss_hp = 15
loot = 0
name = input("Enter a name: ")
print("You have been given a bow and some arrows and have been tasked with one goal: Defeat the boss in the cave.")
print("You enter the cave and find footprints that leads to a path going to the right.")
choice_one = input("Should you continue right? (Y / N) ").lower()
if choice_one == "y":
print("\nYou've decided to head right towards the footprints. While walking you hear a noise in the distance")
print("and you come across blood on the walls. An enemy is close. You draw your bow and prepare to strike.")
print("A shadowy figure emerges from the distance. You ready your bow, set aim and fire. The enemy spots you")
print("and unsheathes a weapon of his own.")
player_attack = random.randint(5, 15)
enemy_attack = random.randint(1, 10)
player_hp -= enemy_attack
enemy_hp -= player_attack
print(f"\n{name}'s HP: {player_hp}")
print(f"Enemy HP: {enemy_hp}\n")
if enemy_hp <= 0:
loot += 100
else:
print("You withdraw more arrows and continue shooting projectiles. The enemy is quick, and returns fire.\n")
player_attack = random.randint(5, 20)
enemy_attack = random.randint(1, 10)
player_hp -= enemy_attack
enemy_hp -= player_attack
print(f"\n{name}'s HP: {player_hp}")
print(f"Enemy HP: {enemy_hp}\n")
loot += 100
print(f"*{name} picked up {loot} gil*\n")
print("You've defeated the enemy that was protecting the boss. Nice job! Now it's time to move forward.\n")
print("It also looks like you have enough gil to afford a potion.")
heal = input("Would you like to restore some health before moving forward? (Y / N) ")
if heal == "y" and loot == 100:
restore_health = random.randint(1, 5)
player_hp += restore_health
loot -= 100
print(f"\n*{name} gained {restore_health} HP*")
print(f"{name}'s HP: {player_hp}")
print(f"Current Gil: {loot}\n")
else:
print("Let's not waste any more time.\n")
print("There are a few paths that lead toward the back of the dungeon, where the bosses lair resides.")
print("Let's gather our scattered arrows and see if we can figure out which way is forward.\n")
print("You wander the cave a bit more and find a few bits of linen. Could it be from a fallen comrade?\n")
print("After taking a few more steps forward you begin to hear some music in the background.")
print("The enemy is close. You get your bow out and prepare for the kill shot.")
print("You take aim. If you're lucky you'll get a nice head shot and it will all be over.")
choice_two = input("Are you ready? (Y / N) ").lower()
if choice_two == "y":
player_attack = random.randint(1, 20)
boss_attack = random.randint(10, 25)
player_hp -= boss_attack
boss_hp -= player_attack
print(f"{name}'s HP: {player_hp}")
print(f"Boss HP: {boss_hp}\n")
if boss_hp <= 0:
print("Critical hit!")
else:
print(f"You just lost {boss_attack} HP! This guy is good, much better than the last enemy you fought.")
print("Regardless, it's imperative that you survive and take this enemy out.")
player_attack = random.randint(10, 20)
boss_attack = random.randint(5, 15)
player_hp -= boss_attack
boss_hp -= player_attack
print("\n*woosh* *woosh*")
print("\nJust a bit more...")
print(f"\n*{name} loses {boss_attack} HP*")
print(f"\n{name}'s HP: {player_hp}")
print(f"Boss HP: {boss_hp}")
print("\nLooks like it's all over now. The boss has been defeated and we can go home.")
print("*final fantasy victory theme plays*")
else:
print("\n*sigh* I knew you weren't ready.")
else:
print("\nI guess you're scared?") |
47295c61a44cfd497988c0ab9265732b3fc7a8ad | tony-x-lin/susd_search | /susd_lqr/plotting_tools/plot.py | 865 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def cost_plot(z, names):
"""
plot training improvement
"""
plt.figure()
plt.grid()
for i in range(len(z)):
plt.plot(z[i])
plt.legend(names)
plt.title("Cost during Training")
def plot(x, x_lqr, dt):
"""
plot the trajectory of the linear test model
using matplotlib
"""
plt.figure()
Nsteps = x.shape[1]
nb_states = x.shape[0]
t = np.array(range(Nsteps))*dt
leg = []
for s in range(nb_states):
plt.plot(t, x[s,:], '-')
leg.append("$x"+str(s)+"$")
for s in range(nb_states):
plt.plot(t, x_lqr[s,:], '--')
leg.append("$x"+str(s)+"^{(lqr)}$")
plt.grid()
plt.legend(leg, ncol=2)
plt.xlabel("Time (s)")
plt.ylabel("Position (m)")
plt.title("System Trajectory vs lqr")
|
6abadf8bb1200db2ad353e542a3140cd53ad77b3 | jjshanks/project-euler | /007/solution.py | 1,096 | 3.6875 | 4 | # https://projecteuler.net/problem=7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10,001st prime number?
# DEV NOTES
# brute force solution took ~90 seconds
# only checking odds dropped the solution down to ~45 seconds
# only checking known primes less than the square root of the test gives a runtime of ~2 seconds
# breaking after finding the first divisable prime makes the runtime ~0.5 seconds
# side note: testing all numbers (not just odd) gives the same approx run time
import math
# populate initial list of primes
primes = [2]
# total known primes at start is 1
total = 1
# the next test candidate is 3
test = 3
while total < 10001:
prime = True
for x in primes:
# don't test above the square root of the value
if x > math.sqrt(test):
break
# if divisable by a prime stop checking
if test % x == 0:
prime = False
break
# if no divisors found add to known list
if prime:
primes.extend([test])
total += 1
# only test odd numbers
test += 2
print primes.pop()
|
d58289b8eec582ac627e8d36ba2d669ac84386a4 | Mykola-L/PythonBaseITEA | /Lesson3/3_2.py | 268 | 3.765625 | 4 | def two_numbers(a, b):
if a == b:
print('a дорівнює b')
elif (a - b) and 5:
print('a - b = 5')
elif (b - a) and 5:
print('b - a = 5')
elif (a + b) and 5:
print('b + a = 5')
return True
two_numbers(2, 3) |
1576ef3c15f969fb484cb8258ab2574ab72ed86e | Berrio2411/Algoritmos2021-01 | /talleres/tallerfuncionesmap.py | 1,079 | 4.25 | 4 | #Crear una función map que haga lo siguiente:
# Devuelva el cuadrado de cada elemento de la lista
potenciador = lambda valor : valor ** 2
lista = [8,4,23,42,15,33,21]
listaCuadrados = list (map(potenciador, lista))
print (listaCuadrados)
#• Divida a todos los elementos de la lista por el mayor número de la misma
lista2 = [4,8,9,13,25,43,29]
maximo = max (lista2)
normalizador = lambda valor : valor / maximo
listaNormalizada = list (map(normalizador, lista2))
print (listaNormalizada)
#Le reste un número n a la lista
lista3 = [2,5,6,12,25,43,21]
valor_n = 2
restador = lambda elemento : elemento - valor_n
listaRestada = list (map(restador, lista3))
print (listaRestada)
# Le sume un número n a la lista
lista4 = [2,5,6,12,25,43,22]
valor_n = 2
sumador = lambda elemento : elemento + valor_n
listaSumada = list (map(sumador, lista4))
print (listaSumada)
#Todos los elementos multiplicados * 5
lista5 = [2,5,6,12,25,33,21]
multiplo = 5
multiplicador = lambda elemento : elemento * multiplo
listaRestada = list (map(multiplicador, lista5))
print (listaRestada)
|
0b9a35e5ad81d0639e7fe01557ed3765cfd91f7d | Taoge123/OptimizedLeetcode | /DailyChallenge/LC_505.py | 928 | 3.703125 | 4 |
import collections
import heapq
class Solution:
def shortestDistance(self, maze, start, destination) -> int:
m, n = len(maze), len(maze[0])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
heap = [(0, start[0], start[1])]
distance = collections.defaultdict(int)
while heap:
dist, i, j = heapq.heappop(heap)
if [i, j] == destination:
return dist
for dx, dy in directions:
x, y, step = i, j, dist
while 0 <= x < m and 0 <= y < n and maze[x][y] == 0:
x += dx
y += dy
step += 1
x -= dx
y -= dy
step -= 1
if (x, y) not in distance or step < distance[(x, y)]:
distance[(x, y)] = step
heapq.heappush(heap, (step, x, y))
return -1
|
c1b16b56afbfd3f4cc9119b2cfb6cc2a35e9ea5e | Leevimseppala/python | /beginner/exercise6_6.py | 1,310 | 3.921875 | 4 | # Kysytään käyttäjältä rajat
lowpoint = int(input("Anna alueen alaraja:\n"))
highpoint = int(input("Anna alueen yläraja:\n"))
# Luodaan kaksi boolean muuttujaa, cont ja found
cont = True
found = False
# Mennään looppiin jossa pysytään niin kauan kunnos cont = False
while cont:
# Käydään läpi jokainen luku rajojen sisällä
for x in range(lowpoint, highpoint + 1):
# Jos luku ei ole jaollinen viidellä se hylätään heti
if x % 5 > 0:
print(f"Luku {x} ei ole jaollinen viidellä, hylätään")
# Jos luku on jaollinen viidellä
# mutta ei jaollinen seitsemällä, se hylätään silti.
elif x % 5 == 0 and x % 7 > 0:
print(f"Luku {x} ei ole jaollinen seitsemällä, hylätään")
# Jos luku on 5 ja 7 jaollinen
# muutetaan found muuttuja Trueksi ja breikataan ulos loopista
elif x % 5 == 0 and x % 7 == 0:
print(f"Luku {x} on jaollinen 5:llä ja 7:llä.")
found = True
break
# Tarkistetaan löytyikö sopiva luku
# printataan teksti ja breikataan ulos loopista.
if found:
print("Lopetaan haku.")
cont = False
break
elif not found:
print("Alueelta ei löytynyt sopivaa arvoa.")
cont = False
break
|
9d3273a5bf924ab227d281fd835a9bdfca338c51 | zeruken117/UWM-WD | /WD/zadanie5.py | 292 | 3.671875 | 4 | a = int(input("Podaj liczbe a: "))
b = int(input("Podaj liczbe b: "))
c = int(input("Podaj liczbe c: "))
if (0<a<=10) and (a>b or b>c):
print('a zawiera sie w przedziale od 0 do 10, oraz a jest wieksze od b lub b jest wieksze od c')
else:
print('warunek nie zostal spelniony') |
3583855ac0b0c578226ad4bbfc007d938d0ac6b3 | navyaramyasirisha/PYTHON2018FALL | /PYTHON/LAB/LAB1/Source/nonrepeat.py | 249 | 3.84375 | 4 | s = input("enter a string of your choice: ")
while s != "":
string_len = len(s)
ch = s[0]
s = s.replace(ch, "")
string_len1 = len(s)
if string_len1 == string_len-1:
print(ch)
break
else:
print("invalid input") |
b8fbffb4370fd7ce91f06b440ce5d18b92c0ad2c | sullivantobias/POO-LG | /Python POO/test.py | 2,186 | 3.6875 | 4 | class Caracter():
def __init__ (self, pseudo, age):
self.pseudo = pseudo
self.age = age
self.race = ""
self.weapons = ""
self.heal = ""
pass
def getRace (self):
return self.race
def setRace (self, race):
self.race = race
def setWeapons (self, weapons):
self.weapons = weapons
def getWeapons (self):
return self.weapons
def setHeal (self, heal):
self.heal = heal
def getHeal (self):
return self.heal
def fight (self):
print("I can't fight")
def healing (self):
print("I can't heal")
def infos (self):
print ("My pseudo is ",self.pseudo," , my age is ",self.age, " and my race is :",self.getRace())
class Warrior (Caracter):
def __init__(self, pseudo, age):
Caracter.__init__(self, pseudo, age)
self.setRace("Warrior")
def walk (self):
print ("I walk like a ",self.getRace())
def fight (self):
if self.weapons:
print ("I can use this",self.getWeapons())
class Thief (Caracter):
def __init__(self, pseudo, age):
Caracter.__init__(self, pseudo, age)
self.setRace("Thief")
def walk (self):
print ("I walk like a ",self.getRace())
def fight (self):
if self.weapons:
print ("I can use this",self.getWeapons())
class Healer (Caracter):
def __init__(self, pseudo, age):
Caracter.__init__(self, pseudo, age)
self.setRace("Healer")
def walk (self):
print ("I walk like a ",self.race)
def healing (self):
if self.heal:
print ("I can use this",self.getHeal())
caracter = [ Warrior ("Garosh", 60), Thief ("BackStabber", 34), Healer ("Healish", 34)]
weapons = [ "Sword", "Dagger", "Stick"]
heal = "Medikit"
i = 0
for value in caracter:
print("\n",caracter[i].__class__.__name__, "Section")
print ("---------------------------------")
caracter[i].setHeal(heal)
caracter[i].setWeapons(weapons[i])
caracter[i].infos()
caracter[i].walk()
caracter[i].fight()
caracter[i].healing()
i = i+1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.