blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ee8c78f491453392d36ee7d33a009b241b357338 | gerph/rosettacode | /json_funcs.py | 1,508 | 4.0625 | 4 | """
Functions for manipulating JSON.
json_iterable + json_encode allow the serialisation of objects which contain the
`__jsonencode__` method. If called, this should return a serialisable object (simple
python objects).
write_json will use those functions to write out a JSON file.
"""
import json
def json_encode(obj):
"""
Encoding function to use for objects which are not known to the standard JSON encoder.
If the object contains a property '__jsonencode__', it is called to obtain the representation
of the object.
"""
def jsonspecial_datetime(obj): # pylint: disable=unused-variable
return obj.isoformat()
if hasattr(obj, '__jsonencode__'):
return obj.__jsonencode__()
special_name = 'jsonspecial_%s' % (obj.__class__.__name__,)
special_func = locals().get(special_name, None)
if special_func:
return special_func(obj)
raise TypeError("Cannot serialise a '%s' object: %r" % (obj.__class__.__name__, obj))
def json_iterable(obj, pretty=False):
if pretty:
return json.JSONEncoder(default=json_encode,
sort_keys=True,
indent=2,
separators=(',', ': ')).iterencode(obj)
else:
return json.JSONEncoder(default=json_encode).iterencode(obj)
def write_json(filename, obj, pretty=False):
with open(filename, 'w') as fh:
for chunk in json_iterable(obj, pretty=pretty):
fh.write(chunk)
|
c71d8d2d61cde1d47e79331750ff1043445aeff1 | poohcid/class | /extra/6.py | 350 | 4.125 | 4 | """Print i"""
def main():
"""main"""
style = input()
num1, num2, num3 = int(input()), int(input()), 1
if num2 < num1:
num3, num2 = -1, num2-2
for i in range(num1, num2+1, num3):
if style == "Vertical":
print("%02d" %i)
elif style == "Horizontal":
print("%02d" %i, end=" ")
main()
|
cad22b24332bf86cc8594ee66df07d821bd9f12e | KaiChen1998/My-Leetcode | /python/110. Balanced Binary Tree.py | 873 | 3.921875 | 4 | class Solution:
"""
Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Solutions:
重点在于如果有一棵子树违反了balance都要将这个结果向上传递,不能简单地计算root两棵子树的高度差
"""
def isBalanced(self, root: TreeNode) -> bool:
return self.height(root) >= 0
def height(self, root):
# value set: [-1, 0, 1]
if(root is None):
return 0
left = self.height(root.left)
right = self.height(root.right)
if((left >= 0) and (right >= 0) and (abs(left - right) <= 1)):
return max(left, right) + 1
else:
return -1 |
0e723f95f9ccf84205ca06ec38c76fff6e84769a | gabrielgamer136/aula-git-gabriel | /Documentos/lista de exercicios 1 python gabriel/lista de exercicios 2 phyton/exercicio numero 2.py | 206 | 3.828125 | 4 | #Gabriel maurilio
ano = int(input("digite um ano"))
if ano % 4 != 0:
print ("nao e bissesto")
else:
if ano % 100 == 0 and not (ano % 400 == 0):
print("nao e bissesto")
else:
print("e bissesto")
|
4a1bcd557e493b2cd66758308686046bfb8c9355 | chaussen/chinese-character-teaching | /src/common/character_dict.py | 17,032 | 3.59375 | 4 | LESSON_10 = {
"花": ["huā","flower; blossom"],
"园": ["yuán","land used for growing plants; site used for public recreation"],
"门": ["mén","gate; door; classifier for lessons, subjects, branches of technology"],
"前": ["qián","front; forward; ahead; first; top (followed by a number); former"],
"个": ["gè","universal measure word"],
"他": ["tā","he or him"],
"后": ["hòu","back; behind; rear; afterwards; after; later"],
"外": ["wài","outside; in addition; foreign; external"],
"年": ["nián","year"],
"季": ["jì","season"],
"儿": ["ér","non-syllabic diminutive suffix"],
"看": ["kàn","to see; to look at; to read; to watch; to visit; to call on; to consider; to regard as; to look after; to treat (an illness); to depend on; to feel (that); (after verb) to give it a try; Watch out! (for a danger)"],
"花园": ["huāyuán","garden"],
"大门": ["dàmén","entrance; door; gate"],
"后门": ["hòumén","the back door; fig. under the counter (indirect way for influence or pressure)"],
"好看": ["hǎokàn","good-looking; nice-looking; good (of a movie, book, TV show etc); embarrassed; humiliated"],
"公": ["gōng","public; collectively owned; common; male (animal)"],
"朵": ["duǒ","measure word for flower"],
"可": ["kě","may, can"],
"玫": ["méi","(fine jade)"],
"菊": ["jú","chrysanthemum"],
"兰": ["lán","orchid (Cymbidium goeringii); fragrant thoroughwort (Eupatorium fortunei); lily magnolia"],
"公园": ["gōngyuán","park (for public recreation)"],
"可爱": ["kěài","adorable; cute; lovely"],
"玫瑰": ["méiguī","rugosa rose (shrub) (Rosa rugosa); rose flower"],
"菊花": ["júhuā","chrysanthemum"],
"兰花": ["lánhuā","cymbidium; orchid"],
"目前": ["mùqián","at the present time; currently"],
"个人": ["gèrén","individual; personal; oneself"],
"其他": ["qítā","other; (sth or sb) else; the rest"],
"之后": ["zhīhòu","afterwards; following; later; after"],
"另外": ["lìngwài","additional; in addition; besides; separate; other; moreover; furthermore"],
"外国": ["wàiguó","foreign (country)"],
"季节": ["jìjié","time; season; period"],
"儿子": ["érzi","son"],
"女儿": ["nǚér","daughter"],
"看来": ["kànlái","apparently; it seems that"],
"看见": ["kànjiàn","to see; to catch sight of"],
}
LESSON_9 = {
'的': ['de',"expressing possession"],
'家': ['jiā',"home; family; classifier for families or businesses; noun suffix for a specialist in some activity, such as a musician or revolutionary, corresponding to English -ist, -er, -ary or -ia"],
'这': ['zhè',"this; these"],
'有': ['yǒu',"to have; there is; there are; to exist; to be"],
'和': ['hé',"and; harmonious"],
'爷爷': ['yéye',"(coll.) father's father; paternal grandfather"],
'奶奶': ['nǎinai',"(informal) grandma (paternal grandmother)"],
'爸爸': ['bàba',"(informal) father"],
'妈妈': ['māma',"mama; mommy; mother"],
'放': ['fàng',"to put; to place; to release; to free; to let go; to let out; to set off (fireworks)"],
'回': ['huí',"go back; return"],
'到': ['dào',"to (a place); until (a time); up to; to go; to arrive; (verb complement denoting completion or result of an action)"],
'给': ['gěi',"to supply; to provide"],
'完': ['wán',"to finish; to be over; whole; complete; entire"],
'把': ['bǎ',"sentence structure; handle"],
'放学': ['fàngxué',"to dismiss students at the end of the school day"],
'回家': ['huíjiā',"to return home"],
'大家': ['dàjiā',"everyone"],
'唱歌': ['chànggē',"to sing a song"],
'国家': ['guójiā',"country; nation; state"],
'这样': ['zhèyàng',"this kind of; so; this way; like this; such"],
'只有': ['zhǐyǒu',"only"],
'和平': ['hépíng',"peace; peaceful"],
'开放': ['kāifàng',"to be open (to the public); to be open-minded; unconstrained in one's sexuality"],
'回答': ['huídá',"to reply; to answer; the answer"],
'得到': ['dédào',"to get; to obtain; to receive"],
'完全': ['wánquán',"complete; whole; totally; entirely"],
'完成': ['wánchéng',"to complete; to accomplish"],
}
CHARACTER_PINYIN_ENGLISH_MAPPING_BACK = {
"的": ["de", "Structural particle modifying nouns"],
"学": ["", "to learn; to study; to imitate"],
"生": ["", "to be born; to give birth; life; to grow"],
"是": ["", "to be (only connecting nouns)"],
"爱": ["", "to love; to be fond of; to like; affection; to be inclined (to do sth); to tend to (happen)"],
"老": ["", "prefix used before the surname of a person or a numeral indicating the order of birth of the children in a family or to indicate affection or familiarity; old (of people); venerable (person); experienced; of long standing; always; all the time; of the past; very; outdated"],
"师": ["", "teacher; master; expert"],
"同": ["", "same"],
"文": ["", "language; culture; writing; formal"],
"校": ["", "school"],
"学习": ["", "to learn; to study"],
"这时": ["", "at this time; at this moment"],
"平时": ["", "ordinarily; in normal times"],
"学生": ["xue2 sheng", "student; schoolchild"],
"老师": ["", "teacher"],
"同学": ["", "to study at the same school; fellow student; classmate"],
"中文": ["", "Chinese language"],
"学校": ["", "school"],
"就是": ["", "(emphasizes that sth is precisely or exactly as stated); precisely; exactly"],
"爱情": ["", "romance; love (romantic)"],
"有钱": ["", "rich"],
"老板": ["", "boss"],
"男朋友": ["", "boy friend"],
"公司": ["", "company"],
"钱": ["", "money"],
"菜": ["", "dish"],
"会": ["", "can; be capable of"],
"给": ["", "to give; to supply; to provide"],
"起来": ["", "(after a verb) indicating the beginning and continuation of an action or a state; indicating an upward movement; bringing things together; (after a perception verb, e.g. 看[kan4]) expressing preliminary judgment"],
"说": ["shuō", "to speak; to say; to explain; to scold; to tell off; a theory (usually in compounds such as 日心说 heliocentric theory)"],
"是": ["shì", "to be (only connecting nouns)"],
"色": ["sè", "color"],
"花": ["huā", "flower; blossom; also pr. [wei3]"],
"妈": ["mā", "ma; mom; mother"],
"马": ["mǎ", "horse; horse or cavalry piece in Chinese chess; knight in Western chess"],
"牛": ["niú", "ox; cow; bull; (slang) awesome"],
"羊": ["yáng", "sheep; goat"],
"鱼": ["yú", "fish"],
"虫": ["chóng", "lower form of animal life including insects larvae worms and similar creatures"],
"鸟": ["niǎo", "bird; (dialect) to pay attention to; (intensifier) damned; goddam"],
"草": ["cǎo", "grass"],
"黄": ["huáng", "yellow; pornographic; to fall through"],
"白": ["bái", "white; snowy; pure; bright; empty; blank; plain; clear; to make clear; in vain; gratuitous; free of charge; reactionary; anti-communist; funeral; to stare coldly; to write wrong character; to state; to explain; vernacular; spoken lines in opera"],
"黑": ["hēi", "black; dark; sinister; secret; shady; illegal; to hide (sth) away; to vilify; (loanword) to hack (computing)"],
"绿": ["lǜ", "green"],
"红": ["hóng", "red; popular; revolutionary; bonus"],
"蓝": ["lán", "blue; indigo plant"],
"马上": ["mǎshàng", "at once; right away; immediately; on horseback (i.e. by military force)"],
"牛奶": ["niúnǎi", "cow's milk"],
"奶牛": ["nǎiniú", "milk cow; dairy cow"],
"山羊": ["shānyáng", "goat; (gymnastics) small-sized vaulting horse"],
"绵羊": ["miányáng", "sheep"],
"钓鱼": ["diàoyú", "to fish (with line and hook); to dupe"],
"昆虫": ["kūnchóng", "insect"],
"小鸟": ["xiǎoniǎo", "penis (kiddie term)"],
"明白": ["míngbái", "clear; obvious; unequivocal; to understand; to realize"],
"绿色": ["lǜsè", "green"],
"黄河": ["huánghé", "Yellow River or Huang He"],
"白天": ["báitiān", "daytime; during the day; day; CL:個|个[ge4]"],
"红色": ["hóngsè", "red (color); revolutionary"],
"草原": ["cǎoyuán", "grassland; prairie; CL:片[pian4]"],
"绿化": ["lǜhuà", "to make green with plants; to reforest"],
"黑暗": ["hēiàn", "dark; darkly; darkness"],
"蓝色": ["lánsè", "blue (color)"],
"草案": ["cǎoàn", "draft (legislation proposal etc)"],
"女朋友": ["nv3 peng2 you", "girl friend"],
"里": ["", "in; inside"],
"游": ["", "to swim; to travel"],
"的": ["de", "Structural particle modifying nouns"],
"说": ["shuō", "to speak; to say; to explain; to scold; to tell off; a theory (usually in compounds such as 日心说 heliocentric theory)"],
"是": ["shì", "to be (only connecting nouns)"],
"色": ["sè", "color"],
"花": ["huā", "flower; blossom; also pr. [wei3]"],
"妈": ["mā", "ma; mom; mother"],
"马": ["mǎ", "horse; horse or cavalry piece in Chinese chess; knight in Western chess"],
"牛": ["niú", "ox; cow; bull; (slang) awesome"],
"羊": ["yáng", "sheep; goat"],
"鱼": ["yú", "fish"],
"虫": ["chóng", "lower form of animal life including insects larvae worms and similar creatures"],
"鸟": ["niǎo", "bird; (dialect) to pay attention to; (intensifier) damned; goddam"],
"草": ["cǎo", "grass"],
"黄": ["huáng", "yellow; pornographic; to fall through"],
"白": ["bái", "white; snowy; pure; bright; empty; blank; plain; clear; to make clear; in vain; gratuitous; free of charge; reactionary; anti-communist; funeral; to stare coldly; to write wrong character; to state; to explain; vernacular; spoken lines in opera"],
"黑": ["hēi", "black; dark; sinister; secret; shady; illegal; to hide (sth) away; to vilify; (loanword) to hack (computing)"],
"绿": ["lǜ", "green"],
"红": ["hóng", "red; popular; revolutionary; bonus"],
"蓝": ["lán", "blue; indigo plant"],
"马上": ["mǎshàng", "at once; right away; immediately; on horseback (i.e. by military force)"],
"牛奶": ["niúnǎi", "cow's milk"],
"奶牛": ["nǎiniú", "milk cow; dairy cow"],
"山羊": ["shānyáng", "goat; (gymnastics) small-sized vaulting horse"],
"绵羊": ["miányáng", "sheep"],
"钓鱼": ["diàoyú", "to fish (with line and hook); to dupe"],
"昆虫": ["kūnchóng", "insect"],
"小鸟": ["xiǎoniǎo", "penis (kiddie term)"],
"明白": ["míngbái", "clear; obvious; unequivocal; to understand; to realize"],
"绿色": ["lǜsè", "green"],
"黄河": ["huánghé", "Yellow River or Huang He"],
"白天": ["báitiān", "daytime; during the day; day; CL:個|个[ge4]"],
"红色": ["hóngsè", "red (color); revolutionary"],
"草原": ["cǎoyuán", "grassland; prairie; CL:片[pian4]"],
"绿化": ["lǜhuà", "to make green with plants; to reforest"],
"黑暗": ["hēiàn", "dark; darkly; darkness"],
"蓝色": ["lánsè", "blue (color)"],
"草案": ["cǎoàn", "draft (legislation proposal etc)"],
"女朋友": ["nv3 peng2 you", "girl friend"],
"风": ["", "wind"],
"云": ["", "cloud"],
"雨": ["", "to rain; to fall"],
"雪": ["", "snow; snowfall"],
"电": ["", "electric; electricity; electrical"],
"天": ["", "day; sky; heaven"],
"地": ["di4", "earth; ground; field; place; land"],
"春": ["", "spring (time)"],
"夏": ["", "summer"],
"秋": ["", "autumn"],
"冬": ["", "winter"],
"干净": ["", "clean; neat"],
"家庭": ["", "family; household"],
"圆珠笔": ["", "ballpoint pen"],
"种类": ["", "kind; type"],
"花样": ["", "variety; way of doing thing; trick"],
"刮风": ["", "blow wind"],
"风格": ["", "style"],
"云南": ["", "Yunnan Province"],
"一场雨": ["yi1 chang2 yu3", "one rain"],
"冰雪": ["", "ice and snow"],
"电冰箱": ["", "refrigerator"],
"电话": ["", "telephone"],
"电饭锅": ["", "electric cooker"],
"电风扇": ["", "electric fan"],
"一天": ["", "one day"],
"今天": ["", "today"],
"天气": ["", "weather"],
"晴天": ["", "sunny day"],
"地区": ["", "district; area; region; suburb"],
"春天": ["", "spring season"],
"春节": ["", "Spring Festival"],
"夏天": ["", "summer season"],
"秋天": ["", "autumn season"],
"冬天": ["", "winter season"],
"我饿了": ["wo3 e4 le", "hungry"],
"妈妈老了": ["ma1 ma lao3 le", "mum is old"],
"下雨了": ["xia4 yu3 le", "it rains"],
"你有女朋友了吗": ["", "do you have girl friend?"],
"我不买了": ["wo3 bu4 mai3 le", "i will not buy it"],
"我不回家吃饭了": ["wo3 bu4 hui2 jia1 chi1 fan4 le", "i am not coming home for dinner"],
"每天都": ["mei3 tian1 dou1", "(do something all the time) every day"],
"漂": ["piao4", ""],
"行": ["hang2", ""],
"呆": ["dai1", ""],
"难": ["nan2", ""],
"空": ["kong4", ""],
"数": ["shu4", ""],
"得": ["dei3", ""],
"行": ["xing2", ""],
"脏": ["zang1", ""],
"着": ["zhao2", ""],
"缝": ["feng2", ""],
"贴": ["tie1", ""],
"重": ["chong2", ""],
"曾": ["ceng2", ""],
"称": ["cheng1", ""],
"切": ["qie1", ""],
"为": ["wei2", ""],
"场": ["chang3", ""],
"分": ["fen1", ""],
"啊": ["a", ""],
"著": ["zhu4", ""],
"折": ["zhe2", ""],
"当": ["dang1", ""],
"调": ["tiao2", ""],
"数": ["shu3", ""],
"空": ["kong1", ""],
"号": ["hao4", ""],
"切": ["qie4", ""],
"向": ["", "direction; orientation; to face; to turn toward; to; towards; "],
"用": ["", "to use; to employ; to have to; to eat or drink; "],
"关系": ["guan1 xi", "relationship"],
"舒服": ["shu1 fu", "comfortable; feeling well"],
"痛苦": ["", "pain; suffering; painful; CL:個|个[ge4]"],
"会": ["hui4", "be capable of"],
"给": ["", "to supply; to provide"],
"起来": ["", "(after a verb) indicating the beginning and continuation of an action or a state; indicating an upward movement (e.g. after 站[zhan4]); bringing things together (e.g. after 收拾[shou1 shi5]); (after a perception verb, e.g. 看[kan4]) expressing preliminary judgment; also pr. [qi3 lai5]"],
"家": ["", "home; family; (polite) my (sister, uncle etc); classifier for families or businesses; refers to the philosophical schools of pre-Han China; noun suffix for a specialist in some activity, such as a musician or revolutionary, corresponding to English -ist, -er, -ary or -ian; CL:個|个[ge4]"],
"她": ["", "she"],
"你": ["", "you (informal, as opposed to courteous 您[nin2])"],
"就": ["", "at once; right away; only; just (emphasis); as early as; already; as soon as; then; in that case; as many as; even if; to approach; to move towards; to undertake; to engage in; to suffer; subjected to; to accomplish; to take advantage of; to go with (of foods); with regard to; concerning"],
"像": ["", "to resemble; to be like; to look as if; such as; appearance; image; portrait; image under a mapping (math.)"],
"好": ["hao3", "good"],
"开": ["", "to open; to start; to turn on; to boil; to write out (a prescription, check, invoice etc); to operate (a vehicle)"],
"了": ["le", "final particle"],
"真": ["", "really; truly; indeed; real; true; genuine"],
"高": ["", "high; tall; above average; loud; your (honorific)"],
"兴": ["xing4", "feeling or desire to do sth; interest in sth; excitement"],
"车": ["", "vehicle;car"],
"见": ["jian4", "to see"],
"说": ["", "to speak; to say; to explain; to scold; to tell off; a theory (usually in compounds such as 日心说 heliocentric theory)"],
"早": ["", "early; morning; Good morning!; long ago; prematurely"],
"们": ["", "plural marker for pronouns, and nouns referring to individuals"],
"开学": ["", "foundation of a University or College; school opening; the start of a new term"],
"高兴": ["gao1 xing4", "happy; glad; willing (to do sth); in a cheerful mood"],
"校车": ["", "school bus"],
"你们": ["", "you (plural)"],
"开始": ["", "to begin; beginning; to start; initial; CL:個|个[ge4]"],
"离开": ["", "to depart; to leave"],
"真正": ["", "genuine; real; true; genuinely"],
"认真": ["", "conscientious; earnest; serious; to take seriously; to take to heart"],
"提高": ["", "to raise; to increase; to improve"],
"兴趣": ["xing4 qu4", "interest (desire to know about sth); interest (thing in which one is interested); hobby; CL:個|个[ge4]"],
"汽车": ["", "car; automobile; bus; CL:輛|辆[liang4]"],
"意见": ["", "idea; opinion; suggestion; objection; complaint; CL:點|点[dian3],條|条[tiao2]"],
"看见": ["", "to see; to catch sight of"],
"说明": ["", "to explain; to illustrate; to indicate; to show; to prove; explanation; directions; caption; CL:個|个[ge4]"],
"小说": ["", "novel; fiction; CL:本[ben3],部[bu4]"],
"人们": ["", "people"],
"良好": ["", "good; favorable; well; fine"],
}
|
080f4751a536bf14d07e696ce631cde270cde96e | ny215/LeetcodeExercise | /LinkedList/23. Merge k Sorted Lists.py | 1,854 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
dummy = res = ListNode(0)
tmp = PriorityQueue()
for l in lists:
if l:
tmp.put((l.val,l))
while not tmp.empty():
val, node = tmp.get()
res.next = ListNode(val)
res = res.next
node = node.next
if node:
tmp.put((node.val, node))
return dummy.next
# time: O(NlogK)
# space: O(N)
#divide and conquer
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
amount = len(lists)
interval = 1
while interval < amount:
for i in range(0, amount - interval, interval * 2):
lists[i] = self.merge(lists[i], lists[i + interval])
interval *= 2
return lists[0]
def merge(self, l1, l2):
head = dummy = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
if l1:
head.next = l1
elif l2:
head.next = l2
return dummy.next
# time: O(NlogK)
# space: O(1) |
0c28f1cfc41c26680dc42427ce3153de76e94c2c | shyam-SDET/coursera-python | /assignment4.6.py | 302 | 3.8125 | 4 | def computepay(h,r):
if(h>40):
result=h*r;
res=((h-40.0)*(r*0.5));
x=result+res;
else:
result=h*r;
x=result;
return x;
hrs = input("Enter Hours:")
h = float(hrs)
rate=input("Enter Rate:")
r=float(rate)
a=computepay(h,r);
print("Pay",a);
|
27c0313bc762c194b2e2b79229cb20b8577f50ca | ykumards/Algorithms | /dp/RecursiveMult.py | 1,199 | 4.28125 | 4 | """
Multiply two number recursively, without using *.
Runtime is O(k) where k is the minimum of the two operands
"""
def _naive_recMult(addr, multer):
if multer == 0:
return 0
addr += _naive_recMult(addr, multer-1)
return addr
def recMult(a, b):
small = min(a,b)
big = max(a,b)
return _recMult(big, small)
# While naive method was O(k), we can reduce this to O(log k)
# 20 * 4 = 20 * 2 + 20 * 2 = 20 * 1 + 20 * 1 + 20 * 1 + 20 * 1
# This is basically the same as last method, but we double each
# result instead of adding subsequent values.
# This gets us the O(log k) runtime. But we still have to handle
# the case when k is odd. For this, simply use:
# 20 * 5 = 20 * 2 + 20 * 2 + 20
def _recMult(big, small):
if small == 0:
return 0
if small == 1: # for 1 * big
return big
half = small >> 1 # Binary shifting basically does integer division by 2
half_prod = _recMult(half, big)
if small % 2 == 0:
return half_prod << 1
else:
return (half_prod << 1) + big
if __name__ == "__main__":
print "10 x 2:", recMult(10,2)
print "3 x 1000:", recMult(3,1000)
print "1212 x 9891:", recMult(1212, 9891)
|
4e8940564ad86b3c49dacf451bf00549abdf6137 | mrstevenaweiss/algorithms | /Cryptography/mental_poker.py | 1,679 | 3.953125 | 4 | ## Mental Poker
import random, math
bitwise_cards = {}
# Create a bitwise hash
suits = ["Clubs", "Hearts", "Spades", "Diamonds"]
cards = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", None]
card = 1
for i in range(1, 53):
if i <= 13:
suit = suits[0]
elif i > 13 and i <= 26:
suit = suits[1]
elif i > 26 and i <= 39:
suit = suits[2]
elif i > 39:
suit = suits[3]
if card == 14:
card = 1
# print(suit, cards[card], 'bitwise=', i)
bitwise_cards[i] = cards[card] + suit
card += 1
# print(bitwise_cards)
# Dealing cards with Keys
# Key == "MY" key (a huge digit)
bitwise_random = random.randint(1, 52)
print(bitwise_random, bitwise_cards[bitwise_random])
# Stage 1: bitwise_random^K % P
# P is some large number or a prime number
print( math.pow(bitwise_random, 2) % P )
# Stage 2: ( bitwise_random^K )^J % P == ( bitwise_random^J )^K % P
# Stage 3: (( bitwise_random^J )^K)^-1K % P == ( bitwise_random^J ) % P
# Stage 4: ( bitwise_random^J )^-1J % P == bitwise_random % P
# Repeated Squaring // Raising large problems efficiently
# Q^11 = Q^1 * (Q^5)^2
# it is not the inverse in Q, but the inverse modulo p-1.That is, take a number i such that ki = 1 modulo p-1
# The Fermat little theorem say that a^(p-1) = 1 modulo p
# Then (q^k)^i = q^(ki) = q modulo p
# For example if p=23 and k=7, then p-1=22, moreover 19*7 = 6*22+1 = 1 modulo 22.
# So for any integer x we have (x^7)^19 = x modulo 23
# For example 15^7 = 170859375 = 11 modulo 23
# and 11^19 = 61159090448414546291 = 15 modulo 23
# (of course you should reduce the power modulo p directly) |
523975807386a5c92671974287c76f8d3bb5d8f0 | jakabk/interviews | /mutable_default_arguments_gotcha.py | 429 | 3.953125 | 4 | # https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
# What’s the output of this code:
def f(x, l = []):
for i in range(x):
l.append(i * i)
# print(l)
return l
if __name__ == "__main__":
# >>> f(2)
# ...
assert f(2) == [0, 1]
# >>> f(3,[3,2,1])
# ...
assert f(3, [3, 2, 1]) == [3, 2, 1, 0, 1, 4]
# >>> f(3)
# ...
assert f(3) == [0, 1, 0, 1, 4]
|
e62c3d7d194624b2a42955cbb896d4e306bbd32b | kevinlogan94/CS_Projects | /CS115/theprogram4.py | 6,213 | 3.703125 | 4 | #Prolog Program 4
# Kevin Logan
# Section 10
# [email protected]
# November 15, 2012
#Preconditions: user inputs: userid, database filename, search phrase,
# case sensitivity setting, web page filename
#purpose:
# search in database file for search phrase, based on case sensitivity
# setting, and create web page of results (hits or no hits)
# also keep history of searches in secret.txt
#postcondition: number of hits on the shell,
# web page file created with results of search,
# user name and search phrase appended to secret.txt
#-----------------------------------------------------
# main function
def main():
# introductory message
print("Big Blue Search Engine")
# input user name, search string, database file name, html file name
# and case sensitivity
name=input("Your user name? ")
database1=input("Enter name of database file (.txt will be added): ")
database=database1 + ".txt"
thekeyword=input("Keyword string to search for: ")
webpage1=input("Enter name for web page of results (extension of .htm will be added): ")
webpage=webpage1 + ".htm"
case=input("Do you want to be case sensitive? (y or n) ")
# try to open database file
# if cannot open it,
# print message and abort program
try:
infile= open(database, "r")
except IOError:
print("Can't open file")
return
# read in the lines from the database file into a
# list of strings to search through
# remember this means first element of list is keyword string,
# second element is the URL that goes with the keywords
# third element more keywords, fourth element is another URL, etc.
# close input database file
lst=infile.readlines()
infile.close()
# open output html file
# prepare it by writing out header
# output heading on page with search string in it
# if not case sensitive, force search string to lower case, header says Search for "thekeyword"
outfile=open(webpage, "w")
print("<html>", file=outfile)
print("<title>Search Findings</title>", file=outfile)
print("<body>", file=outfile)
if case=="n":
print("<h2><p align=center>Search for ", '"'+ thekeyword+'"', "</h2>", file=outfile)
thekeyword=thekeyword.lower()
# if it is case sensitive than the header says "Case Sensitive Search for "thekeyword"
else:
print("<h2><p align=center>Case Sensitive Search for ", '"'+thekeyword+'"', "</h2>", file=outfile)
# initialize hit to zero
hit=0
# print that the webpage was created
print(webpage, "created")
# for all lines in the list from the database file (hit starts at 0)
for line in range(0, len(lst)-1, 2):
# keyword line (call it dbline) is in list at position of line
dbline=lst[line]
# URL is at position line + 1
URL=lst[line+1]
# if not case sensitive, force the string to lower case
if case=="n":
dbline=dbline.lower()
# if search string is found in dbline
if dbline.find(thekeyword) >=0:
# increment hits counter
hit+=1
# call function that outputs the hit as line in HTML file
makehtml(hit, dbline, URL, thekeyword, outfile)
# output # of hits to shell
print(hit, "hits")
# if hits is zero
if hit==0:
# report failure of search
print("failure of search")
# = write "not found" with search phrase to output html file. It displays it in a table in the middle of the screen.
print("<p align=center>", file=outfile)
print("<table border>", file=outfile)
print("<tr><td>", thekeyword, "<td> not found! </tr>", file=outfile)
# output bottom of html page (/table, /body, /html)
# close output file
print("</table>", file=outfile)
print("</body>", file=outfile)
print("</html>", file=outfile)
outfile.close()
# manage the secret file
thesecret(thekeyword, name)
#-----------------------------------------------------------------
#name makehtml
#purpose to output to the html file, the line where the search phrase
# was found, while bolding every occurrence of that search phrase.
# It is sure that the phrase is in the line, this function would not be
# called unless that was true
#preconditions
# number of hits (the first time a hit is found, the header line of the
# hit table must be output)
# the line from the database
# the URL that goes with the line
# the search phrase
# the outputfile object
#postconditions
# no values returned
# output html file is altered by the addition of table lines
#design
def makehtml(hit, dbline, URL, thekeyword, outfile):
# strip the dbline
dbline=dbline.strip()
# if first hit,
if hit==1:
# make the next thing you put in the html centered
print("<p align=center>", file=outfile)
# make a table
print("<table border>", file=outfile)
# output the header line of hit table to output file
print("<tr><th>Hit<th>URL</tr>", file=outfile)
#
# output the start of the hit table line, <tr><td>
print("<tr><td>", file=outfile)
#
# output and replace the the search phrase with <b> and </b> on each side of it.
print(dbline.replace(thekeyword, "<b>"+thekeyword+"</b>"), file=outfile)
# output to output file the URL for the link in the second column of the
# hit table
print("<td> <a href=", URL, ">", URL, " </a></tr>", sep="", file=outfile)
#------------------------------------------------------------------
#name: thesecret
#preconditions
# user name, thekeyword
#
#purpose
# append to secret file the info username and search phrase
#
#postconditions
# no return value
# secret file is altered by writing username and search phrase to it
#
#design
def thesecret(thekeyword, name):
# open secret file for append
infile=open("secret.txt", "a")
# write the person that searched for it
infile.write(name+"\n")
# write the search phrase used
infile.write(thekeyword+"\n")
# close secret file
infile.close()
main()
|
43a7ef166b6d937846e9cb1052f52a8ccb60eebf | shyamdalsaniya/Python | /test.py | 535 | 4.28125 | 4 | def main():
print("hello world form python")
a=60+60
print(a)
#this is way to write a comment
a,b=10,15
print(a,b)
a,b=b,a
print(a,b)
print("%d %d %s"%(a,b,5*"hello"))
#this tuple.it is static array. it can not change after it is created
arr1=(1,2,3,5)
print(arr1,type(arr1))
#this is list.it is dynamic array.it can change after it is created
arr2=[1,2,3,4,5,6]
print(arr2,type(arr2))
arr2.append(7)
print(arr2)
arr2.insert(0,90)
print(arr2)
main()
|
256d5eb43550fde2f2daf2842b12844707cfd0a8 | YektaAkhalili/May-12-2020 | /tuples.py | 247 | 3.828125 | 4 | guests = ("William", "Charlotte")
# print("First person: ", guests[0])
print("original guests: ")
for people in guests:
print(people)
guests = ("HostWilliam", "Holores")
print("replaced guests: ")
for people in guests:
print(people) |
54903180a8a504ffe93ba8f99e6881a02e428f61 | CSant04y/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 920 | 4.09375 | 4 | #!/usr/bin/python3
"""Unittest for max_integer function
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""testing for max integer in list func"""
def test_for_max_int(self):
"""tests successful cases of max_integer"""
self.assertEqual(max_integer([1, 2, 3, 4, 5]), 5)
self.assertEqual(max_integer([]), None)
self.assertEqual(max_integer([1]), 1)
self.assertEqual(max_integer([1, 1, 3, 3, 3, 6, 8, 8]), 8)
self.assertEqual(max_integer([-10, -20, -30]), -10)
self.assertEqual(max_integer([1, 2, 3, 4, 3, 2, 1]), 4)
def test_errors(self):
"""tests errors raised by incorrect type arguments"""
self.assertRaises(Exception, max_integer, ["string", 3])
def test_empty(self):
"""tests errors if argument is none"""
self.assertIsNone(max_integer())
|
0827bb450b1c62049dc09b29c4599a0deb3ce8e0 | brandon-kyle-bailey/project-environment-manager | /manager/tests/test_CreateProject.py | 8,724 | 3.609375 | 4 | #!/usr/bin/env python3
""" A script to create java project environments in the
path the script is run in, or a path specified by the user.
User can specify package names to create and can specify if template
'Main' files should be created for each package.
E.g: environment structure :
# -root_path
# -build
# -test
# -classes
# -reports
# -doc
# -lib
# -src
# -main
# -groovy
# -java
# -<package>
# -<package>.java
# -test
# -groovy
# -java
# -<package> <- for testing
# -<package>.java <- for testing
Packages will be created from first dir under project dir. E.g:
src.test.java.<package>.<packageCLASS>
"""
import os
import sys
import json
import argparse
__author__ = "Brandon Bailey"
__copyright__ = "Copyright 2019, Brandon Bailey"
__credits__ = ["Brandon Bailey"]
__license__ = "GPL"
__version__ = "1.0.5"
__maintainer__ = "Brandon Bailey"
__email__ = ""
__status__ = "Production"
class PythonJavaProjectCreator(object):
"""class wrapper for java environment creator for library moduling"""
def __init__(self):
"""initialize class"""
pass
def is_windows(self):
"""Function call to check if operating system is windows.
:return: Boolean : true if win32"""
if sys.platform == "win32":
return True
else:
False
def get_arguments(self):
"""function to return position arguments of
project/ package creation
:retrun: arguments: positional arguments"""
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--new",
type=str,
help="new project")
parser.add_argument("-p", "--packages",
nargs="+",
type=str,
help="if creating new package in project, \
package name")
parser.add_argument("-f", "--files",
action='store_true',
help="create files")
args = parser.parse_args()
return args
def validate_root_location(self):
"""sanity check function to confirm that current working directory
is desired directory for project creation. If not,
allow user to specify path and store it.
:return: working_directory: path to project"""
desired_path = os.getcwd()
is_correct_path = input(f"Java project will be created in : \
{desired_path} is this correct? [y/n/q] ")
if is_correct_path.lower() == "y":
print(f"Creating project in path : {desired_path}")
if is_correct_path.lower() == "n":
desired_path = input("Please specify the desired path : ")
if is_correct_path.lower() == "q":
sys.exit(1)
if not os.path.exists(desired_path):
print("Warning: Specified path does not exist. Will attempt to create.")
try:
os.mkdir(desired_path)
except Exception as error:
print(f"Warning : Error creating directory : {error}")
return desired_path
def json_template_check(self, root_path):
"""function to determine and retrieve json file data
for directory template.
:param: root_path : path to root location either specified by user
or based on CWD
:return: json_data_template"""
files_in_dir = os.listdir(root_path)
print(files_in_dir)
if not files_in_dir:
print("Warning: No files found, Using default.")
return None
try:
json_file = [os.path.join(root_path, f) for f in files_in_dir \
if "template_paths" in f and f.endswith(".json")][0]
except Exception as error:
print(f"Warning : No json templates found in destionation : {error}")
return None
print("Found json template. retrieving data.")
with open(json_file, "r") as handle:
raw_data = json.load(handle)
return raw_data
def create_directory_streams(self, project_root, template):
"""goes through and creates directory tree based on template.
:param: project_root : root path location for project
:param: template : specific template for dirs to follow"""
java_paths = set()
for directory in template:
model = os.path.join(project_root, directory)
if os.path.basename(model) == "java":
java_paths.add(model)
if not os.path.exists(model):
try:
os.makedirs(model)
except Exception as error:
print(f"Warning: error creating project directory : {error}")
else:
print(f"Path exists : {model}")
return java_paths
def create_package_template_file(self, project_root, model, package):
"""function to create template java file to behave as package main.
:param: project_root : root of project path
:param: model : current java model (src/main/; src/test etc.)
:param: package : current package working on"""
# get project name from root
project = os.path.basename(project_root)
# replace slashes with periods for package parsing
if self.is_windows():
package_header = '.'.join(model.split(project, 1)[1].split("\\")[1:])
else:
package_header = '.'.join(model.split(project, 1)[1].split("/")[1:])
# java file template text structure
file_text = f"""
package {package_header};
public class {package} {{
public static void main(String[] args) {{
System.out.println("Package :\\n\\t{package}\\nFrom :\\n\\t{package_header}\\nCreated successfully.");
}}
}}
"""
# full file path
template_file = os.path.join(model, f"{package}.java")
# create/open file and write template to it
with open(template_file, "w+") as file_handle:
file_handle.write(file_text)
def create_packages(self, project_root, package_roots, packages, make_files=False):
"""function to create package directories if packages specified
:param: package_roots : set of java folder paths"""
for path in package_roots:
for package_name in packages:
model = os.path.join(path, package_name)
if not os.path.exists(model):
try:
os.mkdir(model)
except Exception as error:
print(f"Warning: error creating package folders : {error}")
if make_files:
self.create_package_template_file(project_root, model, package_name)
def create_environment(self):
"""main class loop for environment creation"""
args = self.get_arguments()
root_path = self.validate_root_location()
json_template = self.json_template_check(root_path)
if json_template or json_template != None:
template = [json_template[key] for key in json_template][0]
else:
template = ["build/test/classes",
"build/test/reports",
"doc",
"lib",
"src/main/groovy",
"src/main/java",
"src/test/groovy",
"src/test/java"]
if self.is_windows():
template = [template_path.replace("/","\\") for template_path in template]
print(f"WINDOWS TEMPLATE : {template}")
if args.new:
print(f"new project : {args.new}")
project_root = os.path.join(root_path, args.new)
if not os.path.exists(project_root):
os.mkdir(project_root)
else:
project_root = os.getcwd()
package_roots = self.create_directory_streams(project_root, template)
if args.packages:
print(f"package names : {[i for i in args.packages]}")
if args.files:
print("Will create package files")
self.create_packages(project_root, package_roots, args.packages,
make_files = args.files)
else:
self.create_packages(project_root, package_roots, args.packages)
if __name__ == '__main__':
PythonJavaProjectCreator().create_environment()
|
999392cd4af0f0e9ed912aa6ccef50698ba8482a | sjain93/python_fundamentals2 | /exercise4.py | 266 | 3.78125 | 4 | def charcheck(arg):
if isinstance(arg, str):
if len(arg) <= 8:
print('False')
else:
print('True')
else:
print('Not a string, enter a string')
charcheck(2)
charcheck('james')
charcheck('Perhaps a longer one')
|
8e93ab92fe2949ee05b3886fc865c4d743a689ec | fargofremling/practiceprograms | /primes_summation.py | 785 | 3.53125 | 4 | # Problem #10
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#
# Find the sum of all the primes below two million.
import timeit
import math
start = timeit.default_timer()
n = int(raw_input("What prime number would you like to find?\n> "))
primes = [2,3]
for p in range(5, n+1, 2):
if any(p % i == 0 for i in primes):
# p % 3 == 0 or p % 5 == 0 or p % 7 == 0 or p % 11 == 0 or p % 13 == 0:
continue
else:
for x in range(2, int(math.sqrt(p))):
if p % x == 0:
break
else:
print p
primes.append(p)
print primes
def add(x, y):
return x + y
sum = reduce(add, primes)
print sum
stop = timeit.default_timer()
print stop - start
# answer: 142913828922 |
d5ada4eec915ee6e86545062c21b7d1e275c1929 | zaidjubapu/ZaidAlexa | /zaidAlexa.py | 3,251 | 3.546875 | 4 | import pyttsx3
import datetime
import speech_recognition as sr
import pyaudio
import wikipedia
import webbrowser
import os
import smtplib
engine=pyttsx3.init('sapi5') # engine is nothing but just an object
voices=engine.getProperty("voices") # it return no of voices availble in sapi5 or in engine
# print(voices) # printing no of voices availble in engine
engine.setProperty("voice",voices[0].id) # if there is a multiple voices in sapi5 then we used to set only one voice
print("hello this is zaid welcome you to all in my screen thanks")
def speak(audio):
'''to speak the given input'''
engine.say(audio) # .say function is used to speak engine.just taking input as an audio
engine.runAndWait()
def wishme():
''' to wishing every body based on time'''
hour=int(datetime.datetime.now().hour)
if hour >= 0 and hour<12:
speak("good morning")
elif hour >12 and hour <18:
speak("good afternoon")
else:
speak("good evening")
speak("iam zaid sir. please tell me how may i help you")
def takecommand():
'''it take microphone input from the user and return a string output'''
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold =1
audio_dat=r.listen(source)
try:
print("Recoginizing...")
query = r.recognize_google(audio_dat,language="en-in")
print(f"user said: {query}")
# speak(query)
except:
print("sorry i didnt recoginze your voice\n please tell one more time")
return "None"
return query
def sendemail(to,content):
server=smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login('[email protected]',"z@!d7744")
server.sendmail('[email protected]',to,content)
server.close()
if __name__ == "__main__":
# speak("hello iam zaid")
wishme()
query=takecommand().lower()
speak(query)
# logic on excuting task based on the query
while True:
if "wikipedia" in query:
speak("searching wikipedia..")
query=query.replace('wikipedia',"")
results=wikipedia.summary(query,sentences=1)
speak("according to wikipedia")
print(results)
speak(results)
elif "open youtube" in query:
webbrowser.open("youtube.com")
elif "open google" in query:
webbrowser.open("google.com")
elif "the time" in query:
strtime=datetime.datetime.now().strftime("%H:%M:%S")
print(strtime)
speak(f"sir the time is {strtime}")
elif "open code" in query:
codepath="C:\\Users\\DELL\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(codepath)
elif "send email" in query:
try:
speak("what should i send")
print("please say what should i want to send...")
content=takecommand()
to='[email protected]'
sendemail(to,content)
speak("email has been sent")
except Exception as E:
print(E)
speak("sorry my friend email has not send")
break
speak("thankyou")
|
c9f857bb2db6fc6d59a981a15af972099e90f2c3 | JohnTuUESTC/leetcode_program | /MergeSortedArray.py | 962 | 3.90625 | 4 | #coding:gb2312
'''
leetcode: Merge Sorted Array
'''
import copy
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
temp_nums = copy.deepcopy(nums1)
index_1 = 0 #¼temp_numsλ
index_2 = 0 #¼nums2λ
index_3 = 0 #¼nums1λ
while index_1 < m and index_2 < n:
if temp_nums[index_1] < nums2[index_2]:
nums1[index_3] = temp_nums[index_1]
index_1 += 1
else:
nums1[index_3] = nums2[index_2]
index_2 += 1
index_3 += 1
if index_1 < m:
nums1[index_3:m + n] = temp_nums[index_1:m]
if index_2 < n:
nums1[index_3:m + n] = nums2[index_2:n]
|
e56819d48c63128e36dce30ee43fb22c92a749c5 | outofboundscommunications/courserapython | /play/negatives.py | 756 | 3.90625 | 4 |
'''
read through the list of negatives and campaigns and store in dictionary
'''
import string
fhand = "negativesList.csv"
f2hand = "Report.csv"
negatives = dict()
acctnegatives = dict()
for line in fhand:
line = line.rstrip()
#split the line, at each comma, into a list
words = line.split(',')
#if line empty, skip
if len(words)==0:
continue
#if header, skip
if words[0] =='Campaign':
continue
#parse out the negative keyword text (its the third element in the list)
negtext = words[2]
print negtext, matchtype
matchtype = words[3]
if negtext not in negatives:
negatives[negtext] = matchtype
#print counts
'''
for key in negatives:
print key, negatives[key]
''' |
7072566f63a906f69d6ed436456bd5841633080c | edu-athensoft/stem1401python_student | /py210110d_python3a/day06_210214/homework/stem1403a_hw_5_tengyuhao.py | 2,077 | 4.28125 | 4 | """
[Homework]
Date: 2021-02-07
1. Try out label widget
Description:
create a window based on previous homework
set icon, title, dimension, maxsize, minsize, bg and any other options for the window as much as you know
create at least 2 text Labels
set dimension, font, fg, bg, font and any other options you know.
create at least 2 bitmap Labels
set dimension, fg, bg, font and any other options you know.
Due date: by the end of next Friday
"""
"""
score:
perfect
"""
from tkinter import *
# import time
root = Tk()
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# setting
# set a title
root.title('Python GUI - Kevin Teng\'s homework')
# set an image icon
try:
root.iconbitmap('mylogo.ico')
except FileNotFoundError as fnfe:
print(fnfe)
except Exception as e:
print(e)
# ====== Extra requirements =====
# specify dimension at 16:9
ww = 1600
wh = 900
# init posx, posy
x = ws / 2 - ww / 2
y = hs / 2 - wh / 2
x = int(x)
y = int(y)
# Make it at center point on your screen
root.geometry(f'{ww}x{wh}+{x}+{y}')
# Set a background color
root.configure(background="gray64")
# make it topmost
root.attributes('-topmost', True)
# Set max size and min size
root.maxsize(1600, 900)
root.minsize(300, 300)
# Make it resizable
root.resizable(True, True)
# text Label
# Label1
label1 = Label(root, text='Tkinter Label 1 ', font=('SF Pro Text', 22, 'bold'),
height=10, width=20,
anchor='nw',
fg="white", bg="black")
# show on screen
label1.pack()
# Label2
label2 = Label(root, text='Tkinter Label 2', font=('SF Pro Text', 22, 'bold'),
height=10, width=20,
anchor='nw',
fg='#a1a1a6', bg="black")
# show on screen
label2.pack()
# Bitmap Label
label1 = Label(root, width=30, height=3, bg='black', fg='white',
bitmap='question',
padx=20, pady=20)
label1.pack()
label2 = Label(root, width=30, height=3, bg='black', fg='#a1a1a6',
bitmap='error',
padx=20, pady=20)
label2.pack()
root.mainloop()
|
e37f8d87b3ef63a808f91d5b6ead1f8b21739184 | DeanHe/Practice | /LeetCodePython/LongestIncreasingPathInaMatrix.py | 1,569 | 4.0625 | 4 | """
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]]
Output: 1
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 2^31 - 1
"""
from typing import List
class LongestIncreasingPathInaMatrix:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
mem = [[0] * cols for _ in range(rows)]
def dfs(r, c):
if not mem[r][c]:
cur = matrix[r][c]
mem[r][c] = 1 + max(
dfs(r - 1, c) if r > 0 and cur > matrix[r - 1][c] else 0,
dfs(r + 1, c) if r + 1 < rows and cur > matrix[r + 1][c] else 0,
dfs(r, c - 1) if c > 0 and cur > matrix[r][c - 1] else 0,
dfs(r, c + 1) if c + 1 < cols and cur > matrix[r][c + 1] else 0,
)
return mem[r][c]
return max(dfs(r, c) for r in range(rows) for c in range(cols)) |
673483c41223dc70ac46e316683f1db18f3b93f9 | Roentge-nium/ichw | /pyassign1/planets.py | 1,817 | 3.59375 | 4 | import turtle
import math
sun=turtle.Turtle()
sun.color("yellow")
sun.shape("circle")
sun.shapesize(3)
mercury=turtle.Turtle()
mercury.color("blue")
mercury.shape("circle")
mercury.shapesize(0.382)
venus=turtle.Turtle()
venus.color("#ffff24")
venus.shape("circle")
venus.shapesize(0.949)
earth=turtle.Turtle()
earth.color("#90c8ff")
earth.shape("circle")
earth.shapesize(1)
mars=turtle.Turtle()
mars.color("#934a00")
mars.shape("circle")
mars.shapesize(0.53)
jupiter=turtle.Turtle()
jupiter.color("#ffc890")
jupiter.shape("circle")
jupiter.shapesize(3.34)
saturn=turtle.Turtle()
saturn.color("black")
saturn.shape("circle")
saturn.shapesize(3.07)
mercury.up()
venus.up()
earth.up()
mars.up()
jupiter.up()
saturn.up()
mercury.goto(69.7,0)
venus.goto(109,0)
earth.goto(152.1,0)
mars.goto(249.1,0)
jupiter.goto(815.7*(3/7),0)
saturn.goto(1507/3,0)
mercury.down()
venus.down()
earth.down()
mars.down()
jupiter.down()
saturn.down()
for time in range(360000):
mercury.goto(57.8*math.cos(math.radians(-250*time/97.97))+11.9,math.sqrt(57.8**2-11.9**2)*math.sin(-math.radians(250*time/97.97)))
venus.goto(108.2*math.cos(math.radians(-250*time/224.7))+0.8,math.sqrt(108.2**2-0.8**2)*math.sin(-math.radians(250*time/224.7)))
earth.goto(149.6*math.cos(math.radians(-250*time/365.26))+2.5,math.sqrt(149.6**2-2.5**2)*math.sin(-math.radians(250*time/365.26)))
mars.goto(227.9*math.cos(math.radians(-250*time/686.98))+21.2,math.sqrt(227.9**2-21.2**2)*math.sin(-math.radians(250*time/686.98)))
jupiter.goto(778.3*(3/7)*math.cos(math.radians(-250*time/4332.71))+74.8*(3/7),math.sqrt((778.3*3/7)**2-(74.8*3/7)**2)*math.sin(-math.radians(250*time/4332.71)))
saturn.goto((1427/3)*math.cos(math.radians(-250*time/10759.5))+80./3,math.sqrt((1427/3)**2-(80/3)**2)*math.sin(-math.radians(250*time/10759.5)))
|
ac2a708e5ecc42b82ee814a228da0de85430a2d6 | AmpersandTalks/CIS106-Cesar-Perez | /Assignment 7/Activity 1.py | 1,390 | 4.09375 | 4 | def calculateOvertime(choice, rateperhour):
overtime = (choice - 40) * rateperhour / 2
return overtime
def calculateweekly(choice, rateperhour):
weekly = choice * rateperhour
return weekly
def displayResult(weekly):
print("$" + str(weekly) + " weekly ")
def displayResultOvertime(overtimeResults):
print("$" + str(overtimeResults) + " weekly ")
def getChoice():
print("Enter Y if worked Overtime or N for no Overtime:")
choice = input()
return choice
def gethours():
print("Enter hours worked this week")
hours = float(input())
return hours
def getrateperhour():
print("Enter rate per hour")
rateperhour = float(input())
return rateperhour
def processNotOvertime(choice):
rateperhour = getrateperhour()
weekly = calculateweekly(choice, rateperhour)
overtime = 0
displayResult(weekly)
def processOvertime(choice):
rateperhour = getrateperhour()
weekly = calculateweekly(choice, rateperhour)
overtime = calculateOvertime(choice, rateperhour)
overtimeResults = weekly + overtime
displayResultOvertime(overtimeResults)
# Main
# This program determines the amount of money made weekly with or without ovetime.
choice = gethours()
if choice > 40:
processOvertime(choice)
else:
processNotOvertime(choice)
|
fa482e032d3e277db353dedfe6627ab23a74c6a3 | FabianoBill/Estudos-em-Python | /04-Dicionários.py | 385 | 3.84375 | 4 |
linguas = {'BR': "Português", 'EUA': "Inglês"}
print(linguas['BR'])
print(linguas.get('EUA'))
print('BR' in linguas)
linguas['ES'] = "Espanhol"
print(linguas)
for chave in linguas.keys():
print(chave)
for valor in linguas.values():
print(valor)
for chave, valor in linguas.items():
print(chave, valor)
linguas.pop('BR')
print(linguas)
del linguas['EUA']
print(linguas)
|
cdaad37ad129119650eda826656372c58bce1b45 | GalaxyZpj/Python_Institutional | /Assignments/A1/6.py | 383 | 4.09375 | 4 | i_grade = input('Enter a grade: ')
try:
i_grade = int(i_grade)
except:
print('Enter a valid grade.')
if i_grade <= 10 and i_grade >= 8.5:
a_grade = 'A'
elif i_grade <= 8 and i_grade >= 7.5:
a_grade = 'B'
elif i_grade <= 7 and i_grade >= 6.5:
a_grade = 'C'
elif i_grade <= 6 and i_grade >= 5.5:
a_grade = 'D'
else:
a_grade = 'F'
print(f'Grade: {a_grade}')
|
051948df314746c81525dd00ebae41be66795be8 | ykoga-kyutech/python_work | /basic7.py | 483 | 3.546875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'tie304184'
"""
問題7.
1コラム目の文字列を集計して表示せよ(文字列/カウントを表示)
の解答。
"""
import sys
from collections import Counter
fname_input = "13tokyo\\13TOKYO.CSV"
col1 = list()
with open(fname_input, "r") as fin:
for m in fin:
col1.append(m.split(",")[0])
counter = Counter(col1)
for m, count in counter.most_common():
result = m+"/"+str(count)
print(result) |
0b8d825f4b57217a8ac1c5013185ab59784a39cc | zixcon/python | /script/http/dohttperror.py | 441 | 3.5625 | 4 | import urllib.request
from urllib.error import HTTPError, URLError # 要调用urllib.error模块
req = urllib.request.Request('http://www.baidusxxxx.com')
try:
response = urllib.request.urlopen(req)
except HTTPError as e: # 注意HTTPError别写错了,
print("http error:", e.reason)
print("httperror code:", e.code)
except URLError:
print("url error:", URLError.reason)
else:
print(response.read().decode('utf-8'))
|
a4653c05a6aeb1730f94abb57a062e17c0e59e62 | Halimeda/Python_Pratice | /Exercices/Exo/homework_21_01_corr.py | 285 | 3.953125 | 4 |
numbers = []
while sum(numbers) < 20:
number = input('Donne moi un nombre: ')
number = int(number)
numbers.append(number)
print('Nombre d''entrées: ' + str(len(numbers)))
print('Plus petit nombre: ' + str(min(numbers)))
print('Plus grand nombre: ' + str(max(numbers)))
|
08e9395c01c6553e52747f16a8c5af44a393eafd | nnaka/breast_cancer_classifier | /script.py | 1,612 | 3.59375 | 4 | import matplotlib
import sklearn
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
def main():
# part 1
breast_cancer_data = load_breast_cancer()
# part 2
print breast_cancer_data.data[0]
print breast_cancer_data.feature_names
# part 3
print breast_cancer_data.target
print breast_cancer_data.target_names
# part 5 and 6
training_data, validation_data, training_labels, validation_labels = train_test_split(breast_cancer_data.data, breast_cancer_data.target, train_size= 0.8, random_state = 100)
# part 7
print len(training_data)
print len(training_labels)
# part 9
classifier = KNeighborsClassifier(n_neighbors = 3)
# part 10
classifier.fit(training_data, training_labels)
# part 11
print classifier.score(validation_data, validation_labels)
# part 12 and 15
accuracies = []
for k in range(1, 100):
classifier = KNeighborsClassifier(n_neighbors = k)
classifier.fit(training_data, training_labels)
score = classifier.score(validation_data, validation_labels)
print "For run {}: {}".format(k, score)
accuracies.append(score)
print "Max score: {}".format(max(accuracies))
# part 14
k_list = range(1, 100)
# part 16 and 17
plt.plot(k_list, accuracies)
plt.title("Breast Cancer Classification Accuracy")
plt.xlabel("k")
plt.ylabel("Validation Accuracy")
plt.show()
if __name__ == "__main__":
main()
|
ef37214e3541e87fc73054803590865ca28f20a5 | TOMMYzhn/PandasVersusExcel-master | /6-InputFunction/InputFunction.py | 780 | 3.984375 | 4 | # pandasVersusExcel
# http://sa.mentorx.net/course/89/tasks
# 第六课 函数填充
# 2018-10-18
import pandas as pd
books = pd.read_excel('./Books.xlsx',index_col='ID')
print('----计算前----')
print(books)
# 方法一
# books['Price'] = books['ListPrice'] * books['Discount']
# print('----方法一----')
# print(books)
# 方法二(此方法可以对计算的行的范围进行精确控制)
for i in range(5,16): # books.index:
books['Price'].at[i] = books['ListPrice'].at[i] * books['Discount'].at[i]
print('----方法二----')
print(books)
# 方法一
books['ListPrice'] += 2
# 方法二
def add_2(x):
return x + 2
books['ListPrice'] = books['ListPrice'].apply(add_2)
# 方法三
books['ListPrice'] = books['ListPrice'].apply(lambda x:x+2)
print(books) |
997fd1edf83a7af4cba922d83329bc8ddfdc4278 | shubhamsinha1/Python | /PythonDemos/Commonly_Asked_Code/Array/1.Is_Unique.py | 367 | 3.953125 | 4 | word='abcd'
def is_unique_1(word: str):
if len(word) == 1:
return True
temp_arr=[]
for char in word:
if char not in temp_arr:
temp_arr.append(char)
else:
return False
return True
def is_unique_2(word:str):
return len(set(word)) == len(word)
print(is_unique_1(word))
print(is_unique_2(word)) |
8babf1cead8da82f5242bcf5889ff3bc91c46bd3 | RainbowwwYQ/InnovScraping_GoogleAPI | /2. Cleaning.py | 1,577 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 15:08:20 2020
@author: mayhe
"""
import pandas as pd
import string
# please notice: no comma in original documents!
df = pd.read_csv("GoogleAPI_all.csv", encoding= 'unicode_escape')
remove_url = pd.read_csv("remove_list.csv").drop_duplicates()
# change the file name if it is different from yours!!
# ---- step one: remove strings such as "www" ----
def remove(dataframe, col):
remove_head = ["www","http"]
dataframe["new_links"] = None # the links used to compare
for i in range(len(dataframe)):
temp = dataframe.iloc[i,int(col)]
for m in remove_head:
if (temp.startswith('.') != True) and (m in temp):
temp = temp.lstrip(m).strip(string.punctuation)
index = dataframe.columns.get_loc("new_links")
dataframe.iloc[i,index] = temp
remove(remove_url, 0) # which column you put the links
remove(df, 1)
# ---- step two: remove the common websites such as LinkedIn ----
remove_url = remove_url["new_links"].tolist()
index = df.columns.get_loc("new_links")
for i in range(len(df)):
temp = df.iloc[i,index]
for item in remove_url:
if item in temp:
df.iloc[i,index] = None
before = len(df)
df.dropna(axis=0, how='any', inplace=True)
after =len(df)
diff = before - after
print(f'You have removed {diff} high-frequency URLs!')
df.to_csv("GoogleAPI_cleaned.csv", index = False, sep=',')
# df is data frame we obtain. transfer df to next py file
|
334c80c4f8c90deb1de73612bda5388e819195ab | brandoneng000/LeetCode | /medium/229.py | 1,187 | 3.765625 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
# num_count = {}
# for n in nums:
# num_count[n] = num_count.get(n, 0) + 1
# return [n for n in num_count if num_count[n] > (len(nums) // 3)]
first_major, first_vote, second_major, second_vote, = 0, 0, 1, 0
for n in nums:
if n == first_major:
first_vote += 1
elif n == second_major:
second_vote += 1
elif first_vote == 0:
first_major, first_vote = n, 1
elif second_vote == 0:
second_major, second_vote = n, 1
else:
first_vote -= 1
second_vote -= 1
res = []
if nums.count(first_major) > len(nums) // 3:
res.append(first_major)
if nums.count(second_major) > len(nums) // 3:
res.append(second_major)
return res
def main():
sol = Solution()
print(sol.majorityElement([3,2,3]))
print(sol.majorityElement([1]))
print(sol.majorityElement([1,2]))
if __name__ == '__main__':
main() |
dc666a8f1beaddbff9dcd90854b4bda50df7e2f9 | chandramohank/Logical-Programes | /Python/BalancedParanthesis.py | 595 | 3.890625 | 4 | arr = []
def parens(left, right, string):
print(left,right,string)
# if no more brackets can be added then add the final balanced string
if left == 0 and right == 0:
arr.append(string)
# if we have a left bracket left we add it
if left > 0:
parens(left-1, right+1, string+"(")
# if we have a right bracket left we add it
if right > 0:
parens(left, right-1, string+")")
# the parameters parens(x, y, z) specify:
# x: left brackets to start adding
# y: right brackets we can add only after adding a left bracket
# z: the string so far
parens(3, 0, "")
print(arr) |
48669b5ebf655a4b34f426aab5966471b93eac70 | kecarrillo/monopoly | /Monopoly/Cell.py | 2,632 | 3.96875 | 4 | from Monopoly.Game import Game
class Cell:
"""This class represents the cells from the board game.
"""
def __init__(self, position, name, group):
"""This method is the constructor of the class.
:param position: Position of the cell on the board.
:type position: integer
:param name: Name of the cell.
:type name: string
:param group: Group of the cell: buildable, chance, community,
train station, company, cop, free park, other.
:type group: string
"""
self.position = position
self.name = name
self.owner = None
self.group = group
@staticmethod
def pay_a_rent(pawn, ownership):
"""This method make a pawn pay for a rent.
:param pawn: Instance of Pawn which is on the position.
:type pawn: Pawn
:param ownership: Instance of Ownership which lay on the position.
:type ownership: Ownership
:return: The rent is paid to the owner.
:rtype: void
"""
if ownership.is_mortgaged is False and ownership.owner != pawn.form:
pawn.give_money(ownership.rent(), ownership.owner)
elif ownership.owner == Game.board:
pawn.buy_ownership()
else:
pass
@staticmethod
def luxury_tax_rent(pawn):
"""This method applies the action when the pawn is on the cell
"luxury tax".
:param pawn: Instance of Pawn which is on the cell.
:type pawn: Pawn
:return: Pay the bank.
:rtype: void
"""
pawn.give_money(10_000, Game.bank)
@staticmethod
def income_tax_rent(pawn):
"""This method applies the action when the pawn is on the cell
"Income tax".
:param pawn: Instance of Pawn which is on the cell.
:type pawn: Pawn
:return: Pay the bank.
:rtype: void
"""
pawn.give_money(20_000, Game.bank)
@staticmethod
def free_park(pawn):
"""This method applies the action when the pawn is on the cell
"Free park".
:param pawn: Instance of Pawn which is on the cell.
:type pawn: Pawn
:return: The pawn earn the money of the board.
:rtype: void
"""
pawn.get_money(Game.board.money)
@staticmethod
def cop_cell(pawn):
"""This method applies the action when the pawn is on the cell
"Go to jail".
:param pawn: Instance of Pawn which is on the cell.
:type pawn: Pawn
:return: Send the pawn to jail.
:rtype: void
"""
pawn.go_to_jail()
|
30fcfb165f60a8b9d0eb61443e4abdd576ca1d5c | syurskyi/Python_Topics | /120_design_patterns/016_iterator/_exercises/templates/Iterator_003.py | 1,128 | 4.09375 | 4 | # #==============================================================================
# c_ ReverseIterator o..
# """
# Iterates the object given to it in reverse so it shows the difference.
# """
#
# ___ - iterable_object
# list _ ?
# # start at the end of the iterable_object
# index _ le. ?
#
# ___ -i
# # r_ an iterator
# r_ ?
#
# ___ next
# """ Return the list backwards so it's noticeably different."""
# __ in.. __ 0
# # the list is over, raise a stop index exception
# r_ S..
# in.. _ in.. - 1
# r_ li..|in..
#
# #==============================================================================
# c_ Days o..
#
# ___ -
# days _ |
# "Monday"
# "Tuesday",
# "Wednesday"
# "Thursday"
# "Friday"
# "Saturday"
# "Sunday"
# |
#
# ___ reverse_iter
# r_ R.. ?
#
# #==============================================================================
# __ _______ __ ______
# days _ D..
# ___ day __ ?.r_i..
# print ?
|
525e3e72e46272b828cb677c783d0b8d4f42d8f1 | vikendu/hackerrank-solutions | /reverse_vowels.py | 956 | 3.765625 | 4 | # Given a string, reverse only vowels in it. Leave the remaining string as it is.
# Input Format
# One string.
# Constraints
# 1 <= Length of string <= 10^5
# Output Format
# One string, the original string with vowels reversed.
# Sample Input 0
# trumpisshit
# Sample Output 0
# trimpisshut
in1 = input('')
list1 = []
for i in range(0, len(in1)):
if in1[i] == 'a' or in1[i] == 'e' or in1[i] == 'i' or in1[i] == 'o' or in1[i] == 'u' or in1[i] == 'A' or in1[i] == 'E' or in1[i] == 'I' or in1[i] == 'O' or in1[i] == 'U':
#print(in1[i])
list1.append(in1[i])
else:
continue
list1.reverse()
j = 0
for i in range(0, len(in1)):
if in1[i] == 'a' or in1[i] == 'e' or in1[i] == 'i' or in1[i] == 'o' or in1[i] == 'u' or in1[i] == 'A' or in1[i] == 'E' or in1[i] == 'I' or in1[i] == 'O' or in1[i] == 'U':
print(list1[j], end = "")
j = j+1
else:
print(in1[i], end = "")
|
748b947ce7b8729520f0df0b65d0748b8f019cc0 | scottdaniel/gradschool | /the_beginning.py | 426 | 3.59375 | 4 | program = None
def text_prompt(msg):
try:
return raw_input(msg)
except NameError:
return input(msg)
print('Welcome to Grad School')
program = text_prompt('What program would you like to join?')
print('You have chosen: ',program)
print('It is your first day of grad school')
print('Suddenly, Satan appears')
program = text_prompt('He says: grad school is hell, would you like to continue?')
print('You lose')
|
0758101b941a0639bd9cae223350b0ec13806b8e | smiszym/maze-walk | /mazewalk/game.py | 1,633 | 3.90625 | 4 | import curses
from .maze import Maze
from .generators import *
from .printers import utf8_printer
def _main_inner(stdscr):
stdscr.addstr("Choose maze generation algorithm:\n")
stdscr.addstr(" 1. Breadth First Search\n")
stdscr.addstr(" 2. Depth First Search\n")
stdscr.addstr(" 3. Horizontal Passage\n")
c = None
while c != ord('1') and c != ord('2') and c != ord('3'):
c = stdscr.getch()
if c == ord('1'):
generator = bfs_generator
elif c == ord('2'):
generator = dfs_generator
elif c == ord('3'):
generator = horiz_generator
width = 39
height = 23
m = Maze(width, height, generator, utf8_printer)
pos = m.initial_position
x = pos[0]*2
y = pos[1]
# Draw the maze
stdscr.clear()
stdscr.addstr(str(m))
while True:
if y == m.height - 1:
break # found the exit
stdscr.move(y, x)
c = stdscr.getch()
if c == curses.KEY_LEFT:
if x > 0 and not m.get_wall((x-1)//2, y):
x -= 1
elif c == curses.KEY_RIGHT:
if x//2 < width - 1 and not m.get_wall((x+1)//2, y):
x += 1
elif c == curses.KEY_UP:
if y > 0 and not m.get_wall(x//2, y-1):
y -= 1
elif c == curses.KEY_DOWN:
if y < height - 1 and not m.get_wall(x//2, y+1):
y += 1
elif c == 27:
break # quit the game on Esc key
if y == m.height-1:
stdscr.addstr("Congratulations! You found the exit")
stdscr.getch()
def play():
curses.wrapper(_main_inner) |
f70f76d2f397700cde822f87dbe0c54f49451a90 | DilaraPOLAT/Algorithm2-python | /5.Hafta(list,tuple)/ornek3.py | 1,008 | 4.09375 | 4 | """
ornek3:
liste veri tipi kullilarak kullanicidan alinan ogrenci isim,numara ve vize notu bilgilerini ayrı listelerde tutunuz.
tum ogrenci bilgilerini ve vize notu 70 den buyuk olan ogrencilerin bilgilerini ayri ayri aliniz.
"""
ogr_ad=[]
ogr_no=[]
ogr_vizenot=[]
syc=int(input("kac ogrenci bilgisi gireceksiniz:"))
for i in range(syc):
ad=input("ogrencinin adini giriniz:")
ogr_ad.append(ad)
no=int(input("ogrencinin numarasini giriniz:"))
ogr_no.append(no)
vizenot=int(input("ogrencinin vize notunu giriniz:"))
ogr_vizenot.append(vizenot)
#tum ogrenci bilgilerini listeleme
print("tum ogrenciler:")
for i in range(syc):
print("{}. ogrencinin adi:{},numarasi:{} , vizenotu:{}".format(i+1,ogr_ad[i],ogr_no[i],ogr_vizenot[i]))
#vize notu 70 den buyuk ogrenci bilgilerini listeleme
print("vizenotu 70 den yuksek ogrenciler:")
for i in range(syc):
if ogr_vizenot[i]>70:
print("ogrencinin adi:{} , numarasi:{} , vizenotu:{}".format(ogr_ad[i],ogr_no[i],ogr_vizenot[i]))
|
49c52ec3c4561d45e9bdb9ceaafe72cd8015e64c | tuseto/PythonHomework | /week5/5-Sublist/sublist.py | 544 | 3.625 | 4 | def sublist(list1, list2):
if list1 == []:
return True
for n in range(0, len(list2)-(len(list1)-1)):
if list1[0] == list2[n]:
counter = 0
for i in range(0,len(list1)):
if list1[i] == list2[n+i]:
counter += 1
else:
break
if counter == len(list1):
return True
return False
print(sublist([1,2],[1, 0, 1, 2, 2]))
|
d361c33c63f97f12d996c654588474a0036222ad | eveafeline/coding-challenges | /python/arrays_n_strings/3_URLify_test.py | 1,293 | 4.28125 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string has
sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation in place.)
e.g.
INPUT: "Mr John Smith ", 17
OUTPUT: "Mr%20John%20Smith"
"""
from collections import namedtuple
Case = namedtuple("Case", ["test_string", "length", "expected"])
def URLify(s, n):
trimmed = s[:n]
return trimmed.replace(' ', '%20')
def URLify_regex(s, n):
import re
rex = re.sub(r'[^\w\s]', ' ', s)
return re.sub(r'\s', '%20', rex[:n])
def test_run():
test_cases = [
Case("Mr John Smith ", 13, "Mr%20John%20Smith"),
Case("Mr John Smith ", 15, "Mr%20John%20Smith%20%20")]
for case in test_cases:
result = URLify(case.test_string, case.length)
assert result == case.expected
def test_regex():
test_cases = [
Case("Mr John Smith ", 13, "Mr%20John%20Smith"),
Case("Mr John Smith ", 15, "Mr%20John%20Smith%20%20")]
for case in test_cases:
result = URLify_regex(case.test_string,
case.length)
assert result == case.expected
|
a2341225ae36a480c33e9782f2e016ea18c18451 | sharpo101/blackjack | /blackjack.py | 7,323 | 3.65625 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':0}
playing = True
no_bust = True
game_on = True
class Card:
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
created_card = Card(suit,rank)
self.deck.append(created_card)
def __str__(self):
for card in self.deck:
return f'the cards in the deck are {card}'
def shuffle(self):
random.shuffle(self.deck)
def deal_one(self):
return self.deck.pop()
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self,card):
self.cards.append(card)
self.value += card.value
return self.value
self.adjust_for_aces()
def get_value(self,card):
self.value += card.value
return self.value
def adjust_for_aces(self):
if 'Ace' in [card.rank for card in self.cards]:
self.aces += 1
ace_value = int(input('Ace value 1 or 11?: '))
self.value += ace_value
class Chips:
def __init__(self):
self.total = 100 # This can be set to a default value or supplied by a user input
self.bet = 0
def win_bet(self):
self.total += self.bet * 2
def lose_bet(self):
self.total -= self.bet
def take_bet():
while True:
try:
player_bet.bet = int(input('Place your bet: $'))
return player_bet.bet
while player_bet.bet > player_bet.total:
print('Not enough chips')
player_bet.bet = int(input('Place your bet: $'))
return player_bet.bet
except:
print('Please place a valid bet')
continue
else:
print(f'Your bet is ${player_bet.bet}')
print(f'Your total is ${player_bet.total}')
break
def hit(deck,hand):
hand.add_card(deck.deal_one())
def hit_or_stand(deck,hand):
global playing
options = ['hit','stand']
hitorstand = True
while hitorstand:
try:
player_choice = input('\nWould you like to hit or stand? ')
while player_choice not in options:
print('Please choose hit or stand')
player_choice = input('Would you like to hit or stand? ')
except:
print('Please choose hit or stand!')
continue
else:
if player_choice == 'hit':
hit(deck,hand)
hitorstand = False
break
elif player_choice == 'stand':
global playing
playing = False
hitorstand = False
break
def show_some(player,dealer):
print('\n-------------------')
print('\nyour cards:')
for card in player:
print(card)
print(f"\nDealer's cards:")
print(dealer.cards[1])
def show_all(player,dealer):
print('\n-------------------')
print(f'\nyour cards:')
for card in player:
print(card)
print("\nthe dealer's cards are")
for card in dealer:
print(card)
def player_busts(player,chips):
global playing
global no_bust
if player.value > 21:
chips.lose_bet()
print('\n-------------------')
print('\nYou Bust!')
playing = False
no_bust = False
def player_wins(player,dealer,chips):
global no_bust
if player.value > dealer.value and player.value <= 21:
chips.win_bet()
print('\n-------------------')
print('\nYou win!')
no_bust = False
def dealer_busts(dealer,chips):
global no_bust
if dealer.value > 21:
print('\n-------------------')
print('\nDealer busts!')
chips.win_bet()
no_bust = False
def dealer_wins(player,dealer,chips):
global no_bust
if dealer.value > player.value and dealer.value <= 21:
print('\n-------------------')
print('\nDealer wins!')
chips.lose_bet()
no_bust = False
def push(player,dealer):
global no_bust
if player.value == dealer.value:
print('\n-------------------')
print('\nPUSH')
no_bust = False
def game_over():
global game_on
gameover = True
while gameover:
try:
playagain = ['Y','N']
play_again = input('Would you like to play again? Y or N: ')
while play_again not in playagain:
play_again = input('Please choose Y or N: ')
except:
print('Please choose Y or N')
else:
if play_again == 'Y':
playing = True
blackjack()
elif play_again == 'N':
playing = False
game_on = False
break
def new_hand():
player_hand.cards = []
player_hand.value = 0
player_hand.aces = 0
dealer_hand.cards = []
dealer_hand.value = 0
dealer_hand.aces = 0
for i in range(2):
player_hand.add_card(game_deck.deal_one())
for i in range(2):
dealer_hand.add_card(game_deck.deal_one())
player_hand = Hand()
dealer_hand = Hand()
player_bet = Chips()
game_deck = Deck()
def game_start():
global playing
playing = True
print('Welcome to blackjack!')
player_hand = Hand()
dealer_hand = Hand()
player_bet = Chips()
def blackjack():
global game_on
game_on = True
game_start()
game_deck.shuffle()
print(f'Starting chips: ${player_bet.total}')
while game_on:
global playing
global no_bust
playing = True
no_bust = True
new_hand()
take_bet()
while playing:
player_hand.adjust_for_aces()
show_some(player_hand.cards,dealer_hand)
hit_or_stand(game_deck,player_hand)
player_busts(player_hand,player_bet)
show_all(player_hand.cards,dealer_hand.cards)
while no_bust:
if dealer_hand.value >= 17:
hit(game_deck,dealer_hand)
show_all(player_hand.cards,dealer_hand.cards)
player_wins(player_hand,dealer_hand,player_bet)
dealer_busts(dealer_hand,player_bet)
dealer_wins(player_hand,dealer_hand,player_bet)
push(player_hand,dealer_hand)
print(f'\nYour chip total is: ${player_bet.total}')
if player_bet.total == 0:
game_over()
blackjack()
|
fac81d3d54cfb70b8cbd540056448be501d3398a | Salman791/Practise | /01_Pattern_Exercises.py | 1,320 | 4.375 | 4 | ############### RIGHT-ANGLED TRIANGLE ###############
# Input = int(input("Please enter the number of rows: "))
#
# for i in range(1,Input + 1):
# for j in range(1, i + 1):
# print("*", end=" ")
# print()
############### RIGHT-ANGLED TRIANGLE (Tilt) ############### (Control or Control Flow is the order in which the program executes itself)
# x = int(input("Please enter the number of rows: "))
# y = 1
#
# for i in range(1, x + 1):
# for j in range(1, y + 1):
# print("*", end=" ")
# y += 2
# print()
############### PYRAMID ###############
# x = int(input("Please enter the number of rows: "))
#
# for i in range(0, x):
# for j in range(0, x - i - 1):
# print(end=" ")
# for j in range(0, i + 1):
# print("*", end=" ")
# print()
############### PYRAMID (UPSIDE DOWN) ###############
# x = int(input("Please enter the number of rows: "))
#
# for i in range(0, x):
# for j in range(0, i):
# print(end=" ")
# for j in range(0, x - i):
# print("*", end=" ")
# print()
############### DIAMOND ###############
# x = int(input("Please enter the number of rows: "))
#
# for i in range(0,x):
# print( (" " * (x - i - 1)) + (("* ") * (i+1)))
# for j in range(x - 1, 0, -1):
# print((" ") * (x - j) + (("* ") * (j)))
|
22b258f1911c3347979389ccd4b701d2fc61fa55 | akosuawiafe01/PythonPeers | /Project1-Temperature_Converter.py | 338 | 4.375 | 4 | #Temperature Converter: Fahrenheit to Celcius
print("\n Hey there, welcome to the FC Temperature Calculator \n")
print('Please enter your temperature in Farenheit: \n')
temperature = input()
fahrenheit = int(temperature) - 32
celcius = int(fahrenheit) / 1.8
print('Your temperature is ', str(round(celcius,2)) , ' degree celcius')
|
3125af0c1212adfc38d3abb64b7927e0f5f02e3a | KC-Simmons/Self-Work | /NNFunc.py | 4,168 | 3.53125 | 4 | import numpy as np
#Activation Function (0,1)
sigmoid = lambda i: (1/(1+np.exp(-i)))
vectorized_sigmoid = np.vectorize(sigmoid)
#Set-up Learning Rate
LR = 0.9
class NN(object):
def __init__(self, NumIL, NumHL, NumOL):
self.NumIL = NumIL
self.NumHL = NumHL
self.NumOL = NumOL
#Creates the Weights Matrices
self.weightsHL = (np.random.rand(NumHL,NumIL)*2)-1
self.weightsOL = (np.random.rand(NumOL,NumHL)*2)-1
#Create Bias Matrices
self.biasHL =((np.random.rand(NumHL,1))*2)-1
self.biasOL =((np.random.rand(NumOL,1))*2)-1
def feedforward(self,ffinput):
hiddenlayer = (self.weightsHL.dot(ffinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
return outputlayer
def train(self,trinput,answers):
#Rerun FF code in the train
hiddenlayer = (self.weightsHL.dot(trinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
outputs = outputlayer
#Find the Errors
outputserrors = answers - outputs
weightsOL_t = np.transpose(self.weightsOL)
hiddenerrors = weightsOL_t.dot(outputserrors)
hidden_T = np.transpose(hiddenlayer)
gradients = (LR * outputserrors * outputs * (1 - outputs))
weight_ho_deltas = gradients.dot(hidden_T)
self.weightsOL = self.weightsOL + weight_ho_deltas
self.biasOL = self.biasOL + np.sum(gradients)
input_T = np.transpose(trinput)
hidden_gradients = (LR * hiddenerrors * hiddenlayer * (1 - hiddenlayer))
weight_ih_deltas = hidden_gradients.dot(input_T)
self.weightsHL = self.weightsHL + weight_ih_deltas
self.biasHL = self.biasHL + np.sum(hidden_gradients)
class CopyNN(object):
def __init__(self, NumIL, NumHL, NumOL, weightsHL, weightsOL, biasHL, biasOL):
self.NumIL = NumIL
self.NumHL = NumHL
self.NumOL = NumOL
self.weightsHL = weightsHL
self.weightsOL = weightsOL
self.biasHL = biasHL
self.biasOL = biasOL
def feedforward(self,ffinput):
hiddenlayer = (self.weightsHL.dot(ffinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
return outputlayer
def train(self,trinput,answers):
#Rerun FF code in the train
hiddenlayer = (self.weightsHL.dot(trinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
outputs = outputlayer
#Find the Errors
outputserrors = answers - outputs
weightsOL_t = np.transpose(self.weightsOL)
hiddenerrors = weightsOL_t.dot(outputserrors)
hidden_T = np.transpose(hiddenlayer)
gradients = (LR * outputserrors * outputs * (1 - outputs))
weight_ho_deltas = gradients.dot(hidden_T)
self.weightsOL = self.weightsOL + weight_ho_deltas
self.biasOL = self.biasOL + np.sum(gradients)
input_T = np.transpose(trinput)
hidden_gradients = (LR * hiddenerrors * hiddenlayer * (1 - hiddenlayer))
weight_ih_deltas = hidden_gradients.dot(input_T)
self.weightsHL = self.weightsHL + weight_ih_deltas
self.biasHL = self.biasHL + np.sum(hidden_gradients
NeuralNetwork = NN(2,5,1)
ffinputtest = np.array([[1,0,1,0],[0,1,1,0]])
targets = np.array([1,1,0,0])
print(NeuralNetwork.feedforward(ffinputtest))
for i in range(10000):
NeuralNetwork.train(ffinputtest, targets)
print(NeuralNetwork.feedforward(ffinputtest))
ffinputreal = np.array([[1],[1]])
print(NeuralNetwork.feedforward(ffinputreal))
##ffinput for feedforward alg are read by array
|
f0006d3c8991a30d1e202b806a142a380ffe22f9 | Eriklebson/ExerciciosEtecPAPython | /Python questão 02-10.py | 542 | 4.0625 | 4 | print("=========================================================================")
nomeP = input("Informe o nome do produto:")
valorP = float(input("Informe o valor do produto: R$"))
qtdP = int(input("Informe a quantidade de parcelas em ate 5x:"))
valorParcela = float
print("=========================================================================")
valorParcela = valorP / qtdP
print("O valor das percelas desse produto são:", qtdP, "de R$",valorParcela)
print("=========================================================================")
|
baddebaf428d17541aea325d8c454c89a3909868 | hkristensen/lawn | /lawn.py | 5,488 | 3.6875 | 4 | import random
class Environment():
def __init__(self, growth_rate) -> None:
self.growth_rate = growth_rate
class Lawn():
Lawn_Grid = 0
new_Mower = 0
cut_Percent = 0
current_direction = "x"
def __init__(self, lawn_x, lawn_y) -> None:
self.lawn_x = lawn_x + 2
self.lawn_y = lawn_y + 2
self.lawn_Size = 0
self.Lawn_Grid = []
def make_Lawn(self):
lawn = []
row = []
for i in range(self.lawn_x):
xlist = []
row.append(xlist)
for i in range(self.lawn_y):
new_list = row.copy()
lawn.append(new_list)
self.lawn_Size = self.lawn_y * self.lawn_x
self.Lawn_Grid = lawn
def grow_Grass(self):
for i in range(len(self.Lawn_Grid)):
for u in range(len(self.Lawn_Grid[i])):
self.Lawn_Grid[i][u] = Grass(5)
def spawn_Mower(self):
self.new_Mower = Mower(3,15,15)
for i in range(len(self.Lawn_Grid)):
if i == self.new_Mower.position_x - 1:
for u in range(len(self.Lawn_Grid[i])):
if u == self.new_Mower.position_y - 1:
self.Lawn_Grid[i][u].grass_height = self.new_Mower.cut_height
def move_Mower(self):
directions = ["x","y","xy1","xy2","xy3","xy4","xn","yn"]
random_event_change = random.randint(0,5)
move_x_positive = self.new_Mower.position_x + 1
move_y_positive = self.new_Mower.position_y + 1
move_x_negative = self.new_Mower.position_x - 1
move_y_negative = self.new_Mower.position_y - 1
if random_event_change == 5:
random_change = random.randint(0,7)
self.current_direction = directions[random_change]
if self.current_direction == "x" and (0 < move_x_positive <= self.lawn_x):
self.new_Mower.position_x = move_x_positive
elif self.current_direction == "xn" and (0 < move_x_negative <= self.lawn_x):
self.new_Mower.position_x = move_x_negative
elif self.current_direction == "y" and (0 < move_y_positive <= self.lawn_y):
self.new_Mower.position_y = move_y_positive
elif self.current_direction == "yn" and (0 < move_y_negative <= self.lawn_y):
self.new_Mower.position_y = move_y_negative
elif self.current_direction == "xy1" and (0 < move_y_positive <= self.lawn_y) and (0 < move_x_positive <= self.lawn_x):
self.new_Mower.position_y = move_y_positive
self.new_Mower.position_x = move_x_positive
elif self.current_direction == "xy2" and (0 < move_y_negative <= self.lawn_y) and (0 < move_x_positive <= self.lawn_x):
self.new_Mower.position_y = move_y_negative
self.new_Mower.position_x = move_x_positive
elif self.current_direction == "xy3" and (0 < move_y_negative <= self.lawn_y) and (0 < move_x_negative <= self.lawn_x):
self.new_Mower.position_y = move_y_negative
self.new_Mower.position_x = move_x_negative
elif self.current_direction == "xy4" and (0 < move_y_positive <= self.lawn_y) and (0 < move_x_negative <= self.lawn_x):
self.new_Mower.position_y = move_y_positive
self.new_Mower.position_x = move_x_negative
else:
random_direction = random.randint(0,7)
self.current_direction = directions[random_direction]
for i in range(len(self.Lawn_Grid)):
if i == self.new_Mower.position_x - 1:
for u in range(len(self.Lawn_Grid[i])):
if u == self.new_Mower.position_y - 1:
self.Lawn_Grid[i][u].grass_height = self.new_Mower.cut_height
self.cut_Percent = self.cut_Percent_calc()
def cut_Percent_calc(self):
tot = 0
cut = 0
for i in range(len(self.Lawn_Grid)):
for u in range(len(self.Lawn_Grid[i])):
if self.Lawn_Grid[i][u].grass_height == self.new_Mower.cut_height:
cut += 1
tot += 1
else:
tot += 1
return (cut / tot) * 100
def print_lawn(self):
print_lawn = []
row = []
for i in range(self.lawn_x):
xlist = []
row.append(xlist)
for i in range(self.lawn_y):
new_list = row.copy()
print_lawn.append(new_list)
for i in range(len(self.Lawn_Grid)):
for u in range(len(self.Lawn_Grid[i])):
print_lawn[i][u] = self.Lawn_Grid[i][u].grass_height
for i in range(len(print_lawn)):
print(print_lawn[i])
class Grass():
def __init__(self, grass_height) -> None:
self.grass_height = grass_height
class Mower():
def __init__(self, cut_height, position_x, position_y) -> None:
self.cut_height = cut_height
self.position_x = position_x
self.position_y = position_y
Environment = Environment(1)
Lawn = Lawn(30, 30)
Lawn.make_Lawn()
Lawn.grow_Grass()
Lawn.spawn_Mower()
c = 0
while c < 1024:
print(f"Mower X: {Lawn.new_Mower.position_x}, Y: {Lawn.new_Mower.position_y} Direction {Lawn.current_direction}")
Lawn.move_Mower()
c += 1
print(f"{Lawn.cut_Percent}")
Lawn.print_lawn()
|
4df39295e7b68748ce92856aad6af258add7a12e | camorazrushimoe/projecteuler | /2done.py | 485 | 3.71875 | 4 | def fib(n):
if n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
lst = fib(n-1)
lst.append(lst[-1] + lst[-2])
return lst
fib_num = fib(33)
print(fib_num) # Цифры фибоначи
sum = 0
current_num = 0
while current_num <= 33:
if fib_num[current_num] % 2 == 0:
sum = sum + fib_num[current_num]
current_num += 1
else:
current_num += 1
print(sum) #Правильный ответ 4 613 732
|
ae699be3630e04e637261d0ec9e412c21f7f8761 | shriharshs/AlgoDaily | /leetcode/103-binary-tree-zigzag-level-order-traversal/main.py | 940 | 3.625 | 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):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
res = []
q = []
q.append(root)
cnt = 0
while len(q) > 0:
n = len(q)
temp = []
for i in range(n):
head = q.pop(0)
if cnt % 2 == 0:
temp.append(head.val)
else:
temp.insert(0, head.val)
if head.left != None:
q.append(head.left)
if head.right != None:
q.append(head.right)
res.append(temp)
cnt += 1
return res
|
2afaf68e09cfbb25545744616a64a675308769ad | banderquartz/Python-Learning | /weekly_exercises/character_input.py | 325 | 3.875 | 4 | '''
Created on Nov 18, 2014
@author: mike
'''
from datetime import datetime
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
current_year = datetime.now().year
target_year = 100 - age + current_year
print("You, " + name + " will turn 100 years old in the year " + str(target_year))
|
df6e07390006b46c70b8b274d4938cb4a122b11f | razanALaskar/100DaysOfCode | /4th Week.py | 1,371 | 4.09375 | 4 | # Day 20: Sets
thisset ={"Apple","Orange","Banana","Apple"}
print(thisset)
for x in thisset:
print(x)
print("Banana is in the set:",("Banana"in thisset))
thisset.add("Cherry")
thisset.update(["Mango","Grapes"])
print(thisset)
# Day 21: Sets2
print(len(thisset))
thisset.remove("Apple")
thisset.discard("Orange")
print(thisset)
thisset.clear()
print(thisset)
# Day 22: Dictionaries
cars={"Model":"Ford","Year":"2018"}
print(cars)
print(cars["Year"])
print(cars.get("Model"))
cars["Year"]="2019"
print(cars)
for x in cars:
print(cars[x])
for x in cars.values():
print(x)
for x in cars.items():
print(x)
# Day 23: Dictionaries2
if "Model" in cars:
print("Model is in dictionary")
print(len(cars))
cars["Color"]="Blue"
print(cars)
cars.pop("Year")
print(cars)
cars.clear()
print(cars)
del cars
# Day 24: Dictionaries3
cars={"Model":"Ford","Year":"2018"}
cars1=cars.copy()
cars2= dict(cars)
print(cars1)
myfaily={
"Child1":{"Name":"Rana",
"Age":"18"},
"Child2":{"Name":"Ruba",
"Age":"16"}
}
print(myfaily)
cars4=dict(Model="Ford",Year="2018")
print(cars4)
# Day 25 & 26: Challenge
#1:
set = {1, 3, 5, 7, 8}
set.update([4,8,12])
print(set)
set.discard(8)
print(set)
set.clear()
print(set)
#2:
dic={"name":"pigeon","type":"bird","skin cover":"feathers"}
print(dic["type"])
dic["skin cover"]="colorful feathers "
print(dic) |
204d22434977a30b8d6f52347a961054b4ad8df2 | Yegor9151/Algorithms_and_data_structures_in_Python. | /lesson 2 - loops, recursion, functions/lesson2_task2/l2t2.py | 687 | 4.25 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
"""
num = input("Введите любое натуральное число: ")
even_nums = ''
odd_nums = ''
even, odd = 0, 0
for i in num:
if int(i) % 2 == 0:
even += 1
even_nums += i
else:
odd += 1
odd_nums += i
print(f'четных чисел - {even} ({", ".join(even_nums)})\n'
f'нечетных чисел - {odd} ({", ".join(odd_nums)})')
|
154bee0c3d9f40810d2693af6b115e25ebd890bb | tjdgus3160/algorithm | /CodeUp/재귀함수/(재귀함수)피보나치 수열.py | 105 | 3.78125 | 4 | def fibo(n):
if n<=2:
return 1
return fibo(n-1)+fibo(n-2)
n=int(input())
print(fibo(n))
|
c5ca250a326990d7597178ac4a85e30127b320e5 | imidya/gogo_design_pattern | /class5/answer_bridge.py | 975 | 4.1875 | 4 | import abc
class Drawer(abc.ABC):
@abc.abstractmethod
def forward(self):
raise NotImplementedError()
@abc.abstractmethod
def rotate(self):
raise NotImplementedError()
class TwoDDrawer(Drawer):
def forward(self):
print('2D forward')
def rotate(self):
print('2D rotate')
class ThreeDDrawer(Drawer):
def forward(self):
print('3D forward')
def rotate(self):
print('3D rotate')
class Maze:
def __init__(self, drawer):
self.drawer = drawer
def forward(self):
self.drawer.forward()
def rotate(self):
self.drawer.rotate()
def set_drawer(self, drawer):
self.drawer = drawer
if __name__ == '__main__':
maze = Maze(TwoDDrawer())
maze.forward()
maze.rotate()
maze.set_drawer(ThreeDDrawer())
maze.forward()
maze.rotate()
"""Excepted Result
2D forward
2D rotate
3D forward
3D rotate
"""
|
68a21f1c778236a539ac341bec9dec528eb236e3 | Wil10w/Beginner-Library-2 | /Error handling/Iterate with errors.py | 214 | 3.671875 | 4 | given_items = ["one", "two", 3, 4, "five", ["six", "seven", "eight"]]
for item in given_items:
try:
for j in item:
print(j)
except TypeError:
print('Not iterable')
pass
|
4b6e080b91a5340c8356988d91206fd301a9cbb3 | jgarciakw/virtualizacion | /ejemplos/ejemplos/class_property.py | 526 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#____________developed by paco andres____________________
class Circle(object):
PI = 3.14
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * self.PI * self.radius
@property
def radio(self):
return self.radius
@radio.setter
def radio(self,r):
if r>0:
self.radius=r
if __name__ == "__main__":
c=Circle(1.2)
print(c.perimeter())
print (c.radio)
c.radio=3.0
print (c.radio)
|
d1fd517e8afc8ed1ac7ee6558a7c036df66de135 | zuoyuanwei/package | /sort/xier.py | 1,068 | 3.9375 | 4 | # 希尔排序,将原始列表分解为多个较小的值列表改进插入排序。
# 最后一步执行完整的插入排序,但是不需要非常多的比较(或移位)
# 因为列表已经被较早的增量插入排序预排序。每个遍历产生比以前一个更有序的列表,使得最终遍历更有效。
# 时间复杂度介于O(n)和O(n^2)。
def shellSort(num):
sublistcount = len(num)//2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(num, startposition, sublistcount)
print('After increments of size', sublistcount, 'The list is', num)
sublistcount = sublistcount//2
def gapInsertionSort(num, start, gap):
for i in range(start+gap, len(num), gap):
currentvalue = num[i]
position = i
while position >= gap and num[position-gap] > currentvalue:
num[position] = num[position-gap]
position = position - gap
num[position] = currentvalue
print(shellSort([54,26,93,17,77,31,44,55,20])) |
d754ddbdc7242f9ca716c599bb6709a9abb96dad | mjbaucas/BlackJackBot | /dealer.py | 2,081 | 3.59375 | 4 | from random import *
from cards import Cards
cards = Cards()
class Dealer:
def init(self, deck1, deck2, deck3, deck4):
self.deck1 = deck1
self.deck2 = deck2
self.deck3 = deck3
self.deck4 = deck4
self.hand = []
self.score = 0
self.one_card_score = 0
def deal_card(self):
# Need to take card from one of the four decks at random
decknum = randint(1, 4)
if decknum == 1:
return self.deck1.pop()
elif decknum == 2:
return self.deck2.pop()
elif decknum == 3:
return self.deck3.pop()
elif decknum == 4:
return self.deck4.pop()
def hit(self):
# Dealer must hit if their score is less than 17
card = self.deal_card()
self.take_card(card)
print(f'Dealer\'s Hand After Hit: {" - ".join(self.hand)}')
print(f'Dealer\'s New Score After Hit: {self.get_score()}')
def shuffle_deck(self):
shuffle(self.deck1)
shuffle(self.deck2)
shuffle(self.deck3)
shuffle(self.deck4)
def reset_decks(self, deck1, deck2, deck3, deck4):
self.deck1 = deck1
self.deck2 = deck2
self.deck3 = deck3
self.deck4 = deck4
def take_card(self, card):
self.hand.append(card)
self.update_score()
def update_score(self):
score = 0
aces = 0
for card in self.hand:
number, suit = card.split('_')
score += cards.scores[number]
if number == 'A':
aces += 1
if score > 17 and aces > 0:
while aces > 0 and score > 21:
score -= 10
aces -= 1
# This is the dealer's actual score
self.score = score
# This is the score we will display to the player
number, suit = self.hand[0].split('_')
self.one_card_score = cards.scores[number]
def get_score(self):
return self.score
def get_one_card_score(self):
return self.one_card_score |
52e3f4e8afb6f69a0832c287b3e1eb9923187e4d | geodimitrov/Python-OOP-SoftUni | /Encapsulation/Exercises/01.wild_cat_zoo/project/zoo.py | 4,303 | 3.6875 | 4 | class Zoo:
def __init__(self, name, budget, animal_capacity, workers_capacity):
self.name = name
self.animals = []
self.workers = []
self.__budget = budget
self.__animal_capacity = animal_capacity
self.__workers_capacity = workers_capacity
@staticmethod
def has_enough_space(collection, capacity):
return len(collection) < capacity
@staticmethod
def has_enough_budget(budget, price):
return price <= budget
@staticmethod
def get_sum_workers_salaries(workers):
result = 0
for worker in workers:
result += getattr(worker, "salary")
return result
@staticmethod
def get_sum_animals_needs(animals):
result = 0
for animal in animals:
result += animal.get_needs()
return result
@staticmethod
def get_objects_by_class_type(type, collection):
return [obj for obj in collection if obj.__class__.__name__ == type]
def add_to_zoo(self, animal, price):
self.animals.append(animal)
self.__budget -= price
return f"{animal.name} the {animal.__class__.__name__} added to the zoo"
def add_animal(self, animal, price):
if not self.has_enough_space(self.animals, self.__animal_capacity):
return "Not enough space for animal"
if not self.has_enough_budget(self.__budget, price):
return "Not enough budget"
return self.add_to_zoo(animal, price)
def hire_worker(self, worker):
if not self.has_enough_space(self.workers, self.__workers_capacity):
return "Not enough space for worker"
self.workers.append(worker)
return f"{worker.name} the {worker.__class__.__name__} hired successfully"
def fire_worker(self, worker_name):
worker = [obj for obj in self.workers if obj.name == worker_name]
if not worker:
return f"There is no {worker_name} in the zoo"
self.workers.remove(worker[0])
return f"{worker_name} fired successfully"
def pay_workers(self):
workers_salaries = self.get_sum_workers_salaries(self.workers)
if not self.has_enough_budget(self.__budget, workers_salaries):
return "You have no budget to pay your workers. They are unhappy"
self.__budget -= workers_salaries
return f"You payed your workers. They are happy. Budget left: {self.__budget}"
def tend_animals(self):
animals_needs = self.get_sum_animals_needs(self.animals)
if not self.has_enough_budget(self.__budget, animals_needs):
return "You have no budget to tend the animals. They are unhappy."
self.__budget -= animals_needs
return f"You tended all the animals. They are happy. Budget left: {self.__budget}"
def profit(self, amount):
self.__budget += amount
def animals_status(self):
return f"You have {len(self.animals)} animals\n" \
+ f"----- {len(self.get_objects_by_class_type('Lion', self.animals))} Lions:\n" \
+ "".join(f"{obj.__repr__()}\n" for obj in self.get_objects_by_class_type('Lion', self.animals))\
+ f"----- {len(self.get_objects_by_class_type('Tiger', self.animals))} Tigers:\n" \
+ "".join(f"{obj.__repr__()}\n" for obj in self.get_objects_by_class_type('Tiger', self.animals)) \
+ f"----- {len(self.get_objects_by_class_type('Cheetah', self.animals))} Cheetahs:\n" \
+ "\n".join(obj.__repr__() for obj in self.get_objects_by_class_type('Cheetah', self.animals))
def workers_status(self):
return f"You have {len(self.workers)} workers\n" \
+ f"----- {len(self.get_objects_by_class_type('Keeper', self.workers))} Keepers:\n" \
+ "".join(f"{obj.__repr__()}\n" for obj in self.get_objects_by_class_type('Keeper', self.workers))\
+ f"----- {len(self.get_objects_by_class_type('Caretaker', self.workers))} Caretakers:\n" \
+ "".join(f"{obj.__repr__()}\n" for obj in self.get_objects_by_class_type('Caretaker', self.workers)) \
+ f"----- {len(self.get_objects_by_class_type('Vet', self.workers))} Vets:\n" \
+ "\n".join(obj.__repr__() for obj in self.get_objects_by_class_type('Vet', self.workers)) |
e6ebd32c4664aa73903da3c0b4fd660c0193557a | tonylixu/devops | /algorithm/keyboard-row/keyboard-row.py | 1,133 | 4.0625 | 4 | def findWords(words):
# We define keyboard rows
keyboard_rows = [
['e', 'i', 'o', 'p', 'q', 'r', 't', 'u', 'w', 'y'],
['a', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 's'],
['b', 'c', 'm', 'n', 'v', 'x', 'z']
]
# We sort and eliminate the duplicate
# because if you can type one, you can type many
words_new = []
re = []
for i in words:
words_new.append(''.join(set(sorted(i.lower()))))
position = 0
for w in words_new:
list_w = list(w)
# The number of characters can be typed in each row
counter_1 = counter_2 = counter_3 = 0
length = len(list_w)
for i in list_w:
if i in keyboard_rows[0]:
counter_1 += 1
elif i in keyboard_rows[1]:
counter_2 += 1
elif i in keyboard_rows[2]:
counter_3 += 1
if counter_1 == length or counter_2 == length or counter_3 == length:
re.append(words[position])
position += 1
print re
if __name__ == "__main__":
words = ["Hello", "Alaska", "Dad", "Peace"]
findWords(words) |
5b1e2bd367cd7064713ed7084a4803c65a55cd31 | nurulmisbahudin/Tugas-coding | /LIST.py | 770 | 3.609375 | 4 | jawab = 'ya'
while(jawab == 'ya'):
no = input("NO :")
nama = raw_input("NAMA :")
nim = input("NIM :")
nt= input("NILAI TUGAS :")
nuts = input("NILAI UTS :")
nuas = input("NILAI UAS :")
nakhir = int(nt*30/100)+(nuts*35/100)+(nuas*35/100)
jawab = raw_input("Tambah data (ya/tidak) :")
if jawab == 'tidak':
while(jawab == 'tidak'):
print"____________________________________________________________"
print "| NO | NAMA| NIM | N.TUGAS | N.UTS | N.UAS | N.AKHIR |"
print "------------------------------------------------------------"
print"|",no," | ",nama,"| ",nim,"|",nt,"|",nuts," |",nuas," |",nakhir,"|"
break
|
bf3540869cd84942f604019fd88db5eea27584a9 | speedybees/dailyprogrammer-165-the-forest | /node.py | 1,327 | 3.859375 | 4 | from enum import Enum
class Direction(Enum):
north = n = 1
northeast = ne = 2
east = e = 3
southeast = se = 4
south = s = 5
southwest = sw = 6
west = w = 7
northwest = nw = 8
class Node(object):
def __init__(self):
self.entities = set()
self.travel_directions = {}
def add_travel_direction(self, direction, node):
"""Indicate what node is reached by traveling a direction"""
self.travel_directions[direction] = node
def add_entity(self, entity):
self.entities.add(entity)
def remove_entity(self, entity):
self.entities.remove(entity)
def move_entity_to_node(self, entity, node):
self.remove_entity(entity)
node.add_entity(entity)
entity.node = node
def get_entities_of_type(self, entity_type):
return set([entity for entity in self.entities if type(entity) == entity_type])
def has(self, entity_type):
return (len(self.get_entities_of_type(entity_type)) > 0)
def short(self):
"""Get the short (one character ASCII) value to display for
what's in this node."""
if len(self.entities) == 0:
return '.'
elif len(self.entities) == 1:
return iter(self.entities).next().short()
else:
return '*'
|
063a238f1355b9f299c459c4afd9ba349c4b5068 | honghen15/checkio_ | /long-repeat.py | 895 | 4.15625 | 4 | def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
# your code here
count = 0
max1 = 1
if(line == ''):
return 0
letter = ''
for i in line:
if letter == '' or not (letter == i):
letter = i
count = 1
if letter == '':
max1 =1
else:
count+=1
if ( max1 < count ):
max1 = count
return max1
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
print( long_repeat('sdsffffse'))# == 4, "First"
print( long_repeat('ddvvrwwwrggg'))# == 3, "Second"
print( long_repeat('abababaab'))# == 2, "Third"
print( long_repeat(''))# == 0, "Empty"
print( long_repeat('abababa'))# == 1, "Empty"
print('"Run" is good. How is "Check"?')
|
a7117cc56c3a2e6e7cb2a4bad21867fde3d29806 | eucortes04/python-challenge | /PyBank/main.py | 2,434 | 3.625 | 4 | import os
import csv
#Path to collect dataset
financials_csv_path = os.path.join('Resources','budget_data.csv')
#Reading in CSV
with open(financials_csv_path) as csvfile:
financials = csv.reader(csvfile, delimiter=",")
#accounting for header
csv_header = next(financials)
#Variables
totalMonths = 0 #Holds Months count in financials data
ProfitLossTotal = 0 #Holds total P/L
greatestProfitMonth = "" #Holds month of highest profit
greatestProfit = 0 #Holds amount of highest profit
greatestLossMonth = "" #Holds month of highest loss
greatestLoss = 0 #Holds amount of highest loss
previous_PL = 0 #Holds previous amount of P/L for delta calc
delta_PL = 0 #Holds delta for period
delta_Total = 0 #Holds total delta for all periods
#iterate through the rows of data (Month-Year , P/L)
for row in financials:
#Adding to the month count
totalMonths +=1
#Storing current period changes information
current_PL = int(row[1]) #profit/loss
month = row[0] #month
if previous_PL !=0: #skipping first row since there is no previous month for accurate calculation of delta
delta_PL = current_PL-previous_PL #calc current period delta
delta_Total +=delta_PL #Adding to total delta for all periods
previous_PL = current_PL #setting previous P/L for next row
#Adding to the net P/L
ProfitLossTotal += current_PL
#Finding greatest Profit
if delta_PL>greatestProfit:
greatestProfitMonth = month
greatestProfit = delta_PL
#Finding greatest Loss
if delta_PL<greatestLoss:
greatestLossMonth = month
greatestLoss = delta_PL
#Average change delta total/ total periods (months-1) rounded to 2 decimal places
#Print out Analysis
analysisText = f'''
Financial Analysis
--------------------------
Total Months: {totalMonths}
Total: ${ProfitLossTotal}
Average Change: ${round(delta_Total/(totalMonths-1),2)}
Greatest Increase in Profits: {greatestProfitMonth} (${greatestProfit})
Greatest Decrease in Profits: {greatestLossMonth} (${greatestLoss})'''
print(analysisText)
#write analysis Activity 10,12
output_path = os.path.join("analysis","analysis_output.txt")
with open(output_path, 'w') as analysisDoc:
analysisDoc.write(analysisText)
|
e8edfea23b9a36a6c73b598fb52dab7e1f2223d0 | Gera2019/gu_python | /lesson_11/task_4.py | 3,889 | 3.609375 | 4 | from collections import defaultdict
class OfficeEqpmt:
type = ''
def __init__(self, name, vendor):
self.name = name
self.vendor = vendor
def __str__(self):
return f'{self.type} {self.vendor.capitalize()} {self.name.capitalize()}'
@property
def _data(self):
return (self.type, self.vendor, self.name)
class Printer(OfficeEqpmt):
type = 'printer'
class Scanner(OfficeEqpmt):
type = 'scanner'
class MFU:
def __init__(self, a, b):
self.a = a
self.b = b
type = 'MFU'
class Storage:
total_cnt = 0
_shelf = defaultdict(list)
_location = 'Storage'
@staticmethod
def __data_validation(data):
if not isinstance(data[0], OfficeEqpmt) or not isinstance(data[1], int):
return False
else:
return True
@classmethod
def storage_in(self, equipment, quantity):
self.__item_quantity = [equipment, quantity]
try:
if self.__data_validation(self.__item_quantity):
self.total_cnt += 1 * quantity
self._shelf[equipment._data[0]].append([equipment, quantity, self._location])
else:
raise TypeError
except TypeError:
print(f'The data type is invalid for {equipment}, please check and try again')
@classmethod
def storage_out(self, equipment, quantity, location):
self.__item_quantity = [equipment, quantity]
self.total_cnt -= 1 * quantity
try:
if self.__data_validation(self.__item_quantity):
list_eq = self._shelf[equipment._data[0]]
for el in list_eq:
if el[0] == equipment:
el[1] -= quantity
list_eq.append((equipment, quantity, location))
else:
raise TypeError
except TypeError:
print(f'The data type is invalid for {equipment}, please check and try again')
@classmethod
def get_info(self, args=None):
if args:
for el in self._shelf[args]:
print(f'Position: {el[0]}, Quantity: {el[1]}, Location: {el[2]}')
else:
for item in self._shelf.values():
for el in item:
print(f'Position: {el[0]}, Quantity: {el[1]}, Location: {el[2]}')
# test section
# Создание экзепляров из подклассов Принтер, Сканер и МФУ
p1 = Printer('R450', 'epson')
p2 = Printer('H7000', 'epson')
s = Scanner('U789', 'epson')
m = MFU('S2000', 'futjitsu')
# Проверка метода складка, который фиксирует прием техники
# В качестве параметров метод принимает объект из класса офисной техники и количество данной единицы товара
Storage.storage_in(p1, 1)
Storage.storage_in(p2, 2)
Storage.storage_in(s, 8)
# объект m не является объектом офисной техники, проверка, что валидация данных отрабатывает
# во втором случае, количество не является типом int
Storage.storage_in(m, 2)
Storage.storage_in(m, '3')
print('-' * 10)
# Метод get_info() позволяет вывести информацию о всех товарах или только о конкретных видах,
# например get_info('printer') выведет информацию только о принтерах
Storage.get_info()
print('-' * 10)
Storage.get_info('scanner')
print('-' * 10)
# Проверка метода отпуска товара в отделы
Storage.storage_out(p2, 1, 'Бухгалтерия')
Storage.storage_out(s, 2, 'Юридический отдел')
Storage.get_info()
|
2a1a3ee56b149231fd7de00d1bf245e7e9c08e9c | mattcpfannenstiel/feudalismSimMulti | /Climate.py | 505 | 3.734375 | 4 | import random as r
class Climate:
"""
This represents the number of growing days for each landunit
"""
def __init__(self):
"""
Creates a new instance of climate class for a landunit
"""
self.growthmax = 300
self.growthmin = 80
self.growthdays = r.randint(self.growthmin, self.growthmax)
def getgrowthdays(self):
"""
:return: Returns the number of growth days for a land unit
"""
return self.growthdays |
d0ec06bb7e0a4d418372af1d9dba9e5873ba0ab0 | marcelo046/algoritmo_busca | /main.py | 2,728 | 3.609375 | 4 | %matplotlib inline
import random
import matplotlib.pyplot as plt
import time
# declarações
size = 500 # não pode ser maior que max_number, pois dá erro no random.sample
loops = 25
max_number = 1000
x = []
time_sequential = []
time_binary = []
# comandos iniciais
for i in range(1, size+1):
x.append(i)
# funções
def gen_random_list():
return random.sample(range(1, max_number), size)
def gen_order_list():
list = random.sample(range(1, max_number), size) #creating a list in range 0 to 100
list.sort() # ordering
return list
def get_random_number():
return random.randint(1,101)
def sequential_search(number):
for k in range(0,len(list_numbers_any),1):
if(number == list_numbers_any[k]): return k
return -1
def binary_search(number):
less = 0
high = len(list_numbers_order) - 1
update = 0
while(less <= high):
update = (less + high) // 2
if(number < list_numbers_order[update]):
high =update
elif(number > list_numbers_order[update]):
less = update
else:
return update
def gen_graph(list, title='plot of points'):
plt.cla()
plt.clf()
plt.title(title)
plt.xlabel('x')
plt.ylabel('points')
plt.plot( x , list , 'ro')
plt.show()
def average_vector(vet): # tira a média de um vetor
add = 0
for i in range(0, len(vet), 1):
add += vet[i]
return add
# main
list_numbers_any = gen_random_list()
list_numbers_order = gen_order_list()
print("vetor de números em ordem crescente")
print(list_numbers_order)
gen_graph(list_numbers_order)
print("vetor de números em ordem aleatória")
print(list_numbers_any)
gen_graph(list_numbers_any)
# faz as buscas sequenciais
for it in range(0,loops,1):
search_number_any = random.choice(list_numbers_any)
#print(search_number_any)
start_s = time.time()
sequential_search(search_number_any)
finish_s = time.time()
time_sequential.append(finish_s - start_s)
# faz as buscas binárias
for it in range(0,loops,1):
search_number_order = random.choice(list_numbers_order)
#print(search_number_order)
start_s = time.time()
binary_search( search_number_order)
finish_s = time.time()
time_binary.append(finish_s - start_s)
time_1 = average_vector(time_binary)
time_2 = average_vector(time_sequential)
print("foram realizadas %d buscas em cada vetor de %d posições\n" % (loops, size))
print("O tempo medio da busca binario é: ", time_1*1000, " milissegundos")
print("O tempo medio da busca sequencial é: ",time_2*1000, " milissegundos\n")
print("Nesse caso, a busca binaria foi cerca de %.2f vezes mais rápido que a sequencial" % (time_2 / time_1))
|
90af3a34ae86ec958603dc1555b61f3be291b4ae | yckfowa/codewars_python | /8KYU/Swap Values.py | 181 | 3.515625 | 4 | #Solution 1
def swap_values(args):
args[0], args[1] = args[1], args[0]
-----------------------------------------
#Solution 2
def swap_values(args):
return args.reverse()
|
8b37912e08d5fc2a6656c7631be698bcd98bbe7f | wjj800712/python-11 | /chengxiangzheng/week3/test.py | 244 | 3.546875 | 4 | #python冒泡排序
list=[1,89,37,98,67,82,12,46,328,15,23,124,65,36,76,83]
print(len(list))
for i in range(len(list)):
for j in range(len(list)-1-i):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
print(list) |
a55ad2829bd9bfb2ac8301422302f2fb15cd054b | SophieChien/driving | /driving.py | 742 | 3.984375 | 4 | country = input('請輸入您的國家:')
age = input('請輸入您的年齡: ')
age = int(age)
if country == '台灣':
if age >= 18:
print('您可以考駕照')
else:
print('您還不能考駕照')
elif country == '美國': #根源於if,為if的延伸
if age >= 16:
print('您可以考駕照')
else:
print('您還不能考駕照')
else:
print('只能輸入台灣或美國')
country = input('請輸入您的國家:')
age = input('請輸入您的年齡: ')
age = int(age)
if country == '台灣':
if age >= 18:
print('您可以考駕照')
else:
print('您還不能考駕照')
elif country == '美國': #根源於if,為if的延伸
if age >= 16:
print('您可以考駕照')
else:
print('您還不能考駕照')
|
4f76b680e1927bf2d39024e04925451659e34cb0 | thirstycode/GUI_application_python_tkinter | /prog2.py | 1,712 | 4.03125 | 4 | # made by pratik kinage (thirstycode)
# https://github.com/thirstycode
# importing module tkinter
# first you need to install tkinter module
from tkinter import *
# create window using tkinter
win = Tk()
# title for window
win.title("Convertor")
# declaring input variable in tkinter
input1 = StringVar()
# label allows to insert text and photos (**for photos we need pillow)
w = Label(win,text="This Is Weight Convertor! Entry Value Here(In kg) & Press Convert")
# grid specifies the position of objects to be displayed
w.grid(row = 0 , column = 0)
# function
def conversion():
# we use try-except because variable input1 not always has the expected value
try:
text1.insert(END, str(float(input1.get())*1000) + " grams")
text2.insert(END, str(float(input1.get())*2.20462) + " pounds")
text3.insert(END, str(float(input1.get())*35.274) + " ounches")
except:
pass
# input box declaration
# text variable is variable assigned to text typed in textbox
Input_box = Entry(win , textvariable = input1)
Input_box.grid(row = 1 , column = 0)
# command is the function to be called after pressing the button
# command only needs function name without parenthesis
button1 = Button(win,text = "Convert", command = conversion )
button1.grid(row = 2 , column = 0)
# declaring text box
text1 = Text(win,height = 1 , width = 40)
text1.grid(row = 3,column = 0)
text2 = Text(win,height = 1 , width = 40)
text2.grid(row = 4,column = 0)
text3 = Text(win,height = 1 , width = 40)
text3.grid(row = 5,column = 0)
w2 = Label(win,text="@developed BY Pratik")
w2.grid(row = 6 , column = 1)
# keeps window running
win.mainloop()
|
4c1fbefb077ae6a8f94c98814aea7701097b784c | Leo-Mensah/Exercises | /exercise5.py | 260 | 3.828125 | 4 | first = input("Enter the file name: ")
fname = open(first)
lst = list()
for name in fname:
flist = name.split()
for i in flist:
print(i)
if i in lst :
continue
else:
lst.append(i)
lst.sort()
print(flist)
|
018687a13e5dabcf73d1b806b1e3460c16e6e914 | dakotabourne373/CS1110 | /crypto.py | 623 | 3.5 | 4 | # Dakota Bourne (db2nb) Nick Manalac (ntm4kd) Justin Lakier (Jel5hv)
"""
"""
def encrypt(plain_text, key):
cipher_text = '' # accumulator pattern: start with no encrypted test
for i in range(0, len(plain_text), 1): # look one chunk at a time
chunk = plain_text[i:i+1] # all chunks the same size
cipher_text += encrypt_chunk(chunk, key) # most work is in another function
return cipher_text
def encrypt_chunk(chunk, key):
if chunk == " ":
return " "
else:
return chr(ord(chunk) + key)
print(encrypt("black people", 3))
print(list("black people")) |
a25f46ecfeeac8deadf77142a35e199ff9a978fc | Carb-X/Exercise | /Mlog.py | 2,564 | 3.6875 | 4 | """类的内省和装饰器。
定义一个类Mlog,对于继承自Mlog的子类,每当其调用属性方法时,打印如下内容:
类名、被调用的属性方法和参数值列表
开始运行时间
结束运行时间
函数运行的结果
示例:
class Any(Mlog):
def track(*args, **kwars):
pass
a = Any()
a.track(1,2,3, b="xx")
输出:
[Mlog] Any.track(1,2,3, b="xx")
[start] {start_timestamp}
[end] {end_timestamp}
[result] {result}
"""
import datetime
class Mlog(object):
pass
def method_dec(original_function, cls_name, method_name):
"""This decorator is used to write logs for a class method when it is called."""
def new_function(*args, **kw):
print('[Mlog] {}.{}({}, {})'.format(cls_name, method_name, args, kw))
print('[start] {}'.format(datetime.datetime.now()))
result = original_function(*args, **kw)
print('[end] {}'.format(datetime.datetime.now()))
print('[result] {}'.format(result))
return result
return new_function
def mlog_subclass_dec(Cls):
"""Class decorator for classes derived from Mlog.
When an instance method of a subclass (the method
is not defined in Mlog) is invoked, print:
class name, method name and arguments list;
start and end time of the function call;
result of this invocation.
"""
if (Mlog not in Cls.__bases__): # do nothing if Cls is not derived from Mlog
return Cls
class NewCls(object):
def __init__(self, *args, **kw):
self.oInstance = Cls(*args, **kw)
def __getattribute__(self, attr_name):
try:
attr = super().__getattribute__(attr_name)
except AttributeError:
pass
else:
return attr
attr = self.oInstance.__getattribute__(attr_name)
if type(attr) == type(self.__init__):
return method_dec(attr, Cls.__name__, attr.__name__)
else:
return attr
return NewCls
@mlog_subclass_dec
class Any(Mlog):
def a(self, x, y):
return x + y
# Test 1:
#
# The logs are as follows:
# [Mlog] Any.a((1, 2), {})
# [start] 2019-03-06 20:33:43.395617
# [end] 2019-03-06 20:33:43.395617
# [result] 3
any = Any()
any.a(1, 2)
@mlog_subclass_dec
class Some(object):
def s(self, x):
return x
# Test 2:
#
# No logs are printed because Some is not derived from Mlog.
some = Some()
some.s(1)
|
3cf12c5ad110bd61f13ccb6957afd7cc9c5d1d26 | yoonakim1027/devops_cloud-1 | /myproj02/main06.py | 197 | 3.625 | 4 | def gugudan(number):
# number = 2
print(f"--- {number}단 ---")
for i in range(1, 10):
print(f"{number} * {i} = {number * i}")
for number in range(2, 10):
gugudan(number)
|
b22088c2ebe9734e8382183bdbf7991d50616ed3 | ZhuJiaYou/Interview_Preparation | /leetcode/84_largest_rectangle_area.py | 1,012 | 3.921875 | 4 | def largest_rectangle_area(heights):
largest = 0
def largest_n(i):
low, high = i, i
while low-1 >= 0 and heights[low-1] >= heights[i]:
low -= 1
while high+1 < len(heights) and heights[high+1] >= heights[i]:
high += 1
return (high-low+1)*heights[i]
for i in range(len(heights)):
li = largest_n(i)
if li > largest:
largest = li
return largest
def largest_rectangle_area2(heights):
heights.append(0)
left_boundries = [-1]
largest = 0
for i in range(len(heights)):
while heights[i] < heights[left_boundries[-1]]:
h = heights[left_boundries.pop()]
w = i - left_boundries[-1] - 1
largest = max(largest, w*h)
left_boundries.append(i)
print(heights)
print(left_boundries)
return largest
if __name__ == '__main__':
heights = [2, 1, 5, 6, 2, 3]
print(largest_rectangle_area(heights))
print(largest_rectangle_area2(heights))
|
1ea5429aefcacbdd9dc82d94b09d78c793c7ae98 | Fashad-Ahmed/Python-Practices | /duplications.py | 276 | 3.859375 | 4 |
x=int(input("enter character: "))
list1=[]
for i in range(x):
a=int(input("ennter number: "))
if type(a) == int:
list1.append(a)
else:
continue
final=[]
for i in list1:
if i not in final:
final.append(i)
print(final) |
29e122c37046f2f538c20e84ea02cfe3d9b8cbfe | Ardyn77/PythonExamples | /functions.py | 910 | 3.640625 | 4 | def complexFunction(s,*mult,**amt):
sum = 0
for x in mult:
sum = sum +x
print("the legends name is: ",s,"\n %s, the total sum we have gathered is %d"%(s,sum),"and list is as follows")
for i,j in amt.items():
print("Person",i,"Amount",j)
print(complexFunction("sairam",550,650,750,850,peter = 550, john = 650, mark = 750, chris = 850)
)
''' keyword def introduces function definition. followed by function name
first statement in function body is optional statement called documentation strings
function execution introduces a nre symbol table used for the local variables of the function
all local variables in the function are stored in this table whereas variable references first
look in the local symbol table then in the local symbol table of enclosing function, then in the
global symbol table and finally in the table of buitl-in names.
'''
|
25c32239f2bf683826b49fa179e6db9c421ff3bc | Big-Wisdom1996/Food | /untitled0.py | 1,268 | 3.578125 | 4 | def grabLine(line):
source = open(r"/users/elihermann/documents/github/food/source.txt",'r')
for x in range (0,line):
data = source.readline()
source.close()
return data
def main():
line = grabLine(1)
x = 1
dish,ingredient, AInv, WInv = "","","",""
while(line != "END END"): #Surf through entire document
line = grabLine(x)
#sort content of a line by its prefix
if(len(line) != 1):
prefix = line.split(" ")[0]
content = line.split(" ")[1]
if(prefix == "D"): #right now this is pointless
dish = content
elif(prefix == "I"):
ingredient = content
elif(prefix == "AInv"):
AInv = eval(content[0])#store as integer, and you have to put the [0] here because
elif(prefix == "WInv"): #the string actually has a \n charachter in it which screws it up
WInv = eval(content[0])#store as integer
#When all content is full print and reset content
if(ingredient!="" and AInv!="" and WInv!=""):
need = WInv - AInv
#print("You need",need,ingredient)
#ingredient, AInv, WInv = "","",""
x += 1
main() |
c70ca434e2d6f92e899009926301121d23bd5a02 | haohaixingyun/dig-python | /com/ibm/testing/list.py | 467 | 3.65625 | 4 | '''
Created on Mar 30, 2016
@author: yunxinghai
'''
def main():
Squ = [1,2,3,45,6,8]
sums = 0
lists = ['larry', 'curly', 'moe']
for var in Squ:
sums +=var
print sums
if 'curly' in lists:
print 'yay'
for i in range(10):
print i
j = 0
while j < 100:
print j
j = j + 1
if __name__ == '__main__':
main() |
9a1784c313dd739d4bb344f2b8956693f476b6fb | capitao-red-beard/practice_exercises | /even_or_odd.py | 162 | 4.3125 | 4 | value = int(input('Please enter a maximum value: '))
for i in range(0, value + 1):
if i % 2 == 0:
print(i, 'EVEN')
else:
print(i, 'ODD')
|
f147e4f5a81b178412f789dd5cce5215214a70c8 | maheshmnj/Mathematizer | /rationalnumbertofraction.py | 132 | 3.546875 | 4 | #subscribed codehouse
from fractions import Fraction
value=input("Enter decimal number:")
print(Fraction(value).limit_denominator()) |
35c84a784394d5416fed28805849db854bf1ad81 | maydaymiao/python-training | /L1_String.py | 1,349 | 4.34375 | 4 | '''
print
mulitlines打印分段
len
slice [0] [0:b] [:b] [a:]
string methods: lower, count, index, find, replace
字符串连接(+,+' '+, .format, fstring)
dir, help()
'''
print('hello world')
message = 'Hello World'
print(message)
# mulitlines = '''I like Python,
# Python is awesome.
# '''
# print(mulitlines)
# len()
print('message一共有: ', len(message))
print(message[0])
print(message[0:5]) # 左闭右开
print(message[:5])
print(message[6:])
low = message.lower()
print(low)
print('l在message里出现的次数是:', message.count('l'))
# index, find都是查找字符的index;区别:index找不存在的字符时,会直接报错;但是find会返回-1
print(message.index('l'))
print(message.find('l'))
# print(message.index('x'))
print(message.find('x'))
newMessage = message.replace('World', 'python')
print(newMessage)
greeting = 'Hello'
name = 'Michael'
print(greeting + name)
print(greeting + ' ' + name + '. Welcome')
print('{0} {1}. Welcome'.format(greeting, name))
print(f'{greeting} {name}. Welcome') # Python 3.6以后引入的方法
print(help(str))
print(type(3))
print(type(3.14))
print(3/2)
print(3//2) #除法取整
print(3**2)
print(7%2)
num = 1
# Python里没有++和--
num += 1
print(num)
strNum1 = '100'
strNum2 = '200'
print(strNum1 + strNum2)
print(int(strNum1) + int(strNum2))
|
a96d52dc9b267087e0dd79073957067074b28c2d | YowKuan/Computer-Networks---UDP-TCP | /UDPClient.py | 1,099 | 3.84375 | 4 | from socket import *
serverName = 'localhost'
serverPort = 8888
#we are not specifying the port number of the client socket when we create it
clientSocket = socket(AF_INET, SOCK_DGRAM)
#Initial "hello message to server"
message = "Hi, the client want to establish the connection!"
while True:
clientSocket.sendto(message.encode(), (serverName, serverPort))
question = ''
#Continueously receive message from server until client got either "Green Pass!" or "Red Pass!"
while True:
question, server_addr = clientSocket.recvfrom(2048)
question = question.decode()
if question == 'Green Pass!' or question == 'Red Pass!':
break
answer = input(question + '\nResponse:')
if answer == '':
answer = '.'
#Because we're using UDP, so everytime we send a message, we need to specify serverName and serverPort
clientSocket.sendto(answer.encode(), (serverName, serverPort))
#print out the result
print(question)
#Close UDP connection and terminate the while loop
clientSocket.close()
break
|
6d6699b6a9accd2b63da4bb301fe5cc10441f33a | alex-dukhno/python-tdd-katas | /path_sum_kata/day_11.py | 2,228 | 3.84375 | 4 | import unittest
def path_sum(root, give_sum):
return path_sum_recursive(root, give_sum, [])
def path_sum_recursive(root, given_sum, path):
if root is not None:
path.append(root.val)
if root.is_leaf() and root.val == given_sum:
return [path]
else:
return path_sum_recursive(root.left, given_sum - root.val, list(path)) \
+ path_sum_recursive(root.right, given_sum - root.val, list(path))
else:
return []
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_leaf(self):
return self.left is None and self.right is None
class PathSumTest(unittest.TestCase):
def testEmptyPath_whenEmptyTree(self):
self.assertEqual([], path_sum(None, 10))
def testOnlyRoot_sumEqRootVal(self):
self.assertEqual([[10]], path_sum(TreeNode(10), 10))
def testOnlyRoot_sumNotEqRootVal(self):
self.assertEqual([], path_sum(TreeNode(20), 10))
def testTwoLevel_leftInPath(self):
self.assertEqual([[3, 4]], path_sum(TreeNode(3, TreeNode(4), TreeNode(5)), 7))
def testTwoLevel_bothInPath(self):
self.assertEqual([[1, -1], [1, -1]], path_sum(TreeNode(1, TreeNode(-1), TreeNode(-1)), 0))
def testStopOnLeaves(self):
self.assertEqual([[0, 1, -1]], path_sum(TreeNode(0, TreeNode(1, TreeNode(-1))), 0))
def testBigTree(self):
self.assertEqual(
path_sum(
TreeNode(
5,
TreeNode(
4,
TreeNode(
11,
TreeNode(7),
TreeNode(2)
),
),
TreeNode(
8,
TreeNode(13),
TreeNode(
4,
TreeNode(5),
TreeNode(1)
)
)
),
22
),
[[5, 4, 11, 2], [5, 8, 4, 5]]
)
|
b42e210b3a90cca0b8c777412d4aecfcd41b5254 | sreerajch657/internship | /practise questions/largest length word.py | 372 | 4.5 | 4 | #Python Program to Read a List of Words and Return the Length of the Longest One
str_string=input("enter a string : ")
length=[]
str_string=str_string.split()
length_string=int(len(str_string))
for i in range(0,length_string) :
item=str_string[i]
x=int(len(item))
length.append(x)
length.sort()
print("the higesht word length is : %d " %length[-1])
|
1118c34ee7e321a400e66addd558a293395ad387 | beata0422/Python-Function-Population-Growth | /script.py | 792 | 3.84375 | 4 | city_name = 'Istanbul, Turkey'
pop_1927 = 691000
pop_2017 = 15029231
pop_change = pop_2017 - pop_1927
percentage_gr = pop_change / pop_1927 *100
annual_gr = percentage_gr / 90
print(annual_gr)
def population_growth (year_one, year_two, population_one, population_two):
population_change = population_two - population_one
percentage_gr = population_change / population_one * 100
growth_rate = percentage_gr / (year_two - year_one)
return growth_rate
set_one = population_growth(1927, 2017, pop_1927, pop_2017)
print(set_one)
set_two = population_growth(1950, 2000, 983000, 8831800)
print(set_two)
report = 'The population grew from ' + str(pop_1927) + 'to ' + str(pop_2017) + ', with a total change of ' + str(pop_change) + '. The annual % gr was ' + str(annual_gr)
print(report) |
be5b41a44b679b7c9886b4d34b9622db2bf2df75 | jm2242/interviewPrep | /interviewBit/matrix-median.py | 2,557 | 3.84375 | 4 | import sys
class Solution:
# @param A : list of list of integers
# @return an integer
def findMedian(self, A):
# sub_list_len = len(A[0])
# return ([m[sub_list_len/2] for m in A].sort())[len(A)/2]
l =0
h = sys.maxint
m = None
target = (len(A) * len(A[0]) / 2)
print "target: {0}".format(target)
while (h - l) > 1:
print "h: {0}".format(h)
print "l: {0}".format(l)
# shortened to distinguish from variables in binary search
prevM = m
m = l + (h - l) / 2
# print m
# keep track of the number of numbers less than mid
count = 0
for row in A:
count += self.binary_search(row, m)
print "count for {0} : {1} ".format(m, count)
if count == target:
return m
elif count > target:
h = m - 1
elif count < target:
l = m + 1
if count > target:
return prevM
else:
return m
# slightly modified binary search to return number of elements
# that are smaller than elem
def binary_search(self, nums, elem, length=None):
low = 0
count = 0
if length is None:
length = len(nums)
high = length - 1
else:
high = length - 1
# exit loop when low is either high or greater, depending on if odd or even
# number of elements
while low <= high:
# get the middle
mid = low + (high - low) / 2
# return the count of numbers less than element
if nums[mid] == elem:
return mid
elif nums[mid] > elem:
high = mid - 1
elif nums[mid] < elem:
low = mid + 1
# return whether we are the bottom or top of the list
# tells us whether the number is too small or too large
else:
if nums[mid] < elem:
return mid + 1
else:
#
return mid
if __name__ == "__main__":
sol = Solution()
tests = [ [[1, 3, 5],[2, 6, 9], [3, 6, 9]], [[5],[4],[3],[1],[3],[1],[4],[2],[5],[3],[3] ] ]
print "answer is {0}".format(sol.findMedian(tests[1]))
#print sol.binary_search(A[1], 8)
|
a3061f96184e9a8fa27f3900e8eb095c1357e160 | rrwt/daily-coding-challenge | /gfg/trees/covered_uncovered_node_sum.py | 1,595 | 4.21875 | 4 | """
Given a binary tree, you need to check whether sum of all covered elements
is equal to sum of all uncovered elements or not. In a binary tree, a node
is called Uncovered if it appears either on left boundary or right boundary.
Rest of the nodes are called covered.
"""
from typing import Optional
from binary_tree_node import Node # type: ignore
def get_tree_sum(root) -> int:
if not root:
return 0
return root.data + get_tree_sum(root.left) + get_tree_sum(root.right)
def get_uncovered_sum(root) -> int:
if not root:
return 0
temp = root.left
total = root.data
while temp:
total += temp.data
if temp.left:
temp = temp.left
else:
temp = temp.right
temp = root.right
while temp:
total += temp.data
if temp.right:
temp = temp.right
else:
temp = temp.left
return total
def check_sum(root: Optional[Node]) -> bool:
if root is None or (root.left is None and root.right is None):
return True
temp = root
tree_sum = get_tree_sum(temp)
if tree_sum & 1:
return False
temp = root
uncovered_sum = get_uncovered_sum(temp)
return uncovered_sum == tree_sum / 2
if __name__ == "__main__":
root = Node(8)
root.left = Node(3)
root.left.left = Node(1)
root.left.right = Node(6)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
root.right = Node(10)
root.right.right = Node(14)
root.right.right.left = Node(13)
assert check_sum(root) == False
|
6c484975390a734117e88b8ff2d00c1681f8e1fc | jamiejamiebobamie/pythonPlayground | /pallindromeLL.py | 1,430 | 4.03125 | 4 | """
Test whether a link list in pallindromic.
"""
class Node:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
n = Node(0)
m = Node(1, n)
l = Node(2, m)
k = Node(3, l)
j = Node(2, k)
i = Node(1, j)
h = Node(0, i)
g = Node(5)
f = Node(5, g)
e = Node(3, f)
d = Node(3, e)
c = Node(3, d)
b = Node(1, c)
a = Node(1, b)
L1 = a #not pallindromic
L2 = h #pallindromic
def iterateList(L):
array = []
while L:
array.append(L.data)
L = L.next
return array
def isPallindrome(L):
#trying to not do the brute force method of putting all of the data in an array
#and checking if that array is pallindromic...
#i could also make the singly list a doubly linked list by adding a previous field to each node
#which would make this much much easier...
def length(L):
"""Get the length of the list."""
count = 0
while L:
count+=1
L = L.next
return count
bool = True
count = 0
dummy_head = L
n = length(L)
while bool and L:
while count < n-1:
dummy_head = dummy_head.next
count+=1
else:
bool = dummy_head.data == L.data
print(L,dummy_head, L == dummy_head, L.data, dummy_head.data, n, bool)
count = 0
n -= 2
dummy_head = L.next
L = L.next
isPallindrome(L2)
|
2a513e21a2d6c61d592cbf0b6dfc3f32250fed3e | CrtomirJuren/pygame-projects | /beginning-game-development/Chapter 2/tankgame.py | 918 | 3.671875 | 4 | from tank import Tank
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol") }
alive_tanks = len(tanks)
while alive_tanks > 1:
for tank_name in sorted( tanks.keys() ):
print(tank_name, tanks[tank_name])
first = input("Who fires? ").lower()
second = input("Who at? " ).lower()
try:
first_tank = tanks[first]
second_tank = tanks[second]
except KeyError as name:
print("No such tank!", name)
continue
if not first_tank.alive or not second_tank.alive:
print("One of those tanks is dead!")
continue
print("*" * 30)
first_tank.fire_at(second_tank)
if not second_tank.alive:
alive_tanks -= 1
print("*" * 30)
for tank in tanks.values():
if tank.alive:
print(tank.name, "is the winner!")
break
|
9545fe732a346fe820902d575dd77376ee60c378 | vinaysankar30/Python-Programs | /untitled28.py | 729 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 20:52:47 2019
@author: admin
"""
n = int(input("enter no of rows"))
x = int(input("enter no of coloums"))
a = []
b = []
new = []
for i in range(x):
c = []
s = []
for j in range(n):
e = int(input("enter the number to 1st matrix"))
l = int(input("enter the number to 2nd matrix"))
s.append(l)
c.append(e)
a.append(c)
new.append(s)
for j in range(n):
d = []
for k in range(x):
d.append(0)
b.append(d)
for l in range(len(a)):
for m in range(len(a[l])):
b[l][m]= a[l][m] + new[l][m]
print("sum of two matrix is")
for n in b:
print(n) |
f02111956cf6b268e3250765a366e0c3738511ce | pchhina/interactive-programming | /pong/pong.py | 5,110 | 3.6875 | 4 | import tkinter as tk
import time
import random
root = tk.Tk()
root.title("Pong")
class Pong:
"""Represents the game of pong.
"""
def __init__(self, master):
self.width = 1000
self.height = 800
self.window = tk.Canvas(master, width = self.width, height = self.height)
self.window.grid()
self.paddlewidth = 20
self.paddleheight = 150
self.left_padpos = 0
self.right_padpos = 980
self.left_score = 0
self.right_score = 0
# initial velocity
self.vel_choice = [-1.25, -1.00, -0.75, 0.75, 1.00, 1.25]
self.v = [random.choice(self.vel_choice), random.choice(self.vel_choice)]
# draw gutters
self.window.create_line(20, 0, 20, 800, fill = "#8F8E8F")
self.window.create_line(980, 0, 980, 800, fill = "#8F8E8F")
# draw paddles
self.left_paddle = self.window.create_rectangle(self.left_padpos,
self.left_padpos,
self.left_padpos + self.paddlewidth,
self.left_padpos + self.paddleheight,
fill = "#CBAB27")
self.right_paddle = self.window.create_rectangle(self.right_padpos,
0,
self.right_padpos + self.paddlewidth,
self.paddleheight,
fill = "#209178")
# score labels
self.left_score_label = self.window.create_text(400, 50,
font = ("default", 60), fill = "#8f8e8f",
text = self.left_score)
self.right_score_label = self.window.create_text(600, 50,
font = ("default", 60), fill = "#8f8e8f",
text = self.right_score)
self.window.create_line(500, 20, 500, 80, fill = "#8F8E8F")
# keyboard help labels
self.window.create_text(100, 50, text = "d: move up", fill = "grey")
self.window.create_text(100, 750, text = "f: move down", fill = "grey")
self.window.create_text(900, 50, text = "k: move up", fill = "grey")
self.window.create_text(900, 750, text = "j: move down", fill = "grey")
def spawn_ball(self):
"""spawns a ball at the center of canvas with a random direction
and velocity."""
self.v = [random.choice(self.vel_choice), random.choice(self.vel_choice)]
center = [self.width / 2, self.height / 2]
radius = 50
x0 = center[0] - radius
y0 = center[1] - radius
x1 = center[0] + radius
y1 = center[1] + radius
self.ball = self.window.create_oval(x0, y0, x1, y1, fill = "#D73E44",
outline = "#9D2E3E")
def velocity(self, pos):
"""sets the velocity vector to make the ball bounce off the top and
bottom edge as well as the paddle. Velocity is increased by 10% if the
ball bounces off the paddles. If the ball touches gutter instead of
paddle, scores are updated and the ball is respawned."""
pos_left = self.window.coords(self.left_paddle)
pos_right = self.window.coords(self.right_paddle)
pos_ballcenter = (pos[1] + pos[3]) / 2
if pos[2] > self.width - self.paddlewidth:
if pos_right[1] < pos_ballcenter < pos_right[3]:
self.v[0] *= -1.1
else:
self.window.delete(self.ball)
self.spawn_ball()
self.left_score += 1
if pos[0] < self.paddlewidth:
if pos_left[1] < pos_ballcenter < pos_left[3]:
self.v[0] *= -1.1
else:
self.window.delete(self.ball)
self.spawn_ball()
self.right_score += 1
if pos[3] > self.height or pos[1] < 0:
self.v[1] *= -1
return self.v
def move_ball(self):
"""ball is moved across the canvas every 0.02 seconds.
"""
while True:
pos = self.window.coords(self.ball)
ball_speed = self.velocity(pos)
self.window.move(self.ball, ball_speed[0], ball_speed[1])
self.window.itemconfigure(self.left_score_label, text =
self.left_score)
self.window.itemconfigure(self.right_score_label, text =
self.right_score)
time.sleep(0.02)
root.update()
def move_paddle(self, event):
"""paddle is moved by listening to the keyboard event.
"""
pos_left = self.window.coords(self.left_paddle)
pos_right = self.window.coords(self.right_paddle)
if event.char == "f" and pos_left[3] < self.height:
self.window.move(self.left_paddle, 0, 10)
if event.char == "d" and pos_left[1] > 0:
self.window.move(self.left_paddle, 0, -10)
if event.char == "j" and pos_right[3] < self.height:
self.window.move(self.right_paddle, 0, 10)
if event.char == "k" and pos_right[1] > 0:
self.window.move(self.right_paddle, 0, -10)
root.update()
pong = Pong(root)
root.bind("<Key>", pong.move_paddle)
pong.spawn_ball()
pong.move_ball()
|
c2349bf4d75d17e3c168e1de05dd4ebf57017ed0 | stellahileman/comp110-21f-workspace | /lessons/for_in.py | 215 | 4.21875 | 4 | """An example of for in syntax."""
names: list[str] = ["Stella", "River", "Max", "Claudia"]
i: int = 0
while i < len(names):
name: str = names[i]
print(name)
i += 1
for name in names:
print(name) |
3e7511a47097deda5856235d20113ae794598270 | wtyhome/Python-Learning_Examples | /script24.py | 356 | 3.59375 | 4 | #functions
def f1(inpN):
#2 3 5 8 13 21
n=int(inpN)
if (n==1 or n==2):
return n+1
else:
return f1(n-1)+f1(n-2)
def f2(inpN):
#1 2 3 5 8 13
n=int(inpN)
if (n==1 or n==2):
return n
else:
return f2(n-1)+f2(n-2)
#main
s=0.0
temp=0.0
for i in range(1,21):
temp=(f1(i)/f2(i))
print(temp)
s+=temp
print("Total :" + str(s)) |
228601f54189accac6c71837b9b8e4521978d00a | smohapatra1/scripting | /python/practice/day29/nested_loop_to_find_number_prime3.py | 157 | 3.546875 | 4 | #Prime number with range of values
for i in range(1,200):
for v in range(2, i):
if (i % v ) == 0 :
break
else:
print (i)
|
8c1813f8121ff282115bb88a1e95a42e0dcc9ea8 | altuhov-as/geekbrains-python-start-homework | /lesson_4/task_7.py | 232 | 3.921875 | 4 | def fact(number: int):
temp_result = 1
if number == 0:
yield temp_result
for i in range(1, number + 1):
temp_result *= i
yield temp_result
my_number = 5
for n in fact(my_number):
print(n)
|
94488040b03c9289533284c4c1a8c9b8a2646a23 | MrN1ce9uy/Python | /my_first_program.py | 1,025 | 4.25 | 4 | #This is a simple program that utilizes variables, functions, & a loop.
#Created by MrN1ce9uy
#Define payroll function
def payroll():
#Payroll calculations
hours = float(input("Enter number of hours worked: "))
rate = float(input("Enter hourly rate: "))
amount = hours * rate
#Print values
print ("Hours worked:", hours)
print ("Rate:", rate)
print ("Pay amount:", amount)
#Define mileage function
def mileage():
#MPG calculations
miles = float(input("Enter number of miles traveled: "))
gas = float(input("Enter gallons of gas consumed: "))
mpg = miles / gas
#Print values
print ("Miles:", miles)
print ("Gallons:", gas)
print ("MPG:", mpg)
#Define variable
menuSelection = 0
#Decision loop
while menuSelection != 3:
#Display options to the user and record their input
print("Press 1 for Payroll Calculation")
print("Press 2 for Mileage Calculation")
print("Press 3 to Exit")
menuSelection = int(input())
#if-else statement
if menuSelection == 1:
payroll()
elif menuSelection == 2:
mileage()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.