blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2b7eab50904664194aaf601e3ea4f21bf4f46cc1 | D3ee/StudentManagerSystem | /student.py | 225 | 3.515625 | 4 | class Student(object):
def __init__(self,name,gender,tel):
self.name=name
self.gender=gender
self.tel=tel
def __str__(self):
return f'{self.name},{self.gender},{self.tel}'
|
680671eb632109b18486520bbf0201824b2089d3 | mjjk88/game_of_life_simulation | /game_of_life_simulation_package/life_simulation.py | 2,082 | 3.78125 | 4 | import random
from dataclasses import dataclass
@dataclass
class LifeSimulation:
alive_cells_coordinates: set
box_length: int
@staticmethod
def empty_simulation(): # factory method
return LifeSimulation(alive_cells_coordinates=set(), box_length=100)
def generate_initial_state(self, alive_probability=0.25, random_seed=10):
self.alive_cells_coordinates = set()
random.seed(random_seed)
for x in range(self.box_length):
for y in range(self.box_length):
# cell = random.choices(population=[0, 1], weights=[0.95, 0.05])
is_alive = random.random() < alive_probability # [0.0, 1.0) < p
if is_alive:
self.alive_cells_coordinates.add((x, y))
def generate_next_state(self):
next_alive_cells_coordinates = set()
for x in range(self.box_length):
for y in range(self.box_length):
""" Check number of alive neighbours """
alive_neighbours_number = self._check_alive_neighbours_number(x, y)
""" Rules of living in next generation:
- cell stays alive when has 2 or 3 alive neighbours
- cell becomes alive when has 3 alive neighbours.
If means, regardless of the current state, 3 alive neighbours ensure life in the next generation.
"""
if alive_neighbours_number == 3 or \
((x, y) in self.alive_cells_coordinates and alive_neighbours_number == 2):
next_alive_cells_coordinates.add((x, y))
self.alive_cells_coordinates = next_alive_cells_coordinates
def _check_alive_neighbours_number(self, x, y):
alive_neighbours = 0
for i in range(x-1, x+2):
for j in range(y - 1, y + 2):
if (i, j) != (x, y) and (i, j) in self.alive_cells_coordinates: # we cannot count current cell but just alive neighbours
alive_neighbours += 1
return alive_neighbours
|
855b5993cf3c4780102c22cb0e60a0823da7abc1 | andreplacet/exercicios_python | /exercicio43.py | 420 | 3.78125 | 4 | nome = str(input('Qual seu nome? ')).strip()
altura = float(input('Qual Sua Altura? (m)'))
peso = float(input('Qual o seu peso? (kg)'))
imc = peso / (altura ** 2)
print('O seu imc {}, é de {:.1f}!'.format(nome.capitalize(), imc))
if imc < 18.5:
print('Voce esta abaixo do peso normal')
elif imc >= 18.5 and imc < 25:
print('Voce esta no seu peso ideal')
elif 25 <= imc < 30:
print('Voce esta no sobrepeso')
|
b7ec4f2a20af2386b112ffe81571ad593ac87fb3 | profnssorg/claudioSchefer1 | /6_11.py | 461 | 3.8125 | 4 | """Programa 6_11.py
Descrição:Modificar programa da listagem 6.15 usando for.
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
n = int(0)
# Entrada de dados
n
# Processamento
while True: # este while não pode ser alterado para for pq não sabemos o número de repetições.
n = int(input("Digite um número (0 sai):"))
if n == 0:
break
L.append(n)
# Saída de dados
for e in L:
print(e)
|
a7d0cf53b9402e50619ff78ff09aa71686f9c98c | systembase-kikaku/python-learn | /chapter3/for.py | 219 | 3.5625 | 4 | def myfor(itr, cb):
_itr = iter(itr)
while True:
try:
v = next(_itr)
cb(v)
except StopIteration as e:
break
nums = [1, 2, 4]
myfor(nums, lambda x: print(x))
|
c3014098006e4bb1e67e81bd1dcd2c8dcd0fca43 | jochasinga/mini-hashmap | /hashmap.py | 1,715 | 3.515625 | 4 | import hashlib
from collections import deque
class HashMap(object):
def __init__(self, size = 100):
"""
Create a HashMap object. size default to 100. Anywhere less
than that is very likely to get high collisions.
"""
if size is not None:
self._array = [deque() for x in range(size)]
else:
raise ValueError('size cannot be None (default = 100)')
self.size = size
def _keytoindex(self, key):
"""
Compute the index of the array based on the modulo of the
md5 digest of the key and the hashmap's array's length.
"""
m = hashlib.md5()
m.update(key)
long_number = int(m.hexdigest(), 16)
print('long_number {}'.format(long_number))
index = long_number % len(self._array)
print('index {}'.format(index))
return index
def put(self, key, val):
"""
Save the value into the hashmap entry and delete
the value with a duplicate key.
TODO: Create a sub list of the past versions of values
with duplicate keys instead of deleting them.
"""
i = self._keytoindex(key)
# This will never happen
# if i > len(self._array):
# new_arr = [deque() for x in range(self.size)]
# old_arr = self._array
# self._array = old_arr + new_arr
q = self._array[i]
# check if there's duplicate key and delete the data
index_to_del = None
for i, item in enumerate(q):
if key in item:
index_to_del = i
if index_to_del is not None:
del q[index_to_del]
# key can probably be hashed as string
q.appendleft((key, val))
def get(self, key):
index = self._keytoindex(key)
if index > len(self._array):
raise IndexError
else:
q = self._array[index]
for item in q:
if item[0] == key:
return item[1]
return None |
73234d5bb1da9ee85dc39f96a57c2fa08a8329b4 | FrontEndART/SonarQube-plug-in | /test/python/LIM2Metrics/py2/base/common/Python060/Python060.py | 214 | 3.578125 | 4 | from Tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root, width =400, height=400)
xy = 10, 105, 100, 200
canvas.create_arc(xy, start=0, extent=270, fill='gray60')
canvas.pack()
root.mainloop() |
6125147983456c0e4e2ab42ec1dd29acc81a5c7b | yl29/pe | /q0021.py | 1,293 | 3.53125 | 4 | from time import *
import math
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
# Evaluate the sum of all the amicable numbers under 10000.
def process_number():
output = 0
outputarray = []
tempdict = {}
for num in range(2,10000):
temp = 0
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
temp += i+num/i
if not temp == 0:
temp += 1
if not temp == num:
if temp not in tempdict:
tempdict[temp] = [num]
else:
tempdict[temp].append(num)
for index in tempdict:
for num in tempdict[index]:
if (num in tempdict) and (index in tempdict[num]):# and (num not in outputarray):
outputarray.append(num)
output = sum(outputarray)
return output
start = clock()
print process_number()
print clock() - start, "seconds"
|
dbf6c21846c7b9b62d25ef38fbc0647d2f7ef3f6 | ian0510/MTA-python | /day2-4.py | 378 | 3.875 | 4 | import random
ans = random.randint(1,10)
time = 1
while True:
guess = int(input("guess number?"))
if ans == guess:
print("right")
print(time)
break
elif guess < ans:
print("guess a bigger number")
print("wrong")
elif guess > ans:
print("guess a smaller number")
print("wrong")
time += 1 |
adfe5b7e8e210ddce1521fcbcf511beb807e38e9 | enlambdment/my_pcc | /ch_8/input_albums.py | 399 | 3.65625 | 4 | from make_album import make_album
while True:
print("Enter artist name, album title, & optional tracks number: ")
print("\n(Type q to quit at any time) ")
art_n = input("Artist name: ")
if art_n == 'q':
break
alb_t = input("Album title: ")
if alb_t == 'q':
break
trk_n = input("Tracks number (optional): ")
if trk_n == 'q':
break
alb = make_album(art_n, alb_t, trk_n)
print(alb) |
06387130ab2c2a4099c3285871335d26186fc1dd | jk72/learning-python | /week-01-python/class-test.py | 721 | 3.59375 | 4 | # 사칙연산 계산 클래스
class fourcal:
# 두 숫자 입력 받는 함수
def setdata(self, first, second):
self.first = first
self.second = second
# 더하기 계산 함수
def sum(self):
result = self.first + self.second
return result
# 곱하기 계산 함수
def mul(self):
result = self.first * self.second
return result
# 빼기 계산 함수
def sub(self):
result = self.first - self.second
return result
# 나누기 계산 함수
def div(self):
result = self.first / self.second
return result
a = fourcal()
b = fourcal()
print(type(a))
a.setdata(4, 2)
print(a.sum())
b.setdata(3, 7)
print(b.sub())
|
b5886117f95e5062de50632a3267a8daf74a5972 | yossibaruch/learn_python | /learn_python_the_hard_way/ex11.py | 462 | 3.734375 | 4 | print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and weigh %r." % (age, height, weight)
print "How old are you?",
nage = int(raw_input())
print "How tall are you?",
nheight = int(raw_input())
print "How much do you weigh?",
nweight = int(raw_input())
print "So, multiply all gives: %r." % (nage*nheight*nweight)
|
da29798e872e83d535004009a8076cb5b4c755ef | vivekanandabhat/PYTHON-LEARNING | /S05Q04_Fibonacci.py | 747 | 4.3125 | 4 | """ Take a number as input from the user.
Find which Fibonacci number is nearest to that number and print it.
"""
def print_near_fibo(num) :
a = 1
b = 1
c = 2
while (c < num) :
a = b
b = c
c = a + b
if (( c - num ) > ( num - b )) :
print "The nearest fibonacci number to ", num, "is :", b
else :
print "The nearest fibonacci number to ", num, "is :", c
def get_number():
""" This function prompts the user for a number
It returns an integer.
"""
num = raw_input("Enter the number of your choice : ")
return int(num)
# Main starts from here
number = get_number()
print_near_fibo(number)
|
fa4aeaa73fc1197cc6bdc7bef9f0452ea5bcf286 | dylanbram354/Robots_vs_Dinosaurs | /Robos vs dinos - pycharm/dinosaur.py | 839 | 3.515625 | 4 | import random
class Dinosaur:
def __init__(self, type, attack_power, energy_drain=-10):
self.type = type
self.energy = 100
self.attack_power = attack_power
self.health = 100
self.energy_drain = energy_drain
def attack(self, robot):
attack_types = ('claw', 'bite', 'tail', 'kick', 'SPECIAL')
attack = random.choice(attack_types)
attack_statement = f'{self.type} uses {attack} attack against {robot.name}!'
if attack == 'SPECIAL':
attack_statement += f'\nIt does extra damage! But, it drains more energy...'
robot.health -= self.attack_power + 10
self.energy += self.energy_drain - 10
else:
robot.health -= self.attack_power
self.energy += self.energy_drain
return attack_statement
|
a1ef1a9053430ce9213179c1a95c97942a40a7c1 | alfonsochie/task-week-5 | /number 12 week 5.py | 283 | 4.40625 | 4 | def make_form():
Word = input('Enter a word: ')
if Word.endswith('y'):
New_word=Word[:-1]+'ies'
elif Word.endswith(('o', 'ch', 's', 'sh', 'x' ,'z')):
New_word=Word+'es'
else:
New_word=Word+'s'
print(New_word)
make_form()
|
b4e2eff0500b7a4666a4dba665c582c1848004d1 | sherinfazer/python | /python29.py | 222 | 3.953125 | 4 | time = float(input("Input time in sec: "))
day = time // (24 * 3600)
time = time % (24 * 3600)
hour = time // 3600
time %= 3600
min = time // 60
time %= 60
sec = time
print("d:h:m:s-> %d:%d:%d:%d" % (day, hour, min, sec))
|
993525192fa165f20f1810c7ee23f02680456edb | ervaneet82/python | /practice/EDABIT/letter_check.py | 177 | 3.6875 | 4 | def letter_check(lst):
s1, s2 = lst
for char in s2:
if char.lower()in s1.lower():
pass
else:
return False
return True
print(letter_check(["compadres", "DRAPES"])) |
f01a2ca6b050f9ebc8fddc2dab8fc605b5fbb66e | gaochenchao/test | /MyQueue.py | 2,222 | 3.75 | 4 | # -*- coding: utf-8 -*-
# from mystack import MyStack
__author__ = 'gaochenchao'
class QueNode(object):
def __init__(self, value, next):
self.value = value
self.next = next
def __repr__(self):
return self.value
class MyQueue(object):
def __init__(self):
self.head = QueNode(None, None)
self.last = self.head
self.size = 0
def isEmpty(self):
if self.size == 0:
return True
return False
def Len(self):
return self.size
def offer(self, arg):
node = QueNode(arg, None)
self.last.next = node
self.last = node
self.size += 1
def pull(self):
if self.isEmpty():
return None
node = self.head.next
after = node.next
self.head.next = after
self.size -= 1
if self.size == 0:
self.last = self.head
return node.value
def peek(self):
return self.head.next.value
# mq = MyQueue()
# mq.offer(1)
# mq.offer(2)
# mq.offer(3)
# mq.pull()
# mq.pull()
# print mq.peek()
#
# class MyQueue2(object):
#
# def __init__(self):
# self.stack1 = MyStack()
# self.stack2 = MyStack()
# self.size = 0
#
# def isEmpty(self):
# if self.size == 0:
# return True
# return False
#
# def Len(self):
# return self.size
#
# def offer(self, arg):
# self.stack1.push(arg)
# self.size += 1
#
# def pull(self):
# if self.size == 0:
# return
#
# if self.stack2.isEmpty():
# while not self.stack1.isEmpty():
# self.stack2.push(self.stack1.pop())
# self.stack2.pop()
# self.size -= 1
#
# def peek(self):
# if self.size == 0:
# return
#
# if self.stack2.isEmpty():
# while not self.stack1.isEmpty():
# self.stack2.push(self.stack1.pop())
# # print self.stack2.Len()
# print self.stack2.peek()
#
# que = MyQueue2()
# for i in range(88, 99):
# que.offer(i)
#
# # que.peek()
# # que.pull()
# # que.peek()
#
# for i in range(0, que.Len()):
# que.peek()
# que.pull()
|
7732160732a552293600ff7cc200b53b64f983fc | PhoenixGreen/Python-GUI | /Version 1/2.3 GUI - Image slideshow - Version 2.py | 944 | 3.65625 | 4 | from tkinter import *
image_list = [
"trees1.gif", "image 1 description",
"trees2.gif", "image 2 description",
]
current = 0
#Main window & Background image - Tkinter:
window = Tk()
window.title("Background Image and lables")
# Action After Button Press
def after_click():
global current
global images
if current < len(image_list) -2:
current = current +2
else:
current = 0
# Next Image
images = PhotoImage(file = image_list[current]).subsample(3, 3)
my_image = Label(window, image = images)
my_image.grid(row = 0, column = 0, columnspan = 3)
# Next Text Description
description = Label(window, text = image_list[current +1])
description.grid(row = 1, column = 0, columnspan = 2)
# Create Button - Next Image
button_right = Button(window, text = "Next Image", width = 30, command = after_click)
button_right.grid(row = 1, column = 2)
# Start the program
mainloop()
|
43a2e9822ae4639bd94923f8d581e6544f72ff52 | SMAK-OPERATOR/cp | /bisection.py | 993 | 3.9375 | 4 |
def fn(x):
return x ** 3 - 3 * x ** 2 + 9 * x - 8
def check(r, e):
return abs(r) < e
def bisection(f, e, xl, xr):
max_step = 10
steps = 0
print("Погрешность e = %.5f, отрезок [%.5f; %.5f]" % (e, xl, xr))
print("Максимальное количество шагов %d" % max_step)
print("Проверяем границы отрезка")
print("f(%.5f) = %.5f" % (xl, f(xl)))
if check(f(xl), e):
return xl
print("f(%.5f) = %.5f" % (xr, f(xr)))
if check(f(xr), e):
# print("x0 = %.5f" % xr)
return xr
print("Начинаем итерироваться:")
xm = 0
while abs(xr - xl) > e and steps < max_step:
xm = (xl + xr) / 2
print("Этап %d: xl = %.5f, xr = %.5f, xm = %.5f, f(xm) = %.5f" %
(steps, xl, xr, xm, f(xm)))
if f(xm) * f(xl) <= 0:
xr = xm
else:
xl = xm
steps += 1
return xm
bres = bisection(fn, 0.001, 1, 1.5)
print("x = %.5f; f(x) = %.5f" % (bres, fn(bres)))
|
e6d867d0037bbb2013383872a426c5311585c700 | drliebe/python_crash_course | /ch7/three_exits.py | 897 | 4.0625 | 4 | prompt = 'Enter your age to find out the price of your ticket.'
prompt += "\n('quit' to stop): "
active = True
while active:
age = input(prompt)
if age == 'quit':
active = False
elif int(age) < 3:
print('Your ticket is free.')
elif int(age) < 12:
print('Your ticket is $10.')
else:
print('Your ticket is $15.')
while True:
age = input(prompt)
if age == 'quit':
break
elif int(age) < 3:
print('Your ticket is free.')
elif int(age) < 12:
print('Your ticket is $10.')
else:
print('Your ticket is $15.')
age = ""
while age != 'quit':
age = input(prompt)
if age == 'quit':
print('quitting')
elif int(age) < 3:
print('Your ticket is free.')
elif int(age) < 12:
print('Your ticket is $10.')
elif int(age) >= 12:
print('Your ticket is $15.')
|
46afe3887f368c39ee37c2c2dbc0d3de351c48d9 | Jeffereyy/houses | /random.py | 1,191 | 3.59375 | 4 | from graph import *
import random
canvasSize(2000, 2000)
windowSize(2000, 2000)
x, y = 100, 100
colors = ["red", "green", "blue", "pink", "yellow", "brown", "black", "gray", "white", "orange"]
def base():
penColor (random.choice(colors))
brushColor (random.choice(colors))
rectangle (x, y, x + 100 * rate, y + 100 * rate)
def roof():
penColor (random.choice(colors))
brushColor (random.choice(colors))
polygon ([(x - 25 * rate, y), (x + 50 * rate, y - 50 * rate), (x + 125 * rate, y)])
def window():
penColor (random.choice(colors))
brushColor (random.choice(colors))
rectangle (x + 5 * rate, y + 25 * rate, x + 45 * rate, y + 70 * rate)
penColor (random.choice(colors))
brushColor (random.choice(colors))
rectangle (x + 20 * rate, y + 30 * rate, x + 40 * rate, y + 65 * rate)
def door():
penColor(random.choice(colors))
brushColor(random.choice(colors))
rectangle(x + 60 * rate, y + 30 * rate, x + 80 * rate, y + 85 * rate)
def house():
base()
roof()
window()
door()
for _ in range(randint(2, 7)):
rate = random.random() * 2
house()
x += randint(50, 200)
y += randint(50, 200)
run()
|
2cd404e2be4504e4f9ee44c5b3d9de357b09b76e | Qinpeng96/leetcode | /100. 相同的树.py | 1,314 | 4.15625 | 4 | """
100. 相同的树
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
示例 2:
输入: 1 1
/ \
2 2
[1,2], [1,null,2]
输出: false
示例 3:
输入: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
"""
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:return True#q p当前都为空
if not p or not q: return False#q p 当前有一个为空,一个不为空
if p.val != q.val:return False#两者当前值不相等,返回Fasle
#还有一种情况就是两者都不为空,并且值相等,需要左右向下寻找
#只有所有的都为True,最中结果才会为True
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
|
8bed2bd1693684d0e266c66b94a5c2f09622bc65 | GustavoSeibel/Python3 | /counter.py | 275 | 4.34375 | 4 | counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
#another way to use counter
counter = 5
while counter:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter) |
f50b08ed9d4dca2d624df7913f661d6e344553c3 | thiagomfl/python-studies | /functional_programing/map.py | 415 | 3.6875 | 4 | list_1 = [1,2,3]
double = map(lambda x: x * 2, list_1)
print(list(double))
list_2 = [
{'name': 'John', 'age': 31},
{'name': 'Mary', 'age': 37},
{'name': 'Joseph', 'age': 26}
]
only_names = map(lambda p: p['name'], list_2)
print(list(only_names))
only_ages = map(lambda p: p['age'], list_2)
print(sum(only_ages))
phrases = map(lambda p: f'{p["name"]} has {p["age"]} years old.', list_2)
print(list(phrases))
|
7d712c87282365848b8df3e8412808aa66c8140a | sandance/CodePrac | /EDUCATIVE/Sliding_Window/find_all_anagram_in_a_pattern.py | 884 | 3.65625 | 4 | from collections import defaultdict
def find_string_anagram(str, pattern):
window_start = 0
matched = 0
char_freq = defaultdict(int)
result = []
for char in pattern:
char_freq[char] += 1
for window_end in range(len(str)):
right_char = str[window_end]
if right_char in char_freq:
char_freq[right_char] -= 1
if char_freq[right_char] == 0:
matched += 1
if matched == len(char_freq):
result.append(window_start)
#shrink the window
if window_end >= len(char_freq):
left_char = str[window_start]
window_start += 1
if left_char in char_freq:
#matched -= 1
if char_freq[left_char] == 0:
matched -= 1
char_freq[left_char] += 1
return result
|
287486b79dcf318f38eeac6441b0068313b1eb03 | lalet/Test_Qz | /string_gt_ls.py | 999 | 3.984375 | 4 | from functools import reduce
import argparse
#Split the string based on dot character and return the product
def findVal(str1,str2):
str1_list = str1.split(".")
str2_list = str2.split(".")
total1 = get_reduced_val(str1_list)
total2 = get_reduced_val(str2_list)
return total1,total2
#Function to find the product of all elements in a string
def get_reduced_val(in_list):
return reduce(lambda x, y: int(x)*int(y), in_list)
def main():
parser=argparse.ArgumentParser(description='Sting value comparison app')
parser.add_argument('str1', action="store")
parser.add_argument('str2', action="store")
result=parser.parse_args()
total1, total2 = findVal(result.str1,result.str2)
print(total1,total2)
if total1==total2:
print("Values are equal")
elif total1 > total2:
print(str(total1) + "greater than" + str(total2))
else:
print(str(total2) + ":greater than:" + str(total1))
if __name__ == "__main__":
main()
|
3ae43289d9030b6cbc6616764201834bb611bb21 | FMachiavello/tp-python | /TP5/EJ5.py | 1,033 | 4.09375 | 4 | def primeraLetra(cadena):
"""Muesta la primera letra de cada palabra"""
if type(cadena) not in [str]:
raise TypeError("Ingrese una cadena correcta")
cadenaSplit = cadena.split(' ')
letra = ""
for c in cadenaSplit:
letra += c[0]
print("(a) ", letra)
return("OK (a)")
def letraMayuscula(cadena):
"""Muestra las primera letra de cada palabra en mayuscula"""
if type(cadena) not in [str]:
raise TypeError("Ingrese una cadena correcta")
cadenaTitle = cadena.title()
print("(b) ", cadenaTitle)
return("OK (b)")
def palabrasConA(cadena):
"""Muestra las palabras con 'A' que se ingresaron en la cadena"""
if type(cadena) not in [str]:
raise TypeError("Ingrese una cadena correcta")
palabrasA = []
cadenaSplit = cadena.split(' ')
for c in cadenaSplit:
if c[0] == "a" or c[0] == "A":
palabrasA.append(c)
print("(c) ", " ".join(palabrasA))
if len(palabrasA) == 0:
return("Fail (c)")
return("OK (c)")
|
e8a239e11075205edec433d52ab0904cf92cc953 | serenysdfg/learning_codes | /book推荐系统开发实战/标准化方法.py | 2,560 | 3.890625 | 4 | # -*-coding:utf-8-*-
"""
Author: Thinkgamer
Desc:
代码4-1 Python实现标准化方法
"""
import numpy as np
import math
class DataNorm:
def __init__(self):
self.arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.x_max = max(self.arr) # 最大值
self.x_min = min(self.arr) # 最小值
self.x_mean = sum(self.arr) / len(self.arr) # 平均值
self.x_std = np.std(self.arr) # 标准差
def Min_Max(self):
arr_ = list()
for x in self.arr:
# round(x,4) 对x保留4位小数
arr_.append(round((x - self.x_min) / (self.x_max - self.x_min), 4))
print("经过Min_Max标准化后的数据为:\n{}".format(arr_))
def Z_Score(self):#基于均值和标准差
arr_ = list()
for x in self.arr:
arr_.append(round((x - self.x_mean) / self.x_std, 4))
print("经过Z_Score标准化后的数据为:\n{}".format(arr_))
def DecimalScaling(self):#小数定标
arr_ = list()
j = self.x_max // 10 if self.x_max % 10 == 0 else self.x_max // 10 + 1
for x in self.arr:
arr_.append(round(x / math.pow(10, j), 4))
print("经过Decimal Scaling标准化后的数据为:\n{}".format(arr_))
def Mean(self):#均值归一化
arr_ = list()
for x in self.arr:
arr_.append(round((x - self.x_mean) / (self.x_max - self.x_min), 4))
print("经过均值标准化后的数据为:\n{}".format(arr_))
def Vector(self):
arr_ = list()
for x in self.arr:
arr_.append(round(x / sum(self.arr), 4))
print("经过向量标准化后的数据为:\n{}".format(arr_))
def exponential(self):
arr_1 = list()
for x in self.arr:
arr_1.append(round(math.log10(x) / math.log10(self.x_max), 4))
print("经过指数转换法(log10)标准化后的数据为;\n{}".format(arr_1))
arr_2 = list()
sum_e = sum([math.exp(one) for one in self.arr])
for x in self.arr:
arr_2.append(round(math.exp(x) / sum_e, 4))
print("经过指数转换法(SoftMax)标准化后的数据为;\n{}".format(arr_2))
arr_3 = list()
for x in self.arr:
arr_3.append(round(1 / (1 + math.exp(-x)), 4))
print("经过指数转换法(Sigmoid)标准化后的数据为;\n{}".format(arr_3))
if __name__ == "__main__":
dn = DataNorm()
dn.Min_Max()
dn.Z_Score()
dn.DecimalScaling()
dn.Mean()
dn.Vector()
dn.exponential()
|
55d129a149ea283dadfdf10eb8247db3db82e84f | Raj-Bisen/python | /Divisibilityby3&5.py | 580 | 4.21875 | 4 | # Accept number from user and check whether no is divisible by 3 & 5 or not.
# input : 15
# output : true
#input : 4
#output : false
def ChckDivisible(no):
if ((no % 3)==0)&((no % 5)== 0):
return True
else:
return False
def main():
print("Enter the number")
value = int(input())
bret = ChckDivisible(value)
if (bret == True):
print("Number is divisible by 3 & 5")
else:
print("Number is not divisible by 3 & 5")
if __name__=="__main__":
main() |
6c26d19534d0d7e0e39981bbdf21b91cb5b00d4c | cyct123/LeetCode_Solutions | /189.rotate-array.py | 2,392 | 3.796875 | 4 | #
# @lc app=leetcode id=189 lang=python3
#
# [189] Rotate Array
#
# https://leetcode.com/problems/rotate-array/description/
#
# algorithms
# Medium (39.32%)
# Likes: 13295
# Dislikes: 1553
# Total Accepted: 1.4M
# Total Submissions: 3.6M
# Testcase Example: '[1,2,3,4,5,6,7]\n3'
#
# Given an integer array nums, rotate the array to the right by k steps, where
# k is non-negative.
#
#
# Example 1:
#
#
# Input: nums = [1,2,3,4,5,6,7], k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
#
#
# Example 2:
#
#
# Input: nums = [-1,-100,3,99], k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^5
# -2^31 <= nums[i] <= 2^31 - 1
# 0 <= k <= 10^5
#
#
#
# Follow up:
#
#
# Try to come up with as many solutions as you can. There are at least three
# different ways to solve this problem.
# Could you do it in-place with O(1) extra space?
#
#
#
from typing import List
# @lc code=start
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not k:
return
lcm = self.lcm(len(nums), k)
r = lcm // k
for i in range(len(nums) // r):
prev = nums[i]
for _ in range(r):
index = (i + k) % len(nums)
cur = nums[index]
nums[index] = prev
prev = cur
i = index
def gcd(self, a: int, b: int) -> int:
if not b:
return a
return self.gcd(b, a % b)
def lcm(self, a: int, b: int) -> int:
if a > b:
return a // self.gcd(a, b) * b
return b // self.gcd(a, b) * a
# @lc code=end
class Solution1:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
res = []
for i in range(len(nums)):
res.append(nums[(i - k) % len(nums)])
for i in range(len(nums)):
nums[i] = res[i]
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6]
k = 4
Solution().rotate(nums, k)
print(nums)
|
6756d3d2ca53edf452780844168cd178f77e6690 | islambayoumy/Python-Data-Structure | /Singly LinkedList/LinkedList.py | 9,956 | 4.1875 | 4 | # Singly Linked List
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self): # pragma: no cover
"""
Return data/value inside Node
"""
return self.data
def get_next(self): # pragma: no cover
"""
Return the pointer to the Next Node
"""
return self.next
class LinkedList:
def __init__(self):
self.head = None
self.count = 0
def list_count(self, node):
"""
Return number of Nodes in the LinkedList
"""
if not node:
return 0
return 1 + self.list_count(node.next)
def add_head(self, data):
"""
Insert new Node at the beginning of the LinkedList
"""
node = LinkedListNode(data)
node.next = self.head
self.head = node
self.count += 1
return
def add_node(self, data, position):
"""
Insert new Node at a specific position of the LinkedList
"""
pre_node = self.get_node_by_position(position-1)
node = LinkedListNode(data)
node.next = pre_node.next
pre_node.next = node
self.count += 1
return
def add_tail(self, data):
"""
Insert new Node at the ending of the LinkedList
"""
node = LinkedListNode(data)
self.count += 1
if self.head is None:
self.head = node
return
else:
current = self.head
while current.next:
current = current.next
current.next = node
return
def get_head(self):
"""
Return head of LinkedList
"""
return self.head
def get_tail(self):
"""
Return tail of LinkedList
"""
current = self.head
while current.next:
current = current.next
return current
def get_node_by_position(self, position):
"""
Search a node by position
"""
if position <= 1:
return self.get_head()
elif 1 < position <= self.list_count(self.head):
node = self.head
for _ in range(0, position-1):
node = node.next
return node
else:
return self.get_tail()
def get_node_by_data(self, data):
"""
Search a node by data
"""
current = self.head
while current:
if current.data == data:
return current
current = current.next
return
def get_position_of_node_by_data(self, data):
"""
Return position of first occurence of a data
"""
current = self.head
position = 0
while current:
position += 1
if current.data == data:
return position
current = current.next
return
def delete_head(self):
"""
Delete the head of the LinkedList and return the new head
"""
node = self.head
if node:
self.head = node.next
node = None
self.count -= 1
return self.head
def delete_by_position(self, position):
"""
Delete a node of the LinkedList at certain position
"""
pre_node = self.get_node_by_position(position-1)
node = pre_node.next
if self.get_head() in [pre_node, node]:
return self.delete_head()
elif node:
pre_node.next = node.next
node = None
self.count -= 1
return
def delete_by_data(self, data):
"""
Delete a node of the LinkedList by data
"""
node = self.get_node_by_data(data)
node_position = self.get_position_of_node_by_data(data)
pre_node = self.get_node_by_position(node_position-1)
if self.get_head() in [pre_node, node]:
return self.delete_head()
elif node:
pre_node.next = node.next
node = None
self.count -= 1
return
def reverse_list_iterative(self):
"""
Reverse the LinkedList iteratively
"""
pre_node = None
curr_node = self.head
while curr_node:
nxt = curr_node.next
curr_node.next = pre_node
pre_node = curr_node
curr_node = nxt
self.head = pre_node
return
def reverse_list_recursive(self):
"""
Reverse the LinkedList recursively
"""
def reverse_recursive(pre_node, curr_node):
if not curr_node:
return pre_node
nxt = curr_node.next
curr_node.next = pre_node
pre_node = curr_node
curr_node = nxt
return reverse_recursive(pre_node, curr_node)
self.head = reverse_recursive(None, self.head)
return
def print_list(self): # pragma: no cover
"""
Print the whole LinkedList
"""
current = self.head
while current:
print(current.data)
current = current.next
return
def swap_nodes(self, node_data1, node_data2):
"""
Swap two adjacent nodes
"""
if node_data1 == node_data2:
return
pre_node1 = None
curr_node1 = self.head
while curr_node1 and curr_node1.data != node_data1:
pre_node1 = curr_node1
curr_node1 = curr_node1.next
pre_node2 = None
curr_node2 = self.head
while curr_node2 and curr_node2.data != node_data2:
pre_node2 = curr_node2
curr_node2 = curr_node2.next
if not curr_node1 or not curr_node2:
return
if pre_node1:
pre_node1.next = curr_node2
else:
self.head = curr_node2
if pre_node2:
pre_node2.next = curr_node1
else:
self.head = curr_node1
curr_node1.next, curr_node2.next = curr_node2.next, curr_node1.next
def merge_two_sorted_lists(self, mlist):
head_list1 = self.head
head_list2 = mlist.head
newlist = None
if not head_list1:
return head_list2
if not head_list2:
return head_list1
if head_list1 and head_list2:
if head_list1.data <= head_list2.data:
newlist = head_list1
head_list1 = newlist.next
else:
newlist = head_list2
head_list2 = head_list2.next
newhead = newlist
while head_list1 and head_list2:
if head_list1.data <= head_list2.data:
newlist.next = head_list1
newlist = head_list1
head_list1 = newlist.next
else:
newlist.next = head_list2
newlist = head_list2
head_list2 = newlist.next
if not head_list1:
newlist.next = head_list2
if not head_list2:
newlist.next = head_list1
return newhead
def remove_duplicates(self):
"""
Removing duplicate data
"""
current = self.head
previous = None
dupl_values = list()
while current:
if current.data in dupl_values:
previous.next = current.next
current = None
else:
dupl_values.append(current.data)
previous = current
current = previous.next
def compare_two_lists_is_equal(self, head2):
"""
Check if two linkedlists are identically equals
"""
current1 = self.head
current2 = head2
if not current1 and not current2:
return 1
count1 = self.list_count(current1)
count2 = self.list_count(current2)
if count1 != count2:
return 0
while current1 and current2:
if current1.data != current2.data:
return 0
current1 = current1.next
current2 = current2.next
return 1
def count_occurence(self, data):
"""
Count number of occurence of a value
"""
count = 0
current = self.head
while current:
if current.data == data:
count += 1
current = current.next
return count
def rotate_list(self, k):
"""
Rotating the list to kth
"""
p = self.head
q = self.head
previous = None
count = 0
while p and count < k:
previous = p
p = p.next
q = q.next
count += 1
p = previous
while q:
previous = q
q = q.next
q = previous
q.next = self.head
self.head = p.next
p.next = None
def is_palindrome(self):
"""
Check if the list is palindrome
(could be read the same from both sides)
"""
s = ""
current = self.head
while current:
s += current.data
current = current.next
return s == s[::-1]
def move_tail_to_head(self):
"""
Move tail of the list to head
"""
current = self.head
pre_tail = None
while current.next:
pre_tail = current
current = current.next
current.next = self.head
self.head = current
pre_tail.next = None
return
"""
Method just for testing
"""
def test_func(): # pragma: no cover
llist = LinkedList()
llist.add_tail("A")
llist.add_tail("B")
llist.add_tail("C")
llist.add_tail("D")
llist.move_tail_to_head()
llist.print_list()
test_func()
|
9e20838910dc48c07cad4997f3bfc23444d4e7d8 | myuakash96/OPS435-NAA | /lab5c.py | 830 | 3.921875 | 4 | #!/usr/bin/env python3
#Author ID: myuakash
def add(number1, number2):
# Add two numbers together, return the result, if error return string 'error: could not add numbers'
try:
return(int(number1)+int(number2))
except:
return('error: could not add numbers')
def read_file(filename):
# Read a file, return a list of all lines, if error return string 'error: could not read file'
try:
f = open(filename,'r')
a = f.readlines()
f.close()
return(a)
except FileNotFoundError:
return('error: could not read file')
if __name__ == '__main__':
print(add(10,5)) # works
print(add('10',5)) # works
print(add('abc',5)) # exception
print(read_file('seneca2.txt')) # works
print(read_file('file10000.txt')) # exception
|
1c6e09f1f5c3657ba06c7ba1ce6b851e13f4bc8b | ecastan960/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 304 | 3.546875 | 4 | #!/usr/bin/python3
def no_c(my_string):
i = 0
Lmy_string = list(my_string)
for x in my_string:
if 'c' == x:
Lmy_string.pop(i)
elif 'C' == x:
Lmy_string.pop(i)
else:
i = i + 1
my_string = ''.join(Lmy_string)
return my_string
|
0b827aaded1dd5f4adbaa2d4c952c5dc8070e0c2 | gabriellaec/desoft-analise-exercicios | /backup/user_026/ch74_2020_04_13_14_22_59_302529.py | 274 | 3.609375 | 4 | def conta_bigramas(palavra):
dic = {}
a = 0
for i in range(len(palavra)-1):
bigrama = palavra[a] + palavra[a+1]
a+=1
if bigrama not in dic:
dic[bigrama] = 1
else:
dic[bigrama]+=1
return dic |
6a375694a8e2b3546cbaa52334658d03b0199c28 | iuga/MiniFlow | /miniflow/losses.py | 1,913 | 4.21875 | 4 | import numpy as np
from miniflow.layers import Layer
"""
Loss/Cost/Objective Functions
-----------------------------
Function that maps an event or values of one or more variables into a real number intuitively representing
some "cost" associated with the event.
Intuitively, the loss will be high if we're doing a poor job of clasifying the training data, and it will
be low if we're doing well.
In other words, the loss function measures how compatible a given set of parameters is with respect to the
ground truth labels in the training dataset. It's defined in such way that making good predictions on the
training data is equivalent to having a small loss.
"""
class MSE(Layer):
def __init__(self, y_true):
"""
The mean squared error cost function.
Should be used as the last node for a network.
"""
self.y_true = y_true
Layer.__init__(self)
def forward(self):
"""
Calculates the mean squared error.
"""
# NOTE: We reshape these to avoid possible matrix/vector broadcast
# errors.
#
# For example, if we subtract an array of shape (3,) from an array of shape
# (3,1) we get an array of shape(3,3) as the result when we want
# an array of shape (3,1) instead.
#
# Making both arrays (3,1) insures the result is (3,1) and does
# an elementwise subtraction as expected.
y = self.y_true.value.reshape(-1, 1)
a = self.inbounds[0].value.reshape(-1, 1)
self.m = self.y_true.value.shape[0]
# Save the computed output for backward.
self.diff = y - a
self.value = np.mean(self.diff**2)
def backward(self):
"""
Calculates the gradient of the cost.
"""
self.gradients[self.y_true] = (2 / self.m) * self.diff
self.gradients[self.inbounds[0]] = (-2 / self.m) * self.diff
|
b1b2a9a03bbbb001e5cb2b47b04cb915cd9878ce | mchen7588/python_bday | /program.py | 852 | 4.0625 | 4 | import datetime
def header():
print('------------------------')
print('----------bday----------')
print('------------------------')
def get_bday():
print('bday??')
year = int(input('year [YYYY]: '))
month = int(input('month [MM]: '))
day = int(input('day [DD]: '))
return datetime.date(year, month, day)
def calculate_days(bday, today):
this_year_bday = datetime.date(year=today.year, month=bday.month, day=bday.day)
return (this_year_bday - today).days
def print_bday_info(days):
if days < 0:
print('{} days ago'.format(-days))
elif days > 0:
print('{} days to go'.format(days))
else:
print('happy bday!!!')
def main():
header()
bday = get_bday()
today = datetime.date.today()
days = calculate_days(bday, today)
print_bday_info(days)
main()
|
4f6d030d9f0ee39ccee47f15d3f3d29230e481ee | minxiii/TIL_python | /day4/funcLab3.py | 520 | 3.890625 | 4 | def expr(a,b,c):
if c == '+':
ans = a + b
elif c== '-':
ans = a - b
elif c== '*':
ans = a * b
elif c== '/':
ans = a / b
else :
ans = None
return ans
s = '연산 결과 : '
result = expr(6,3,'+')
if result!= None:
print(s,result)
else:
print('수행불가')
result = expr(6,3,'-')
if result!= None:
print(s,result)
else:
print('수행불가')
result = expr(3,3,'a')
if result!= None:
print(s,result)
else:
print('수행불가') |
74b9d801dc363655e1c48a9320ee9593fcb010a8 | jacobpad/CSE250 | /week01/w1a.py | 1,428 | 3.796875 | 4 | # %%
import pandas as pd
import altair as alt
# %%
alt.data_transformers.enable("json")
# %%
# Reading in data
url = (
"https://github.com/byuidatascience/data4python4ds/raw/master/data-raw/mpg/mpg.csv"
)
mpg = pd.read_csv(url)
mpg
# %%
displ_vs_hwy = alt.Chart(mpg).encode(x="displ", y="hwy").mark_circle()
displ_vs_hwy
# %%
# I'm not too sure about this part of the reading/assignmemnt
# chart = (alt.Chart(<DATA>)
# .encode(<ENCODINGS>)
# <.mark_*()>)
# %%
# Run Chart(mpg).mark_point(). What do you see?
alt.Chart(mpg).mark_point()
# %%
# The shape of mpg is 234 rows, 11 columns
mpg.shape
# %% [markdown]
# What does the `drv` variable describe? According to the [data](https://github.com/byuidatascience/data4python4ds/blob/master/data.md#fuel-economy-data-from-1999-to-2008-for-38-popular-models-of-cars) `drv` means "the type of drive train, where f = front-wheel drive, r = rear wheel drive, 4 = 4wd"
# %%
# Make a scatterplot of `hwy` vs `cyl`
hwy_vs_cyl_chart = alt.Chart(mpg).encode(x="cyl", y="hwy").mark_circle()
hwy_vs_cyl_chart
# %%
# What happens if you make a scatterplot of `class` vs `drv`? Why is the plot not useful?
# It has nothing to prove regarding the hypothesis that "cars with big engines use more fuel."
class_vs_drv_chart = alt.Chart(mpg).encode(x="class", y="drv").mark_circle()
class_vs_drv_chart
# %%
# Save the chart required
displ_vs_hwy.save("displ_vs_hwy.png")
# %%
|
413fa1999b89775f35620ca787fd6004d6b13faf | dallasmcgroarty/python | /General_Programming/CSV/writing.py | 1,310 | 3.953125 | 4 | # writing to csv files
# can use lists of dicts to write to csv
# writer - creates a write object for writing to csv
# writerow - method on writer to write a row to the CSV
from csv import writer, DictWriter, DictReader
# with open('CSV/cats.csv', 'w') as f:
# csv_writer = writer(f)
# csv_writer.writerow(["Name", "Age"])
# csv_writer.writerow(["Blue","3"])
# csv_writer.writerow(["Sam", "4"])
# writing to CSV files using dictionaries
with open('CSV/cats.csv', 'w') as f:
headers = ["Name", "Breed", "Age"]
csv_writer = DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow({
"Name": "Garfield",
"Breed": "Tabby",
"Age": 10
})
# using dictwriter and dictreader
# convert cm in csv to inches
def cm_to_in(cm):
return float(cm) * 0.393701
with open('CSV/fighters.csv') as f:
csv_reader = DictReader(f)
fighters = list(csv_reader)
with open('CSV/inches_fighters.csv', 'w') as f:
headers = ["Name", "Country", "Height"]
csv_writer = DictWriter(f, fieldnames=headers)
csv_writer.writeheader()
for fighter in fighters:
csv_writer.writerow({
"Name": fighter["Name"],
"Country":fighter["Country"],
"Height": cm_to_in(fighter["Height (in cm)"])
}) |
e500693fc24d1d6e6dc55a7291e96469e5f7faff | acbueff/coursera-network-data | /project6.py | 332 | 3.703125 | 4 | import json
import urllib
address = raw_input('Enter json: ')
url = urllib.urlopen(address)
input = url.read()
info = json.loads(input)
print 'Retrieved ',len(info),' characters'
print (info)
sum = 0
count = 0
for item in info['comments']:
count +=1
sum += item['count']
print 'Count: ',count
print 'Sum: ', sum |
03dc07949fa91805fbaaf3e7fe64ea6b2165688e | omaribrahim4/decisionMakingSystem | /DecisionMakingSystem/utils/KeybordListener.py | 955 | 3.625 | 4 | '''
Created on Jan 9, 2018
@author: Ibrahim Ali Fawaz
this class listens to keyboard entries from the user.
'''
from pynput import keyboard
import time
def on_press(key):
if key==keyboard.Key.left:
setsteering(-1)
if key==keyboard.Key.right:
setsteering(1)
def on_release(key):
if key==keyboard.Key.left:
setsteering(0)
if key==keyboard.Key.right:
setsteering(0)
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
def thread1():
global steeringAngle
steeringAngle=0
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
time.sleep(1)
def getSteering():
global steeringAngle
return steeringAngle
def setsteering(st):
global steeringAngle
steeringAngle=st
|
b6b95b693de1829ee700dd6a2f759640f7778e21 | viswan29/Leetcode | /Dynamic Programming/buy_&_sell_with_transaction_fee.py | 1,662 | 4.09375 | 4 | '''
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
'''
class Solution:
def maxProfit(self, prices: List[int], fee: int):
n = len(prices)
buy = -prices[0] # stores value with extra stock
sold = 0 # stores max profit till now (bsbs)
for i in range(1, n):
nbuy = max(buy, sold-prices[i]) # max(prv day buy or buy today)
# (sold-prices[i]) means buy on prv sold
nsold = max(sold, buy+prices[i]-fee) # max(prv day sell or sell today)
# (buy+prices[i]-fee) means sell on prv buy with transaction fee
buy = nbuy
sold = nsold
return sold |
4837418eced7f89ee2c81cdd1c8f9d39991943a4 | Shikha8789/Python-Programs | /Loops/Program3.py | 302 | 4.3125 | 4 | # Write a python program to print all alphabets from a to z. - using while loop
res = ""
index = 97 # Integer value of a = 97
while index!=123: # Integer value of z = 123
res+=chr(index) # chr() take iterable as input and convert them into ASCII character
index = index+1
print(res)
|
29531eb9bbbd52bc0c947e4bcc7269bc2a4f0abb | Aasthaengg/IBMdataset | /Python_codes/p02713/s409854027.py | 163 | 3.671875 | 4 | from math import gcd
k=int(input())
cnt=0
for i in range(1,k+1):
for j in range(1,k+1):
a=gcd(i,j)
for k in range(1,k+1):
cnt+=gcd(a,k)
print(cnt)
|
9e66dee2773fc2104cb150247d7ec8300a14fa97 | vividwang/python-start | /7-5.py | 194 | 4.0625 | 4 | age = int(input('How old are ya?'))
if age < 3:
print('You are for free.')
elif age > 3 and age < 12:
print('You have to pay 10 dollers.')
else :
print('You have to pay 15 dollers.') |
af42d627ea55450d85c0412f9e6659272a5a67cd | PatiKoszi/FirstStepsPython | /Wisielec.py | 775 | 3.765625 | 4 | import random
print("Podaj pseudonim: ")
nick = input()
#haslo = "skarpeta"
lista = ["jedenastopietrowiec", "ostatni"]
haslo = str(lista[random.randint(0, len(lista)-1)])
tablica = list(haslo)
for i in range(len(haslo)):
tablica[i] = '_'
# print(tablica)
print(' '.join(tablica))
zycia = 6
while zycia > 0:
print(nick, "Pozostalo ci ", zycia, "zyc")
# litera = input("Podaj litere: ")
print(nick, "Podaj litere: ")
litera = input()
if litera in haslo:
for i in range(len(tablica)):
if haslo[i] == litera:
tablica[i] = litera
print(' '.join(tablica))
if ''.join(map(str, tablica)) == haslo:
print(nick, "ZWYCIESTWO!!!")
break
else:
zycia -= 1
|
91bdb3c66f875337fb8a3a9e97df6875b577cca5 | Omkar02/FAANG | /G_418_SentenceScreenFitting.py | 673 | 3.796875 | 4 | # import __main__ as main
# from Helper.TimerLogger import CodeTimeLogging
# fileName = main.__file__
# fileName = fileName.split('\\')[-1]
# CodeTimeLogging(Flag='F', filename=fileName, Tag='String', Difficult='Medium')
def wordsTyping(sentence, rows, cols):
sentence = " ".join(sentence) + " "
n = len(sentence)
total = 0
for i in range(rows):
total += cols
if sentence[total % n] == ' ':
total += 1
else:
while total > 0 and sentence[(total - 1) % n] != ' ':
total -= 1
return int(total / n)
rows = 3
cols = 6
sentence = ["a", "bcd", "e"]
print(wordsTyping(sentence, rows, cols))
|
461bdc0d0e6ad4c7f056fe0cd949e49ba9e00fa1 | Bjolav/INFO135_Assignments | /zit010_assignment1.py | 1,819 | 3.78125 | 4 | def task1():
oxford = 171476
korean = 1100373
italian = 260000
counter = 0
while oxford > 1:
oxford = oxford / 2
if oxford >= 0.5:
counter += 1
print(f"The Oxford dictionary requires", counter, "steps")
counter = 0
while korean > 1:
korean = korean / 2
if korean >= 0.5:
counter += 1
print(f"The Korean dictionary requires", counter, "steps")
counter = 0
while italian > 1:
italian = italian / 2
if italian >= 0.5:
counter += 1
print(f"The Italian dictionary requires", counter, "steps")
def task2():
class House:
def __init__(self):
owner.self = owner
owner = "landlord"
def print_welcome():
print("Welcome landlord!")
def task3():
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
if self.head != None:
start = self.head
while self.head != None:
print(self.head.data)
self.head = self.head.next
self.head = start
elif self.head == None:
print("Nothing is in this linked list")
def add(self, data_new):
node_next = Node(data_new)
if self.head == None:
self.head = node_next
return None
node_last = self.head
while node_last.next != None:
node_last = node_last.next
node_last.next = node_next
linked_list = LinkedList()
def main():
task1()
task2()
task3()
if __name__ == "__main__":
main() |
f758a5c4d437d5e33960a1db74ed6377d5147beb | hfujikawa/DataSci | /pd_df_diff.py | 1,163 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 09:34:00 2020
https://teratail.com/questions/184798
@author: i2m
"""
import pandas as pd
import numpy as np
df1 = pd.DataFrame([[1,1,2],
[1,2,3]]) # この行がペアになる
df2 = pd.DataFrame([[1,2,4,5], # この行がペアになる
[2,3,3,3]])
# 先頭2列(タプルとして)のハッシュ値を得る
df1['hash'] = df1.apply(lambda r: hash((r[0],r[1])),axis=1)
df2['hash'] = df2.apply(lambda r: hash((r[0],r[1])),axis=1)
# ハッシュ値をインデックスとする
df1 = df1.set_index('hash',drop=True)
df2 = df2.set_index('hash',drop=True)
# インデックスで内部結合
# 重複列において右側はそのまま、左(M)側の重複列名には「_dup」を付加する
df = pd.merge(df1,df2,left_index=True,right_index=True, how='inner',suffixes=['_dup',''])
# 左(M)側の重複列は不要なので削除
for col in df.columns:
if '_dup' in str(col):
df = df.drop(str(col), axis=1)
df = df.reset_index(drop=True) # 通常のインデックスに戻す
print(df)
"""
0 1 2 3
0 1 2 4 5
""" |
603ed622d3a77237245a40b0090b4c5c1bf7547b | JangHwanBae132/CodingTest | /solution/210806/위장.py | 428 | 3.640625 | 4 | def solution(clothes):
answer = 0
dic = {}
makeDic(dic, clothes)
answer = 1;
answer = makeAnswer(answer, dic)-1
return answer
def makeDic(dic, clothes):
for c in clothes:
if c[1] not in dic.keys():
dic[c[1]] = [c[0]]
else:
dic[c[1]].append(c[0])
def makeAnswer(answer, dic):
for key in dic.keys():
answer *= len(dic[key])+1;
return answer
|
f5bf0c32645b3861412eda39df000c3cecd1b679 | fatadel/cs50 | /pset6/credit/credit.py | 1,571 | 4.4375 | 4 | import sys
# "counter", shows current digit's position
count = 1
# final "checksum"
checksum = 0
# After the last step of the while loop last digit will be stored in n;
# The digit before it will be stored here in penultimateDigit
# We knowingly initialize it with invalid number since its unknown and can be determined after the first step
# and only if there is more than 1 digit in the number
penultimateDigit = -1
# Prompt user for the credit card number
# Prompt again if it's not an appropriate number
while True:
n = input("Number: ")
try:
n = int(n)
break
except ValueError:
continue
# Calculate the checksum
while n // 10 != 0:
if count % 2 == 0:
checksum += ((n % 10) * 2 % 10 + (n % 10) * 2 // 10)
else:
checksum += n % 10
penultimateDigit = n % 10
count += 1
n //= 10
# Do the same for the last digit
if count % 2 == 0:
checksum += (n * 2 % 10 + n * 2 // 10)
else:
checksum += n
# Check if the checksum is correct
if checksum % 10 != 0:
print("INVALID")
sys.exit(0)
# Check for appropriate credit cards
if ((n == 3 and penultimateDigit == 4) or (n == 3 and penultimateDigit == 7)) and count == 15:
print("AMEX")
elif ((n == 5 and penultimateDigit == 1)
or (n == 5 and penultimateDigit == 2)
or (n == 5 and penultimateDigit == 3)
or (n == 5 and penultimateDigit == 4)
or (n == 5 and penultimateDigit == 5)) and count == 16:
print("MASTERCARD")
elif n == 4 and (count == 13 or count == 16):
print("VISA")
else:
print("INVALID") |
51f7f78310ee79c40c71261a3b815790b9a845d3 | faseehahmed26/Python-Practice | /forloop.py | 90 | 3.953125 | 4 |
sum=0
x=int(input("enter n value"))
for val in range(1,x+1):
sum=sum+val
print(sum)
|
fa10ec9ed25ee23d4a383d6f320a6a1aacb03e03 | SuperLavrik/Home_work | /test_3.py | 190 | 3.59375 | 4 | # a = float(input("Input a - "))
# b = float(input("Input b - "))
# c = float(input("Input c - "))
a = 50
b = 42
c = 88
print("( a * b + 4) / ( c - 1 ) = %.2f" % (( a * b + 4) / ( c - 1 )) ) |
d991e3275452bafae7673f2da7262c978f8b411a | aileentran/coding-challenges | /minidxsumoftwolists.py | 2,269 | 3.765625 | 4 | """leetcode challenge: 599. Minimum Index Sum of Two Lists
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
Example 1:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
Note:
The length of both lists will be in the range of [1, 1000].
The length of strings in both lists will be in the range of [1, 30].
The index is starting from 0 to the list length minus 1.
No duplicates in both lists.
"""
# thoughts
# input: two lists
# output: list w/item found in both lists and least list idx sum - ex: (0 + 1)
# empty list var
# sum idx var = None
# i = idx list 1
# k = idx list 2
# while loop -> idx can loop through both
# if item in list 1 == item in list 2
# add i and k
# if sum == None or sum == i + k
# sum = i + k
# append item
# else if i + k < sum,
# reset list - list = []
# append current item
# outside of loop
# return list
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
same_fave = []
sum_idx = None
# idx of list1
i = 0
while i < len(list1):
if list1[i] in list2:
#TODO: get idx of item in list[2]
# idx of item in list2
k = list2.index(list1[i])
a_sum = i + k
if sum_idx == None or sum_idx == a_sum:
sum_idx = a_sum
same_fave.append(list1[i])
elif a_sum < sum_idx:
sum_idx = a_sum
same_fave = []
same_fave.append(list1[i])
i+=1
return same_fave
|
0cc03a5f14c14bd5b825e5099e04e5590c987366 | BubbaHotepp/code_guild | /python/rot13.py | 569 | 3.90625 | 4 | import string
def main():
cypher_text = []
user_input = input('Please enter plain text to encode: ')
alphabet_lower = string.ascii_lowercase
alphabet_upper = string.ascii_uppercase
x = 13
for chr in user_input:
if chr in alphabet_lower:
cypher_text += alphabet_lower[(alphabet_lower.find(chr) + x) % 26]
elif chr in alphabet_upper:
cypher_text += alphabet_upper[(alphabet_upper.find(chr) + x) % 26]
else:
cypher_text.append(chr)
print(''.join(cypher_text))
main() |
ebed4f45812fc4921999d7176c1f06b2830755e4 | psy1088/Algorithm | /Programmers/메뉴 리뉴얼.py | 815 | 3.546875 | 4 | from itertools import combinations
def check(dict):
arr = []
if not dict:
return arr
else:
max_val = max(list(dict.values()))
if max_val < 2:
return arr
for d in dict:
if dict[d] == max_val:
arr.append(''.join(d))
return arr
def solution(orders, course):
res = []
for _len in course:
dict = {}
for order in orders:
if len(order) < _len:
continue
for case in combinations(order, _len):
case = tuple(sorted(case))
if case in dict:
dict[case] += 1
else:
dict[case] = 1
for x in check(dict):
res.append(x)
return sorted(res)
|
39ae1de8b5d31a4e39f9b2df9451db1b9e4dcbe0 | LukeMurphy/RPI | /testing/tkinter and threading/tkinter_test_2.py | 1,176 | 3.65625 | 4 | import random
import time
from Tkinter import *
root = Tk()
root.title = "Game"
root.resizable(0, 0)
root.wm_attributes("-topmost", 1)
canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
self.id2 = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id2, 245, 100)
self.canvas.bind("<Button-1>", self.canvas_onclick)
self.text_id = self.canvas.create_text(300, 200, anchor="se")
self.canvas.itemconfig(self.text_id, text="hello")
def canvas_onclick(self, event):
self.canvas.itemconfig(
self.text_id, text="You clicked at ({}, {})".format(event.x, event.y)
)
def draw(self):
self.canvas.move(self.id, 0, -1)
self.canvas.after(5, self.draw)
def draw2(self):
self.canvas.move(self.id2, 0, 1)
self.canvas.after(50, self.draw2)
ball = Ball(canvas, "red")
ball.draw() # Changed per Bryan Oakley's comment.
ball.draw2() # Changed per Bryan Oakley's comment.
root.mainloop()
|
6da537a6786f641973b74e8439b0df14f3d5f095 | Bublinz/Python-Expert | /Assignments/student_fidel/assignment3.py | 904 | 4.15625 | 4 | # welcome to our office.
while True:
print('what is your name?')
name = input()
if name != 'vicTOria':
continue
print('hello, vicTOria you are welcome.')
print('please enter your email account?')
email = input()
if email != 'ViCtOrIa@gmail.com':
continue
print('please enter your password')
password = input()
if len(password) >= 8:
print('successfully granted')
print('how old are you? ')
age = input ()
print('you will be ' + str(int(age)+1) + ' next years')
print('where are you from? ')
address = input ()
print('what is the name of your best friend')
name = input ()
print('what is your occupation? ')
occupation = input ()
print('what is your complexion')
complexion = input()
print('request granted')
break
|
9eacf5a0f00d9d21ce2d734ac840fb100c4e464a | Dongzi-dq394/leetcode | /python_solution/0247.py | 1,524 | 3.515625 | 4 | class Solution:
def findStrobogrammatic(self, n: int) -> List[str]:
# Solution by myself: Brute Force + Palindrome (160ms: 24.60%)
if n==1: return ['0', '1', '8']
ele = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
res = []
for i in range(n//2):
if i==0:
res += ['1', '6', '8', '9']
else:
temp = []
for sub_res in res:
for char in '01689':
temp.append(sub_res+char)
res = temp
if n&1:
temp = []
for sub_res in res:
for char in '018':
temp.append(sub_res+char)
res = temp
for i in range(len(res)):
for j in range(n//2-1, -1, -1):
res[i] += ele[res[i][j]]
return res
# Solution from Discussion: Backtracking (104ms: 84.37%)
# Very Tricky!
mapping = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
res = []
def backtracking(left, right, l, r):
if l>r:
res.append(left+right)
return
if l==r:
for char in '018':
res.append(left+char+right)
return
for char in mapping:
if char=='0' and l==0:
continue
backtracking(left+char, mapping[char]+right, l+1, r-1)
backtracking('', '', 0, n-1)
return res |
96b4e316c06131bcb1df4d745cd13dadf6dd4fd3 | zachMelby/TicTacToe | /tic_tac_toe.py | 4,570 | 4.34375 | 4 | __author__ = 'zacharymelby'
# Global list to represent the board, initialized to all blank spaces
BOARD = ['', '', '', '', '', '', '', '', '']
# Chars to represent the board locations numbering (i.e., the values
# the user will enter to specify their play)
LOCATION_LIST = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def welcomeMessage():
'''
This non-returning function will display the greeting to the user
'''
print('')
print('This program will allow two players to play the game of tic-tac-toe.')
print("Player 1 has 'X', and player 2 has 'O'.")
def displayBoard(BOARD):
'''
This non-returning function will loop through the borad and display all the
current moves in a grid
'''
# for loop to step through the game board
for i in range(len(BOARD)):
# If no play has been made at 'i' location, print a dash
if BOARD[i] == '':
print(' - ', end='')
# Else print the appropriate value
else:
print('', BOARD[i], '', end='')
# Print empty string and new line to display the board as a 3x3 array
if i == 2:
print('')
if i == 5:
print('')
print('')
def getMove(BOARD, LOACTIONS, player):
'''
This funciton will take in the board, a list of valid moves, and the current player.
It will get the move from the current player and add their move to the board.
This will not return anything, just modify the game board.
'''
# stuff here
print('')
displayBoard(BOARD)
# Show what number user should input to complete their move
print('Using the board positions shown below...\n')
print(' 1 2 3 \n 4 5 6 \n 7 8 9 \n')
print(player[0], end='')
move = int(input(', enter your move: '))
while move not in LOACTIONS:
print('You entered an invalid move, please retry')
print(player[0], end='')
move = int(input(', enter your move: '))
BOARD[LOACTIONS.index(move)] = player[1]
def win(board, player):
"""
This function will check the board for all possible wining
scenarios and return True if those conditions are met, ortherwise
it will return False.
"""
# Check rows
if board[0] == player[1] and board[1] == player[1] and board[2] == player[1]:
return True
elif board[3] == player[1] and board[4] == player[1] and board[5] == player[1]:
return True
elif board[6] == player[1] and board[7] == player[1] and board[8] == player[1]:
return True
# Check Columns
elif board[0] == player[1] and board[3] == player[1] and board[6] == player[1]:
return True
elif board[1] == player[1] and board[4] == player[1] and board[7] == player[1]:
return True
elif board[2] == player[1] and board[5] == player[1] and board[8] == player[1]:
return True
# Check diag
elif board[0] == player[1] and board[4] == player[1] and board[8] == player[1]:
return True
elif board[2] == player[1] and board[4] == player[1] and board[6] == player[1]:
return True
else:
return False
def tieGame(BOARD):
#if win(BOARD, player) == False:
if '' in BOARD:
return False
else:
return True
def main():
# Display the welcoming message and get player 1 and 2
welcomeMessage()
name1 = input('Enter the name of payer 1: ')
player1 = (name1, 'X')
name2 = input('Enter the name of player 2: ')
player2 = (name2, 'O')
print(player1[0], "you start. You are playing 'X'")
last_player = ''
gameover = False
tie = False
# Start game loop
while gameover == False and tie == False:
getMove(BOARD, LOCATION_LIST, player1)
last_player = player1[0]
gameover = win(BOARD, player1)
if gameover == False:
print('gameover = ', gameover)
tie = tieGame(BOARD)
if tie == False:
print('tie = ', tie)
getMove(BOARD, LOCATION_LIST, player2)
last_player = player2[0]
gameover = win(BOARD, player2)
print('gameover = ', gameover)
if gameover == False:
tie = tieGame(BOARD)
print('tie = ', tie)
# show final state of board
displayBoard(BOARD)
# if game is won
if gameover == True:
print(last_player, end='')
print(', you win!')
# if game is a tie
elif tie == True:
print('Game ends in a tie, everyone is a winner!')
main()
|
d0c0960c9613b012e1c4970b39522bef039e6a69 | bhanuponguru/ag_py | /agpy/timer.py | 1,177 | 3.546875 | 4 | # Initial code written by Stevo.
import time
class TimerException(Exception):
pass
class Timer:
def __init__(self):
self.start_time = get_current_ms()
self.running = True
self.current_time = 0
def restart(self):
self.start_time = get_current_ms()
self.running = True
self.current_time = 0
def pause(self):
self.running = False
self.current_time = get_current_ms() - self.start_time
def resume(self):
self.running = True
self.start_time = (get_current_ms() - self.current_time)
self.current_time = 0
def get_elapsed(self):
if self.running == False:
return int(self.current_time)
else:
return int(get_current_ms()-self.start_time)
def set_elapsed(self, elapsed):
if elapsed < 0:
raise TimerException("This value must be at least 0")
self.starttime = (get_current_ms() - elapsed)
if self.running == False:
self.current_time = elapsed
elapsed = property(get_elapsed, set_elapsed)
def get_current_ms():
ctime = time.time()
ctime *= 1000
return ctime
|
1603fdb19fb341049a51f67382d5c5755b489563 | RyanT0m/Uno-Multiplayer | /Server.py | 1,612 | 3.71875 | 4 | #!/usr/bin/env python3
import socket
class Server(socket.socket):
'''
Server represents the server side communication for Uno
'''
def __init__(self, *args, **kwargs):
super.__init__(socket.AF_INET, socket.SOCK_STREAM)
self.port = kwargs.get("port")
self.host = kwargs.get("host")
self.data = None
if not host:
self.host = self._getHost()
if not port:
self.port = self._getPort()
def _getHost(self):
'''
Get host will attempt to return the host Ipv4 address using socket library
inputs
None
outputs
return -- string of Ipv4 address
'''
try:
return socket.gethostbyname(socket.gethostname())
except:
print("[Error] - Unable to obtain host IP address")
def _getPort(self):
'''
Will get a random port to initiate the connection
inputs
None
outputs
return -- integer value for port
'''
return random.randint(4000,5000)
def start(self):
'''
Starts listening on host and port, then connects to first host and stores recieved
data until no more data is sent
inputs
None
outputs
None
'''
self.bind((self.host,self.port))
s.listen()
connection, address = s.accept()
with connection:
while True:
data = conn.recv(1024)
if not data:
break
self.data += data
|
06cc32021053708b5512612fc154ce3aabcfdc49 | akenYu/learnpy | /showme/04/countword.py | 437 | 4.0625 | 4 | # 第 0004 题:任一个英文纯文本文件,统计其中的单词出现的个数
filename = 'hello.txt'
line_counts = 0
word_counts = 0
char_counts = 0
with open(filename, 'r') as f:
for line in f:
word = line.split()
line_counts += 1
word_counts += len(word)
char_counts += len(line)
if __name__ == '__main__':
print('line counts', line_counts)
print('word counts', word_counts)
print('char_counts', char_counts) |
232ef2abad728705e82715a5465d64c4730bc5c5 | ShadowKyogre/project-euler | /problem35.py | 727 | 3.65625 | 4 | import math
from collections import defaultdict
def isPrime(num):
if num == 2: return True
divisor=2
while divisor < math.sqrt(num):
if divisor % num == 0:
return False
divisor+=1
else:
return True
cache=defaultdict(lambda: bool(1))
def primeSieve(maxnum):
sqrt=math.sqrt(maxnum)
for i in range(2,int(sqrt)+1):
if isPrime(i):
j=2
while i*j <= maxnum:
cache[i*j]=False
j+=1
primeSieve(int(1E6))
cnt=0
for i in range(2,int(1E6)):
if cache[i]:
digits = list(str(i))
digits.insert(0,digits.pop())
while int(''.join(digits)) != i:
if not cache[int(''.join(digits))]:
break
digits.insert(0,digits.pop())
else:
cnt+=1
|
0668b6517d686599c6d049cd3dddfd0c478348f7 | SudhamathiAthi/Codekata | /PositiveORNegORZero.py | 202 | 4.1875 | 4 | num=input("Enter the number to test:")
if(num>0):
print +str(num),"is a positive number"
elif(num<0):
print +str(num),"is a negative number"
else:
print "It is zero"
|
1a6990528fd61328ad23280663176275d1737b5e | eronekogin/leetcode | /2020/add_digits.py | 344 | 3.5 | 4 | """
https://leetcode.com/problems/add-digits/
See https://leetcode.com/problems/add-digits/discuss/68580/Accepted-C%2B%2B-O(1)-time-O(1)-space-1-Line-Solution-with-Detail-Explanations
for more details.
"""
class Solution:
def addDigits(self, num: int) -> int:
if not num:
return 0
return 1 + (num - 1) % 9
|
4ebada4c62f2b17535bee347cab6a870c1c8de10 | jingjuanwang/Python_project | /hanoi.py | 277 | 3.953125 | 4 | def move(n, fr, to, sapce):
print str(n) + ' ' + 'from' + ' ' + str(fr) + 'to' + str(to)
def hanoi(n, fr, to, space):
if n == 1:
return move(n, fr, to, space)
else:
hanoi(n-1, fr, space, to)
hanoi(1, fr, to, space)
hanoi(n-1, space, to, fr)
hanoi(3, 'p', 'q', 'r') |
aa19c231a58cdd8cc4ec1d2e630fa16705e4ea04 | ylana-mogylova/Python | /Examples/is_s2_rotation_of_s1.py | 1,028 | 4.46875 | 4 | """
Assume you have a method isSubstring which checks if one word is a isSubstring of another.
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only
one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat").
"""
def is_substring(s2, s1):
if s2 in s1:
return True
else:
return False
def is_rotation_substring(s1, s2):
string_big = s1 + s1
if is_substring(s2, string_big):
return True
else:
return False
if __name__ == "__main__":
list_of_inputs = [("waterbottle", "erbottlewat"), ("waterbottle", "aterbottlew"), ("waterbottle", "ewaterbottl"),\
("waterbottle", "awterbottlew")]
for each_tuple in list_of_inputs:
s1 = each_tuple[0]
s2 = each_tuple[1]
if is_rotation_substring(s1, s2):
print("Substring %s is a rotation of %s" % (s2, s1))
else:
print("Substring %s is not a rotation of %s" % (s2, s1))
|
ceb4789679f4fa8f0b7dccca275347344a824e0e | rajeshsurana/PythonPortfolio | /WordGame/hand_class.py | 3,067 | 4.125 | 4 | import random
class Hand(object):
def __init__(self, n):
'''
Initialize a Hand.
n: integer, the size of the hand.
'''
assert type(n) == int
self.HAND_SIZE = n
self.VOWELS = 'aeiou'
self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
# Deal a new hand
self.dealNewHand()
def dealNewHand(self):
'''
Deals a new hand, and sets the hand attribute to the new hand.
'''
# Set self.hand to a new, empty dictionary
self.hand = {}
# Build the hand
numVowels = self.HAND_SIZE / 3
for i in range(numVowels):
x = self.VOWELS[random.randrange(0,len(self.VOWELS))]
self.hand[x] = self.hand.get(x, 0) + 1
for i in range(numVowels, self.HAND_SIZE):
x = self.CONSONANTS[random.randrange(0,len(self.CONSONANTS))]
self.hand[x] = self.hand.get(x, 0) + 1
def setDummyHand(self, handString):
'''
Allows you to set a dummy hand. Useful for testing your implementation.
handString: A string of letters you wish to be in the hand. Length of this
string must be equal to self.HAND_SIZE.
This method converts sets the hand attribute to a dictionary
containing the letters of handString.
'''
assert len(handString) == self.HAND_SIZE, "Length of handString ({0}) must equal length of HAND_SIZE ({1})".format(len(handString), self.HAND_SIZE)
self.hand = {}
for char in handString:
self.hand[char] = self.hand.get(char, 0) + 1
def calculateLen(self):
'''
Calculate the length of the hand.
'''
ans = 0
for k in self.hand:
ans += self.hand[k]
return ans
def __str__(self):
'''
Display a string representation of the hand.
'''
output = ''
hand_keys = self.hand.keys()
hand_keys.sort()
for letter in hand_keys:
for j in range(self.hand[letter]):
output += letter
return output
def update(self, word):
"""
Does not assume that self.hand has all the letters in word.
Updates the hand: if self.hand does have all the letters to make
the word, modifies self.hand by using up the letters in the given word.
Returns True if the word was able to be made with the letter in
the hand; False otherwise.
word: string
returns: Boolean (if the word was or was not made)
"""
# Your code here
newHand = self.hand.copy()
for letter in word:
if(self.hand.get(letter, 0)<=0):
return False
newHand[letter] -= 1
for letter in word:
self.hand[letter] -= 1
return True
myHand = Hand(7)
print myHand
print myHand.calculateLen()
myHand.setDummyHand('aazzmsp')
print myHand
print myHand.calculateLen()
myHand.update('za')
print myHand
|
d303413fd396b9e36d0d96b14afc581e7b6f5486 | aiktcprogrammersclub/Python_Workshop | /DAY2/palindrome.py | 120 | 3.921875 | 4 |
n = str(raw_input("Enter no ::",))
a=list(n)
if(a==a[::-1]):
print "palindrome"
else:
print "not palindrome" |
e68999f68ebc66d5476fdbda627384d83c8ee9cf | vehery/seven-segment-ocr | /image_selection.py | 1,908 | 3.5625 | 4 | """
image_selection.py
This module gives the user an image to specify selections
in and returns those selections
@author: Suyash Kumar <suyashkumar2003@gmail.com>
"""
import cv2
import sys
# Shared variable declarations
refPts = []
image=1
numSelected=0
"""
Called every time a click event is fired on the displayed
image. Is used to record ROI selections from the user, and
updates the image to place a bounding box highlighting the
ROIs
"""
def click_handler(event, x, y, flags, pram):
global refPts, image, numSelected
if(event == cv2.EVENT_LBUTTONDOWN):
if(len(refPts)==0):
refPts = [(x,y)]
else:
refPts.append((x,y))
elif (event == cv2.EVENT_LBUTTONUP):
refPts.append((x,y))
cv2.rectangle(image, refPts[numSelected*2], refPts[(numSelected*2)+1], (0,255,0), 2, lineType=8)
cv2.imshow("image",image)
numSelected = numSelected+1
def getSelectionsFromImage(img):
global image, refPts, numSelected
image = img
refPts = [] # Reinit refPts
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_handler)
cv2.imshow("image",image)
while True:
#cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
if (key == ord("d")):
break;
if (key == ord("r")):
refPts = refPts[:len(refPts)-2]
numSelected = numSelected-1
image = clone.copy()
if ((len(refPts) % 2) == 0):
print len(refPts)/2
print refPts
for selection in range(0, len(refPts)/2):
roi = clone[refPts[0+(selection*2)][1]:refPts[1+(selection*2)][1], refPts[0+(2*selection)][0]:refPts[1+(2*selection)][0]]
cv2.imshow("ROI"+str(selection), roi)
else:
sys.exit("Selection Capture didn't get an even number of bounding points.")
cv2.waitKey(0)
cv2.destroyAllWindows()
return refPts
|
577ac407e10ef23d7b1d142a3b997d24d11acde9 | omkarindulkar/Python-Training | /Regular Expression/regex4.py | 801 | 3.5 | 4 | # ? (0 or 1)
import re
# batregex = re.compile(r'bat(wo)?man')
# text = batregex.search("I like batman")
# print(text.group())
# * (0 or more)
# batregex = re.compile(r'bat(wo)*man')
# text = batregex.search("I like batwowoman")
# print(text.group())
# + (1 or more)
# batregex = re.compile(r'bat(wo)+man')
# text = batregex.search("I like batwoman")
# print(text.group())
# {1,5}
# batregex = re.compile(r'bat(wo){2,4}man')
# text = batregex.search("I like batwowoman")
# print(text.group())
# numregex = re.compile(r'((\d\d\d-)?\d\d\d-\d\d\d\d(,)?){3}')
# num = numregex.search("my phone numbers are 889-889-9805,777-122-1055,932-9122")
# print(num.group())
#Greedy and (?)Non Greedy
numregex = re.compile(r'\d{4,5}')
no = numregex.search(" my fav no is 123456789")
print(no.group())
|
3f3790b0a3a20d306b620a591f38a3f673a23092 | Soliloquiess/Luckyday | /data/triangle.py | 502 | 3.734375 | 4 | class Triangle:
def __init__(self, name, under, height):
self.name = name
self.under = under
self.height = height
def triangle_print(self):
print(f'이름 = {self.name}\n밑변 = {self.under}\n높이 = {self.height}')
def triangle_area(self):
print('*'*40)
print(f'삼각형의 넓이 = {(self.under * self.height)/2}')
print('*' * 40)
def total(self):
self.triangle_print()
self.triangle_area()
print() |
fef5f6c0f816d8dad21f2fb5ea5bdfbd57734dee | spaceymacey/pythonintro | /hangman.py | 3,139 | 4 | 4 | # Let's make Hangman
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''','''
+---+
| |
O |
|
|
|
=========''','''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
|\ |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
|
=========''','''
+---+
| |
O |
/|\ |
/ |
|
=========''','''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
#method showing the picture, the incorrect guesses and current blanks
def displayBoard(HANGMANPICS, missedLetters, correctLetters, myWord):
print(HANGMANPICS[len(missedLetters)])
print("You've taken %d incorrect guesses." % len(missedLetters))
#loop to print out all incorrect guesses
for letter in missedLetters:
print(letter)
#variable to hold blanks
blanks = '_' * len(myWord)
#prints out any correct guesses inside our blanks
for i in range(len(myWord)):
if myWord[i] in correctLetters:
blanks = blanks[:i] + myWord[i] + blanks[i+1:]
print blanks
#method to get the user's input (the actual guessing of the letter)
def getGuess(alreadyGuessedLetters):
while True:
guess = raw_input("Guess a letter!")
guess = guess.lower()
if len(guess) != 1:
print("Please guess one letter :S")
elif guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please enter a letter >.<")
elif guess in alreadyGuessedLetters:
print("You already guessed that letter! >:( ")
else:
return guess
#method to generate a random word
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList.split()) - 1)
return wordList.split()[wordIndex]
#setting up variables as inputs
words = "jazzed bopping jinx joke quiz shivving waxes grogginess faking"
print("Hey there, let's play hangman!")
myWord = getRandomWord(words)
gameOver = False
correctLetters = ""
missedLetters = ""
#main loop
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, myWord)
guess = getGuess(correctLetters + missedLetters)
#check for user's guess
if guess in myWord:
correctLetters = correctLetters + guess
#check if player got all the letters
win = True
for i in range(len(myWord)):
if myWord[i] not in correctLetters:
win = False
break
if win:
print("You've guessed the word!")
gameOver = True
#user guesses incorrect letter
else:
missedLetters = missedLetters + guess
if (len(HANGMANPICS) - 1) == len(missedLetters):
displayBoard(HANGMANPICS, missedLetters, correctLetters, myWord)
print("You've lost! The word is %s." % myWord)
gameOver = True
if gameOver:
answer = raw_input("Do you want to play again?")
answer.lower()
if answer == "yes":
myWord = getRandomWord(words)
gameOver = False;
correctLetters = ""
missedLetters = ""
else:
break
|
d9e3dcc0687ef81e48f7a6d842958901c83a8b0b | optionalg/cracking_the_coding_interview_python-1 | /ch8_recursion_and_dynamic_programming/8.12_eight_queens.py | 1,210 | 4.15625 | 4 | # [8.12] Eight Queens: Write an algorithm to print all ways of
# arranging eight queens on an 8x8 chess board so that none
# of them share the same row, column, or diagonal. In this case,
# "diagonal" means all diagonals, not just the two that bisect
# the board.
import unittest
def queens(num_queens):
results = []
grid_size = num_queens
columns = [None]*num_queens
n_ways(columns, 0, results, grid_size)
return results
def n_ways(columns, row, results, grid_size):
if row == grid_size:
results.append(columns)
return
for col in range(0, grid_size):
if is_valid(columns, row, col, grid_size):
cols_copy = columns[:]
cols_copy[row] = col
n_ways(cols_copy, row+1, results, grid_size)
def is_valid(columns, row1, col1, grid_size):
if col1 in columns:
return False
for row2, col2 in enumerate(columns):
if col2 is not None:
if abs(col1 - col2) == abs(row1 - row2):
return False
return True
class Test(unittest.TestCase):
def test_queens(self):
self.assertEqual(len(queens(8)), 92)
if __name__ == '__main__':
unittest.main()
|
6092fa2b31b24d8537cb609bcb82037bdd619ca3 | psr1981/data-structure-and-algorithms | /sorting/selection-sort.py | 408 | 3.65625 | 4 | def selection_sort(a):
for i in range(len(a) - 1):
maxPos = 0
for j in range(len(a) - i ):
if a[j] > a[maxPos]:
maxPos = j;
print ('exchangin value of ', str(maxPos) , ' and ' , str(j) )
temp = a[j]
a[j] = a[maxPos]
a[maxPos] = temp
print (a)
return a
a = [ 2, 4, 1, 8, 7]
print (a)
print (selection_sort(a))
|
b4cbc2310d61cdc85cd0df25c8a050a5cc2e4f32 | charles-fowler/SOM_neural_net | /graph.py | 2,920 | 3.671875 | 4 | class Vertex(object):
def __init__(self,node):
self.id = node
self.adj = {}
def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in self.adj])
def add_neighbor(self, neighbor, weight=0):
self.adj[neighbor] = weight
def get_connections(self):
return self.adj
def get_id(self):
return self.id
def get_weight(self, neighbor):
return self.adj[neighbor]
class Graph:
def __init__(self):
self.vertices = {}
self.num_vertices = 0
def __str__(self):
return str(x for x in self.vertices) + str(self.num_vertices)
def __iter__(self):
return iter(self.vertices.values())
def add_vertex(self, node):
self.num_vertices = self.num_vertices + 1
new_vertex = Vertex(node)
self.vertices[node] = new_vertex
return new_vertex
def get_vertex(self, n):
if n in self.vertices:
return self.vertices[n]
else:
return None
def add_edge(self, frm, to, cost=0):
if frm not in self.vertices:
self.add_vertex(frm)
if to not in self.vertices:
self.add_vertex(to)
self.vertices[frm].add_neighbor(self.vertices[to], cost)
self.vertices[to].add_neighbor(self.vertices[frm], cost) # adds to both vertices
def get_vertices(self):
return self.vertices.keys()
def generate_square_map(rows,columns): # square with no diagonals
g = Graph()
for r in rows:
for c in columns:
g.add_vertex(str(r + c))
for r in rows: # column to column connectors
for ct,cf in zip(columns[:-1],columns[1:]): #ct = column to and rf = row from etc.
#print(r+ct+"-->"+r+cf)
g.add_edge(str(r+ct),str(r+cf),1)
for c in columns: # row to row connectors
for rf,rt in zip(rows[:-1],rows[1:]):
#print(rf+c+"-->"+rt+c)
g.add_edge(str(rf+c),str(rt+c),1)
return g
def generate_triangular_map(rows,columns): # right leaning parallelogram
g = Graph()
for r in rows:
for c in columns:
g.add_vertex(str(r + c))
for r in rows: # pure column to column connectors
for ct, cf in zip(columns[:-1], columns[1:]):
# print(r+ct+"-->"+r+cf)
g.add_edge(str(r + ct), str(r + cf), 1)
for rf, rt in zip(rows[:-1], rows[1:]): # down a column connectors (diagonal right)
for c in columns:
# print(rf+c+"-->"+rt+c)
g.add_edge(str(rf + c), str(rt + c), 1)
for rf,rt in zip(rows[1:],rows[:-1]):
for cf, ct in zip(columns[:-1], columns[1:]):
g.add_edge(str(rf + cf), str(rt + ct), 1)
return g
graph = generate_triangular_map(["A", "B", "C", "D", "E"],["1", "2", "3", "4"])
p = graph.get_vertices()
print(p)
a = graph.get_vertex("B2")
print(a)
|
594d1bfc8ec055b5a407ab5091761beccb404924 | harshnisar/masstoeba | /masstoeba/scripts/sentencesplitter.py | 1,941 | 3.546875 | 4 | '''Module to define functions required to tokenize any language in the world.
'''
import nltk
import csv
from collections import namedtuple
import re, os
#TODO
# Convert the file data into static hardcode data in the end.
#The sentence splitter, will split the given text, in sentences using Punkt Tokenizer.
Lang = namedtuple('Lang',['codename','language', 'need_punkt','stopchar'])
def get_lang_info(lang):
'''Reads langinfo.csv and returns information about the particular language as a namedtuple
Returns in order : codename, language, need_punkt, stopcharlist(unicode)
'''
langinfolist = []
filepath = 'langinfo.csv'
my_dir = os.path.dirname(__file__)
print my_dir
newfilepath = os.path.join(my_dir, filepath)
print newfilepath
with open(newfilepath,'rb') as f:
c = csv.reader(f,delimiter = '\t')
for row in c:
# print row
if row[0] == lang:
langinfolist = row
break
return Lang(lang, langinfolist[1].decode('utf-8'), langinfolist[2]=='True', langinfolist[3].decode('utf-8').split(u','))
def splitter(text,lang):
'''Tokenizes the text(unicode) in any specified language and returns as a list of unicode sentences
Checks whether a language requires the usage of Punkt Tokenizer from hardcoded data about languages. If not, simply splits and returns.
'''
thislang = get_lang_info(lang)
if thislang.need_punkt:
sent_detector = nltk.data.load('tokenizers/punkt/%s.pickle'%(thislang.language))
sentences = (sent_detector.tokenize(text.strip()))
return sentences
else:
sentEnd = re.compile('[%s!?]'%thislang.stopchar[0])
sentList = sentEnd.split(text.strip())
# return text.strip().split(thislang.stopchar[0])
return sentList[:-1]
# print get_lang_info('eng')
# print splitter('hello. what the fuck in goig. Mr. what?','eng') |
48abc77a1f9b7899a7950b6240a894a761bc6a46 | PrasamsaNeelam/CSPP1 | /cspp1-practice/m3/iterate_even_reverse.py | 50 | 3.578125 | 4 | i=10
print('Hello!')
while(i>1):
print(i)
i-=2
|
2664f6fe291cd7071bb776bc21714fbebef5d629 | tuxerman/snippets | /montyHallStatCheck.py | 1,048 | 3.890625 | 4 | import random
switchDoors = True # whether player changes his choice after host opens a door
sampleTries = 100
timesWon, timesLost = 0,0
for iters in range (sampleTries):
# put the car behind a random door
car = (int)(random.uniform(0,3))
#print "Car is behind",car
# pick one door out of the remaining doors to open
iOpen = (int)(random.uniform(0,3))
#print "You initially choose",iOpen
# host picks the other door and offers you the choice
heOpens = 0
while (heOpens == car or heOpens == iOpen):
heOpens = heOpens + 1
#print "Host opens",heOpens
# switch to the other unopened door and play.
finalDoor = 0
if(switchDoors is True):
while (finalDoor == iOpen or finalDoor == heOpens):
finalDoor = finalDoor + 1
#print "You finally choose", iOpen
# check for a win
if (finalDoor == car):
#print "Won"
timesWon = timesWon + 1
else:
#print "Lost"
timesLost = timesLost + 1
print "Times won", timesWon
print "Times lost", timesLost
print "Won", (100*timesWon/(timesWon+timesLost)), "%"
|
47dd74481eec01ef1ba0ef9c69bf7a59d8a2f424 | Wcy20010925/rickandmorty | /Tkinter.py | 1,421 | 3.5 | 4 | '''
GuessNumberGame
'''
import tkinter as tk
import tkinter.messagebox
#s1: creat window
GussNum = tk.Tk()
GussNum.minsize(400,300)
GussNum.title('MyGameGussNumber')
#s2: creat components and
#s3: distribute components
lableshow = tk.Label(GussNum,text='Wellcome to our game!\nplease input yourNumber',height =2)
lableshow.place(x=50,y=10)
entryIn = tk.Entry(GussNum)
entryIn.place(x=50,y=70)
cmdGuss = tk.Button(GussNum,text='Guess')
cmdGuss.place(x=230,y=70)
txtOut = tk.Text(GussNum)
txtOut.place(x=10,y=100)
#s4:events
from random import randint
targetNum = randint(1,11)
count = 0
flagOver = False
def checkNum():
global targetNum
global count
global flagOver
yourNum = eval(entryIn.get())
txt = ''
txt1 = ''
if yourNum == targetNum:
flagOver = True
txt = "Congratulations! good job!"
tk.messagebox.showinfo('Good',txt)
elif yourNum < targetNum:
txt = 'too low!'
txt1 = 'You Can Try'+str(2-count)+'times'
tk.messagebox.showinfo("low",txt)
else:
txt = 'too height!'
txt1 = 'You Can Try'+ str(2-count)+'times'
tk.messagebox.showinfo("height",txt)
txtOut.insert(tk.END,"yourNum is "+str(yourNum)+' '+txt+txt1+'\n')
count += 1
if count >=3:
flagOver = True
def guessClick():
global flagOver
if not flagOver:
checkNum()
cmdGuss['command']=guessClick
GussNum.mainloop()
|
3a118a56e0b1fddc85bc8d20eda81378cc716687 | dalon1/webscrapper | /csv_utils.py | 1,204 | 3.53125 | 4 | import csv
class CSVUtils(object):
@staticmethod
def createCSVFile(file_name, records):
# removing that extra blank line created by default between records.
with open(file_name, 'w', newline='') as csvfile:
# Creating file writer (python) or stream writer (c#)
file_writer = csv.writer(csvfile, delimiter = ',',
dialect = 'excel', quoting = csv.QUOTE_MINIMAL, quotechar='|')
for record in records:
file_writer.writerow([record.bank_name, record.account_name, record.account_range, record.rate])
@staticmethod
def createCSVRecord(stream):
# Example: <bank_name>, <bank_account_name>, <range_rate>, <interest rate>
records = []
for i in range(0, len(stream)):
for j in range(0, len(stream[i]['accounts'])):
print([stream[i]['name'], stream[i]['url'],
stream[i]['accounts'][j]['account_name'], stream[i]['accounts'][j]['account_xpath'] ])
records.append([stream[i]['name'], stream[i]['url'],
stream[i]['accounts'][j]['account_name'], stream[i]['accounts'][j]['account_xpath']])
return records
|
398bea63c04800553156e680e798ccfb515f4c60 | piyushPathak309/100-Days-of-Python-Coding | /Print Half Pyramid Using Loops.py | 899 | 4.375 | 4 | # Write a Python program that prints a pyramid pattern made with asterisks.
#
# The number of rows should be determined by the value of the variable n. This value will be entered by the user.
#
# You may assume that the value of n is a positive integer.
#
# 🔹 Expected Output:
# If the value of n is 5, this is the expected output:
#
# *
# * *
# * * *
# * * * *
# * * * * *
# If the value of n is 10, this is the expected output:
#
# *
#
# * *
#
# * * *
#
# * * * *
#
# * * * * *
#
# * * * * * *
#
# * * * * * * *
#
# * * * * * * * *
#
# * * * * * * * * *
#
# * * * * * * * * * *
n = int(input("Enter a Number :"))
for i in range(1, n + 1):
for j in range(1, n + 1):
if (j >= 6 - i):
print("*", end=" ")
print(" ")
|
1a13e0773950b0acc3ba3880e13dfcd218a62ea0 | bendikjohansen/euler | /projecteuler/level_1/p12.py | 1,240 | 3.921875 | 4 | from typing import List
from functools import reduce
def product(numbers: List[int]):
return reduce(lambda x, y: x * y, numbers, 1)
def find_primes(limit: int) -> List[int]:
is_prime = [False, False, True] + [True] * limit
primes = [2]
for i in range(3, limit, 2):
if is_prime[i]:
primes.append(i)
for j in range(i*i, limit, 2 * i):
is_prime[j] = False
return primes
def count_divisors(number: int, primes: List[int]) -> List[int]:
prime_counts = []
rest = int(number)
for prime in primes:
if prime > rest:
return product([count + 1 for count in prime_counts])
count = 0
while rest % prime == 0:
count += 1
rest //= prime
if count > 0:
prime_counts.append(count)
return 0
def highly_divisible_triangular_number(expected_divisor_count: int) -> int:
primes = find_primes(int(1e7))
for i in range(1, int(1e7)):
number = sum(range(i+1))
divisors_count = count_divisors(number, primes)
if expected_divisor_count < divisors_count:
return number
if __name__ == "__main__":
print(highly_divisible_triangular_number(500))
|
dcbf94b8bc529f81f2951a857e76a6038a33e7ae | wewakeprasad/Learning_Python | /UsingJava.py | 320 | 3.65625 | 4 | planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
#for planent in planents:
#print(planent,' ')
#short_planets=[planet for planet in planents if len(planet)<6]
#short_planets
loud_short_planents=[planet.upper()+' ! ' for planet in planets if len(planet)<6 ]
loud_short_planents |
cc1c6b2216495cc28771462074fe6f7b7fb3dff3 | MathieuTuli/python-shape-grammars | /src/python_shape_grammars/vector.py | 3,330 | 4.21875 | 4 | '''2D Vector for grid-based alignment of the Graph
'''
import math
class Vector:
def __init__(self, x: float, y: float) -> None:
self.x: float = float(x)
self.y: float = float(y)
def __str__(self) -> str:
return f"{type(self).__name__} ({self.x}, {self.y})"
def __add__(self, other: 'Vector') -> 'Vector':
if not isinstance(other, Vector):
raise ValueError("Cannot add vector with other not of type Vector")
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other: 'Vector') -> bool:
return False if not isinstance(other, Vector) else \
self.x == other.x and self.y == other.y and \
type(self).__name__ == type(other).__name__
def left_of(self, other: 'Vector') -> int:
'''Returns int whether or not the vector is the left of the other
@return 0 if not the left vector
@return 1 if the left vector
@return -1 if the vectors are on the same vertical line
'''
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
return 1 if self.x < other.x else 0 if self.x > other.x else -1
def right_of(self, other: 'Vector') -> int:
'''Returns int whether or not the vector is the right of the other
@return 0 if not the right vector
@return 1 if the right vector
@return -1 if the vectors are on the same vertical line
'''
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
return 1 if self.x > other.x else 0 if self.x < other.x else -1
def beneath(self, other: 'Vector') -> int:
'''Returns int whether or not the vector is beneath the other
@return 0 if not beneath the vector
@return 1 if beneath the vector
@return -1 if the vectors are on the same vertical line
'''
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
return 1 if self.y < other.y else 0 if self.y > other.y else -1
def above(self, other: 'Vector') -> int:
'''Returns int whether or not the vector is above the other
@return 0 if not above the vector
@return 1 if above the vector
@return -1 if the vectors are on the same vertical line
'''
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
return 1 if self.y > other.y else 0 if self.y < other.y else -1
def distance_to(self, other: 'Vector') -> float:
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
return math.sqrt(math.pow((self.x - other.x), 2) +
math.pow((self.y - other.y), 2))
def linear_combination(self, other: 'Vector',
value: float, self_value: float = None) -> 'Vector':
if not isinstance(other, Vector):
raise ValueError(f"Passed in vector is not of type Vector")
self_value = value if self_value is None else self_value
return Vector(x=(self.x * self_value) + (other.x * value),
y=(self.y * self_value) + (other.y * value))
|
d950c1a1c8b58ffe73f05a92724681fe1a67af26 | jasdestiny0/Competitive-Coding | /Algo Experts/Merge Linked Lists/solution.py | 484 | 3.90625 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def mergeLinkedLists(headOne, headTwo):
p1=headOne
p2=headTwo
prev=None
while p1!=None and p2!=None:
if p1.value <p2.value:
prev=p1
p1=p1.next
else:
if prev is not None:
prev.next=p2
prev=p2
p2=p2.next
prev.next=p1
if p1 is None:
prev.next=p2
return headOne if headOne.value<headTwo.value else headTwo
|
3c2e81b0127a727ee8bed0df39eb65506159fc3b | Aasthaengg/IBMdataset | /Python_codes/p02418/s544575939.py | 110 | 3.75 | 4 | import re
s=input()
p=input()
s_s=s+s
match=re.search(p,s_s)
if match:
print('Yes')
else:
print('No')
|
c81928abeb8b5375f83feb2be4619e9c6f1cc6cf | clodonil/python-exercicios | /jogo_adivinha_numero.py | 2,399 | 4 | 4 | '''
O Jogo consiste em sorteador 2 numeros, um para cada jogador. Os jogadores tem 3 tentativas
de acertar e quem acertar primeiro leva ou quem chegar mais perto do numero sorteado.
'''
import random
# Controle do while
controle=1
# Lista para guardar quem chegou mais perto
dif_jogador1=[]
dif_jogador2=[]
# garda o ganhador do jogo
ganhador=0
#lista com os jogadores e numero sorteado
jogador={}
# Le o nome dos 2 jogadores e sortea os numeros
jogador[raw_input("Digite o nome do 1 Jogador:")]=random.randrange(0,50)
jogador[raw_input("Digite o nome do 2 Jogador:")]=random.randrange(0,50)
#quem comeca primeiro?
quem_joga_primeiro = random.choice(jogador.keys())
quem_joga_segundo = list((set(jogador.keys())-set([quem_joga_primeiro])))[0]
while controle < 4:
# Jogada do jogador 1
jogada_1 = int(raw_input("JOGADA %d DO JOGADOR %s:" %(controle,quem_joga_primeiro)))
# Verifica se a ganhador
if jogador[quem_joga_primeiro] == jogada_1:
ganhador = quem_joga_primeiro
break
elif jogador[quem_joga_primeiro] > jogada_1:
print "O Numero eh maior"
elif jogador[quem_joga_primeiro] < jogada_1:
print "O Numero eh menor"
# Guarda a distancia do numero sorteado
dif_jogador1.append(abs(jogador[quem_joga_primeiro] - jogada_1))
# Jogada do jogador 2
jogada_2 = int(raw_input("JOGADA %d DO JOGADOR %s:" %(controle,quem_joga_segundo)))
# Verifica se a ganhador
if jogador[quem_joga_segundo] == jogada_2:
ganhador = quem_joga_segundo
break
elif jogador[quem_joga_segundo] > jogada_2:
print "O Numero eh maior"
elif jogador[quem_joga_segundo] < jogada_2:
print "O Numero eh menor"
# Guarda a distancia do numero sorteado
dif_jogador2.append(abs(jogador[quem_joga_segundo] - jogada_2))
# Controle das jogadas
controle += 1
# Verifica se ha ganhador
if ganhador != 0:
print "O Vencedor eh %s" %(ganhador)
else:
# Verifica quem chegou mais perto
dif_jogador1.sort()
dif_jogador2.sort()
if dif_jogador1[0] < dif_jogador2[0]:
print "O Vencedor eh %s, sorteado: %d" %(quem_joga_primeiro, jogador[quem_joga_primeiro])
elif dif_jogador2[0] < dif_jogador1[0]:
print "O Vencedor eh %s, sorteado: %d" %(quem_joga_segundo, jogador[quem_joga_segundo])
else:
print "Empate...."
raw_input("Pressione Enter") |
08a83fcdc2cc2bf1cac59d33e8b30fbd5e140a20 | SingleDreamer/Blog_Project | /app.py | 3,319 | 3.53125 | 4 | from flask import Flask, render_template, request#, redirect, url_for
import sqlite3
app = Flask(__name__)
#x=0
#conn = sqlite3.connect("blog.db")
#p ="create table posts(post_id integer, post_title text, post_author text, post_content text);"
#comm = "create table comments(comment_id integer, comment_content text, comment_author text,p_id integer);"
#c = conn.cursor()
#c.execute(p)
#c.execute(comm)
#conn.commit();
@app.route("/")
def home():
newpost = request.args.get ("new_post", None)
title = request.args.get ("title", None)
author = request.args.get ("author", None)
post = request.args.get ("post", None)
conn = sqlite3.connect("blog.db")
c = conn.cursor()
if newpost == "Post":
q = "Insert Into posts Values('" + title + "','" + author + "','" + post + "');"
c.execute(q)
#x = x + 1
#link = '/'+ title + ''
s = "Select title From posts"
t = "Select author From posts"
u = "Select content From posts"
title_list = []
author_list = []
post_list = []
titles = c.execute(s)
title_list = [(str(x)[3:])[:-3] for x in titles]
authors= c.execute(t)
author_list = [(str(x)[3:])[:-3] for x in authors]
posts= c.execute(u)
post_list = [(str(x)[3:])[:-3] for x in posts]
conn.commit()
print title_list
print author_list
print post_list
return render_template ("index.html",
#ignore link
#link = link,
title_list = title_list,
author_list = author_list,
post_list = post_list)
@app.route("/<title>")
##check if title is unique
def post(title):
t = title.replace ("+", " ")
nc = request.args.get ("new_comment", None)
commentor = request.args.get ("commentor", None)
comment = request.args.get ("comment", None)
print commentor
print comment
conn = sqlite3.connect("blog.db")
c = conn.cursor()
if nc == "Post":
q = "Insert Into comments Values('" + t + "','" + commentor + "','" + comment + "');"
c.execute(q)
commentor_list = []
comment_list = []
a = "select author from posts where title = '" + t + "'"
author = c.execute (a)
authorstr = author= [(str(x)[3:])[:-3] for x in author]
print authorstr
p = "select content from posts where title = '" + t + "'"
post = c.execute (p)
poststr = [(str(x)[3:])[:-3] for x in post]
print poststr
x = "select commentor from comments where title == '" + t + "';"
y = "select comment from comments where title == '" + t + "';"
commentors = c.execute (x)
commentor_list = [(str(x)[3:])[:-3] for x in commentors]
comments = c.execute (y)
comment_list = [(str(x)[3:])[:-3] for x in comments]
conn.commit()
print commentor_list
print comment_list
return render_template ("post.html",
title = t,
author = authorstr[0],
post = poststr[0],
commentor_list = commentor_list,
comment_list = comment_list)
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0",port=8888)
|
6db473b21fb149a295a10d8d30891d80276211d7 | Eunaosei24788/lista3 | /oi4.py | 1,061 | 4.125 | 4 | print("Este programa serve para calcular a média entre duas notas de 0 a 10")
a = int(input("Insira a primeira nota: "))
while a > 10 or a < 0:
print("Este número não é valido")
a = int(input("Insira uma outra nota: "))
b = int(input("Insira a segunda nota: "))
while b > 10 or b < 0:
print("Este número não é valido")
b = int(input("Insira uma outra nota: "))
c = a + b
print("Sua média é: ")
print(c / 2)
print("Deseja fazer outro cálculo?")
d = str(input("Digite sim, ou não: "))
if d == "não":
print("Tchau")
while d == "sim":
a = int(input("Insira a primeira nota: "))
while a > 10 or a < 0:
print("Este número não é valido")
a = int(input("Insira uma outra nota: "))
b = int(input("Insira a segunda nota: "))
while b > 10 or b < 0:
print("Este número não é valido")
b = int(input("Insira uma outra nota: "))
c = 0
c = a + b
print("Sua média é: ")
print(c / 2)
print("Deseja fazer outro cálculo?")
d = str(input("Digite sim, ou não: "))
if d == "não":
print("Tchau")
break
|
3c486ab9ab9d7c2aa9bdaee9f2257ba5baf2a3d6 | yashpal-choudhary/gitlearn | /assignments/task3.py | 627 | 3.90625 | 4 | '''
Problem statement :
Write a function which takes a string s as input and prints the frequencies of all the words in the string. eg: quick fox lazy dog quick donkey fire fox input returns {quick: 2, fox: 2, lazy: 1, dog: 1, donkey: 1, fire: 1}. Use <space> as the delimiter to identify what a word is.
'''
class Task():
def __init__(self, s: str) -> None:
self.s = s.lower()
def main(self):
d = {}
for i in self.s.split():
d[i] = d.get(i, 0) + 1
return d
if __name__ == '__main__':
s = input('Enter the string : ')
result = Task(s).main()
print(result)
|
1d0f3d6c1e62065bfd56a0c5cea6cdec1ffda2cd | akaptur/GlassJack | /pickMove.py | 2,069 | 3.828125 | 4 | # determine which card you should play
import readCard
from theBook import card_book
#returned from cardReader --> card 1 and card 2
test_ace =[('A', 'S', 'A'), ('J', 'H', '10'), ('3', 'H', '3')]
test_pair =[('7', 'S', '7'), ('7', 'H', '7'), ('3', 'H', '3')]
#consider adding a turn count. this is not adequate for all game states
def whos_card(cards):
if len(cards) <5:
player_hand = cards[:2]
dealer_hand = cards[2:]
else:
player_hand = cards[:3]
dealer_hand = cards[2:]
print 'Player\'s Hand is: %s' % player_hand
print 'Dealer\'s Hand is: %s' % dealer_hand
return player_hand, dealer_hand
#refactor such that formatting doesn't need to be repeated for each case
def score(hand):
if len(hand) > 1:
if hand[0][0] == hand[0][1]:
print 'We have two matching cards'
player_hand = ('%s,%s') %(hand[0][0], hand[0][1])
elif hand[0][0] == 'A':
print 'We have an Ace!'
player_hand = ('A,%s') %(hand[0][1])
elif hand[0][1] == 'A':
print 'We have an Ace!'
player_hand = ('A,%s') %(hand[0][0])
else:
player_hand = str(int(hand[0][0]) + int(hand[0][1]))
print 'Your hand is %s' %player_hand
dealer_hand = ('%s') %hand[1][0]
print 'The dealer\'s hand is %s' %dealer_hand
score_round = (player_hand, dealer_hand)
print score_round
return score_round
def pick_move(score):
#match book to score re.match
mv = card_book.get(score)
if mv == 'H':
move = 'Hit!'
elif mv == 'D':
move = 'Double Down!'
elif mv == 'S':
move = 'Stand'
else:
move = 'Split'
return move
def game_main():
cards = readCard.main()
card_value = [x[2] for x in cards]
card_owner = whos_card(card_value)
scored = score(card_owner)
move= pick_move(scored)
print move
return move
'''
1. we need to processs the card to make sure they are in the right form
2. search the dictionary for that pair
3. return the correct move (H, D, S, P)
'''
|
582f8093b9d80ce512cd4daedee6045bc269d917 | Govrie/Govrie.github.io | /HW2-1.py | 307 | 3.5 | 4 | #!/usr/bin/env python3 -tt
"""File: hello.py """
def number_of_matches(J, S):
k = 0
for i in J:
for j in S:
if i == j:
k += 1
return k
#Run only if called as a script
if __name__ == '__main__':
J = 'aA'
S = 'aAABBB'
print(number_of_matches(J,S))
|
ba113ae8de53cd7d69d23ccbf4abb2bbabfade07 | Adelaide95/laba3 | /individual.py | 576 | 4.125 | 4 |
import math
x1 = int(input("Введи координату X1: "))
y1 = int(input("Введи координату Y1: "))
x2 = int(input("Введи координату X2: "))
y2 = int(input("Введи координату Y2: "))
x3 = int(input("Введи координату X3: "))
y3 = int(input("Введи координату Y3: "))
a = math.sqrt( pow(x2 - x1, 2) + pow(y2 - y1, 2) )
b = math.sqrt( pow(x3 - x2, 2) + pow(y3 - y2, 2) )
c = math.sqrt( pow(x3 - x1, 2) + pow(y3 - y1, 2) )
p = (a + b + c) / 2
S = math.sqrt( p*(p - a)*(p - b)*(p - c) )
print(S)
|
18a4ce53a12e6ff61f64d1408d9e931d3293d0d7 | kill-git/p5-datavisualisation | /project/density.py | 532 | 3.546875 | 4 | import pandas
import matplotlib.pyplot as plt
plt.style.use('ggplot')
weather = pandas.read_csv("./data/oxforddata.txt", sep='\t')
target = 'rain'
weather['Period'] = weather['yyyy'].apply(lambda x: 'Before' if x < 1991 else 'After')
weather = weather.groupby(['mm','Period']).mean().reset_index().pivot(index='mm', columns='Period', values=target).reset_index()
print weather
weather[['After','mm','Before']].plot(kind='kde',x='mm')
plt.title('{0} comparison before and after 1991'.format(target))
plt.xlabel(target)
plt.show()
|
e01c4e3e50eee6d6557580433a850eb5892bd27b | windniw/just-for-fun | /leetcode/397.py | 910 | 3.90625 | 4 | """
link: https://leetcode.com/problems/integer-replacement
problem: 给定n,定义一次操作为 n = n // 2 if n is even else n + 1 or n - 1,问至少多少次操作后,n可以为1
solution: 贪心。本质上,操作为消除末位0,当n为偶数时右移,当n为奇数时通过进1或退1将末位置为0;只关注末两位,当其为 11 时的最优操作是
11 -> 00 -> 0 -> nil,而非 11 -> 10 -> 1 -> 0 -> nil,当且仅当 n 为 3 时特殊情况(这时不是尽可能消0,而是要保留倒数第二位的1)
"""
class Solution:
def integerReplacement(self, n: int) -> int:
cnt = 0
while n != 1:
cnt += 1
if n == 3:
return cnt + 1
elif n & 0b1 == 0:
n >>= 1
elif n & 0b10 == 0b10:
n += 1
else:
n -= 1
return cnt
|
5efd4a2ae6d2a0d5ff6eded8f00c0f6bd4e0b26f | viren3196/Python | /sumprimes.py | 199 | 3.515625 | 4 | def prime(n):
if n<=1:
return(False)
for i in range(2,n):
if n%i==0:
return(False)
return(True)
def sumprimes(l):
s = 0
for i in range(0,len(l)):
if(prime(l[i])):
s+=l[i]
return s
|
205333d55f3bacd98a752f884b2ecd25d5c087ac | qfma/ohnolog-dc | /utilities/runner.py | 4,684 | 3.515625 | 4 | #!/usr/bin/env python2.7
''' Run different programs
This file provided various python functions that use the os and sys
modules in order to list files, folders etc.
'''
import sys
import os
import time
from subprocess import Popen, list2cmdline
import subprocess
import multiprocessing
import functools
import logging
import pprint
log = logging.getLogger('pipeline')
def cpu_count():
'''Returns the number of CPUs in the system'''
num = 1
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
pass
elif sys.platform == 'darwin':
try:
num = int(os.popen('sysctl -n hw.ncpu').read())
except ValueError:
pass
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
pass
return num
def exec_commands(cmds, max_task=cpu_count()):
'''
Exec commands in parallel in multiple process. By default it uses
cpu_count() to determine the number of processors and uses all of them.
The user can specify a lower number manually using the max_task parameter.
'''
if not cmds:
return # empty list
def done(p):
return p.poll() is not None
def success(p):
return p.returncode == 0
def fail():
sys.exit(1)
# If the number of processors set is higher than available CPUs
# use all.
if max_task > cpu_count():
max_task = cpu_count()
processes = []
# While loop submits commands to precessors.
while True:
while cmds and len(processes) < max_task:
task = cmds.pop()
print list2cmdline(task)
processes.append(Popen(task))
for p in processes:
if done(p):
if success(p):
processes.remove(p)
else:
fail()
if not processes and not cmds:
break
else:
time.sleep(0.05)
def exec_in_row(cmds):
'''
Exec commands one after the other until finished. This is helpful
if a program is already parallelized, but we have to submit many jobs
after each other.
'''
if not cmds:
return # empty list
def done(p):
return p.poll() is not None
def success(p):
return p.returncode == 0
def fail():
sys.exit(1)
for task in cmds:
print task
p = Popen(task)
p.wait()
if done(p):
if success(p):
print "done!"
else:
fail()
def sub_call(command, stdout=None, shell=False):
'''
Subprocess manager: will log commands and raise an error
if return code does not equal 0.
'''
pretty_command = pprint.pformat(command, indent=4)
log.debug('running command:\n{}'.format(pretty_command))
if stdout:
log.debug('writing to: ' + stdout.name)
subprocess.check_call(command, stdout=stdout, shell=shell)
def multiprocess(iterator):
'''
Returns the multiprocess decorator. This function's only purpose
is to pass its iterator argument along.
'''
def multiprocess_decorator(func):
'''
Returns the multiprocess wrapper
'''
@functools.wraps(func)
def multiprocess_wrapper():
'''
Multiprocesses a given function with arguments specified
by the iterator. This will create a separate process for each
item in the iterator.
'''
# log.info('#' * 45 + ' -> start')
# log.info('Calling multi_processor with target: ' + func.__name__)
jobs = []
for it in iterator:
if isinstance(it, tuple):
j = multiprocessing.Process(target=func,
name=(func.__name__ + ' ' + str(it)),
args=it)
else:
j = multiprocessing.Process(target=func,
name=(func.__name__ + ' ' + it),
args=(it,))
jobs.append(j)
j.start()
for j in jobs:
j.join()
for j in jobs:
if j.exitcode != 0:
raise AssertionError('multi process returned with non-0 '
'exit code')
# log.info('#' * 45 + ' end <-')
return multiprocess_wrapper
return multiprocess_decorator
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.