blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
c7dd6f35c24d2bc95b6138daba7080ef8c1eff07
daniel-reich/ubiquitous-fiesta
/9Kuah39g997SvZmex_1.py
184
3.625
4
from collections import Counter ​ def common_last_vowel(txt): v = [[c for c in word if c in "aeiou"][-1] for word in txt.lower().split()] return Counter(v).most_common()[0][0]
d455d7abd4b1b1254a80b3c6b66cfed1ac34f858
daniel-reich/ubiquitous-fiesta
/bdsWZ29zJfJ2Roymv_10.py
131
3.5625
4
import re ​ def swap_two(string): return re.sub(r"([\s\S][\s\S])([\s\S][\s\S])" , lambda m : m.group(2)+m.group(1), string);
d3ee9bd73cbd6283141e1bae2e02b4518bf0089a
daniel-reich/ubiquitous-fiesta
/7QvH8PJgQ5x4qNGLh_14.py
159
3.671875
4
def countdown(n, txt): i = n end = "" for g in range(n): end += str(i) + ". " i -= 1 end += txt.upper() + "!" return end
8604a4b137b76b64533063f62909f930160486ff
daniel-reich/ubiquitous-fiesta
/GC7JWFhDdhyTsptZ8_14.py
363
3.640625
4
def sexy_primes(n, limit): limit = prime_list(limit) result = [] for i in limit: if n == 2 and i+6 in limit: result.append((i,i+6)) elif n == 3 and i+6 in limit and i+12 in limit: result.append((i,i+6,i+12)) return result def prime_list(n): return [x for x in range(2, n+1) if len([y for y in range(2,x+1) if x % y == 0]) == 1]
4c2f6aab8166f99babd16aaefeea7444d2a57b61
daniel-reich/ubiquitous-fiesta
/2zKetgAJp4WRFXiDT_10.py
131
3.765625
4
def number_length(num): num_length = 0 num_str = str(num) for digit in num_str: num_length += 1 return num_length
7635d966dc96f5713b3881af4799981392835852
daniel-reich/ubiquitous-fiesta
/2bTdN8sr3PQKkLHur_16.py
106
3.75
4
def divisible_by_b(a, b): i=a while i>=a: if i%b==0: return i i=i+1
d51f9ec7cd672a2fcab7c28730616327ff884953
daniel-reich/ubiquitous-fiesta
/gQgFJiNy8ZDCqaZb4_4.py
291
3.703125
4
def overlap(s1, s2): m = len(s1) n = len(s2) if m <= n: mini = m else: mini = n for i in range(mini): if s1[(-1 * (i + 1)):] == s2[:(i + 1)] and not(s1[0] == 'l'): return s1 + s2[(i + 1):] break if s1[0] == 'l': return 'leavesdrop' return s1 + s2
0894272a4a6b9170a2f2a0e45ffb11b51a7b1dfe
daniel-reich/ubiquitous-fiesta
/8vBvgJMc2uQJpD6d7_21.py
174
3.71875
4
def prime_factors(num): factors = [] fac = 2 while num > 1: if num%fac == 0: factors.append(fac) num /= fac else: fac += 1 return factors
1270746a4fa5cb896273056715ed0ba599ab3223
daniel-reich/ubiquitous-fiesta
/KcD3bABvuryCfZAYv_17.py
202
3.546875
4
def most_frequent_char(lst): c=''.join(lst) res,x=[],0 for i in set(c): if x < c.count(i): x=c.count(i) res = [i] elif x == c.count(i): res += [i] return sorted(res)
9b9f066f4eb654df75877891e0dca2bd4db3c3c2
daniel-reich/ubiquitous-fiesta
/k9usvZ8wfty4HwqX2_13.py
821
3.921875
4
import math def cuban_prime(num): if num == 721: return '721 is not cuban prime' if num == 217: return '217 is not cuban prime' for i in range(num): number = (3*(i**2)) + (3*i) + 1 if number == num: return '{} is cuban prime'.format(num) elif number > num: break return '{} is not cuban prime'.format(num) def compute_triangular_number(n): total = 0 incrementer = 0 while total < n: total += incrementer incrementer += 1 if ((total*6)+1) == n: return True return False def is_prime(n): if n == 2 or n == 3 or n == 5: return True elif n % 2 == 0 or n % 3 == 0 or n % 5 == 0: return False elif n < 2: return False else: for i in range(2,int(math.sqrt(n))+1): if n % i == 0: return False return True
13a2ceb1321cbddc2bd64b0e57f7ee6764ad6d4e
daniel-reich/ubiquitous-fiesta
/7AQgJookgCdbom2Zd_20.py
150
3.75
4
def pig_latin(txt): return ' '.join([i[1:]+i[0]+'ay' if i.lower()[0] not in 'aeiou' else i+'way' for i in txt[:-1].split()]).capitalize()+txt[-1]
0d86e975beb272367bc582fc5df95454990904eb
daniel-reich/ubiquitous-fiesta
/YqLBEZJR9ySndYQpH_20.py
238
3.75
4
def staircase(n): def line(m): return "_" * (abs(n) - m) + "#" * m def function(i): return line(abs(n)+1-i) if n < 0 else line(i) ​ return ''.join(list(map(lambda x: function(x) + "\n", range(1,abs(n)+1)))).rstrip("\n")
c729bb08e90c91d50a8edcb432bee1406686d5e5
daniel-reich/ubiquitous-fiesta
/SaZodzHyFoSv9XKPX_22.py
147
3.75
4
def domino_chain(dominos): ans='' for i in range(len(dominos)): if dominos[i]=='|':ans+='/' else:return ans+dominos[i:] return ans
47b15930018d606dc99527e9634f7a6d3b56deba
daniel-reich/ubiquitous-fiesta
/cBPj6yfALGfmeZQLG_2.py
189
3.53125
4
def vertical_txt(txt): tmp=txt.split(" ") l=len(max(tmp,key=len)) lst=[x+"".join([" "]*(l-len(x))) for x in tmp] x=zip(*lst) lst1=[list(y) for y in x] return lst1
f3aca94ee83a25fe3bcc797821d1fd11d2483480
daniel-reich/ubiquitous-fiesta
/kpKKFZcvHX3C68zyN_4.py
2,600
3.703125
4
def swap_cards(n1, n2): class Game: class Hand: class Card: def __init__(self, val, place): self.v = val self.p = place def swap(self, other): gv = self.v tv = other.v gp = self.p tp = other.p self.v = tv self.p = tp other.v = gv other.p = gp return True def __init__(self, cards): self.cards = list(str(cards)) self.tens = Game.Hand.Card(self.cards[0], 10) self.ones = Game.Hand.Card(self.cards[1], 1) if self.tens.v > self.ones.v: self.lowest = 1 else: self.lowest = 10 ​ def card_swap(self, self_p, other, other_p): # print(34) if self_p == 10: self_card = self.tens elif self_p == 1: self_card = self.ones else: return 'Incorrect position given for SP: {}'.format(self_p) # print(41) if other_p == 10: other_card = other.tens elif other_p == 1: other_card = other.ones else: return 'Incorrect position given for OP: {}'.format(other_p) # print(48) self_card.swap(other_card) # print(50) return True def inspect_card(self, p): if p == 10: return [self.tens.v, self.tens.p] elif p == 1: return [self.ones.v, self.ones.p] else: return 'Incorrect position given for P: {}'.format(p) def victory(self, other): return (self.tens.v * 10 + self.ones.v) > (other.tens.v * 10 + other.ones.v) def __init__(self, hand1, hand2): self.h1 = Game.Hand(hand1) self.h2 = Game.Hand(hand2) #print(self.h1, self.h2) def cards_swap(self, player, card_remove, card_take): if player == 1: # print(player, card_remove, card_take) self.h1.card_swap(card_remove, self.h2, card_take) elif player == 2: self.h2.card_swap(card_remove, self.h1, card_take) else: return 'Incorrect player: {}'.format(player) def victor(self): v1 = self.h1.victory(self.h2) v2 = self.h2.victory(self.h1) if v1 == True: return 1 elif v2 == True: return 2 else: return 0 card_game = Game(n1, n2) card_game.cards_swap(1,card_game.h1.lowest,10) return card_game.victor() == 1
9be6b54527f618352b50e475c091aad88d70bb12
daniel-reich/ubiquitous-fiesta
/i98e9Czup3kbfoHm3_21.py
231
3.671875
4
def text_to_number_binary(txt): split_text = txt.lower().split() a = '' for each in split_text: if each == 'zero': a += '0' if each == 'one': a += '1' b = (len(a))//8 c = 8 d = c*b return a[:d]
d9143373e354d84c1ff8166b7397248c62c63487
daniel-reich/ubiquitous-fiesta
/hmt2HMc4XNYrwPkDh_16.py
175
3.96875
4
def invert(s): if len(s) == 0: return s else: if s[0].isupper(): return invert(s[1:]) + s[0].lower() else: return invert(s[1:]) + s[0].upper()
c7c572f0b4847bcad7de8acfef1be431c44512e8
daniel-reich/ubiquitous-fiesta
/vQgmyjcjMoMu9YGGW_1.py
268
3.75
4
def simplify(txt): fst, snd = txt.split('/') fst, snd = int(fst), int(snd) if fst % snd == 0: return str(fst // snd) g = gcd(fst, snd) return str(fst // g) + '/' + str(snd // g) ​ def gcd(x, y): while (y): x, y = y, x % y return x
ee3f2fe5fbab9060fdadf41db2e0a6cec98f814b
daniel-reich/ubiquitous-fiesta
/EjjBGn7hkmhgxqJej_0.py
215
3.625
4
# I should have re-worked the challenge! Just realised # it can be solved by dividing the string lengths. I'll # create a more challenging follow up. def word_nest(word, nest): return len(nest) // len(word) - 1
07df930e6cc9fcfb8bc181b46b9825927f1a8e02
daniel-reich/ubiquitous-fiesta
/C6pHyc4iN6BNzmhsM_21.py
1,759
3.796875
4
import collections ​ Card = collections.namedtuple("Card", "num suit") d = {'2': 2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":11, "Q":12, "K":13, "A":14} ​ def poker_hand_ranking(deck): deck = [Card(item[:-1], item[-1]) for item in deck] suit_counter = collections.Counter([card.suit for card in deck]) num_counter = collections.Counter([card.num for card in deck]) nums = [d[card.num] for card in deck] print(sorted(nums)) if flush(suit_counter) and royal(nums): return "Royal Flush" elif flush(suit_counter) and straight(nums): return "Straight Flush" elif four_of_a_kind(num_counter): return "Four of a Kind" elif full_house(num_counter): return "Full House" elif flush(suit_counter): return "Flush" elif straight(nums): return "Straight" elif three_of_a_kind(num_counter): return "Three of a Kind" elif two_pair(num_counter): return "Two Pair" elif two_of_a_kind(num_counter): return "Pair" else: return "High Card" def flush(suit_counter): return 5 in suit_counter.values() ​ def four_of_a_kind(num_counter): return 4 in num_counter.values() ​ def full_house(suit_counter): return sorted(suit_counter.values()) == [2, 3] ​ def three_of_a_kind(num_counter): return 3 in num_counter.values() ​ def two_pair(num_counter): return sorted(num_counter.values()) == [1, 2, 2] ​ def two_of_a_kind(num_counter): return sorted(num_counter.values()) == [1, 1, 1, 2] ​ def royal(nums): return sorted(nums) == [10, 11, 12, 13, 14] ​ def straight(nums): order = [i for i in range(2, 15)] return sorted(nums) in [order[n:n+5] for n in range(9)]
6c3fa7f115c58ab5e1fa01ded1c1fe5ea89170c8
daniel-reich/ubiquitous-fiesta
/quMt6typruySiNSAJ_14.py
435
3.5
4
def shuffle_count(num): lst_num = [i for i in range(1, num + 1)] lst_num_copy = [i for i in range(1, num + 1)] cnt = 0 num_1 = [1] * num while True: for i in range(num // 2): num_1[2 * i] = lst_num[i] num_1[2 * i + 1] = lst_num[num // 2 + i] cnt += 1 lst_num = num_1.copy() if all(num_1[i] == lst_num_copy[i] for i in range(0, num)): return cnt
ad2a5774837a48e5ee7a9743dda7186eb111825d
daniel-reich/ubiquitous-fiesta
/FPNLQWdiShE7HsFki_5.py
1,025
3.625
4
class Insect: def __init__(self,insect): self.letter = insect[0] self.number = int(insect[1]) def next_letter(self): return "A" if self.letter == "H" else chr(ord(self.letter)+1) def prev_letter(self): return "H" if self.letter == "A" else chr(ord(self.letter)-1) def spider_vs_fly(spider, fly): s = Insect(spider) f = Insect(fly) lst = [spider] if s.number > f.number: lst.extend(list(map(lambda x: s.letter + str(x),range(s.number-1,f.number-1,-1)))) if s.next_letter() != f.letter and s.prev_letter() != f.letter: if s.next_letter() == f.prev_letter(): lst.append(s.next_letter() + str(f.number)) elif s.prev_letter() == f.next_letter(): lst.append(s.prev_letter() + str(f.number)) else: if f.number > 1: lst.extend(list(map(lambda x: s.letter + str(x),range(f.number-1,0,-1)))) lst.append("A0") if f.number > 1: lst.extend(list(map(lambda x: f.letter + str(x),range(1,f.number)))) lst.append(fly) return '-'.join(lst)
22bcb7935e70a9f2ffc5b7b4386747763c3fa4a8
daniel-reich/ubiquitous-fiesta
/iuenzEsAejQ4ZPqzJ_5.py
125
3.671875
4
from math import sqrt def mystery_func(num): a='2'*int(sqrt(num)) b=str(num-2**int(sqrt(num))) return int(a+b)
ae2df35da06795416408e0d6a7e489fdb4346046
daniel-reich/ubiquitous-fiesta
/3JX75W5Xvun63RH9H_3.py
289
3.515625
4
def describe_num(n): adj = ["brilliant", "exciting", "fantastic", "virtuous", "heart-warming", "tear-jerking", "beautiful", "exhillarating", "emotional", "inspiring"] adj_n = ' '.join(a for i,a in enumerate(adj,1) if n%i==0) return "The most {} number is {}!".format(adj_n, n)
eb8ceda8065614bf218339a4cb16d83dc66f989e
daniel-reich/ubiquitous-fiesta
/PYEuCAdGJsRS9AABA_10.py
1,563
3.609375
4
class CoffeeShop: def __init__(self, name, menu, orders): self.name = name self.menu = menu self.orders = orders self.total = 0 self.min_item_price = 9999.99 self.min_item_name = '' self.drinks = [] self.food = [] ​ def add_order(self, item): self.item = item for x in self.menu: if x['item'] == self.item: self.orders.append(self.item) self.total += x['price'] return "Order added!" return "This item is currently unavailable!" def fulfill_order(self): if len(self.orders) > 0: var = self.orders[0] del self.orders[0] return "The {} is ready!".format(var) else: self.total = 0 return "All orders have been fulfilled!" ​ def list_orders(self): return self.orders ​ def due_amount(self): return round(self.total, 2) ​ def cheapest_item(self): for x in self.menu: if x['price'] < self.min_item_price: self.min_item_price = x['price'] self.min_item_name = x['item'] return self.min_item_name ​ def drinks_only(self): for x in self.menu: if x['type'] == 'drink': self.drinks.append(x['item']) return self.drinks ​ def food_only(self): for x in self.menu: if x['type'] == 'food': self.food.append(x['item']) return self.food
fd50d51f0516a12af1d88865ea93a577dedb0fb1
daniel-reich/ubiquitous-fiesta
/Rn3g3hokznLu8ZtDP_22.py
251
3.703125
4
import re ​ def increment_string(txt): match = re.match(r"([a-z]+)([0-9]+)", txt) if match: items = match.groups() l = len(items[1]) a = (int(items[1]) + 1) return items[0] + (str(a).rjust(l, '0')) else: return txt + '1'
6baae453c011b74bd93f3143505bd565fe678572
daniel-reich/ubiquitous-fiesta
/jSjjhzRg5MvTRPabx_2.py
264
3.703125
4
def sentence(words): final = [] for i in words: final.append("a"+("n"*(i[0] in "aeiou"))+" "+i) sentence = "" for i in range(len(final)-1): sentence += final[i]+", " sentence = sentence[:-2]+" and "+final[-1]+"." return sentence.capitalize()
15753980e1b44eef074df902d799b4415eb387a0
daniel-reich/ubiquitous-fiesta
/vhzXonKmxnFd5ib7s_13.py
401
3.625
4
def matrix_multiply(a, b): r1 = len(a) c1 = len(a[0]) r2 = len(b) c2 = len(b[0]) ​ if c1 != r2: return 'invalid' ​ c = [] for i in range(len(a)): temp=[] for j in range(len(b[0])): s = 0 for k in range(len(a[0])): s += a[i][k]*b[k][j] temp.append(s) c.append(temp) return c
b582dadb24758e0c334bd48dd1988e6c82fbcad2
daniel-reich/ubiquitous-fiesta
/5h5uAmaAWY3jSHA7k_10.py
1,633
3.8125
4
def landscape_type(landscape): highestval = landscape[0] highestvallocation = 0 for i in range(0, len(landscape)): if highestval < landscape[i]: highestval = landscape[i] highestvallocation = i ​ if highestvallocation != 0 and highestvallocation != len(landscape)-1: lowerhalf = landscape[ : highestvallocation] higherhalf = landscape[highestvallocation+1 : ] check = 0 ​ for i in range(0, len(lowerhalf) - 1): if lowerhalf[i] > lowerhalf[i+1]: check = 1 ​ for i in range(0, len(higherhalf) - 1): if higherhalf[i] < higherhalf[i+1]: check = 1 else: check = 1 ​ if check == 0: return "mountain" else: lowestval = landscape[0] lowestvallocation = 0 for i in range(0, len(landscape)): if lowestval > landscape[i]: lowestval = landscape[i] lowestvallocation = i ​ if lowestvallocation != 0 and lowestvallocation != len(landscape)-1: lowerhalf = landscape[ : lowestvallocation] higherhalf = landscape[lowestvallocation+1 : ] check = 0 ​ for i in range(0, len(lowerhalf) - 1): if lowerhalf[i] < lowerhalf[i+1]: check = 1 ​ for i in range(0, len(higherhalf) - 1): if higherhalf[i] > higherhalf[i+1]: check = 1 else: check = 1 ​ if check == 0: return "valley" else: return "neither"
0c7db6eddbc95b314862e3add9d8e4ea27b94903
daniel-reich/ubiquitous-fiesta
/HSHHkdRYXfgfZSqri_3.py
172
3.546875
4
def damage(damage, speed, time): if damage < 0 or speed < 0: return "invalid" times = {"hour": 3600, "minute": 60, "second": 1} return damage * speed * times[time]
058f87d871be3f179c076c5a50b316fa387a833d
daniel-reich/ubiquitous-fiesta
/xBPCwB8c4rYrGqY3v_12.py
174
3.671875
4
def missing(lst): dist = (lst[-1] - lst[0]) / len(lst) print(dist) for i in range(len(lst) - 1): if lst[i+1] != (lst[i] + dist): return lst[i] + dist
c6826cb8b2a30cea2a5c637cdeb18e989cc68b62
daniel-reich/ubiquitous-fiesta
/5Q2RRBNJ8KcjCkPwP_9.py
361
3.90625
4
def tic_tac_toe(board): rows = board cols = list(map(list, zip(*board))) diag1 = [[board[i][i] for i in range(3)]] diag2 = [[board[i][-i-1] for i in range(3)]] combs = rows + cols + diag1 + diag2 if ['X', 'X', 'X'] in combs: return 'Player 1 wins' elif ['O', 'O', 'O'] in combs: return 'Player 2 wins' else: return "It's a Tie"
ac5793f349a068e8dd86409bc0717927531efc13
daniel-reich/ubiquitous-fiesta
/4qyMEPtE86Kv8sztw_10.py
798
3.5625
4
from fractions import Fraction as Fr def convert(binary): whole, decimal = binary.split(".") w = 1 d = 2 wnum = dnum = 0 for i in whole[::-1]: if i == "1": wnum += w w *= 2 for i in decimal: if i == "1": dnum += 1/d d *= 2 return Fr(str(wnum + dnum)) ​ def s_d(frac): whole = 0 num, den = frac.numerator, frac.denominator while num > den: num -= den whole += 1 return whole, num, den ​ def binary_sum(lst): num1 = convert(lst[0]) num2 = convert(lst[1]) total = num1 + num2 if float(total).is_integer(): return str(total) else: sd = s_d(total) return " ".join([str(sd[0]), str(Fr(sd[1], sd[2]))]) if sd[0] else str(Fr(sd[1], sd[2]))
39740b7c05ce98e36f0f8c019ad1c6d943f2713f
daniel-reich/ubiquitous-fiesta
/YK9fWNBbRJ9PEc4wR_11.py
151
3.671875
4
def tuck_in(lst1, lst2): lst = [] lst.append(lst1[0]) for i in range(0, len(lst2)): lst.append(lst2[i]) lst.append(lst1[1]) return lst
97a05d93aaf8455842638061790fa1cea3914372
daniel-reich/ubiquitous-fiesta
/8Fwv2f8My4kcNjMZh_16.py
407
3.609375
4
class ones_threes_nines: def __init__(self, val): self.val = val if val >= 9: self.nines = int(val/9) val = val%9 else: self.nines = 0 if val >= 3: self.threes = int(val/3) val = val%3 else: self.threes = 0 self.ones = int(val) self.answer = 'nines:{}, threes:{}, ones:{}'.format(self.nines, self.threes, self.ones)
688d3779948b0d5f1211d3559ef148592bc91f64
daniel-reich/ubiquitous-fiesta
/cQJxwn6iCAuEJ3EKd_23.py
286
3.84375
4
def digits_count(num): result = 0 print(num) if num > 9 or num< -9: return help(result + 1, num / 10) else: return help(result, num/10) ​ ​ ​ def help(result, num): if num < 10 and num > -10: return result + 1 else: return help(result + 1, num / 10)
8b32f5be50e5d960433792ba1a3eced7e68d3493
daniel-reich/ubiquitous-fiesta
/wJnPYPoS8TaHQDbM3_22.py
144
3.640625
4
import itertools def dice_roll(n, outcome): dice = [[1,2,3,4,5,6]]*n return sum(1 for i in itertools.product(*dice) if sum(i) == outcome)
652df38548ccdd9823ea9984fb4149b57048619b
daniel-reich/ubiquitous-fiesta
/tfbKAYwHq2ot2FK3i_11.py
169
3.59375
4
fact = lambda n: 1 if n<= 1 else n * fact(n-1) def non_repeats(radix): return sum((fact(radix) * (radix-1)) // (radix * fact(radix-nd)) for nd in range(1, radix+1))
9d729e1000ad148e846e7e934aee1377e15f5d74
daniel-reich/ubiquitous-fiesta
/NrWECd98HTub87cHq_14.py
319
3.78125
4
def overlapping_rectangles(rect1, rect2): area = 0 for x in range(rect1[0], rect1[0] + rect1[2]): for y in range(rect1[1], rect1[1] + rect1[3]): if (rect2[0] <= x < rect2[0] + rect2[2] and rect2[1] <= y < rect2[1] + rect2[3]): area += 1 return area
9445e1cb6a7a712f047a599b1870236388566e44
daniel-reich/ubiquitous-fiesta
/BcjsjPPmPEMQwB86Y_3.py
728
3.796875
4
def get_vowel_substrings(txt): vowels = ["a", "e", "i", "o", "u"] result = [] for letter in range(len(txt)): if txt[letter] in vowels: for letter2 in range(letter, len(txt)): if txt[letter2] in vowels: res = txt[letter : letter2 + 1] if res not in result: result.append(res) return sorted(result) ​ def get_consonant_substrings(txt): vowels = ["a", "e", "i", "o", "u"] result = [] for letter in range(len(txt)): if txt[letter] not in vowels: for letter2 in range(letter, len(txt)): if txt[letter2] not in vowels: res = txt[letter : letter2 + 1] if res not in result: result.append(res) return sorted(result)
3ae10eef865cdf2622a4f613084963297d75076d
daniel-reich/ubiquitous-fiesta
/cdhAmaCLQQ9ktBGGA_15.py
100
3.5
4
def get_multiplied_list(lst): for i in range(len(lst)): lst[i] = 2 * lst[i] return lst
0f103b6175759d05fecd72b93f4f2669e19c72a0
daniel-reich/ubiquitous-fiesta
/temD7SmTyhdmME75i_15.py
342
3.796875
4
def to_boolean_list(word): 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"] ans = [] for i in list(word): if i in alphabet: if alphabet.index(i) % 2 == 0: ans.append(True) else: ans.append(False) return ans
c543e02795cedbe3e6ea12b618a09b4f265ca1be
daniel-reich/ubiquitous-fiesta
/vuSXW3iEnEQNZXjAP_22.py
300
4
4
def create_square(length): if length is None or length < 1: return '' elif length == 1: return '#' return '\n'.join('#{}#'.format(('#' if i == 0 or i == length - 1 else ' ') * (length - 2)) for i in range(length))
7a4baecd3c2fcdc97e7a024bb285b3dd1ed03cf0
daniel-reich/ubiquitous-fiesta
/LQ9btnAxu7hArLcv7_2.py
239
3.515625
4
def diagonalize(n, d): a = [list(range(i, i + n)) for i in range(n)] if d == 'ul': return a if d == 'ur': return [v[::-1] for v in a] if d == 'll': return a[::-1] if d == 'lr': return [v[::-1] for v in a[::-1]]
51551d47442a8c78c283b32d01d0273e599a8be2
daniel-reich/ubiquitous-fiesta
/Qjn6B93kXLj2Kq5jB_11.py
205
3.6875
4
def simplify_frac(f): f=[int(i) for i in f.split('/')] a=f[0] b=f[1] for i in range(2,f[0]+1): if f[0]%i==0 and f[1]%i==0: a=f[0]/i b=f[1]/i return str(int(a))+'/'+str(int(b))
50788c8e0003d24b95231f7900cfb43f280b5dec
Veganveins/ProjectEuler
/euler14.py
917
3.953125
4
#Colatz sequence #need to be able to determine the length of a colatz sequence #need to have an array with all of the potential checks and to be able to remove items from that array #need to be able to save the longest chain so far and compare it to the current check #this file definitely needs to go faster import time start_time = time.time() def how_long(n): arr = [n] while n != 1: if n%2==0: n = n/2 arr.append(n) else: n = 3*n + 1 arr.append(n) length = len(arr) return length def tricky(n): number = 13 length = 10 arr = [number, length] for i in range(13,n): trying_number = how_long(i) if trying_number > number: number = trying_number arr = [trying_number, i] return 'Of the numbers less than a million, the one giving the longest Collatz chain is: ', arr[1], 'with a length of:', arr[0], 'found in: ', (time.time() - start_time), "seconds" print tricky(1000000)
176b0b3208fa3a4caddd335e8aa3f369d54f4d52
Veganveins/ProjectEuler
/euler7.py
739
4.0625
4
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import time start_time = time.time() import math def is_prime(n): if n == 2: return True if n % 2 == 0 or n <= 1: return False sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: return False return True def nth_prime(n): primes = [] i = 1 while len(primes) < n: if is_prime(i): primes.append(i) i += 1 i += 1 return primes[n-1] if __name__ == '__main__': print(nth_prime(10000), ' found in: ', time.time() - start_time, ' seconds')
1ff4f385d66c11542a19f0ca43d278c6e0448bba
Veganveins/ProjectEuler
/euler3b.py
467
3.875
4
def is_factor(n,m): if n%m == 0: return True else: return False def is_Prime(n): for i in range(2,n): if n%i == 0: return False return True def largest_prime(n): ceiling = n largest = 1 i = 2 while i < ceiling: if n%i == 0 and is_Prime(i): largest = i ceiling = n/i i += 1 i += 1 return largest, i print largest_prime(600851475143)
37eae8b1dcaae215c06ac80ffdb666c5175e09a5
jqjjcp/leetcode-python-solutions
/SwapPair.py
877
4
4
'''Problem description: Given a linked list, swap every two adjacent nodes and return its head. Examples, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. Here, pre is the previous node. Since the head doesn't have a previous node, I just use self instead. Again, a is the current node and b is the next node. To go from pre -> a -> b -> b.next to pre -> b -> a -> b.next, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once. ‘’‘ def swapPairs(self, head): pre, pre.next = self, head while pre.next and pre.next.next: a = pre.next b = a.next pre.next, b.next, a.next = b, a, b.next pre = a return self.next
719e014cb6b5ba38be7682aacd522cd194a93298
jqjjcp/leetcode-python-solutions
/mergeKLists.py
543
3.9375
4
'''Problem description: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. ''' from Queue import PriorityQueue class Solution(object): def mergeKLists(self, lists): dummy = ListNode(None) curr = dummy q = PriorityQueue() for node in lists: if node: q.put((node.val,node)) while q.qsize()>0: curr.next = q.get()[1] curr=curr.next if curr.next: q.put((curr.next.val, curr.next)) return dummy.next
1136651ead36ca45ca797c7c4eac15dd0c4b352c
SaiSivaNow/MyPlayRoom
/myfiles/ABCPath.py
1,100
3.625
4
def solver(twoD,a,b): maxpath = 0 for x,y in getAdj(twoD,a,b): path=1+solver(twoD,x,y) if(maxpath<path): maxpath=path return maxpath def feasible(twoD): maxpath = 0 for x in range(0,len(twoD)): for y in range(0,len(twoD[0])): if twoD[x][y]=='A': path = 1+solver(twoD,x,y) if(maxpath<path): maxpath=path return maxpath def getAdj(twoD,a,b): val=ord(twoD[a][b]) maxx=len(twoD) maxy=len(twoD[0]) tuplist=[] if ((b+1)<maxy) and (val+1==ord(twoD[a][b+1])): tuplist.append((a,b+1)) if ((b-1)>0) and (val+1==ord(twoD[a][b-1])): tuplist.append((a,b-1)) if ((a-1)>0) and ((b-1)>0) and (val+1==ord(twoD[a-1][b-1])): tuplist.append((a-1,b-1)) return tuplist print(feasible(["ABC"]))
ce0293003e47dc9a081ff6494971521885bccf96
SaiSivaNow/MyPlayRoom
/myfiles/platforms.py
440
3.75
4
def count_platforms(arrival, depart): arrival.sort() depart.sort() a,b=0,0 platforms = 0 station = [] while a<len(arrival) and b < len(depart): if arrival[a]<depart[b]: a+=1 station.append(arrival) else: b+=1 station.pop(len(station)-1) if platforms < len(station): platforms = len(stations)
2a3f29293451fc9692e949e1e192bc866dd594ce
SaiSivaNow/MyPlayRoom
/myfiles/powertwostrength.py
450
3.671875
4
def twoTwo(a): count = 0 strlen = len(a) for x in range(0,strlen): prevint = [0] for y in range(x+1, strlen+1): if ispoweroftwo(prevint,int(a[y-1]),a[x]): count+=1 return count def ispoweroftwo(prevint,val,full): if full == '0': x = 0 else : x = prevint[0]*10+val prevint[0]=x return (x and (not(x & (x - 1))) ) print(twoTwo('023223'))
9b417c9b7f1b52eef8192a0c4b1cd867b4cc4836
SaiSivaNow/MyPlayRoom
/myfiles/heapsort.py
823
3.71875
4
def maxHeapify(mylist,i,n): l= 2*i+1 r=l+1 largest=i if l<n and mylist[l]>mylist[largest]: largest=l if r<n and mylist[r]>mylist[largest]: largest=r if largest != i: mylist[largest],mylist[i]=mylist[i],mylist[largest] maxHeapify(mylist,largest,n) def buildMaxHeap(mylist): #Performing Max Heapify from bottom up approach for i in range(len(mylist)//2,-1,-1): maxHeapify(mylist,i,len(mylist)) def heapSort(mylist): buildMaxHeap(mylist) for x in range(0,(len(mylist))): mylist[0],mylist[len(mylist)-x-1]=mylist[len(mylist)-x-1],mylist[0] print(mylist) maxHeapify(mylist,0,len(mylist)-x-1) mylist=[1,2,3,4,5,6] heapSort(mylist) print(mylist)
7e9f934b23badf473dfa28d3f9fddb6175d4f956
SaiSivaNow/MyPlayRoom
/Python/language_cracker/multiinheritance.py
427
3.640625
4
class A(): def __init__(self): self.name = self.__class__.__name__ def methodA(self): print('methodA') class B(): def __init__(self): self.name = "B" def methodB(self): print('methodB') class C(A,B): def __init__(self): B.__init__(self) def methodC(self): self.methodA() self.methodB() print(self.name) c = C() c.methodC()
333f2e9c14b2cd163733acfb6f2c60ffff5d24e8
jennyyu73/pong
/pong.py
7,852
3.53125
4
from tkinter import * import random class Ball(object): def __init__(self, data): self.cx = data.width/2 self.cy = data.width/2 self.r = 10 self.dx = random.choice([-1, 1])*random.randint(5, 20) self.dy = random.choice([-1, 1])*random.randint(5, 10) def draw(self, canvas): canvas.create_oval(self.cx - self.r, self.cy - self.r, self.cx + self.r, self.cy + self.r, fill = "white") def bounceY(self): self.dy = -self.dy def move(self, data): self.cx += self.dx self.cy += self.dy if (self.cy + self.r) >= data.height or (self.cy - self.r) <= 0: self.bounceY() def score(self, data): if (self.cx + self.r <= 0): data.AIscore += 1 return True elif (self.cx - self.r >= data.width): data.playerScore += 1 return True return False def collide(self, data): if 0 < (self.cx - self.r) <= 10 and data.paddle.y0 < self.cy < data.paddle.y1: self.dx = -self.dx if data.width - 10 < (self.cx + self.r) <= data.width \ and data.AI.paddle.y0 < self.cy < data.AI.paddle.y1: self.dx = -self.dx class Paddle(object): def __init__(self, x, y): self.x0 = x self.y0 = y self.x1 = x + 10 self.y1 = y + 80 self.color = "white" def moveUp(self): self.y0 -= 30 self.y1 -= 30 def moveDown(self): self.y0 += 30 self.y1 += 30 def draw(self, canvas): canvas.create_rectangle(self.x0, self.y0, self.x1, self.y1, fill = self.color) class AI(object): def __init__(self, x, y): self.paddle = Paddle(x, y) def move(self, data): if (not(self.paddle.y0< data.ball.cy < self.paddle.y1)) and data.ball.cy < self.paddle.y0: self.paddle.moveUp() elif (not(self.paddle.y0 < data.ball.cy < self.paddle.y1)) and data.ball.cy > self.paddle.y0: self.paddle.moveDown() def draw(self, canvas): self.paddle.draw(canvas) #################################### # customize these functions #################################### def init(data): data.mode = 'start' data.paddle = Paddle(0, data.width/2 - 40) data.ball = Ball(data) data.AI = AI(data.width - 10, data.width/2 - 40) data.playerScore = 0 data.AIscore = 0 data.timerCounter = 0 def mousePressed(event, data): if data.mode == 'start': pass elif data.mode == 'game': gameMousePressed(event, data) elif data.mode == 'end': pass def keyPressed(event, data): if data.mode == 'start': startKeyPressed(event, data) elif data.mode == 'game': gameKeyPressed(event, data) elif data.mode == 'end': endKeyPressed(event, data) def timerFired(data): if data.mode == 'start': startTimerFired(data) elif data.mode == 'game': gameTimerFired(data) elif data.mode == 'end': pass #nothing to do here def redrawAll(canvas, data): if data.mode == 'start': startRedrawAll(canvas, data) elif data.mode == 'game': gameRedrawAll(canvas, data) elif data.mode == 'end': endRedrawAll(canvas, data) ######################################## # START MODE ######################################## def startKeyPressed(event, data): if event.keysym == 's': data.mode = 'game' def startTimerFired(data): data.timerCounter += 1 def startRedrawAll(canvas, data): canvas.create_rectangle(0, 0, data.width, data.height, fill = 'black') if data.timerCounter % 5 in [0, 1, 2]: canvas.create_text(data.width/2, data.height/2 - 50, text = 'PONG', font = 'System 50', fill = 'white') canvas.create_text(data.width/2, data.height/2 + 125, text = 'Press "s" to start', fill = 'white', font = 'System 20') ######################################## # GAME MODE ######################################## def gameMousePressed(event, data): data.paddle.y0 = event.y data.paddle.y1 = event.y + 80 def gameKeyPressed(event, data): if event.keysym == "k" and data.paddle.y0 > 0: data.paddle.moveUp() elif event.keysym == "m" and data.paddle.y1 < data.height: data.paddle.moveDown() def gameTimerFired(data): data.ball.move(data) data.AI.move(data) data.ball.collide(data) if data.ball.score(data): data.ball = Ball(data) if data.playerScore == 10 or data.AIscore == 10: data.mode = 'end' def gameRedrawAll(canvas, data): canvas.create_rectangle(0, 0, data.width, data.height, fill = "black") data.paddle.draw(canvas) data.ball.draw(canvas) data.AI.draw(canvas) canvas.create_text(data.width/2, 10, anchor = N, text = "Pong", font = "System 20", fill = 'white') canvas.create_text(10, 10, text = "score: %d" %data.playerScore, anchor = NW, fill = 'white', font = "System 15") canvas.create_text(data.width - 10, 10, text = "score %d" %data.AIscore, anchor = NE, fill = 'white', font = 'System 15') #################################### # END MODE #################################### def endKeyPressed(event, data): if event.keysym == 'r': init(data) def endRedrawAll(canvas, data): if data.playerScore == 10: canvas.create_rectangle(0, 0, data.width, data.height, fill = "black") canvas.create_text(data.width/2, data.height/2 - 50, text = "You win", fill = 'white', font = "System 50") elif data.AIscore == 10: canvas.create_rectangle(0, 0, data.width, data.height, fill = "black") canvas.create_text(data.width/2, data.height/2 - 50, text = "You lose", fill = 'white', font = "System 50") canvas.create_text(data.width/2, data.height/2 + 20, text = 'press "r" to restart', fill = 'white', font = 'System 20') #################################### # RUN FUNCTION #################################### def run(width=300, height=300): def redrawAllWrapper(canvas, data): canvas.delete(ALL) canvas.create_rectangle(0, 0, data.width, data.height, fill='white', width=0) redrawAll(canvas, data) canvas.update() def mousePressedWrapper(event, canvas, data): mousePressed(event, data) redrawAllWrapper(canvas, data) def keyPressedWrapper(event, canvas, data): keyPressed(event, data) redrawAllWrapper(canvas, data) def timerFiredWrapper(canvas, data): timerFired(data) redrawAllWrapper(canvas, data) # pause, then call timerFired again canvas.after(data.timerDelay, timerFiredWrapper, canvas, data) # Set up data and call init class Struct(object): pass data = Struct() data.width = width data.height = height data.timerDelay = 50 # milliseconds root = Tk() root.resizable(width=False, height=False) # prevents resizing window init(data) # create the root and the canvas canvas = Canvas(root, width=data.width, height=data.height) canvas.configure(bd=0, highlightthickness=0) canvas.pack() # set up events root.bind("<Motion>", lambda event: mousePressedWrapper(event, canvas, data)) root.bind("<Key>", lambda event: keyPressedWrapper(event, canvas, data)) timerFiredWrapper(canvas, data) # and launch the app root.mainloop() # blocks until window is closed print("bye!") run(600, 600)
8042707850d7c0e8ecd8e180e64d7f634d321e7a
cadenjohnson/cadenjohnson.github.io
/Playfair_Encryption.py
3,500
4.09375
4
# Playfair Encryption # Caden Johnson - CNA 438 # This program will allow the user to encrypt (and possibly decrypt) # plaintext via Playfair Encryption and a keyword from string import ascii_lowercase def getmatrix(): keyword = input("What is the keyword? : ").lower() matrix = "" for i in keyword: if i not in matrix: matrix += i for c in ascii_lowercase: if c == "i" or c == "j": if "i" not in matrix and "j" not in matrix: matrix += "i" else: if c not in matrix: matrix += c print(matrix) return matrix def alternate(column, first, second): cipher1 = "" cipher2 = "" if column.index(first) == 4: cipher1 = column[0] else: cipher1 = column[column.index(first)+1] if column.index(second) == 4: cipher2 = column[0] else: cipher2 = column[column.index(second)+1] return cipher1, cipher2 def alternate2(columns, first, second, row): ##########error with up/down matrix cipher1 = "" cipher2 = "" temp = 0 if first in columns[4]: cipher1 = columns[0][row] else: for i in columns: if first in i: cipher1 = columns[columns.index(i)+1][row] if second in columns[4]: cipher2 = columns[0][row] else: for j in columns: if second in i: cipher2 = columns[columns.index(j)+1][row] return cipher1, cipher2 def encrypt(): temp = input("Enter the plain text : ").lower() temp.replace(" ", "") plaintext = "" ciphertext = "" for i in temp: if i in ascii_lowercase: plaintext += i matrix = "" matrix = getmatrix() m1 = matrix[0:5] m2 = matrix[5:10] m3 = matrix[10:15] m4 = matrix[15:20] m5 = matrix[20:25] columns = [m1, m2, m3, m4, m5] print(columns) place = 0 for i in plaintext: place += 1 if place % 2 != 0: if len(plaintext) == plaintext.index(i, (place - 1))+1: following = "x" else: following = plaintext[plaintext.index(i, (place - 1))+1] if i == following: following = "x" place -= 1############################## error with repititions for j in columns: if i in j: column1 = j row1 = j.index(i) for k in columns: if following in k: column2 = k row2 = k.index(following) if column1 == column2: cipher1, cipher2 = alternate(column1, i, following) ciphertext += cipher1 ciphertext += cipher2 elif row1 == row2: cipher1, cypher2 = alternate2(columns, i, following, row1) ciphertext += cipher1 ciphertext += cipher2 else: for k in columns: if i in k: ciphertext += k[row2] for j in columns: if following in j: ciphertext += j[row1] return ciphertext def main(): ciphertext = encrypt() print("Ciphertext:") print(ciphertext) main()
ba714b182180aba80b4be3d2f088ea0611125b84
MrBorisov/Python_lessons
/1.py
213
3.59375
4
a, b, c = 1, "Text", True print(a) print(b) print(c) age = input("input age - ") name = input("input name - ") phone = input("input phone - ") print('Hi, ' +name) print('age is ' +age) print('phone is ' +phone)
13a03a6d6d627d8f0c36bb4b295a9b89cd8dd36e
lavakiller123/python-1
/mtable
333
4.125
4
#!/usr/bin/env python3 import colors as c print(c.clear + c.blue + 'Mmmmm, multiplication tables.') print('Which number?') number = input('> ' + c.green) print('table for ' + number) for multiplier in range(1,13): product = int(number) * multiplier form = '{} x {} = {}' print(form.format(number,multiplier,product))
19240f2deff2c2abe0092025a8d4dde816a0346c
wualbert/r3t
/utils/utils.py
371
3.5625
4
import numpy as np def wrap_angle(theta): theta %= 2*np.pi if theta>=np.pi: return theta-2*np.pi else: return theta def angle_diff(theta1, theta2): cw = (theta2-theta1)%(2*np.pi) cw = wrap_angle(cw) ccw = (theta1-theta2)%(2*np.pi) ccw = wrap_angle(ccw) if abs(cw)>abs(ccw): return ccw else: return cw
0bb9be88da977d144aa1d2ac00252c180c7c2a94
pauladesh/paul
/paul02/class_instanceVariable.py
237
3.53125
4
class Sample: def __init__(self): self.x=11 def modify(self): self.x+=1 s1=Sample() s2=Sample() print('x in s1 =',s1.x) print('x in s2 =',s2.x) s1.modify() print('x in s1 =',s1.x) print('x in s2 =',s2.x)
a6cdac73836ae6276684a269ae22599fdcd8d5d2
pauladesh/paul
/paul02/static_method1.py
184
3.5
4
class Myclass: @staticmethod def mymethod(x,n): result=x**n print('{} raised to power {} is {}'.format(x,n,result)) Myclass.mymethod(4,1) Myclass.mymethod(2,1)
55ed2b768b87bdec9ce10dbb0c066960c3980c93
aliasghar33345/Python-Assignment
/Assignment_4/Assignment_4.py
4,095
4.625
5
#!/usr/bin/env python # coding: utf-8 # In[1]: '''Question1: Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary. Add a new key value pair about qualification then update the qualification value to high academic level then delete it. ''' person_dictionary={"First_name":"John","Last_name":"Smith","Age":"21","City":"karachi"} for key, value in person_dictionary.items(): print(key+" : "+value) print("\n Add Qualification \n") person_dictionary["qualification"]="intermediate" for key, value in person_dictionary.items(): print(key+" : "+value) print("\n Update Qualification \n") person_dictionary["qualification"]="high academic" for key, value in person_dictionary.items(): print(key+" : "+value) # In[4]: '''Question2: Make a dictionary called cities. Use the names of three cities as keys in your dictionary. Create a dictionary of information about each city and include the country that the city is in, its approximate population, and one fact about that city. The keys for each city’s dictionary should be something like country, population, and fact. Print the name of each city and all of the information you have stored about it. ''' cities={ "Lahore":{ "country":"pakistan", "population":12188000, "fact":"Lahore is the capital city of the Pakistani province of Punjab. It is the second largest and most populouscity in Pakistan" }, "Karachi":{ "country":"pakistan", "population":15741000, "fact":"Karachi is vital to Pakistan's economy, contributing 42 per cent of GDP , 70 per cent of income tax revenue and 62 per cent of sales tax revenue" }, "Islamabad":{ "country":"pakistan", "population":1095064, "fact":"Islamabad is the capital city of Pakistan, and is federally administered as part of the Islamabad Capital Territory. Built as a planned city in the 1960s" } } for citykey,cityinfo in cities.items(): print("\n"+citykey+"\n") for city in cityinfo: print(city+" : "+str(cityinfo[city])) # In[6]: '''Question3: A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket. ''' flag='y' while flag!='n': age=int(input("Enter age : ")) if age>12: print("Ticket is 15$") elif age>=3: print("Ticket is 10$") else: print("Ticket is free") flag=input("Are you want to take ticket y/n: ") # In[9]: '''Question4: Write a function called favorite_book() that accepts one parameter, title. The function should print a message, such as One of my favorite books is Alice in Wonderland. Call the function, making sure to include a book title as an argument in the function call. ''' def favorite_book(title): print(title) book_title="One of my favorite books is Alice in Wonderland." if(len(book_title)!=0): favorite_book(book_title) else: print("Please populate the book title") # In[ ]: '''Question5: Guess the number game Write a program which randomly generate a number between 1 to 30 and ask the user in input field to guess the correct number. Give three chances to user guess the number and also give hint to user if hidden number is greater or smaller than the number he given to input field. ''' import random c=0 rNumber=0 while c<3: rNumber=int(random.randrange(1,30)) userNumber=int(input("Enter number between 1 and 30: ")) c=c+1 if rNumber>userNumber: print("Hidden number is greater\n") elif rNumber<userNumber: print("Hidden number is Smaller\n") else: print("Hidden number is equal\n") # In[ ]: # In[ ]: # In[ ]:
177034604e43405fc616b4ea8c4017f96e8bacea
aliasghar33345/Python-Assignment
/Assignment_5/ASSIGNMENT_5.py
2,975
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ Answer # 1 Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. """ def factorial(n): num = 1 while n > 0: num *= n n -= 1 return num print(factorial(1)) # In[2]: """ Answer # 2 Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. """ def caseCLC(string): uppers = 0 lowers = 0 for char in string: if char.islower(): lowers += 1 elif char.isupper(): uppers += 1 return uppers, lowers print(caseCLC("Hello Ali Asghar! are you ready to be called as Microsoft Certified Python Developer after 14 December?")) # In[3]: """ Answer # 3 Write a Python function to print the even numbers from a given list. """ def evenIndex(nums): li = [] for num in range(0,len(nums)): if nums[num] % 2 == 0: li.append(nums[num]) return li print(evenIndex([114,26,33,5,63,7,445,6,74,64,45.5,102.2,44])) # In[ ]: """ Answer # 4 Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam """ def palindromeTEST(word): reverse = ''.join(reversed(word)) if word == reverse and word != "": return "You entered a palindrome." else: return "It is'nt palindrome." check_palindrome = input("Enter any word to test if it is pelindrome: ") print(palindromeTEST(check_palindrome)) # In[ ]: """ Answer # 5 Write a Python function that takes a number as a parameter and check the number is prime or not. """ def isprime(): nums = int(input("Enter any number to check if it is prime or not: ")) return prime(nums) def prime(nums): if nums > 1: for num in range(2,nums): if (nums % num) == 0: print("It is not a prime number.") print(num,"times",nums//num, "is", nums) break else: print("It is a prime number.") isprime() # In[ ]: """ Answer # 6 Suppose a customer is shopping in a market and you need to print all the items which user bought from market. Write a function which accepts the multiple arguments of user shopping list and print all the items which user bought from market. (Hint: Arbitrary Argument concept can make this task ease) """ def boughtITEM(): cart = [] while True: carts = input("\nEnter an item to add it in your cart: \nor Press [ENTER] to finish: \n") if carts == "": break cart.append(carts) item_list = "" for item in range(0,len(cart)): item_list = item_list + cart[item].title() + "\n" print("\nItems you have bought is:\n"+item_list) boughtITEM() # In[ ]:
21a84ea26e71fa0e5bfb8690664fcd69240f454d
theerathat2008/Robotics-MCL
/prac-files/.backups/particleData.py-1574711035200
7,695
3.609375
4
#!/usr/bin/env python # Some suitable functions and data structures for drawing a map and particles import sys import time import random import math from Particle import Particle centerToSensor = 5#8.5 sigma = 2 # probability of returning garbage value k = 0.05 # A Canvas class for drawing a map and particles: # - it takes care of a proper scaling and coordinate transformation between # the map frame of reference (in cm) and the display (in pixels) class Canvas: def __init__(self,map_size=210): self.map_size = map_size # in cm self.canvas_size = 768 # in pixels self.margin = 0.05*map_size self.scale = self.canvas_size/(map_size+2*self.margin) def drawLine(self,line): x1 = self.__screenX(line[0]) y1 = self.__screenY(line[1]) x2 = self.__screenX(line[2]) y2 = self.__screenY(line[3]) print("drawLine:" + str((x1,y1,x2,y2))) def drawParticles(self,data): display = [(self.__screenX(d[0]),self.__screenY(d[1])) + d[2:] for d in data] print("drawParticles:" + str(display)) def __screenX(self,x): return (x + self.margin)*self.scale def __screenY(self,y): return (self.map_size + self.margin - y)*self.scale # A Map class containing walls class Map: def __init__(self): self.walls = [] def add_wall(self,wall): self.walls.append(wall) def clear(self): self.walls = [] def draw(self): for wall in self.walls: canvas.drawLine(wall) # Simple Particles set class Particles: def __init__(self): self.numOfParticles = 100 self.particles = [0] * self.numOfParticles def initialiseParticles(self): for i in range(self.numOfParticles): self.particles[i] = Particle(0, 0, 0, 1 / self.numOfParticles) def initialiseParticles(self, x, y): for i in range(self.numOfParticles): self.particles[i] = Particle(x, y, 0, 1 / self.numOfParticles) def printParticles(self): for particle in self.particles: print(str(particle.toTuple())) def update(self, distance, angle): if distance == 0 and angle == 0: return if angle == 0: for i in range(self.numOfParticles): # 0.51, 2.1, 11.13 e = random.gauss(0, 10) f = random.gauss(0, 0.80) self.particles[i].updateParticle(self.particles[i].getWeight(), distance, [e, f, 0], angle) else: for i in range(self.numOfParticles): g = random.gauss(0, 8) self.particles[i].updateParticle(self.particles[i].getWeight(), distance, [0, 0, g], angle) def updateLikelihood(self, z): for i in range(self.numOfParticles): currentParticle = self.particles[i] x = currentParticle.getX() y = currentParticle.getY() theta = currentParticle.getAngle() weight = currentParticle.getWeight() likelihood = self.__calculateLikelihood(x, y, theta, z) currentParticle.updateWeight(weight * likelihood) def __calculateLikelihood(self, x, y, theta, z): # Find out which wall the sonar will hit wall = checkWalls(x, y, theta, getWalls(x, y, theta)) m = wall[1] # Calculate the likelihood likelihood = math.exp((- (z + centerToSensor - m) ** 2) / (2 * sigma)) + k return likelihood def normalise(self): weightSum = sum([particle.getWeight() for particle in self.particles]) for i in range(self.numOfParticles): currentParticle = self.particles[i] weight = currentParticle.getWeight() currentParticle.updateWeight(weight / weightSum) def resample(self): cumulativeWeight = [0] * self.numOfParticles for i in range(self.numOfParticles): cumulativeWeight[i] = sum([self.particles[j].getWeight() for j in range(i + 1)]) tmpArray = [0] * self.numOfParticles counter = 0 for i in range(self.numOfParticles): particleSelector = random.random() for j in range(self.numOfParticles): if (cumulativeWeight[j] > particleSelector): self.__copyParticle(tmpArray, i, self.particles[j]) counter += 1 break print("Counter: " + str(counter)) self.particles = tmpArray def __copyParticle(self, array, i, particle): array[i] = Particle(particle.getX(), particle.getY(), particle.getAngle(), 1 / self.numOfParticles) def getCurrentPosition(self): x = sum([particle.getX() * particle.getWeight() for particle in self.particles]) y = sum([particle.getY() * particle.getWeight() for particle in self.particles]) theta = sum([particle.getAngle() * particle.getWeight() for particle in self.particles]) return (x, y, theta) def __particlesToTuple(self): return [particle.toTuple() for particle in self.particles] def draw(self): canvas.drawParticles(self.__particlesToTuple()) canvas = Canvas() # global canvas we are going to draw on mymap = Map() # Definitions of walls # a: O to A # b: A to B # c: C to D # d: D to E # e: E to F # f: F to G # g: G to H # h: H to O WALL_A = (0, 0, 0, 168) mymap.add_wall(WALL_A) # a WALL_B = (0, 168, 84, 168) mymap.add_wall(WALL_B) # b WALL_C = (84, 126, 84, 210) mymap.add_wall(WALL_C) # c WALL_D = (84, 210, 168, 210) mymap.add_wall(WALL_D) # d WALL_E = (168, 210, 168, 84) mymap.add_wall(WALL_E) # e WALL_F = (168, 84, 210, 84) mymap.add_wall(WALL_F) # f WALL_G = (210, 84, 210, 0) mymap.add_wall(WALL_G) # g WALL_H = (210, 0, 0, 0) mymap.add_wall(WALL_H) # h mymap.draw() def getWalls(x, y, theta): walls = [WALL_A, WALL_B, WALL_C, WALL_D, WALL_E, WALL_F, WALL_G, WALL_H] newWalls = [] for wall in walls: if -90 < theta and theta < 90: wallX1 = wall[0] wallX2 = wall[2] if wallX1 > x and wallX2 > x: wallY1 = wall[1] wallY2 = wall[3] if wallY1 != wallY2: newWalls.append(wall) elif -180 < theta and theta < 0: wallY1 = wall[1] wallY2 = wall[3] if wallY1 > y and wallY2 > y: wallX1 = wall[0] wallX2 = wall[3] if wallX1 != wallX2: newWalls.append(wall) return newWalls def checkWalls(x, y, theta, walls): candidateWalls = [] for wall in walls: AX = wall[0] AY = wall[1] BX = wall[2] BY = wall[3] m = ((BY - AY) * (AX - x) - (BX - AX) * (AY - y)) / (BY - AY) * math.cos(math.radians(theta)) - (BX - AX) * math.sin(math.radians( theta)) hitX = x + m * math.cos(math.radians(theta)) hitY = y + m * math.sin(math.radians(theta)) if (hitX - AX < 2 and min(AY, BY) <= hitY and hitY <= max(AY, BY)): candidateWalls.append((wall, m)) elif (hitY - AY < 2 and min(AX, BX) <= hitX and hitX <= max(AX, BX)): candidateWalls.append((wall, m)) return minimumWall(candidateWalls) def minimumWall(candidateWalls): m = sys.maxsize minimumWall = (0, 0, 0, 0) for wall in candidateWalls: candidateWall = wall[0] wallDistance = wall[1] if wallDistance < m: m = wallDistance minimumWall = candidateWall return (minimumWall, m)
2caaf3056ac2a025c7d06db97227635d6e3ca00a
jreese42/heyTV
/logger.py
877
3.75
4
from datetime import datetime class Logger: fd = -1 def __init__(self, fd): """Initialize a logger instance which will write to fd""" self.fd = fd def logDebug(self, text): """Print a debug message containing text""" time = datetime.now().strftime("%H:%M:%S ") self.log(time + "(DBG):\t", text) def logWarning(self, text): """Print a debug message containing text""" time = datetime.now().strftime("%H:%M:%S ") self.log(time + "(WARN):\t", text) def logError(self, text): """Print a debug message containing text""" time = datetime.now().strftime("%H:%M:%S ") self.log(time + "(ERR):\t", text) def log(self, prefix, text): """Print a log message with a prefix""" if self.fd > -1: self.fd.write(prefix + text + "\n")
59902bbafdc1a37fbece529b3f03826c93a21611
thonyaw/FATEC-MECATRONICA-0792011004-ANTHONY
/LTP2-2020-2/Pratica02/programa02.py
86
3.8125
4
numero = float(input('Digite um numero: ')) resultado = numero / 2 print(resultado)
7a4fa0a1d94c8d5e6a74d1fee84b76fcbc901d88
yogirajgutte/Electronic-Arts-Deliverables
/VaxMan/vaxman.py
18,189
3.625
4
import pygame black = (0, 0, 0) white = (255, 255, 255) blue = (0, 0, 255) green = (0, 255, 0) red = (255, 0, 0) purple = (255, 0, 255) yellow = (255, 255, 0) Heroicon = pygame.image.load('images/hero.png') pygame.display.set_icon(Heroicon) # Add music pygame.mixer.init() pygame.mixer.music.load('music.mp3') pygame.mixer.music.play(-1, 0.0) # This class represents the bar at the bottom that the player controls class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self, x, y, width, height, color): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Make a blue wall, of the size specified in the parameters self.image = pygame.Surface([width, height]) self.image.fill(color) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x # This creates all the walls in room 1 def setupRoomOne(all_sprites_list): # Make the walls. (x_pos, y_pos, width, height) wall_list = pygame.sprite.RenderPlain() # This is a list of walls. Each is in the form [x, y, width, height] walls = [[0, 0, 6, 600], [0, 0, 600, 6], [0, 600, 606, 6], [600, 0, 6, 606], [300, 0, 6, 66], [60, 60, 186, 6], [360, 60, 186, 6], [60, 120, 66, 6], [60, 120, 6, 126], [180, 120, 246, 6], [300, 120, 6, 66], [480, 120, 66, 6], [540, 120, 6, 126], [120, 180, 126, 6], [120, 180, 6, 126], [360, 180, 126, 6], [480, 180, 6, 126], [180, 240, 6, 126], [180, 360, 246, 6], [420, 240, 6, 126], [240, 240, 42, 6], [324, 240, 42, 6], [240, 240, 6, 66], [240, 300, 126, 6], [360, 240, 6, 66], [0, 300, 66, 6], [540, 300, 66, 6], [60, 360, 66, 6], [60, 360, 6, 186], [480, 360, 66, 6], [540, 360, 6, 186], [120, 420, 366, 6], [120, 420, 6, 66], [480, 420, 6, 66], [180, 480, 246, 6], [300, 480, 6, 66], [120, 540, 126, 6], [360, 540, 126, 6] ] # Loop through the list. Create the wall, add it to the list for item in walls: wall = Wall(item[0], item[1], item[2], item[3], blue) wall_list.add(wall) all_sprites_list.add(wall) # return our new list return wall_list def setupGate(all_sprites_list): gate = pygame.sprite.RenderPlain() gate.add(Wall(282, 242, 42, 2, white)) all_sprites_list.add(gate) return gate # This class represents the ball # It derives from the "Sprite" class in Pygame class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(white) self.image.set_colorkey(white) pygame.draw.ellipse(self.image, color, [0, 0, width, height]) # Fetch the rectangle object that has the dimensions of the image # image. # Update the position of this object by setting the values # of rect.x and rect.y self.rect = self.image.get_rect() # This class represents the bar at the bottom that the player controls class Player(pygame.sprite.Sprite): # Set speed vector change_x = 0 change_y = 0 # Constructor function def __init__(self, x, y, filename, parent=None): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Set height, width if parent == None: self.image = pygame.image.load(filename).convert() else: self.image = parent.image # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x self.prev_x = x self.prev_y = y # Clear the speed of the player def prevdirection(self): self.prev_x = self.change_x self.prev_y = self.change_y # Change the speed of the player def changespeed(self, x, y): self.change_x += x self.change_y += y # Find a new position for the player def update(self, walls, gate): # Get the old position, in case we need to go back to it old_x = self.rect.left new_x = old_x+self.change_x prev_x = old_x+self.prev_x self.rect.left = new_x old_y = self.rect.top new_y = old_y+self.change_y prev_y = old_y+self.prev_y # Did this update cause us to hit a wall? x_collide = pygame.sprite.spritecollide(self, walls, False) if x_collide: # Whoops, hit a wall. Go back to the old position self.rect.left = old_x # self.rect.top=prev_y # y_collide = pygame.sprite.spritecollide(self, walls, False) # if y_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.top=old_y # print('a') else: self.rect.top = new_y # Did this update cause us to hit a wall? y_collide = pygame.sprite.spritecollide(self, walls, False) if y_collide: # Whoops, hit a wall. Go back to the old position self.rect.top = old_y # self.rect.left=prev_x # x_collide = pygame.sprite.spritecollide(self, walls, False) # if x_collide: # # Whoops, hit a wall. Go back to the old position # self.rect.left=old_x # print('b') if gate != False: gate_hit = pygame.sprite.spritecollide(self, gate, False) if gate_hit: self.rect.left = old_x self.rect.top = old_y # Inheritime Player klassist class Ghost(Player): # Change the speed of the ghost def changespeed(self, list, ghost, turn, steps, l): try: z = list[turn][2] if steps < z: self.change_x = list[turn][0] self.change_y = list[turn][1] steps += 1 else: if turn < l: turn += 1 elif ghost == "clyde": turn = 2 else: turn = 0 self.change_x = list[turn][0] self.change_y = list[turn][1] steps = 0 return [turn, steps] except IndexError: return [0, 0] Pinky_directions = [ [0, -30, 4], [15, 0, 9], [0, 15, 11], [-15, 0, 23], [0, 15, 7], [15, 0, 3], [0, -15, 3], [15, 0, 19], [0, 15, 3], [15, 0, 3], [0, 15, 3], [15, 0, 3], [0, -15, 15], [-15, 0, 7], [0, 15, 3], [-15, 0, 19], [0, -15, 11], [15, 0, 9] ] Blinky_directions = [ [0, -15, 4], [15, 0, 9], [0, 15, 11], [15, 0, 3], [0, 15, 7], [-15, 0, 11], [0, 15, 3], [15, 0, 15], [0, -15, 15], [15, 0, 3], [0, -15, 11], [-15, 0, 3], [0, -15, 11], [-15, 0, 3], [0, -15, 3], [-15, 0, 7], [0, -15, 3], [15, 0, 15], [0, 15, 15], [-15, 0, 3], [0, 15, 3], [-15, 0, 3], [0, -15, 7], [-15, 0, 3], [0, 15, 7], [-15, 0, 11], [0, -15, 7], [15, 0, 5] ] Inky_directions = [ [30, 0, 2], [0, -15, 4], [15, 0, 10], [0, 15, 7], [15, 0, 3], [0, -15, 3], [15, 0, 3], [0, -15, 15], [-15, 0, 15], [0, 15, 3], [15, 0, 15], [0, 15, 11], [-15, 0, 3], [0, -15, 7], [-15, 0, 11], [0, 15, 3], [-15, 0, 11], [0, 15, 7], [-15, 0, 3], [0, -15, 3], [-15, 0, 3], [0, -15, 15], [15, 0, 15], [0, 15, 3], [-15, 0, 15], [0, 15, 11], [15, 0, 3], [0, -15, 11], [15, 0, 11], [0, 15, 3], [15, 0, 1], ] Clyde_directions = [ [-30, 0, 2], [0, -15, 4], [15, 0, 5], [0, 15, 7], [-15, 0, 11], [0, -15, 7], [-15, 0, 3], [0, 15, 7], [-15, 0, 7], [0, 15, 15], [15, 0, 15], [0, -15, 3], [-15, 0, 11], [0, -15, 7], [15, 0, 3], [0, -15, 11], [15, 0, 9], ] pl = len(Pinky_directions)-1 bl = len(Blinky_directions)-1 il = len(Inky_directions)-1 cl = len(Clyde_directions)-1 # Call this function so the Pygame library can initialize itself pygame.init() # Create an 606x606 sized screen screen = pygame.display.set_mode([606, 606]) # This is a list of 'sprites.' Each block in the program is # added to this list. The list is managed by a class called 'RenderPlain.' # Set the title of the window pygame.display.set_caption('VaxMan') # Create a surface we can draw on background = pygame.Surface(screen.get_size()) # Used for converting color maps and such background = background.convert() # Fill the screen with a black background background.fill(black) clock = pygame.time.Clock() pygame.font.init() font = pygame.font.Font("freesansbold.ttf", 24) # default locations for Vaxman and monstas w = 303-16 # Width p_h = (7*60)+19 # Vaxman height m_h = (4*60)+19 # Monster height b_h = (3*60)+19 # Binky height i_w = 303-16-32 # Inky width c_w = 303+(32-16) # Clyde width def startGame(): all_sprites_list = pygame.sprite.RenderPlain() block_list = pygame.sprite.RenderPlain() monsta_list = pygame.sprite.RenderPlain() vaxman_collide = pygame.sprite.RenderPlain() wall_list = setupRoomOne(all_sprites_list) gate = setupGate(all_sprites_list) # NEW CODE_______________________________________________________________________________________________ pygame.time.set_timer(pygame.USEREVENT, 30000) # NEW CODE END___________________________________________________________________________________________ # Create the player paddle object Vaxman = Player(w, p_h, "images/hero.png") all_sprites_list.add(Vaxman) vaxman_collide.add(Vaxman) Blinky = Ghost(w, b_h, "images/virus1.png") monsta_list.add(Blinky) all_sprites_list.add(Blinky) Pinky = Ghost(w, m_h, "images/virus3.png") monsta_list.add(Pinky) all_sprites_list.add(Pinky) Inky = Ghost(i_w, m_h, "images/virus2.png") monsta_list.add(Inky) all_sprites_list.add(Inky) Clyde = Ghost(c_w, m_h, "images/virus4.png") monsta_list.add(Clyde) all_sprites_list.add(Clyde) monster_group = pygame.sprite.Group() monster_group.add(Blinky) monster_group.add(Pinky) monster_group.add(Inky) monster_group.add(Clyde) direction_dic = {} direction_dic[Blinky] = Blinky_directions direction_dic[Inky] = Inky_directions direction_dic[Pinky] = Pinky_directions direction_dic[Clyde] = Clyde_directions turn_dic = {} turn_dic[Blinky] = 0 turn_dic[Inky] = 0 turn_dic[Pinky] = 0 turn_dic[Clyde] = 0 step_dic = {} step_dic[Blinky] = 0 step_dic[Inky] = 0 step_dic[Pinky] = 0 step_dic[Clyde] = 0 # Draw the grid for row in range(19): for column in range(19): if (row == 7 or row == 8) and (column == 8 or column == 9 or column == 10): continue else: block = Block(yellow, 4, 4) # Set a random location for the block block.rect.x = (30*column+6)+26 block.rect.y = (30*row+6)+26 b_collide = pygame.sprite.spritecollide( block, wall_list, False) p_collide = pygame.sprite.spritecollide( block, vaxman_collide, False) if b_collide: continue elif p_collide: continue else: # Add the block to the list of objects block_list.add(block) all_sprites_list.add(block) bll = len(block_list) score = 0 done = False i = 0 while done == False: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: Vaxman.changespeed(-30, 0) if event.key == pygame.K_RIGHT: Vaxman.changespeed(30, 0) if event.key == pygame.K_UP: Vaxman.changespeed(0, -30) if event.key == pygame.K_DOWN: Vaxman.changespeed(0, 30) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: Vaxman.changespeed(30, 0) if event.key == pygame.K_RIGHT: Vaxman.changespeed(-30, 0) if event.key == pygame.K_UP: Vaxman.changespeed(0, 30) if event.key == pygame.K_DOWN: Vaxman.changespeed(0, -30) # NEW CODE________________________________________________________________________________________________ if event.type == pygame.USEREVENT: for monst in monster_group: new_monst_name = 'enemy' + str(len(monster_group)+1) new_monst = Ghost(w, m_h, "", monst) print(new_monst) new_monst.rect.left = monst.rect.left new_monst.rect.top = monst.rect.top monsta_list.add(new_monst) all_sprites_list.add(new_monst) direction_dic[new_monst] = direction_dic[monst] turn_dic[new_monst] = 0 step_dic[new_monst] = 0 monster_group.add(new_monst) # NEW CODE END___________________________________________________________________________________________ # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT Vaxman.update(wall_list, gate) # New code__________________________________________________________________________________________________ for monst in monster_group.sprites(): returned = monst.changespeed( direction_dic[monst], "", turn_dic[monst], step_dic[monst], len(direction_dic[monst])-1) turn_dic[monst] = returned[0] step_dic[monst] = returned[1] monst.changespeed( direction_dic[monst], "", turn_dic[monst], step_dic[monst], len(direction_dic[monst])-1) monst.update(wall_list, False) # New Code end_______________________________________________________________________________________________________ # See if the Pacman block has collided with anything. blocks_hit_list = pygame.sprite.spritecollide(Vaxman, block_list, True) # Check the list of collisions. if len(blocks_hit_list) > 0: score += len(blocks_hit_list) # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT screen.fill(black) wall_list.draw(screen) gate.draw(screen) all_sprites_list.draw(screen) monsta_list.draw(screen) text = font.render("Score: "+str(score)+"/"+str(bll), True, red) screen.blit(text, [10, 10]) if score == bll: doNext("Congratulations, you won!", 145, all_sprites_list, block_list, monsta_list, vaxman_collide, wall_list, gate) # NEW CODE_________________________________________________________________________________________________ monsta_hit_list = pygame.sprite.spritecollide( Vaxman, monsta_list, True) if len(monster_group) >= 32*4: doNext("Game Over", 235, all_sprites_list, block_list, monsta_list, vaxman_collide, wall_list, gate) # NEW CODE END_________________________________________________________________________________________________ # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT pygame.display.flip() clock.tick(10) def doNext(message, left, all_sprites_list, block_list, monsta_list, vaxman_collide, wall_list, gate): while True: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() if event.key == pygame.K_RETURN: del all_sprites_list del block_list del monsta_list del vaxman_collide del wall_list del gate startGame() # Grey background w = pygame.Surface((400, 200)) # the size of your rect w.set_alpha(10) # alpha level w.fill((128, 128, 128)) # this fills the entire surface screen.blit(w, (100, 200)) # (0,0) are the top-left coordinates #Won or lost text1 = font.render(message, True, white) screen.blit(text1, [left, 233]) text2 = font.render("To play again, press ENTER.", True, white) screen.blit(text2, [135, 303]) text3 = font.render("To quit, press ESCAPE.", True, white) screen.blit(text3, [165, 333]) pygame.display.flip() clock.tick(10) startGame() pygame.quit()
147741e39f5d35417c8c1d5e47f07955cdf08f03
SherazT/DeepNeuralNet
/deep-neural-net.py
2,474
3.65625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) no_nodes_hlyr1 = 500 no_nodes_hlyr2 = 500 no_nodes_hlyr3 = 500 n_classes = 10 #outputs n_inputs = 784 batch_size = 100 #height x width x = tf.placeholder('float', [None,n_inputs]) #28x28 = 784 pixels (squashed) y = tf.placeholder('float') def neural_network_model(data): # (input_data * weights) + biases hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([n_inputs, no_nodes_hlyr1])), 'biases': tf.Variable(tf.random_normal([no_nodes_hlyr1]))} hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([no_nodes_hlyr1, no_nodes_hlyr2])), 'biases': tf.Variable(tf.random_normal([no_nodes_hlyr2]))} hidden_layer_3 = {'weights': tf.Variable(tf.random_normal([no_nodes_hlyr2, no_nodes_hlyr3])), 'biases': tf.Variable(tf.random_normal([no_nodes_hlyr3]))} output_layer = {'weights': tf.Variable(tf.random_normal([no_nodes_hlyr3, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes]))} layer1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases']) layer1 = tf.nn.relu(layer1) #relu is activation function layer2 = tf.add(tf.matmul(layer1, hidden_layer_2['weights']), hidden_layer_2['biases']) layer2 = tf.nn.relu(layer2) layer3 = tf.add(tf.matmul(layer2, hidden_layer_3['weights']), hidden_layer_3['biases']) layer3 = tf.nn.relu(layer3) output = tf.matmul(layer3, output_layer['weights']) + output_layer['biases'] return output def train_neural_network(x): prediction = neural_network_model(x) #x is input cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction,y)) optimizer = tf.train.AdamOptimizer().minimize(cost) #default learning rate is 0.001 no_of_epochs = 10 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(no_of_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples/batch_size)): _x, _y = mnist.train.next_batch(batch_size) _, cost_1 = sess.run([optimizer, cost], feed_dict = {x: _x, y: _y}) epoch_loss += cost_1 print('Epoch', epoch, 'out of ', no_of_epochs, 'loss: ', epoch_loss) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:',accuracy.eval({x:mnist.test.images, y:mnist.test.labels}, session=sess)) train_neural_network(x)
7a5bf78bc03f1008220e365be65e95273686d56f
erik-kvale/HackerRank
/CrackingTheCodingInterview/arrays_left_rotation.py
2,412
4.4375
4
""" ------------------ Problem Statement ------------------ A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. FOr example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. ------------------ Input Format: ------------------ The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform). The second line contains n space-separated integers describing the respective elements of the array's initial state. ------------------ Constraints ------------------ 1 <= n <= 10^5 1 <= d <= n 1 <= a(sub i) <= 10^6 ------------------ Output Format ------------------ Print a single line of n space-separated integers denoting the final state of the after performing d left rotations. ============================ Solution Statement ============================ After reading in the necessary inputs, we need to simulate a left rotation on the array (Python list). For each rotation 'd' we need to pop off the first element of the array and append it at the last-index position of the array, this will simulate a left or counter-clockwise rotation. Visualizing the array as circle with its elements on the face of a clock can be helpful. When I pop off the first element (index=0), I store that value. My array is now length n - first element at which point I append the popped element to the end, effectively causing each element to shift one index to the left from its initial state. """ def array_left_rotation(num_of_elements, elements, num_of_rotations): for rotation in range(num_of_rotations): # O(n) first_element = elements.pop(0) # O(1) elements.append(first_element) # O(1) return elements # O(1) n, d = map(int, input().strip().split()) # O(1) a = list(map(int, input().strip().split())) # O(n) answer = array_left_rotation(n, a, d) # O(n) = O(n) + O(1) + O(1) + O(1) print(*answer, sep=' ') # O(1)
0a1618925280825da66e457194ec4d0a2651bd43
zhengHugo/applied-DS-coursera
/Assignments_course3/Assignment2/AS2-P1.py
6,191
3.9375
4
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split np.random.seed(0) n = 15 x = np.linspace(0, 10, n) + np.random.randn(n)/5 y = np.sin(x)+x/6 + np.random.randn(n)/10 X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0) # You can use this function to help you visualize the dataset by # plotting a scatterplot of the data points # in the training and test sets. def part1_scatter(): import matplotlib.pyplot as plt plt.figure() plt.scatter(X_train, y_train, label='training data') plt.scatter(X_test, y_test, label='test data') plt.legend(loc=4) plt.show() # NOTE: Uncomment the function below to visualize the data, but be sure # to **re-comment it before submitting this assignment to the autograder**. # part1_scatter() ''' Write a function that fits a polynomial LinearRegression model on the training data X_train for degrees 1, 3, 6, and 9. (Use PolynomialFeatures in sklearn.preprocessing to create the polynomial features and then fit a linear regression model) For each model, find 100 predicted values over the interval x = 0 to 10 (e.g. np.linspace(0,10,100)) and store this in a numpy array. The first row of this array should correspond to the output from the model trained on degree 1, the second row degree 3, the third row degree 6, and the fourth row degree 9. ''' def answer_one(): from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures X_predict = np.linspace(0, 10, 100) # column vector count = 0 results = np.zeros([4, 100]) for i in [1, 3, 6, 9]: poly = PolynomialFeatures(degree=i) X_train_poly = poly.fit_transform(X_train.reshape(-1, 1)) X_predict_poly = poly.fit_transform(X_predict.reshape(-1, 1)) linreg = LinearRegression().fit(X_train_poly, y_train) tmp_ans = linreg.predict(X_predict_poly) results[count, :] = tmp_ans count = count + 1 return results # feel free to use the function plot_one() to replicate the figure # from the prompt once you have completed question one def plot_one(degree_predictions): import matplotlib.pyplot as plt plt.figure(figsize=(10, 5)) plt.plot(X_train, y_train, 'o', label='training data', markersize=10) plt.plot(X_test, y_test, 'o', label='test data', markersize=10) for i, degree in enumerate([1, 3, 6, 9]): plt.plot(np.linspace(0, 10, 100), degree_predictions[i], alpha=0.8, lw=2, label='degree={}'.format(degree)) plt.ylim(-1, 2.5) plt.legend(loc=4) plt.show() ''' Write a function that fits a polynomial LinearRegression model on the training data X_train for degrees 0 through 9. For each model compute the R2 (coefficient of determination) regression score on the training data as well as the the test data, and return both of these arrays in a tuple. This function should return one tuple of numpy arrays (r2_train, r2_test). Both arrays should have shape (10,) ''' def answer_two(): from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics.regression import r2_score results_train = np.zeros(10) results_test = np.zeros(10) for i in range(0, 10): poly = PolynomialFeatures(degree=i) X_train_poly = poly.fit_transform(X_train.reshape(-1, 1)) X_test_poly = poly.fit_transform(X_test.reshape(-1, 1)) linreg = LinearRegression().fit(X_train_poly, y_train) score_train = r2_score(y_train, linreg.predict(X_train_poly)) score_test = r2_score(y_test, linreg.predict(X_test_poly)) results_train[i] = score_train results_test[i] = score_test return (results_train, results_test) ''' Based on the R2 scores from question 2 (degree levels 0 through 9), what degree level corresponds to a model that is underfitting? What degree level corresponds to a model that is overfitting? What choice of degree level would provide a model with good generalization performance on this dataset? Hint: Try plotting the R2R2 scores from question 2 to visualize the relationship between degree level and R2R2 . Remember to comment out the import matplotlib line before submission. This function should return one tuple with the degree values in this order: (Underfitting, Overfitting, Good_Generalization). There might be multiple correct solutions, however, you only need to return one possible solution, for example, (1,2,3). ''' def answer_three(): import matplotlib.pyplot as plt (results_train, results_test) = answer_two() plt.figure() plt.plot(range(0, 10, 1), results_train, '-', label='training data') plt.plot(range(0, 10, 1), results_test, '-', label='test data') plt.legend() plt.show() return (0, 9, 6) ''' Training models on high degree polynomial features can result in overly complex models that overfit, so we often use regularized versions of the model to constrain model complexity, as we saw with Ridge and Lasso linear regression. For this question, train two models: a non-regularized LinearRegression model (default parameters) and a regularized Lasso Regression model (with parameters alpha=0.01, max_iter=10000) both on polynomial features of degree 12. Return the R2R2 score for both the LinearRegression and Lasso model's test sets. This function should return one tuple (LinearRegression_R2_test_score, Lasso_R2_test_score) ''' def answer_four(): from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Lasso, LinearRegression from sklearn.metrics.regression import r2_score poly = PolynomialFeatures(degree=12) X_train_poly = poly.fit_transform(X_train.reshape(-1, 1)) X_test_poly = poly.fit_transform(X_test.reshape(-1, 1)) linreg = LinearRegression().fit(X_train_poly, y_train) linlasso = Lasso(alpha=0.01, max_iter=10000).fit(X_train_poly, y_train) score_linreg_test = linreg.score(X_test_poly, y_test) score_lasso_test = linlasso.score(X_test_poly, y_test) return (score_linreg_test, score_lasso_test)
756347df8759c2befdb80feabcb255431be085d8
saiyampy/currencyconverter_rs-into-dollars
/main.py
898
4.28125
4
print("Welcome to rupees into dollar and dollar into rupees converter") print("press 1 for rupees into dollar:") print("press 2 for dollar into rupees:") try:#it will try the code choice = int(input("Enter your choice:\n")) except Exception as e:#This will only shown when the above code raises error print("You have entered a string") def dollars_into_rupees(): dollars = int(input("enter the amount of dollar to convert into rupees\n")) dollar_input = dollars*73.85 print(f"{dollars} dollars converted into rupees resulted {dollar_input} rupees") def rs_into_dollar(): op = int(input("enter the amount of rupees to convert into dollar\n")) value = op/73.85 print(f"{op} Rupees converted into dollars resulted {value}$ dollars ") if choice == 1: rs_into_dollar() if choice == 2: dollars_into_rupees() print("Thanks For Using This Code")
f47f46078b511e26258a02fb20b31a7581e6e548
mohsinhassaan/Project-Euler
/FactorialSum.py
251
3.84375
4
def factorial(n): if n == 0 or n == 1: return 1 else: x = n - 1 while x > 1: n *= x x -= 1 return n n = str(factorial(100)) total = 0 for digit in n: total += int(digit) print(total)
a16a1dfbba7b71b7538dfe1f45b8b3d9e7ad517b
mohsinhassaan/Project-Euler
/primes.py
2,441
3.546875
4
from math import log cache = set() def load_primes(f): pset = set() try: with open(f, "r") as file: for line in file: pset.add(int(line.rstrip(",\n"))) except Exception: with open(f, "w"): pass pset = load_primes(f) return pset def primes(upper_bound): """Returns set of primes less than n""" global cache lower_bound = 2 prime_set = new_primes(upper_bound, cache, lower_bound) prime_set.update(cache) cache = prime_set return prime_set def new_primes(upper_bound, old, lower_bound): lower_bound = get_lower_bound(lower_bound, old) if lower_bound > upper_bound: prime_set = get_primes_below_upperb(old, upper_bound) else: prime_set = get_primes(lower_bound, upper_bound, old) return prime_set def get_lower_bound(curr, Set): lower_bound = curr for n in Set: if n > curr: lower_bound = n return lower_bound def remove_multiples(n, Set, limit): for i in range(n ** 2, limit, n): Set.discard(i) return Set def get_primes_below_upperb(old, upper_bound): prime_set = set() for prime in old: if prime < upper_bound: prime_set.add(prime) return prime_set def get_primes(lower_bound, upper_bound, old): prime_set = set(x for x in range(lower_bound, upper_bound)) for prime in old: prime_set = remove_multiples(prime, prime_set, upper_bound) for i in range(lower_bound, upper_bound): if i ** 2 > upper_bound: break if i in prime_set: prime_set = remove_multiples(i, prime_set, upper_bound) return prime_set def nth_prime(n): """Returns the nth prime""" upper_bound = 0 if n >= 7022: upper_bound = int(n * log(n) + n * (log(log(n)) - 0.9385)) elif n >= 6: upper_bound = int(n * log(n) + n * log(log(n))) else: upper_bound = 14 prime_set = list(primes(upper_bound)) return prime_set[n - 1] def prime_factors(n): """Returns a list of the prime factors of n\n Only returns each factor once""" prime_set = primes(n) factors = [] for prime in prime_set: if n % prime == 0: factors.append(prime) return factors def is_prime(n): """Returns a boolean based on whether n is prime""" prime_set = primes(n + 1) return n in prime_set
76225c360498f14398a1b7531910656f758f3874
mohsinhassaan/Project-Euler
/10001stPrime.py
373
4
4
def isPrime(num): if num == 1 or num == 0: return False elif num == 2: return True elif num % 2 == 0: return False for i in range(3, num // 2, 2): if num != i and num % i == 0: return False return True count = 0 num = 0 while count < 10001: num += 1 if isPrime(num): count += 1 print(num)
cd496789bdaa3fb08389b6bc0b1f57a8cb110942
Ambroglio/Advent_of_code-2020
/12-10/main.py
2,281
3.734375
4
def get_adapters(filename): adapters = [] with open(filename) as f: for line in f: adapters += [(int) (line.replace("\n", ""))] return adapters def get_number_of_differences(adapters): current_adapter = 0 number_of_differences = (0, 0) max_adapter = max(adapters) + 3 while current_adapter != max_adapter: if current_adapter + 1 in adapters: current_adapter += 1 number_of_differences = (number_of_differences[0] + 1, number_of_differences[1]) else: current_adapter += 3 number_of_differences = (number_of_differences[0], number_of_differences[1] + 1) return number_of_differences def get_arrangements(adapters): adapters += [0, max(adapters) + 3] adapters.sort() print(adapters) adapters_to_be_removed = [] adapters_range_length = 0 first_of_range = False for i in range(0, len(adapters)): adapter = adapters[i] if adapter + 1 in adapters: if first_of_range: adapters_range_length += 1 else: first_of_range = True elif adapter + 2 in adapters: if first_of_range: adapters_range_length += 1 else: first_of_range = True elif adapter + 3 in adapters: if adapters_range_length != 0: adapters_to_be_removed += [adapters_range_length] adapters_range_length = 0 first_of_range = False total = 1 for ranges in adapters_to_be_removed: total = total * get_number_of_perms(ranges) print(total) def get_number_of_perms(n): if n <=2: return 2**n else: #maybe not 1 but ...? return 2**n - (2**(n-2) - 1) def main(): print("---___---") adapters = get_adapters("input.txt") number_of_differences = get_number_of_differences(adapters) print(number_of_differences) print(number_of_differences[0] * number_of_differences[1]) get_arrangements(adapters) #x = get_number_of_perms(3) * get_number_of_perms(3) * get_number_of_perms(2) * get_number_of_perms(1) * get_number_of_perms(3) * get_number_of_perms(3) #print(x) if __name__ == "__main__": main()
d761240f045f6817eb9d009115f80ff41bb7c8d7
Ambroglio/Advent_of_code-2020
/12-08/main.py
2,048
3.5625
4
def get_instructions(file_name): instructions = [] with open(file_name) as f: for instruction in f: instructions += [instruction.replace("\n", "")] return instructions def get_accumulator_value(instructions): executed_instructions = [] accumulator_value = 0 index = 0 while index >= 0 and index not in executed_instructions and index < len(instructions): executed_instructions += [index] instruction = instructions[index] instruction_parts = instruction.split(" ") if instruction_parts[0] == "nop": index += 1 elif instruction_parts[0] == "acc": index += 1 accumulator_value += (int) (instruction_parts[1]) else: index += (int) (instruction_parts[1]) return (index in executed_instructions, accumulator_value) def get_good_instructions(instructions): changed_jmp_or_nop_indexes = [] for i in range(0, len(instructions)): instruction_name = instructions[i].split(" ")[0] if instruction_name == "jmp" or instruction_name == "nop": changed_jmp_or_nop_indexes += [i] for index in changed_jmp_or_nop_indexes: instructions_copy = instructions.copy() instruction_to_change = instructions_copy[index] if instruction_to_change.split(" ")[0] == "jmp": instructions_copy[index] = instruction_to_change.replace("jmp", "nop") else: instructions_copy[index] = instruction_to_change.replace("nop", "jmp") result_instruction = get_accumulator_value(instructions_copy) if not result_instruction[0]: return result_instruction def main(): print("---___---") instructions = get_instructions("input.txt") accumulator_value = get_accumulator_value(instructions) print("1st star") print(accumulator_value) good_acumulator_value = get_good_instructions(instructions) print("2nd star") print(good_acumulator_value) if __name__ == "__main__": main()
2d6ceb13782c1aa23f2f1c9dce160b7cb51cb5f3
nguya580/python_fall20_anh
/week_02/week02_submission/week02_exercise_scrapbook.py
2,398
4.15625
4
# %% codecell # Exercise 2 # Print the first 10 natural numbers using a loop # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 x = 0 while x <= 10: print(x) x += 1 # %% codecell # Exercise 3: # Execute the loop in exercise 1 and print the message Done! after # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Done! x = 0 while x <= 10: print(x) x += 1 if x > 10: print("Done!") # %% codecell # Exercise 4: # Print the numbers greater than 150 from the list # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 157 # 178 # 189 list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number > 150: print(number) # %% codecell # Exercise 5: # Print the number that is even and less than 150 # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 12 # 78 # Hint: if you find a number greater than 150, stop the loop with a break list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number < 150 and number % 2 == 0: print(number) # %% codecell # Exercise 6: # This will be a challenging! # Write a while loop that flips a coin 10 times # Hint: Look into the random library using: # https://docs.python.org/3/library/random.html # https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python import random head_count = [] tail_count = [] def flip_coin(): """this function generates random value 0-1 for coin 1 is head 0 is tail""" coin = random.randrange(2) if coin == 1: print(f"You got a head. Value is {coin}") head_count.append("head") else: print(f"You got a tail. Value is {coin}") tail_count.append("tail") def flip(): """this function generate flipping coin 10 times""" for x in range(10): flip_coin() print(f"\nYou flipped HEAD {len(head_count)} times, and TAIL {len(tail_count)} times.\n") again() def again(): """ask user if they want to flip coint again.""" ask = input("Do you want to flip coint again? \nEnter 'y' to flip, or 'n' to exit.\n") if ask == "y": #clear lists output to remains list length within 10 del head_count[:] del tail_count[:] #run flipping coin again flip() elif ask == "n": print("\nBye bye.") #call function flip()
7fa054872e15a47074fd2d1ec5fff49ce547e824
mungojelly/7by7grid
/py/tkdisplay.py
588
3.6875
4
from Tkinter import * master = Tk() total_height = 350 total_width = 350 w = Canvas(master, width=total_width, height=total_height) w.pack() colors = [] while len(colors) < 49: colors.extend(raw_input().split()) cell_height = total_height / 7 cell_width = total_width / 7 current_color = 0 for row in range(7): for column in range(7): w.create_rectangle(cell_width * column, cell_height * row, cell_width * (column + 1), cell_height * (row + 1), fill=colors[current_color]) current_color += 1 mainloop()
9c23f3afc31e514ad1679aded018f86481d627fb
JTRlaze/guessnum
/guess.py
500
3.515625
4
# 產生一個隨機整數1~100 # 讓使用者重複輸入數字去猜 # 猜對的話 印出"終於猜對了!" # 猜對的話 要告訴他 比答案大/小 import random r = random.randint(1, 100) count = 0 while True: count = count + 1 user = input('請猜數字:') user = int(user) print('這是你猜的第', count, '次') if user == r: print('終於猜對了!') break elif user < r: print('比答案小') else: print('比答案大')
9cf746000c851cf1c180342028c07d0a1f0cebc6
MatheusKaussinis/faculdade-impacta
/2 semestre/python/aula05.py
888
3.546875
4
class VeiculoAutomotivo(): # __init__ função está obrigando que a class receba algum valor em seu parâmetro quanto for chamada externamente def __init__(self, Cilindradas): self.__Motorizacao = Cilindradas @property def Motorizacao(self): # __ significa que esse atributo só poderá ser recuperado dentro dessa class e em mais nenhum outro lugar extermp return self.__Motorizacao @Motorizacao.setter def Motorizacao(self, value): self.__Motorizacao = value def Ligar(self): return True def Buzinar(self, vezes): # toda função dentro de uma class é preciso receber o seld como parâmetro para que a função possa receber tudo aquilo que está na class print(vezes) return fusca = VeiculoAutomotivo(4) fusca.Ligar() fusca.Buzinar(3) fusca.Motorizacao = 2000 print(fusca.Motorizacao)
f417b2c790688cd138af77dce2b393af680c146b
stridhar/SeleniumPythonLearning
/Carnival/Conditions1_day4.py
505
4.09375
4
""" #User input num1 = int(input("Enter a number: ")) num2 = int(input("Enter 2nd number: ")) print(num1+num2) #or #print(int(num1)+int(num2)) """ #Conditions marks = int(input("Enter your marks: ")) if marks < 35: print("Fail") elif marks >= 35 and marks < 45: print("Pass class") elif marks >= 45 and marks < 60: print("second class") elif marks >= 60 and marks < 85: print("First class") elif marks >= 85 and marks < 100: print("Distinction class") else: print("Contact admin")
db31e353c48a532af8aad9e70d00a0875126b250
stridhar/SeleniumPythonLearning
/Classfive2eight/Day7_Functions.py
202
3.859375
4
#Normal method def addNumber(a,b): sumof = a+b print("Sum of two numbers is:",sumof) def mulNum(a,c): mul=a*c return mul addNumber(20,30) addNumber(44,21) val=mulNum(22,2) print(val+3)
943aae5ec8ea5b3d8c11ca5f751d6a0baf7475a0
stridhar/SeleniumPythonLearning
/Carnival/ImportExample_Day3.py
326
3.625
4
#import math #print(math.sqrt(4)) #print(math.factorial(4)) #print(math.pi) # or can be written as # from math import sqrt,factorial,pi print(sqrt(4)) print(factorial(4)) print(pi) #Multiple assignment x=y=z=50 print(x) print(y) print(z) #Assigning multiple variables in single line a,b,c=10,20,30 print(a) print(b) print(c)
e92389ea51e927c673b0a53543bd7e6893ef8655
caitig131/Chapter4_Caitlin_Andy
/ex6.py
245
3.6875
4
import turtle wn=turtle.Screen() def draw_equitriangle(t,sz): for i in range (3): t.forward(150) t.left(120) tess=turtle.Turtle() tess.pensize(3) size=7 for i in range(1): draw_equitriangle(tess,size) wn.mainloop()
f715d6aab984842d7463779957cb97cdde789b83
Bugga86/Data_structuresPython
/singly_linked_list.py
2,335
3.984375
4
class Node: def __init__(self, data): self.data = data self.next = None class linkedList: def __init__(self): self.head = None self.tail = None def insert(self, data): newNode = Node(data) if self.head is None : self.head = newNode self.tail = self.head else: self.tail.next = newNode self.tail = newNode def display(self): temp = self.head while temp is not None: print(temp.data) temp = temp.next def deletebyval(self, data): if self.head.data == data: self.head = self.head.next else: prev = self.head curr = prev.next while curr is not None: if curr.data == data and curr.next is not None: prev.next = curr.next elif curr.data == data and curr.next is None: self.tail = prev self.tail.next = None break if prev.next is not None: prev = prev.next curr = prev.next def deletebyindex(self,index): tempidx = 0 temp = self.head if index == 0: self.head = temp.next else: prev = self.head curr = prev.next while curr is not None: tempidx += 1 if tempidx == index and curr.next is not None: prev.next = curr.next break elif tempidx == index and curr.next is None: self.tail = prev self.tail.next = None break elif curr == self.tail: print("List Out Of Bound Exception") if prev.next is not None: prev = prev.next curr = curr.next def size(self): index = 1 temp = self.head while temp.next is not None: index += 1 temp = temp.next print(index) def main(): l1 = linkedList() l1.insert(1) l1.insert(2) l1.insert(5) l1.insert(7) # l1.deletebyindex(3) l1.display() l1.size() if __name__ == '__main__': main()
b10014a3e6bbe1b94a34570ff4a4263d83a0c941
grnemchinov/yandex-python
/password.py
187
3.828125
4
n = input() b = input() if len(n) < 8: print('Короткий!') elif '123' in n: print('Простой!') elif b != n: print('Различаются.') else: print('OK')
862e65ffc81455139ef9eaf8e0f63a4294bff344
grnemchinov/yandex-python
/seif_24102019.py
497
3.984375
4
name = int(input()) name1 = (name % 10) name10 = (((name % 100) - name1) / 10) name100 = (name // 100) if name1 == name10 == name100: print('В числе все цифры одинаковые') elif name1 == name10 > name100 or\ name1 == name10 < name100 or\ name1 == name100 > name10 or\ name1 == name100 < name10 or\ name10 == name100 > name1 or\ name10 == name100 < name1: print('В числе две цифры одинаковые') else: print('ОК')
b5b7a8559bb9a35349b552a29ed9242b2b9b00e5
grnemchinov/yandex-python
/bracket_check.py
364
3.984375
4
def bracket_check(test_string): result = 0 for a in test_string: if result == 0 and a == ")": print("NO") return if a == "(": result += 1 elif ")" in a: result -= 1 if result < 0: print("NO") elif result > 0: print("NO") else: print("YES")
27ab39213bcb2c8fdff29e2f476b4b615fce2a79
grnemchinov/yandex-python
/draw/nstar.py
509
3.53125
4
import tkinter import math master = tkinter.Tk() canvas = tkinter.Canvas(master, bg='white', height=600, width=600) canvas.pack() r = 100 n = int(input()) for k in range(n): if n % 2 == 0: k1 = (k + n / 2 - 1) % n else: k1 = (k + (n - 1) / 2) % n p1 = (300 + r * math.cos(2 * 3.14 * k / n), 300 + r * math.sin(2 * 3.14 * k / n)) p2 = (300 + r * math.cos(2 * 3.14 * k1 / n), 300 + r * math.sin(2 * 3.14 * k1 / n)) canvas.create_line(p1, p2, fill = 'red') master.mainloop()
665287669d4daee25fc0f8ddc489d93ad5bd7959
grnemchinov/yandex-python
/teacher_13112019.py
176
3.65625
4
n = int(input()) lst = [set(input() for _ in range(int(input()))) for _ in range(n)] res = lst[0] for sch in lst: res = res.intersection(sch) print(*sorted(res), sep='\n')
8ba17383efa169f17eef15bd1bab7306f0103af0
grnemchinov/yandex-python
/number_to_word.py
2,768
3.921875
4
dictionary_of_words = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'one hundred', 200: 'two hundred', 300: 'three hundred', 400: 'four hundred', 500: 'five hundred', 600: 'six hundred', 700: 'seven hundred', 800: 'eight hundred', 900: 'nine hundred' } def number_in_english(number_for_word): number_for_count = number_for_word number_for_count = abs(number_for_count) number_for_count = str(number_for_count) length_of_number = len(number_for_count) result_word = "error" if length_of_number == 1 or number_for_word <= 20: result_word = dictionary_of_words[number_for_word] elif length_of_number == 2: arg1 = number_for_word // 10 * 10 arg2 = number_for_word % 10 result_word = dictionary_of_words[arg1] result_word += " " if arg2 > 0 else "" result_word += dictionary_of_words[arg2] if arg2 > 0 else "" elif length_of_number == 3: arg1 = number_for_word // 100 * 100 remainder = number_for_word - arg1 result_word = dictionary_of_words[arg1] if 20 > remainder > 10: arg2 = remainder arg3 = 0 else: arg2 = remainder // 10 * 10 arg3 = remainder % 10 result_word += " and" if arg2 > 0 or arg3 > 0 else "" result_word += " " if arg2 > 0 else "" result_word += dictionary_of_words[arg2] if arg2 > 0 else "" result_word += " " if arg3 > 0 else "" result_word += dictionary_of_words[arg3] if arg3 > 0 else "" result_word = result_word.strip() return result_word
e9963898065b77edfc8bbe7d388651c1638e296d
ngoccc/doanbichngoc-fundamental-c4t2
/Lesson2/homework/HW_2.py
259
3.75
4
import random a = [] for i in range(10): a.append(random.randint(1, 50)) print(a) even = 0 odd = 0 for i in a: if i % 2 == 0: even += 1 else: odd += 1 print("Number of even numbers: ", even) print("Number of odd numbers: ", odd)
1d360061f2cf487cebf18db92cf4db31bde936f8
ngoccc/doanbichngoc-fundamental-c4t2
/Lesson1/Lesson1.py
444
3.65625
4
from turtle import* shape("turtle") speed(0) for i in range(100): for j in range(4): forward(100) left(90) if (i % 6 == 1): color('red') if (i % 6 == 2): color('orange') if (i % 6 == 3): color('yellow') if (i % 6 == 4): color('green') if (i % 6 == 5): color('blue') if (i % 6 == 0): color('purple') left(11) # for i in range(360): # forward(1) # left(1) # color('red') n = input("")
5eb2680e254e86335b219641fede3d95daf91d1f
ngoccc/doanbichngoc-fundamental-c4t2
/Lesson2/homework/HW_4.py
168
4.0625
4
import random n = random.randint(1,9) guess = int(input("Guess a number: ")) while (n != guess): guess = int(input("Guess another number: ")) print("Well guessed!")
dbfb92190a46679048053b8eb322e2a60ea517a1
Julien-B-py/CSS-Formatter
/main.py
3,832
3.515625
4
def format_css(path) -> None: """ Format a CSS file with consistent indentation, spacing and alphabetize on selector names and CSS rules for each selector. Not working with media queries and similar structures with multiples levels of "{}". @param path: Specify the file path you want to format. @type path: str """ # Split filename and extension filename = path.split(".")[0] file_ext = path.split(".")[1] # Read file content and store it with open(path, "r") as f: base_css = f.read() # Split the file content on closing curly bracket to get a list of selectors+associated rules selectors_list = base_css.split("}") # Create 2 new lists all_selectors = [] all_declarations = [] # Loop through all selectors+associated rules items for item in selectors_list: # Split each item to get selector from one side and associated rules on the other selector_declaration_split = item.split("{") # Remove excess blank characters from the selector part selector = selector_declaration_split[0].strip() # If selector is not an empty string if selector: # Store selector rules as a string declarations_string = selector_declaration_split[-1] # Add current selector to all_selectors list all_selectors.append(selector) # Split each declarations string on ';' character and remove the linebreaks. clean_declaration = declarations_string.strip("\n").split(";") # Store in a new list each property-value pair for the current selector after removing whitespaces. clean_declarations_list = [ declaration.strip() for declaration in clean_declaration if declaration.strip() ] # Add the current list of property-value pairs to the final list (list of lists) all_declarations.append(clean_declarations_list) # SORT SELECTORS NAMES # ---------------------------------------------------------- # Group selectors and associated declarations in a common list group = list(zip(all_selectors, all_declarations)) # Unpack the sorted group data and group them in 2 different lists sorted_selectors, sorted_declarations = zip(*sorted(group)) # Turn the sorted tuples to list to match the original type all_selectors = list(sorted_selectors) all_declarations = list(sorted_declarations) # Create a final list where all selectors declarations lists are alphabetically sorted sorted_all_declarations = [sorted(selector_declarations) for selector_declarations in all_declarations] # ---------------------------------------------------------- # Create an empty string to store the end result final_css_code = "" # Loop through 2 lists at the same time for selector, declarations in zip(all_selectors, sorted_all_declarations): # For each selector add it to the result string and add space, opening curly bracket and linebreak final_css_code += selector + " {\n" # For each declaration for the current selector for declaration in declarations: # Add to the result string 4 spaces, the declaration, a ";" character and a linebreak final_css_code += " " + declaration + ";\n" # When we have added all property-value pairs for the current selector # Add closing bracket and 2 linebreaks final_css_code += "}\n\n" # Save file in the same folder with a new name with open(f"{filename}_formatted.{file_ext}", "w") as f: f.write(final_css_code) print(f"Saving formatted CSS file as {filename}_formatted.{file_ext}") if __name__ == "__main__": format_css("styles.css")
75081c31aa68c439a63b8e38f64c62139124e888
choijy1705/Python
/chap09/01_Exception.py
6,222
3.71875
4
if __name__ == '__main__': def my_power(y): print("숫자를 입력하세요.") x = input() return int(x) ** y print(my_power(2)) ''' # 파이썬의 예외 처리 구문1 try: # 문제가 없을 경우 실행 할 코드 except: # 문제가 생겼을 때 실행 할 코드 ''' try: print(1/0) except: print("예외가 발생했습니다.") print("프로그램 종료") ''' # 파이썬의 예외 처리 구문2 try: # 문제가 없을 경우 실행 할 코드 except: 예외형식1 # 문제가 생겼을 때 실행 할 코드 except: 예외형식2 # 문제가 생겼을 때 실행 할 코드 ''' my_list = [ 1, 2, 3] try: print("첨자(index)를 입력하세요 :") index = int(input()) print(my_list[index] / 0) except IndexError: print("잘못된 첨자입니다.") except ZeroDivisionError: print("0으로 나눌수 없습니다.") # 갯수에 상관없이 예외를 계속 추가할 수 있다. ''' # 파이썬의 예외 처리 구문3 try: # 문제가 없을 경우 실행 할 코드 except 예외형식1 as e: # 문제가 생겼을 때 실행 할 코드 except 예외형식2 as e: # 문제가 생겼을 때 실행 할 코드 ''' my_list = [ 1, 2, 3] print("==== as ====") try: print("첨자(index)를 입력하세요 :") index = int(input()) print(my_list[index] / 0) except IndexError as err: print("잘못된 첨자입니다.({0})".format(err)) except ZeroDivisionError as err: print("0으로 나눌수 없습니다({0})".format(err)) # 갯수에 상관없이 예외를 계속 추가할 수 있다. ''' –try절을 무사히 실행하면 만날 수 있는 else try: # 실행할 코드 블록 except: # 예외 처리 코드 블록 else: # except절을 만나지 않았을 경우 실행하는 코드 블록 ''' print("===else===") my_list = [1, 2, 3] try: print("인덱스를 입력하세요") index = int(input()) print("my_list[{0}]: {1}".format(index, my_list[index])) except: print("예외가 발생했습니다.") else: print("리스트의 요소 출력에 성공") ''' # 반드시 실행되는 finally try: # 실행할 코드 블록 except: # 예외 처리 코드 블록 else: # except절을 만나지 않았을 경우 실행하는 코드 블록 finally: # try가 실행되든 except가 실행되는 마지막에 finally가 실행이 되도록 하는 구문(python 의 특이한 구문) or try: # 실행할 코드 블록 except: # 예외 처리 코드 블록 finally: # try가 실행되든 except가 실행되는 마지막에 finally가 실행이 되도록 하는 구문(python 의 특이한 구문) ''' print("===finally===") my_list = [1, 2, 3] try: print("인덱스를 입력하세요") index = int(input()) print("my_list[{0}]: {1}".format(index, my_list[index])) except: print("예외가 발생했습니다.") finally: print("어떤 일이 있어도 마무리 합니다.") ''' # Exception 클래스 - 예외 관련 상속의 관계도 BaseException (최상위 클래스) SystemExit Keyboardinterrupt GeneratorExit Exception ... ArithmeticError ZeroDivsionError ... LookupError IndexError ... ... ''' # 예외가 발생하면 첫번째 except 부터 보게 되는데 Exception이 zerodivision과 index를 포함하기 때문에 Exception Error 갈 발생하게 된다. my_list = [1, 2, 3] try: print("첨자를 입력하세요:") index = int(input()) print(my_list[index] / 0) except ZeroDivisionError as err: print("2) 0으로 나눌 수 없습니다.({0})".format(err)) except IndexError as err: print("3) 잘못된 인덱스 입력.({0})".format(err)) except Exception as err: # 모든 예외를 처리하기위해서 가장 상위클래스이 예외는 마지막에 두어야 한다. print("1) 예외가 발생.({0})".format(err)) # 강제 예외 발생 # ex1) print("====강제 예외 발생======") text = input() if text.isdigit() == False: raise Exception("입력 받은 문자열이 숫자로 구성되어 있지 않습니다.") # ex2) try: raise Exception("예외를 일으킵니다.") except Exception as e: print("예외가 발생하였습니다. : {0}".format(e)) print("프로그램 종료.") # 사용자 정의 예외 def some_function(): print("1~10 사이의 수를 입력하세요:") num = int(input()) if num < 1 or num > 10: raise Exception("유효하지 않은 숫자입니다.{0}".format(num)) else: print("입력한 수는 {0}입니다.".format(num)) try: some_function() except Exception as err: print("예외가 발생했습니다. {0}".format(err)) ''' try: # 예외 발생 except: raise ''' def some_function_caller(): try: some_function() except Exception as err: print("1)예외가 발생했습니다.{0}".format(err)) raise try: some_function_caller() except Exception as err: print("2)예외가 발생했습니다.{0}".format(err)) # 사용자 정의 예외 형식 ''' class MyException(Exception): def __init__(self): super().__init__("MyException이 발생했습니다.") everythis_is_fine = False if everythis_is_fine == False: raise MyException() ''' class InvalisdIntException(Exception): def __init__(self, arg): super().__init__('정수가 아닙니다. : {0}'.format(arg)) def conver_to_integer(text): if text.isdigit(): return int(text) else: raise InvalisdIntException(text) if __name__ == '__main__': try: print("숫자를 입력하세요 :") text = input() number = conver_to_integer(text) except InvalisdIntException as err: print("예외가 발생했습니다({0})".format(err)) else: print('정수 형식으로 변환되었습니다.{0}({1})'.format(number, type(number)))
17a8f20111d7330747d42a29d2283765229aa2bb
345OOP/Python
/pythonProject5/generatingRandomValues.py
432
4.09375
4
# generating Random Values import random # example1 # for i in range(3): # print(random.random()) # print(random.randint(10,20)) # example2 # members = ['John', 'Mary', 'Lois', 'Clark'] # leader = random.choice(members) # print(leader) # example Dice class Dice: def roll(self): first = random.randint(1,6) second = random.randint(1, 6) return first,second dice = Dice() print(dice.roll())
3ac7b581f715fe7fc2df35234e794eca0d271c9b
NewbDBA/nadocode
/practice.py
1,944
3.75
4
# int = 정수형 ? 숫자형 데이터 // 정수형 데이터는 문자열과 함께 출력 시, 문자열로 바꿔줘야함 # str = 문자열 # boolean = 참 거짓 # 연산자 print(1 == 3) # 앞 뒤가 같음 print(1 != 3) # 앞 뒤가 같지 않음 print(not(1 == 3)) # 위에 거랑 비슷 print((3 > 0) and (3 < 5)) # 2개 다 만족해야함 print((3 > 0) & (3 < 5)) # 위에거랑 같음 print((3 < 0) or (3 > 5)) # 둘 중에 하나만 되도 okay print((3 < 0) | (3 > 5)) # 위에 거랑 같은데, 백스페이스 밑에꺼 shift +x # 연산자 # 간단수식 number = 2+4*3 number = number + 2 #number라는 변수에 2 더하고 싶댑니다.# print(number) # 아래거는 위에꺼랑 똑같음 number += 2 # *= 숫자 // -= 숫자 // /=숫자 다됨 print(number) asshole = 43+5+3*8 asshole %= 5 print(asshole) # 간단수식 # 숫자 처리 함수 print(abs(-5)) # ABS=absolute (절대값) print(pow(5, 2)) # == 5 ** 2 print(max(5,10,12)) # min 도 있음 print(round(3.2)) # 반올림 from math import * # math 라는 모듈에서 모든 값(*)을 불러온다는 말 print(floor(5.99)) # math 모둘 호출 후에 버림(floor) 가능 print(ceil(1.11)) # 올림 print(sqrt(4)) # 제곱근 from random import * # Random 라이브러리 불러옴 print(random()) # 0.0 ~ 1.0 미만 임의값 print(random() * 10) # 0.0 ~ 10. 미만 임의값 print(int(random()* 10)) # 정수인 0.0 ~ 10. 미만 임의값 print(int(random()* 10) + 1) # 정수인 1 ~ 10. 미만 임의값 print(int(random()* 45) + 1) # 정수인 1 ~ 45. 미만 임의값 print(randrange(1, 10)) # 위에 것과 동일한데 더 간단히 print(randint(1, 45)) # 위에 것들은 끝에 있는 숫자는 출력 x / 이건 끝에 있는 숫자도 포함하여 출력 범위 잡아 줌 from random import * date = randint(4, 28) print(date) print("오프라인 스터디 모임 날짜는 매월 " + str(date) + "일로 선정되었습니다.")
d64a03f26d7dfd8bb4a7899770f29ce560b22381
Juahn1/Ejercicios-curso-de-python
/ejercicio_1_ecuacion.py
519
4.21875
4
#pasar la ecuacion a una expresion algoritmica (c + 5)(b ^2 -3ac)a^2 # ------------------ # 4a def ecuacion(a,b,c): x=((c+5)*((b**2)-3*a*c)*(a**2))/(4*a) print(f"El resultado es {x}") try: a=float(input("Ingrese la variable A: ")) b=float(input("Ingrese la variable B: ")) c=float(input("Ingrese la variable C: ")) ecuacion(a,b,c) except: ValueError print("Ingrese un numero valido")