blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bde1a653d76316d23b9a8fdc8f85f082159136ee | Meshugah/EPI | /src/C0/_81_.py | 870 | 3.828125 | 4 | # stacks and queues baybeee
# queues are fifo
# stack are first in last out like pancakes
import collections
def print_linked_list_in_reverse(head):
nodes = []
while head:
nodes.append(head.data)
head = head.next
while nodes:
print(nodes.pop())
# implement a stack with max API
class Stack:
# my ADT
cacheElementMax = collections.namedtuple("cacheElementMax",('element', 'max'))
def __init__(self):
self.stack = []
def empty(self):
return len(self.stack) == 0
def max(self):
if self.empty():
raise IndexError
return self.stack[-1].max
def pop(self):
if self.empty():
raise IndexError
return self.stack.pop().element
def push(self, x):
self.append(self.cacheElementMax(x, x if self.empty() else max(x, self.max())))
|
8ac81494f4e68f6ccc9d08180c475bd9c5c8c00c | earl-grey-cucumber/Algorithm | /99-Recover-Binary-Search-Tree/solution.py | 777 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
p, q, pre = None, None, None
def recoverTree(self, root):
global p, q, pre
p, q, pre = None, None, None
if not root:
return
self.helper(root)
temp = p.val
p.val = q.val
q.val = temp
def helper(self, cur):
global p, q, pre
if not cur:
return
self.helper(cur.left)
if pre and pre.val > cur.val:
if not p:
p = pre
q = cur
else:
q = cur
pre = cur
self.helper(cur.right) |
a48ef00d5671b7b09f1ac306800abbb07632730c | senorpatricio/python-exercizes | /exercise3.py | 990 | 4.1875 | 4 |
# exercise 3
def isFloat(string):
try:
float(string)
return True
except ValueError:
return False
def check():
mph = raw_input("Enter a speed in miles per hour: ")
if mph.isdigit() and mph is not "0":
return mph
elif isFloat(mph) and mph is not "0":
return mph
else:
print "Reenter speed, it must be a number > 0: "
return check()
mph = float(check())
meters_per_mile = 1609.34
meters_per_hour = mph * meters_per_mile
barleycorns = mph * 117.647 * 24
furlongs = (meters_per_hour / 201.168) * 24 * 14
mach = meters_per_hour / ((1130 * 60 * 60) / 3.28084)
light_speed = meters_per_hour/(299792458 * 60 * 60)
print "Converted to Barleycorns per day is: {}" .format(barleycorns)
print "Converted to Furlongs per fortnight is: {}" .format(furlongs)
print "Converted to Mach number is: {}" .format(mach)
print "Converted to percentage of the speed of light is: {}" .format(light_speed)
print "Thanks for playing, dude!"
|
ef3dba4c4c3c06bed77a06379821a8460f18620c | supriya1610190086/python_Logical_Question | /conversion time.py | 696 | 3.65625 | 4 | # def convert(str1):
# if str1[:-2] == "AM" and str1[:2]== "12":
# return str1[:-2]
# elif str1[:-2] == "PM" and str1[:2]=="24":
# return str1[:-2]
# else:
# return str(int(str1[:2]) + 12) + str1 [2:11]
# print(convert(input("")))
# def convert_time(s):
# list1=["01","02","03","04","05","06","07","08","09","10","11","12"]
# list2=[13,14,15,16,17,18,19,20,21,22,23,24]
# l=s[0:2]
# m=s[2:10]
# if "pm" in s:
# i=0
# while i<len(list1):
# if list1[i]==l:
# print(str(list2[i])+m)
# i=i+1
# else:
# print(s)
# convert_time(input().lower())
|
c8870163b3223a209937cd98f41126154701a1c8 | mnocenti/aoc20 | /day7.py | 43,236 | 3.625 | 4 | #/usr/bin/python
import itertools
def search_bag(outermost, target, seen):
for _,bag_type in input[outermost]:
if bag_type == target:
return True
if not bag_type in seen:
seen.add(bag_type)
found = search_bag(bag_type, target, seen)
if found:
return True
return False
def part1():
print(len([b for b in input if search_bag(b, "shiny gold", set())]))
def count_bags(outermost):
count = 0
for n,bag_type in input[outermost]:
count += n + n*count_bags(bag_type)
return count
def part2():
print(count_bags("shiny gold"))
input = {
"bright olive": [ (5, "dotted white"), (2, "wavy lavender")],
"plaid brown": [ (3, "bright lime"), (5, "plaid coral")],
"dim coral": [ (1, "shiny maroon"), (2, "bright orange"), (3, "clear lavender")],
"dull olive": [ (5, "wavy purple"), (2, "plaid white"), (4, "vibrant magenta"), (1, "light brown")],
"dim yellow": [ (1, "bright cyan"), (3, "striped green"), (5, "dim white")],
"drab chartreuse": [ (3, "shiny lime"), (2, "bright indigo"), (2, "muted yellow"), (5, "dim tan")],
"dim cyan": [ (4, "drab tomato"), (3, "dotted teal"), (1, "posh purple"), (2, "faded brown")],
"striped indigo": [ (2, "wavy brown")],
"dull coral": [ (5, "mirrored salmon")],
"light violet": [ (3, "light maroon"), (3, "plaid purple"), (1, "pale lime"), (2, "pale orange")],
"clear magenta": [ (3, "muted tan"), (3, "clear lime"), (3, "bright magenta"), (3, "faded purple")],
"drab turquoise": [ (1, "dark violet")],
"dim black": [ (4, "vibrant turquoise")],
"dotted gray": [ (1, "posh salmon"), (5, "drab lime"), (1, "clear coral"), (1, "faded lime")],
"light lime": [ (5, "wavy lavender"), (3, "shiny black")],
"bright yellow": [ (3, "dotted beige"), (4, "clear purple"), (4, "faded salmon"), (5, "drab black")],
"shiny teal": [ (3, "dotted chartreuse"), (1, "wavy yellow"), (3, "clear lavender")],
"shiny crimson": [ (2, "light plum"), (3, "shiny black")],
"shiny lime": [ (1, "dim turquoise"), (4, "pale fuchsia")],
"pale lavender": [ (3, "bright lavender"), (5, "wavy blue")],
"shiny purple": [],
"clear lime": [ (2, "drab bronze")],
"vibrant lavender": [ (2, "plaid crimson"), (3, "plaid yellow")],
"clear gray": [ (4, "shiny indigo"), (1, "vibrant salmon"), (3, "bright yellow"), (2, "light green")],
"dark lime": [ (1, "light lime"), (3, "vibrant yellow"), (5, "faded bronze")],
"bright chartreuse": [ (5, "mirrored olive"), (2, "mirrored white"), (1, "bright black"), (2, "clear olive")],
"wavy red": [ (5, "bright black"), (4, "dotted salmon"), (4, "clear tomato"), (4, "faded teal")],
"posh coral": [ (4, "posh plum"), (4, "shiny magenta"), (4, "light plum")],
"shiny coral": [ (5, "shiny yellow")],
"light bronze": [ (2, "shiny purple"), (5, "mirrored maroon"), (2, "light white")],
"mirrored olive": [ (5, "mirrored white")],
"pale crimson": [ (2, "vibrant gold"), (1, "bright yellow"), (2, "light green"), (4, "shiny gray")],
"bright cyan": [ (1, "muted plum"), (5, "dark bronze"), (4, "dotted teal"), (5, "faded fuchsia")],
"posh bronze": [ (1, "muted gold"), (5, "shiny turquoise"), (3, "wavy bronze")],
"mirrored yellow": [ (1, "dull maroon"), (2, "posh orange"), (3, "striped lime"), (4, "plaid crimson")],
"muted brown": [ (5, "mirrored indigo")],
"posh lavender": [ (2, "dotted violet"), (3, "clear orange")],
"shiny salmon": [ (3, "bright red"), (1, "light turquoise"), (2, "drab turquoise")],
"striped teal": [],
"pale purple": [ (1, "faded yellow"), (2, "dotted beige"), (1, "dark red"), (5, "plaid yellow")],
"drab tomato": [ (2, "faded aqua"), (2, "faded purple")],
"wavy yellow": [ (2, "wavy gold"), (1, "dotted beige"), (2, "shiny gold"), (4, "posh tomato")],
"shiny yellow": [ (3, "wavy brown"), (5, "dull violet"), (2, "muted tomato"), (4, "dull magenta")],
"wavy brown": [],
"faded teal": [ (5, "muted plum"), (1, "posh indigo")],
"vibrant tomato": [ (1, "pale blue")],
"drab red": [ (3, "light teal"), (4, "shiny lime")],
"muted beige": [ (4, "light teal"), (2, "vibrant orange"), (1, "drab turquoise")],
"dotted orange": [ (3, "plaid cyan"), (3, "shiny beige"), (1, "bright chartreuse")],
"posh fuchsia": [ (3, "posh tomato"), (5, "bright blue")],
"striped lime": [ (4, "vibrant red"), (1, "bright yellow"), (5, "faded yellow"), (3, "dim gold")],
"bright white": [ (1, "clear purple"), (2, "drab crimson")],
"wavy olive": [ (1, "pale lavender"), (2, "dotted lime")],
"clear black": [ (2, "pale yellow")],
"clear brown": [ (2, "vibrant crimson")],
"dotted aqua": [ (4, "light green"), (4, "light purple"), (3, "pale blue")],
"dull red": [ (1, "bright fuchsia"), (2, "plaid crimson"), (5, "dotted salmon"), (1, "light salmon")],
"light red": [ (2, "mirrored purple"), (2, "dull teal")],
"mirrored bronze": [ (4, "striped lavender"), (1, "dotted brown"), (1, "posh maroon"), (1, "shiny chartreuse")],
"light silver": [ (4, "dim orange"), (1, "dim aqua"), (5, "plaid crimson")],
"faded violet": [ (5, "dotted tomato"), (3, "wavy beige")],
"muted violet": [ (1, "dotted brown")],
"muted black": [ (3, "shiny purple"), (1, "dark salmon"), (3, "bright lavender"), (2, "shiny white")],
"muted tomato": [ (3, "dull magenta"), (1, "muted fuchsia")],
"faded olive": [ (3, "bright coral"), (5, "dark salmon"), (3, "dotted lavender"), (5, "vibrant purple")],
"dotted indigo": [ (2, "drab yellow"), (5, "dim coral"), (3, "striped green")],
"dull turquoise": [ (3, "dark black")],
"faded fuchsia": [ (4, "dull green"), (5, "pale lavender")],
"mirrored gray": [ (2, "mirrored brown"), (3, "shiny gray"), (2, "light maroon")],
"dull violet": [ (5, "muted tomato")],
"vibrant crimson": [ (1, "vibrant tomato"), (1, "striped maroon"), (3, "drab plum")],
"pale olive": [ (3, "shiny lime"), (4, "dim turquoise")],
"muted orange": [ (1, "dull orange"), (5, "shiny tomato"), (5, "pale yellow"), (1, "faded orange")],
"vibrant orange": [ (5, "muted yellow"), (1, "plaid salmon"), (5, "dim aqua")],
"bright brown": [ (3, "muted gray"), (2, "dull cyan")],
"clear coral": [ (3, "clear crimson"), (4, "dotted yellow"), (1, "bright orange")],
"clear blue": [ (1, "posh tan")],
"shiny cyan": [ (3, "light gold")],
"plaid tomato": [ (3, "dull magenta"), (2, "clear brown"), (1, "wavy plum")],
"dim magenta": [ (5, "dark orange")],
"mirrored plum": [ (3, "dull green"), (4, "light violet"), (2, "vibrant bronze"), (4, "vibrant tomato")],
"muted green": [ (1, "dull crimson"), (2, "drab crimson"), (2, "dim red")],
"wavy gray": [ (3, "dark silver")],
"mirrored white": [ (4, "bright yellow"), (2, "bright blue")],
"dark white": [ (2, "posh turquoise"), (2, "light plum")],
"striped maroon": [ (5, "shiny white"), (3, "shiny coral"), (3, "pale salmon")],
"shiny aqua": [ (1, "bright indigo"), (5, "dim plum")],
"vibrant chartreuse": [ (3, "drab gold"), (1, "striped cyan"), (2, "drab violet"), (1, "muted black")],
"faded chartreuse": [ (4, "bright bronze"), (3, "dark silver"), (1, "bright aqua")],
"shiny olive": [ (1, "light silver")],
"dim chartreuse": [ (5, "striped tomato")],
"vibrant red": [ (3, "mirrored beige")],
"vibrant white": [ (4, "light aqua")],
"dim gold": [ (3, "plaid gray")],
"posh chartreuse": [ (3, "wavy blue"), (5, "dull maroon"), (5, "muted yellow")],
"striped purple": [ (4, "shiny orange"), (3, "dim lavender"), (3, "muted lavender"), (5, "plaid tomato")],
"plaid white": [ (2, "striped salmon")],
"striped tomato": [ (5, "bright blue")],
"bright lime": [ (5, "dark maroon"), (1, "shiny gray"), (3, "light white")],
"vibrant yellow": [ (3, "plaid magenta"), (3, "wavy chartreuse"), (3, "bright lavender"), (1, "vibrant salmon")],
"faded red": [ (3, "plaid turquoise"), (2, "wavy cyan"), (5, "dim chartreuse")],
"dim red": [ (4, "muted coral")],
"dotted beige": [],
"pale magenta": [ (1, "light violet"), (2, "mirrored lime")],
"muted fuchsia": [],
"vibrant purple": [ (5, "shiny purple"), (4, "dim turquoise"), (2, "bright violet"), (1, "dotted beige")],
"pale tomato": [ (3, "dull magenta"), (5, "dim turquoise")],
"wavy gold": [ (2, "muted tomato"), (5, "posh tomato")],
"dull green": [ (1, "shiny indigo"), (3, "dull maroon")],
"muted magenta": [ (1, "clear tan"), (5, "dim tomato"), (1, "plaid purple"), (1, "wavy gray")],
"drab bronze": [ (5, "dull violet"), (1, "light green"), (3, "dim turquoise")],
"vibrant coral": [ (5, "bright black"), (5, "vibrant salmon")],
"dim gray": [],
"mirrored black": [ (5, "mirrored lavender")],
"muted cyan": [ (5, "mirrored gold")],
"light aqua": [ (1, "dull cyan"), (4, "dull lavender"), (2, "wavy crimson")],
"mirrored gold": [ (1, "light orange")],
"vibrant cyan": [ (2, "pale chartreuse"), (5, "vibrant tan")],
"dotted green": [ (2, "vibrant tan")],
"vibrant tan": [ (5, "pale lime")],
"drab magenta": [ (3, "light gold"), (2, "posh yellow"), (4, "mirrored salmon"), (4, "muted black")],
"clear teal": [ (3, "vibrant red"), (3, "dotted crimson"), (3, "plaid fuchsia")],
"dark coral": [ (4, "posh fuchsia"), (5, "mirrored fuchsia")],
"bright plum": [ (5, "vibrant blue")],
"drab indigo": [ (2, "shiny orange"), (3, "light indigo"), (2, "drab crimson"), (5, "light purple")],
"shiny chartreuse": [ (4, "clear gold")],
"plaid coral": [ (1, "shiny white"), (2, "dotted plum"), (5, "wavy indigo")],
"dull silver": [ (3, "striped white"), (2, "faded gold"), (3, "dark fuchsia")],
"dotted teal": [ (5, "clear lime")],
"posh black": [ (4, "light plum"), (4, "dark plum"), (4, "vibrant plum")],
"wavy black": [ (5, "bright bronze")],
"mirrored magenta": [ (3, "muted olive"), (5, "striped tomato"), (2, "clear lavender")],
"posh indigo": [ (4, "clear salmon"), (3, "vibrant salmon")],
"vibrant brown": [ (2, "drab turquoise")],
"pale blue": [ (3, "vibrant silver"), (5, "plaid turquoise")],
"wavy lavender": [ (5, "plaid lime"), (1, "plaid crimson"), (5, "wavy coral"), (1, "dark gold")],
"shiny tan": [ (5, "plaid blue"), (3, "shiny bronze"), (1, "mirrored gold"), (4, "faded salmon")],
"muted purple": [ (3, "muted tan")],
"mirrored crimson": [ (2, "drab plum"), (3, "muted magenta"), (5, "dim yellow")],
"muted red": [ (1, "wavy indigo")],
"dotted tomato": [ (5, "plaid turquoise"), (1, "dull lime")],
"dull orange": [ (2, "shiny yellow"), (1, "drab bronze"), (4, "shiny lime")],
"clear aqua": [ (3, "dull cyan"), (2, "bright yellow"), (2, "shiny maroon")],
"light coral": [ (4, "wavy black")],
"posh silver": [ (5, "light bronze"), (2, "clear purple"), (5, "pale fuchsia"), (2, "dull cyan")],
"drab coral": [ (2, "posh yellow")],
"light fuchsia": [ (2, "dim gray")],
"faded cyan": [ (1, "faded orange")],
"bright aqua": [ (1, "muted black"), (1, "muted chartreuse"), (1, "wavy blue")],
"drab lavender": [ (4, "posh yellow")],
"posh gray": [ (4, "shiny lime"), (5, "dotted gold"), (4, "vibrant maroon")],
"plaid blue": [ (5, "vibrant tan"), (5, "mirrored white"), (5, "shiny purple"), (1, "clear white")],
"shiny gray": [ (2, "muted fuchsia"), (5, "plaid crimson"), (5, "faded salmon")],
"light brown": [ (4, "dotted tan"), (5, "wavy coral"), (3, "plaid teal")],
"striped magenta": [ (2, "wavy turquoise")],
"striped aqua": [ (2, "light cyan"), (2, "plaid lime"), (2, "mirrored orange"), (1, "posh lime")],
"bright teal": [ (1, "faded plum"), (1, "dark blue"), (1, "posh cyan"), (2, "striped chartreuse")],
"pale green": [ (1, "muted black"), (4, "faded olive"), (1, "wavy chartreuse"), (5, "dim maroon")],
"vibrant bronze": [ (3, "vibrant lavender"), (3, "faded blue"), (4, "dim brown"), (4, "drab chartreuse")],
"pale brown": [ (3, "faded yellow"), (1, "vibrant tomato")],
"wavy aqua": [ (1, "striped magenta"), (1, "mirrored silver"), (1, "dim gold")],
"dotted yellow": [ (2, "drab turquoise"), (2, "drab maroon"), (1, "light teal")],
"pale salmon": [ (2, "bright indigo"), (3, "wavy violet")],
"posh red": [ (3, "posh blue"), (4, "muted yellow"), (5, "dark silver")],
"wavy violet": [ (2, "dotted lime"), (2, "vibrant purple"), (1, "dull maroon")],
"drab purple": [ (4, "plaid crimson"), (1, "shiny plum")],
"light black": [ (2, "faded teal"), (1, "faded yellow"), (2, "muted fuchsia")],
"dim turquoise": [ (4, "wavy beige"), (1, "shiny plum"), (3, "muted tomato"), (4, "dull magenta")],
"dark tan": [ (5, "drab chartreuse"), (3, "dim coral")],
"striped gray": [ (5, "muted red"), (1, "bright blue"), (5, "wavy maroon")],
"muted tan": [ (5, "drab turquoise"), (1, "light maroon"), (5, "plaid purple")],
"posh green": [ (3, "dotted chartreuse"), (4, "muted yellow"), (5, "shiny gray"), (1, "dark black")],
"mirrored lime": [ (4, "clear teal"), (5, "wavy coral"), (2, "mirrored beige")],
"muted plum": [ (5, "faded yellow"), (3, "posh blue")],
"dark maroon": [ (2, "dotted lavender")],
"plaid green": [ (3, "wavy yellow"), (1, "shiny indigo"), (4, "mirrored maroon"), (5, "dim gray")],
"mirrored teal": [ (5, "dim magenta"), (1, "dark magenta"), (3, "plaid green")],
"wavy crimson": [ (1, "vibrant cyan"), (2, "light beige")],
"wavy green": [ (4, "dim tan"), (1, "dotted lime"), (5, "drab white"), (2, "bright beige")],
"shiny brown": [ (5, "dark silver"), (3, "shiny maroon"), (5, "dotted lavender")],
"muted turquoise": [ (5, "dark indigo"), (3, "drab plum")],
"mirrored lavender": [ (2, "clear salmon"), (2, "plaid maroon"), (3, "wavy cyan")],
"drab blue": [ (3, "dotted olive"), (1, "shiny chartreuse"), (1, "drab magenta"), (2, "mirrored maroon")],
"bright fuchsia": [ (1, "dark olive")],
"pale turquoise": [ (2, "striped chartreuse")],
"posh white": [ (1, "striped cyan"), (1, "plaid coral"), (2, "dim gray"), (3, "shiny red")],
"drab brown": [ (4, "plaid red")],
"pale gold": [ (2, "dim tan"), (5, "dark red"), (4, "vibrant cyan"), (5, "dark violet")],
"plaid maroon": [ (1, "shiny lime"), (4, "faded lavender"), (2, "dim tan"), (5, "vibrant purple")],
"vibrant green": [ (1, "drab purple"), (2, "faded blue")],
"bright violet": [ (1, "dotted lavender"), (5, "light chartreuse"), (4, "bright indigo")],
"bright magenta": [ (5, "shiny purple"), (5, "light teal"), (2, "pale purple"), (4, "pale silver")],
"plaid orange": [ (1, "dull green")],
"posh olive": [ (5, "dark silver"), (3, "drab yellow"), (2, "dim brown"), (4, "dull gray")],
"light teal": [ (3, "dim gray")],
"shiny beige": [ (1, "dark cyan"), (1, "vibrant yellow")],
"drab cyan": [ (4, "dim silver"), (1, "wavy maroon")],
"pale gray": [ (2, "dark salmon")],
"plaid beige": [ (3, "bright purple"), (1, "drab plum"), (4, "shiny bronze"), (3, "drab salmon")],
"dull plum": [ (4, "mirrored orange")],
"shiny violet": [ (3, "drab olive")],
"striped turquoise": [ (1, "faded green")],
"dark aqua": [ (5, "clear crimson")],
"dim crimson": [ (3, "faded chartreuse"), (3, "light orange"), (4, "striped plum")],
"faded tan": [ (1, "dark cyan"), (1, "bright silver")],
"faded brown": [ (3, "faded purple"), (1, "posh orange"), (5, "light silver")],
"mirrored coral": [ (1, "vibrant tan")],
"clear olive": [ (2, "pale olive")],
"pale lime": [ (2, "muted fuchsia"), (1, "dim gray"), (5, "dotted beige"), (5, "striped teal")],
"wavy white": [ (3, "dim indigo"), (3, "plaid green"), (2, "dull gold")],
"pale plum": [ (5, "plaid gray")],
"plaid yellow": [ (5, "dark yellow"), (1, "mirrored white"), (5, "shiny white"), (1, "shiny lime")],
"drab salmon": [ (2, "vibrant blue"), (2, "plaid plum"), (1, "shiny gray"), (3, "bright black")],
"striped fuchsia": [ (2, "striped teal"), (5, "drab black"), (2, "bright magenta")],
"mirrored fuchsia": [ (3, "drab black")],
"dark indigo": [ (1, "dull lime"), (4, "vibrant cyan"), (1, "bright gray"), (3, "pale purple")],
"posh blue": [ (1, "shiny yellow")],
"dark turquoise": [ (4, "bright yellow"), (3, "wavy bronze")],
"posh tan": [ (4, "shiny plum"), (4, "dark silver"), (3, "wavy beige"), (1, "mirrored fuchsia")],
"bright turquoise": [ (1, "dotted green"), (4, "faded silver"), (1, "plaid turquoise")],
"vibrant teal": [ (4, "plaid teal"), (3, "pale blue")],
"plaid purple": [ (2, "dim tan"), (5, "light turquoise")],
"drab plum": [ (2, "dull green"), (5, "posh lavender"), (3, "drab tan")],
"dark blue": [ (3, "mirrored indigo"), (3, "dark red")],
"vibrant black": [ (2, "shiny red"), (5, "posh brown"), (1, "mirrored yellow")],
"mirrored brown": [ (1, "shiny indigo"), (2, "shiny yellow"), (5, "shiny blue"), (5, "clear yellow")],
"dotted crimson": [ (3, "posh tomato"), (4, "vibrant blue"), (5, "dark violet"), (5, "posh violet")],
"shiny bronze": [ (1, "plaid maroon")],
"drab orange": [ (4, "dotted crimson"), (4, "clear bronze"), (3, "pale turquoise"), (5, "dim coral")],
"wavy fuchsia": [ (4, "posh fuchsia"), (5, "wavy purple"), (2, "muted cyan")],
"plaid black": [ (2, "drab crimson"), (4, "vibrant tomato"), (4, "clear bronze"), (4, "faded lavender")],
"mirrored red": [ (3, "shiny crimson")],
"faded tomato": [ (1, "clear aqua"), (3, "vibrant bronze")],
"light turquoise": [ (2, "posh silver"), (2, "shiny black"), (5, "muted blue")],
"faded crimson": [ (5, "posh blue"), (4, "dim maroon")],
"dull magenta": [],
"dark plum": [ (5, "vibrant purple"), (5, "wavy brown"), (2, "dark indigo")],
"dotted white": [ (1, "dark teal"), (5, "dull white"), (2, "pale salmon"), (1, "dotted plum")],
"wavy indigo": [ (5, "shiny maroon"), (4, "shiny lime")],
"faded coral": [ (5, "dim indigo"), (1, "striped brown")],
"vibrant turquoise": [ (4, "dotted magenta"), (5, "bright lavender"), (5, "plaid turquoise"), (5, "striped lavender")],
"muted gray": [ (1, "mirrored white")],
"dotted gold": [ (4, "dark brown")],
"dim salmon": [ (3, "light gold"), (4, "plaid purple")],
"clear salmon": [ (3, "striped lavender"), (5, "posh teal"), (4, "vibrant turquoise")],
"vibrant olive": [ (3, "striped fuchsia"), (3, "muted indigo"), (1, "dotted yellow"), (4, "bright white")],
"bright salmon": [ (1, "drab orange")],
"muted maroon": [ (5, "dim crimson"), (4, "dark red"), (5, "plaid purple")],
"light tan": [ (2, "dotted blue")],
"dotted turquoise": [ (4, "faded lime"), (2, "dotted silver"), (4, "mirrored cyan")],
"shiny magenta": [ (1, "mirrored salmon"), (3, "dim fuchsia"), (3, "muted red")],
"dark cyan": [ (5, "dark brown"), (5, "vibrant silver"), (5, "dim green")],
"dim violet": [ (4, "vibrant turquoise"), (1, "pale crimson"), (4, "bright red"), (3, "muted black")],
"dull aqua": [ (3, "drab teal")],
"dim aqua": [ (3, "vibrant blue"), (4, "pale salmon"), (5, "shiny bronze"), (2, "dim olive")],
"light gray": [ (4, "dull white"), (4, "dim blue")],
"dull salmon": [ (1, "striped fuchsia"), (5, "dark white"), (2, "pale tan")],
"plaid teal": [ (1, "dim olive"), (2, "faded purple"), (4, "shiny gray"), (1, "shiny salmon")],
"clear tan": [ (1, "clear lime"), (4, "mirrored turquoise"), (4, "bright white"), (3, "drab bronze")],
"wavy beige": [ (2, "muted fuchsia"), (3, "clear bronze"), (2, "bright yellow")],
"plaid salmon": [ (2, "drab bronze"), (2, "drab chartreuse"), (4, "plaid crimson"), (5, "shiny lime")],
"drab lime": [ (2, "clear orange"), (4, "dotted silver"), (5, "dark maroon"), (5, "dim magenta")],
"bright crimson": [ (5, "shiny maroon")],
"clear turquoise": [ (4, "vibrant blue")],
"clear lavender": [ (3, "pale fuchsia"), (2, "bright lavender"), (2, "dark orange"), (1, "dull magenta")],
"clear green": [ (3, "clear orange")],
"pale cyan": [ (2, "dull purple"), (1, "clear olive")],
"posh lime": [ (2, "clear purple")],
"dim lavender": [ (3, "clear crimson"), (4, "striped violet")],
"faded indigo": [ (5, "dull cyan"), (2, "plaid blue"), (4, "striped teal")],
"posh aqua": [ (5, "bright aqua"), (2, "shiny indigo"), (2, "drab silver"), (1, "vibrant turquoise")],
"dark magenta": [ (3, "light silver")],
"clear cyan": [ (3, "pale fuchsia"), (2, "shiny coral"), (1, "dull magenta"), (4, "dim turquoise")],
"pale yellow": [ (1, "vibrant tan"), (4, "drab plum")],
"dim plum": [ (4, "striped gray"), (2, "posh tomato"), (1, "drab black")],
"dark purple": [ (3, "bright indigo"), (3, "dull purple")],
"clear plum": [ (4, "bright cyan"), (5, "dim turquoise")],
"faded magenta": [ (1, "muted olive"), (3, "plaid chartreuse")],
"mirrored aqua": [ (2, "clear lavender")],
"light white": [ (3, "dim gray"), (3, "bright white"), (2, "striped teal"), (4, "light green")],
"clear gold": [ (2, "wavy coral")],
"dull lavender": [ (2, "wavy beige"), (3, "drab black")],
"dark yellow": [ (3, "wavy gray"), (1, "dark salmon"), (2, "vibrant tan")],
"dotted black": [ (4, "dim plum"), (2, "bright white")],
"posh tomato": [ (5, "wavy beige"), (1, "dim gray"), (3, "shiny lime"), (5, "bright black")],
"bright indigo": [ (4, "striped teal"), (1, "shiny yellow"), (5, "dotted beige")],
"dim purple": [ (5, "dark tan"), (5, "striped lavender")],
"posh plum": [ (5, "posh maroon")],
"pale bronze": [ (5, "shiny silver")],
"striped crimson": [ (2, "dark indigo")],
"plaid fuchsia": [ (1, "shiny lime"), (4, "mirrored orange")],
"dark orange": [ (2, "dotted lavender"), (1, "posh blue"), (2, "muted yellow")],
"dim blue": [ (2, "clear yellow")],
"clear violet": [ (2, "shiny bronze")],
"shiny blue": [ (4, "dark salmon"), (5, "posh plum")],
"dull lime": [ (5, "plaid green"), (3, "bright black"), (4, "drab maroon")],
"muted lavender": [ (1, "dark gray"), (2, "bright crimson")],
"plaid gray": [ (5, "bright black"), (5, "pale silver")],
"light yellow": [ (2, "mirrored crimson")],
"muted chartreuse": [ (1, "pale fuchsia"), (1, "plaid purple")],
"dim lime": [ (3, "dull maroon"), (3, "bright red"), (3, "drab black")],
"light purple": [ (5, "dull violet"), (5, "vibrant lavender")],
"posh orange": [ (5, "pale salmon"), (5, "light chartreuse"), (1, "dark red")],
"vibrant violet": [ (3, "shiny gray")],
"pale silver": [ (5, "mirrored salmon")],
"light tomato": [ (2, "dim tan"), (1, "faded silver"), (4, "plaid yellow"), (3, "drab gold")],
"posh salmon": [ (3, "bright plum")],
"dotted plum": [ (4, "pale gold"), (1, "vibrant lavender"), (2, "pale blue")],
"shiny lavender": [ (1, "dull gray"), (4, "muted teal"), (2, "dotted yellow"), (2, "bright turquoise")],
"dim beige": [ (2, "wavy yellow"), (2, "drab violet"), (1, "wavy gold"), (5, "clear cyan")],
"posh cyan": [ (2, "clear lavender"), (4, "clear salmon"), (4, "posh tan")],
"light maroon": [ (5, "dark violet"), (3, "plaid lime"), (3, "wavy gold"), (5, "dotted lime")],
"dotted lime": [ (3, "clear bronze"), (5, "dim turquoise")],
"dim bronze": [ (3, "light fuchsia")],
"faded black": [ (3, "light bronze"), (2, "bright beige")],
"striped white": [ (1, "mirrored white")],
"clear red": [ (1, "pale orange"), (2, "clear orange"), (1, "dull maroon"), (3, "dark bronze")],
"muted lime": [ (5, "dim fuchsia")],
"vibrant gold": [ (4, "wavy blue"), (3, "clear gray"), (5, "vibrant turquoise")],
"clear silver": [ (3, "light violet"), (5, "dull turquoise")],
"muted indigo": [ (3, "dark orange"), (4, "light gold")],
"bright green": [ (4, "dark red")],
"vibrant plum": [ (5, "dull tomato"), (4, "bright cyan"), (4, "plaid purple")],
"wavy cyan": [ (4, "muted plum")],
"plaid cyan": [ (4, "clear orange"), (3, "dull chartreuse")],
"faded salmon": [ (1, "dim gray")],
"shiny turquoise": [ (3, "light aqua"), (1, "vibrant beige"), (4, "clear turquoise"), (1, "faded silver")],
"dotted silver": [ (5, "dotted blue"), (1, "dotted salmon")],
"striped black": [ (2, "plaid crimson"), (5, "dotted silver"), (5, "dull maroon")],
"dull indigo": [ (4, "dim magenta"), (4, "shiny magenta"), (2, "pale yellow"), (1, "plaid cyan")],
"bright coral": [ (1, "shiny coral"), (2, "muted tomato"), (4, "drab crimson")],
"faded bronze": [ (5, "posh cyan"), (5, "light beige"), (1, "drab yellow"), (3, "striped lime")],
"drab green": [ (1, "clear cyan")],
"pale black": [ (2, "muted yellow")],
"muted salmon": [ (4, "plaid crimson"), (2, "vibrant lime")],
"dark violet": [ (4, "clear cyan"), (1, "mirrored maroon"), (5, "drab black")],
"faded aqua": [ (3, "pale fuchsia"), (1, "clear teal"), (5, "light white")],
"vibrant indigo": [ (5, "light turquoise")],
"bright blue": [ (1, "shiny purple"), (1, "wavy brown")],
"dark olive": [ (2, "wavy beige")],
"vibrant beige": [ (3, "wavy beige"), (1, "posh violet"), (4, "dark teal")],
"dotted olive": [ (5, "dotted magenta")],
"muted coral": [ (2, "vibrant silver"), (3, "dim coral")],
"dark chartreuse": [ (4, "faded tomato"), (2, "light violet"), (4, "clear silver")],
"light green": [],
"bright gray": [ (2, "drab yellow"), (2, "muted indigo")],
"posh crimson": [ (5, "plaid indigo"), (3, "wavy lime"), (2, "dull turquoise"), (5, "faded salmon")],
"drab yellow": [ (3, "shiny purple"), (4, "dark salmon"), (3, "shiny coral"), (2, "shiny plum")],
"dull white": [ (3, "plaid lavender"), (4, "dark beige"), (1, "posh beige")],
"drab olive": [ (1, "shiny cyan"), (3, "bright fuchsia")],
"striped olive": [ (2, "drab aqua"), (3, "muted chartreuse"), (2, "clear red"), (1, "posh turquoise")],
"posh purple": [ (1, "dull lime"), (2, "dull plum"), (3, "dark black")],
"mirrored green": [ (2, "mirrored salmon")],
"dull teal": [ (1, "dark gray"), (1, "posh indigo"), (5, "light coral")],
"dim indigo": [ (5, "dark maroon")],
"faded gray": [ (4, "muted crimson")],
"light blue": [ (2, "plaid violet"), (3, "dim tomato"), (4, "plaid crimson"), (5, "dull orange")],
"plaid turquoise": [ (2, "muted blue"), (5, "clear white"), (1, "dull violet")],
"striped gold": [ (2, "striped brown"), (1, "wavy silver")],
"faded blue": [ (1, "dark lavender"), (4, "muted yellow"), (2, "bright yellow"), (2, "dim tan")],
"clear beige": [ (5, "dim tan"), (4, "faded blue"), (2, "bright green")],
"shiny indigo": [ (1, "shiny purple")],
"striped brown": [ (2, "light gold")],
"shiny black": [ (1, "posh red"), (5, "bright black"), (3, "posh plum"), (5, "clear white")],
"pale aqua": [ (5, "plaid purple"), (3, "wavy orange"), (5, "dotted purple"), (4, "bright lime")],
"dark beige": [ (3, "clear white"), (3, "wavy yellow"), (3, "posh turquoise"), (2, "posh tan")],
"striped green": [ (3, "posh red"), (2, "shiny salmon"), (4, "mirrored salmon"), (3, "posh teal")],
"pale violet": [ (5, "wavy turquoise"), (1, "bright aqua")],
"dim tomato": [ (5, "dim tan")],
"mirrored cyan": [ (5, "shiny indigo"), (3, "faded blue")],
"plaid magenta": [ (3, "mirrored brown"), (5, "pale olive"), (2, "clear purple")],
"dotted tan": [ (5, "plaid turquoise")],
"dull fuchsia": [ (2, "shiny crimson"), (3, "clear olive")],
"clear orange": [ (5, "dotted lime"), (2, "dark olive"), (3, "bright yellow"), (2, "wavy violet")],
"light indigo": [ (1, "drab plum"), (5, "dim lime")],
"muted aqua": [ (5, "faded red"), (5, "pale blue"), (5, "dull lavender")],
"faded plum": [ (5, "drab turquoise")],
"dark gold": [ (4, "faded salmon"), (4, "bright black"), (4, "dim chartreuse")],
"striped bronze": [ (2, "dark beige")],
"mirrored purple": [ (3, "dim turquoise"), (4, "shiny bronze")],
"faded white": [ (4, "faded tomato"), (3, "faded aqua"), (5, "faded gold"), (4, "vibrant orange")],
"wavy turquoise": [ (2, "dotted olive"), (1, "muted yellow")],
"striped blue": [ (5, "wavy bronze"), (3, "shiny chartreuse")],
"dull gray": [ (4, "pale lavender")],
"plaid plum": [ (4, "dim olive"), (3, "faded olive")],
"pale coral": [ (1, "faded yellow"), (3, "shiny plum"), (4, "striped tomato"), (4, "shiny bronze")],
"drab violet": [ (2, "plaid black"), (5, "bright violet"), (3, "pale blue")],
"vibrant gray": [ (4, "vibrant indigo"), (1, "dull beige"), (1, "dull plum"), (1, "dotted brown")],
"drab gray": [ (5, "mirrored brown"), (5, "bright coral")],
"pale chartreuse": [ (2, "dull cyan"), (4, "mirrored fuchsia")],
"dotted lavender": [ (2, "bright blue"), (3, "light chartreuse")],
"dull tomato": [ (5, "wavy yellow")],
"dull purple": [ (5, "wavy brown"), (1, "muted yellow")],
"wavy orange": [ (4, "bright orange"), (1, "dotted purple"), (3, "dull blue"), (3, "light crimson")],
"dotted purple": [ (1, "bright cyan"), (5, "wavy violet"), (3, "vibrant cyan")],
"light lavender": [ (4, "shiny salmon"), (4, "mirrored salmon"), (2, "wavy magenta")],
"plaid crimson": [ (3, "dotted salmon"), (2, "plaid maroon"), (5, "pale chartreuse"), (3, "dotted beige")],
"plaid lavender": [ (2, "clear bronze"), (5, "light silver"), (1, "bright lavender")],
"wavy lime": [ (1, "dim coral")],
"clear tomato": [ (1, "dark violet")],
"light gold": [ (1, "striped teal"), (2, "vibrant purple"), (5, "dark salmon")],
"faded turquoise": [ (1, "shiny lime"), (1, "posh orange"), (1, "plaid maroon")],
"wavy tomato": [ (2, "plaid plum"), (1, "dull lime"), (3, "dull maroon")],
"faded beige": [ (3, "clear maroon"), (1, "dotted brown")],
"dark black": [ (1, "faded salmon"), (1, "light green"), (4, "clear bronze"), (4, "dotted lavender")],
"striped violet": [ (4, "mirrored beige")],
"plaid chartreuse": [ (2, "dotted purple")],
"posh maroon": [ (5, "wavy yellow"), (2, "pale chartreuse")],
"posh yellow": [ (5, "mirrored blue"), (2, "wavy beige")],
"bright black": [ (3, "clear bronze"), (5, "wavy gray")],
"shiny tomato": [ (3, "dotted plum"), (1, "shiny orange"), (4, "faded teal"), (1, "bright lavender")],
"dotted chartreuse": [ (2, "muted yellow"), (4, "faded cyan"), (3, "striped indigo"), (1, "drab red")],
"pale tan": [ (3, "dotted chartreuse")],
"dim white": [ (2, "dim tomato"), (3, "striped indigo"), (1, "faded red"), (3, "mirrored turquoise")],
"mirrored salmon": [ (1, "pale chartreuse"), (3, "faded salmon"), (2, "dark silver")],
"vibrant fuchsia": [ (3, "dim olive"), (1, "striped magenta"), (2, "dark magenta"), (2, "drab white")],
"drab silver": [ (2, "dotted silver"), (4, "wavy yellow"), (2, "dim turquoise"), (2, "shiny maroon")],
"dull yellow": [ (2, "posh teal"), (1, "muted chartreuse"), (1, "pale salmon"), (1, "posh beige")],
"clear fuchsia": [ (4, "light turquoise"), (1, "dull white"), (3, "plaid indigo"), (1, "shiny gold")],
"dark bronze": [ (2, "faded salmon")],
"vibrant lime": [ (3, "dull chartreuse"), (5, "shiny yellow")],
"wavy tan": [ (4, "wavy indigo"), (3, "dull crimson")],
"mirrored tan": [ (4, "dim salmon"), (5, "dim tomato"), (4, "mirrored salmon"), (3, "drab indigo")],
"plaid bronze": [ (2, "dotted silver"), (1, "striped black"), (2, "dotted tomato")],
"shiny silver": [ (2, "muted salmon"), (5, "bright magenta"), (2, "drab lime")],
"mirrored violet": [ (1, "shiny yellow"), (5, "vibrant tan")],
"dotted red": [ (3, "posh beige"), (3, "posh lavender"), (3, "shiny lavender"), (4, "pale bronze")],
"mirrored chartreuse": [ (3, "dark coral"), (1, "muted cyan")],
"drab crimson": [ (4, "bright blue"), (4, "faded salmon")],
"striped salmon": [ (4, "posh fuchsia"), (4, "faded salmon"), (3, "shiny yellow")],
"dark gray": [ (3, "bright bronze")],
"striped tan": [ (3, "vibrant green")],
"dull maroon": [ (1, "muted tomato")],
"light crimson": [ (1, "posh green")],
"faded lavender": [ (2, "dotted beige")],
"clear white": [ (2, "bright bronze"), (2, "wavy gray"), (4, "dull magenta"), (2, "shiny lime")],
"dim orange": [ (5, "drab gray"), (4, "drab tan"), (3, "faded black"), (2, "pale cyan")],
"faded green": [ (4, "dim blue")],
"plaid aqua": [ (2, "drab indigo"), (5, "pale turquoise"), (1, "pale tomato")],
"dotted magenta": [ (5, "pale lavender"), (2, "shiny yellow"), (3, "posh tomato")],
"faded maroon": [ (5, "wavy plum"), (2, "shiny lime")],
"dim silver": [ (2, "dull cyan"), (1, "shiny salmon"), (1, "striped salmon")],
"dotted salmon": [ (1, "posh tomato"), (4, "bright black")],
"vibrant salmon": [ (2, "dark silver")],
"striped beige": [ (2, "clear tomato"), (1, "mirrored indigo"), (2, "pale chartreuse"), (3, "dull yellow")],
"bright orange": [ (1, "pale lime")],
"muted crimson": [ (1, "dotted lavender")],
"muted bronze": [ (3, "light green")],
"shiny fuchsia": [ (4, "plaid indigo"), (5, "bright fuchsia")],
"bright red": [ (2, "posh fuchsia"), (2, "clear cyan")],
"dim maroon": [ (1, "dotted beige"), (2, "drab black"), (5, "posh tomato"), (3, "striped lavender")],
"bright gold": [ (5, "dim chartreuse"), (1, "vibrant salmon"), (2, "faded black")],
"drab white": [ (1, "clear yellow"), (4, "pale cyan"), (5, "dark yellow")],
"clear purple": [ (2, "wavy brown"), (3, "dull magenta"), (5, "dim gray"), (4, "shiny purple")],
"dim green": [ (2, "posh turquoise"), (4, "light bronze")],
"dull blue": [ (1, "light salmon"), (1, "posh red"), (2, "clear brown")],
"bright silver": [ (3, "dotted bronze"), (1, "plaid blue"), (2, "light coral")],
"bright bronze": [ (3, "dull magenta"), (3, "light white")],
"shiny gold": [ (3, "wavy gold")],
"wavy bronze": [ (4, "dull lime"), (2, "shiny white"), (2, "dim silver")],
"muted yellow": [ (5, "dark bronze"), (3, "light white"), (5, "shiny coral"), (4, "shiny lime")],
"faded orange": [ (3, "plaid maroon"), (5, "shiny plum"), (2, "mirrored white")],
"vibrant silver": [ (1, "bright coral"), (5, "wavy blue"), (1, "mirrored maroon")],
"mirrored maroon": [ (5, "drab crimson"), (4, "striped tomato")],
"striped silver": [ (2, "dotted olive"), (3, "muted white"), (5, "dark black"), (5, "light gray")],
"drab gold": [ (2, "clear coral")],
"plaid tan": [ (2, "plaid orange"), (2, "muted beige"), (2, "mirrored purple")],
"bright beige": [ (5, "light plum")],
"light salmon": [ (1, "dark black"), (5, "mirrored salmon"), (1, "dim silver")],
"dull beige": [ (2, "dark lavender")],
"posh magenta": [ (3, "muted yellow")],
"dotted violet": [ (1, "wavy brown"), (3, "dim turquoise")],
"vibrant blue": [ (4, "wavy gray"), (2, "light turquoise"), (1, "drab bronze"), (4, "wavy cyan")],
"wavy purple": [ (3, "dotted olive"), (2, "dull lime")],
"wavy plum": [ (3, "posh chartreuse")],
"dark silver": [],
"dark teal": [ (4, "posh red"), (4, "dark lavender")],
"plaid lime": [ (2, "muted fuchsia")],
"posh violet": [ (5, "clear olive")],
"plaid olive": [ (4, "vibrant tan"), (5, "plaid fuchsia")],
"mirrored indigo": [ (5, "posh maroon"), (5, "light turquoise")],
"vibrant maroon": [ (4, "vibrant beige")],
"light magenta": [ (2, "vibrant gray"), (4, "clear crimson")],
"clear indigo": [ (4, "light gray"), (1, "plaid blue")],
"shiny red": [ (4, "vibrant blue"), (1, "wavy brown"), (5, "striped maroon"), (5, "posh orange")],
"dark crimson": [ (2, "bright yellow")],
"dull crimson": [ (5, "striped salmon"), (3, "faded purple"), (4, "clear tomato")],
"pale red": [ (1, "dotted cyan"), (2, "dark turquoise")],
"striped plum": [ (4, "faded yellow"), (1, "posh blue")],
"dim olive": [ (1, "light green"), (1, "faded salmon")],
"dim brown": [ (5, "drab bronze"), (2, "dark red"), (3, "shiny gold")],
"pale orange": [ (3, "pale gray"), (1, "clear olive")],
"shiny green": [ (2, "clear turquoise"), (1, "mirrored aqua"), (2, "dull red"), (4, "dull bronze")],
"dotted fuchsia": [ (3, "vibrant bronze"), (1, "dull maroon"), (5, "wavy indigo")],
"posh teal": [ (4, "pale blue"), (1, "pale lime")],
"pale teal": [ (5, "muted beige"), (5, "dark salmon"), (2, "faded black")],
"vibrant aqua": [ (5, "vibrant silver"), (5, "shiny maroon")],
"light olive": [ (2, "plaid turquoise")],
"dim teal": [ (1, "muted magenta"), (5, "wavy maroon"), (5, "striped brown"), (4, "clear plum")],
"faded silver": [ (2, "dull lavender")],
"dark fuchsia": [ (2, "dim black"), (3, "dotted olive")],
"dotted cyan": [ (3, "clear gold")],
"pale beige": [ (2, "clear turquoise")],
"vibrant magenta": [ (5, "light bronze"), (3, "drab black")],
"pale indigo": [ (2, "vibrant cyan")],
"clear bronze": [ (1, "vibrant salmon")],
"pale white": [ (4, "faded orange")],
"light chartreuse": [],
"striped chartreuse": [ (4, "clear gray")],
"dark salmon": [ (5, "wavy gray"), (1, "light chartreuse"), (2, "clear gray")],
"muted gold": [ (3, "bright lavender"), (4, "vibrant yellow"), (3, "posh silver")],
"muted white": [ (4, "muted blue"), (1, "light gold")],
"dim tan": [ (5, "posh fuchsia"), (5, "wavy brown"), (1, "dim turquoise")],
"dull black": [ (5, "dotted cyan"), (2, "posh turquoise"), (5, "pale salmon")],
"faded lime": [ (4, "mirrored orange"), (2, "vibrant orange"), (2, "dull lavender"), (3, "dotted chartreuse")],
"drab tan": [ (5, "shiny maroon"), (4, "mirrored white"), (3, "dull plum"), (4, "shiny plum")],
"muted olive": [ (4, "faded blue")],
"dull chartreuse": [ (4, "shiny cyan"), (5, "dark silver"), (2, "dark violet"), (2, "bright lavender")],
"posh turquoise": [ (4, "pale orange"), (2, "dotted yellow"), (3, "bright tomato"), (2, "vibrant turquoise")],
"dull tan": [ (2, "mirrored purple")],
"drab teal": [ (1, "dull lavender")],
"light beige": [ (3, "plaid yellow"), (4, "faded lavender")],
"wavy blue": [ (3, "shiny purple")],
"striped orange": [ (4, "vibrant cyan")],
"shiny orange": [ (2, "shiny black"), (2, "shiny coral")],
"dull brown": [ (3, "wavy bronze")],
"mirrored silver": [ (4, "vibrant tan"), (4, "faded fuchsia"), (5, "dark red"), (3, "wavy blue")],
"wavy teal": [ (1, "pale coral")],
"drab black": [ (4, "wavy brown"), (4, "striped teal"), (2, "muted fuchsia"), (4, "shiny indigo")],
"drab aqua": [ (2, "bright orange"), (1, "vibrant tan")],
"mirrored orange": [ (2, "striped salmon"), (1, "wavy gray"), (5, "pale blue"), (4, "mirrored salmon")],
"muted teal": [ (4, "drab tan"), (4, "posh beige"), (4, "faded green")],
"faded yellow": [ (3, "shiny purple"), (3, "wavy blue"), (1, "muted fuchsia")],
"shiny maroon": [ (3, "striped salmon"), (5, "wavy violet")],
"wavy silver": [ (4, "faded blue"), (2, "vibrant salmon"), (5, "plaid gray")],
"shiny white": [ (4, "dark salmon")],
"posh brown": [ (5, "drab red")],
"bright purple": [ (2, "dim silver")],
"dotted brown": [ (1, "dotted yellow")],
"striped lavender": [ (5, "shiny gold"), (5, "mirrored fuchsia")],
"dark lavender": [ (3, "bright violet"), (5, "dull violet"), (1, "shiny coral")],
"drab maroon": [ (2, "light white"), (2, "vibrant turquoise"), (2, "vibrant cyan")],
"pale maroon": [ (3, "dim red")],
"plaid gold": [ (4, "posh bronze")],
"striped coral": [ (5, "drab blue"), (3, "muted bronze")],
"drab fuchsia": [ (1, "shiny bronze")],
"light cyan": [ (1, "dotted fuchsia"), (1, "drab violet")],
"plaid silver": [ (3, "clear gray"), (5, "light teal"), (3, "vibrant tan"), (1, "bright white")],
"wavy coral": [ (1, "shiny black"), (3, "mirrored maroon")],
"posh gold": [ (3, "bright yellow"), (2, "dark lavender")],
"drab beige": [ (5, "bright gray"), (3, "pale olive"), (3, "plaid chartreuse")],
"wavy salmon": [ (5, "shiny beige"), (1, "posh violet")],
"pale fuchsia": [ (4, "wavy gray"), (1, "wavy beige")],
"dim fuchsia": [ (1, "dim beige"), (4, "muted cyan"), (1, "clear lavender")],
"bright tan": [ (2, "drab crimson")],
"striped red": [ (2, "muted black")],
"dark green": [ (5, "plaid red")],
"faded gold": [ (2, "muted white"), (5, "clear yellow"), (1, "light fuchsia"), (4, "dotted violet")],
"striped cyan": [ (2, "drab purple"), (1, "shiny fuchsia"), (2, "light salmon")],
"dull bronze": [ (1, "faded black"), (4, "dull lavender")],
"dull cyan": [ (5, "faded salmon"), (1, "clear bronze")],
"shiny plum": [ (2, "dark silver")],
"mirrored beige": [ (3, "posh red"), (1, "clear chartreuse"), (2, "muted magenta")],
"mirrored tomato": [ (3, "posh lavender"), (4, "light violet"), (1, "wavy crimson"), (1, "dim tan")],
"light plum": [ (5, "dim tan"), (2, "dotted beige"), (4, "posh blue"), (4, "light green")],
"mirrored blue": [ (4, "faded lavender"), (4, "pale salmon")],
"clear maroon": [ (3, "dark salmon"), (2, "shiny brown"), (4, "wavy purple"), (1, "plaid yellow")],
"bright maroon": [ (4, "pale turquoise"), (4, "drab violet"), (2, "clear lime")],
"plaid red": [ (1, "drab turquoise"), (1, "striped teal"), (4, "plaid yellow")],
"mirrored turquoise": [ (3, "clear orange"), (5, "bright blue"), (3, "posh plum")],
"dark brown": [ (5, "striped fuchsia"), (5, "mirrored plum"), (1, "wavy crimson"), (4, "clear gray")],
"muted silver": [ (2, "dim tan"), (2, "muted crimson")],
"dark red": [ (2, "wavy beige"), (1, "clear bronze"), (5, "shiny coral"), (3, "shiny indigo")],
"dark tomato": [ (2, "faded gray"), (2, "dim tomato")],
"muted blue": [ (5, "posh silver")],
"wavy magenta": [ (4, "faded tomato")],
"plaid violet": [ (5, "dim aqua"), (4, "drab orange"), (4, "posh lavender"), (2, "dull yellow")],
"faded purple": [ (4, "vibrant bronze"), (5, "bright bronze"), (1, "faded red"), (4, "clear tan")],
"wavy chartreuse": [ (5, "bright white"), (2, "shiny coral"), (3, "bright cyan")],
"plaid indigo": [ (3, "pale purple"), (2, "posh orange")],
"bright tomato": [ (5, "plaid blue"), (2, "posh orange"), (1, "vibrant purple")],
"wavy maroon": [ (1, "striped white")],
"bright lavender": [ (3, "faded salmon"), (5, "mirrored maroon"), (5, "posh tomato")],
"light orange": [ (2, "bright blue"), (1, "dark yellow"), (2, "clear gray"), (2, "striped salmon")],
"posh beige": [ (2, "dark orange")],
"clear chartreuse": [ (5, "striped maroon"), (5, "light chartreuse"), (4, "drab black")],
"dotted blue": [ (4, "clear cyan")],
"dotted coral": [ (4, "shiny tomato"), (1, "posh gold"), (5, "muted olive")],
"striped yellow": [ (5, "faded purple"), (4, "drab purple"), (5, "dark yellow"), (5, "muted red")],
"dull gold": [ (1, "light turquoise")],
"dotted maroon": [ (3, "dark maroon"), (2, "faded yellow")],
"clear yellow": [ (2, "plaid maroon"), (5, "bright gray"), (4, "pale olive"), (5, "shiny indigo")],
"clear crimson": [ (5, "faded yellow")],
"dotted bronze": [ (2, "muted tomato")],
}
if __name__ == "__main__":
part1()
part2() |
de3487e2ddca771954c49f2b6c27e9b9ba846275 | linbeta/Day-18_Hirst-painting | /color_extract.py | 325 | 3.578125 | 4 | # =====This part is using colorgram to extract colors from the image. ====#
import colorgram
colors = colorgram.extract("brighter_dots.jpg", 60)
color_list = []
for color in colors:
new_color = color.rgb
r = new_color[0]
g = new_color[1]
b = new_color[2]
color_list.append((r, g, b))
print(color_list)
|
cbb6879b1460c1acaad976391148d545c1bfd69b | 425776024/Learn | /pyoop/3/2.py | 783 | 3.625 | 4 | class Fjs(object):
def __init__(self, name):
self.name = name
def hello(self):
print("said by : ", self.name)
def __getattr__(self, item):
print("访问了特性1:" + item)
return None
raise AttributeError
def __setattr__(self, key, value):
print("访问了特性2:" + key)
self.__dict__[key] = value
def __getattribute__(self, item):
print("访问了特性3:" + item)
return object.__getattribute__(self, item)
fjs = Fjs("fjs")
print(fjs.name )
print('-------------1-------')
fjs.hello()
print('--------------2------')
fjs.bb
"""
访问了特性:name
fjs
---------------2-----
访问了特性:hello
访问了特性:name
said by : fjs
""" |
ffaef098cafd8b66bfc98b8f647d8be0b7ee8c74 | ari10000krat/checkio | /Home/Between Markers.py | 1,898 | 3.625 | 4 | def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
start_index = 0 if text.rfind(begin) == -1 else text.find(begin) + len(begin) # End of the first sepatrator
end_index = len(text) if text.find(end) == -1 else text.find(end) # Begin of the second separator
return text[start_index:end_index]
# def bigger_price(limit, data):
# return sorted(data, key=lambda x: x['price'], reverse=True)[:limit]
#
# def between_markers(text: str, begin: str, end: str) -> str:
# if text.find(begin) > text.find(end) > -1:
# return ''
# return text.split(begin)[-1].split(end)[0]
if __name__ == '__main__':
print('TEST #1 : ',between_markers("<head><title>My new site</title></head>",
"<title>", "</title>"))
print('TEST #2 : ',between_markers('What is >apple<', '>', '<'))
print('TEST #3 : ',between_markers('No[/b] hi', '[b]', '[/b]'))
print('TEST #4 : ',between_markers('What is >ap ple<', '>', '<'))
print('TEST #5 : ',between_markers('No [b]hi', '[b]', '[/b]'))
print('TEST #6 : ',between_markers('No hi', '[b]', '[/b]'))
print('TEST #7 : ',between_markers('No <hi>', '>', '<'))
# These "asserts" are used for self-checking and not for testing
assert between_markers("<head><title>My new site</title></head>",
"<title>", "</title>") == "My new site", "HTML"
assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
print('Wow, you are doing pretty good. Time to check it!')
|
7759642ea2e197004bb0ce8585b3d654771f45ac | Vitoria0/Notepad | /Observações-05.py | 2,146 | 4.3125 | 4 | # Interactive Help
#Ele explica como funciona e os valores de determinada função
help(print)
print('\n')
#Outra maneira seria
print(input.__doc__)
print('\n')
###
#Docstrings
def contador(i, f, p):
"""
-> Faz uma contagem e mostra na tela
:param i: Inicio da contagem
:param f: Fim da contagem
:param p: Passo da contagem
:return: Sem retorno
Função criada por nick
"""
c = i
while c <= f:
print(f'{c} ', end='')
c += p
#-----Programa principal
contador(2, 20, 2)
print('\n')
help(contador)
print('\n')
###
#Parâmetros Opcionais
def somar(a=0, b=0, c=0):
"""
-> Faz a soma de três valores e mostra o resultado na tela
:param a: O primeiro valor
:param b: O segundo valor
:param c: O terceiro valor
:return: Sem retorno
"""
s = a + b + c
print(f'A soma vale {s}')
#------Programa Principal
somar(3, 2, 5)
somar(7, 7)
somar(9)
somar()
print('\n')
###
#Escopo de Variáveis
def teste():
x = 8 #--- 'X' Tem um escopo local, pois vale apenas na função
print(f'Na função teste, n vale {n}')
print(f'Na função teste, x vale {x}')
#------Programa Principal
n = 2 #--- 'N' Tem um escopo global pois foi criado fora da função e pode ser citada dentro dela
print(f'No programa principal n vale {n}')
teste()
# print(f'No programa principal, x vale {x}') ----Dá erro
print('\n')
###
#Escopo Local
def teste(b):
global a #--- Não crie uma nova variável 'a'
a = 8 #--- Cria uma variavel a local
b += 4
c = 2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
#------Programa Principal
#Escopo Global
a = 5
print(f'A fora vale {a}')
teste(a)
print(f'Agora "A" fora vale {a}')
print('\n')
###
#Retornando Valores
def soma(a=0, b=0, c=0):
"""
-> Faz a soma de três valores e mostra o resultado na tela
:param a: O primeiro valor
:param b: O segundo valor
:param c: O terceiro valor
:return: Sem retorno
"""
s = a + b + c
return s
r1 = soma(3, 2, 5)
r2 = soma(18, 61)
r3 = soma(99, -81)
print(f'As somas deram {r1}, {r2} e {r3}') |
14e538c13f09a95da8ff8324f72396e423e11342 | Gameatron/python-things | /CS1/Conditionals/human_age_v2_robertst.py | 612 | 4.21875 | 4 | def human_age(age):
if age < 1:
term = 'baby'
if age < 3:
term = 'toddler'
elif age < 5:
term = 'preschooler'
elif age < 9:
term = 'child'
elif age < 13:
term = 'preteen'
elif age < 19:
term = 'teen'
elif age < 40:
term = 'young adult'
elif age < 65:
term = 'adult'
else:
term = 'elderly'
print(f'A human {age} years old is usually called "{term}"')
def main():
age = float(input("Please enter an age: "))
human_age(age)
if __name__ == "__main__":
main() |
7c9c1b02e24cd85fad64c3e55601d6cb1555a8fc | theusouza0/Python | /while.py | 698 | 4.15625 | 4 | #3. Crie um programa que solicite o código do produto e a quantidade, calcule e exiba o total do item, então solicite novamente código e quantidade até que o usuário digite 0 (zero). Então exiba o total da compra.
#Entrada
valor = 0
soma = 0
print("Mercado!")
#Processamento e saída
while True:
code = int(input("\nDigite o código do produto:\nPara sair Digite \"0\"!\n"))
if(code == 0):
print("\n\nO total foi de R${:.2f}".format(soma))
break
else:
valor = float(input("Digite o preço do produto de código {}: ".format(code)))
quantia = int(input("Digite a quantidade do produto: "))
soma = soma + (valor * quantia) |
7a1ddf7761be3ca035dc1964de2c1a3ca8d3dd2c | kudoyoshihiro10xx/09_dict_practice | /fruits.py | 505 | 3.859375 | 4 | # 辞書を定義
fruits_dict= {"りんご":"Apple",
"ぶどう":"Grape",
"みかん":"Orange"}
# print(fruits["りんご"])
# print(fruits["ぶどう"])
# print(fruits["みかん"])
# Keyだけforループ
for jp_name in fruits_dict.keys():
print(jp_name)
# Valueだけforループ
for en_name in fruits_dict.values():
print(en_name)
# KeyとValueを同時にforループ
for jp_name, en_name in fruits_dict.items():
print(f"{jp_name}は英語で{en_name}")
|
7a3bdc49947b11dc4b79cb7367284e0fd6c428d4 | thanhtuan18/anthanhtuan-fundametal-c4e15 | /Session2/change_color.py | 359 | 3.546875 | 4 | # from turtle import *
#
# speed (0)
#
# color ("green")
# forward (100)
# color ("red")
# forward (100)
#
# mainloop ()
from turtle import *
speed (0)
width (5)
for i in range (3):
color ("red")
forward (20)
penup ()
forward (20)
pendown ()
color ("blue")
forward (20)
penup ()
forward (20)
pendown ()
mainloop ()
|
9c789ae02a7e203f95cd9219ceaaf91816083d10 | sethmnielsen/optimization-techniques | /lectures/prob.py | 1,485 | 3.53125 | 4 | """
The provided function takes in a vector x of length 3
and returns a scalar objective f to be minimized,
a vector of constraints c to be enforced as c <= 0,
a vector gf containing the gradients of f,
and a matrix gc containing the gradients of the constraints
\[gc[i, j] = partial c_i / partial x_j].
In addition to the nonlinear constraints, you should also
enforce the constraint that x >= 0.
The deterministic optimum of this problem is:
x^* = [0.06293586, 2.91716569, 0.07491246], f^*=1.158963
Using the simplified reliability-based optimization methodology
discussed in the text, find the reliable optimum under the
assumption that the inputs are normally distributed and have
a standard deviation of
sigma_1 = 0.01, sigma_2 = 0.1, sigma_3 = 0.05.
Each constraint should be satisfied with a target
reliability of 99.5%.
Briefly describe the how/why of your approach
and turn in your code.
"""
import numpy as np
def prob(x):
f = -x[1]*x[2]*x[3] + [x[2] - 4]^2 + 10*x[1]^3*x[3]
c = np.zeros(2, 1)
c[1] = 2*x[1]^2 + x[2] + x[3] - 3.0
c[2] = -2*x[1] - 4*x[2]*x[3] + 1.0
gf = np.zeros(3, 1)
gf[1] = -x[2]*x[3] + 30*x[1]^2*x[3]
gf[2] = -x[1]*x[3] + 2*[x[2] - 4]
gf[3] = -x[1]*x[2] + 10*x[1]^3
gc = np.zeros(2, 3)
gc[1, 1] = 4*x[1]
gc[1, 2] = 1.0
gc[1, 3] = 1.0
gc[2, 1] = -2.0
gc[2, 2] = -4*x[3]
gc[2, 3] = -4*x[2]
return f, c, gf, gc |
2656dd060642d9d95ab86a4c5f0ca63cb0bc0d16 | joswha/interviewpreparation | /coding-interview-university/DataStructures/Array/array.py | 1,921 | 4.125 | 4 | # Implement a vector (mutable array with automatic resizing):
# Practice coding using arrays and pointers, and pointer math to jump to an index instead of using indexing.
# New raw data array with allocated memory
# can allocate int array under the hood, just not use its features
# start with 16, or if starting number is greater, use power of 2 - 16, 32, 64, 128
# size() - number of items
# is_empty()
# at(index) - returns item at given index, blows up if index out of bounds
# push(item)
# insert(index, item) - inserts item at index, shifts that index's value and trailing elements to the right
# prepend(item) - can use insert above at index 0
# pop() - remove from end, return value
# delete(index) - delete item at index, shifting all trailing elements left
# remove(item) - looks for value and removes index holding it (even if in multiple places)
# find(item) - looks for value and returns first index with that value, -1 if not found
# resize(new_capacity) // private function
# when you reach capacity, resize to double the size
# when popping an item, if size is 1/4 of capacity, resize to half
def size(arr):
return len(arr)
def is_empty(arr):
return len(arr) == 0
def at(arr, index):
return arr[index]
def push(arr, value):
arr.append(value)
def insert(arr, index, val):
arr.insert(index, val)
def prepend(arr, value):
insert(arr, 0, value)
def pop(arr):
arr.remove(len(arr) - 1)
return arr[len(arr) - 1]
def delete(arr, index):
arr.remove(arr[index])
def remove(arr, value):
for i in arr:
if i == value:
arr.remove(i)
def find(arr, value):
for i in range(0, len(arr)):
if arr[i] == value:
return i
return -1
arr = [1,2,3,2,5]
# insert(arr, 1, 5)
# prepend(arr, 4)
# delete(arr, 1)
# remove(arr, 2)
print(find(arr, 3)) |
ec5808be9b9cc327035a1baaa03319308fbccbd3 | AhmedRaja1/Python-Beginner-s-Starter-Kit | /Code only/4- Functions/Debugging.py | 147 | 3.90625 | 4 | def product(*numbers):
total = 1
for number in numbers:
total *= number
return total
result = product(1, 2, 3)
print(result)
|
6faad19f1a12ad65e79c213424e7604134ddd257 | mehulchopradev/bryan-python | /evennos.py | 308 | 3.78125 | 4 | n = int(input('Enter n : '))
i = 0
# while loop
'''while i <= n:
if not i % 2:
print(i)
i = i + 1'''
# for loop
'''
for v in <<sequence of elements>>:
I1
I2
I3
'''
# 0 to n
# range(0, n + 1)
'''for v in range(n+1):
if not v % 2:
print(v)'''
for v in range(0, n + 1, 2):
print(v) |
6156adfa7c2427998aa29d4a5cc83171c75f43a5 | ghostrider77/improve_coding_skills | /Python/algorithmic_toolbox/12_maximizing_revenue.py | 561 | 3.578125 | 4 | import sys
def convert_to_intlist(line):
return [int(elem) for elem in line.split()]
def calc_maximal_revenue(profit_per_click, average_click):
revenue = 0
for p, a in zip(sorted(profit_per_click), sorted(average_click)):
revenue += p * a
return revenue
def main():
data = sys.stdin.read().splitlines()
profit_per_click = convert_to_intlist(data[1])
average_click = convert_to_intlist(data[2])
result = calc_maximal_revenue(profit_per_click, average_click)
print(result)
if __name__ == "__main__":
main()
|
64e2f03d28cf9cc7700a693a7509b0c726baf9e9 | J-AugustoManzano/livro_Python | /ExerciciosAprendizagem/Cap08/c08ex03.py | 626 | 3.984375 | 4 | a = []
s = 0
print("Somatório de valores informados")
# Entrada de dados
i = 0
resp = 'S';
while (resp.upper() == 'S'):
a.append(float(input("\nEntre o {0:3}o. valor: ".format(i + 1))))
s += a[i]
i += 1
print()
print("Deseja continuar? ")
resp = input("Tecle [S] para SIM / qualquer caractere para NAO: ")
# Apresentação dos dados
print()
for i in range(len(a)):
print("A[{0:3}] = {1:8,.2f} na posição {2:3}.".format(i + 1, a[i], i))
print()
print("Soma dos valores informados = {0:8,.2f}".format(s))
enter = input("\nPressione <Enter> para encerrar... ")
|
c411105b1bc50f85ea3862065b8b70636d5823e3 | Kalia3/Scrapping-py | /assingment 13(b) (scraping data on web page).py | 979 | 3.703125 | 4 | ''' Scraping in (http://py4e-data.dr-chuck.net/comments_1003519.html) this
URL and find the sum of no. in this web page. '''
import urllib.request, urllib.parse, urllib.error #imported for getting on web(socket or connection)
from bs4 import BeautifulSoup #for reading html on web page
y = 0
url = input("Enter url- ") #http://py4e-data.dr-chuck.net/comments_1003519.html
html = urllib.request.urlopen(url).read()
print(html)
soup = BeautifulSoup(html,"html.parser") # to make htlm organised and read-able
print(soup)
tags = soup("span") # makes seperate list of this specific tag with data we want
print(tags)
for tag in tags :
z = tag
for x in z :
y = y + int(x)
print(y)
# to make dictionary of words with with counting(which name comes how many times)
'''d = dict()
tags = soup("tr")
for tag in tags :
q = tag.contents[0]
for k in q :
d[k] = d.get(k,0) + 1
print(d)'''
|
56166119c4f1819612aab742eac338301422a34b | sethhardik/language-model-machine-learning | /code.py | 2,940 | 3.875 | 4 | import numpy as np
from keras.models import Sequential
from keras.layers import Dense,LSTM,Embedding
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
data = """ Jack and Jill went up the hill\n
To fetch a pail of water\n
Jack fell down and broke his crown\n
And Jill came tumbling after\n """
#object of tokenizer class created
tokenizer=Tokenizer()
#data fitted by tokenizer
tokenizer.fit_on_texts([data])
#encoded_data stores the value of repeated score of the word 1= highly repeated 21= least repeated
encoded_data=tokenizer.texts_to_sequences([data])[0]
print(encoded_data)
''' Data Formation
calculate the vocab size
tokenizer.word_size gives dictionary of words corresponidng to the there label no.
eg: "and" is repeated most in the data and thus it has label 1
now the list will be created containing current word and next word. this list will be fed into the neural network
and training will be done on the list created
list format ----> [current word :next word]'''
vocab_size=len(tokenizer.word_index)+1
print(vocab_size)
word_sequence=[] #list_word_sequence created
for i in range(1,len(encoded_data)):
sequence=encoded_data[i-1:i+1] #saving encoder current word and next word in sequence variable
word_sequence.append(sequence)
word_sequence=np.array(word_sequence) #converting list into array
print(word_sequence)
'''# Splitting of Data
now we have generated data in right format and now we can use the data to in our ML model
'''
x_train,y_train = word_sequence[:,0],word_sequence[:,1] #slicing coloumn of the array into x_train and y_train
print(f"x_train:{x_train} \ny_train:{y_train}") #print statement
#converting categorical data to numerical data using one hot encoding
#The binary variables are often called “dummy variables"
y_train=to_categorical(y_train,num_classes=vocab_size)
model=Sequential()
model.add(Embedding(vocab_size,10,input_length=1))
model.add(LSTM(70))
model.add(Dense(vocab_size,activation="softmax"))
model.compile(loss="categorical_crossentropy",optimizer="adam",metrics=["accuracy"])
print(model.summary())
model.fit(x_train,y_train,epochs=500,verbose=1)
x_test=input("enter word whose next word you wanna predict:")
no_next_word=int(input("enter no. of predictions you want:"))
#in_test variable created to prevent chnages form testing element. can be ignored and changes can be done directly
#on the x_test
in_test,next_word=x_test,x_test
print(f"entered word:{x_test}")
for i in range(no_next_word):
print(i)
out_word=""
encoded_test=tokenizer.texts_to_sequences([in_test])[0]
encoded_test=np.array(encoded_test)
#prediction:
y_predict=model.predict_classes(encoded_test,verbose=0)
for word, index in tokenizer.word_index.items():
if y_predict==index:
out_word=word
break
in_test=out_word
print(f"predicted next words:{out_word}")
|
cc2a4a7fde59ac9f34faba40c40ac4bd08d5a71c | MD-AZMAL/python-programs-catalog | /Data-Structures/graphs/kruskal.py | 3,556 | 3.5 | 4 | """ Author - Sidharth Satapathy """
""" This code is in python 3 """
class Vertex(object):
def __init__(self,name):
self.name = name
self.node = None
class Node(object):
def __init__(self,height,nodeId,parentNode):
self.height = height
self.nodeId = nodeId
self.parentNode = parentNode
class Edge(object):
def __init__(self,weight,start,end):
self.weight = weight
self.startVertex = start
self.targetVertex = end
def __cmp__(self,otherEdge):
return self.cmp(self.weight, otherEdge.weight)
def __lt__(self,otherEdge):
selfPriority = self.weight
otherPriority = otherEdge.weight
return selfPriority < otherPriority
class DisjointSet(object):
def __init__(self,vertexList):
self.vertexList = vertexList
self.rootNodes = []
self.nodeCount = 0
self.setCount = 0
self.makeSets(vertexList)
def find(self,node):
currentNode = node
while currentNode.parentNode is not None:
currentNode = currentNode.parentNode
root = currentNode
currentNode = node
while currentNode is not root:
temp = currentNode.parentNode
currentNode.parentNode = root
currentNode = temp
return root.nodeId
def merge(self,node1,node2):
index1 = self.find(node1)
index2 = self.find(node2)
if index1 == index2:
return # They are in the same set
root1 = self.rootNodes[index1]
root2 = self.rootNodes[index2]
if root1.height < root2.height:
root1.parentNode = root2
elif root1.height > root2.height:
root2.parentNode = root1
else:
root1.parentNode = root2
root2.height = root2.height+1
def makeSets(self, vertexList):
for v in vertexList:
node = Node(0,len(self.rootNodes),None)
v.node = node
self.rootNodes.append(node)
self.setCount = self.setCount + 1
self.nodeCount = self.nodeCount + 1
class Kruskal(object):
def spanningTree(self,vertexList,edgeList):
spanning = []
disjoint = DisjointSet(vertexList)
edgeList.sort()
for edge in edgeList:
u = edge.startVertex
v = edge.targetVertex
if disjoint.find(u.node) is not disjoint.find(v.node):
spanning.append(edge)
disjoint.merge(u.node,v.node)
for edge in spanning:
print (edge.startVertex.name," -> ",edge.targetVertex.name)
vertex1 = Vertex("a")
vertex2 = Vertex("b")
vertex3 = Vertex("c")
vertex4 = Vertex("d")
vertex5 = Vertex("e")
vertex6 = Vertex("f")
edge1 = Edge(2,vertex1,vertex2)
edge2 = Edge(4,vertex1,vertex4)
edge3 = Edge(4,vertex2,vertex3)
edge4 = Edge(4,vertex2,vertex4)
edge5 = Edge(3,vertex2,vertex5)
edge6 = Edge(1,vertex2,vertex6)
edge7 = Edge(5,vertex3,vertex6)
edge8 = Edge(2,vertex4,vertex5)
edge9 = Edge(5,vertex5,vertex6)
vertexList = []
vertexList.append(vertex1)
vertexList.append(vertex2)
vertexList.append(vertex3)
vertexList.append(vertex4)
vertexList.append(vertex5)
vertexList.append(vertex6)
edgeList = []
edgeList.append(edge1)
edgeList.append(edge2)
edgeList.append(edge3)
edgeList.append(edge4)
edgeList.append(edge5)
edgeList.append(edge6)
edgeList.append(edge7)
edgeList.append(edge8)
edgeList.append(edge9)
algorithm = Kruskal()
algorithm.spanningTree(vertexList, edgeList)
|
1e503308a39bf605ae491406f4e66c67a562a5b8 | joseck12/blog | /tests/test_user.py | 701 | 3.578125 | 4 | import unittest
from app.models import User
from app import db
#the setup method creates an instances of our user
class UserModelTest(unittest.TestCase):
def setUp(self):
self.new_user = User(username = 'joseck',password = 'qwerty', email = 'jogachi4@gmail.com')
def save_user(self):
db.session.add(self.new_user)
db.session.commit()
def test_password_setter(self):
self.assertTrue(self.new_user.pass_secure is not None)
def test_no_access_password(self):
with self.assertRaises(AttributeError):
self.new_user.password
def test_password_verification(self):
self.assertTrue(self.new_user.verify_password('qwerty'))
|
162b66a26d08323ad2b6d856e3c8bb1735d293a7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/schdan037/question4.py | 1,008 | 3.953125 | 4 | """Daniel Schwartz
question 4
april 2014"""
# used for math functions inout by user
import math
def main():
"""main,
receives input and prints out graph of function"""
f = input("Enter a function f(x):\n")
#nest for loop generates x, y values in ranges of graph
for y in range(-10, 11):
for x in range(-10, 11):
y_real = - eval(f)
if y == round(y_real):
# puts o at graph point
print("o", end="")
elif (x == 0) and (y == 0):
# puts a + in the centre
print("+", end="")
elif x == 0:
# puts a | at the y axis
print("|", end="")
elif y == 0:
# puts a - at the x axis
print("-", end="")
else:
# fills empty spaces
print(" ", end="")
print() # new line
# runs main on entry
if __name__ == '__main__':
main() |
befc36c5dfef12a8840347ebe5d8aca666bdef55 | Jimmyopot/JimmyLeetcodeDev | /data_structures/binary_trees.py | 6,804 | 4 | 4 | '''
- Tree represents the nodes connected by edges.
- It is a non-linear data structure.
- It has the following properties.
# One node is marked as Root node.
# Every node other than the root is associated with one parent node.
# Each node can have an arbiatry number of chid node.
- Search for a value in a Binary tree:
# Searching for a value in a tree involves comparing the incoming value with the value exiting nodes.
# Here also we traverse the nodes from left to right and then finally with the parent.
# If the searched for value does not match any of the exitign value, then we return not found message else the found message is returned.
'''
# example 1
# creating root node
class Node:
def __init__(self, data):
self.left = None # Left Child
self.right = None # Right Child
self.data = data # Node Data
# inserting into a tree
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data) # recursion
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# search for value in a binary tree.
# findval method to compare the value with nodes
def findval(self, search_val):
if search_val < self.data:
if self.left is None:
return str(search_val) + " Not Found"
return self.left.findval(search_val)
elif search_val > self.data:
if self.right is None:
return str(search_val) + " Not Found"
return self.right.findval(search_val)
else:
print(str(self.data) + " Found!")
# function to print tree
def printTree(self):
if self.left:
self.left.printTree()
print(self.data),
if self.right:
self.right.printTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(16)
root.insert(3)
root.printTree()
print(root.findval(1))
print(root.findval(14))
# example 2 [TREE TRAVERSAL]
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root) # initializes root node
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "")
elif traversal_type == "inorder":
return self.inorder_print(tree.root, "")
elif traversal_type == "postorder":
return self.postorder_print(tree.root, "")
else:
print("Traversal type " + str(traversal_type) + " is not supported")
return False
# depth-first search / pre-order traversal
def preorder_print(self, start, traversal):
# Root -> left -> right
if start:
traversal += (str(start.value) + "_")
traversal = self.preorder_print(start.left, traversal) # remember this is RECURSION(calling func in itself)
traversal = self.preorder_print(start.right, traversal) # remember this is RECURSION(calling func in itself)
return traversal
# depth-first search / in-order traversal
def inorder_print(self, start, traversal):
# Left -> root -> right
if start:
traversal = self.inorder_print(start.left, traversal) # remember this is RECURSION(calling func in itself)
traversal += (str(start.value) + "_")
traversal = self.inorder_print(start.right, traversal) # remember this is RECURSION(calling func in itself)
return traversal
# depth-first search / post-order traversal
def postorder_print(self, start, traversal):
# Left -> right -> root
if start:
traversal = self.inorder_print(start.left, traversal) # remember this is RECURSION(calling func in itself)
traversal = self.inorder_print(start.right, traversal) # remember this is RECURSION(calling func in itself)
traversal += (str(start.value) + "_")
return traversal
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3) # 1
tree.root.left.left = Node(4) # / \
tree.root.left.right = Node(5) #2 3
tree.root.right.left = Node(6) #/ \ / \
tree.root.right.right = Node(7) #4 5 6 7
tree.root.right.right.right = Node(8) # \
# 8
print(tree.print_tree("preorder"))
# 1_2_4_5_3_6_7_8_
print(tree.print_tree("inorder"))
# 4_2_5_1_6_3_7_8_
print(tree.print_tree("postorder"))
# 4_2_5_6_3_7_8_1_
# example 3
# run time: log2(n)
class Node2:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class binary_tree2:
def __init__(self):
self.root = None
def add(self, current, value):
if root is None:
self.root = Node2(value)
else:
if value < current.value:
if current.left == None:
current.left = Node2(value)
else:
self.add(self.left, value) # recursion
else:
if current.right == None:
current.right = Node2(value)
else:
self.add(self.right, value) # recursion
def visit(self, node):
print(node.value)
# preorder search
def preorder(self, current):
# root -> left -> rigth
self.visit(current) # starts as root node
self.preorder(current.left) #recursion
self.preorder(current.rigth) #recursion
# inorder search
def inorder(self, current):
# left -> root -> rigth
self.inorder(current.left) #recursion, starts as left node
self.visit(current) # root node
self.inorder(current.rigth) #recursion
# postorder search
def postorder(self, current):
# left -> right -> root
self.preorder(current.left) #recursion, starts as left node
self.preorder(current.rigth) #recursion
self.visit(current) # root node
|
2e5547151fa0f906a303a163257ebda103d5dddd | wttttt-wang/leetcode_withTopics | /Backtracking/gray-code*.py | 529 | 3.671875 | 4 | """
Gray Code
@ Backtracking: Get results[n = 3] from results[n = 2] : [00, 01, 11, 10] --> [000, 001, 011, 010, 110, 111, 101, 100]
@ Also see: 'math/gray-code'
"""
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n < 0:
return []
results = [0]
added = 1
for i in range(n):
results += [added + results[j] for j in range(len(results) - 1, -1, -1)]
added <<= 1
return results
|
7ba3d15de5c18eb40f5772c186962e9bb7ffca4c | Shandris1/QAC-work-Python | /Python/AddingClasses.py | 305 | 3.625 | 4 | class Replicate():
"""docstring for Replicate"""
def __init__(self, A=0, B=0, C=0):
self.a = A
self.b = B
self.c = C
def __add__(self, other):
print("2+2")
return self.a * other.a
china = Replicate(5)
japan = Replicate(7)
print(china + japan)
6 + 4
|
d89f58d25346278cf9d153f29a82bae8b6c2e39a | ThiagoCComelli/URI-Online-Judge | /URI-py/1154.py | 176 | 3.515625 | 4 | # -*- coding: utf-8 -*-
qtde = 0
soma = 0
while True:
n = int(input())
if n >= 0:
soma += n
qtde += 1
else:
break
print("%.2f"%(soma/qtde))
|
4bcc1ededfc4a0f4221fb8bea994cc418fb5ae65 | HarunErenMutlu/reflexiveTransitiveClosureAlgorithm | /reflexiveTransitiveClosureAlgorithm.py | 3,717 | 3.609375 | 4 | import itertools
def createSet(sampleSet):
newSet = set()
for i in sampleSet:
newSet.add(i)
return newSet
def make_it_reflexive(alphabet,relation):
newSet = createSet(relation)
for i in alphabet:
newSet.add((i,i))
return newSet
def findAllTuplesOfIndex(index, alphabet):
tupleOfIndex = set()
for element in itertools.product(alphabet, repeat=index):
tupleOfIndex.add(element)
return list(tupleOfIndex)
def algorithm1(alphabet,relation):
reflexive_closure = set()
alphabet = list(alphabet)
for index in range(len(alphabet)):
tupleLength = index+1
for tuple in findAllTuplesOfIndex(tupleLength, alphabet):
if tupleLength == 1:
reflexive_closure.add((tuple[0], tuple[0]))
elif tupleLength == 2:
if (tuple[0], tuple[1]) in relation:
reflexive_closure.add((tuple[0], tuple[1]))
else:
indexOfTraversing = 0
done = False
# traversing tuple with double indexing
while indexOfTraversing+1 != tupleLength:
if (tuple[indexOfTraversing], tuple[indexOfTraversing+1]) in reflexive_closure:
# we cannot create a tuple with last index and null(lastIndex,null)
if indexOfTraversing+1 == tupleLength - 1:
done = True
break
indexOfTraversing += 1
# it breaks the path
else:
break
if done:
reflexive_closure.add((tuple[0], tuple[tupleLength - 1]))
return reflexive_closure
def algorithm2(alphabet,relation):
newSet = make_it_reflexive(alphabet,relation)
list_alphabet = sorted(list(alphabet))
i,j,k = 0,0,0
while(i < len(list_alphabet)):
j = 0
while (j < len(list_alphabet)):
k = 0
while (k < len(list_alphabet)):
if ((list_alphabet[i],list_alphabet[j]) in newSet
and (list_alphabet[j],list_alphabet[k]) in newSet
and (list_alphabet[i],list_alphabet[k]) not in newSet ):
newSet.add((list_alphabet[i], list_alphabet[k]))
i,j,k= 0,0,0
else: k+=1
j+=1
i+=1
return newSet
def algorithm3(alphabet,relation):
newSet = make_it_reflexive(alphabet,relation)
for j in alphabet:
for i in alphabet:
for k in alphabet:
if((i,j) in newSet and (j,k) in newSet and (i,k) not in newSet):
newSet.add((i,k))
return newSet
def getAlphabeth():
givenInput = input("Please enter member of alphabets with commas, (For example: 1,2,3,4,5) :")
return set(givenInput.split(","))
def getSample():
relation = input("Please enter relations with a space (For example: 1,2 2,3 3,5) :")
relationList = relation.split(" ")
relations = set()
for i in relationList:
relations.add(tuple(i.split(",")))
return set(relations)
def main():
print("Welcome to Reflexive Closure Algorithm Program")
alphabet = getAlphabeth()
sample = getSample()
print("Result for first algorithm is: ")
print(sorted(list(algorithm1(alphabet,sample))))
print("Result for second algorithm is: ")
print(sorted(list(algorithm2(alphabet,sample))))
print("Result for third algorithm is: ")
print(sorted(list(algorithm3(alphabet,sample))))
main() |
5506ac587b3f24393a0a2f35164aa152ea2336e4 | Nagajothikp/Nagajothi | /s31.py | 210 | 3.65625 | 4 | x=input("Enter a braces:")
count1=0
count2=0
for i in x:
if i =='(':
count1=count1 +1
else:
count2=count2 +1
if(count1==count2):
print("yes")
else:
print("no")
|
67f4979670771b1e292848ea3894af32426132cb | golubitsky/exercism-solutions | /python/rna-transcription/rna_transcription.py | 306 | 3.5625 | 4 | def to_rna(dna_strand):
convert = {
'G':'C',
'C':'G',
'T':'A',
'A':'U'
}
if any(char not in convert for char in dna_strand):
raise ValueError(f"Can only convert {convert.keys()}")
return "".join(list(map(lambda char:convert[char], dna_strand))) |
3927c9ed10e0326144c6d41144159b7009f2eb96 | SamCadet/PythonScratchWork | /my_car.py | 371 | 3.96875 | 4 | ''' p. 175 The import statement at u tells Python to open the car module and
import the class Car. Now we can use the Car class as if it were defined in
this file. The output is the same as we saw earlier: '''
from car import Car
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
|
3d7bc8eb1802fd5231730b89782f80047bcde73f | sergio-ruano27/201612203-Cortos980 | /Corto1/collatz.py | 273 | 3.953125 | 4 | #SERGIO ESTUARDO RUANO NAJARRO
#201612203
def collatz(num):
while(num != 1):
if(num %2> 0):
num = 3*num +1
yield num
else:
num = num/2
yield num
n=203
for i in range(2,n):
print(list(collatz(i)))
|
93c3aacf8a59fea767925f247a09490c75b58c2b | Jeffery-Zhou/URLeapMotion | /threadstu.py | 397 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
import threading, time
def fun1():
while True:
time.sleep(2)
print("fun1")
def fun2():
while True:
time.sleep(6)
print("fun2")
threads = []
threads.append(threading.Thread(target=fun1))
threads.append(threading.Thread(target=fun2))
print(threads)
if __name__ == '__main__':
for t in threads:
print(t)
t.start() |
37221df1c2b2d185b0cffc2ad58baaf8f80ec45d | sarthak77/practice | /word/line_and_page_break.py | 569 | 3.65625 | 4 | """
To add a line break (rather than starting a whole new paragraph), you
can call the add_break() method on the Run object you want to have
the break appear after. If you want to add a page break instead, you
need to pass the value docx.text.WD_BREAK.PAGE as a lone argument to
add_break(), as is done in the middle of the following example:
"""
import docx
doc = docx.Document()
doc.add_paragraph('Thi is on the first page!')
#error
doc.paragraphs[0].runs[0].add_break(docx.text.WD_BREAK.PAGE)
doc.add_paragraph('This is on the second page!')
doc.save('twoPage.docx') |
8dcbf055ce4dc5e5561df8075c16c2f7e8c337aa | patpalmerston/Data-Structures | /binary_search_tree/binary_search_tree.py | 10,142 | 3.921875 | 4 | import sys
sys.path.append('../doubly_linked_list')
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have a next node it is point to."""
def insert_after(self, value):
current_next = self.next
self.next = ListNode(value, self, current_next)
if current_next:
current_next.prev = self.next
"""Wrap the given value in a ListNode and insert it
before this node. Note that this node could already
have a previous node it is point to."""
def insert_before(self, value):
current_prev = self.prev
self.prev = ListNode(value, current_prev, self)
if current_prev:
current_prev.next = self.prev
"""Rearranges this ListNode's previous and next pointers
accordingly, effectively deleting this ListNode."""
def delete(self):
if self.prev:
self.prev.next = self.next
if self.next:
self.next.prev = self.prev
"""Our doubly-linked list class. It holds references to
the list's head and tail nodes."""
class DoublyLinkedList: # dont have to have this
def __init__(self, node=None):
self.head = node
self.tail = node
self.length = 1 if node is not None else 0
## most expensive source is us, then computation, memory, storage
## dont need max, min, etc but have power to add them if needed
def __len__(self):
return self.length
"""Wraps the given value in a ListNode and inserts it
as the new head of the list. Don't forget to handle
the old head node's previous pointer accordingly."""
def add_to_head(self, value):
new_node = ListNode(value, None, None)
self.length += 1
##if list is empty
if not self.head and not self.tail:
self.head = new_node
self.tail = new_node
else:
#replace head; new_node = self.head
# next and prev are the pointers and the bucket
# putting a ref to our new node in the bucket
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
"""Removes the List's current head node, making the
current head's next node the new head of the List.
Returns the value of the removed Node."""
def remove_from_head(self):
value = self.head.value
self.delete(self.head)
return value
"""Wraps the given value in a ListNode and inserts it
as the new tail of the list. Don't forget to handle
the old tail node's next pointer accordingly."""
def add_to_tail(self, value):
new_node = ListNode(value, None, None)
self.length += 1
##if list is empty
if not self.head and not self.tail:
self.head = new_node
self.tail = new_node
else:
#replace head; new_node = self.head
# next and prev are the pointers and the bucket
# putting a ref to our new node in the bucket
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
"""Removes the List's current tail node, making the
current tail's previous node the new tail of the List.
Returns the value of the removed Node."""
def remove_from_tail(self):
value = self.tail.value
self.delete(self.tail)
return value
"""Removes the input node from its current spot in the
List and inserts it as the new head node of the List."""
def move_to_front(self, node):
if node is self.head:
return
value = node.value
self.delete(node)
self.add_to_head(value)
"""Removes the input node from its current spot in the
List and inserts it as the new tail node of the List."""
def move_to_end(self, node):
if node is self.tail:
return
value = node.value
self.delete(node)
self.add_to_tail(value)
"""Removes a node from the list and handles cases where
the node was the head or the tail"""
def delete(self, node):
# handles meta data of head, tail and etc link list
if not self.head and not self.tail:
#this shouldnt happen, handle error
return
self.length -= 1
if self.head is self.tail:
# is means are they the exact same thing
self.head = None
self.tail = None
elif self.head is node:
self.head = node.next
node.delete()
elif self.tail is node:
self.tail = node.prev
node.delete()
else:
node.delete()
"""Returns the highest value currently in the list"""
def get_max(self):
if not self.head:
return None
max_val = self.head.value
current = self.head
while current:
if current.value > max_val:
max_val = current.value
current = current.next
return max_val
class Queue:
def __init__(self):
self.size = 0
# Why is our DLL a good choice to store our elements?
self.storage = DoublyLinkedList()
def enqueue(self, value):
self.size += 1
return self.storage.add_to_tail(value)
def dequeue(self):
if self.size is 0:
return
else:
self.size -= 1
return self.storage.remove_from_head()
def len(self):
return self.size
class Stack:
def __init__(self):
self.size = 0
# Why is our DLL a good choice to store our elements?
self.storage = DoublyLinkedList()
def push(self, value):
self.size += 1
return self.storage.add_to_head(value)
def pop(self):
if self.size is 0:
return
else:
self.size -= 1
return self.storage.remove_from_head()
def len(self):
return self.size
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
if self.value:
if value < self.value:
if self.left is None:
self.left = BinarySearchTree(value)
else:
self.left.insert(value)
elif value > self.value:
if self.right is None:
self.right = BinarySearchTree(value)
else:
self.right.insert(value)
else:
self.value = value
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
if self.value == target:
return True
elif target < self.value and self.left:
return self.left.contains(target)
elif target > self.value and self.right:
return self.right.contains(target)
return False
# Return the maximum value found in the tree
def get_max(self):
if (self.right):
return self.right.get_max()
return self.value
# Call the function `cb` on the value of each node
# You may use a recursive or iterative approach
def for_each(self, cb):
#version 1 recursive
# cb(self.value)
# if self.right:
# self.right.for_each(cb)
# if self.left:
# self.left.for_each(cb)
# if not self.right and not self.left:
# return
#version 2 iterative
stack = Stack()
stack.push(self)
while stack.len() > 0:
current_node = stack.pop()
if current_node.right:
stack.push(current_node.right)
if current_node.left:
stack.push(current_node.left)
cb(current_node.value)
# DAY 2 Project -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self, node):
if node.left:
self.in_order_print(node.left)
print(node.value)
if node.right:
self.in_order_print(node.right)
# print(node.value)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self, node):
#grab tha que
que = Queue()
#add the node to the que
que.enqueue(node)
while que.size > 0:
# remove node from front of que
node = que.dequeue()
print(node.value)
# check left
if node.left is not None:
#add left node to que
que.enqueue(node.left)
# check right
if node.right is not None:
#add right node to que
que.enqueue(node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self, node):
#make a stack
stack = Stack()
#put root in stack
stack.push(node)
#loop through stack
while stack.size > 0:
#pop node off stack
sp = stack.pop()
#check node value
print(sp.value)
#check left
if sp.left is not None:
#add left to stack
stack.push(sp.left)
#check right
if sp.right is not None:
#add right to stack
stack.push(sp.right)
# STRETCH Goals -------------------------
# Note: Research may be required
# Print In-order recursive DFT
def pre_order_dft(self, node):
pass
# Print Post-order recursive DFT
def post_order_dft(self, node):
pass
|
db22219e3bb6c829bf741eb3652e823d37572718 | sanghunjlee/bisection-method-calculator | /itercalc.py | 2,913 | 4 | 4 | """This module contains iteration method(s) that is used to find the zero.
BisectionMethod will calculate the zero by using the bisection method -- the next subdivision is found using an average of the previous subdivision's endpoints.
"""
import logging
from random import uniform
from mathform import MathFormula
MARGIN_OF_ERROR = 0.000000001
class BisectionMethod(object):
"""Method used for finding zero via bisecting existing subdivision.
Keyword arguments:
_f -- math-formula.MathFunction object, that is, the function for which the zero is calculated
"""
_f: MathFormula
is_single_variable: bool
def __init__(self, math_formula):
self._f = math_formula
self.is_single_variable = (len(self._f.variables) == 1)
def find_zero(self, a=None, b=None) -> float:
"""
Args:
a: start-point of the subdomain of the function on which to find the zero (default: None)
b: endpoint of the subdomain of the function on which to find the zero (default: None)
Returns:
"""
if self.is_single_variable:
interval = [-1.0, 1.0]
unbounded = True
if a is not None and b is not None:
unbounded = False
interval = [a, b]
var = self._f.variables[0]
variable_value_dict = {var: 0.0}
points = []
while len(points) < 2:
x = uniform(interval[0], interval[1])
variable_value_dict[var] = x
try:
y = self._f.evaluate(**variable_value_dict)
except ValueError:
raise ValueError('Cannot establish the starting interval')
print(f"for x = {x}, f(x) = {y}")
if len(points) == 0:
points.append((x, y))
elif y * points[0][1] < 0:
points.append((x, y))
else:
if unbounded:
interval[0] = interval[0] - (interval[1] - interval[0])
interval[1] = interval[1] + (interval[1] - interval[0])
for i in range(50):
x_b = (points[0][0] + points[1][0]) / 2
variable_value_dict[var] = x_b
try:
y_b = self._f.evaluate(**variable_value_dict)
except ValueError:
raise ValueError(f'Cannot evaluate such value: {x_b}')
if y_b == 0 or abs(y_b) < MARGIN_OF_ERROR:
break
elif y_b * points[0][1] < 0:
points[1] = (x_b, y_b)
elif y_b * points[1][1] < 0:
points[0] = (x_b, y_b)
print(f"{i}\t|{x_b:.10f}\t|{y_b}\t\t")
logging.info(f"The zero of the function is: {x_b:.8}")
return x_b
|
024724213be0c5faa732e02090b3e66576af302b | shadowfelldown/AdventureGame | /Player.py | 2,724 | 4 | 4 | import random
import map
__author__ = 'Daniel'
def options(choices):
while True:
try:
userchoice = str(raw_input('What do you do? '))
if 'stuck' in userchoice.lower():
return 'STUCK'
if 'hint' in userchoice.lower():
return 'HINT'
if 'help' in userchoice.lower():
return 'HELP'
if 'quit' in userchoice.lower():
sure = raw_input("are you sure? Y/N")
if sure.lower() == 'y':
return 'QUIT'
else:
continue
if 'take' in userchoice.lower():
if 'treasure' in userchoice.lower():
return 'TREASURE'
if 'use' in userchoice.lower():
if 'map' in userchoice.lower():
return 'MAP'
if 'go' or 'proceed' in userchoice.lower():
if any(ext in userchoice.upper() for ext in choices):
if 'north' in userchoice.lower():
return 'NORTH'
if 'south' in userchoice.lower():
return 'SOUTH'
if 'east' in userchoice.lower():
return 'EAST'
if 'west' in userchoice.lower():
return 'WEST'
else:
print 'You cannot go that way'
continue
except ValueError:
print "Please enter a string"
#better try again... Return to the start of the loop
continue
else:
print "invalid entry, please type 'HELP' if you are stuck"
continue
def distanceto(userpos,target,):
if userpos > target:
distance = round(((userpos - target) / 10))
distance += round(((userpos - target) % 10))
else:
distance = round((target - userpos) / 10)
distance += round((target - userpos) % 10)
print "You are", distance, " rooms away from your goal"
#once target function is defined, will be room name, i.e goal, treasure, exit.
def movement(direction,userpos,maplist,choices):
if direction == 'NORTH':
userpos = userpos-10
print 'you proceed NORTH'
return userpos
if direction == 'SOUTH':
userpos = userpos+10
print 'you proceed SOUTH'
return userpos
if direction == 'EAST':
userpos = userpos+1
print 'you proceed EAST'
return userpos
if direction == 'WEST':
userpos = userpos-1
print 'you proceed WEST'
return userpos
else:
print 'you cannot go that way'
return userpos
|
1d91f3d249f2902cf47953bb1f59ae3ede5026aa | hashtagallison/Python | /Practice_STP/Challenge_Questions/Ch8 - Challenges/Ch8_Challenge1.py | 951 | 3.765625 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 8 pg 121 - Challenges
# hashtagallison - Practice 2019-04-11
#-------------------------------------------
#-------------------------------------------
# CHAPTER 8: CHALLENGES
# - Official Answer Key: http://tinyurl.com/hlnsdot (Don't look until you try for yourself!!)
#-------------------------------------------
#1. Call a different function from the statistics module.
# More about the statistics module: https://docs.python.org/3/library/statistics.html#module-statistics
import statistics
group = [1, 22, 333, 4444, 55555]
pdev = statistics.pstdev(group) # population standard deviation of data
print(pdev)
#2. Create a module named cubed with a function that takes a number as a parameter, and returns the number cubed.
# Import and call the function from another module.
# See the other files in the folder for the result. |
e131178d3481ed8a542fe91d1cda9edf52082f39 | iamparkerm/pythonRPG | /main.py | 4,169 | 3.671875 | 4 | # updated for python3
import sys
import time
from scripts.classes import *
p = Player()
#Main() is the first function the game runs
def main():
intro()
# Loop that begins game
while p.knowledge < 16:
line = input("What would you like to do? > ")
args = line.split()
if len(args) > 0:
commandFound = False
# was Commands.keys: in py2
for c in Commands:
# if the first letter[0] in the input is equal to the first letter in the Commands dict value
if args[0] == c[:len(args[0])]:
# then Player.help(Player())
Commands[c](p)
commandFound = True
break
if not commandFound:
print("{} doesn't understand the suggestion.".format(p.name))
if p.knowledge == 0:
killed_screen()
break
# boss battle info
boss = Boss()
p.state = 'argue'
p.enemy = boss
print(
"-----------FINAL STAGE------------\n {} joins the free speech rally. "
"But what is this?! An angry mob wants to de-platform the rally! {} wonders what they're afraid of hearing?"
" \nBOSS ENCOUNTERED \n {} encounters the {}!".format(p.name, p.name, p.name, boss.name))
print(
"\n 'You think we care about OBJECTIVE TRUTH and KNOWLEDGE?!"
" We only believe in the subjective truths our LIVED EXPERIENCES!"
" What can you possibly say to deny this??', says the {}".format(boss.name))
# loop that begins boss battle
while boss.knowledge > 0:
line = input("What would you like to do? > ")
args = line.split()
if len(args) > 0:
commandFound = False
for c in Commands:
if args[0] == c[:len(args[0])]:
Commands[c](p)
commandFound = True
break
if not commandFound:
print("{} doesn't understand the suggestion.".format(p.name))
if p.state != 'argue':
kill_screen()
break
def intro():
print(
"Oh, hello, I didn't see you there. You look smart as shit. I bet you're from Owl Town and"
"\nback on campus for some learning. Well watch out for the big rally today planned over in Red Square.")
time.sleep(2)
print("..........."
"\nSo which one are you, anyway?"
"\nCorey? type 1 \nEric? press 2 \nJosh? press 3 \nKevin? press 4 \nParker? press 5")
choice = ''
while not (choice == 1 or choice == 2 or choice == 3 or choice == 4 or choice == 5):
try:
choice = eval(input("Choice ="))
except NameError:
print("\nNot an integer! Try again.")
continue
if choice == 1:
p.name = 'Corey'
p.specialname = 'VERY ACCURATE THROW!'
elif choice == 2:
p.name = 'Eric'
p.specialname = 'PARTYING DAD!'
elif choice == 3:
p.name = 'Josh'
p.specialname = 'RETARD STRENGTH!'
elif choice == 4:
p.name = 'Kevin'
p.specialname = 'AVOIDS CONFRONTATION!'
elif choice == 5:
p.name = 'Parker'
p.specialname = 'REKRAP ASTRAL PLANE!'
print("\nWelcome, {}. (type help to see what your options are)".format(p.name))
#win game function
def kill_screen():
print(
"\n {} vanquished all the post-modernist illiberals! {} has returned freedom of speech to campus! \n".format(
p.name, p.name))
print(
"Hi, this is ReKrap, and thanks for playing. I know we had a lot of fun today, but its important to remember that knowledge is half the battle thumbs up emoji")
print("developer - ReKrap")
print("writer - ReKrap")
print("THE END")
print("P.S. There's a potential Donkey Kong kill screen coming up if anyone is interested.")
#lose game function
def killed_screen():
print(
"Your head feels a little foggy, but you can't think of any response. Maybe you will go home and nap. \nPlease reload the program to play again.")
sys.exit()
if __name__ == '__main__':
main()
|
92858ce1ba67fcf35d235e22637099c1180fbf39 | 17390089054/Python | /matplotlib/scatter_squares.py | 506 | 3.5 | 4 | import matplotlib.pyplot as plt
x_values=list(range(1,1001))
y_values=[x**2 for x in x_values]
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,
edgecolor='none',s=40)
#设置图表标题并加上标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of Values",fontsize=14)
plt.axis([0,1100,0,1100000])
#plt.show()
#将图表保存在文件目录中 并裁剪掉多余的空白区域
plt.savefig("squares_plot.png",bbox_inches='tight')
|
72f2ad8a38748b9c6626aff8db7c992e24f78169 | qmaurmann/pytris | /tetris.py | 12,650 | 3.59375 | 4 | """This is the main file for the Pytris project. The three concrete classes
defined herein are
Board: generally controls the flow of the game, e.g. interacting with the
classes defined in tetris_pieces.py to determine whether and how pieces
get moved around the board. Also responsible for displaying the state of
the board.
NextPieceDisplay: is responsible for creating and displaying the next piece.
Main: a window containing a Board, a NextPieceDisplay, and other components
relevant to the game state. The Board actually controls what happens to
these components during game play.
Also defines an abstract class SquarePainter (extended by both Board and
NextPieceDisplay), and a convenience function styled_set_label_text.
@author Quinn Maurmann
"""
import pygtk
pygtk.require("2.0")
import cairo
import glib
import gtk
import random
import tetris_pieces
tuple_add = tetris_pieces.tuple_add # too useful to call by namespace
DOT_SIZE = 30
ROWS = 18
COLS = 10
class SquarePainter(gtk.DrawingArea):
"""Abstract SquarePainter class factors out the ability to paint squares
on a grid. Extended by both the Board and NextPieceDisplay classes."""
def paint_square(self, pos, color, cr):
"""Paints a square on the grid at a particular (int, int) position.
Color is given as an RGB triple (of floats between 0 and 1); cr is the
Cairo context. Used only in the expose methods of Board and
NextPieceDisplay"""
cr.set_source_rgb(*color)
i, j = pos
cr.rectangle(i*DOT_SIZE+1, j*DOT_SIZE-1, DOT_SIZE-2, DOT_SIZE-2)
cr.fill()
class Board(SquarePainter):
"""Board is responsible for handling all game logic and displaying
state."""
def __init__(self, next_piece_display, level_display, lines_display,
score_display):
super(Board, self).__init__()
self.set_size_request(COLS*DOT_SIZE, ROWS*DOT_SIZE)
self.connect("expose-event", self.expose)
self.next_piece_display = next_piece_display
self.level_display = level_display
self.lines_display = lines_display
self.score_display = score_display
self.level = 0
self.lines = 0
self.score = 0
self.over = False
self.increment_level() # formats label and starts timer
self.increment_lines(0) # formats label
self.increment_score(0) # formats label
self.curr_piece = self.next_piece_display.get_piece()
self.locked_squares = {} # (int,int): color dictionary
def expose(self, widget, event):
"""Paint current piece and all locked squares; should only be called
via self.queue_draw."""
cr = widget.window.cairo_create()
cr.set_source_rgb(0, 0, 0)
cr.paint()
for pos, color in self.locked_squares.iteritems():
self.paint_square(pos, color, cr)
for pos in self.curr_piece.occupying():
self.paint_square(pos, self.curr_piece.color, cr)
### Easiest to put "GAME OVER" message here ###
if self.over:
cr.select_font_face('Sans', cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_BOLD)
### HACK: The following doesn't scale with DOT_SIZE ###
cr.set_font_size(41)
cr.move_to(10, 200)
cr.set_source_rgb(0, 0, 0) # dark drop-shadow
cr.show_text('GAME OVER')
cr.move_to(12, 202)
cr.set_source_rgb(.82, .82, .82) # light main text
cr.show_text('GAME OVER')
cr.stroke()
def on_board(self, pos):
"""Determine whether a position is actually on the board."""
i, j = pos
return 0 <= i < COLS and 0 <= j < ROWS
def can_move_curr_piece(self, delta):
hypothetical = self.curr_piece.test_move(delta)
return all(pos not in self.locked_squares and self.on_board(pos)
for pos in hypothetical)
def move_curr_piece(self, delta, point=False):
"""Check the validity of a move, and conditionally perform it.
One point may be granted, e.g. when the player moves the piece down
voluntarily."""
if self.over: return
elif self.can_move_curr_piece(delta):
self.curr_piece.confirm_move(delta)
if point: self.increment_score(1)
elif delta == (0,1): # "illegal" down move
self.lock_curr_piece()
self.queue_draw()
def drop_curr_piece(self):
"""Drop (and lock) curr_piece as far as possible, granting points
equal to the distance of the drop."""
if self.over: return
delta = (0, 0) # now make this as big as possible
while True:
new_delta = tuple_add(delta, (0, 1))
if self.can_move_curr_piece(new_delta):
delta = new_delta
else:
break
self.increment_score(delta[1])
self.move_curr_piece(delta)
self.lock_curr_piece()
self.queue_draw()
def rotate_curr_piece(self):
"""Check the validity of a rotation, and conditionally perform it."""
if self.over: return
hypothetical = self.curr_piece.test_rotate()
if all(pos not in self.locked_squares and self.on_board(pos)
for pos in hypothetical):
self.curr_piece.confirm_rotate()
self.queue_draw()
def lock_curr_piece(self):
"""Add squares of current piece to the collection of locked squares.
Make calls to clear full rows, generate another piece, and check
whether the game should end."""
for pos in self.curr_piece.occupying():
self.locked_squares[pos] = self.curr_piece.color
self.clear_rows()
self.curr_piece = self.next_piece_display.get_piece()
if any(pos in self.locked_squares
for pos in self.curr_piece.occupying()):
self.game_over()
def game_over(self):
"""End the game. (Doesn't currently have to do much, because the
actual painting is done conditionally in expose.)"""
self.over = True
def clear_rows(self):
"""Clear any full rows, modifying the variables locked_squares,
level, lines, and score as appropriate."""
### Previous version had a bug, in that it assumed the set of ###
### indices of full rows had to be a contiguous sequence! ###
full_rows = [j for j in range(ROWS) if all(
(i, j) in self.locked_squares for i in range(COLS))]
if not full_rows: return
### Calculate how for to drop each other row, and do it ###
drop = {j: len([k for k in full_rows if k > j]) for j in range(ROWS)}
self.locked_squares = {(i, j+drop[j]): color for (i, j), color in
self.locked_squares.items() if j not in full_rows}
### Now just update score, etc. ###
d = len(full_rows)
self.increment_lines(d)
self.increment_score(self.level*{1: 40, 2: 100, 3: 300, 4: 1200}[d])
if self.level < self.lines // 10 + 1:
self.increment_level()
def increment_lines(self, d):
"""Increment lines by d, and change the label."""
self.lines += d
styled_set_label_text(self.lines_display, "Lines: "+str(self.lines))
def increment_score(self, x=1):
"""Increment score by x, and change the label."""
self.score += x
styled_set_label_text(self.score_display, "Score: "+str(self.score))
def increment_level(self):
"""Increment level by 1, and change the label. Also call make_timer
and hook up the resulting function with glib.timeout_add, to be
called every 2.0/(level+3) seconds."""
self.level += 1
styled_set_label_text(self.level_display, "Level: "+str(self.level))
glib.timeout_add(2000//(self.level+3), self.make_timer(self.level))
def make_timer(self, lev):
"""Creates a callback function on_timer, which moves current piece
down (without granting a point). If the current level moves beyond
lev, then on_timer will stop working, and will need to be replaced."""
def on_timer():
if (lev == self.level) and not self.over: # finds lev in scope
self.move_curr_piece((0, 1))
return True
else:
return False # kills on_timer
return on_timer
class NextPieceDisplay(SquarePainter):
"""Responsible for both creating and showing new pieces."""
def __init__(self):
super(NextPieceDisplay, self).__init__()
self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0, 0, 0))
self.set_size_request(8*DOT_SIZE, 4*DOT_SIZE)
self.connect("expose-event", self.expose)
self.next_piece = self.create_piece()
def expose(self, widget, event):
"""Displays the next piece; should only be called via
self.queue_draw."""
cr = widget.window.cairo_create()
cr.set_source_rgb(0.05, 0.05, 0.05)
cr.paint()
for pos in self.next_piece.occupying():
self.paint_square(tuple_add(pos, (-1, 1)),
self.next_piece.color, cr)
def create_piece(self):
"""A Piece factory."""
p_type = random.choice(tetris_pieces.CONCRETE_TYPES)
return p_type()
def get_piece(self):
"""Generates a new piece and shows it; returns the old piece.
Analogous to next() operation for iterators."""
old = self.next_piece
new = self.create_piece()
self.next_piece = new
self.queue_draw()
return old
class Main(gtk.Window):
"""Main window. Contains a Board and other relevant display objects. Is
not responsible for any in-game control beyond passing simple instructions
to the Board on keystroke events."""
def __init__(self):
super(Main, self).__init__()
self.set_title("Tetris")
self.set_resizable(False)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.connect("key-press-event", self.on_key_down)
### Create and reformat labels ###
self.next_piece_words = gtk.Label("Undefined")
self.level_display = gtk.Label("Undefined")
self.lines_display = gtk.Label("Undefined")
self.score_display = gtk.Label("Undefined")
self.next_piece_words.set_alignment(.2, .4)
self.level_display.set_alignment(.2, 0)
self.lines_display.set_alignment(.2, 0)
self.score_display.set_alignment(.2, 0)
styled_set_label_text(self.next_piece_words, "Next Piece:")
### Note: Board automatically fixes other three labels ###
self.next_piece_display = NextPieceDisplay()
self.board = Board(self.next_piece_display, self.level_display,
self.lines_display, self.score_display)
self.hbox = gtk.HBox() # split screen into 2 panels
self.add(self.hbox)
self.hbox.add(self.board) # left panel is Board
self.vbox = gtk.VBox() # right panel has everything else in a VBox
### Have to wrap VBox in EventBox to change BG color ###
self.vbox_wrapper = gtk.EventBox()
self.vbox_wrapper.add(self.vbox)
self.vbox_wrapper.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.Color(0.05, 0.05, 0.05))
self.hbox.add(self.vbox_wrapper)
self.vbox.add(self.next_piece_words)
self.vbox.add(self.next_piece_display)
self.vbox.add(self.level_display)
self.vbox.add(self.lines_display)
self.vbox.add(self.score_display)
self.show_all()
def on_key_down(self, widget, event):
key = event.keyval
if key == gtk.keysyms.Left:
self.board.move_curr_piece((-1, 0))
elif key == gtk.keysyms.Up:
self.board.rotate_curr_piece()
elif key == gtk.keysyms.Right:
self.board.move_curr_piece((1, 0))
elif key == gtk.keysyms.Down:
self.board.move_curr_piece((0, 1), point=True)
elif key == gtk.keysyms.space:
self.board.drop_curr_piece()
def styled_set_label_text(label, text):
"""Set the text of a gtk.Label with the preferred markup scheme. (Simple
enough not to be worth extending gtk.Label just for this method.)"""
front = "<b><span foreground='#AAAAAA' size='large'>"
end = "</span></b>"
label.set_markup(front+text+end)
if __name__ == "__main__":
Main()
gtk.main()
|
5877578ec81d77cb87ef32daba202c016a2f31d6 | IngridFCosta/Exercicios-de-Python-Curso-em-video | /condicoesAninhadas/ex036_emprestimoBank.py | 786 | 4.09375 | 4 | """"036- Escreva um programa para aprovar o emprestimo bancario
para a compra de uma casa. O programa vai perguntar o valor da casa,
o sálario do comprador e em quantos anos ele vai pagar.
-Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário
ou então o empréstimo será negado.
"""
valorCasa= float(input('Qual o valor da casa?'))
salarioComprador= float(input('Qual o salario do comprador?'))
anosPag=int(input('Em quantos anos deseja pagar?'))
prestacao=valorCasa/(anosPag*12)
percentualSal=(salarioComprador*30)/100
print('O valor da prestação é:{}'.format(prestacao))
if prestacao > percentualSal:
print('Emprestimo negado! A prestação excede 30% do seu salario.')
elif prestacao <= percentualSal:
print('Emprestimo aceito!')
|
4d8409fd75964b3a6e18956f9e1a2704c27b7d2f | taeheechoi/data-structure-algorithms-python | /20-80-questions/BST.py | 1,356 | 4.3125 | 4 | #https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-binary-search-tree-exercise-3.php
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_BST(root):
stack = []
prev = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if prev and root.data <= prev.data:
return False
prev = root
root = root.right
return True
def isBST(root, l = None, r = None):
if root == None:
return True
if (l != None and root.data <= l.data):
return False
if (r != None and root.data >= r.data):
return False
return isBST(root.left, l, root) and isBST(root.right, root, r)
root = Node(3)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(4)
if is_BST(root):
print("is BST")
else:
print("not a BST")
if isBST(root):
print("is BST")
else:
print("not a BST")
root2 = Node(4)
root2.left = Node(2)
root2.right = Node(5)
root2.left.left = Node(1)
root2.left.right = Node(3)
if is_BST(root2):
print("is BST")
else:
print("not a BST")
if isBST(root2):
print("is BST")
else:
print("not a BST") |
77d8a09fceccdb9ac3bf9ed74816b8a5eeceee92 | hernandez232/FP_Laboratorio_06_00075919 | /Ejercicio2.py | 137 | 4.03125 | 4 | n = int (input ("Inserte un numero: "))
for f in range (1, n+1):
for c in range (1, f+1):
print (f, end=" ")
print (" ") |
8b26a2111a223859a2fed703c3ef8b8bda57e5e1 | Xitram/Batter-Up | /ExcelFinal/BudgetOrganizer.py | 6,915 | 3.671875 | 4 | import openpyxl #the needed imports for this script
from sys import argv
script, filename = argv #sets the script name and filename as necessary args to run
#IMPROVEMENT: set the filename as a rawinput to pass
data = open(filename, "r") #gives a variable for the opened file
everything = []
title = []
expense = [] #***The necessary lists we'll be using***
reimbursable = [] # Not sure how necessary or good it is to just throw these
living_expense = [] # all out there at once, but it helped me wrap my head around
housing = [] # what I was doing
other = []
def sort_data(f): #first function, takes our open file, sorts its data between a price (integer), and its title. Into two lists
all_info = f.read().split()
while len(all_info) > 0:
an_item = all_info.pop()
try:
expense.append(int(an_item))
except ValueError:
title.append(an_item)
sort_data(data) #runs the sort_data function on our open file with our budjet data
def process_lists(a, b): # this function takes our new expense and title lists, prints
# corresonding values side by side, and allows me to input
position = 0 # what category of expense(and its list) I want to send it to(ie housing costs)
while len(a) and len(b) > 0:
item_title = a[position]
item_expense = b[position]
print "Where would you like to send this one ?"
print """******************"""
print item_title,
print item_expense
print """******************"""
send = raw_input("A = Reimburse, B = Living Expense, C = Housing, D = Other ")
if send == "A":
title.remove(item_title) # removes items from their master expense/title list
expense.remove(item_expense)
reimbursable.append(item_title), #appends both items to their appropriate list based
reimbursable.append(item_expense)#on what excel sheet it will be recorded on
while item_title in title: #this loop will double check expenses with same
locT = title.index(item_title) #..title and append them too, this was to avoid
locE = title.index(item_title) #..processing redundant expenses that
popTitle = title.pop(locT) #..were tracked a lot, like transportation and coffee
popExpense = expense.pop(locE)
reimbursable.append(popTitle)
reimbursable.append(popExpense)
elif send == "B":
title.remove(item_title)
expense.remove(item_expense)
living_expense.append(item_title),
living_expense.append(item_expense)
while item_title in title:
locT = title.index(item_title) # had to find a way to keep the expense
locE = title.index(item_title) # ..and title aligned and appending
popTitle = title.pop(locT) #..together since they were techically in two
popExpense = expense.pop(locE) # seperate lists.
living_expense.append(popTitle)
living_expense.append(popExpense)
elif send == "C":
title.remove(item_title)
expense.remove(item_expense)
housing.append(item_title),
housing.append(item_expense)
while item_title in title:
locT = title.index(item_title)
locE = title.index(item_title)
popTitle = title.pop(locT)
popExpense = expense.pop(locE)
housing.append(popTitle)
housing.append(popExpense)
elif send == "D":
title.remove(item_title)
expense.remove(item_expense)
other.append(item_title),
other.append(item_expense)
while item_title in title:
locT = title.index(item_title)
locE = title.index(item_title)
popTitle = title.pop(locT)
popExpense = expense.pop(locE)
other.append(popTitle)
other.append(popExpense)
else:
print "Unrecognized input, try again."
process_lists(title, expense)
budj = openpyxl.load_workbook('BlankBudj.xlsx') #sets variables for the Excel workbook I'll be using (blank template already saved in directory)
#and the following names and gives variables for Sheets, there will be a sheet for each expense type
sheet_main = budj.active # this is to cross check specific expenses if I want to
sheet_reim = budj.get_sheet_by_name('Sheet2')
sheet_living = budj.get_sheet_by_name('Sheet3')
sheet_housing = budj.create_sheet(title = 'Housing')
sheet_other = budj.create_sheet(title = 'Other')
sheet_reim.title = 'Reimbursements'
sheet_living.title = 'Living'
sheet_housing.title = 'Housing'
sheet_main.title = 'Main'
def list_to_sheet(a_list, a_sheet): #this function will cycle through our sorted lists, and append them to the proper expense sheet in workbook
rows_needed = len(a_list) / 2 + 1
while len(a_list) > 0:
for rowNum in range(1, rows_needed):
for colNum in range(1, 3):
if len(a_list) > 0:
our_thing = a_list.pop()
a_sheet.cell(row = rowNum, column = colNum).value = our_thing
list_to_sheet(reimbursable, sheet_reim)
list_to_sheet(living_expense, sheet_living)
list_to_sheet(housing, sheet_housing)
list_to_sheet(other, sheet_other) #runs the function for every list, sheet combo we have
def total_sheets(from_sheet): #this function will take values from column 1 of a expense sheet, and get their sum
rows = from_sheet.max_row
to_total =[]
for x in range(1, rows):
a_value = from_sheet.cell(row = x, column = 1).value
to_total.append(a_value)
return sum(to_total)
print "What is the conversion rate? "
conv_rate = raw_input("? ") #the conversion rate here is changing daily, this helps me adjust when Im months behind
sheet_main['C2'].value = total_sheets(sheet_living) / int(conv_rate) #takes the cell in the main sheet, will make its value the corresponding sum of the numbers in the expense sheet that goes with it
sheet_main['C12'].value = total_sheets(sheet_housing) / int(conv_rate)
sheet_main['C20'].value = total_sheets(sheet_other) / int(conv_rate)
sheet_main['C35'].value = total_sheets(sheet_reim) / int(conv_rate)
print "Save your new budjet sheet as? "
save_as = raw_input("> ")
budj.save(save_as)
#Ways to improve: a back function, a once sorted sort all of same value,
|
915966359141544979197250f4ae1155616ad58d | ZhouPao/work | /RedisQueue.py | 1,677 | 3.546875 | 4 | import redis
class RedisQueue(object):
"""
Simple Queue with Redis Backend
"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""
The default connection parameters are: host='localhost', port=6379, db=0
"""
self.__db= redis.Redis(**redis_kwargs)
self.key = '%s:%s' %(namespace, name)
def qsize(self):
"""
Return the approximate size of the queue.
"""
return self.__db.llen(self.key)
def empty(self):
"""
Return True if the queue is empty, False otherwise.
"""
return self.qsize() == 0
def rput(self, item):
"""
Put item into the queue.
"""
self.__db.rpush(self.key, item)
def lput(self,item):
"""
put item to left
:param item:
:return:
"""
self.__db.lpush(self.key,item)
def lget(self, block=True, timeout=None):
"""
get item in left
"""
if block:
item = self.__db.blpop(self.key, timeout=timeout)
else:
item = self.__db.lpop(self.key)
if item:
item = item[1]
return item
def rget(self, block=True, timeout=None):
"""
get item in right
:param block:
:param timeout:
:return:
"""
if block:
item=self.__db.brpop(self.key,timeout=timeout)
else:
item=self.__db.rpop(self.key)
if item:
item=item[1]
return item
def get_nowait(self):
"""
Equivalent to get(False).
"""
return self.get(False)
|
f02610dfd0a58c6e1cd27d270a4461164a073575 | maxmyth01/unit5 | /longestWord.py | 393 | 4.0625 | 4 | #Max Low
#11-13-17
#middleWord.py -- finds middle if even print both
words = input('Enter some words: ').split()
lettercount=0
maxletters = 0
maxword=0
for w in words:
for ch in w:
lettercount += 1
if lettercount > maxletters:
maxletters = lettercount
maxword = w
lettercount = 0
print("The longest word is",maxword)
|
54ee354b7d8839dcf03f09606db554bd650fc6fd | tchia007/Simplilearn | /Deep_Learning/tensorFlowTutorial_p2.py | 3,956 | 3.984375 | 4 | '''
This code has been copied from the simplilearn tensorflow tutorial
https://www.youtube.com/watch?v=E8n_k6HNAgs&index=24&list=PLEiEAq2VkUULYYgj13YHUWmRePqiu8Ddy
'''
#--------------1. Read the census_data.csv using pandas library
import pandas as pandas
census = pd.read_csv("census_data.csv")
#--------------2. Display the head of the dataset
print census.head()
#--------------3. Convert the label column to 0s and 1s instead of strings
print census['income_bracket'].unique()
def label_fix(label):
if label == ' <=50k':
return 0
else:
return 1
census['income_bracket'] = census['income_bracket'].apply(label_fix)
#--------------4. Perform a Train Test split on the dataset
from sklearn.model_selection import train_test_split
x_data = census.drop('income_bracket', axis = 1)
y_labels = census['income_bracket']
X_train, X_test, y_train, y_test = train_test_split(x_data, y_labels, test_size = 0.3, random_state = 101)
#--------------5. Create the feature columns for the categorical values using library lists or hash bucks
import tensorflow as tf
#Create the tf.feature_columns for the categorical values. use the vocabulary lists or just use hash buckets
#vocublary list is when we know the exact values that can be taken. look at gender
#hash bucket can have any value
#hash_bucket_size is how many values that the category can be. usually try to pick larger value
gender = tf.feature_column.categorical_column_with_vocabulary_list("gender", ["Female", "Male"])
occupation = tf.feature_column.categorical_column_with_hash_bucket("occupation", hash_bucket_size=1000)
marital_status = tf.feature_column.categorical_column_with_hash_bucket("marital_status", hash_bucket_size=1000)
relationship = tf.feature_column.categorical_column_with_hash_bucket("relationship", hash_bucket_size=1000)
education = tf.feature_column.categorical_column_with_hash_bucket("education", hash_bucket_size=1000)
workclass = tf.feature_column.categorical_column_with_hash_bucket("workclass", hash_bucket_size=1000)
native_country = tf.feature_column.categorical_column_with_hash_bucket("native_country", hash_bucket_size=1000)
#--------------6. Create the feature columns for the continiuous values using numeric column
#Create the continuous feature_columns for the continuous values using numeric_column
age = tf.feature_column.numeric_column("age")
education_num = tf.feature_column.numeric_column("education_num")
capital_gain = tf.feature_column.numeric_column("capital_gain")
capital_loss = tf.feature_column.numeric_column("capital_loss")
hours_per_week = tf.feature_column.numeric_column("hours_per_week")
#--------------7. Put all these variables into a single list with the variable name feat_cols
feat_cols = [gender, occupation, marital_status, relationship, education, workclass, native_country,
age, education_num, capital_gain, capital_loss, hours_per_week]
#--------------8. Creat the input function. Batch size is up to you
input_func = tf.estimator.inputs.pandas_input_fn(x = X_train, y = y_train, batch_size = 100, num_epochs = None, shuffle = True)
#--------------9. Create the model with tf.estimator using LinearClassifier
model = tf.estimator.LinearClassifier(feature_columns = feature_cols)
#--------------10. Train the model for at least 5000 steps
model.train(input_fn = input_func, steps = 5000)
#--------------11. Evaluation fo the model
pred_fn = tf.estimator.inputs.pandas_input_fn(x = X_test, batch_size = len(X_test), shuffle = False)
#--------------12. Create a list of class_ids key values from the prediction list dictionaries.
##-----------------These predictions will be used to compare against y_test values
final_preds = []
for pred in predictions:
final_preds.append(pred['class_ids'][0])
print final_preds[:10]
#--------------13. Calculat the models performance on Test data
from sklearn.metrics import classification_report
print classification_report(y_test, final_preds)
|
7d57f1a59084ebe2edba2c5ca3d0e46cc1a64087 | mjgrace/python-mit-open-courseware | /PythonHW1/src/rps.py | 721 | 4 | 4 | player1 = raw_input("Enter player 1 selection: ")
if (player1 != "rock" and player1 != "paper" and player1 != "scissors"):
print "Invalid selection"
player2 = raw_input("Enter player 2 selection: ")
if (player2 != "rock" and player2 != "paper" and player2 != "scissors"):
print "Invalid selection"
if ((player1 == 'rock' and player2 == 'scissors')
or (player1 == 'scissors' and player2 == 'paper')
or (player1 == 'paper' and player2 == 'rock')):
print "Player 1 wins"
if ((player2 == 'rock' and player1 == 'scissors')
or (player2 == 'scissors' and player1 == 'paper')
or (player2 == 'paper' and player1 == 'rock')):
print "Player 2 wins"
if (player1 == player2):
print "Tie"
|
68cbc4dab7374c03abbfacdb8e30d1ae87e5b084 | fatecoder/Python-practices | /battleship.py | 1,490 | 3.703125 | 4 | #!/bin/python
import random
tablero = []
vista = []
tam = random.randrange(2, 6)
def gene_tablero():
for i in range(tam):
tablero.append([])
for j in range(tam):
tablero[i].append("O")
#ship
tablero[random.randrange(0,tam)][random.randrange(0,tam)] = "S"
def test_view_tablero() :
for i in range(len(tablero)) :
row = ''
for j in range(len(tablero)):
row = row +" "+ tablero[i][j]
print row
#test_view_tablero()
def gene_view() :
for i in range(tam) :
vista.append([])
for j in range(tam) :
vista[i].append("O")
def user_view() :
for i in range(len(vista)) :
row = ' '
for j in range(len(vista)) :
row = row +" "+ vista[i][j]
print row
def play() :
print ".:Ingresa coordenadas a atacar:."
cx = int(raw_input("-> Coord x: "))
cy = int(raw_input("-> Coord y: "))
if cx < tam and cy < tam :
if tablero[cy][cx] == "S" :
print "NAVE DESTRUIDA!!!"
vista[cy][cx] = "S"
user_view()
else :
print "SIGUE INTENTANDO..."
print "-------------------------------"
vista[cy][cx] = "X"
user_view()
play()
else :
print "VALORES FUERA DE RANGO"
print "-------------------------------"
user_view()
play()
gene_tablero()
test_view_tablero()
gene_view()
user_view()
play()
|
a84226a010f0b63854b0e0e3f6c4c2f194724e02 | maxianren/algorithm_python | /recusion_base_conversion.py | 1,782 | 3.96875 | 4 | '''
Base conversion
Given a number in base M, please convert it to base N
Input format:
Two lines, the first line has two digits, which are M and N in decimal notation, separated by spaces; where M and N satisfy 2 ≤ M and N ≤ 36
The second line has the number to be converted, the part of each digits exceeding 9 is represented by capital letters A-Z from 10 to 36;
input data should ensure the largest number of digits not exceed M
Output format:
A line of string, representing the converted N number
Input sample:
8 16
473
Sample output:
13B
'''
#the main function
def m_to_n_base(m,n,input_m_base):
# set global variable which would be use in the following functions
global library
library = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# phase 1: convert M_base into decimal
m_decimal=m_to_decimal(m,input_m_base)
# phase 2: convert decimal into N_base
return decimal_to_n(m_decimal,n)
# phase 1: convert M_base into decimal
def m_to_decimal(m,input_m_base):
# set initial variables
digits=len(str(input_m_base))
sum=0
# iteratively calculate the sum
for d,i in enumerate(str(input_m_base)):
# set variables in the loop
power=digits-d-1
index=library.index(i)
# sum up
sum+=index*m**power
return sum
# phase 2: convert decimal into N_base
def decimal_to_n(m_decimal,n):
# recursion: reduce the complexity of the problem and self-referential
if m_decimal>0:
return decimal_to_n(m_decimal//n,n)+library[m_decimal%n]
# recursion stop condition: m_decimal == 0
else:
return ''
if __name__ == "__main__":
m,n= 8,16
#m, n = map(int, input().split())
input_m_base = 471
#input_m_base = input()
print(m_to_n_base(m, n, input_m_base)) |
99aa19fc583a9d79de276c6266b1918a33e36eeb | bivanalhar/rec_problem | /separate_file.py | 2,661 | 3.53125 | 4 | """
This file is intended to split the csv file of the QFactory Statistics
into several csv files, each is unique based on semester identity
"""
import csv
appended_row_h1s1 = []
appended_row_h1s2 = []
appended_row_hcal = []
appended_row_hsta = []
appended_row_hsu1 = []
appended_row_hsu2 = []
appended_row_m1s1 = []
appended_row_m2s1 = []
appended_row_m3s1 = []
#Step No.1 : storing all of the H1S1 information into separate csv file
with open("info_qfactory.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ",")
for row in csv_reader:
if row[1] == "H1S1":
appended_row_h1s1.append(row)
elif row[1] == "H1S2":
appended_row_h1s2.append(row)
elif row[1] == "HCAL":
appended_row_hcal.append(row)
elif row[1] == "HSTA":
appended_row_hsta.append(row)
elif row[1] == "HSU1":
appended_row_hsu1.append(row)
elif row[1] == "HSU2":
appended_row_hsu2.append(row)
elif row[1] == "M1S1":
appended_row_m1s1.append(row)
elif row[1] == "M2S1":
appended_row_m2s1.append(row)
elif row[1] == "M3S1":
appended_row_m3s1.append(row)
else:
print(row[1])
with open("info_qfactory_h1s1.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_h1s1:
csv_writer.writerow(row)
with open("info_qfactory_h1s2.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_h1s2:
csv_writer.writerow(row)
with open("info_qfactory_hcal.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_hcal:
csv_writer.writerow(row)
with open("info_qfactory_hsta.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_hsta:
csv_writer.writerow(row)
with open("info_qfactory_hsu1.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_hsu1:
csv_writer.writerow(row)
with open("info_qfactory_hsu2.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_hsu2:
csv_writer.writerow(row)
with open("info_qfactory_m1s1.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_m1s1:
csv_writer.writerow(row)
with open("info_qfactory_m2s1.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_m2s1:
csv_writer.writerow(row)
with open("info_qfactory_m3s1.csv", mode = 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter = ",")
for row in appended_row_m3s1:
csv_writer.writerow(row) |
8a67db12307a1bc931d3fbbffbb699885b5f3928 | Jav10/Python | /C-digosPython/estructurasControl.py | 1,300 | 4.3125 | 4 | #Estructuras de Control
#Autor: Javier Arturo Hernández Sosa
#Fecha: 1/Sep/2017
#Descripcion: Curso Python FES Acatlán
#sentencia IF,ELSE y ELIF
edad = 10
if(edad<18):
print("Eres un niño todavía")
elif(edad>=18 and edad<40):
print("Eres un adulto")
elif(edad>=40 and edad<70):
print("Ya estas viejo")
else:
print("Ya te pasaste de maduro")
#sentencia WHILE
x = 0
while(True):
x = x + 1
if(x==3):
print("Nos brincamos el 3")
continue
elif(x==8):
print("En el 8 rompemos el ciclo")
break
print(x)
'''Función RANGE
range(inicio,final,incremento) Genera una progreción aritmética
range(10) 0 a 9
range(5,10) 5 a 9
range 5,10,2) 5 a 9 de 2 en 2
'''
#sentencia FOR
for i in range(1,10,1):
if(i==3):
print("Se brinca el 3")
continue
elif(i==8):
print("Rompiendo for")
break
print(i)
#FOR y WHILE pueden tener una cláusula ELSE
'''En el caso del for la cláusula se ejecuta cuando finaliza el el for pero no cuando termina por un break
En el caso de while la cláusula se ejecuta cuando la condición se vuelve false
'''
for i in "Hola":
print(i)
else:
print("Termino la iteración del for")
y = 3
while(y<10):
y = y + 1
if(y==8):
print("Se rompe el ciclo")
break
print(y)
else:
print("La condición se rompio")
|
a63b118187b8131a385603eca1551f98b5a74009 | rafaelperazzo/programacao-web | /moodledata/vpl_data/13/usersdata/109/4753/submittedfiles/flipper.py | 300 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CÓDIGO AQUI
P=input('Digite a posição de P:')
R=input('Digite a posição de R:')
if P==1 and R==0:
print('B')
if P==1 and R==1:
print('A')
if P==0 and R==0:
print('C')
if P==0 and R==1:
print('c')
|
068239d4e6776599bad54ccf91d05e18b9952b02 | jpaulopd/IFB | /202001/lp2/codigos/adivinhacaoPart.py | 1,516 | 3.96875 | 4 | print("*********************************")
print("Bem vindo ao jogo de adivinhação!")
print("*********************************")
#numero_secreto = random.randrange(1, 101) # 0.0 1.0
#pontos = 1000
#print("Qual o nível de dificuldade?")
#print("(1) Fácil ")
#print("(2) Médio ")
#print("(3) Difícil ")
#nivel = int(input("Digite o nível: "))
#if (nivel == 1):
# total_de_tentativas = 20
#elif (nivel == 2):
# total_de_tentativas = 10
#else:
# total_de_tentativas = 5
rodada = 1
total_de_tentativas = 3
numero_secreto = 42
for rodada in range(rodada, total_de_tentativas + 1):
print(f"Tentativa {rodada} de {total_de_tentativas}")
chute = int(input("Digite um número entre 1 e 100: "))
print(f"Você digitou {chute:0d}")
acertou = chute == numero_secreto
maior = chute > numero_secreto
menor = chute < numero_secreto
# if (chute < 1 or chute > 100):
# print("Você deve digitar um valor entre 1 e 100!")
# continue
if (acertou):
# print("Você acertou e fez {} pontos!".format(round(pontos)))
print(f"Você acertou!Rodada {rodada} de {total_de_tentativas} tentativas")
break
else:
if (maior):
print(f"Você errou! O seu chute foi maior que o número secreto.")
elif (menor):
print("Você errou! O seu chute foi menor que o número secreto.")
# pontos_perdidos = abs(numero_secreto - chute) / 3
# pontos = pontos - pontos_perdidos
rodada += 1
print("fim do jogo") |
d4617ea452a253fc454b2b7781e032df1bc67f79 | jlassi1/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 400 | 4.25 | 4 | #!/usr/bin/python3
"""module"""
def write_file(filename="", text=""):
"""function that writes a string to a text file (UTF8)
and returns the number of characters written"""
with open(filename, mode="w", encoding="UTF8") as myfile:
myfile.write(text)
num_char = 0
for word in text:
for char in word:
num_char += 1
return num_char
|
fbe4f078636bed0a0070a3e192a279a8cce776e4 | manelbonilla/hackerrank | /Artificial_Intelligence/Tic tac toe Random.py | 665 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
from random import shuffle
import re
import sys
def print_board(board):
for r in board:
for c in r:
print(c, end='')
print("")
def nextMove(player, board):
available = []
for i1 in range(3):
for i2 in range(3):
cell = board[i1][i2]
if cell != 'X' and cell != 'O': available.append((i1, i2))
shuffle(available)
move = available[0]
print(move[0], move[1])
if __name__ == '__main__':
player = input().split()
r1 = list(input())
r2 = list(input())
r3 = list(input())
r = [ r1, r2, r3]
nextMove(player, r)
#nextMove("X", [list("___"), list("___"), list("_XO")])
|
8289efd5c2efb55c9b4a2a627d79d3536fa7ce16 | Abbath90/python_epam | /homework9/task1/merge_sorted.py | 570 | 4 | 4 | """
Write a function that merges integer from sorted files and returns an iterator
file1.txt:
1
3
5
file2.txt:
2
4
6
#>>> list(merge_sorted_files(["file1.txt", "file2.txt"]))
[1, 2, 3, 4, 5, 6]
"""
from pathlib import Path
from typing import Iterator, List, Union
def merge_sorted_files(file_list: List[Union[Path, str]]) -> Iterator:
list_of_numbers = []
for file in file_list:
with open(file) as file_object:
for line in file_object.readlines():
list_of_numbers.append(int(line))
return iter(sorted(list_of_numbers))
|
c87262ffcb67a750c9fd4870568d268cbb9349f8 | baxievski/exercism | /python/matching-brackets/matching_brackets.py | 642 | 3.890625 | 4 | import re
def is_paired(input_string):
cleaned_string = re.sub(r"[^\[\]\(\)\{\}]", "", input_string)
stack = []
opening_braces = "({["
closing_braces = ")}]"
for current_brace in cleaned_string:
if current_brace in opening_braces:
stack.append(current_brace)
continue
if len(stack) == 0:
return False
last_brace = stack.pop()
opening_brace = opening_braces[closing_braces.index(current_brace)]
if last_brace != opening_brace:
return False
return len(stack) == 0
if __name__ == "__main__":
print(f"{is_paired('([])[]')=}")
|
34215b22a77ca423d121f8cc710eefad327f0c21 | hexinyu1900/PythonPractice | /GuessNumber.py | 472 | 3.84375 | 4 | import random
guess = []
answer = []
number = 0
for i in range(3):
A = random.randint(1, 3)
B = random.randint(1, 3)
guess.append(A)
answer.append(B)
if A == B:
number += 1
continue
print("guess =", guess, ", answer =", answer)
print(number)
if number == 0:
print("小A一次都没猜对")
elif number == 1:
print("小A猜中了一次")
elif number == 2:
print("小A猜中了两次")
else:
print("小A全部猜中了")
|
0a26588eea2ed870164149d8a22106961e2a02a8 | BettyAtt/myWork | /week07/lecture/followAlong.py | 759 | 4.25 | 4 | # This program is to demonstrate files
# follow along to the lecture
# Author Betty Attwood
# Credit Andrew Beatty's code
with open(".\lecture1.txt", "w") as f:
print ("create a file")
# mode r won't work, as won't r+
# 'a' append mode will work,
# x wont work as file exists
with open("textData.txt", "rt") as f :
#data = f.read(2)
#print (data)
for line in f:
# includes each of the lines for f
print("we got: ", line.strip())
# strip gets ride of spaces & carriage returns
# writing to a file
#with open("output.txt", "wt") as f:
with open("output.txt", "at") as f:
f.write("boo hoo\n")
#chaning the above will overwrite the file
# if you don't want to over write use append
print("my data", file=f) |
df1aa8e782cecb338e5467912ebb965d8b9de8ab | patkub/userscripts | /scripts/zoom.us logger/chatlogger.sh | 1,007 | 3.8125 | 4 | #!/usr/bin/env python3
import argparse, json, textwrap
# python chatlogger.py chat.json
# python chatlogger.py chat.json --output chat.txt
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Usage Examples:
Display chat from file:
python chatlogger.py chat.json
Display and output chat to file:
python chatlogger.py chat.json --output chat.txt
''')
)
parser.add_argument("chat", type=str, help='chat json file')
parser.add_argument('--output', metavar='OUTPUT', type=str, help='output file to save chat text to')
args = parser.parse_args()
chat_log = list()
with open(args.chat, "r") as f:
data = json.load(f)
for message in data:
chat_log.append("[" + message['time'] + "] " + message['username'] + ": " + message['content'])
for msg in chat_log:
print(msg)
if args.output:
with open(args.output, "w+") as f:
f.writelines("%s\n" % msg for msg in chat_log)
|
b8ad68ca372a4e45e09306f0d869fa420bacf25a | ajrinanw/Python-Projects-Protek | /Chapter 05/Praktikum 2/Latihan 05.py | 601 | 3.78125 | 4 | #CHAP.05 PRAK.02 LATIHAN 05
from random import randint
bil = randint(0,100)
print("Hi.. Nama saya Mr.Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 1 sampai dengan 100. Silahkan tebak ya..!!")
tebakan = int(input("Tebakan Kamu :"))
while True:
if (tebakan > bil):
print ("Yahhh tebakan mu terlalu besar, coba lagi")
tebakan = int(input("Tebakan Kamu :"))
elif (tebakan < bil):
print ("Yahhh tebakan mu terlalu kecil, coba lagi")
tebakan = int(input("Tebakan Kamu :"))
else :
print ("Yeayy tebakan mu BENAR")
break
|
662023d77d0b173a8f99386279032b958513237d | RockutSaben/Codechef_Solutions | /DSA_Learning_Series/Easy_Problems_to_Get_Started/1__Buy_Please.py | 1,353 | 3.703125 | 4 | #Question
'''Chef went to a shop and buys 'a' pens and 'b' pencils. Each pen costs 'x' units and
each pencil costs 'y' units. Now find what is the total amount Chef will spend to buy
'a' pens and 'b' pencils.
INPUT:
First-line will contain 4 space separated integers a, b, x and y respectively.
Output:
Print the answer in a new line.
Constraints:
1 ≤ a, b, x, y ≤ 10^3
Sample Input 1:
2 4 4 5
Sample Output 1:
28
Sample Input 2:
1 1 4 8
Sample Output 2:
12
Explanation:
- In the first example, total cost is (2 * 4 + 4 * 5) = 28.
- In the second example, total cost is (1 * 4 + 1 * 8) = 12.
'''
#NOTE: Please do not copy and paste, kindly try to understand and apply on your own.
#Solution
#use try and except as without them you might get EOF (End of file) error
try:
#using input().split() to split the total input string into a list of multiple strings containing the individual numbers
# Applying map(int, input().split()) to convert every individual strings into integers
# Realloting the integers into respective variables
no_of_pens, no_of_pencils, cost_per_pen, cost_per_pencil = list(map(int, input().split()))
#calculating the total amount
total_amount_spent = no_of_pens*cost_per_pen + no_of_pencils*cost_per_pencil
#printing the desired output
print(total_amount_spent)
except:
pass
|
7c8f97151a1212f568fb6a30217ea69617d3da4b | xiaoyueli/MOOC | /DatastructureAndAlgorithm/DataStructure-ZhejiangU(20160229-20160603)/week9_InsertionOrHeapSort.py | 2,293 | 3.796875 | 4 | def check(lst1, lst2):
for idx in range(len(lst1)):
if lst1[idx] != lst2[idx]:
return False
return True
def printOut(lst):
result = ""
for idx in range(len(lst)):
result += str(lst[idx])
if idx != len(lst) - 1:
result += " "
print(result)
def insertSort(poto, candi):
def insertSub(sub, num):
sub.append(num)
for idx in range(len(sub) - 1, 0, -1):
if sub[idx] < sub[idx - 1]:
temp = sub[idx]
sub[idx] = sub[idx - 1]
sub[idx - 1] = temp
else:
break
if check(poto, candi):
return
new = []
flag = False
while poto:
insertSub(new, poto.pop(0))
inte_r = new + poto
if flag:
printOut(inte_r)
return
if check(candi, inte_r):
print("Insertion Sort")
flag = True
def buildMaxHeap(lst, root, length):
lson = root * 2 + 1
value = lst[root]
while lson <= length - 1:
next_r = lson
if lson < length - 1 and lst[lson] < lst[lson + 1]:
next_r = lson + 1
if value < lst[next_r]:
lst[root] = lst[next_r]
root = next_r
lson = root * 2 + 1
else:
break
lst[root] = value
def heapSort(lst, candi):
# (len(lst) - 1) // 2 is the idx of the last item's parent
# travel all the nodes with children to build MaxHeap
for root in range((len(lst) - 1) // 2, -1, -1):
buildMaxHeap(lst, root, len(lst))
flag = False
for rear in range(len(lst) - 1, -1, -1):
if flag:
printOut(lst)
return
if check(lst, candi):
print("Heap Sort")
flag = True
temp = lst[rear]
lst[rear] = lst[0]
lst[0] = temp
buildMaxHeap(lst, 0, rear)
def scanMethod(meth1, meth2, poto, candi):
meth1(list(poto), list(candi))
meth2(list(poto), list(candi))
def main():
nums = int(input())
poto = input().split()
candi = input().split()
for idx in range(nums):
poto[idx] = int(poto[idx])
candi[idx] = int(candi[idx])
scanMethod(insertSort, heapSort, poto, candi)
main()
|
3f2b5572d68041e137d22ccc8e09a8ea68917915 | jenamico/Markov-Chains | /markov.py | 1,485 | 3.859375 | 4 | #!/usr/bin/env python
from sys import argv
def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
markov_dictionary = {}
filename = open(corpus, 'r')
read_file = filename.read()
words = read_file.split()
for word_index in range(0, len(words) - 2):
key = (words[word_index], words[word_index + 1])
value = words[word_index + 2]
# markov_dictionary[(words[word_index], words[word_index + 1])] = markov_dictionary.((words[word_index], words[word_index + 1])) [words[word_index + 2]]
if key not in markov_dictionary:
markov_dictionary[key] = [value]
else:
markov_dictionary[key].append(value)
return markov_dictionary
def make_text(chains):
"""Takes a dictionary of markov chains and returns random text
based off an original text."""
import random
starting_point = random.choice(chains.keys())
print
#pick a random value based on random key
#intiate a list or string
#new key = index 1 from tuple + value
#in a while loop
# break if key = none
#return string or list
return "Here's some random text."
def main():
#Change this to read input_text from a file
script, filename = argv
input_text = "Would you, could you in"
chain_dict = make_chains(filename)
crandom_text = make_text(chain_dict)
# print random_text
if __name__ == "__main__":
main()
|
870e997d7d5f2c2309bf873381c1af7274101019 | amalmhn/PythonDjangoProjects | /flow_controls/looping_statements/for_loop/nested_forloop2.py | 156 | 3.546875 | 4 | # *
# **
# ***
# ****
#4 coloumn and row
for row in range(1,5): #row=1
for coloumn in range(0,row): #col(0,2)
print("*", end=" ")
print()
|
707ae372b77d660e8ff670ac5c3339e9f5bf6ea9 | chunche95/ProgramacionModernaPython | /IntroductionToPythonAndProgrammingBasic-Cisco-master/contents/programs/3.1.6.6Operators on lists-in and not in.py | 91 | 3.65625 | 4 | myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList) |
4d417102aa34855ad57372c209adee03a905569b | NikoTaga/Python-algorithms-and-data-structures | /lesson_3/task_3.py | 746 | 4.21875 | 4 | '''
В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
разбор не смотрел
'''
import random
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
min_elem = MAX_ITEM
min_index = 0
max_elem = 0
max_index = 0
for i, item in enumerate(array):
if min_elem > item:
min_elem = item
min_index = i
if max_elem < item:
max_elem = item
max_index = i
print(f'min-{min_elem}, index-{min_index}')
print(f'max-{max_elem}, index {max_index}')
array[min_index], array[max_index] = array[max_index], array[min_index]
print(array)
|
712eabb773bb1a1b997b1f745110570bf8ea7d95 | thuspatrick/PYTHON-EXERCICES | /exercices/morefizzbuzz.py | 933 | 3.96875 | 4 | # Nettoyer la console avant le demarrage du programme #
import os
os.system('clear')
#######################################################
##################
# counting FIZZBUZZ #
#################
num = 1
fizzes = 0
buzzes = 0
fizzbuzzes = 0
fizval = []
buzval = []
fizbuzval = []
while num <= 1000:
if ((num % 3) == 0) and ((num % 5) == 0):
print("FIZZBUZZ " + str(num) + " est divisible par 3 et 5")
fizzbuzzes += 1
fizbuzval.append(num)
elif (num % 5) == 0:
print("BUZZ " + str(num) + " est divisible par 5")
buzzes += 1
buzval.append(num)
elif (num % 3) == 0:
print("FIZZ " + str(num) + " est divisible par 3")
fizzes += 1
fizval.append(num)
else:
print(num)
num += 1
print("\nFizzes = " + str(fizzes))
print("All Fizzes : " + str(fizval))
print("\nBuzzes = " + str(buzzes))
print("All Buzzes : " + str(buzval))
print("\nFizzbuzzes = " + str(fizzbuzzes))
print("All Fizzbuzzes : " + str(fizbuzval)) |
7a5d27ee02dfe26b5477bab87e21ae06a63f4639 | ajoyoommen/aichallenge-ants | /bots/MyBot.py | 5,263 | 3.78125 | 4 | #!/usr/bin/env python
# define a class with a do_turn method
# the Ants.run method will parse and update bot input
# it will also run the do_turn method for us
import random
from ants import Ants
class MyBot:
def __init__(self):
obstacles = []
def distance(self, ants, loc1, loc2):
'calculate the closest distance between to locations'
row1, col1 = loc1
row2, col2 = loc2
d_col = min(abs(col1 - col2), ants.cols - abs(col1 - col2))
d_row = min(abs(row1 - row2), ants.rows - abs(row1 - row2))
return d_row + d_col
def direction(self, ants, loc1, loc2):
'determine the 1 or 2 fastest (closest) directions to reach a location'
row1, col1 = loc1
row2, col2 = loc2
height2 = ants.rows//2
width2 = ants.cols//2
d = []
if row1 < row2:
if row2 - row1 >= height2:
d.append('n')
if row2 - row1 <= height2:
d.append('s')
if row2 < row1:
if row1 - row2 >= height2:
d.append('s')
if row1 - row2 <= height2:
d.append('n')
if col1 < col2:
if col2 - col1 >= width2:
d.append('w')
if col2 - col1 <= width2:
d.append('e')
if col2 < col1:
if col1 - col2 >= width2:
d.append('e')
if col1 - col2 <= width2:
d.append('w')
return d
def do_setup(self, ants):
self.hills = []
self.unseen = []
for row in range(ants.rows):
for col in range(ants.cols):
self.unseen.append((row, col))
def do_turn(self, ants):
orders = {}
targets = {}
def do_move_direction(loc, direction):
"""
Issues order to move in a direction if
- Loc is unoccupied
- Loc has not already been issued an order
"""
new_loc = ants.destination(loc, direction)
if (ants.unoccupied(new_loc) and new_loc not in orders):
ants.issue_order((loc, direction))
orders[new_loc] = loc
return True
else:
return False
def do_move_location(loc, dest):
"""
Moves in a direction towards a location. Adds dest to targets
"""
directions = self.direction(ants, loc, dest)
for direction in directions:
if do_move_direction(loc, direction):
targets[dest] = loc
return True
return False
# Clear orders to my hills
for hill_loc in ants.my_hills():
orders[hill_loc] = None
# find close food
ant_dist = []
for food_loc in ants.food():
for ant_loc in ants.my_ants():
dist = self.distance(ants, ant_loc, food_loc)
ant_dist.append((dist, ant_loc, food_loc))
ant_dist.sort()
for dist, ant_loc, food_loc in ant_dist:
if food_loc not in targets and ant_loc not in targets.values():
do_move_location(ant_loc, food_loc)
# attack hills
for hill_loc, hill_owner in ants.enemy_hills():
if hill_loc not in self.hills:
self.hills.append(hill_loc)
ant_dist = []
for hill_loc in self.hills:
for ant_loc in ants.my_ants():
if ant_loc not in orders.values():
dist = ants.distance(ant_loc, hill_loc)
ant_dist.append((dist, ant_loc, hill_loc))
ant_dist.sort()
for dist, ant_loc, hill_loc in ant_dist:
do_move_location(ant_loc, hill_loc)
# explore unseen areas
for loc in self.unseen[:]:
if ants.visible(loc):
self.unseen.remove(loc)
if self.unseen:
for ant_loc in ants.my_ants():
if ant_loc not in orders.values():
unseen_dist = []
for unseen_loc in self.unseen:
dist = ants.distance(ant_loc, unseen_loc)
unseen_dist.append((dist, unseen_loc))
unseen_dist.sort()
for dist, unseen_loc in unseen_dist:
if do_move_location(ant_loc, unseen_loc):
break
# unblock own hill
for hill_loc in ants.my_hills():
if hill_loc in ants.my_ants() and hill_loc not in orders.values():
for direction in ('s', 'e', 'w', 'n'):
if do_move_direction(hill_loc, direction):
break
if __name__ == '__main__':
# psyco will speed up python a little, but is not needed
try:
import psyco
psyco.full()
except ImportError:
pass
try:
# if run is passed a class with a do_turn method, it will do the work
# this is not needed, in which case you will need to write your own
# parsing function and your own game state class
Ants.run(MyBot())
except KeyboardInterrupt:
print('ctrl-c, leaving ...')
|
07e1aea139b7ce45146ecfd7306e16fa1ced6060 | macmiles/tic-tac-toe-player-vs-ai | /app.py | 9,967 | 4.125 | 4 | # PYTHON BASED TIC-TAC-TOE GAME WITH A WORKING AI
# AUTHOR: SELIM CAM
# DATE: 09.22.2017
# X | O | X
# --- --- ---
# O | X | O
# --- --- ---
# X | O | X
import random
# set value to 1 to better understand how the AI algorithm makes decisions
debug_mode = 0
# default user symbols
player = "X"
ai = 'O'
# default grid list
number_list = list(range(1, 10))
corner_list = [1, 3, 7, 9]
def print_gui(grid):
print('')
print(' %s | %s | %s ' % (grid[0], grid[1], grid[2]))
print('--- --- ---')
print(' %s | %s | %s ' % (grid[3], grid[4], grid[5]))
print('--- --- ---')
print(' %s | %s | %s ' % (grid[6], grid[7], grid[8]))
print('')
def check_winner(grid):
# winner = 0 (default), 1 (player wins), 2 (ai wins), 3 (tie)
winner = 0
turn_list = [player, ai]
for turn in turn_list:
# horizontal check
for i in range(3):
if grid[0 + (i * 3)] == turn and grid[1 + (i * 3)] == turn and grid[2 + (i * 3)] == turn:
if turn == player:
winner = 1
else:
winner = 2
break
# vertical check
for j in range(3):
if grid[0 + j] == turn and grid[3 + j] == turn and grid[6 + j] == turn:
if turn == player:
winner = 1
else:
winner = 2
break
# diagonal check
if grid[0] == turn and grid[4] == turn and grid[8] == turn:
if turn == player:
winner = 1
else:
winner = 2
break
if grid[2] == turn and grid[4] == turn and grid[6] == turn:
if turn == player:
winner = 1
else:
winner = 2
break
# checks to see how many of the cells in the grid have been selected
selected_cells = 0
for each in grid:
if each not in number_list:
selected_cells += 1
# if all cells in the grid have been selected and there's still no winner, we have a tie game (winner == 3)
if selected_cells == 9:
winner = 3
return winner
def cost_check(turn, grid):
# grid stores all the possible moves and their respective costs to win using that route
cost_result = []
# determine who opponent is
if turn == player:
opponent = ai
else:
opponent = player
# horizontal check
for i in range(3):
range_index = [0 + (i * 3), 1 + (i * 3), 2 + (i * 3)]
chosen = []
available = []
for k in range_index:
if grid[k] in number_list:
available.append(k + 1)
elif grid[k] == turn:
chosen.append(k + 1)
cost_result.append({'chosen': chosen, 'available': available})
# vertical check
for j in range(3):
range_index = [0 + j, 3 + j, 6 + j]
chosen = []
available = []
for k in range_index:
if grid[k] in number_list:
available.append(k + 1)
elif grid[k] == turn:
chosen.append(k + 1)
cost_result.append({'chosen': chosen, 'available': available})
# diagonal 1 check
range_index = [0, 4, 8]
chosen = []
available = []
for k in range_index:
if grid[k] in number_list:
available.append(k + 1)
elif grid[k] == turn:
chosen.append(k + 1)
cost_result.append({'chosen': chosen, 'available': available})
# diagonal 2 check
range_index = [2, 4, 6]
chosen = []
available = []
for k in range_index:
if grid[k] in number_list:
available.append(k + 1)
elif grid[k] == turn:
chosen.append(k + 1)
cost_result.append({'chosen': chosen, 'available': available})
return cost_result
def ai_logic(grid):
# pulls cost analysis for all the possible moves the player can make
player_cost = cost_check(player, grid)
# pulls cost analysis for all the possible moves the AI can make
ai_cost = cost_check(ai, grid)
# if debug mode is activated (debug_mode == 1), player and ai cost analysis for all possible moves is diplayed
if debug_mode == 1:
print('### Player Cost:', player_cost)
print('### AI Cost:', ai_cost)
ai_cell_selection = []
player_cell_selection = []
# check to see if player is one move away from winning
for each in player_cost:
if len(each['available']) == 1 and len(each['chosen']) == 2:
player_cell_selection.append(each['available'][0])
break
# check to see if AI is one move away from winning
for each in ai_cost:
if len(each['available']) == 1 and len(each['chosen']) == 2:
ai_cell_selection.append(each['available'][0])
break
# check to see if player or AI is one move away from winning
if player_cell_selection or ai_cell_selection:
# if AI is one move away from winning, then always go with AI's last cell first; otherwise, block the player's last cell
if ai_cell_selection:
cell_selection = ai_cell_selection[0]
else:
cell_selection = player_cell_selection[0]
else:
# list keeps track of cells chosen - ai uses this to win
if grid[4] != player and grid[4] != ai:
cell_selection = 5
else:
# find the min cost move
min_cost_value = 99999
min_cost_index = 0
for z, each in enumerate(ai_cost):
# cell count will be equal to 3 if opponent hasn't select a cell in this block of cells
cell_count = len(each['available']) + len(each['chosen'])
if cell_count == 3:
if len(each['available']) < min_cost_value:
min_cost_value = len(each['available'])
min_cost_index = z
# if there are no viable moves for the AI to win and the player isn't one move away from winning, the else condition will trigger and the first available move is selected by the AI
if min_cost_value != 99999:
cell_selection = random.choice(
ai_cost[min_cost_index]['available'])
for each in ai_cost[min_cost_index]['available']:
if each in corner_list:
cell_selection = each
break
else:
for each in ai_cost:
if len(each['available']) > 0:
cell_selection = random.choice(each['available'])
break
return cell_selection
def main():
# app header
print(
'TIC-TAC-TOE GAME BY SELIM CAM [NOTE: enter "q" to quit at any time]')
print('===================================================================')
# set winner to default value
winner = 0
# player gets to go first because humans > AI
current_player = 1
# grid is set to a default list of values 1-9
grid = number_list[:]
# print tic-tac-toe grid for the first time
print_gui(grid)
# loops until there's a winner or all the cells on the grid are full
while winner == 0:
error_check = 0
if current_player == 1: # USER ACTIONS
# continuous loop used for error validation
while error_check == 0:
# selects user input
x = input(">> It's your move, please choose a cell: ")
# input value of 'q' quits the app
if x.lower() == 'q':
return
try:
# convert string input to an int
x = int(x)
# checks to see if the input is a value between 1-9
if x not in number_list:
print(
'Error - enter a number between 1-9 to select a cell on the grid.')
else:
# validation to check if the chosen cell is empty
if grid[x - 1] not in number_list:
print('Error - that cell is already taken. Try again.')
else:
error_check = 1 # if this executes, then error check was passed
except ValueError:
print(
'Error - make sure to enter a number. Preferably one that\'s between 1-9.')
# execute the players move
grid[x - 1] = player
# switch turns
current_player = 2
else: # AI ACTIONS
# logic determines best possible move for AI
x = ai_logic(grid)
print('## AI HAS PICKED CELL %s ##' % (x))
# executes best possible move for AI
grid[x - 1] = ai
# switch turns
current_player = 1
# check if the game has ended
winner = check_winner(grid)
# print current state of tic-tac-toe board after AI's turn or after the game has ended
if current_player == 1 or winner != 0:
print_gui(grid)
# remind the user that he's a mere mortal and will probably never win
if winner != 0:
if winner == 1:
print("Victory! Congrats you have achieved the impossible.")
elif winner == 2:
print("Defeat! It's okay, you have proven that you're only human. Well, a blind human. Honestly, how did you not see that?")
elif winner == 3:
print("Tie. Can't say I didn't see that coming.")
# prompt user to try again
y = input(">> Care to try again? [y/n] ")
if y.lower() == 'yes' or y.lower() == 'y':
main()
if __name__ == "__main__":
main()
|
ac9e021f5b559422c8e5e412b0063f5374ccf08d | niketanrane/CodingDecoding | /Codeforces/141A.py | 222 | 3.5 | 4 | if __name__ == "__main__":
guest = input()
host = input()
total = sorted(input())
guest += host
guest = sorted(guest)
if guest == total:
print("YES")
else:
print("NO") |
5992e0e3fa55a4124524315a6b1e93b7773a7b4d | snguy3nn/data_structures | /linkedlist.py | 556 | 3.828125 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_node(self, data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
return
else:
self.tail.next = node
self.tail = self.tail.next
def add_to_beginning(self, data):
new_node = Node(data)
new_node.ref = self.head
self.head = new_node
# ???
def contains_node(self):
pass
|
970ebbabab0ea06d80bf04fc99704fad50a0f351 | samprasgit/leetcodebook | /python/34_FindFirstandLastPositionofElementinSortedArray.py | 910 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/28 4:54 PM
# @Author : huxiaoman
# @File : 34_FindFirstandLastPositionofElementinSortedArray.py
# @Package : LeetCode
# @E-mail : charlotte77_hu@sina.com
class Solution:
def searchRange(self, nums, target):
left_idx = self.extreme_insertion_index(nums, target, True)
if left_idx == len(nums) or nums[left_idx] != target:
return [-1, -1]
return [left_idx, self.extreme_insertion_index(nums, target, False)-1]
def extreme_insertion_index(self, nums, target, left):
lo = 0
hi = len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > target or (left and target == nums[mid]):
hi = mid
else:
lo = mid+1
return lo
if __name__=='__main__':
s = Solution()
print s.searchRange([5,7,7,8,8,10],8) |
8e70258ed9e546cd440c0b0cfbbfdd440cb7f845 | catoostrophe/MP1---Morpion | /Morpion vs AI.py | 4,687 | 3.75 | 4 | import random,time
#Liste des valeurs_tableau possibles du robot
liste_robot=[]
#Liste des valeurs du tableau:
valeurs_tableau = []
#Les listes prennent les valeurs de 0 à 8 (qui représentent alors les cases du tableau et les valeurs_tableau possibles du robot et du joueur).
for x in range (0, 9):
valeurs_tableau.append(x)
liste_robot.append(x)
#Fonction permettant l'affichage du tableau qui sera mis à jour après chaque tour
def tableau():
print() #choix esthétique : plus espacé
print(valeurs_tableau[0], valeurs_tableau[1], valeurs_tableau[2]) #ligne 1 du tableau
print(valeurs_tableau[3], valeurs_tableau[4], valeurs_tableau[5]) #ligne 2 du tableau
print(valeurs_tableau[6], valeurs_tableau[7], valeurs_tableau[8]) #ligne 3 du tableau
print() #choix esthétique
#Fonction mise en place lorsque c'est le tour du joueur
def tour_joueur():
J1=int(input("Quelle case choisissez-vous? ")) #Le joueur choisit la case où il veut placer son symbole. ATTENTION : un caractère autre qu'un chiffre va arrêter le programme.
if J1 in valeurs_tableau: #Vérification du saisi du joueur 1:
for x in range (0,9): #Le numéro de case choisi par le joueur 1 sera remplacé par "X" si c'est un chiffre compris entre 0 et 8 (9-1).
if valeurs_tableau[J1]==x:
valeurs_tableau[J1]="X"
liste_robot.remove(x) #Enlève la case choisie par le joueur des choix possibles pour le robot.
else: #Lorsque le chiffre saisi n'est pas un chiffre/nombre compris entre 0 et 8 où qu'il est déjà pris, le joueur 1 devra rejouer.
print()
print("Pas possible. Saisissez un chiffre entre 0 et 8 qui n'est pas déjà pris.")
print()
tour_joueur()
#Fonction mise en place lorsque c'est le tour du robot
def tour_robot():
J2 = random.choice(liste_robot) #le robot choisit une valeur au hasard dans la liste des choix
print()
print("Le robot a choisi la case ",J2,"!")
print()
for x in range (0,9):
if valeurs_tableau[J2]==x:
valeurs_tableau[J2]="O"
liste_robot.remove(x) #Enlève la case choisie par le robot des choix possibles pour le robot.
#Fonction régulant les tours
def tour():
tours=1 #Nombre de tours
while tours<=9: #Tant qu'il n'y a pas d'égalité
if tours%2==0: #Le nombre de tours sera pair lorsque c'est le tour du robot et impair lorsque c'est le tour du joueur
tour_robot()
tableau()
else:
tour_joueur()
tours=tours+1
if gagnant()==True: #Si le joueur a gagné
tableau()
print("Vous avez gagné! :)")
time.sleep(2)
exit()
if gagnant()==False: #Si le joueur a perdu
tableau()
print("Vous avez perdu! :(")
time.sleep(2)
exit()
print()
print("Egalité! Recommencez le programme pour un nouveau jeu.")
def gagnant(): #On teste toutes les combinaisons possibles permettant la victoire.
if valeurs_tableau[0]==valeurs_tableau[1]==valeurs_tableau[2]=="X" or valeurs_tableau[3]==valeurs_tableau[4]==valeurs_tableau[5]=="X" or valeurs_tableau[6]==valeurs_tableau[7]==valeurs_tableau[8]=="X" or valeurs_tableau[0]==valeurs_tableau[3]==valeurs_tableau[6]=="X" or valeurs_tableau[1]==valeurs_tableau[4]==valeurs_tableau[7]=="X" or valeurs_tableau[2]==valeurs_tableau[5]==valeurs_tableau[8]=="X" or valeurs_tableau[0]==valeurs_tableau[4]==valeurs_tableau[8]=="X" or valeurs_tableau[2]==valeurs_tableau[4]==valeurs_tableau[6]=="X": #Pour tester si le joueur 1 a gagné
return True
elif valeurs_tableau[0]==valeurs_tableau[1]==valeurs_tableau[2]=="O" or valeurs_tableau[3]==valeurs_tableau[4]==valeurs_tableau[5]=="O" or valeurs_tableau[6]==valeurs_tableau[7]==valeurs_tableau[8]=="O" or valeurs_tableau[0]==valeurs_tableau[3]==valeurs_tableau[6]=="O" or valeurs_tableau[1]==valeurs_tableau[4]==valeurs_tableau[7]=="O" or valeurs_tableau[2]==valeurs_tableau[5]==valeurs_tableau[8]=="O" or valeurs_tableau[0]==valeurs_tableau[4]==valeurs_tableau[8]=="O" or valeurs_tableau[2]==valeurs_tableau[4]==valeurs_tableau[6]=="O": #Pour tester si le joueur 2 a gagné
return False
#Commence le jeu
print("Ce jeu est un jeu de morpion classique. Veuillez entrer un chiffre de 0 à 8 qui correspondra au numéro de la case où vous voulez placer votre symbole. Le joueur 1 sera représenté par le symbole 'X' et le joueur 2 par le symbole 'O'.")
print()
tableau() #Affiche le tableau de début (avec seulement les chiffres)
tour()
gagnant()
|
ef63eab8f64d95054655dfe9ec440289d28dc67b | nhenninger/CrackingTheCodingInterview6e | /ch04_Trees_and_Graphs/q04_09_bst_sequences.py | 1,443 | 3.609375 | 4 | from nodes import BinaryTreeNode as BTNode
# 4.9 BST Sequences
def bst_sequences(root: BTNode) -> list:
"""
Prints all possible arrays that could produce the given binary search tree
Assumes tree contains distinct elements.
Not thread safe.
Runtime: O(2^n)
Memory: O(2^n)
"""
arrays = []
if root is None:
arrays.append([])
return arrays
prefix = [root.data]
left_sequence = bst_sequences(root.left)
right_sequence = bst_sequences(root.right)
# Weave together
for left in left_sequence:
for right in right_sequence:
weave = []
_weave_lists(left, right, weave, prefix)
arrays.extend(weave)
return arrays
def _weave_lists(first: list, second: list, weave: list, prefix: list) -> None:
# Remove the head from one list, recurse on it, then do the same for the other list.
if len(first) == 0 or len(second) == 0:
clone = prefix.copy()
clone.extend(first)
clone.extend(second)
weave.append(clone)
return
head_of_first = first.pop(0)
prefix.append(head_of_first)
_weave_lists(first, second, weave, prefix)
prefix.pop(len(prefix) - 1)
first.insert(0, head_of_first)
head_of_second = second.pop(0)
prefix.append(head_of_second)
_weave_lists(first, second, weave, prefix)
prefix.pop(len(prefix) - 1)
second.insert(0, head_of_second)
|
3cfe0d970c94d4db59887493089401ca1686a8f9 | SRchary/Python | /PYTHON_BASICS/text_to_speech.py | 760 | 3.578125 | 4 | import pyttsx
engine = pyttsx.init()
engine.say('HELLO ammulu')
engine.setProperty('rate', 100)
engine.say('Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics. ')
engine.say('Hai Swapna')
engine.say('Hai Swapna are you mad')
voice = engine.getProperty('voice')
print voice
#engine.say('Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics. ')
engine.runAndWait()
|
8e72fb71eeaec9570b6721e89afeb3c783af2aac | GiovanniCassani/discriminative_learning | /nonwords/neighbors.py | 6,763 | 3.515625 | 4 | __author__ = 'GCassani'
import helpers as help
from collections import defaultdict, Counter
def map_neighbours_to_pos(neighbours_file, wordform2pos, ids2words):
"""
:param neighbours_file: the file with the neighbours retrieved for each test item: each item is on a different
column, with neighbours retrieved for it in the same column
:param wordform2pos: a dictionary mapping wordforms to the set of pos tags with which the wordform was found in
the input corpus
:param ids2words: a dictionary mapping column indices to test items
:return neighbours: a dictionary mapping each test item to the list of pos tags of the words retrieved as
neighbours. in case a neighbour is ambiguous with respect to the category, all categories
with which it was retrieved are considered
"""
neighbours = defaultdict(list)
with open(neighbours_file, "r") as f:
for line in f:
words = line.strip().split('\t')
for col_id, word in enumerate(words):
if not word in ids2words.values():
if ':' in word:
neighbours[ids2words[col_id]].append(word.split(':')[1])
else:
target_tags = wordform2pos[word]
for tag in target_tags:
neighbours[ids2words[col_id]].append(tag)
return neighbours
########################################################################################################################
def get_tag_distribution(neighbours):
"""
:param neighbours: a dictionary mapping words to the list of pos tags of the neighbors
:return neighbours_distr: a dictionary mapping each test word to each category which appears in the neighborhood
and its frequency of occurrence
:return pos_set: a set containing the unique pos tags found in the neighbours list
"""
neighbours_distr = defaultdict(dict)
pos_set = set()
for word in neighbours:
neighbours_list = neighbours[word]
distr = Counter(neighbours_list)
for pos in distr:
neighbours_distr[word][pos] = distr[pos]
pos_set.add(pos)
return neighbours_distr, pos_set
########################################################################################################################
def write_neighbor_summary(output_file, neighbours_distr, pos_set, table_format="long", cond="minimalist"):
"""
:param output_file: the path where the summary will be written to
:param neighbours_distr: a dictionary mapping words to the pos tags of its neighboring vectors and their
frequency count in the neighbor list
:param pos_set: an iterable of strings, indicating the pos tags encountered across the neighbors
:param cond: a string indicating the input used for the experiment
:param table_format: a string indicating how to print data to table, either 'long' or 'wide'. In the long
format, five columns are created, first the nonword followed by its intended pos tag,
then the condition, then the category, then the frequency. In the wide format, each
category is a different column, with each nonword-category cell indicating how many
neighbors tagged with the category were found in the neighborhood of the nonword.
An extra column indicates the condition.
"""
pos_tags = sorted(pos_set)
with open(output_file, "w") as f:
if table_format == "wide":
f.write("\t".join(["Nonword", "Target", "Condition", "\t".join(pos_tags)]))
f.write('\n')
for word in neighbours_distr:
baseform, target = word.split("|")
counts = []
for tag in pos_tags:
try:
counts.append(str(neighbours_distr[word][tag]))
except KeyError:
counts.append("0")
f.write('\t'.join([baseform, target, cond, '\t'.join(counts)]))
f.write('\n')
elif table_format == "long":
f.write("\t".join(["Nonword", "Target", "Condition", "Category", "Count"]))
f.write('\n')
for word in neighbours_distr:
baseform, target = word.split("|")
for tag in pos_tags:
try:
f.write('\t'.join([baseform, target, cond, tag, str(neighbours_distr[word][tag])]))
except KeyError:
f.write('\t'.join([baseform, target, cond, tag, '0']))
f.write('\n')
else:
raise ValueError("unrecognized format %s!" % table_format)
########################################################################################################################
def nn_analysis(neighbours_file, tokens_file, output_file, cond="minimalist", table_format="long"):
"""
:param neighbours_file: the path to the file containing neighbours for the target words
:param tokens_file: the path to the file containing summary information about tokens, lemmas, pos tags, and
triphones
:param output_file: the path where the summary will be written to
:param cond: a string indicating the input used for the experiment
:param table_format: a string indicating how to print data to table, either 'long' or 'wide'. In the long
format, five columns are created, first the nonword followed by its intended pos tag,
then the condition, then the category, then the frequency. In the wide format, each
category is a different column, with each nonword-category cell indicating how many
neighbors tagged with the category were found in the neighborhood of the nonword.
An extra column indicates the condition.
"""
ids2words = help.map_indices_to_test_words(neighbours_file)
words2pos = help.map_words_to_pos(tokens_file)
neighbors2pos = map_neighbours_to_pos(neighbours_file, words2pos, ids2words)
neighbors_distr, pos_set = get_tag_distribution(neighbors2pos)
write_neighbor_summary(output_file, neighbors_distr, pos_set, cond=cond, table_format=table_format)
|
8657eaabfec2e73566deb7cff77349ae0912b4b5 | boopalanjayaraman/DataStructures_Algorithms | /Big O Analysis - Project 01/Task1.py | 910 | 4.0625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def get_unique_numbers(data_list):
numbers_0 = [record[0] for record in data_list]
numbers_1 = [record[1] for record in data_list]
numbers_0.extend(numbers_1)
unique_numbers = set(numbers_0)
return unique_numbers
if __name__ == '__main__':
all_unique_numbers = get_unique_numbers(texts)
all_unique_numbers.update(get_unique_numbers(calls))
print('There are {0} different telephone numbers in the records.'.format(len(all_unique_numbers))) |
10fc63f6608a45c2a6f4ad9341597205f9446d78 | thapaliya123/Python-Practise-Questions | /data_types/problem_26.py | 463 | 4.34375 | 4 | """
26. Write a Python program to insert a given string at the beginning of all items in
a list.
"""
def insert_string_to_list_at_begining(sample_list, insert_string):
string_to_list = [insert_string+str(item) for item in sample_list]
return string_to_list
sample_list = [1, 2, 3, 4]
insert_string = "emp"
print(f"The list after insert {insert_string} at begining to list{sample_list} is {insert_string_to_list_at_begining(sample_list, insert_string)}")
|
fc6adbaa7407f22b77f62822854978ebc4943187 | thelmuth/cs-101-spring-2021 | /Class32/nyt_satellite_image_manip.py | 4,312 | 3.890625 | 4 | """
Replicates some of the work of this NYT article.
https://www.nytimes.com/interactive/2020/09/02/upshot/america-political-spectrum.html
In particular, we can take an image, sort its pixels by luminance, and make the
new image.
"""
from PIL import Image
import matplotlib.pyplot as plt
def main():
### This is a satellite image of Blue Ridge, VA
# satellite = Image.open("Blue_Ridge.jpg")
satellite = Image.open("Nevada_Summerlin.jpg")
# satellite = Image.open("Hamilton_College.jpg")
satellite.show()
print(satellite.width, satellite.height)
## Sort the picture by luminance and put it back in order
sorted_image = nyt(satellite)
def nyt(image):
"""Replicates the NYT study cited in the docstring."""
pixels = get_all_pixels(image)
print("We have", len(pixels), "pixels")
print("The first 10 pixels are:", pixels[:10])
### Want to sort the pixels by their luminance values
### How can we do that?
print("Starting to find luminance of pixels")
pixels_with_luminance = attach_luminance_to_pixels(pixels)
print("Done finding luminance of pixels")
### Create a dictionary of luminance values
luminance_freq = get_luminance_frequencies(pixels_with_luminance)
print("The first 10 pixels with luminance are:", pixels_with_luminance[:10])
pixels_with_luminance.sort()
print("The first 10 pixels after sorting are:", pixels_with_luminance[:10])
final_gradient = make_image_from_pixel_list(image.width, image.height,
pixels_with_luminance)
final_gradient.show()
### We need:
### List of luminance values from 0 to 255
### List of the counts of luminance values from the dictionary
luminances = []
luminance_freq_list = []
for lum in range(256):
luminances.append(lum)
if lum in luminance_freq:
luminance_freq_list.append(luminance_freq[lum])
else:
luminance_freq_list.append(0)
plt.plot(luminances, luminance_freq_list)
plt.xlabel("Luminance")
plt.ylabel("Frequency")
plt.show()
def get_luminance_frequencies(list_of_lum_and_pixels):
"""Make a dictionary representing the frequencies of luminance values
for this list of luminance/pixel data"""
### Each element is of the form: (luminance, (R, G, B))
lum_freq = {}
for tup in list_of_lum_and_pixels:
lum = tup[0]
if lum not in lum_freq:
lum_freq[lum] = 1
else:
lum_freq[lum] += 1
return lum_freq
def make_image_from_pixel_list(width, height, pixels_with_luminance):
"""Creates a new image with given width and height, filled with the
pixels from pixels_with_luminance."""
new_image = Image.new("RGB", (width, height))
count = 0
# Iterate through the locations in new_image
for y in range(height):
print("building new image at y =", y)
for x in range(width):
pixel_with_luminance = pixels_with_luminance[count]
pixel = pixel_with_luminance[1]
new_image.putpixel((x, y), pixel)
count += 1
return new_image
def attach_luminance_to_pixels(list_of_pixels):
"""Take a list of pixels and make a list of tuples that have luminance
as the first element and the pixel as the second."""
pixels_with_luminance = []
for pixel in list_of_pixels:
pwl = (luminance(pixel), pixel)
pixels_with_luminance.append(pwl)
return pixels_with_luminance
def get_all_pixels(image):
"""Given an image, returns a list of all pixels in the image."""
pixels = []
for y in range(image.height):
print("Gathering pixels, at y = ", y)
for x in range(image.width):
pixel = image.getpixel((x, y))
pixels.append(pixel)
return pixels
def luminance(rgb):
"""Finds the average of r, g, and b components to determine how
bright a pixel is."""
(r, g, b) = rgb
return (r + g + b) // 3
if __name__ == "__main__":
main()
|
aced0d712e9d6aeac84f1e7ea57f438d8cf67d20 | DivyamSingh18/Note_Taker | /main.py | 1,637 | 4.28125 | 4 | print("#################### Welcome to Note_Taker ####################")
print("\n To write a note, enter keyword 'write' ")
print(" To read a note, enter keyword 'read' ")
print(" To append to a note, enter keyword 'append' ")
cmd = input("\n\nWhat operation do you want to perform: ")
if cmd == "write":
n = int(input("Enter the number of notes you want to write:"))
note_taker = open("Your Notes.txt","w")
for i in range(1, n+1):
note_inp = input("Enter your Note: ")
note_taker.write("Note no. ")
note_taker.write(str(i))
note_taker.write("=> ")
note_taker.write(note_inp+"\n")
record = open("record_file.txt", "w")
record.write(str(i))
record.close()
print("Your notes have been saved successfully!")
note_taker.close()
elif cmd == "read":
note_taker = open("Your Notes.txt", "r")
print("Your notes are as follows:")
note_out = note_taker.read()
print(note_out)
note_taker.close()
elif cmd == "append":
note_taker = open("Your Notes.txt", "a")
m = int(input("Enter the number of notes you want to add:"))
x = open("record_file.txt","r")
record = int(x.read())
for i in range(record+1, record+1 +m):
note_apd = input("Enter your Note: ")
note_taker.write("Note no. ")
note_taker.write(str(i))
note_taker.write("=> ")
note_taker.write(note_apd+"\n")
print("Your notes have been added successfully!")
note_taker.close()
else:
print("// Invalid Command //")
|
b8b591909cf25d30d9f984b12b898ec1f54330f7 | mare-astrorum/leetcode-practice | /191009 Watering Plants.py | 3,743 | 3.75 | 4 | """
https://leetcode.com/discuss/interview-question/394347/google-oa-2019-watering-flowers-20
"""
plants = [2, 4, 1, 5, 6, 100]
capacity1 = 5
capacity2 = 7
watering_plants(plants, capacity1, capacity2)
sum(plants)
def watering_plants(plants, capacity1, capacity2):
import copy
refill = 2 # refill starts with 2 because each bucket needs filling
capacity1_starting = copy.deepcopy(capacity1)
capacity2_starting = copy.deepcopy(capacity2)
if len(plants) > 1000:
return "Error, check number of plants"
for plant in plants:
if plant > 1000000000:
return "Error, check plant values"
for i in range(len(plants)):
plant = plants[0]
# When get to the middle, do a final loop.
if len(plants) == 1:
if capacity2 - plant >= 0:
return refill
elif capacity1 - plant >= 0:
return refill
elif capacity1 + capacity2 - plant >= 0:
return refill
else:
capacity1 = capacity1_starting
capacity2 = capacity2_starting
refill += 1
if capacity1 - plant >= 0:
return refill
elif capacity2 - plant >= 0:
refill += 1
return refill
elif capacity1 + capacity2 - plant >= 0:
return refill
else:
refill += 2
plant_watered3 = plant - capacity1 - capacity2
while plant_watered3 >= capacity1 + capacity2:
if plant_watered3 >= capacity1 or capacity2:
refill += 1
elif plant_watered3 >= capacity1 + capacity2:
refill += 2
plant_watered3 = plant_watered3 - capacity1 - capacity2
return refill
# Start with end value in the list
if capacity2 - plants[-1] >= 0:
capacity2 = capacity2 - plants[-1]
plants.pop(-1)
elif capacity2 - plants[-1] < 0:
refill += 1
capacity2 = capacity2_starting
plant_watered2 = plants[-1] - capacity2
while plant_watered2 >= capacity2:
refill += 1
plant_watered2 = plant_watered2 - capacity2
plants.pop(-1)
# Continue with the first value in the list
if capacity1 - plants[0] >= 0:
capacity1 = capacity1 - plants[0]
plants.pop(0)
elif capacity1 - plants[0] < 0:
refill += 1
capacity1 = capacity1_starting
plant_watered1 = plants[0] - capacity1
while plant_watered1 >= capacity1:
refill += 1
plant_watered1 = plant_watered1 - capacity1
plants.pop(0)
#
# """ Generic function """
#def get_to_middle(i, capacity, capacity_starting):
#
# if capacity - plants[i] >= 0:
# capacity = capacity - plants[0]
# plants.pop(i)
# elif capacity - plants[i] < 0:
# refill += 1
# capacity = capacity_starting
# plant_watered = plants[i] - capacity1
# while plant_watered > capacity:
# refill += 1
# plant_watered = plant_watered - capacity
# plants.pop(i)
#
# return refill |
ce8a6daa9183bd168f5e29fa3ffadb43c54c2ea3 | Franklin-Wu/project-euler | /p002.py | 630 | 3.96875 | 4 | # Even Fibonacci numbers
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fibonacci1 = 1;
fibonacci2 = 2;
sum = 0;
while fibonacci1 <= 4000000:
if (fibonacci1 % 2 == 0):
sum += fibonacci1;
print "%d" % fibonacci1;
fibonacci3 = fibonacci1 + fibonacci2;
fibonacci1 = fibonacci2;
fibonacci2 = fibonacci3;
print "sum = %d" % sum;
|
d3c049b91302779f6b13530c6b7ddd53d605ea0a | V2xray1024/pyHack | /replaceTools.py | 682 | 3.515625 | 4 | '''
Description: 命令格式如 python script.py old_str new_str filename
对指定文件内容进行全局替换,并且替换完后打印替换了多少处内容
Author: yrwang
Date: 2021-09-01 18:03:12
LastEditTime: 2021-09-02 21:39:50
LastEditors: yrwang
'''
import sys
# print(sys.argv)
old_str = sys.argv[1]
new_str = sys.argv[2]
filename = sys.argv[3]
# 1 读取文件
f = open(filename, "r+")
data = f.read()
# 2 计算并替换
old_str_count = data.count(old_str)
new_data = data.replace(old_str, new_str)
# 3 清空
f.seek(0)
f.truncate()
# 4 保存新数据
f.write(new_data)
print(f"成功替换了{old_str}为{new_str},一共{old_str_count}处....")
|
ff7488264a00c95c79d309a7e98b0ec2e203e848 | Himanshu091190/IIT_Madras_Python | /yuio.py | 429 | 3.921875 | 4 | ##try:
## print(x)
##except TypeError:
## print("Variable x is not defined")
##except NameError:
## print("Variable x)( is not defined")
##except:
## print("Something else went wrong")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
|
515b3270c9d23082486d984a889b5988f9e39ad0 | wherby/hackerrank | /Algorithms/Oracle/test3.py | 632 | 3.703125 | 4 | #// array, 'a', 'b', 'c'
#// unsorted
#// input -> ['b', 'a', 'b', 'a', 'c', 'a']
#// output ->
def sortls(ls):
pa,pb,pc = 0,0,0
n =len(ls)
for i in range(n):
t= ls[i]
if t == 'a':
pa = pa +1
if t =='b':
pb = pb +1
if t == 'c':
pc = pc +1
print ls
ls =['b', 'a', 'b', 'a', 'c', 'a']
sortls(ls)
pb =0
pa =-1
pa =1
['a', 'b', 'b', 'a', 'c', 'a']
pb = 1
pa =3
['a', 'a', 'b', 'b', 'c', 'a']
pb =2
pa =5
pc =4
['a', 'a', 'a', 'b', 'c', 'b']
pb =3
pa =2
pc =4
['a', 'a', 'a', 'b', 'c', 'b']
pb =5
pa =2
pc =4
['a', 'a', 'a', 'b', 'b', 'c'] |
36ac13bf8bcc2809615491f0f4dd20ae2afd64cc | lee7py/Python-Programming | /Ch03/3-4-2.py | 246 | 3.953125 | 4 | ## Display population from 2014 to 2018.
pop = 300000
print("{0:10} {1}".format("Year", "Population"))
for year in range(2014, 2019):
print("{0:<10d} {1:,d}".format(year, round(pop)))
pop += 0.03 * pop # Increase pop by 3 percent.
|
ab8ac5509b5c801486646cd92a12d021d15d7b52 | xexugarcia95/LearningPython | /CodigoJesus/ProgramacionFuncional/Ejercicio5.py | 299 | 3.859375 | 4 | """Escribir una función que reciba una frase y devuelva un diccionario
con las palabras que contiene y su longitud."""
def apply_func(frase):
lista = frase.split(' ')
diccionario = map(len, lista)
return dict(zip(lista, diccionario))
print(apply_func("hola amigo que tal estas"))
|
c340913ece85820276dcc52273cb0dee7fa46455 | stepus3000/sphinx-msiit | /Sphinx-Project/code_sources/Holmes/doyl.py | 789 | 3.90625 | 4 | import random
error = ["Я не понимаю, введи цифрой.", "Не смешно, давай нормально.", "Очень смешно", "Так трудно ввести пару цифр?", "Неправильный ответ, давай еще раз."]
while True:
year = input("Сколько тебе лет? ")
try:
answer = int(year)
if 0 <= answer <= 140:
print("Крутяк!")
break
elif answer < 0:
print("Да ладно, ты не можешь быть младше новорденного.")
elif answer > 140:
print("Давай честно, я не верю, что это твой возраст")
except ValueError:
print(random.choice(error))
|
9219fec726d71c657c0f6203e38fcf3c1902bc67 | Adarsh0047/Object-Oritented-Programming | /Oops/user_defined_exception.py | 106 | 3.765625 | 4 | y=input("Please enter a positive number: \n")
if int(y) <=0:
raise ValueError("Negative Number")
|
b29bf1f2be9f8dbe6a928826b3a42ae858bcaab3 | Brandilyar/PythonOzon | /Banch/Banch.py | 574 | 3.921875 | 4 | count = 0
def degree_recursion(degree,result_list=[]):
global count
count = count + 1
number = 5
if degree == 0 or degree == 1:
return 1
else:
result = number * degree_recursion(degree-1,result_list)
result_list.append(result)
'''if degree == count:
return result_list
else:'''
return result
def degree_cycle(degree):
result = []
number = 5
if degree == 0 or degree == 1:
return 1
else:
for i in range(1,degree):
result=number**i
return result
|
69b54fde762b51332aa992ba6e969c5d7038c2a0 | junedsaleh/Python-Programs | /Programs/BinarySearch.py | 326 | 3.59375 | 4 | lst = [6,8,9,23,45,56]
lst.sort()
high = len(lst)-1
low = 0
flag = 0
print(high)
print(low)
n = input("Enter Number")
n = int(n)
while(low <= high):
mid = (low + high)/2
if(mid == n)
flag = 0
elif(lst[mid]>n):
flag = 0
else
flag=0
if(flag==1):
print("Value not Found")
|
9bc94edfebbfadfb5d90bf3e7dc119967dc27943 | krishna-rawat-hp/PythonProgramming | /codes/stringformat.py | 717 | 4.5 | 4 | # String format method in python
# Example-1 format with {}
str1 = "java"
str2 = "python"
str = "{} and {} are good languages".format(str1,str2)
print(str)
# Example-2 format with {index}
strin = "{1} is easy compare to {0}.".format(str1,str2)
print(strin)
# Example-3 format with number system
val = 10
print("Decimal value is {0:d}".format(val))
print("Hexadecimal value is {0:x}".format(val))
print("Octal value is {0:o}".format(val))
print("Binary value is {0:b}".format(val))
# Example-4 format with {:,}
val1 = 100000000
print("Simple value {} VS Comma seprated value {:,}".format(val1,val1))
# Example-5 format percentage
fval = 59/9
print("Original value {} VS formated value {:.2%}".format(fval,fval))
|
b0cf52ca9cd3c12f84813012e8cc0d6dbbed9c4a | iSkylake/Algorithms | /Tree/KthLargeBST.py | 1,975 | 3.828125 | 4 | # Create a function that returns the Kth largest value in a Binary Search Tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
self.size = 0
# def insert(self, val):
# new_node = Node(val)
# if self.size < 1:
# self.root = new_node
# self.size += 1
# else:
# add = False
# node = self.root
# while not add:
# if val < node.val and not node.left:
# node.left = new_node
# self.size += 1
# add = True
# elif val > node.val and not node.right:
# node.right = new_node
# self.size += 1
# add = True
# elif val < node.val:
# node = node.left
# else:
# node = node.right
def insert(self, val):
new_node = Node(val)
if not self.root:
self.root = new_node
else:
self._insert(self.root, new_node)
def _insert(self, node, new_node):
if new_node.val < node.val:
if not node.left:
node.left = new_node
else:
self._insert(node.left, new_node)
else:
if not node.right:
node.right = new_node
else:
self._insert(node.right, new_node)
def kth_large_BST(root, k):
count = 0
val = 0
def traverse(node, k):
nonlocal count, val
if not node:
return
traverse(node.right, k)
count += 1
if count == k:
val = node.val
traverse(node.left, k)
traverse(root, k)
return val
#Using Array
# def kth_large_BST(root, k):
#
# inorder = []
#
# def traverse(node):
# nonlocal inorder
#
# if not node:
# return
# traverse(node.right)
# inorder.append(node.val)
# traverse(node.left)
#
# traverse(root)
# return inorder[k-1]
# a = Node(5)
# b = Node(4)
# c = Node(2)
# d = Node(7)
# e = Node(6)
# f = Node(9)
# a.left = b
# b.left = c
# a.right = d
# d.left = e
# d.right = f
bst = BST()
bst.insert(5)
bst.insert(4)
bst.insert(2)
bst.insert(7)
bst.insert(6)
bst.insert(9)
print(kth_large_BST(bst.root, 3))
print(kth_large_BST(bst.root, 5)) |
cd11542b28904b0865526267ec5db987183b714d | Yu4n/Algorithms | /CLRS/bubblesort.py | 647 | 4.25 | 4 | # In bubble sort algorithm, after each iteration of the loop
# largest element of the array is always placed at right most position.
# Therefore, the loop invariant condition is that at the end of i iteration
# right most i elements are sorted and in place.
def bubbleSort(ls):
for i in range(len(ls) - 1):
for j in range(0, len(ls) - 1 - i):
if ls[j] > ls[j + 1]:
ls[j], ls[j + 1] = ls[j + 1], ls[j]
'''for j in range(len(ls) - 1, i, -1):
if ls[j] < ls[j - 1]:
ls[j], ls[j - 1] = ls[j - 1], ls[j]'''
a = [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
bubbleSort(a)
print(a)
|
020faa764f096d361c801b962c965525db19182c | sol0703/programacion-1 | /examenes/quiz3.py | 4,171 | 3.765625 | 4 | # Trabajamos Miguel Zuleta
# punto 1
# a
print('Punto a')
class ElementosDigitales ():
def __init__ (self, nombre, creador, fechadepublicacion):
self.nombre = nombre
self.creador = creador
self.fechadepublicacion = fechadepublicacion
def mostrarAtributos (self,):
print (f''' Los atributos de la pelicula son:
1- Su creador es {self.nombre}
2- El nombre de la compañia es {self.creador}
3- Su fecha de publicacion fue {self.fechadepublicacion}
''')
ElementosDigitales1 = ElementosDigitales('Julian', 'Marvel', '1 de Diciembre del 2119')
ElementosDigitales1.mostrarAtributos ()
# b
print('Punto b')
class Usuario ():
def __init__ (self, nombre, edad, sexo, nacionalidad):
self.nombre = nombre
self.edad = edad
self.sexo = sexo
self.nacionalidad = nacionalidad
def mostrarAtributos (self, cancion):
print (f' Hola soy {self.nombre}, tengo {self.edad} años, soy {self.sexo} y soy de {self.nacionalidad} y estoy escuchando {cancion}' )
Usuario1 = Usuario('Sara', 20, 'Mujer', 'Colombiana')
Usuario1.mostrarAtributos ('Adios')
# c
print('Punto c')
class Pagina ():
def __init__ (self, tipodecontenido, formato, fechadepublicacion):
self.tipodecontenido = tipodecontenido
self.formato = formato
self.fechadepublicacion = fechadepublicacion
def mostrarAtributos (self):
print (f''' Los atributos de la pagina son:
1- Su contenido es {self.tipodecontenido}
2- El formato {self.formato}
3- Su fecha de publicacion es {self.fechadepublicacion}
''')
Pagina1 = Pagina('Musica', 'web', '2 de enero de 2001')
Pagina1.mostrarAtributos ()
# punto 2
# a
print ('punto 2')
class Cancion (ElementosDigitales):
def _init_(self, nombre, creador, fechadepublicacion, Generomusical, Duracion):
super().__init__(nombre, creador, fechadepublicacion)
self.Generomusical = Generomusical
self.Duracion = Duracion
def mensaje (self, Nombre, Fechadecreacion):
print (f'Cuando se crea una nueva cancion: {Nombre}, tambien se ve su fecha de creacion: {Fechadecreacion}')
def veces (self, cancionnombre):
for lista in range(cancionnombre):
print (f'La cancion {cancionnombre} se a reproducido {lista+1} veces')
Cancion1 = Cancion('Estrellita', 'Maluma', '7 de marzo de 1999')
Cancion1.mensaje('Estrellita', '5 de abril de 1997')
Cancion1.veces (5)
# b
class Artista (Usuario):
def _init_(self, nombre, edad, sexo, nacionalidad, Generomusical, numerocanciones, numerodealbum, ciudad):
super().__init__(nombre, nombre, edad, sexo, nacionalidad)
self.Generomusical = Generomusical
self.numerocanciones = numerocanciones
self.ciudad = ciudad
self.numerodealbum = mumerodealbum
def comunicado (self, numerodealbum, Generomusical, numerocanciones, ciudad):
print (f'''Soy el artista {self.nombre} tengo {self.edad} años, soy genero {self.sexo}, soy de {self.nacionalidad}
voy a lanzar mi album numero {numerodealbum} del gennero musical {Generomusical},
donde cantare {numerocanciones} canciones.
Preparete {ciudad} ALLA VOY !!!
''')
Artista1 = Artista('Paco', 70, 'Hombre', 'Peru')
Artista1.comunicado(1, 'tango', 7, 'DF')
# c
class Favoritos (Pagina):
def __init__ (self, tipodecontenido, formato, fechadepublicacion, favoritoscomunidad, fechaactualizacion):
Pagina.__init__(self, tipodecontenido, formato, fechadepublicacion)
self.favoritoscomunidad = favoritoscomunidad
self.fechaactualizacion = fechaactualizacion
def agregarcancion (self, cancion, actualizacion):
self.favoritoscomunidad.append(cancion)
self.fechaactualizacion = actualizacion
def mostrarlista (self, cancioneliminada):
print (self.favoritoscomunidad)
self.favoritoscomunidad.pop(cancioneliminada)
lista = ["let it go", "Adios", "Yellow"]
Yellow = Favoritos('cancion', 'web', 2002, 'lista', '4 de mayo de 2015')
Yellow.mostrarlista(2)
Yellow.agregarcancion('cancion nueva', 2015)
print (Yellow.favoritoscomunidad)
|
a9b65d20a521f9e16a9e65e2745f663217cab1e7 | gktgaurav/python-coding-basics | /pract.py | 416 | 3.96875 | 4 | # # # print('gfgfgffhgfhgfhg')
# # x=[2,4,6,8,10]
# # x1=[]
# # for i in x:
# # x1.append(i*2)
# # print(x)
# # print(x1)
# odd_list=[1,3,5,7,9]
# unordered_list={11,12,13,14,15,16,17,18,19,20}
# for n in unordered_list:
# if not n%2==0:
# odd_list.append(n)
# print(odd_list)
my_list = [34, 82.6, "Darth Vader", 17, "Hannibal"]
my_tuple=(my_list[0],my_list[len(my_list)-1],len(my_list))
print(my_tuple) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.