blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8b1cfa1de0e55ed2c8ce01a2ab8e7ec56188daa5 | spomenka/ZSV-2018-02 | /CodeWars-zadaci/int-cw6-while-znamenke.py | 389 | 3.5625 | 4 | '''
napisi program koji za ucitani broj n mnozi njegove znamenke sve dok ne dodje
do jednoznamenkastog broja. Program treba ispisati koliko puta se mnozenje
moze ponoviti.
Npr.
n=39 ---> 3 (3*9=27, 2*7=14, 1*4=4)
n=999 ---> 4
n=4 ----> 0
'''
n=int(input())
m = 1
z=0
if n < 10:
print (0)
else:
while n > 0:
m = n%10 * m
n = n//10
z+=1
print (z+1)
|
5f8d77b048534a6a06477fc923e33abff0cef22b | jiahuihan98/small-python-projects | /translate Morse Code/morse.py | 1,540 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 14 16:42:07 2016
name: Jiahui Han
net ID: jh5226
Practice 1
"""
def create_dictionary(filename):
in_file = open(filename , 'r')
dict_morse = {}
for line in in_file:
line = line.strip()
line_list = line.split('\t')
key = line_list[0]
value = line_list[1]
dict_morse[key] = value
in_file.close()
return dict_morse
def create_morse(filename , text):
text = text.upper()
dict_morse = create_dictionary(filename)
out_string = ''
for char in text:
if char == ' ':
out_string += ' ' * 7
else:
morse = dict_morse[char]
out_string = out_string + morse + (' ' * 3)
return out_string
def create_text(filename , text):
dict_morse = create_dictionary(filename)
out_string = ''
text_list = text.split(' ' * 7)
for element in text_list:
word_list = element.split(' ' * 3)
for word in word_list:
for key in dict_morse:
if dict_morse[key] == word:
out_string += key
out_string += ' '
return out_string.lower()
def main():
user_input_text = input('Please enter text:')
morse_string = create_morse('Morse Code Chart.txt' , user_input_text)
print(morse_string)
user_input_morse = input('Please enter morse text:')
text_string = create_text('Morse Code Chart.txt' , user_input_morse)
print(text_string)
main() |
e4383b4fac41d8601c9a1ccc2b295d07d8842edf | SophieN12/kyh-practice | /uppg14.py | 899 | 3.75 | 4 | FRUITS = ['banana', 'apple', 'orange']
CARS = ['volvo', 'ford', 'tesla']
COLORS = ['blue', 'yellow', 'pink']
def run():
basket = input("Skriv olikla färger med komma imellan:").split(", ")
# basket = ['volvo', 'is', 'an', 'orange', 'apple', 'yellow']
cars = []
fruits = []
colors = []
rest = []
for item in basket:
if item in CARS:
cars.append(item)
elif item in FRUITS:
fruits.append(item)
elif item in COLORS:
colors.append(item)
else:
rest.append(item)
write_things(sorted(cars), 'Cars')
write_things(sorted(fruits), 'Fruits')
write_things(sorted(colors), 'Colors')
write_things(sorted(rest), 'Misc')
def write_things(items, kind):
print(f"{kind.upper()} ({len(items)}st)")
for item in items:
print(f" {item}")
if __name__ == '__main__':
run()
|
19411038853a02db5b0272d4fbd4cf5275933689 | tkshim/leetcode | /leetcode_0922_SortArrayByParity.py | 796 | 3.5625 | 4 | #!/usr/sortArrayByParityIIbiSolutionn/env python
#!coding: utf-8
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
#愚数、奇数、返り値のリストを用意する
O=[]
E=[]
X=[]
# %は任意の数で割った余りを示す
# 偶数と奇数の箱に分ける。
for i in A:
if i % 2 == 0:
O.append(i)
else:
E.append(i)
# 偶数と奇数のリストから順番に値を取り出す。
for n in range(len(A)/2):
X.append(O[n])
X.append(E[n])
return X
ins001 = Solution()
print ins001.sortArrayByParityII([4,2,5,7])
|
97bd3c3e1bef9767a2872d73d7a5e4aa92d02deb | jmcmartin/iteration | /swap.py | 1,965 | 3.875 | 4 | #Number 1
def replace_letter(phrase, swapped_letter, final_letter):
new_phrase = ''
for i in phrase:
if swapped_letter == i:
new_phrase += final_letter
else:
new_phrase += i
return new_phrase
print replace_letter("banana", "a", "!")
#Number 2
def switch_letters(phrase, swapped_letter_1, swapped_letter_2):
new_phrase2 = ''
for i in phrase:
if swapped_letter_1 == i:
new_phrase2 += swapped_letter_2
elif swapped_letter_2 == i:
new_phrase2 += swapped_letter_1
else:
new_phrase2 += i
return new_phrase2
print switch_letters("textbook", "e", "o")
#Number 3
#Split function to break up the original bad sentence
def split_sentence(first_sentence):
first_sentence += ' '
word = ''
split_list = []
for i in range(len(first_sentence)):
if first_sentence[i] != ' ':
word += first_sentence[i]
else:
split_list.append(word)
word = ''
return split_list
def switch_words(phrase, word1, word2):
new_sentence = ""
check_words = split_sentence(phrase)
for i in range(len(check_words)):
if check_words[i] == word1:
new_sentence += word2
new_sentence += ' '
elif check_words[i] == word2:
new_sentence += word1
new_sentence += ' '
else:
new_sentence += check_words[i]
new_sentence += ' '
return new_sentence
print switch_words("The quick brown fox jumps over the lazy dog", "fox", "dog")
#Number 4
def censor_text(bad_sentence, list_of_censored_words, replacement_words):
good_sentence = ""
check_words = split_sentence(bad_sentence)
for i in range(len(check_words)):
if check_words[i] not in list_of_censored_words:
good_sentence += check_words[i] + ' '
for n in range(len(list_of_censored_words)):
if check_words[i] == list_of_censored_words[n]:
good_sentence += replacement_words[n] + ' '
return good_sentence
print censor_text("What the fuck is this shit you bitch ass", ["fuck", "shit", "ass", "bitch"], ["heck", "poop", "butt", "friend"]) |
42d1956cc6a74439dad7269527f5ab81064641ab | PurpleBubble123/pp | /object_oriented/inherit/polymorphic.py | 1,303 | 3.90625 | 4 | # It is a nice day. Let's get start
# @Author : Boya
# @Time : 27/04/2020 15.00
"""
多态:一类事物有多种形态
多态性:
"""
from abc import ABCMeta, abstractmethod
class Animal:
def run(self):
raise AttributeError("子类必须实现这个方法")
class Person(Animal):
#pass
def run(self):
print("人走")
class Pig(Animal):
def run(self):
print("pig run")
class Dog(Animal):
def run(self):
print("dog run")
person = Person()
person.run()
pig = Pig()
pig.run()
dog = Dog()
dog.run()
"""
多态性
"""
def func(obj):
obj.run()
# 往USB里插入设备
# func(person)
# func(pig)
# func(dog)
class Computer(metaclass=ABCMeta):
@abstractmethod # 不能实例化一个包含抽象方法的类
def usb_insert(self):
pass
class ThinkPad(Computer):
def usb_insert(self):
pass
def usb_run(self,sub_computer):
sub_computer.usb_insert()
class Mouse(Computer):
def usb_insert(self):
print("insert mouse")
class Kerboard(Computer):
def usb_insert(self):
print("insert keyboard")
# buy a computer
computer = ThinkPad()
# buy a mouse
m = Mouse()
# insert mouse
#usb_run(m)
computer.usb_run(m)
# buy a keyboard
k = Kerboard()
#usb_run(k)
computer.usb_run(k)
|
26d781961bd31a69ebadb0a8f1c6485cca073421 | jfmam/algorithm | /taeho/baekjoon/python/easy.py | 146 | 3.515625 | 4 | arr = []
for _ in range(10):
n = int(input())
if n % 42 not in arr:
arr.append(n % 42)
print(len(arr))
arr [[1,2,3,4,5]]
|
f3f2e56a9579fcee20fee1a86d714a91527bcf44 | jamtot/BitAndBobs | /alculator/alculator.py | 4,073 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def formatted(f): return format(f, '.2f').rstrip('0').rstrip('.')
class Drink(object):
def __init__(self,percentage,mil_amount,cost=0.0,name="Your drink"):
self.percentage = percentage
self.mil_amount = mil_amount
self.cost = cost
self.name = name
self.units = (self.percentage*self.mil_amount)/1000.0
self.cost_per_unit = self.cost / self.units
self.alc_content, self.cent_content, self.mil_of_alc = self.get_content()
def get_content(self):
# get the alcoholic content
alc_content = (self.mil_amount/100.0)*self.percentage
if self.cost > 0:
# alcohol per cent
cent_content = alc_content/(self.cost*100.) # cost in euro
# the price per mil of alcohol
mil_of_alc = (self.cost*100.)/alc_content
return alc_content, cent_content, mil_of_alc
def describe(self):
if self.cost > 0:
print "At €%s,"%formatted(self.cost),
print "%.fml of %s at %s%% contains %sml of alcohol."%(
self.mil_amount, self.name, formatted(self.percentage), formatted(self.alc_content))
if self.cost > 0:
print "You get %sml of alcohol per every cent." % (
formatted(self.cent_content))
print "It is %s cent per mil of alcohol." % formatted(self.mil_of_alc)
print "Contains %s units, €%s per unit."% (
formatted(self.units), formatted(self.cost_per_unit) )
def compare(self, other):
# comparisons using a couple of different methods
print "Comparing %s and %s." % (self.name, other.name)
print "-\tBetter bang for buck:",
winner = self if self.comparison(
self.cost_per_unit, other.cost_per_unit, False) else other
print winner.name+" - Cost per unit €%.2f" % winner.cost_per_unit
print "-\tCheaper overall:",
if self.cost<other.cost:
print self.name+" - €%s"%formatted(self.cost)
else: print other.name+" - €%s"%formatted(other.cost)
print "-\tHigher alcoholic content:",
winner = self if self.comparison(
self.percentage, other.percentage) else other
print winner.name+" - %s%%" % formatted(winner.percentage)
print "-\tMore volume:",
winner = self if self.comparison(
self.mil_amount, other.mil_amount) else other
print winner.name+" - %sml" % formatted(winner.mil_amount)
print "-\tPrice per ml of alcohol:",
winner = self.compare_attr(other, "mil_of_alc", False)
print "%s - %sc per ml" % (winner.name, formatted( winner.mil_of_alc))
def comparison(self, d1, d2, higher_wins=True):
if d1==d2:
print "Same for both, returning first -",
return True
elif (d1>d2) == higher_wins:
return True
else:
return False
def compare_attr(self, other, var, higher_wins=True):
if getattr(self,var)==getattr(other,var): print "Same."
elif (getattr(self,var)>getattr(other,var)) == higher_wins:
return self
else:
return other
if __name__ == "__main__":
print
jack = Drink(40, 700, 25.00, "Jack Daniel's (700ml)")
jack.describe()
print "---------"
capn = Drink(35, 1000, 28.00, "Captain Morgan (1000ml)")
capn.describe()
print "---------"
capn2 = Drink(35, 350, 12.00, "Captain Morgan (350ml)")
capn2.describe()
print "---------"
miller = Drink(4.3, 24*500, 24.00, "Miller 24pk (4000ml)")
miller.describe()
print "---------"
# a promotion the local tesco had while I was in college
bush = Drink(40, 350, 5.00, "Bushmills (350ml)")
bush.describe()
print "---------"
huzzar = Drink(37.5, 200, 6.00, "Huzzar 20cl")
huzzar.describe()
print "---------"
print "Some comparisons."
bush.compare(capn2)
print "---------"
jack.compare(capn)
|
e40183bb571631006bac66d7539085f3a76a0040 | BiljanaPavlovic/pajton-kurs | /begginer/2. cas/zadatak2.py | 248 | 3.78125 | 4 | ime=input('Unesite ime:')
prezime=input('Unesite prezime:')
ime_i_prezime=ime+' '+prezime
print(ime_i_prezime)
print('Duzina imena je',len(ime))
print('Duzina prezimena je', len(prezime))
print("Duzina imena i prezimena je", len(ime_i_prezime)-1)
|
83c9aa119280c5221381c2efacbdc1a5699b93cd | lyqtiffany/learngit | /caiNiao/sanShiSiShi/sanShiLiuSuShu.py | 399 | 3.578125 | 4 | #题目:求100之内的素数。
for num in range(1,100):
if num > 1:
for i in range(2, num):
if num % i == 0:
break #break之后测试下一个num
else:
print(num)
num = []
for i in range(2, 101):
flag = 0
for j in range(1, i+1):
if i % j == 0:
flag += 1
if flag == 2:
num.append(i)
print(num) |
f8ef122d7f306fee11fd7eaf9a3e6057d7c634e0 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/1204.py | 2,667 | 3.828125 | 4 | #!/usr/bin/env python
import sys
class b:
IN = sys.stdin
number = 0
@classmethod
def case(cls):
cls.number += 1
return 'Case #%d:' % cls.number
@classmethod
def line(cls, type=str):
line = cls.IN.readline()
return type(line.strip('\n'))
@classmethod
def splitline(cls, type=str):
line = cls.IN.readline()
return [type(x) for x in line.split()]
class Move:
"""
"""
def __init__(self, n_move, move):
self.n_move = n_move
self.move = move
class Robot:
"""
"""
def __init__(self, moves):
self.moves = moves
self.moves.reverse()
self.current_move = None
if len(moves) > 0:
self.current_move = moves.pop()
self.current_position = 1
def do_move(self, n_move):
"""
Arguments:
- `self`:
"""
if self.current_move is None:
return False
if self.current_move.n_move == n_move:
if self.current_position == self.current_move.move:
if len(self.moves) == 0:
self.current_move = None
else:
self.current_move = self.moves.pop()
return True
else:
if self.current_position < self.current_move.move:
self.current_position += 1
elif self.current_position > self.current_move.move:
self.current_position -= 1
else:
if (self.current_position < self.current_move.move):
self.current_position += 1
elif self.current_position > self.current_move.move:
self.current_position -= 1
return False
def go():
"""
Starts the program.
"""
t = b.line(int)
for i in range(t):
moves = b.splitline()
moves_orange, moves_blue = [], []
n_moves = int(moves[0])
for j in range(n_moves):
index = j*2+1
move = Move(j+1, int(moves[index+1]))
if (moves[index] == 'O'):
moves_orange.append(move)
else:
moves_blue.append(move)
orange_robot = Robot(moves_orange)
blue_robot = Robot(moves_blue)
n_move, time = 0, 0
while n_move < n_moves:
orange_move = orange_robot.do_move(n_move+1)
blue_move = blue_robot.do_move(n_move+1)
if orange_move or blue_move:
n_move += 1
time += 1
print b.case(),
print time
go()
|
fece94f1b1013b09fbd440c8fb40ab64f99d3cc1 | skostic14/PA_vezbe | /vezba08/Zadatak/Zadatak/Zadatak.py | 5,850 | 3.546875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright ? 2019 pavle <pavle.portic@tilda.center>
#
# Distributed under terms of the BSD-3-Clause license.
import base64
import random
def generate_primes(start, n):
'''
Generate a list of prime numbers between ``start`` and ``n``
'''
correction = (n % 6 > 1)
n = {0: n, 1: n - 1, 2: n + 4, 3: n + 3, 4: n + 2, 5: n + 1}[n % 6]
sieve = [True] * (n // 3)
sieve[0] = False
for i in range(int(n**0.5) // 3 + 1):
if sieve[i]:
k = 3 * i + 1 | 1
sieve[((k * k) // 3)::2 * k] = [False] * ((n // 6 - (k * k) // 6 - 1) // k + 1)
sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = [False] * ((n // 6 - (k * k + 4 * k - 2 * k * (i & 1)) // 6 - 1) // k + 1)
primes = [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]]
for i in range(len(primes)):
if primes[i] > start:
return primes[i:]
return []
def calculate_gcd(a, b):
'''
Calculate the greatest common denominator
'''
while b > 0:
q = a // b
a, b = b, a - q * b
return a
def calculate_lcm(a, b):
'''
Calculate the lowest common multiple
'''
if a == 0 or b == 0:
return 0
return abs((a * b) // calculate_gcd(a, b))
def inverse(e, modulus):
'''
Modular multiplicative inverse
'''
r_p = e
r_n = modulus
s_p, s_n = 1, 0
while r_n > 0:
q = r_p // r_n
r_p, r_n = r_n, r_p - q * r_n
s_p, s_n = s_n, s_p - q * s_n
if r_p != 1:
raise ValueError('No inverse value can be computed' + str(r_p))
while s_p < 0:
s_p += modulus
return s_p
def make_key_pair(length):
'''
Create a public/private key pair.
The key pair is generated from two random prime numbers. The argument
``length`` specifies the bit length of the number ``n`` shared between
the two keys.
'''
if length < 4:
raise ValueError('Cannot generate a key of length less than 4 (got {length})'.format(length = length))
# Min and max length of n to fit inside ``length`` bits
n_min = 1 << (length - 1)
n_max = (1 << length) - 1
# Min and max length of ``p`` and ``q`` so that their product fits into ``length`` bits
p_min = 1 << (length // 2 - 1)
p_max = 1 << (length // 2 + 1)
# TODO: generate key pair
primes = []
primes = generate_primes(p_min, p_max)
print(n_min)
print(n_max)
p = 0
q = 0
while p*q < n_min or p*q > n_max or p > q:
p = random.choice(primes)
q = random.choice(primes)
n = p*q
l = calculate_lcm(p-1, q-1)
e = 3
while calculate_gcd(e, l) != 1:
e+=1
d = inverse(e, l)
pubkey = PublicKey(length, n, e)
privkey = PrivateKey(length, n, d)
print("Public key: n =", n, "e =", e)
print("Private key: n =", n, "d =", d)
return (pubkey, privkey)
def encrypt(pubkey, chunk):
# TODO: implement encryption
return chunk**pubkey.e % pubkey.n
#pass
def decrypt(privkey, chunk):
# TODO: implement encryption
return chunk**privkey.d % privkey.n
#pass
class PublicKey():
def __init__(self, length=0, n=0, e=0):
self.length = length
self.n = n
self.e = e
def save(self):
with open('public.key', 'w') as f:
f.write('{length},{n},{e}'.format(length = self.length, n = self.n, e = self.e))
def load(self):
with open('public.key', 'r') as f:
len_str, n_str, e_str = f.read().split(',')
self.length = int(len_str)
self.n = int(n_str)
self.e = int(e_str)
class PrivateKey():
def __init__(self, length=0, n=0, d=0):
self.length = length
self.n = n
self.d = d
def save(self):
with open('private.key', 'w') as f:
f.write('{length},{n},{d}'.format(length = self.length, n = self.n, d = self.d))
def load(self):
with open('private.key', 'r') as f:
len_str, n_str, d_str = f.read().split(',')
self.length = int(len_str)
self.n = int(n_str)
self.d = int(d_str)
def string_to_numbers(in_string, chunk_size):
'''
Convert a string into a list of numbers where each number represents ``chunk_size`` characters
'''
numbers = []
for i in range(0, len(in_string), chunk_size):
s = in_string[i:i + chunk_size]
n = 0
for c in s:
n = (n << 8) + ord(c)
numbers.append(n)
return numbers
def numbers_to_string(numbers, chunk_size):
'''
Convert a list of numbers, where each number represents ``chunk_size`` characters into a string
'''
s = ''
for n in numbers:
temp_s = ''
for _ in range(chunk_size):
temp_s += chr(n & 255)
n = n >> 8
s += temp_s[::-1]
return s
def genkey(length):
public, private = make_key_pair(length)
public.save()
private.save()
def loadkey():
public = PublicKey()
public.load()
private = PrivateKey()
private.load()
return public, private
def encrypt_message(message):
public, private = loadkey()
chunk_size = public.length // 8
numbers = string_to_numbers(message, chunk_size)
encrypted_numbers = [encrypt(public, n) for n in numbers]
encoded_bytes = b''.join([n.to_bytes(chunk_size, 'big') for n in encrypted_numbers])
return base64.b64encode(encoded_bytes).decode('ascii')
def decrypt_message(message):
public, private = loadkey()
chunk_size = public.length // 8
decoded = base64.b64decode(message)
encrypted_numbers = [int.from_bytes(decoded[i:i + chunk_size], 'big') for i in range(0, len(decoded), chunk_size)]
numbers = [decrypt(private, n) for n in encrypted_numbers]
return numbers_to_string(numbers, chunk_size)
def main():
command = input('command> ')
if command == 'genkey':
key_length = input('key length> ')
genkey(int(key_length))
elif command in ('encrypt', 'decrypt'):
input_file = input('in file> ')
output_file = input('out file> ')
with open(input_file, 'r') as f:
message = f.read()
if command == 'encrypt':
message = encrypt_message(message)
elif command == 'decrypt':
message = decrypt_message(message)
with open(output_file, 'w') as f:
f.write(message)
else:
print('Unexpected command "', command, '"', sep='')
if __name__ == '__main__':
main()
|
206b65219604f085e5d7efcd9373ec28d2bb8b96 | Farazulhaque/UnitConverterApp_Python | /UnitConverterApp.py | 2,934 | 3.9375 | 4 | while True:
print()
fromValue = int(input("Enter From Value : "))
fromUnit = input("Enter From Unit(in,ft,yd,mi) : ")
toUnit = input("Enter To Unit(in,ft,yd,mi) : ")
floatfromValue = float(fromValue)
if fromUnit == toUnit:
print(str(floatfromValue) + " " + fromUnit + " => " + str(floatfromValue) + " " + fromUnit)
elif fromUnit == "in" and toUnit == "ft":
toValue = round(fromValue / 12, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "in" and toUnit == "yd":
toValue = round(fromValue / 36, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "in" and toUnit == "mi":
toValue = round(fromValue / 63360, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "ft" and toUnit == "in":
toValue = round(fromValue * 12, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "ft" and toUnit == "yd":
toValue = round(fromValue / 3, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "ft" and toUnit == "mi":
toValue = round(fromValue / 5280, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "yd" and toUnit == "in":
toValue = round(fromValue * 36, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "yd" and toUnit == "ft":
toValue = round(fromValue * 3, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "yd" and toUnit == "mi":
toValue = round(fromValue / 1760, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "mi" and toUnit == "in":
toValue = round(fromValue * 63360, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "mi" and toUnit == "ft":
toValue = round(fromValue * 5280, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
elif fromUnit == "mi" and toUnit == "yd":
toValue = round(fromValue * 1760, 7)
print(str(floatfromValue) + " " + fromUnit + " => " + str(toValue) + " " + toUnit)
else:
if (("in" not in fromUnit) and ("ft" not in fromUnit) and ("yd" not in fromUnit) and ("mi" not in fromUnit)):
print("FromUnit is not valid")
break
else:
print("ToUnit is not valid")
break
|
1a3e87eb054b78ded2372d4e2e022c2492437c90 | NaNdalal-dev/hacker-rank-problems | /easy/count_valley.py | 225 | 3.5625 | 4 | '''
Counting Valleys:
https://www.hackerrank.com/challenges/counting-valleys/problem
'''
def countingValleys(n, s):
v=0
valley=0
for i in s:
if(i=='U'):
v+=1
if(v==0):
valley+=1
else:
v-=1
return valley
|
d31ef6945e559c19a0ce08f292c9ba63d23447d8 | Alin666/LeetCode-Primary | /排序-合并两个有序数组.py | 1,131 | 3.859375 | 4 | # 给你两个有序整数数组nums1 和 nums2,请你将 nums2 合并到nums1中,使 nums1 成为一个有序数组。
# 说明:
#
# 初始化nums1 和 nums2 的元素数量分别为m 和 n 。
# 你可以假设nums1有足够的空间(空间大小大于或等于m + n)来保存 nums2 中的元素。
#
# 示例:
# 输入:
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
#
# 输出:[1,2,2,3,5,6]
class Solution(object):
def merge_sort(self, nums1, nums2):
m = []
i, j = 0, 0
l_1, l_2 = len(nums1)-1, len(nums2)-1
# 当i,j的索引位置小于等于索引最大值的时候
while i <= l_1 and j <= l_2:
if nums1[i] <= nums2[j]:
m.append(nums1[i])
i += 1
else:
m.append(nums2[j])
j += 1
m = m + nums1[i:] + nums2[j:]
return m
if __name__ == '__main__':
n1 = [1, 2, 3, 4, 5]
n2 = [2, 4, 5, 6, 7]
s = Solution()
m = s.merge_sort(n1, n2)
print(m)
# [1, 2, 2, 3, 4, 4, 5, 5, 6, 7]
|
e14baadac9235d0724be6c8e9ead8bd9e6876018 | Aaron136/SPL2 | /grundlagen-python.py | 1,215 | 3.953125 | 4 | # grundlagen-python.py
# Kommentare erfolgen mit hashtag
# Ausgabe von Daten
print("Hello World")
# Variable definieren (kann ohne Typ erfolgen)
heimat = "Erde"
print(heimat, "an World: ", "Hallo")
# Eingabe
wer = input("Und wer bist du? ")
# und gibt den Text wieder aus
print("Hallo", wer)
if(wer == "ich"):
print ("Hallo Du!")
else:
print ("Hallo ", wer)
lieblingszahl = input("Was ist deine Lieblingszahl?")
print("Super, ich mag die Zahl ", lieblingszahl)
print("Aber die groessere Zahl", int (lieblingszahl)+10, "mag ich noch mehr!")
runden = input("Wie viele Runden sollen wir spielen")
runden = int(runden)
for runde in range(1,runden):
print ("Runde", runde, "von", runden, ": Sieger:","ich")
# zufallszahl erzeugen
zufallszahl = random.randint(1,6)
# zufallszahl 1 3 5 ich bin sieger
# sonst computer
if (zufallszahl == 1 or zufallszahl == 3 or zufallszahl == 5):
sieger = "ich"
else:
sieger = "computer"
print ("Runde", runde, "von", runden, ": Sieger:", sieger, ": gewuerfelt wurde:", zufallszahl)
if (siege_ich > siege_computer):
print("Du gewinst!")
elif(siege_ich < siege_computer):
print("Du verlierst!")
else:
print("Unentschieden")
print ("Game Over") |
a4eb60de7aea4fc2c19c7cdfd32333ec5195053c | CaiqueSobral/PyLearning | /Code Day 1 - 10/Code Day 5 Loops/2_Avarage Height.py | 344 | 3.75 | 4 | student_heights = input("Input a list of student heights. ").split()
sum_of_heights = 0
number_of_heights = 0
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
sum_of_heights += student_heights[n]
number_of_heights += 1
print("The avarage height is: " + str(round(sum_of_heights / number_of_heights))) |
20411fb420f8ea6086e1fd75ff76989b1e02b0a2 | Philex5/Python-Learn | /Python-learn/3.Advanced_Features/列表生成式.py | 681 | 3.640625 | 4 | # List Comprehensions
import os
print(list(range(1,11)))
print([x*x for x in range(1, 11)])
print([x*x for x in range(1, 20) if x % 2 == 0])
print([m+n for m in 'ABC' for n in 'XYZ'])
print([d for d in os.listdir('/home/philex/SegNet')])
d = {'x':'A', 'y':'B', 'z':'C'}
for k, v in d.items():
print(k+'='+v)
print([k+'='+v for k,v in d.items()])
L = ['HEllo','World','IBM','APPLE']
print([s.lower() for s in L])
L1 = ['Hello','World',18,'Apple',None]
L2 = []
for l in L1:
if isinstance(l, str):
L2.append(l.lower())
else:
continue
print(L2)
# 使用列表生成式简洁太多了,厉害!
print([l.lower() for l in L1 if isinstance(l, str)])
|
919a267388222ccff998378d9ca7a6915cc5d403 | sudarshansanjeev/Python | /xyz.py | 284 | 3.96875 | 4 | #i=1;
#while i<=10:
# print("Just for Demo: ", i);
# i+=1;
list1 = [11,22,33,44,55];
for item in list1 :
print(item)
print("--------------------");
for i in range(0,100,5):
print(i);
print("---------------------");
for i in range(200,0,-50):
print(i);
|
04e6ad4e73ea9ca3a45d513284b4f855fb30e6d5 | AbdeAMNR/python-training | /Lecture 05 OOP/class vs Instence Variable.py | 1,364 | 4.15625 | 4 | class Person(object):
"""
this is a static var
it can be changed depends on how you access it
p1.gender='Male' ==> static variable accessed via instance, change will affect to instance Object
Person.gender='Male' ==> change will affect all the Instance Objects
"""
gender = 'female'
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
@property
def full_name(self):
pass
@full_name.getter
def full_name(self):
return "{} {}".format(self.first_name, self.last_name)
@full_name.setter
def full_name(self, str):
given_str = str.split()
self.first_name = given_str[0]
self.last_name = given_str[1]
@full_name.deleter
def full_name(self):
self.first_name = None
self.last_name = None
def __str__(self):
return "{}, {}".format(self.full_name, self.gender)
def __eq__(self, other):
return True if self.full_name.__eq__(other.full_name) else False
p1 = Person('abde', 'AMANAR', 22)
p2 = Person('grechen', 'SEA', 20)
print(p1.__eq__(p2))
p1.gender = 'Male'
Person.gender = 'df'
print(p1.gender)
"""
print(p1.full_name)
p1.full_name = 'Yassine AMANAR'
print(p1.full_name)
del p1.full_name
print(p1.__str__())
print(p1.__eq__(p2))
"""
|
7fedafc182fdef23eefd1d9931095ffebd1a6894 | leohck/python_exercises | /EX_EstruturaDeDecisao/ex6.py | 425 | 4 | 4 | __author__ = 'leohck'
print('>.....----- EX 6 ----.....< ')
"""
Faça um Programa que leia três números e mostre o maior deles.
"""
n=[0,0,0]
for i in range(3):
n[i] = int(input('digite um numero: '))
if n[0] == n[1] and n[1] == n[2]:
print('os tres numeros sao iguais')
elif n[0] > n[1]:
if n[0]>n[2]:
print(n[0])
else:
print(n[2])
elif n[1]>n[2]:
print(n[1])
else:
print(n[2])
|
c9dbd64d339cfb6bbb0d456a8d9e51aa4dac9391 | zzh1026/MyPythonTest | /venv/src/python6mianxiangduixiang/__init__.py | 1,184 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
' 注释 '
__author__ = 'zzh'
# 面向对象编程
#
# 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想。OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s同学的成绩为:%s' % (self.name, self.score))
bart = Student('bart', 50)
lisa = Student(name='Lisa Simpson', score=87)
bart.print_score()
lisa.print_score()
# 面向对象的设计思想是从自然界中来的,因为在自然界中,类(Class)和实例(Instance)的概念是很自然的。
# Class是一种抽象概念,比如我们定义的Class——Student,是指学生这个概念,而实例(Instance)则是一个个具体的Student,
# 比如,Bart Simpson和Lisa Simpson是两个具体的Student。
# 所以,面向对象的设计思想是抽象出Class,根据Class创建Instance。
# 面向对象的抽象程度又比函数要高,因为一个Class既包含数据,又包含操作数据的方法。
|
06e4b2731ffd9eaedb56f6ff16c6bd8902e330de | menghsuann/Leetcode-Prep | /permutation.py | 663 | 3.96875 | 4 | #function
def toString(List):
return ''.join(List)
def permute(a, l, r):
if l == r:
print toString(a)
else:
for i in xrange(l, r + 1):
a[l], a[i] = a[i], a[l]
permute(a, l + 1, r)
a[l], a[i] = a[i], a[l] # backtrack
string = "ABC"
n = len(string)
a = list(string)
permute(a, 0, n-1)
#https://www.geeksforgeeks.org/python-program-to-print-all-permutations-of-a-given-string/
#inbuilt function
from itertools import permutations
import string
s = "ABCD"
a = string.ascii_letters
p = permutations(s)
d = []
for i in list(p):
if (i not in d):
d.append(i)
print(''.join(i))
|
9f5fb1f9d27b0448fbe93dbf994cd565ebed4ca6 | alessandraburckhalter/Bootcamp-Exercises | /python101/06-celsius-to-fahrenheit.py | 373 | 4.4375 | 4 | #Task: Prompt the user for a number in degrees Celsius, and convert the value to degrees in Fahrenheit and display it to the user.
print("Enter a number in degrees Celsius and you'll get the value in degrees Fahrenheit.")
print("\nReady? Let's go!")
celsius = float(input("\nTemperature in C? "))
#formula
F = (celsius * 9/5) + 32
print(f"\nThe temperature is {F} F.") |
ccff11cbba17779a1c7874a24449a90fb5eefe2c | liamw309/PyEncrypt | /keycreater.py | 1,099 | 4.28125 | 4 | import random
class keycreater(object):
'''
This class is used to create a key for the encryption
'''
def __init__(self):
'''
This method helps to create the key. It creates a whole new key by appending a new list (key) and removing it from the old list (alphabet). It does this in a random order.
Attributes: alphabet (base list), key (new list), char (random letter/number from alphabet)
'''
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '[', '{', ']', '}', '|', ':', ';', '<', '>']
self.key = []
while len(self.key) < 35:
char = random.choice(alphabet)
alphabet.remove(char)
self.key.append(char)
def createkey(self):
return self.key |
3dfccd60728d7b52daac886c530df3367b1b9a24 | jjlis/kurs_katowice | /dzień 2/kolekcje_Zadanie4.py | 249 | 3.546875 | 4 | liczby = []
for i in range(101):
if i % 3 == 0 or i % 5 == 0:
liczby.append(i)
print("liczby podzielne przez 3 lub 5")
print("\n".join(map(str,liczby)))
print(f"W przedziale 0-100 jest {len(liczby)}liczb podzielnych przez 3 lub 5.")
|
239b64ef0681a93dae9dfe164100e7815e0ffe34 | samh99474/Python-Class | /pythone_classPractice/week3/Week3_Quiz_106360101謝尚泓/quiz3.py | 932 | 3.828125 | 4 | def main():
print("Quiz 3")
lines = int(input("輸入要打的行數(奇數):"))
if lines % 2 == 0:
print('您輸入的不是奇數')
return False
"""Exit
import sys
sys.exit(0)
"""
half_lines = lines // 2 + 1
# 打印上半
for i in range(half_lines):
print(" " * (half_lines - i), end="") #end=""表示不換行
if i == 0:
print("*")
else:
print("*", end="")
print("*" * (2 * i - 1), end="")
#print(" " * (2 * i - 1), end="")
print("*")
# 打印下半
for i in range(half_lines - 1):
print(" " * (i + 2), end="")
if i == half_lines - 2:
print("*")
else:
print("*", end="")
print("*" * (lines - 4 - 2 * i), end="")
#print(" " * (lines - 4 - 2 * i), end="")
print("*")
|
e47d8f47e7f01481694c995e63214c23392197f1 | MatthewMoor/different | /Algorithms/quiksort.py | 703 | 3.78125 | 4 | import random
def quicksort(arr):
if len(arr) < 2:
return arr
else:
piv = arr[0]
smaller = [i for i in arr[1:] if i <= piv]
greater = [i for i in arr[1:] if i > piv]
return quicksort(smaller) + [piv] + quicksort(greater)
array = [321, 45, 1, 52, -2, 4]
print(quicksort(array))
#______________________________________________________________________________________
def quicksort_two(nums):
if len(nums) <= 1:
return nums
else:
q = random.choice(nums)
l_nums = [n for n in nums if n < q]
e_nums = [q] * nums.count(q)
b_nums = [n for n in nums if n > q]
return quicksort_two(l_nums) + e_nums + quicksort_two(b_nums)
print(quicksort_two(array)) |
47a017754bd8deadfca583e7d75c8ed575bea1cd | andreiG97/100daysOfCodeDay1 | /day2/ex1.py | 194 | 4.03125 | 4 | # adding digits
two_digit_number = input("Type a two digit number: ")
def adding_digits(num):
a = int(num[0])
b = int(num[1])
return a + b
print(adding_digits(two_digit_number))
|
2ab394b82db6c559ca440e9bb744e755bff59bef | reingart/python | /exercises/book-store/example.py | 706 | 3.515625 | 4 | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return BOOK_PRICE * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_far
groups = list(set(books))
min_price = float('inf')
for i in range(len(groups)):
remaining_books = books[:]
for v in groups[:i + 1]:
remaining_books.remove(v)
price = calculate_total(remaining_books,
price_so_far + _group_price(i + 1))
min_price = min(min_price, price)
return min_price
|
abc44dd9ade84bde56a6bed9c0314954f15029ef | juishah14/Accessing-Web-Data | /using_GeoJSON_api.py | 2,988 | 4.03125 | 4 | # Assignment from University of Michigan's Coursera Course Using Python to Access Web Data
# For this assignment, we will use the GeoLocation Lookup API, which is modelled after the Google API, to look up universities and parse the
# returned data.
# The program will prompt for a location, contact a web service, and retrieve JSON for the web service , parse that data, and retrieve
# the first place_id from the JSON file. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
# Test with location South Federal University to get ChIJy0Uc1Zmym4gR3fmAYmWNuac as place id
import urllib.request, urllib.parse, urllib.error
import json
import ssl
api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy.....IDByT70'
if api_key is False:
# Using API endpoint that has a static subset of Google Data. This API uses the same parameter (address) as the Google API.
# Note- this API has no rate limit, so can test as often as you like.
# If you visit the URL with no parameters, you will get a "No address..." response.
# To call the API, must include a key= parameter and provide the address that you are requesting as the address= parameter
# to urllib.parse.urlencode(), so that it can properly encode the URL.
api_key = 42
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
address = input('Enter location: ')
if len(address) < 1: break
parms = dict()
parms['address'] = address
if api_key is not False: parms['key'] = api_key
# creating a url
# the urlib.parse part encodes the address properly so that it can be concatenated to the end of the service url
# it will encode it to look something like address=Ann+Arbor%2C+MI if you give the address Ann Arbor, MI
url = serviceurl + urllib.parse.urlencode(parms)
print('Retrieving', url)
# opening url and getting a handle back; reading data from handle and
# decoding that data from UTF-8 to Unicode and saving it in a string data
url_handle = urllib.request.urlopen(url, context=ctx)
# all data stored as one string in variable data
data = url_handle.read().decode()
print('Retrieved', len(data), 'characters')
try:
# parsing that string (data that we got back from Google API) to now store all data in that as a dict (js is a dict)
js = json.loads(data)
except:
js = None
if not js or 'status' not in js or js['status'] != 'OK':
print('Failure to Receive Location')
continue
# Optional: to see all raw data at once
# print(json.dumps(js, indent=4))
place_id = js['results'][0]['place_id']
print(place_id)
|
b91a0546c6f8a830651ceba0698663c63a4f445a | zjuzpz/Algorithms | /StrobogrammaticNumberII.py | 1,644 | 4.15625 | 4 | """
247. Strobogrammatic Number II
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Find all strobogrammatic numbers that are of length = n.
For example,
Given n = 2, return ["11","69","88","96"].
"""
# O(n^2 * 5^(n/2))
# O(n)
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n <= 0:
return []
res = []
if n % 2 == 1:
self.find(res, [], n // 2, True)
else:
self.find(res, [], n // 2, False)
return res
def find(self, res, cur, length, mid):
if len(cur) == length:
right = self.getRight(cur)
if mid:
res.append("".join(cur + ["0"] + right))
res.append("".join(cur + ["1"] + right))
res.append("".join(cur + ["8"] + right))
else:
res.append("".join(cur + right))
return
if len(cur) != 0:
cur.append("0")
self.find(res, cur, length, mid)
cur.pop()
for i in ["1", "6", "8", "9"]:
cur.append(i)
self.find(res, cur, length, mid)
cur.pop()
def getRight(self, l):
res = []
for i in l:
if i in ["0", "1", "8"]:
res.append(i)
elif i == "6":
res.append("9")
else:
res.append("6")
res.reverse()
return res
if __name__ == "__main__":
print(Solution().findStrobogrammatic(7))
|
cda3d58fb901496b889fe79594a6bee56358b675 | BeastTechnique/MailMaster | /pycamera.py | 428 | 3.515625 | 4 | import picamera
from time import sleep
def take_pic():
print("About to take a picture")
with picamera.PiCamera() as camera:
i = 0
sleep(.2)
while i < 10:
sleep(.1)
camera.resolution = (1280, 720)
camera.capture("/home/pi/Documents/cse408/images/{x}.jpg".format(x=i))
i += 1
print("Picture " + '#'+ str(i))
print("Picture Taken")
|
7f086657352cc3be9cc2be2f4e9370bfaa6167b3 | imagine5am/project-euler | /p007.py | 264 | 3.921875 | 4 | import math
def isPrime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
count = 6
number = 13
while count != 10001:
number += 1
if isPrime(number):
count += 1
print(str(number))
|
ddbbdde4555e2167c78ac8d6ca924ca92b9b6111 | Ausiden/class | /line_model.py | 1,167 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def pointplot(x,y): #画点
plt.plot(x,y,'rx',ms=5)
plt.xticks(np.arange(4,9,1))
plt.yticks(np.arange(-5,15,5))
def sumcost(x,theta,y,m): #计算损失函数
c=np.dot(x,theta)-y
ct=c.T
return np.dot(ct,c)/(2*m)
def fitpoint(x,y,m,diedai): #迭代返回最优的theta
theta=np.zeros((2,1))
a=0.001
xt=x.T
cost=np.zeros((diedai,1))
for i in range(diedai):
cost[i]=sumcost(x,theta,y,m)
theta=theta-a*(np.dot(xt,np.dot(x,theta)-y)/m)
print(theta)
return theta,cost
def descend(cost,diedai): #画迭代次数与代价函数的值的图像
costx = np.arange(0,diedai, 1)
costy = cost[costx]
plt.plot(costx,costy)
plt.xticks(np.arange(0,diedai,30))
plt.yticks(np.arange(5,30,5))
plt.show()
text=np.loadtxt("ex1data1") #读取文件中的数据
xx=text[:,0]
yy=text[:,1]
pointplot(xx,yy)
m=len(xx)
diedai=150 #迭代次数
yy=yy.reshape((m,1))
x0=np.ones((m,1))
X=np.c_[x0,xx]
theta,cost=fitpoint(X,yy,m,diedai)
print(cost)
x=np.arange(4,9,1)
y=theta[0]+theta[1]*x
plt.plot(x,y)
plt.show()
descend(cost,diedai)
|
e4dc8b5fd2938a697029f0ca38cbf393493b908f | A432-git/Leetcode_in_python3 | /946_验证栈序列.py | 475 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 09:48:56 2020
@author: leiya
"""
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
start = 0
for num in pushed:
stack.append(num)
while stack and stack[-1] == popped[start]:
stack.pop()
start += 1
if not stack:
return True
else:
return False |
530927d35f65aa1bc8035ef577d9d4a514682ac0 | picktsh/python | /code/day08/99乘法表.py | 652 | 3.5 | 4 | n = 9
for i in range(1, n + 1):
str = ''
for j in range(1, i + 1):
str += '{0}×{1}={2}; '.format(j, i, i * j)
print(str)
# for 最简化版本
for i in range(1, 10):
for j in range(1, i + 1):
print('{0}×{1}={2}'.format(j, i, i * j), end=' ')
print('')
# for 条件退出版本
for i in range(1, 10):
for j in range(1, 10):
print('%d X %d = %d' % (j, i, i * j), end=' ')
if i == j:
print('')
break
# while 条件退出版本
i = 1
while i <= 9:
j = 1
while j <= i:
print('%d X %d = %d' % (j, i, i * j), end=' ')
j += 1
print('')
i += 1
|
7702aa8e8522fcb1047436023b34848137919b71 | titanspeed/PDX-Code-Guild-Labs | /Python/b_jack.py | 3,718 | 3.5 | 4 | import random
class Card:
def __init__(self, suit, rank, value):
self.rank = rank
self.suit = suit
self.value = value
self.card = {}
self.hidden = None
def __str__(self):
if self.hidden is True:
return '?'
else:
return '{} of {}'.format(self.rank, self.suit)
def __repr__(self):
return '{} of {}'.format(self.rank, self.suit)
def hide_card(self):
self.hidden = True
def reveal_card(self):
self.hidden = False
class Deck:
def __init__(self, numdecks=5):
self.contents = self.create_deck(numdecks)
def create_deck(self, numdecks):
master_list = {
'hearts': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10,
'Q': 10,
'K': 10,
'A': 1},
'spades': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10,
'Q': 10,
'K': 10,
'A': 1},
'diamonds': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10,
'Q': 10,
'K': 10,
'A': 1},
'clubs': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10,
'Q': 10, 'K': 10,
'A': 1}}
gamedeck = []
for times in range(numdecks):
for k, v, in master_list.items():
for x, y in v.items():
gamedeck.append(Card(k, x, y))
return gamedeck
class Hand:
def __init__(self, name):
self.contents = []
self.name = name
self.value = self.hand_value()
def __str__(self):
return '{} - {}'.format(self.contents, self.value)
def __repr__(self):
return '{} of {}'.format(self.contents, self.value)
def take_card(self, card):
self.contents.append(card)
self.hand_value()
self.score_hand()
def hand_value(self):
self.value = 0
for i in self.contents:
self.value += i.value
def score_hand(self):
self.score = 0
aces = False
for i in self.contents:
if i.value == 1:
aces = True
self.score += 1
else:
self.score += i.value
if aces:
if self.score + 10 <= 21:
self.score += 10
class DealerHand(Hand):
def __init__(self):
Hand.__init__(self)
def d_hit(self, deck):
while self.value <= 16:
self.contents.append(deck.pop())
self.hand_value()
continue
class BlackJackGame():
def __init__(self, player1='player1', player2='player2'):
self.dealer = DealerHand()
self.deck = Deck()
self.player1 = Hand()
self.player2 = Hand()
self.players = [self.player1, self.player2, self.dealer]
def shuffle(self):
random.shuffle(self.deck.contents)
def run_game(self):
busted = False
self.shuffle()
for times in range(2):
self.player1.take_card(self.deck.contents.pop())
self.player2.take_card(self.deck.contents.pop())
self.dealer.take_card(self.deck.contents.pop())
for peeps in self.players:
print(peeps)
for peeps in self.players:
if peeps.value == 20:
print('Blackjack!')
new_game = BlackJackGame(input('Name of player 1: '), input('Name of player 2: '))
new_game.run_game()
|
a60d761eb0d9bda51048597719c81148d48e38ba | lilianeascosta/CodigosPython | /TheHuxley/Atividade07(matriz)/fabrica_de_motores.py | 966 | 3.625 | 4 | motores = []
aux = 0
vetor_aux = [0] * 2
custo = []
motor_resultado = []
#pega os dados da maquina
for mes in range(12):
aux = input().split()
for i in range(2):
vetor_aux[i] = int(aux[i])
motores.append(vetor_aux[:])
#pega os valores do custo e lucro
for i in range(2):
aux = input().split()
for j in range(2):
vetor_aux[i] = float(aux[i])
custo.append(vetor_aux[:])
print('custo = ', custo)
#multiplicacao
for a in range(12): #laço para motor_resultado
for l in range(12): #laço para motores e custo
aux = 0
for c in range(2):
motor_resultado[a] += motores[l][c] * custo[c][aux]
aux = aux + 1
#saida
for a in range(12): #laço para motor_resultado
for l in range(12): #laço para motores e custo
for c in range(2):
print('Motor[{}], Mes[{}], custo=[{}], lucro=[{}]'.format(a, l, custo[0][c], custo[1][c]))
print()
#print('motores = ', motores) |
0d0fa5df6ce86574aa746ecc6fc5ed7fb64a7cfd | facingwaller/deeplearning | /rnn_lstm/lstm2.py | 6,814 | 4.0625 | 4 | """ Recurrent Neural Network.
A Recurrent Neural Network (LSTM) implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Links:
[Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)
[MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
"""
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
import rnn_lstm.data_helpers as data_helpers
import numpy as np
import os
import time
import datetime
from tensorflow.contrib import learn
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
tf.flags.DEFINE_string("positive_data_file", "../data/rt-polarity.pos-1", "Data source for the positive data.")
tf.flags.DEFINE_string("negative_data_file", "../data/rt-polarity.neg-1", "Data source for the negative data.")
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
mnist = input_data.read_data_sets("../MNIST_data/", one_hot=True)
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
'''
To classify images using a recurrent neural network, we consider every image
row as a sequence of pixels. Because MNIST image shape is 28*28px, we will then
handle 28 sequences of 28 steps for every sample.
因为图片大小是28,所以此系列一次是28
'''
# Training Parameters
# 学习率
learning_rate = 0.001
# 步数
training_steps = 201 #10000
# 一个批次的数量
batch_size = 128
display_step = 200
# Network Parameters
num_input = 28 # MNIST data input (img shape: 28*28) 1次28张图片
timesteps = 28 # timesteps
num_hidden = 128 # hidden layer num of features
num_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph input
X = tf.placeholder("float", [None, timesteps, num_input])
Y = tf.placeholder("float", [None, num_classes])
# Define weights
weights = {
'out': tf.Variable(tf.random_normal([num_hidden, num_classes]))
}
biases = {
'out': tf.Variable(tf.random_normal([num_classes]))
}
def RNN(x, weights, biases):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, timesteps, n_input)
# Required shape: 'timesteps' tensors list of shape (batch_size, n_input)
# Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)
print("x1:",x)
# X = tf.placeholder("float", [None, timesteps, num_input])
# x1: Tensor("Placeholder:0", shape=(?, 28, 28), dtype=float32)
# 将x按行拆成num行,
x = tf.unstack(x, num=timesteps, axis=1)
# tf.unstack(value=1,num=2,axis=1)
# [<tf.Tensor 'unstack:0' shape=(?, 28) dtype=float32>, <tf.Tensor 'unstack:1' shape=(?, 28) dtype=float32>,...
print("x2",x)
# Define a lstm cell with tensorflow
# http://blog.csdn.net/qiqiaiairen/article/details/53239506
# 基本的LSTM循环网络单元
# num_units: int, 在LSTM cell中unit 的数目
# forget_bias: float, 添加到遗忘门中的偏置
# input_size: int, 输入到LSTM cell 中输入的维度。默认等于 num_units
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
# Get lstm cell output
# (outputs, state)
outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
# Linear activation, using rnn inner loop last output
print("active1:", outputs)
print("active2:",outputs[-1])
return tf.matmul(outputs[-1], weights['out']) + biases['out']
# logits 未归一化的概率,是一个十维的向量, 一般也就是 softmax层的输入
logits = RNN(X, weights, biases)
print("logits:",logits)
prediction = tf.nn.softmax(logits) #
# Define loss and optimizer
# http://blog.csdn.net/hejunqing14/article/details/52397824
# 第一个坑:logits表示从最后一个隐藏层线性变换输出的结果!假设类别数目为10,那么对于每个样本这个logits应该是个10维的向量,
# 且没有经过归一化,所有这个向量的元素和不为1。然后这个函数会先将logits进行softmax归一化,
# 然后与label表示的onehot向量比较,计算交叉熵。 也就是说,这个函数执行了三步(这里意思一下):#
# sm=nn.softmax(logits)
# onehot=tf.sparse_to_dense(label,…)
# nn.sparse_cross_entropy(sm,onehot)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
for step in range(1, training_steps+1):
# 待考虑
# batch_x = data_helpers.batch_iter(
# list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)
# batch_y = data_helpers.batch_iter(
# list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs)
# batch_x, batch_y = mnist.train.next_batch(batch_size)
batch_x, batch_y = mnist.train.next_batch(batch_size)
if step == 1 :
print("batch_x 1 :", batch_x)
print("batch_y:", batch_y)
print("batch_x 1 :", len(batch_x))
print("batch_y:", len(batch_y))
# Reshape data to get 28 seq of 28 elements
batch_x = batch_x.reshape((batch_size, timesteps, num_input))
if step == 1 :
print("batch_x 2 :", len(batch_x))
# Run optimization op (backprop)
sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
if step % display_step == 0 or step == 1:
# Calculate batch loss and accuracy
loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
print("Optimization Finished!")
# Calculate accuracy for 128 mnist test images
test_len = 128
test_data = mnist.test.images[:test_len].reshape((-1, timesteps, num_input))
test_label = mnist.test.labels[:test_len]
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={X: test_data, Y: test_label}))
|
2116098d9f09c344aee2638682b66d18d42c5aa0 | 256018/256018-MiniProject | /src/MenuAfterLogin.py | 963 | 3.765625 | 4 | import os
import withdraw
import deposit
import PasswordChange
def clear_screen():
# Clear Screen
os.system('cls')
print() # print blank line after clearing the screen
def menu2(account):
# account is a list of account info
# account[0] id
# account[1] name
# account[2] password
# account[3] balance
print("\n---------Hello, {0}--------- ".format(account[1]))
ch = int(input("\n1) show info \n2) deposit\n3) withdraw\n"
"4) change password \n5) logout\n\nchoice>> "))
clear_screen()
if ch == 1:
print("ID: {}\nName: {}\nBalance: {}\n".format(account[0], account[1], account[3]))
elif ch == 2:
deposit.deposit(account)
elif ch == 3:
withdraw.withdraw(account)
elif ch == 4:
PasswordChange.change_password(account)
elif ch == 5:
return
else:
print("ERROR: Wrong choice. Please Enter a valid choice\n")
menu2(account)
|
9ddc238007c87f19a2b02d7cf8cd594cb75d01c0 | Nikhil14091997/Code-File | /Cracking the Coding Interview/Linked List/returnKthToLast.py | 1,270 | 3.921875 | 4 | # removing the duplicates from the linked list - unsorted
'''
kth to last element in a linkedlist
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while(temp != None):
print(temp.data, end=" ")
temp = temp.next
print()
def removeKth(self, k):
# we will use a runner node
node = self.head
runner = self.head
if k == 0:
return None
for i in range(k):
if runner is None:
return None # out of bounds
else:
runner = runner.next
while runner is not None:
node = node.next
runner = runner.next
return node.data
list = LinkedList()
list.head = Node(10)
list.head.next = Node(12)
list.head.next.next = Node(11)
list.head.next.next.next = Node(11)
list.head.next.next.next.next = Node(12)
list.head.next.next.next.next.next = Node(11)
list.head.next.next.next.next.next.next = Node(10)
list.printList()
print(list.removeKth(0))
|
ae6cf668cce3faf20a13ff58a233ce4690b3cf54 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/kvrsha004/question3.py | 651 | 4.03125 | 4 | #Q1 of Assignment 3
#KVRSHA004
#Framed message
message = input("Enter the message: \n")
count = eval(input("Enter the message repeat count: \n"))
frame = eval(input("Enter the frame thickness: \n"))
endline = 0
hyphens = 2*frame
for i in range(frame):
print("|"*endline, "+", "-"*(len(message)+hyphens),
"+", "|"*endline, sep="")
endline+=1
hyphens-=2
for i in range(count):
print("|"*frame, message, "|"*frame)
endline-=1
hyphens+=2
for i in range(frame):
print("|"*endline, "+", "-"*(len(message)+hyphens),
"+", "|"*endline, sep="")
endline-=1
hyphens+=2 |
bcd1204ff0bab42df4fb9f172c08f060626d6272 | PJHalvors/Learning_Python | /ZedEx17.py | 958 | 3.8125 | 4 | #!/bin/env/python
"""This is Zed's Learn Python the Hard Way: Exercise 17."""
#Import the class(or function, I dunno which yet) argv from module named sys
from sys import argv
#Import the function exists from class path within module os
from os.path import exists
print argv
#Set variables for argv function
script, from_file, to_file = argv
#Write a string indicating that you'll be copying something from file to new file
print "Copying from %s to %s" % (from_file, to_file)
#How can this be done in one line?
#Set variables for your input file and the input data from your file
in_file = open(from_file)
indata = in_file.read()
#Use indata variable to print file size in a string
print "The input file is %d bytes long" % len(indata)
print "Ready, hit RETURN to continue, CTRL-C to abort."
#Create a new file to write this info to
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done!"
out_file.close()
in_file.close()
|
7ce71bad195ae0d1e6d980859b258e23ea6bc56f | lucadiliello/sweep-line-algorithm-python | /examples.py | 1,210 | 3.5625 | 4 | import networkx as nx
from matplotlib import *
from pylab import *
import random
import itertools
from SweepLineAlgorithm.geometry import Graph
def generate_circuit(n_nodes, n_edges, ranges=(0,50)):
if n_edges > n_nodes * (n_nodes-1)/2:
# this graph cannot exists
return None
nodes = [(random.uniform(*ranges), random.uniform(*ranges)) for i in range(n_nodes)]
all_edges = list(itertools.combinations(range(n_nodes), 2))
edges = []
for i in range(n_edges):
j = random.randint(0,len(all_edges)-1)
edges.append(all_edges[j])
del all_edges[j]
return Graph(nodes, edges)
if __name__ == "__main__":
# generating a random graph
G = generate_circuit(5,8)
# print number of crossing edges and the total length of the edges
print "Intersections:", G.intersection_number(), "Total edges length:", G.edges_total_length()
# draw the graph
G.plot()
# moving the first node to x = 100
G.nodes[0].x = 100
# print again the number of crossing edges and the total length of the edges
print "Intersections:", G.intersection_number(), "Total edges length:", G.edges_total_length()
# draw the graph
G.plot()
|
d8fb46159dbb77441ca7ef91aac239f69ab1095f | Eqliphex/python-crash-course | /chapter06 - Dictionaries/exercise6.7_people.py | 687 | 4.125 | 4 | # Initiate 3 persons which are 3 dictionaries:
person1 = {
'first_name': 'patrick',
'last_name': 'meyer',
'age': 26,
'city': 'aarhus'
}
person2 = {
'first_name': 'morten',
'last_name': 'struckmann',
'age': 25,
'city': 'esbjerg'
}
person3 = {
'first_name': 'david',
'last_name': 'lam',
'age': 23,
'city': 'køge'
}
# Put the 3 people into a list:
people = [person1, person2, person3]
# Printing all their information:
for person_info in people:
for key, value in person_info.items():
print("person:" + str(key).title() + ": " + str(value).title())
print()
print() # For making a format linebreak
|
a337546bf2f37d7dd30939f986f202c28797e1c5 | Infinidat/infi.clickhouse_orm | /scripts/generate_ref.py | 5,151 | 4.28125 | 4 |
import inspect
from collections import namedtuple
DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')
def _get_default_arg(args, defaults, arg_index):
""" Method that determines if an argument has default value or not,
and if yes what is the default value for the argument
:param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
:param defaults: array of default values, eg: (42, 'something')
:param arg_index: index of the argument in the argument array for which,
this function checks if a default value exists or not. And if default value
exists it would return the default value. Example argument: 1
:return: Tuple of whether there is a default or not, and if yes the default
value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)
"""
if not defaults:
return DefaultArgSpec(False, None)
args_with_no_defaults = len(args) - len(defaults)
if arg_index < args_with_no_defaults:
return DefaultArgSpec(False, None)
else:
value = defaults[arg_index - args_with_no_defaults]
if (type(value) is str):
value = '"%s"' % value
return DefaultArgSpec(True, value)
def get_method_sig(method):
""" Given a function, it returns a string that pretty much looks how the
function signature would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature.
eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
"""
# The return value of ArgSpec is a bit weird, as the list of arguments and
# list of defaults are returned in separate array.
# eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
# varargs=None, keywords=None, defaults=(42, 'something'))
argspec = inspect.getargspec(method)
arg_index=0
args = []
# Use the args and defaults array returned by argspec and find out
# which arguments has default
for arg in argspec.args:
default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)
if default_arg.has_default:
val = default_arg.default_value
args.append("%s=%s" % (arg, val))
else:
args.append(arg)
arg_index += 1
if argspec.varargs:
args.append('*' + argspec.varargs)
if argspec.keywords:
args.append('**' + argspec.keywords)
return "%s(%s)" % (method.__name__, ", ".join(args[1:]))
def docstring(obj):
doc = (obj.__doc__ or '').rstrip()
if doc:
lines = doc.split('\n')
# Find the length of the whitespace prefix common to all non-empty lines
indentation = min(len(line) - len(line.lstrip()) for line in lines if line.strip())
# Output the lines without the indentation
for line in lines:
print(line[indentation:])
print()
def class_doc(cls, list_methods=True):
bases = ', '.join([b.__name__ for b in cls.__bases__])
print('###', cls.__name__)
print()
if bases != 'object':
print('Extends', bases)
print()
docstring(cls)
for name, method in inspect.getmembers(cls, lambda m: inspect.ismethod(m) or inspect.isfunction(m)):
if name == '__init__':
# Initializer
print('####', get_method_sig(method).replace(name, cls.__name__))
elif name[0] == '_':
# Private method
continue
elif hasattr(method, '__self__') and method.__self__ == cls:
# Class method
if not list_methods:
continue
print('#### %s.%s' % (cls.__name__, get_method_sig(method)))
else:
# Regular method
if not list_methods:
continue
print('####', get_method_sig(method))
print()
docstring(method)
print()
def module_doc(classes, list_methods=True):
mdl = classes[0].__module__
print(mdl)
print('-' * len(mdl))
print()
for cls in classes:
class_doc(cls, list_methods)
def all_subclasses(cls):
return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in all_subclasses(s)]
if __name__ == '__main__':
from infi.clickhouse_orm import database
from infi.clickhouse_orm import fields
from infi.clickhouse_orm import engines
from infi.clickhouse_orm import models
from infi.clickhouse_orm import query
from infi.clickhouse_orm import funcs
from infi.clickhouse_orm import system_models
print('Class Reference')
print('===============')
print()
module_doc([database.Database, database.DatabaseException])
module_doc([models.Model, models.BufferModel, models.MergeModel, models.DistributedModel, models.Constraint, models.Index])
module_doc(sorted([fields.Field] + all_subclasses(fields.Field), key=lambda x: x.__name__), False)
module_doc([engines.Engine] + all_subclasses(engines.Engine), False)
module_doc([query.QuerySet, query.AggregateQuerySet, query.Q])
module_doc([funcs.F])
module_doc([system_models.SystemPart])
|
cebfd2fd7cbcd53792e1326a532ae1377ce10196 | s-tefan/python-exercises | /quaternions.py | 1,967 | 3.671875 | 4 | class Quaternion:
def __init__(self, re=0, im=(0, 0, 0)):
self.real = re
self.imag = im
def conj(self):
return Quaternion(self.real, tuple(-k for k in self.imag))
def __add__(self, a):
if isinstance(a, Quaternion):
return Quaternion(
self.real + a.real, tuple(self.imag[k] + a.imag[k] for k in range(3))
)
else:
return Quaternion(self.real + a.real, self.imag)
def __neg__(self):
return Quaternion(-self.real, tuple(-k for k in self.imag))
def __sub__(self, a):
return self + (-a)
def __mul__(self, a):
if isinstance(a, Quaternion):
u = self.imag
v = a.imag
re = self.real * a.real - sum(u[k] * v[k] for k in range(3))
imlist = [0, 0, 0]
for k in range(3):
imlist[k] = (
self.real * v[k]
+ a.real * u[k]
+ u[(k + 1) % 3] * v[(k - 1) % 3]
- v[(k + 1) % 3] * u[(k - 1) % 3]
)
return Quaternion(re, tuple(imlist))
else:
return Quaternion(self.real * a, self.imag)
def __str__(self):
return "({} + {}i + {}j + {}k)".format(
self.real, self.imag[0], self.imag[1], self.imag[2]
)
def __repr__(self):
return (self.real, self.imag)
if __name__ == "__main__":
import math
def test():
i = Quaternion(0, (1, 0, 0))
j = Quaternion(0, (0, 1, 0))
print(
"i = {}, j = {}, i*i = {}, i*j = {}, j*i = {}".format(
i, j, i * i, i * j, j * i
)
)
v = (1 / 3 ** (1 / 2),) * 3
th = math.pi / 6
vs = tuple(k * math.sin(th) for k in v)
s = Quaternion(math.cos(th), vs)
print(s)
b = i
for k in range(13):
print(b)
b = s * b * s.conj()
|
ea08392eaae3e17cf77736e78f80819005901b5c | Ekaterina-sol/Python_Basics | /hw1/hw1_1.py | 662 | 3.875 | 4 | first_variable = 25;
second_variable = 45;
sum = first_variable + second_variable
print("Первое число: ",first_variable)
print("Второе число: ",second_variable)
print("Сумма чисел: ", sum)
user_name = input("Введите ваше имя: ")
user_city = input("Введите ваше место рождения: ")
user_age = input("Ведите ваш возраст: ")
user_salary = int(input("Ведите вашу зарплату в месяц, руб.: "))
print(f'Добрый день, {user_name}! Вы из {user_city}, Вам {user_age}.')
print(f'Ваша годовая зарплата {12*user_salary} руб.') |
1e68f91b72c2c99c735e7cfc2cd6a32e9c6bc725 | sergeyuspenskyi/hillel_homeworks | /HW-13.py | 300 | 3.921875 | 4 | set_1 = set()
for number in range(5):
set_1.add(input('Put int or float number: '))
set_1 = list(set_1)
min_num = set_1[0]
max_num = set_1[0]
for i in set_1:
if min_num > i:
min_num = i
if max_num < i:
max_num = i
print('Min num = ', min_num)
print('Max num = ', max_num)
|
8e0b0d332777037b0e55c85871c80a2b5c166727 | aroraravi87/Python_ZerotoMastery | /pythonmodules/utilityhelper/utility.py | 161 | 3.578125 | 4 | print(__name__)
def addition(num1,num2):
return num1 + num2
def multiply(num1,num2):
return num1 * num2
def divide(num1,num2):
return num1/num2 |
9867203ce48e26234c889dc62ce4eade653bc0f0 | hopo/cio | /01_Elementary/fizz-buzz/py-01/main.py | 534 | 3.890625 | 4 |
def checkio(number):
if number % 15 == 0:
return "Fizz Buzz"
elif number % 3 == 0:
return "Fizz"
elif number % 5 == 0:
return "Buzz"
return str(number) # int -> str casting
if __name__ == '__main__':
ex1 = checkio(15) # "Fizz Buzz", "15 is divisible by 3 and 5"
print(ex1)
ex2 = checkio(6) # "Fizz", "6 is divisible by 3"
print(ex2)
ex3 = checkio(5) # "Buzz", "5 is divisible by 5"
print(ex3)
ex4 = checkio(7) # "7", "7 is not divisible by 3 or 5"
print(ex4)
|
8a68f668d68eb9d479e6756a45ae4f4797c4db46 | hiromzn/study-python | /sample/array_basic.py | 1,343 | 4 | 4 | #! /usr/bin/env python
##
## list (1D)
##
l = ['apple', 100, 0.123]
print( l )
##
## list (2D)
##
l_2d = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
print( l_2d )
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
##
## index
##
print(l[1])
# 100
print(l_2d[1])
# [3, 4, 5]
print(l_2d[1][1])
# 4
print(l[:2])
# ['apple', 100]
print( "l_num = [0, 10, 20, 30, 40, 50]" )
l_num = [0, 10, 20, 30, 40, 50]
print( "print(min(l_num))" ); print(min(l_num))
# 0
print( "print(max(l_num))" ); print(max(l_num))
# 30
print( "print(sum(l_num))" ); print(sum(l_num))
# 60
print( "print(len(l_num))" ); print(len(l_num))
print( "print(sum(l_num) / len(l_num))" ); print(sum(l_num) / len(l_num))
# 15.0
print( "l_num[0]" ); print(l_num[0])
print( "l_num[1]" ); print(l_num[1])
print( "l_num[5]" ); print(l_num[5])
# ERROR : print( "l_num[6]" ); print(l_num[6])
print( "l_num[1:1]" ); print(l_num[1:1])
print( "l_num[1:2]" ); print(l_num[1:2])
print( "l_num[1:3]" ); print(l_num[1:3])
print( "l_num[0:3]" ); print(l_num[0:3])
print( "l_num[0:4]" ); print(l_num[0:4])
print( "l_num[0:5]" ); print(l_num[0:5])
##
## for loop
##
l_str = ['apple', 'orange', 'banana']
for s in l_str:
print(s)
##
## Multidimensional array
##
##
import numpy as np
arr = np.array([0, 1, 2])
print(arr)
# [0 1 2]
arr_2d = np.array([[0, 1, 2], [3, 4, 5]])
print(arr_2d)
# [[0 1 2]
# [3 4 5]]
|
cfec126f664a66cf63efe47971bb11ba7eadb19b | luizdefranca/Curso-Python-IgnoranciaZero | /Aulas Python/Conteúdo das Aulas/018/Gabarito/Exercício 2 - Gabarito 2.py | 435 | 4.28125 | 4 | m = int(input("Digite m: "))
n = 1
for n in range(m+1):
soma, cont, x, aux = 0, 1, 1, n
for cont in range(n):
soma = soma + 2*cont
while x <= aux**3:
if aux**3 == x*aux + soma:
print ("O número", aux, "elevado ao cubo tem como soma: ")
while aux - 1 >= 0:
r = x + 2*(aux - 1)
print (r)
aux -= 1
x = aux**3
x += 1
|
f9f926c60bc905662c1d7d2a7abed9cf3cc35daa | NotARectangle/Honours2021 | /Datatest/extractingLines.py | 1,757 | 3.515625 | 4 | import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#To make plots for who has the most lines in the series. Coded by following
# https://www.kaggle.com/zoiaran/who-has-the-most-words-and-lines-in-ds9
data = json.load(open('../Dataset/all_series_lines.json', 'r'))
tng_episodes = data['TNG'].keys()
total_word_counts={}
total_line_counts={}
#for i, ep in enumerate(episodes)
series = "TNG"
print(data['TNG']['episode 0'].keys())
for ep in tng_episodes:
#for all characters in list
script = data[series][ep]
characters = data[series][ep].keys()
for member in characters:
character_lines = script[member]
total_words_by_member_in_ep = 0
total_lines_by_member_in_ep = 0
#total_words_by_member = sum()
for l in character_lines:
total_words_by_member_in_ep += len(l.split())
total_lines_by_member_in_ep += 1
if member in total_word_counts.keys():
total_word_counts[member]=total_word_counts[member]+total_words_by_member_in_ep
total_line_counts[member]=total_line_counts[member]+total_lines_by_member_in_ep
else:
total_word_counts[member]=total_words_by_member_in_ep
total_line_counts[member]=total_lines_by_member_in_ep
words_df=pd.DataFrame(list(total_word_counts.items()), columns=['Character','No. of Words'])
most_words=words_df.sort_values(by='No. of Words', ascending=False).head(12)
lines_df=pd.DataFrame(list(total_line_counts.items()), columns=['Character','No. of Lines'])
most_lines=lines_df.sort_values(by='No. of Lines', ascending=False).head(12)
most_words.plot.bar(x='Character',y='No. of Words')
most_lines.plot.bar(x='Character',y='No. of Lines')
plt.show()
|
7a1c57fe3b2148ce9f263bf6299c45482949a4e6 | SmasterZheng/leetcode | /力扣刷题/1281整数的各位积和之差.py | 891 | 3.890625 | 4 | """
给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
示例 1:
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21
提示:
1 <= n <= 10^5
"""
class Solution:
def subtractProductAndSum(self, n):
'''
思路:转成字符串再成列表,单独计算列表元素之积和和的差值
:param n:
:return:
'''
ji,he = 1,0
for i in list(str(n)):
ji= ji*eval(i) # 积
he = he+eval(i) # 和
return ji-he
if __name__ == '__main__':
solution = Solution().subtractProductAndSum(123)
print(solution)
|
091b088dbb420ac20bd9eb0bfb0336b99fb4919a | suspendisse02/Scientific_Computing_with_Python | /057_built-in_func_list.py | 138 | 3.53125 | 4 | num = [5, 25, 18, 4, 26, 36, 45, 85, 99, 64, 15]
print(len(num))
print(max(num))
print(min(num))
print(sum(num))
print(sum(num)/len(num))
|
f949747256449538fe1ecdc4cd0bb87c1f28db3b | nielsdimmers/training | /HelloWorld.py | 1,659 | 4.46875 | 4 | # HelloWorld.py
# Niels Dimmers 2021
# Shows custom message based on commandline name given or asks for name.
# Requires at least python version 3 (python3)
# Import system library to get version info.
import sys
# sys.argv contains commandline arguments, the first is the script name, the second the argument, if there are fewer than 2, ask for the name, otherwise, assume the given command is the name (useful for automated testing)
if len(sys.argv) < 2 or sys.argv[1] == '':
# Ask for user input (your name) amd store it in variable 'userName'
userName = input('What is your name? \n')
else:
# Set the name to the argument given on commandline
userName = sys.argv[1]
# This is a dictionary mapping, mapping the keys (on the lef of the colon) with the values (on the right).
# This all is stored in a variable named 'nameMessages'.
nameMessages = {
'NIELS':'Nice to see you, O grande creator!',
'ALEKS':'Hello there, Aleksandra'
}
# the f at the beginning of the string states that this one is special, and variables in the text between { and } should be replaced with values. This is the default message (if the name is not in the nameMessages list above.)
defaultMessage = f'I do not think I have seen you here before, {userName}, but still nice to meet you.'
# put the username to capitalisation, so it doesn't matter how you wrote it, it always picks the right name.
userNameUpper = userName.upper()
# this generates the return message, find the message by the key (userNameUpper), and if not found, set it to defaultMessage
returnMessage = nameMessages.get(userNameUpper, defaultMessage)
# print the actual resulting message
print(returnMessage) |
8410e2e0bbb28af4f0300fd9a2af9824aba55584 | PriyankaKhire/ProgrammingPracticePython | /CircularQ.py | 1,134 | 3.515625 | 4 | #Circular Q
class CircularQ(object):
def __init__(self, size):
self.size = size
self.array = [None for i in range(size)]
self.numElements = 0
# delete from head
self.head = 0
# add from tail
self.tail = 0
def push(self, element):
if(self.numElements == self.size):
print "Q full"
return
self.array[self.tail] = element
self.tail = (self.tail+1)%self.size
self.numElements = self.numElements + 1
print self.array
def pop(self):
if(self.numElements == 0):
print "Q empty"
return
print self.array[self.head]
self.array[self.head] = None
self.head = (self.head+1)%self.size
self.numElements = self.numElements - 1
print self.array
# Main
obj = CircularQ(5)
obj.push(1)
obj.push(2)
obj.push(3)
obj.push(4)
obj.push(5)
obj.push(6)
obj.pop()
obj.push(6)
obj.push(7)
obj.pop()
obj.push(7)
obj.pop()
obj.pop()
obj.pop()
obj.pop()
obj.pop()
obj.pop()
obj.push(8)
obj.pop()
obj.push(9)
|
9bfdce25d300e78f8737c5bca111600bdd566bee | Dhanya1234/python-assignment-5 | /assignment 4_ ro check whether given number is present in given range or not.py | 136 | 4 | 4 | def input(n):
if n in range(3,9):
print("number is in given range ",n)
else:
print("number is not in given range")
input(6)
|
6b179a5428394cc5757bb0f5de114151ce8f5848 | leonberlang/datasciencefundamentals | /week1-exercises/lists-snack-exercise.py | 693 | 4.03125 | 4 | friends = ["Henk", "Jaap", "Kees"] #, "Herman", "Jasper", "Luuk", "Steyn", "Nick"
snacklist = []
for name in friends:
print(name)
name_length = len(name)
print(str(name_length) + " characters long")
snack = input(name + ", What is your fav snack?")
snacklist.append(snack)
index = 0
for name in friends:
print(name)
print(index)
print(snacklist[index]) #wat tussen [] staat is het nummer in de lijst, en daar kan je controle uitoefenen via zelf daar steeds eentje bij toe te voegen
index = index + 1 #moet eerst printen anders begin je al bij EEN
# if u use for the variable after that is new and created
# can also just make varaible snack = snacklist[index]
|
c8dce913694c4449787e0626696c4941376c531c | saleed/LeetCode | /31.py | 743 | 3.6875 | 4 | def nextPermutation(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) == 0 or len(nums) == 1:
return
for i in list(reversed(range(len(nums) - 1))):
if nums[i] < nums[i + 1]:
break
if i == 0 and nums[i] > nums[i + 1]:
nums = list(reversed(nums))
print nums
else:
for j in list(reversed(range(i + 1, len(nums)))):
if nums[j] > nums[i]:
break
nums[i], nums[j] = nums[j], nums[i]
nums = nums[:i + 1] + list(reversed(nums[i + 1:]))
print nums
a=[1,3,2]
nextPermutation(a)
b=[3,2,1]
nextPermutation(b)
c=[1,3,6,5,2,1]
nextPermutation(c)
|
79a0ce0b52eb080732c4917aa1af733edb983102 | kasrasadeghi/cs373 | /notes/06-14.py | 772 | 3.6875 | 4 | # -----------
# Wed, 14 Jun
# -----------
"""
semantics of the operator and types in Python
start exploring in detail iteration and iterables in Python
"""
def f (n: int) -> int :
if (n <= 1)
return 1
return n * f(n - 1)
def f (n: int) -> int :
m = 1
while (n > 0) :
m *= n
n -= 1
return m
a = [2, 3, 4]
p = iter(a)
print(next(p)) # 2
print(next(p)) # 3
print(next(p)) # 4
print(next(p)) # raise StopIteration
# ---------
# Questions
# ---------
"""
What is a recursive procedure? Recursive process?
What is tail recursion?
Why don't containers allow direct iteration?
What is iter()?
What do iterators do when they're exhausted?
What is range() and xrange() in Python 2?
What is range() in Python3?
What is reduce()?
"""
|
86482a0a66af515230d5549076c27f6fc2a3340f | sulegebedek/PG1926-Python-Problem-Sets | /TekSayiGuncelleme.py | 322 | 3.59375 | 4 | list=[]
index = int(input("Kaç sayı gireceksiniz: "))
for i in range(index):
number = list.append(int(input("sayı giriniz:")))
print("\n")
print(list)
print("\n")
enBuyuk = list[0]
for j in list:
if j % 2 != 0 :
if j > enBuyuk:
enBuyuk = j
print("En buyuk tek sayı: {}".format(enBuyuk))
|
71d40c8a6eb84689d230f55f2a8a1eb36e826820 | liuhuipy/Algorithm-python | /tree/build-binary-tree.py | 945 | 3.578125 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: list, inorder: list) -> TreeNode:
if not preorder:
return
if len(preorder) == 1:
return TreeNode(preorder[0])
root_index, root = 0, TreeNode(preorder[0])
for i in range(len(inorder)):
if inorder[i] == root.val:
root_index = i
break
if root_index:
root.left = self.buildTree(preorder[1: root_index + 1], inorder[:root_index + 1])
if root_index < len(inorder) - 1:
root.right = self.buildTree(preorder[root_index + 1:], inorder[root_index + 1:])
return root
# if __name__ == '__main__':
# preorder = [3, 9, 20, 15, 7]
# inorder = [9, 3, 15, 20, 7]
# solution = Solution()
# solution.buildTree(preorder, inorder)
|
a62937d4d557ce87c7126d17e93c6b17d38cdf50 | maykooljb/pythonLearning | /areaOfASquare.py | 153 | 4.15625 | 4 | side = input("Enter the measure of the side of the square: ");
side = int(side);
area = side * side;
print("the area of the square is: ");
print(area);
|
a731106799b3a4b0e4fa9106a9c6443798cda0a9 | lndaquino/data-structures-and-algorithms-using-python | /Algorithms/patternMatching.py | 770 | 4.03125 | 4 | '''
text processing using brute force for patter matching
ideia é encontrar padrão (palavra, substring etc) dentro de um texto
task - buscar métodos mais otimizados, que retornem multiplas posições do padrão encontrado e pode ser escolhido em ignorar maiuscula/minuscula (por enquanto só retorna o primeiro encontrado)
'''
def bruteForce(text, pattern):
lenText, lenPattern = len(text), len(pattern)
for i in range(lenText - lenPattern + 1):
j = 0
while j < lenPattern and text[i + j] == pattern[j]:
j += 1
if j == lenPattern:
return i #substring text[i : i+j] corresponde a pattern
return -1
text = 'Python é uma excelente linguagem, pois python é muito fácil de aprender.'
pattern = 'python'
print(bruteForce(text, pattern)) |
5debfc4c3bf04df02591d6a17649ff1ff7f7f265 | elYaro/Codewars-Katas-Python | /8 kyu/Abbreviate_a _Two_Word_Name.py | 506 | 3.609375 | 4 | '''
Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
The output should be two capital letters with a dot seperating them.
It should look like this:
Sam Harris => S.H
Patrick Feeney => P.F
'''
# 2nd try - after refactor
def abbrevName(name):
a = name.split()
return "{0:s}.{1:s}".format(a[0][0].upper(), a[1][0].upper())
# 1st try
def abbrevName(name):
a = (name.split())
return "{}.{}".format(a[0][0].upper(), a[1][0].upper()) |
609268778d52a688f614910101686b9b59ad53e1 | dmytrov/stochasticcontrol | /code/linalg/routines.py | 1,327 | 3.625 | 4 | import numpy as np
def lines_closest_pts(a, b, c, d):
"""
Returns two closest pints on the lines AB and CD,
which detetermines the distance between the lines.
a, b, c, d: [3] numpy vectors
return: n, m: [3] numpy vectors of the closest points
"""
A = np.array([[(b-a).dot(b-a), -(b-a).dot(d-c)],
[(d-c).dot(b-a), -(d-c).dot(d-c)]])
B = -np.array([(b-a).dot(a-c), (d-c).dot(a-c)])
x = np.linalg.inv(A).dot(B)
n = a + x[0] * (b-a)
m = c + x[1] * (d-c)
return n, m
def lines_angle(a, b, c, d):
"""
Returns the angle between the lines AB and CD,
a, b, c, d: [3] numpy vectors
return: alpha: [3] numpy vector
"""
A = (a-b) / np.linalg.norm(a-b)
B = (c-d) / np.linalg.norm(c-d)
alpha = np.arccos(np.dot(A, B))
return alpha
if __name__ == "__main__":
a = np.array([ 1, 2, -2])
b = np.array([ 2, 3, -2])
c = np.array([ 0,-1, 5])
d = np.array([ 0, 1, 5])
n, m = lines_closest_pts(a, b, c, d)
assert np.allclose(n, np.array([ 0., 1., -2.]))
assert np.allclose(m, np.array([ 0., 1., 5.]))
a = np.array([ 0, 0, -3])
b = np.array([ 1, 1, -3])
c = np.array([ 0, 0, 5])
d = np.array([ 1, 0, 5])
alpha = lines_angle(a, b, c, d)
assert np.allclose(alpha, np.pi / 4)
|
24601bd3e990284a5da3ac21758c8dc4703e8e64 | hudsone8024/CTI-110 | /P3LAB_Debugging_EricHudson.py | 460 | 3.875 | 4 | # CTI-110
# P3LAB- Debugging
# Eric Hudson
# 30 June 2020
#
print()
if score >= A_score:
print("Your grade is A.")
else:
if score >= B_score:
print("Your grade is B.")
else:
if score >= C_score:
printL"Your grade is C.")
else:
if score >= D_score:
print("Your grade is D.")
else:
print("Your grade is F.")
print()
print()
# Write if and else statements
# Ensure each result is printed
# Align all clauses
# Indent all print executions |
570880d9ec264094d14662276b7d66847231bda8 | angela-mccleery-miller/journal_list | /PYTHON/pythonAlgorithms/lists.py | 424 | 3.90625 | 4 | #Lists:
my_list = [10,20,30, 40, 50]
for i in mylist:
print i
#Tuples:
my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for i in my_tup:
print i
#Dict (is a hash-table):
my_dict = {'name': 'Bronx', 'age': '2', 'occupation': "Corey's Dog"}
for key, val in my_dict.iteritems():
print("My {} is {}". format(key, val))
#Set:
my_set = {10,20,30,40,50,10,20,30,40,50}
for i in my_set:
print(i) |
d6ffcf69483c1b4ee356b7609360b1cee2343609 | amberbeymer/Beymer_story | /acute.py | 175 | 3.765625 | 4 | pyth_diff = a[2]**2 - (b[0]**2 + c[1]**2)
if (pyth_diff > 0):
print("Triangle is obtuse")
elif (pyth_diff == 0):
print("Triangle is right")
else:
print("Triangle is acute") |
032b70ce15e6fd882f76e5417b3f86c6fab16d39 | whchoi78/python | /wiget.py | 752 | 3.984375 | 4 | from tkinter import*
window = Tk()
window.title("hello")
"""
bt1 = Button(window, text="버튼1")
bt2 = Button(window, text="버튼2")
bt3 = Button(window, text="버튼3")
bt1.pack(side=LEFT) #LEFT, TOP, BOTTON
bt2.pack(side=LEFT)
bt3.pack(side=LEFT)
"""
bt = [0,0,0]
for i in range(3):
bt[i] = Button(window, text="버튼"+str(i+1))
bt[i].place(x=10, y=10, width=50, height=50) #pack함수쪽에다 일일이 하기 귀찮으면 미리 place함수에 담아서 필요할때 꺼냄
bt[i].pack()
# bt[i].pack(side=TOP, fill=X, padx=10, pady=10, ipadx=10, ipady=10) #fill은 채우기 padx는 가로 여백 pady는 세로 여백 ipad는 버튼 안 여백
#place(x=x좌표, y=y좌표, width=폭, hegiht=높이)
window.mainloop() |
1a87fe4f117a6cd3900332cda0d1d6248ce73969 | Ubivius/art-assets | /pixel_art_generator/utils.py | 1,202 | 3.78125 | 4 | import math
import numpy as np
from logger import logger
def euclidean_distance(row1, row2):
""" Method that process the Euclidean distance between two vectors
:param row1: First vector
:param row2: Second vector
:return: Euclidean distance
"""
#distance = 0.0
#for i in range(len(row1)-1):
# distance += (row1[i] - row2[i])**2
#np.sum(row1 - row2) ** 2
return np.sqrt((row1 - row2).sum() ** 2)
def init_codebook(init_type, N, width):
""" Initialisation of the codebook
:param init_type: Type of initialisation
:param N: Bit budget
:return: Initialized codebook
"""
codebook = np.zeros((2 ** N, width))
if init_type == "random":
pass
elif init_type == "equal":
for i in range(0, 2 ** N):
for j in range(0, width):
codebook[i, j] = (256 / 2 ** N) * (i + 1) - 1
elif init_type == "fixed":
codebook = np.array([[27, 27],
[101, 101],
[175, 175],
[216, 216]])
else:
logger.error("Wrong type of codebook initialisation. Try \"equal\" or \"random\".")
return codebook
|
6420c7ed1cb229e10351662a234f8bd17b82ffda | EugeneStill/PythonCodeChallenges | /archive/findTheDuplicate.py | 284 | 3.78125 | 4 | def find_the_duplicate(l1):
l1.sort()
for i in range(1, len(l1)):
if l1[i] == l1[i-1]:
return l1[i]
return None
print(find_the_duplicate([1,2,1,4,3,12])) # 1
print(find_the_duplicate([6,1,9,5,3,4,9])) # 9
print(find_the_duplicate([2,1,3,4])) # None
|
4cb72c150ceb29c83616792951b5835837908b9c | ritallopes/Cifras | /Vigenere/vigenere.py | 861 | 3.671875 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
chave = "ipanema"
def searchPosition(ch):
'''
Funcao para buscar posicao do caracter no alfabeto definido O(n), onde n e a posicao de ch no alfabeto
:param char ch - caracter a ser procurado no alfabeto
'''
for i in range(0,len(alphabet)):
if alphabet[i] == ch:
return i
return -1
def readFile(file):
file_open = open(file, "r")
file_to_write = open("texto_claro.txt","w")
msg = str()
aux = 0
for line in file_open:
for letter in line:
pos = searchPosition(letter)
pos_chave = aux % len(chave)
if (pos == -1):
file_to_write.write(letter)
msg+= letter
else:
aux += 1
p = (pos - searchPosition(chave[pos_chave]) + 26 ) % 26 #uso de expressao algebrica
file_to_write.write(alphabet[p])
msg += alphabet[p]
return msg
print(readFile("mensagem.txt"))
|
e8ebec7a4cb5fa70a98fa797f1ee9e5e966fa1cb | lalitzz/DS | /Sequence5/CTCI/1-Array_String/9string_rotation.py | 828 | 3.640625 | 4 | def is_rotation(s1, s2):
if len(s1) == 0 or len(s1) != len(s2):
return False
s1 = s1 + s1
return _is_substring(s1, s2)
def _is_substring(s1, s2):
return kmp_pattern(s2, s1)
def kmp_pattern(pattern, text):
print(pattern, text)
S = pattern + '$' + text
s = compute_prefix(S)
result = []
for i in range(len(pattern) + 1, len(S)):
if s[i] == len(pattern):
result.append(i - 2 * len(pattern))
return result
def compute_prefix(pattern):
n = len(pattern)
s = [None for i in range(n)]
s[0] = 0
border = 0
for i in range(1, n):
while border > 0 and pattern[i] != pattern[border]:
border = s[border - 1]
if pattern[i] == pattern[border]:
border += 1
else:
border = 0
s[i] = border
return s
s1 = "waterbottle"
s2 = "erbottlewat"
print(is_rotation(s1, s2)) |
f40179770b686b5551b49121c51dfe5a4886133f | ashwin-suresh-kumar/Python-Programs | /TikTacToe.py | 5,786 | 3.75 | 4 | '''
Created on Dec 22, 2015
@author: Ashwin Suresh Kumar
'''
from random import randint
first_row = ['NA']*3
second_row = ['NA']*3
third_row = ['NA']*3
flag_p1 = 0
#flag_p2 = 0
def print_board():
global first_row
global second_row
global third_row
print "\n"
print "%s | %s | %s" %(first_row[0],first_row[1],first_row[2])
print "--------------"
print "%s | %s | %s"%(second_row[0],second_row[1],second_row[2])
print "--------------"
print "%s | %s | %s"%(third_row[0],third_row[1],third_row[2])
print "\n"
def check_win(player):
global first_row
global second_row
global third_row
if( first_row[0] == first_row[1] == first_row[2] == 'X' or first_row[0] == first_row[1] == first_row[2] == 'O' or
first_row[0] == second_row[0] == third_row[0] == 'X' or first_row[0] == second_row[0] == third_row[0] == 'O' or
first_row[0] == second_row[1] == third_row[2] == 'X' or first_row[0] == second_row[1] == third_row[2] == 'O' or
first_row[1] == second_row[1] == third_row[1] == 'X' or first_row[1] == second_row[1] == third_row[1] =='O' or
second_row[0] == second_row[1] == second_row[2] == 'X' or second_row[0] == second_row[1] == second_row[2] == 'O' or
first_row[2] == second_row[1] == third_row[0] == 'X' or first_row[2] == second_row[1] == third_row[0] == 'O' or
first_row[2] == second_row[2] == third_row[2] == 'X' or first_row[2] == second_row[2] == third_row[2] == 'O' or
third_row[0] == third_row[1] == third_row[2] == 'X' or third_row[0] == third_row[1] == third_row[2] == 'O' or
third_row[2] == second_row[1] == first_row[0] =='X' or third_row[2] == second_row[1] == first_row[0] == 'O' ):
print 'Player %s is the winner' %player
else:
swap_player()
def swap_player():
global flag_p1
if (flag_p1 == 1):
flag_p1 = 0
play(2)
else:
play(1)
def insert_to_board(player,p_input,symbol):
position = int(p_input)
global first_row
global second_row
global third_row
if(position != 1 or position != 2 or position != 3 or position != 4 or position != 5 or position != 6 or position != 7 or position != 8 or position != 9):
if(position == 1 or position == 2 or position == 3):
if(first_row[0] == 'NA' or first_row[1] == 'NA' or first_row[2] == 'NA'): #list full check
if(first_row[position-1] == 'NA'): #position occupied check
first_row.pop(position-1)
first_row.insert(position-1,symbol)
print_board()
check_win(player)
else:
print 'Please select a different position, overwrite is not possible'
play(player)
else:
print 'First row is full, please select a number except 1 , 2 and 3'
play(player)
elif (position == 4 or position == 5 or position == 6):
if(second_row[0] == 'NA' or second_row[1] == 'NA' or second_row[2] == 'NA'): #list full check
if(second_row[position-4] == 'NA'): #position occupied check
second_row.pop(position-4)
second_row.insert(position-4,symbol)
print_board()
check_win(player)
else:
print 'Please select a different position, overwrite is not possible'
play(player)
else:
print 'Second row is full, please select a number except 4 , 5 and 6'
play(player)
else:
if(third_row[0] == 'NA' or third_row[1] == 'NA' or third_row[2] == 'NA'): #list full check
if(third_row[position-7] == 'NA'): #position occupied check
third_row.pop(position-7)
third_row.insert(position-7,symbol)
print_board()
check_win(player)
else:
print 'Please select a different position, overwrite is not possible'
play(player)
else:
print 'Third row is full, please select a number except 7 , 8 and 9'
play(player)
else:
print 'The user input is not valid, Please try again'
play(player)
def play(player):
if(player == 1):
global flag_p1
print "It is player 1 turn"
flag_p1 = 1
p1_input = raw_input("Enter a number between 1 to 9 : ")
insert_to_board(player,p1_input,'X')
else:
print "It is player 2 turn"
p2_input = raw_input("Enter a number between 1 to 9 : ")
insert_to_board(player,p2_input,'O')
def game_play():
print "The game has begun"
player = randint(0,2)
if(player == 1):
play(1)
else:
play(2)
def instructions():
title = " Tic Tac Toe "
print title.center(60,'*')
print 'Step 1: The computer will randomly pick the player to play first'
print "Step 2: First player will play with the symbol 'X'"
print "Step 3: Second player will play with the symbol 'O'"
print "Use the number pad to choose the box in which the player wants to enter their symbol"
print "The play area appears as follows"
print "\n"
print "(1) | (2) | (3)"
print "----------------"
print "(4) | (5) | (6)"
print "----------------"
print "(7) | (8) | (9)"
print "\n"
input = raw_input("Enter 'Y' to continue or 'N' to quit:")
if(input == 'Y' or input == 'y' ):
game_play()
elif(input == 'N' or input == 'n'):
exit()
else:
print 'unknown input, game restart!'
instructions()
instructions() |
dcd5a152a34ec17fd522f354d87a8c188c265df8 | luitzenhietkamp/cs50 | /pset6/caesar/caesar.py | 564 | 4.09375 | 4 | import sys
from cs50 import get_string
# ensure proper usage
if not len(sys.argv) == 2:
print("Usage: python caesar.py k")
sys.exit(1)
key = int(sys.argv[1])
# prompt user for input
message = get_string("plaintext: ")
# encrypt the message
ciphertext = ""
for c in message:
if c.isupper():
ciphertext += chr((ord(c) - ord("A") + key) % 26 + ord("A"))
elif c.islower():
ciphertext += chr((ord(c) - ord("a") + key) % 26 + ord("a"))
else:
ciphertext += c
# output result
print("ciphertext: ", end="")
print(ciphertext) |
a18b3d4c900b760226169f4a0a70f020c9e3854b | doyoonkim3312/PythonPractice | /Exercise/Math Quiz/math_quiz.py | 1,132 | 4.34375 | 4 | ###############################################################################
# Author: Doyoon Kim (kim3312@purdue.edu)
# Date: Mar 19, 2021
# Description This program generate simple math question about adding two digit
# number and three digit number.
###############################################################################
import random as random
def main():
# Write your mainline logic here ------------------------------------------
twoDigitNumber: int = random_number(2)
threeDigitNumber: int = random_number(3)
correctAnswer = twoDigitNumber + threeDigitNumber
print(f" {twoDigitNumber}")
print(f"+ {threeDigitNumber}")
print("-----")
userAnswer = int(input("= "))
if userAnswer == correctAnswer:
print(f"Correct -- Good Work!")
else:
print(f"Incorrect. The correct answer is {correctAnswer}.")
def random_number(digits):
if digits == 2:
return random.randrange(10,100)
elif digits == 3:
return random.randrange(100,1000)
# Don't change this -----------------------------------------------------------
if __name__ == '__main__':
main()
|
7fa07c1f85ae18d21c70726cf2cdf2544bf6d883 | Sana-mohd/log_in-and-sign_up | /sign_up_if-else.py | 1,612 | 4.03125 | 4 | user_ans=input("enter either log in or sign up: ")
if user_ans=="sign up":
user_name=input("enter your user name: ")
i=1
list=["0","1","2","3","4","5","6","7","8","9"]
while i<2:
password=input("enter your password: ")
a=0
b=0
c=0
for x in password:
if x>"A" and x<"Z" or x>"a" and x<"z" or x=="@" or x=="#" or x in list:
if x>"A" and x<"Z" or x>"a" and x<"z":
c=c+1
elif x in list:
a=a+1
elif x=="@" or x=="#":
b=b+1
if a==0:
print("req atleast one number")
if b==0:
print("req atleast one special character\nplease sign up again")
if c==0:
print("req alphabets ")
i=i+1
if a>=1 and b>=1 and c>=1:
print("alright it is acceptable")
confirm_password=input("enter your password for confirmation: ")
if password==confirm_password:
print("congratulations\nyou are signed up successfully")
import json
dict={}
json_file={}
dict[user_name]=password
list=[dict]
json_file["user"]=list
f=open("signup.json","w")
json.dump(json_file,f,indent=1)
f.close()
else:
print("both passwords are not same\ncheck weather you have entered both passwords correclt or not")
else:
print("not acceptable")
|
275a4a57f4fa9151c3288e15cee4b89a325648e4 | PavleMatijasevic/PPJ | /vezbanje/vezbanje/automat1.py | 573 | 3.5625 | 4 | import sys
stanje = 'A'
zavrsno = 'D'
prelaz = {('A', 'b'):'B', ('A', 'c'):'CE',
('B', 'b'):'D', ('CE','a'):'CE',
('CE', 'b'):'D'}
while True:
try:
print("Unesi a ili b ili c\n")
c = input()
if(c != 'a' and c != 'b' and c != 'c'):
sys.exit("Pogresan unos!\n")
except EOFError:
break;
if prelaz.get((stanje, c)) is None:
sys.exit("Greska, rec nije deo jezika")
stanje = prelaz[(stanje, c)]
print('\t')
if(stanje == zavrsno):
print("Uspesno")
else:
print("Neuspesno") |
14b3292f4ae4d1b246a6f10be0e5d3dfcfa64d51 | karthikkosireddi-g/P-Class | /Week1/16-NestedDictionaries.py | 609 | 3.5625 | 4 | d1 = {
"name" : "mac",
"ip" : "10.20.30.40",
"status" : 1
}
d2 = {
"name" : "linux",
"ip" : "10.20.30.41",
"status" : 3
}
d = {
"d1": {
"name": "mac",
"ip": "10.20.30.40",
"status": 1
},
"d2" : {
"name": "linux",
"ip": "10.20.30.41",
"status": 3
},
"d3": {
"name": "win",
"ip": "10.20.30.42",
"status": 5
}
}
print (d)
print(d["d2"])
print(d["d1"]["name"])
d["allDevices"] = {
"1" : "d1",
"2" : "d2",
"3" : "d3",
"4" : "not present"
}
print (d["allDevices"])
print (d)
|
82cd462f5d8b5b34947b7f3818045420b5ac8826 | darraes/coding_questions | /v2/_leet_code_/0142_detect_cycle.py | 1,123 | 3.578125 | 4 | class Node:
def __init__(self, value, next=None):
self.next = next
self.value = value
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
node = runner = head
while runner and runner.next:
node = node.next
runner = runner.next.next
if node == runner:
intersect = head
while node != intersect:
node = node.next
intersect = intersect.next
return node
return None
###############################################################
import unittest
def from_list(list):
idx = 0
while idx < len(list) - 1:
list[idx].next = list[idx + 1]
idx += 1
return list[0]
class TestFunctions(unittest.TestCase):
def test_1(self):
s = Solution()
source = [Node(1), Node(2), Node(3), Node(5), Node(7)]
n = from_list(source)
source[-1].next = source[1]
s.detectCycle(n)
if __name__ == "__main__":
unittest.main()
|
4189f3cb04fe930b68d6ca56412c3bfac7eedbad | aquibali01/100DaysOfCode- | /Day10/day-10-start/main.py | 452 | 4.28125 | 4 | # function with outputs
def format_name(f_name,l_name):
"""Take first and last name and format it to title format""" #docstring
if f_name == "" or l_name == "":
return "You didn't provide valid inputs"
title_name = f_name.title() + " "+l_name.title()
return title_name #return tells the computer the function ends
formated_string = format_name(input("What is your first name ? "),input("What is your last name ? "))
print(formated_string) |
67a80cf89f7624c14ba84a6d41a9624e19911aa2 | tylerem21/isat340_miniproject | /Retrieve member data.py | 287 | 4.03125 | 4 | #Retrieve Data
import sqlite3
conn=sqlite3.connect("celebrities.db")
cursor=conn.cursor()
#SQL SELECT statement
sql2="select * from members"
cursor.execute(sql2)
#get the rows
rows=cursor.fetchall()
#iterate over the results and print them
for row in rows:
print(row)
conn.close()
|
2939271b1447cc74e6020193f567c591b4d0a17f | ranasalman3838/pythonpractice | /Day7.py | 1,793 | 4.25 | 4 | # class Dog:
# def __init__(self, name, age):
# self.name = name
# self.age = age
#
# def bark(self):
# print(f"{self.name} is barking")
#
# def age(self):
# print(f"{self.name} age is {self.age}")
#
#
# dog1 = Dog('German Shepherd', 4)
# print(f'{dog1.age}')
# dog1.bark()
# 9-1. Restaurant: Make a class called Restaurant . The __init__() method for
# Restaurant should store two attributes: a restaurant_name and a cuisine_type .
# Make a method called describe_restaurant() that prints these two pieces of
# information, and a method called open_restaurant() that prints a message indi-
# cating that the restaurant is open.
# Make an instance called restaurant from your class. Print the two attri-
# butes individually, and then call both methods.
# class Restaurant:
# def __init__(self, restaurant_name, cuisine_type):
# self.restaurant_name=restaurant_name
# self.cuisine_type = cuisine_type
#
# def describe_restaurant(self):
# print(f'restaurant name is {self.restaurant_name} and cuisine type is {self.cuisine_type}')
#
# def open_restaurant(self):
# print(f'{self.restaurant_name} is opened')
#
# r = Restaurant('onecup','chinese')
# print(f'{r.restaurant_name}')
# r.describe_restaurant()
# r.open_restaurant()
# 9-3. Users: Make a class called User . Create two attributes called first_name
# and last_name , and then create several other attributes that are typically stored
# in a user profile. Make a method called describe_user() that prints a summary
# of the user’s information. Make another method called greet_user() that prints
# a personalized greeting to the user.
# Create several instances representing different users, and call both methods
# for each user.
|
48cfb8843839d33e4ee9a02936abc856c8843909 | haseeb33/Book-Store | /intermediate.py | 2,106 | 3.96875 | 4 | """
A program that store this book information:
Backend functionaltiy
Creating the db file
attaching the functions with buttons
"""
from back_end import Database
import front_end as fe
from tkinter import *
db = Database("books.db")
#When the app starts creating the book table in books.db
def view_command():
fe.book_list.delete(0, END)
hide_entries()
for row in db.view():
fe.book_list.insert(END, row)
def search_command(title, author, shelf, price, quantity, section):
fe.book_list.delete(0, END)
for row in db.search(title, author, shelf, price, quantity, section):
fe.book_list.insert(END, row)
def insert_command(title, author, shelf, price, quantity, section):
fe.book_list.delete(0, END)
row = (title, author, shelf, price, quantity, section)
db.insert(title, author, shelf, price, quantity, section)
fe.book_list.insert(END, row)
def update_command(title, author, shelf, price, quantity, section):
fe.book_list.delete(0, END)
row = (title, author, shelf, price, quantity, section)
db.update(selected_tuple[0],title, author, shelf, price, quantity, section)
fe.book_list.insert(END, row)
def delete_command():
fe.book_list.delete(0, END)
hide_entries()
db.delete(selected_tuple[0])
for row in db.view():
fe.book_list.insert(END, row)
def get_selected_row(event):
global selected_tuple
index = fe.book_list.curselection()[0]
selected_tuple = fe.book_list.get(index)
update_entries()
def hide_entries():
fe.title_e.delete(0, END)
fe.author_e.delete(0, END)
fe.shelf_e.delete(0, END)
fe.quantity_e.delete(0, END)
fe.price_e.delete(0, END)
fe.section_e.delete(0, END)
def update_entries():
hide_entries()
try:
fe.title_e.insert(END, selected_tuple[1])
fe.author_e.insert(END, selected_tuple[2])
fe.shelf_e.insert(END, selected_tuple[3])
fe.quantity_e.insert(END, selected_tuple[4])
fe.price_e.insert(END, selected_tuple[5])
fe.section_e.insert(END, selected_tuple[6])
|
5bf9ad5a9c79697216da9ab6aaf4b1f2ae14dc54 | tl1759/FinalProject_PDS | /map/userinput.py | 1,031 | 3.515625 | 4 | ####################################################################################################
#
#
# Author : Liwen Tian(tl1759)
# DS GA 1007
# Final Project
#
# This is the users input module.
#
####################################################################################################
import csv
import shapefile
import pandas as pd
import numpy as np
from cleanupModule import *
from plotmapModule import *
import sys
agencyList = ['HPD','DOT','NYPD','FDNY','DEP','DOHMH','DPR','TLC']
def getinput():
print "Choose two different agencies in the agencies' List:"
print agencyList
agency1 = raw_input('Please choose the first agency:\n')
agency2 = raw_input('please choose the second agency:\n')
if agency1 in agencyList and agency2 in agencyList:
pass
else:
print "Error: Agencies are not correctly selected!"
print "Please make sure the agency is in the list otherwise the output is not valid.\n"+" There are no such agencies. ("+agency1+','+agency2+")"
sys.exit()
return agency1,agency2
|
cef919c306f8f9d250e0df226da3b3f2e479edeb | Jace-Yang/ml-algorithms-built-from-scratch | /model_Neural Network/models/NeuralNetwork.py | 4,710 | 3.53125 | 4 | # !!! 请先阅读 代码文档.pdf 中模型的建立、求解和逐步讲解。
# 作者:吴宇翀 经济统计学 2017310836 https://wuyuchong.com
# 代码开源托管在 https://github.com/wuyuchong/DataMining/tree/master/HomeWork
# ----------------- 导入基本模块 -----------------
import numpy as np
import math
from matplotlib import pyplot as plt
# ------------ 导入source中定义的函数 ------------
from source.sigmoid import sigmoid
from source.sigmoidDerivative import sigmoidDerivative
from source.mse import mse
# ---------------- 定义神经网络类 ----------------
class NeuralNetwork:
def __init__(self, X, y, learn_rate = 0.1, epochs = 100):
# 学习率和迭代次数
self.learn_rate = learn_rate
self.epochs = epochs
# 数据
self.X = X
self.y = y
# 权重和截距的初始化
self.weight_1a = np.random.normal()
self.weight_1b = np.random.normal()
self.weight_2a = np.random.normal()
self.weight_2b = np.random.normal()
self.weight_o1 = np.random.normal()
self.weight_o2 = np.random.normal()
self.bias_1 = np.random.normal()
self.bias_2 = np.random.normal()
self.bias_o = np.random.normal()
# 记录损失函数值
self.record = np.array([None, None])
# 用于画 MSE 的图像
def figure(self):
x = self.record[1:,0]
y = self.record[1:,1]
plt.title("Variation of the Loss Function")
plt.xlabel("epochs")
plt.ylabel("MSE")
plt.plot(x,y,"ob")
plt.show()
# 定义前馈
def feedforward(self, x):
h1 = sigmoid(self.weight_1a * x[0] + self.weight_1b * x[1] + self.bias_1)
h2 = sigmoid(self.weight_2a * x[0] + self.weight_2b * x[1] + self.bias_2)
o1 = sigmoid(self.weight_o1 * h1 + self.weight_o2 * h2 + self.bias_o)
return o1
# 定义预测函数
def predict(self):
y_preds = np.apply_along_axis(self.feedforward, 1, self.X)
return y_preds
# 定义训练函数
def train(self):
for epoch in range(self.epochs):
for x, y_true in zip(self.X, self.y):
# 初次前馈
sum_h1 = self.weight_1a * x[0] + self.weight_1b * x[1] + self.bias_1
h1 = sigmoid(sum_h1)
sum_h2 = self.weight_2a * x[0] + self.weight_2b * x[1] + self.bias_2
h2 = sigmoid(sum_h2)
sum_o1 = self.weight_o1 * h1 + self.weight_o2 * h2 + self.bias_o
o1 = sigmoid(sum_o1)
y_pred = o1
# 计算导数
L_ypred = -2 * (y_true - y_pred)
# 输出层
ypred_weight_o1 = h1 * sigmoidDerivative(sum_o1)
ypred_weight_o2 = h2 * sigmoidDerivative(sum_o1)
ypred_bias_o = sigmoidDerivative(sum_o1)
ypred_h1 = self.weight_o1 * sigmoidDerivative(sum_o1)
ypred_h2 = self.weight_o2 * sigmoidDerivative(sum_o1)
# 隐藏层 1
h1_weight_1a = x[0] * sigmoidDerivative(sum_h1)
h1_weight_1b = x[1] * sigmoidDerivative(sum_h1)
h1_bias_1 = sigmoidDerivative(sum_h1)
# 隐藏层 2
h2_weight_2a = x[0] * sigmoidDerivative(sum_h2)
h2_weight_2b = x[1] * sigmoidDerivative(sum_h2)
h2_bias_2 = sigmoidDerivative(sum_h2)
# # 迭代权重和偏差
# 隐藏层 1
self.weight_1a -= self.learn_rate * L_ypred * ypred_h1 * h1_weight_1a
self.weight_1b -= self.learn_rate * L_ypred * ypred_h1 * h1_weight_1b
self.bias_1 -= self.learn_rate * L_ypred * ypred_h1 * h1_bias_1
# 隐藏层 2
self.weight_2a -= self.learn_rate * L_ypred * ypred_h2 * h2_weight_2a
self.weight_2b -= self.learn_rate * L_ypred * ypred_h2 * h2_weight_2b
self.bias_2 -= self.learn_rate * L_ypred * ypred_h2 * h2_bias_2
# 输出层
self.weight_o1 -= self.learn_rate * L_ypred * ypred_weight_o1
self.weight_o2 -= self.learn_rate * L_ypred * ypred_weight_o2
self.bias_o -= self.learn_rate * L_ypred * ypred_bias_o
# 计算损失函数,并保存
y_preds = np.apply_along_axis(self.feedforward, 1, self.X)
loss = mse(self.y, y_preds)
new = np.array([epoch, loss])
self.record = np.vstack([self.record, new])
|
9bda55e43a80dfe4630693922c7ab7b99c567d82 | himanshu2922t/FSDP_2019 | /DAY-02/operation.py | 1,027 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 15:05:54 2019
@author: Himanshu Rathore
"""
number_list = input("Enter a space separated list of numbers: ").split()
def Add():
sum = 0
for number in number_list:
sum += int(number)
return sum
def Multiply():
product = 0
for number in number_list:
product *= int(number)
return product
sorted_list = sorted(number_list)
def Sorting():
return sorted_list
def Smallest():
return sorted_list[0]
def Largest():
return sorted_list[-1]
def Remove_Duplicate():
list_without_duplicates = list()
for number in number_list:
if number not in list_without_duplicates:
list_without_duplicates.append(number)
return list_without_duplicates
def Print(list_to_print):
print("Sum =",Add())
print("Multiply =",Multiply())
print("Largest =",Largest())
print("Smallest =",Smallest())
print("Sorted =",Sorting())
print("Without Duplicates =",Remove_Duplicate())
Print(number_list) |
209dac495d5033c27d1e80b8d413321ea9cd435e | UCGD/PFB2019-Walkthrough | /ProblemSet4/problem4.8-9.py | 126 | 3.71875 | 4 | #!/usr/bin/env python3
for x in range(1,101):
print(x)
## same using list comprehension
[print(x) for x in range(1,101)]
|
8e54e5b63fdac43fa0e0d386ce2d93926d821ae9 | nabilatajrin/MITx-6.00.1x-IntroductionToComputerScienceAndProgrammingUsingPython | /wk03-structured-types/tuples-and-lists/exercise/exercise-04**.py | 601 | 3.90625 | 4 | aList = [0, 1, 2, 3, 4, 5]
bList = aList
aList[2] = 'hello'
print(aList)
print(bList)
print(aList == bList)
print(aList is bList)
cList = [6, 5, 4, 3, 2]
dList = []
for num in cList:
dList.append(num)
print(cList)
print(dList)
print(cList == dList)
print(cList is dList)
"""Python has the two comparison operators == and is. At first sight they seem to be the same,
but actually they are not. == compares two variables based on their actual value. In contrast, the is operator
compares two variables based on the object id and returns True if the two variables refer to the same object.""" |
70ca306e2928e770b11ee5f2e7a3e05cc86218dd | shiv125/Competetive_Programming | /codechef/JUNE17/correct.py | 1,764 | 3.6875 | 4 | def sieve(MAX,all_primes):
prime=[True for i in range(MAX+1)]
p=2
while p*p<=MAX:
if prime[p]==True:
for i in range(p*2,MAX+1,p):
prime[i]=False
p+=1
for p in range(2,MAX):
if prime[p]==True:
all_primes.append(p)
def binarysearchfloor(arr,low,high,x):
mid=0
while low<=high:
if low>high:
return -1
if x>=arr[high]:
return high
mid=(low+high)/2
if arr[mid]==x:
return mid
if mid>0 and arr[mid-1]<=x and x<arr[mid]:
return mid-1
if x<arr[mid]:
high=mid-1
if x>arr[mid]:
low=mid+1
return -1
def binarysearch(arr,low,high,x):
mid=0
while low<=high:
if x<=arr[low]:
return low
if x>arr[high]:
return -1
mid=(low+high)/2
if arr[mid]<x:
if mid+1<=high and x<=arr[mid+1]:
return mid+1
else:
low=mid=1
else:
if mid-1>=low and x>arr[mid-1]:
return mid
else:
high=mid-1
return -1
MAX=10**3+10
primes=[0]*MAX
all_primes=[]
sieve(MAX,all_primes)
print len(all_primes)
print all_primes[-1]
for i in range(2,MAX):
if primes[i]==0:
for j in range(1,MAX/i):
if primes[i*j]==0:
primes[i*j]=i
dic={}
tt=len(all_primes)
test=[0]*tt
for i in range(tt):
dic[all_primes[i]]=i
n=input()
arr=map(int,raw_input().split())
m=input()
result=[]
for i in range(m):
L,R,X,Y=map(int,raw_input().split())
fi=binarysearch(all_primes,0,tt-1,X)
si=binarysearchfloor(all_primes,0,tt-1,Y)
res=0
curr=0
count=0
if fi!=-1:
for j in range(L-1,R):
elem=arr[j]
curr=primes[elem]
count=1
while elem>1:
elem=elem/primes[elem]
if curr==primes[elem]:
count+=1
continue
test[dic[curr]]+=count
curr=primes[elem]
count=1
for k in range(fi,si+1):
res+=test[k]
for k in range(tt):
test[k]=0
result.append(res)
for i in result:
print i
|
0db71e1e42f548c5155829ebc14b1dcf419565c4 | BigThingisComing/baekjoon | /17413.py | 489 | 3.625 | 4 | import sys
input = sys.stdin.readline
string = input().rstrip()
tmp = ''
result = ''
tag_tf = False
for chari in string:
if tag_tf == False:
if chari == '<':
tag_tf = True
tmp = tmp + chari
elif chari == ' ':
tmp = tmp + chari
result = result + tmp
tmp = ''
else:
tmp = chari + tmp
else:
tmp = tmp + chari
if chari == '>':
tag_tf = False
result = result + tmp
tmp = ''
result = result + tmp
print(result) |
17c4c7d94200a1afcd9715bedf7ae9e139031568 | Protogenoi/CoreySchafer | /For Beginners/Dictionaries.py | 1,057 | 4.21875 | 4 |
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'Gym']}
print(student)
print(student['name'])
print(student['courses'])
# Get will return None instead of a error in the key pair value is not found
print(student.get('name'))
print(student.get('phone'))
print(student.get('phone', 'Not Found'))
print('-----Update Student Name-----')
student['name'] = 'Sally'
print(student['name'])
student.update({'name': 'Mikey', 'age': 32, 'phone': '07401434619'})
print(student)
# Delete specific key and its value
print('-----Delete key and value-----')
age = student.pop('age') # del student['age']
print(student)
print(age)
# Find how many keys a dictionary has
print('-----Find keys in dictionary-----')
print(len(student))
# Find values in dictionary
print('-----Print values in dictionary-----')
print(student.values())
# Return keys and values
print('-----Print keys and values-----')
print(student.items())
# Loop through keys and values
print('-----Loop through keys and values-----')
for key, value in student.items():
print(key, value)
|
59f5763b49045c4d5ab2333f281bc5f92f5ee5a7 | rishikakrishna/CIS210 | /ii_3.py | 421 | 3.71875 | 4 | # Place fingers on first and last letter
s = (input)
left = 0
right = len(s) - 1;
while left < right:
if s[left] != s[right]:
return False #SyntaxError: 'return' outside fxn
#Move fingers towards the center
left = left +1
right - right -1
return True
#At each step, s is the portion between fingers
while len(s) > 1:
if s[0] != s [-1]:
return False
#Move fingers towards the center
s = s[1:-1]
return True |
8323dae7fe35af2530c7c9d805f2344b36c74ee0 | mpayalal/Talleres | /TalleresDatos/Taller1/punto6Taller.py | 315 | 4.125 | 4 | def invertirNumero(num, indice = 0):
if(indice == len(num)-1):
return(num[indice])
else:
return(invertirNumero(num, indice+1) + num[indice])
numero = input("Ingrese el número que desea invertir: ")
numInv = invertirNumero(numero)
print("El número invertido es:", numInv) |
93f9ab58a463765405b3891375d502892329ba8c | SebastianTuesta/6.0001 | /EDX VERSION/Middle Term Exam/p6.py | 317 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 16:58:20 2017
@author: Sebastian
"""
# Paste your code here
def gcd(a, b):
"""
a, b: two positive integers
Returns the greatest common divisor of a and b
"""
#YOUR CODE HERE
if b==0:
return a
else:
return gcd(b,a%b)
|
4427866df74bd2ce04ed61177b7e724cda05aa2c | daniel-reich/ubiquitous-fiesta | /EjjBGn7hkmhgxqJej_18.py | 102 | 3.671875 | 4 |
def word_nest(word, nest):
c=0
while nest:
nest=nest.replace(word,'')
c+=1
return c-1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.