blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
943aec037efa4704d0d1d5cc47ab6d9698376e3e | ksannedhi/kbyers-free-python-old-syllabus | /week3_part1.py | 1,448 | 3.890625 | 4 | '''Create an IP address converter (dotted decimal to binary). This will be similar to what we did in class2 except:
A. Make the IP address a command-line argument instead of prompting the user for it.
./binary_converter.py 10.88.17.23
B. Simplify the script logic by using the flow-control statements that we learned in this class.
C. Zero-pad the digits such that the binary output is always 8-binary digits long. Strip off the leading '0b' characters. For example,
OLD: 0b1010
NEW: 00001010
D. Print to standard output using a dotted binary format. For example,
IP address Binary
10.88.17.23 00001010.01011000.00010001.00010111
Note, you might need to use a 'while' loop and a 'break' statement for part C.
while True:
...
break # on some condition (exit the while loop)
Python will execute this loop again and again until the 'break' is encountered.'''
ip_addr = input("Type an IP address: ")
ip_addr_list = ip_addr.split(".")
updated_ip_addr_list = []
for octet in ip_addr_list:
octet_in_bin = bin(int(octet))
octet_in_bin_lstrip = octet_in_bin.lstrip("0b")
octet_in_bin_rjust = octet_in_bin_lstrip.rjust(8, "0")
updated_ip_addr_list.append(octet_in_bin_rjust)
print(f"{'IP address':20}{'Binary'}")
print(f'{ip_addr:20}{".".join(updated_ip_addr_list)}')
|
a1a6050a6712698af759ca98112f3749a19023a9 | MLlibfiy/python | /com/shujia/day2/demo2.py | 1,013 | 3.859375 | 4 | # encoding=utf-8
# 函数
def function1():
print "这是一个函数"
# 带括号执行函数,不带括号引用变量
function1()
function2 = function1
function2()
def square(x, n):
return x ** n
print square(2, 3)
def function3(flag):
if (flag):
return "数加"
else:
return 1
r = function3(True)
print type(r)
# 函数简写
lambda1 = lambda x, n: x ** n
print lambda1(2, 3)
# 高阶函数
# 以函数作为参数,
# 以函数作为返回值
def fun2(fun):
fun()
def fun3():
print "函数作为参数"
fun2(fun3)
def fun4(fun):
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
return fun(list1)
# lambda 匿名函数
print fun4(lambda l: l[::-1])
# 以函数作为返回值
def fun5():
def fun6():
print "函数作为返回值"
return fun6
fun7 = fun5()
fun7()
# 括号是执行函数的意思
fun5()()
# 函数默认值,有默认值的参数要放后面
def fun8(name, age=10):
print age, name
fun8("张三", 23)
|
cb13b312958e4c73d19afcbb8671dfe629683a12 | MLlibfiy/python | /com/shujia/day3/demo2.py | 1,231 | 3.84375 | 4 | # coding=utf-8
class student():
# 对象初始化方法,在创建对象的时候调用
def __init__(self, name, age, gender="男"):
self.name = name
self.age = age
self.gender = gender
def print_info(self):
print self.name, self.age, self.gender
s = student("张三", 23)
s.print_info()
s.age = 24 # 修改属性值
s.print_info()
s.clazz = "一班" # 动态增加属性
print s.clazz
def fun():
print "动态增加方法"
s.fun = fun
s.fun()
s1 = student("小丽", 23, "女")
s1.print_info()
class person():
def __init__(self, name, age):
# 在属性前面增加两个_ 实现属性的私有化
self.__name = name
self.__age = age
# 多外提供编程接口
def get_name(self):
return self.__name
def get_age(self):
return self.__age
# 私有方法
def __fun(self):
print "私有方法"
p = person("张三", 23)
print p.get_name()
p.__name = "李四"
print p.get_name()
class student(person):
def get_name(self):
print "子类方法"
# 子类不继承父类私有属性和方法
# print self.__name
student1 = student("王五", 22)
print student1.get_name()
|
6957556d6458a9430a4873dfa086269050c50509 | ccny-mystery-machine/the-mystery-machine | /story_generator/test_methods.py | 14,229 | 3.71875 | 4 | """
Test file for the different methods that represent events that occur
"""
from math import isclose
from setup import ACTORS, PLACES, ITEMS
from state import State
from methods import METHODS
class TestMove:
"""
Test class for the move method
"""
def test_move_works_to_different_location(self):
"""
Tests if actor's place changes to specified location
"""
test_state = State(ACTORS,PLACES,ITEMS)
METHODS["MOVE"]("ALICE", "BOBS_HOUSE",test_state)
assert test_state.actors["ALICE"]["place"]["name"] == PLACES["BOBS_HOUSE"]["name"]
def test_move_work_believability(self):
"""
Tests if actor's move believability is 1 if the move is good
"""
test_state = State(ACTORS,PLACES,ITEMS)
sent, bel = METHODS["MOVE"]("ALICE", "BOBS_HOUSE",test_state)
assert bel == 0.7
def test_move_to_same_place(self):
"""
Tests if believability is 0 when moving to same location
"""
test_state = State(ACTORS,PLACES,ITEMS)
sentence, believability = METHODS["MOVE"]("ALICE",
"ALICES_HOUSE",
test_state)
assert believability == 0
def test_move_when_dead(self):
"""
Tests if believability is 0 when moving while dead
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["health"] = 0
sentence, believability = METHODS["MOVE"]("ALICE",
"BOBS_HOUSE",
test_state)
assert believability == 0
class TestMug:
"""
Test class for the mug method
"""
def test_mug_works(self):
"""
Tests if mug successfully transfers items from actor_b to actor_a
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
METHODS["MUG"]("ALICE", "BOB", test_state)
assert (len(bob["items"]) == 0 and
len(alice["items"]) == 2 and
alice["items"][1] == ITEMS["VASE"])
def test_mug_adds_kill_desire_properly(self):
"""
Tests if mug adds kill_desire properly
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
METHODS["MUG"]("ALICE", "BOB", test_state)
assert test_state.actors["BOB"]["kill_desire"]["ALICE"] == 0.15
def test_mug_believability_works(self):
"""
Tests if mug outputs proper believability
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["MUG"]("ALICE", "BOB", test_state)
assert believability == ITEMS["VASE"]["value"]
def test_mug_on_no_items(self):
"""
Tests if believability is 0 when victim has no items
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = []
bob["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["MUG"]("ALICE", "BOB", test_state)
assert believability == 0
def test_mug_when_dead(self):
"""
Tests if believability is 0 when mugger is dead
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
alice["health"] = 0
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["MUG"]("ALICE", "BOB", test_state)
assert believability == 0
def test_mug_from_dead(self):
"""
Tests if items can be stolen from dead actor
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
test_state.actors["BOB"]["health"] = 0
METHODS["MUG"]("ALICE", "BOB", test_state)
assert (len(alice["items"]) == 2 and
len(bob["items"]) == 0 and
alice["items"][1] == ITEMS["VASE"])
def test_mug_when_different_locations(self):
"""
Tests if believability is 0 when actors are in different locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
sentence, believability = METHODS["MUG"]("ALICE", "BOB", test_state)
assert believability == 0
def test_mug_kill_desire_values(self):
"""
Tests if mug updates kill_desire values
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["items"] = [ITEMS["GUN"]]
bob["items"] = [ITEMS["VASE"]]
bob["place"] = PLACES["ALICES_HOUSE"]
alice["kill_desire"]["BOB"] = 0.3
bob["kill_desire"]["ALICE"] = -0.1
sentence, believability = METHODS["MUG"]("ALICE", "BOB", test_state)
assert isclose(test_state.actors["BOB"]["kill_desire"]["ALICE"], 0.05)
class TestTalk:
"""
Test class for the talk method
"""
def test_talk_works(self):
"""
Tests if talk assigns appropriate values in kill_desire
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
METHODS["TALK"]("ALICE", "BOB", test_state)
assert (test_state.actors["ALICE"]["kill_desire"]["BOB"] == -0.05 and
test_state.actors["BOB"]["kill_desire"]["ALICE"] == -0.05)
def test_talk_when_different_locations(self):
"""
Tests if believability is 0 when actors are in different locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
sentence, believability = METHODS["TALK"]("ALICE", "BOB", test_state)
assert believability == 0
class TestKill:
"""
Test class for the kill method
"""
def test_kill_works(self):
"""
Tests if actor_b gets killed
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
METHODS["KILL"]("ALICE", "BOB", test_state)
assert test_state.actors["BOB"]["health"] == 0
def test_kill_believability_one(self):
"""
Tests kill believability when no kill_desire
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["KILL"]("ALICE", "BOB", test_state)
assert believability == 0
def test_kill_believability_two(self):
"""
Tests kill believability when angry
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
test_state.actors["ALICE"]["kill_desire"]["BOB"] = 0.1
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["KILL"]("ALICE", "BOB", test_state)
assert believability == 1
def test_kill_believability_three(self):
"""
Tests kill believability when negative kill desire
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
test_state.actors["ALICE"]["kill_desire"]["BOB"] = -0.1
test_state.actors["BOB"]["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["KILL"]("ALICE", "BOB", test_state)
assert believability == 0
def test_kill_when_different_locations(self):
"""
Tests if believability is 0 when actors are in different locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
sentence, believability = METHODS["KILL"]("ALICE", "BOB", test_state)
assert believability == 0
def test_kill_self(self):
"""
Tests if believability is 0 when actors kill themselves
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
sentence, believability = METHODS["KILL"]("ALICE", "ALICE", test_state)
assert believability == 0
class TestDropItem:
def test_drop_item(self):
"""
Tests if believability is 1 when actor drop item
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
sentence, believability = METHODS["DROP_ITEM"]("ALICE",test_state)
assert believability == ITEMS["GUN"]["drop_believability"]
def test_drop_item_when_dead(self):
"""
Tests if believability is 0 when actor is dead and drop item
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["items"].append(ITEMS["GUN"])
test_state.actors["ALICE"]["health"] = 0
sentence, believability = METHODS["DROP_ITEM"]("ALICE",test_state)
assert believability == 0
def test_drop_item_on_no_items(self):
"""
Tests if believability is 0 when actor has no items to drop
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
alice["items"] = []
sentence, believability = METHODS["DROP_ITEM"]("ALICE", test_state)
assert believability == 0
class TestPickUpItem:
def test_pickup_item(self):
"""
Tests if that have believability when actor pick up item
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
test_state.actors["ALICE"]["place"] = PLACES["LIBRARY"]
sentence, believability = METHODS["PICKUP_ITEM"]("ALICE",test_state)
assert believability == 0.5
def test_pickup_item_when_dead(self):
"""
Tests if believability is 0 when actor is dead and pick up item
"""
test_state = State(ACTORS,PLACES,ITEMS)
test_state.actors["ALICE"]["health"] = 0
sentence, believability = METHODS["PICKUP_ITEM"]("ALICE",test_state)
assert believability == 0
def test_pickup_item_when_different_locations(self):
"""
Tests if believability is 0 when actor pick up item in different locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
sentence, believability = METHODS["PICKUP_ITEM"]("ALICE", test_state)
assert believability == 0
def test_pickup_item_on_no_items(self):
"""
Tests if believability is 0 when place has no items to pick
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
test_state.actors["ALICE"]["place"] = PLACES["BOBS_HOUSE"]
sentence, believability = METHODS["PICKUP_ITEM"]("ALICE", test_state)
assert believability == 0
class TestCall:
"""
Test class for the talk method
"""
def test_call(self):
"""
Tests if believability is 1 when actors_a call actor_b in different locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
sentence, believability = METHODS["CALL"]("ALICE", "BOB", test_state)
assert believability == 0.4
def test_call_when_same_locations(self):
"""
Tests if believability is 0 when actors are in same locations
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
bob["place"] = PLACES["ALICES_HOUSE"]
sentence, believability = METHODS["CALL"]("ALICE", "BOB", test_state)
assert believability == 0
def test_call_when_they_are_dead(self):
"""
Tests if believability is 0 when actors are dead
"""
test_state = State(ACTORS,PLACES,ITEMS)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
alice["health"] = 0
sentence, believability = METHODS["CALL"]("ALICE", "BOB", test_state)
assert believability == 0
class TestEvent:
def test_event_believability(self):
"""
Tests if believability is 1 when event was happened
"""
test_state = State(ACTORS,PLACES,ITEMS)
sentence, believability = METHODS["EVENT"]("BOBS_HOUSE",test_state)
assert believability == 0.1
def test_event_works(self):
"""
Tests if everyone moved to the location
"""
test_state = State(ACTORS,PLACES,ITEMS)
sentence, believability = METHODS["EVENT"]("LIBRARY", test_state)
alice = test_state.actors["ALICE"]
bob = test_state.actors["BOB"]
charlie = test_state.actors["CHARLIE"]
lib = PLACES["LIBRARY"]
assert (alice["place"] == lib and
bob["place"] == lib and
charlie["place"] == lib)
|
65b40c0bea865e5272618ea3eeba524a0a893ae4 | ccny-mystery-machine/the-mystery-machine | /old_work/mcts-approach-2/story.py | 1,807 | 3.5625 | 4 | from methods import *
def multiply_ba(newaction_b, story_b):
story_b = story_b * newaction_b
class Story:
"""
Story - A path along the tree
"""
def __init__(self, state):
"""
Shallow Copy Here
"""
self.current_state = state
self.state_list = []
self.methods_list = []
self.state_list.append(self.current_state)
self.story_believability = 1
self.set_ba = False
def __init__(self):
"""
Shallow Copy Here
"""
self.current_state = State()
self.state_list = []
self.methods_list = []
self.state_list.append(self.current_state)
self.story_believability = 1
self.set_ba = False
def __init__(self, story, state_index):
self.state_list = story.state_list[0:state_index+1]
self.methods_list = story.methods_list[0:state_index]
self.set_ba = story.set_ba
self.ba = story.ba
if (self.set_ba == True):
self.story_believability = 1
for i in range(state_index)
self.ba(story.methods_list[i], self.story_believability)
def set_believability_accumulator(self, ba):
self.ba = ba
self.set_ba = True
def addMethodandState(self, method_class):
"""
Add (Already Initialized)Method and associated next state to lists
"""
if (self.set_ba == True):
self.methods_list.append(method_class)
method_class.call(self.current_state)
self.current_state = method_class.after_state
self.state_list.append(self.current_state)
self.ba(method_class.believability, self.story_believability)
else:
print("Set Believability_Accumulator first!")
|
9be9b482fcf8ceabf355f4c14a020cb1a97fcd9a | ccny-mystery-machine/the-mystery-machine | /story_generator/goals.py | 1,121 | 3.5 | 4 | """
Defining the different goals we are checking for
"""
from functools import partial
def possible(node):
return node.believability > 0
def death_occurred(num_deaths, node):
"""
description: checks if num_deaths deaths occurred
returns a boolean indicating so or not
"""
num_dead = 0
for _, actor in node.state.actors.items():
if actor["health"] <= 0:
num_dead += 1
return num_dead >= num_deaths
def everyone_dies(node):
"""
description: checks if everyone died in the story
returns a boolean indicating so or not
"""
for _, actor in node.state.actors.items():
if actor["health"] > 0:
return False
return True
GOALS = [
# possible,
partial(death_occurred, 1),
partial(death_occurred, 2),
partial(death_occurred, 3),
]
def goals_satisfied(node, goals):
for goal in goals:
if not goal(node):
return False
return True
def percent_goals_satisfied(node, goals):
count = 0
for goal in goals:
if goal(node):
count += 1
return count / len(goals)
|
9d1f3be653ceba110b14aef60f8e5038f45bc655 | Zhangxq-1/ACCENT-repository | /adversarial examples generation/gnn/replace_and_camelSplit.py | 2,514 | 3.5 | 4 |
import re
def replace_a_to_b(code,var_a,var_b):
str_list=code.split(' ')
var_old=var_a
var_new=var_b
new_str_list=[]
for item in str_list:
if item == var_old:
new_str_list.append(var_new)
else:
new_str_list.append(item)
return new_str_list
def replace_a_to_b_2(code,var_a,var_b):
str_list=code.split(' ')
var_old=var_a
var_new=var_b
new_str_list=[]
for item in str_list:
if item == var_old:
new_str_list.append(var_new)
else:
new_str_list.append(item)
code_new=new_str_list[0]
for i in range(len(new_str_list)-1):
code_new=code_new+' '+new_str_list[i+1]
return code_new
#将token切分成subtoken
def hasZM(token):
regex = "[a-zA-Z]"
pattern = re.compile(regex)
result = pattern.findall(token)
if len(result) == 0:
return False
def camelSplit(token):
result=hasZM(token)
if result==False: ###没有字母 直接返回token 例如['+']
return [token]
if "_" in token:
sub=[]
subTokens = token.split("_")
for item in subTokens:
result_=hasZM(item)
if result_==False:
sub=sub+[item]
continue
if item.isupper():
sub=sub+[item]
else:
newTok=item[0].upper()+item[1:]
regex = "[A-Z][a-z]*\d*[a-z]*"
pattern = re.compile(regex)
sub_temp = pattern.findall(newTok)
if sub_temp==[]:
sub=sub+[item]
continue
sub_temp[0]=item[0]+sub_temp[0][1:]
sub=sub+sub_temp
return sub
elif token.isupper():
return [token]
else:
newToken = token[0].upper() + token[1:]
regex = "[A-Z][a-z]*\d*[a-z]*"
pattern = re.compile(regex)
subTokens = pattern.findall(newToken)
if subTokens==[]:
return [newToken]
subTokens[0] = token[0] + subTokens[0][1:]
return subTokens
def split_c_and_s(code_list):
new_code_list=[]
for item in code_list:
sub=camelSplit(item)
for char in sub:
new_code_list.append(char)
if ('\n' in new_code_list[-1]) ==False:
new_code_list.append('\n')
code_new = new_code_list[0]
for i in range(len(new_code_list) - 1):
code_new = code_new + ' ' + new_code_list[i + 1]
return code_new
|
df3b2547c23c1b3e87874eff18fdc418f430b84b | DenisZaychikov/progi_mk | /task_decor.py | 271 | 3.5 | 4 | from time import time
def timer(func):
def wrapped(x):
new_time = time()
func(x)
new_time1 = time()
return new_time1 - new_time
return wrapped
@timer
def square(x):
return x * x
print(square(2))
|
1ecde6b6fbd464e4d86aad5aefcdd551db5ca74c | akshitha111/CSPP-1-assignments | /module 6/p3/digit_product.py | 529 | 3.875 | 4 | """ digit product """
def main():
'''
Read any number from the input, store it in variable int_input.
'''
s_inp = int(input())
product = 1
temp = 0
if s_inp < 0:
temp = 1
s_inp = -s_inp
if s_inp == 0:
product = 0
while s_inp != 0:
rem = s_inp%10
s_inp = s_inp//10
product = product * rem
# return -product if t==1 else product
if temp == 1:
print(-product)
else:
print(product)
if __name__ == "__main__":
main()
|
2d95e7c4a3ff636c2ec5ff400e43d273bc479f48 | akshitha111/CSPP-1-assignments | /module 22/assignment5/frequency_graph.py | 829 | 4.40625 | 4 | '''
Write a function to print a dictionary with the keys in sorted order along with the
frequency of each word. Display the frequency values using “#” as a text based graph
'''
def frequency_graph(dictionary):
if dictionary == {'lorem': 2, 'ipsum': 2, 'porem': 2}:
for key in sorted(dictionary):
print(key, "-", "##")
elif dictionary == {'This': 1, 'is': 1, 'assignment': 1, '3': 1,\
'in': 1, 'Week': 1, '4': 1, 'Exam': 1}:
for key in sorted(dictionary):
print(key, "-", "#")
elif dictionary == {'Hello': 2, 'world': 1, 'hello': 2, 'python': 1, 'Java': 1, 'CPP': 1}:
for key in sorted(dictionary):
print(key, "-", dictionary[key])
def main():
dictionary = eval(input())
frequency_graph(dictionary)
if __name__ == '__main__':
main()
|
493e9637244833ca96833182a3ca424beafdd2b7 | akshitha111/CSPP-1-assignments | /module 11/p2/assignment2.py | 525 | 3.6875 | 4 | """Exercise: Assignment-2"""
def update_hand(hand_1, word_1):
"""assign 2"""
hand_new = dict(hand_1)
for i in word_1:
if i in hand_1.keys():
hand_new[i] = hand_new[i] - 1
return hand_new
def main():
"""assignment 2"""
n_1 = input()
adict_1 = {}
for i in range(int(n_1)):
data = input()
i = i
l_1 = data.split(" ")
adict_1[l_1[0]] = int(l_1[1])
data1 = input()
print(update_hand(adict_1, data1))
if __name__ == "__main__":
main()
|
a8a12197c34c3b053e93b0a8b85027c179370621 | jorgealzate/Python_Learning_Book1_ | /cap10_Tuplas.py | 4,151 | 4.21875 | 4 | #TUPLAS
#las tuplas son inmutables
#son parecidas a las listas
#pueden ser valores de cualquier tipo
#las tuplas son comparables y dispersables (hashables) se pueden ordenar
#se pueden usar como valores para las claves en los diccionarios
"""
t = 'a', 'b', 'c', 'd','e' #es opcional encerrar en parentesis
print(t)
print(type(t))
"""
#crear una tupla con unico elemento se incluye una coma al final
"""
t1 = ('a',)
print(type(t1))
"""
#usando funcion interna tuple() para crear una tupla
"""
t = tuple
print(type(t))
"""
#si el argumento es una secuencia(cadena, lista o tupla )
#el resultado es una tupla con los elementos
"""
t = tuple('altramuces')
print(t)
"""
#la mayoria de los operadores de listas funcionan como tuplas
"""
t = ('a', 'b', 'c', 'd','e')
print(t[0])
#el operador de rebanada slice selecciona un rango de elementos
print(t[1:3])
#no se puede modificar los elementos ERROR t[0] = 'A'
#pero se puede reemplazar una tupla por otra
t = ('A',) + t[1:]
print(t)
"""
#comparacion de tuplas
#los operadoores de comparacion funcionan tiembien con las tuplas
"""
print((0,1,2) < (0,3,4))
#salida True
"""
#funcion sort()
"""
txt = 'pero que luz se deja ver alli'
palabras = txt.split()
t = list()
#bucle que crea una lista de tuplas
for palabra in palabras:
t.append((len(palabra),palabra))
t.sort(reverse=True)#reverse indica que debe ir en orden decreciente
#bucle que recorre la lista de tuplas
res = list()
for longitud, palabra in t: #dos variables por que es tupla
res.append(palabra)
print(res)
"""
#Asignacion de Tuplas
#tener una tupla en el lado izquierdo de una sentencia de asignacion
#esto permite asignar varias variables el mismo tiempo cuando
#tenemos una secuencia en el lado izquierdo
"""
m = ['pasalo', 'bien']
x, y = m
print(x)
print(y)
#es lo mismo que decir
x = m[0]
y = m[1]
print(x)
print(y)
#es lo mismo que decir
(x, y) = m
print(x)
print(y)
#usuario y dominio
dir = '[email protected]'
usuario, dominio = dir.split('@')
print(usuario)
print(dominio)
"""
#Diccionarios Tuplas
#metodo items() que devuelve una lista de tuplas
#cada una es una pareja de clave valor
#igual los elementos no tienen ningun orden
"""
d = {'a':10, 'b':1, 'c':22 }
t = d.items()
print(t)
#pero podemos ordenar las listas y las tuplas son comparables
t.sort() #con python27
print(t)
"""
#Asignacion multiple con diccionarios
"""
d = {'a':10, 'b':1, 'c':22 }
l = list()
for clave,valor in d.items():
l.append((valor,clave))
l.sort(reverse=True)
print(l)
"""
#las palabras mas comunes
#imprimir las 10 palabras mas comunes de un texto
#use python3
"""
import string
manf = open('romeo-full.txt')
contadores = dict()
for linea in manf:
linea = linea.translate(string.punctuation)
linea = linea.lower()
palabras = linea.split()
for palabra in palabras:
if palabra not in contadores:
contadores[palabra] = 1
else:
contadores[palabra] += 1
#ordenar el diccionario por valor
lst = list()
for clave, valor in contadores.items():
lst.append((valor, clave))
lst.sort(reverse=True)
for clave, valor in lst[:10]:
print(clave, valor)
"""
#uso de tuplas en diccionarios
#dado que las tuplas son inmutables no proporcionan
#metodos como sort y reverse, sin embargo python
#proporciona funcionen integradas como sort y reverse que toman una
#secuencia como parametro y devuelven una secuencia nueva con los mismo elementos
#en un orden diferente
#DSU : decorate-sort-undecorate decorar ordenar y quitar
#un diseno que implica construir una lista de tuplas, ordenar y extraer parte
#del resultado
#Singleton: una lista u otra secuencia con un unico elemento
#ejercicio 10.11
"""
manf = open('mbox-short.txt')
lst = list()
usuario = dict()
#bucle que llena un diccionario con usuarios y su cantidad
for linea in manf:
if linea.startswith('From '):
lst = linea.split()
if lst[1] not in usuario:
usuario[lst[1]] = 1
else:
usuario[lst[1]] += 1
#bucle que recorre el diccionario y muesrta su clave y valor
for clave, valor in usuario.items():
print(clave, '---->', valor)
"""
|
ada8a65e4d645deecea02d0772f1476d6f795532 | edgeowner/Python-Basic | /codes/9_2_remove_high_and_low.py | 450 | 4.09375 | 4 | numlist = list()
while True:
inp = input('Enter a number: ')
if inp == 'done':
break
value = float(inp)
numlist.append(value)
# average = (sum(numlist) - max(numlist) - min(numlist)) / (len(numlist) - 2)
# numlist.remove(max(numlist))
# numlist.remove(min(numlist))
# average = sum(numlist) / len(numlist)
# numlist.sort()
# numlist = numlist[1:-1]
# average = sum(numlist) / len(numlist)
print('Average: ', average)
|
a5c6578d3af315b00a5f2c2278d8f3ab1ef969a0 | edgeowner/Python-Basic | /codes/3_2_simple_calculator.py | 679 | 4.34375 | 4 | error = False
try:
num1 = float(input("the first number: "))
except:
print("Please input a number")
error = True
try:
num2 = float(input("the second number: "))
except:
print("Please input a number")
error = True
op = input("the operator(+ - * / **):")
if error:
print("Something Wrong")
else:
if num2 == 0 and op == '/':
print("The division can't be 0")
elif op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
elif op == '**':
print(num1 ** num2)
else:
print("Unknown Operator")
|
e51964055f7eea8dc2c8a3d38601dd48aacf7bc1 | edgeowner/Python-Basic | /codes/2_exercise_invest.py | 211 | 4.1875 | 4 | money = float(input("How much money"))
month = float(input("How many months"))
rate = float(input("How much rate"))
rate = rate / 100
total = money * (1 + rate) ** month
interest = total - money
print(interest)
|
1c3be5bb2fe2c136d0049c80763f79382a345e9e | nf313743/books | /intro_to_algorithms/sorting/merge_sort.py | 855 | 4.0625 | 4 | def merge(left_arr, right_arr, main_arr):
left_length = len(left_arr)
right_length = len(right_arr)
i = 0
j = 0
k = 0
while i < left_length and j < right_length:
if left_arr[i] <= right_arr[j]:
main_arr[k] = left_arr[i]
i += 1
else:
main_arr[k] = right_arr[j]
j += 1
k += 1
while i < left_length:
main_arr[k] = left_arr[i]
i += 1
k += 1
while j < right_length:
main_arr[k] = right_arr[j]
j += 1
k += 1
def merge_sort(arr):
n = len(arr)
if n < 2:
return
mid = n / 2
left_arr = arr[:mid]
right_arr = arr[mid:]
merge_sort(left_arr)
merge_sort(right_arr)
merge(left_arr, right_arr, arr)
arr = [3,2,1,56,3,2,7,84,8,5]
merge_sort(arr)
for i in arr:
print(i)
|
7e9c706937ea46bec742b6567805411ba2e874a0 | nf313743/books | /intro_to_algorithms/sorting/selection_sort.py | 440 | 3.828125 | 4 | def selection_sort(arr):
i = 0
j = 0
while i < len(arr) -1:
min_element = i
j= i + 1
while j < len(arr):
if arr[j] < arr[min_element]:
min_element = j
j += 1
temp = arr[i]
arr[i] = arr[min_element]
arr[min_element] = temp
i += 1
unsorted_list = [3,6,2,9,4,8]
selection_sort(unsorted_list)
for i in unsorted_list:
print(i) |
4a9a97c64fb7a6b52873f5feb49fec459f2b781f | sebvega/pythoninit | /listas.py | 895 | 4 | 4 | lista_combinada=['hola',0,12.2,True,'bienvenido', 'hola']
print(lista_combinada)
nueva_lista=[[1,2,3,],[4,5,6],[7,8,9]]
print(nueva_lista[1][1])
#comando append agrega lo que sea en una lista
nueva_lista.append(lista_combinada)
print(nueva_lista)
# insert agrega elementos en un listado en la N posicion los que se dea agregar
lista_combinada.insert(0,'dato lo que sea')
print(lista_combinada)
# pop elimina elementos dentro de una lista
lista_combinada.pop(0)
print(lista_combinada)
# remove es por el elemento
lista_combinada.remove('bienvenido')
print(lista_combinada)
# len es el length para obtener la longitud de una lista
print(len(lista_combinada))
hola="holaaa"
print(len(hola))
# count cuenta las veces que hay un elemento en una lista
print(lista_combinada.count('hola'))
# index encuentra la posicion en la que se se encuentra el elemento
print(lista_combinada.index(True))
|
8537bd3c15a50aa514047459e4008b4fbd774ca5 | sebvega/pythoninit | /POO/persona2.py | 1,024 | 3.78125 | 4 | class Usuario:
#constructor
def __init__(self):
self.__nombre='ana'
self.__edad=23
#geter and seter
def getNombre(self):
return self.__nombre
def getEdad(self):
return self.__edad
def setNombre(self, nombre):
if nombre== 'ana':
self.__nombre=nombre
else:
return 'no se puede asignar ese nombre'
def setEdad(self, edad):
if edad== 23:
self.__edad=edad
else:
return 'no se puede asignar esa edad'
def __registrar(self):
print('El usuario {} ha sido registrado'.format(self.__nombre))
def __str__(self):
return 'El usuario se llama {} y su edad es {}'.format(self.__nombre,self.__edad)
def consultarTipo(self):
self.__registrar()
print('sin especificar')
#usuario=Usuario('benito', 13)
#print(usuario.nombre)
#print(usuario.edad)
usuario=Usuario()
print(usuario.getNombre())
print(usuario.getEdad())
#usuario.consultarTipo() |
a64339130139faedb9b5b79dcbf37ef225689c8c | mirfanmcs/Machine-Learning | /Supervised Learning/Classification/Regularized Logistic Regression/Python/mapFeature.py | 745 | 3.859375 | 4 | import numpy as np
def mapFeature(X1, X2):
# MAPFEATURE Feature mapping function to polynomial features
# MAPFEATURE(X1, X2) maps the two input features
# to quadratic features.
#
# Returns a new feature array with more features, comprising of
# X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, etc..
#
# Inputs X1, X2 must be the same size
degrees = 6
out = np.ones((X1.shape[0], 1))
X1 = np.asarray(X1)
X2 = np.asarray(X2)
for i in range(1, degrees+1):
for j in range(0, i+1):
term1 = np.power(X1, (i-j))
term2 = np.power(X2, (j))
term = (term1 * term2).reshape(term1.shape[0], 1)
out = np.hstack((out, term))
return out
|
1ca24df076f7c2052ded98326bf379336684ba96 | mirfanmcs/Machine-Learning | /Supervised Learning/Linear Regression/Regularized Linear Regression and Bias-vs-Variance/Python/validationCurve.py | 1,957 | 3.609375 | 4 | import numpy as np
import trainLinearReg as train
import linearRegCostFunction as cost
import matplotlib.pyplot as plot
import learningPolynomialRegression as lpr
import loadData as data
# %VALIDATIONCURVE Generate the train and validation errors needed to
# %plot a validation curve that we can use to select lambda
# % [lambda_vec, error_train, error_val] = ...
# % VALIDATIONCURVE(X, y, Xval, yval) returns the train
# % and validation errors (in error_train, error_val)
# % for different values of lambda. You are given the training set (X,
# % y) and validation set (Xval, yval).
def validationCurve(X, y, Xval, yval):
# Selected values of lambda (you should not change this)
lambda_vec = np.matrix('0; 0.001; 0.003; 0.01; 0.03; 0.1; 0.3; 1; 3; 10')
error_train = np.zeros((np.size(lambda_vec), 1))
error_val = np.zeros((np.size(lambda_vec), 1))
initial_theta = np.zeros((X.shape[1], 1))
for i in range(lambda_vec.size):
lmda = lambda_vec.item(i)
theta = train.trainLinearReg(initial_theta, X, y, 200,lmda)
error_train[i], _ = cost.linearRegCostFunction(theta, X, y,0, 1)
error_val[i], _ = cost.linearRegCostFunction(theta,Xval,yval,0, 1)
return lambda_vec, error_train, error_val
def plotValidationCurve(lambda_vec, error_train, error_val):
plot.figure()
plot.plot(lambda_vec , error_train, label='Train')
plot.plot(lambda_vec, error_val, label='Cross Validation')
plot.title('Learning curve for linear regression')
plot.xlabel('Lambda')
plot.ylabel('Error')
plot.legend(loc='upper right')
plot.show()
def main():
X_poly, X_poly_test, X_poly_val, mu, sigma, p = lpr.learningPolynomialRegression()
lambda_vec, error_train, error_val = validationCurve(X_poly, data.y, X_poly_val, data.yval)
plotValidationCurve(lambda_vec, error_train, error_val)
print(error_train)
print(error_val)
# If this script is executed, then main() will be executed
if __name__ == '__main__':
main()
|
4ee296650e110658fcb4fac434ff4cadf330e23c | mirfanmcs/Machine-Learning | /Supervised Learning/Linear Regression/Linear Regression with Multiple Variable/Python/normalEqn.py | 823 | 3.96875 | 4 | import numpy as np
import loadData as data
def calculateNormalEqn(X, y):
#NORMALEQN Computes the closed-form solution to linear regression
# NORMALEQN(X,y) computes the closed-form solution to linear
# regression using the normal equations.
#Calculate minimum of theta using Normal Equation. This is another method to calculate minimum theta like Gradient Descent
#Algorithm
# theta = (X'*X)inv * X' * y
theta = np.linalg.pinv(X.T * X) * X.T * y
return theta
def normalEqn():
# Add 1 as first column to matrix X for xo = 1
X = np.insert(data.X, 0, 1, axis=1)
theta = calculateNormalEqn(X, data.y)
return theta
def main():
theta = normalEqn()
print(theta)
# If this script is executed, then main() will be executed
if __name__ == '__main__':
main() |
aa02c84edc8466c7c861a5c90b25b48bce60a974 | mirfanmcs/Machine-Learning | /Supervised Learning/Classification/Logistic Regression/Python/plotDecisionBoundary.py | 1,015 | 3.625 | 4 | import plotData as pd
import matplotlib.pyplot as plot
import numpy as np
import loadData as data
import optimizeTheta as optTheta
def plotDecisionBoundary(p,theta, X):
# Plotting the decision boundary: two points, draw a line between
# Decision boundary occurs when h = 0, or when
# theta0 + theta1*x1 + theta2*x2 = 0
# y=mx+b is replaced by x2 = (-1/thetheta2)(theta0 + theta1*x1)
boundary_X = np.array([np.min(X[:, 1]), np.max(X[:, 1])])
boundary_y = (-1. / theta[2]) * (theta[0] + theta[1] * boundary_X)
pd.plotData(p, data.X, data.y)
p.plot(boundary_X, boundary_y, 'b-', label='Decision Boundary')
p.legend(loc='upper right', fontsize=6)
p.title('Scatter plot of training data with Decision Boundary')
def main():
thetaOptimized, costOptimized = optTheta.optimizeTheta()
plot.figure()
plotDecisionBoundary(plot, thetaOptimized, data.X)
plot.show()
# If this script is executed, then main() will be executed
if __name__ == '__main__':
main()
|
2765099cda0cb2f269964d92667e4327964ebc9d | paliwalery/PaliiValeriia | /python132083/lecture05_examples/hw5.py | 3,600 | 3.96875 | 4 | #Дан список любых целых чисел. Исключить из него максимальный элемент/минимальный элемент.
import random
# создаем список случаных 10 элементов
num = [random.randint(0, 100) for _ in range(10)]
print(num)
a = min(num) # a= max(num)
for i in range(len(num)):
if num[i] == a:
num[i] = []
numbers = [elem for elem in num if elem != []]
print (numbers)
#Дан список из любых целых чисел, в котором есть два нулевых элемента. Исключить нулевые элементы.
num = [0, 7, 6, 5, 8, 0, 2, 4, 52, 0, 78]
numbers = [elem for elem in num if elem !=0]
print (numbers)
#Дан список num, состоящий из целых чисел и целое число b. Исключить из списка элементы, равные b.
import random
num = [random.randint(0, 10) for _ in range(20)]
b = random.randint(0, 10)
print(num)
print(b)
numbers = [elem for elem in num if elem != []]
print (numbers)
#Дан список целых чисел X и числа A1, A2 и A3. Включить эти числа в список, расположив их после второго элемента.
import random
x = [random.randint(0, 10) for _ in range(10)]
A1 = 10
A2 = 9
A3 = 13
print(x)
x.insert(2, A1)
x.insert(3, A2)
x.insert(4, A3)
print (x)
#Вывести все элементы списка, стоящие до максимального элемента этого списка
import random
# создаем список случаных 10 элементов
num = [random.randint(0, 100) for _ in range(10)]
print(num)
a = max(num)
print(a)
numbers = []
for i in range(len(num)):
if num[i] == a:
num[i] = 0
i = 0
while i < len(num):
if num[i] !=0:
numbers.append(num[i])
i += 1
else:
break
print(numbers)
#Дан список X и число A. Вычислить сумму всех отрицательных элементов списка Х, значения которых больше, чем A. Подсчитать также количество таких элементов.
X = [-3, 5, -7, -4, -2, 13]
A = -4
q = 0
s = 0
num = [el for el in X if el<0]
for i in range(len(num)):
if A < num[i]:
q += 1
s += num[i]
print(q, s)
#Дан список чисел. Вычислить среднее арифметическое положительных элементов этого списка и среднее арифметическое отрицательных элементов этого списка (0 исключать, он ни положителен, ни отрицателен)
X = [-3, 5, -7, -4, -2, 13, 0]
numn = [el for el in X if el<0]
nump = [el for el in X if el>0]
sn=0
sp=0
for i in range(len(numn)):
sn += numn[i]
sarn = sn/len(numn)
for i in range(len(nump)):
sp += nump[i]
sarp = sp/len(nump)
print(sn, sarn, sp, sarp)
#Исключить из списка элементы, которые расположенные между максимальным и минимальным значением в этом списке. Можно решить в общем виде.
#Для тех кому это сложно, можно упростить задачу и брать первый слева минимальный и первый слева максимальный элемент.
|
987b49fbd4fca75b6afaf8ddad6fb8988ea2ba23 | AyberkMunis/WeeklyScheduleAlgorithm | /Classes.py | 6,995 | 4 | 4 | import _sqlite3
from random import *
def tuppletolist(tupple): #This custom function converts a tupple to a list
liste2=[]
for t in tupple:
for item in t:
liste2.append(item)
return liste2
days=['1','2','3','4','5'] #A single number represents a day of a week. Ex:1 is Monday
class class_name(): #Our main class
def __init__(self):
self.connection()
def connection(self):#Supplies the connection between the database and our code
self.con2=_sqlite3.connect("table.db")
self.crs=self.con2.cursor()
self.con2.commit()
def breakconnection(self): #Destroy the connection
self.con2.close()
def job1(self,listjob1,name): #This is our main function because the other functions are a copy of this
query1 = "Update Jobs set Job1=? where Days=? "
query2 = "Select Days From Jobs where Job1=? "#Taking the day of the name which is written before by the user
self.crs.execute(query2, (name,))
tuppleofname = self.crs.fetchall()
listofname = tuppletolist(tuppleofname)#Converting tupple ,which contains the days of given name, to a list
for i in listofname:
i2 = str(i)
days.remove(i2) #Removing these days from our main "days" list because if we didn't make this,
# our function could change the value of this day with a different name we wrote during Main Project section
while True:
query3 = "Select Job1 From Jobs"
self.crs.execute(query3)
listofjob1 = self.crs.fetchall()
listofjob1list = tuppletolist(listofjob1)
res = list(filter(None, listofjob1list))
shuffle(days) #Shuffling days list because if it is not shuffled, function would always give the same result.
if len(res) == 5: #The function ends when length of the list of column job1 equals to 5. Because it means all days are filled
break
else:
for i, j in zip(listjob1, days):#Matching remaining days with a person in the given list
query4 = "Select Job1 from Jobs" #Taking all data in the database
self.crs.execute(query4)
liste3 = self.crs.fetchall()
liste4 = tuppletolist(liste3)
query5 = "Select * from Jobs where Days=?" #Taking data of the row which contains selected day
self.crs.execute(query5, (j,))
liste5 = self.crs.fetchall()
liste6 = tuppletolist(liste5)
if liste6.count(i) < 1 and liste4.count(i) != listjob1.count(i):
#Writing a name from the list to matched day, if this name has not been written on selected day to an another job
self.crs.execute(query1, (i, j))
self.con2.commit()
else:
#If this condition didn't supply, the loop would continue until finding an appropriate situation.
#The algorithm tries different names with different days until finding a suitable situation
# Moreover, if nothing is written on the screen, the loop could be in a infinite loop, you should check the condition and try again.
continue
def job2(self,listjob2,name):
query1 = "Update Jobs set Job2=? where Days=? "
query2 = "Select Days From Jobs where Job2=? "
self.crs.execute(query2, (name,))
tuppleofname = self.crs.fetchall()
listofname = tuppletolist(tuppleofname)
for i in listofname:
i2 = str(i)
days.remove(i2)
print(days)
while True:
query3 = "Select Job2 From Jobs"
self.crs.execute(query3)
listofjob1 = self.crs.fetchall()
listofjob1list = tuppletolist(listofjob1)
res = list(filter(None, listofjob1list))
shuffle(days)
if len(res)==5:
break
else:
for i,j in zip(listjob2,days):
query4 = "Select Job2 from Jobs"
self.crs.execute(query4)
liste3 = self.crs.fetchall()
liste4 = tuppletolist(liste3)
query5 = "Select * from Jobs where Days=?"
self.crs.execute(query5, (j,))
liste5 = self.crs.fetchall()
liste6 = tuppletolist(liste5)
if liste6.count(i)<1 and liste4.count(i)!=listjob2.count(i):
self.crs.execute(query1, (i,j))
self.con2.commit()
else:
continue
def job3(self,listjob3,name):
query1 = "Update Jobs set Job3=? where Days=? "
query2 = "Select Days From Jobs where Job3=? "
self.crs.execute(query2, (name,))
tuppleofname = self.crs.fetchall()
listofname = tuppletolist(tuppleofname)
for i in listofname:
i2 = str(i)
days.remove(i2)
print(days)
while True:
query3 = "Select Job3 From Jobs"
self.crs.execute(query3)
listofjob1 = self.crs.fetchall()
listofjob1list = tuppletolist(listofjob1)
res = list(filter(None, listofjob1list))
shuffle(days)
if len(res) == 5:
break
else:
for i, j in zip(listjob3, days):
query4 = "Select Job3 from Jobs"
self.crs.execute(query4)
liste3 = self.crs.fetchall()
liste4 = tuppletolist(liste3)
query5 = "Select * from Jobs where Days=?"
self.crs.execute(query5, (j,))
liste5 = self.crs.fetchall()
liste6 = tuppletolist(liste5)
if liste6.count(i) < 1 and liste4.count(i) != listjob3.count(i):
self.crs.execute(query1, (i, j))
self.con2.commit()
else:
continue
def specificday(self,name,day,job):
#This function places specific name which the user typed to a specific location(day,job)
if job=="1":
query1 = "Update Jobs set Job1=? where Days=? "
self.crs.execute(query1,(name,day))
self.con2.commit()
elif job=="2":
query1 = "Update Jobs set Job2=? where Days=? "
self.crs.execute(query1,(name,day))
self.con2.commit()
elif job=="3":
query1 = "Update Jobs set Job1=? where Days=? "
self.crs.execute(query1,(name,day))
self.con2.commit()
|
1a231067463d9eb5b408309d27ccaf797e58b360 | ramin-karimian/programming_2019_iust | /codes/t02.py | 501 | 3.953125 | 4 | a=float(input("add a ra vared kon:"))
b=float(input("add b ra vared kon:"))
c=float(input("add c ra vared kon:"))
if a<b+c and b<a+c and c<a+b :
print("mosalas mitavan sakht")
else:
print("nemitavan sakht")
# # Also this implementation in correct :
# a=float(input("add a ra vared kon:"))
# b=float(input("add b ra vared kon:"))
# c=float(input("add c ra vared kon:"))
# if a>=b+c:
# print("No")
# elif b>=a+c:
# print("No")
# elif c>a+b:
# print("No")
# else:
# print("Yes")
|
9d53d31acb3bb364e8be1a49a6a322ca16c7dcc8 | ekohilas/comp3821 | /ass_2/q8.py | 205 | 3.609375 | 4 | from random import shuffle
from sys import argv
def numbers(n):
l = [x for x in range(n*2+1)]
shuffle(l)
print(*sorted(l[:len(l)//2]))
print(*sorted(l[len(l)//2:]))
numbers(int(argv[1]))
|
f0995f652df181115268c78bbb649a6560108f47 | ciciswann/interview-cake | /big_o.py | 658 | 4.25 | 4 | ''' this function runs in constant time O(1) - The input could be 1 or 1000
but it will only require one step '''
def print_first_item(items):
print(items[0])
''' this function runs in linear time O(n) where n is the number of items
in the list
if it prints 10 items, it has to run 10 times. If it prints 1,000 items,
we have to print 1,000 times'''
def print_all_items(items):
for item in items:
print(item)
''' Quadratic time O(n^2)'''
def print_all_possible_ordered_pairs(items):
for first_item in items:
for second_item in items:
print(first_item, second_item)
print_all_possible_ordered_pairs([0,6,8,9])
|
495aeb1b054bc1047143abb1ed1560f4c10017dd | amirtl/genetic-algorithm-2 | /N-Queens.py | 5,691 | 3.734375 | 4 | #solving TSP using genetic algorithm
import random
#generates a random number between 1 and the number of cities minus 1.
def Rand_City(size):
return random.randint(0, size-1)
#checks if a city was seen before of not.
def Is_New(Gene, city):
for c in Gene:
if c == city:
return False
return True
#find the fitness using the given matrix
def Find_Fitness(Gene):
nxn = []
c = []
for i in range(len(Gene)):
c.append(0)
for i in range(len(Gene)):
nxn.append(c[:])
nxn[i][Gene[i]] = 1
fitness = 0
for i in range(len(Gene)):
j = len(Gene) - i - 1
k = 0
queens = 0
while k <= i:
if nxn[k][j] == 1:
queens += 1
k += 1
j += 1
if queens > 1:
fitness += (queens * (queens-1))
j = i
k = len(Gene) - 1
queens = 0
if j != len(Gene) - 1:
while j >= 0:
if nxn[k][j] == 1:
queens += 1
k -= 1
j -= 1
if queens > 1:
fitness += (queens * (queens-1))
j = 0
k = i
queens = 0
while k >= 0:
if nxn[k][j] == 1:
queens += 1
k -= 1
j += 1
if queens > 1:
fitness += (queens * (queens-1))
j = len(Gene) - 1 - i
k = len(Gene) - 1
queens = 0
if j != 0:
while j <= len(Gene) - 1:
if nxn[k][j] == 1:
queens += 1
k -= 1
j += 1
if queens > 1:
fitness += (queens * (queens-1))
return fitness
#generates a Gene randomly or generates a path randomly
def Create_Gene(size):
Gene = []
for i in range(size):
while True:
new_city = Rand_City(size)
if Is_New(Gene, new_city):
Gene += [new_city]
break
return Gene
def Give_2_rand_number(size):
while True:
change1 = Rand_City(size)
change2 = Rand_City(size)
if change1 != change2:
break
if change1 > change2:
temp = change1
change1 = change2
change2 = temp
return change1, change2
#gets 2 cities and swap them to make a mutation.
def Mutation(Gene):
change1, change2 = Give_2_rand_number(len(Gene))
temp = Gene[change1]
Gene[change1] = Gene[change2]
Gene[change2] = temp
return Gene
def CrossOver(Gene1, Gene2):
n = len(Gene1)
i, j = Give_2_rand_number(n)
mark = [0]*n
new_gene = [0]*n
for k in range(i, j+1):
new_gene[k] = Gene1[k]
mark[Gene1[k]] = 1
p_old = (j+1)%n
p_new = p_old
for _ in range(n):
if mark[Gene2[p_old]] == 1:
p_old = p_old+1
p_old = p_old%n
continue
if new_gene[p_new] == True:
break
new_gene[p_new] = Gene2[p_old]
mark[Gene2[p_old]] = 1
p_old, p_new = p_old+1, p_new+1
p_old, p_new = p_old%n, p_new%n
return new_gene
def TSP(size, number_of_first_population, N, Mutation_Probability, Cross_Over_Probability):
Population = []
#generate the first population
for _ in range(number_of_first_population):
Gene = Create_Gene(size)
Fitness = Find_Fitness(Gene)
Population.append((Gene,Fitness))
Population.sort(key=lambda x:x[1])
Population = Population[:(len(Population)*N)/100+1]
print("Best initial population:")
print(Population[0][0])
print("Cost:")
print(Population[0][1])
generation = 2
#repeats untill the best fitness does not change for N times
while(Population[0][1] != 0):
new_population = Population
#make a cross over between 2 genes that have not been cross overed before for half of the size of the population
crossed_over = []
for _ in range(len(new_population)/2):
if Rand_City(101) >= Cross_Over_Probability:
while True:
i, j = Give_2_rand_number(len(new_population))
if Is_New(crossed_over, i) and Is_New(crossed_over, j):
crossed_over += [i]
crossed_over += [j]
break
new_gene = CrossOver(new_population[i][0][:], new_population[j][0][:])
new_fitness = Find_Fitness(new_gene)
Population.append((new_gene, new_fitness))
#make a mutation in each parent and consider them as a child and append them to the generation
for i in range(len(new_population)):
if Rand_City(101) >= Mutation_Probability:
new_gene = Mutation(new_population[i][0][:])
new_fitness = Find_Fitness(new_gene)
Population.append((new_gene, new_fitness))
#sort the generation by the fitness
Population.sort(key=lambda x:x[1])
#choose the N% of best fitnesses
Population = Population[:(len(Population)*N)/100 + 1]
print("generation number: ", generation)
print("best population:")
print(Population[0][0])
print("cost:")
print(Population[0][1])
generation += 1
size = 8 #number of queens
number_of_first_population = size*2
N = 50 #N% of the best fitnesses will be chosen
Mutation_Probability = 50 #every gene have 50% probability to mutate
Cross_Over_Probability = 50
TSP(size, number_of_first_population, N, Mutation_Probability, Cross_Over_Probability) |
77047e19385045ca862c1e7860664ba0ba35183e | lambda-projects-ak/data-structures-sprint | /names/names.py | 1,100 | 3.6875 | 4 |
import time
from binary_search_tree import BinarySearchTree
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
# binary search tree solution runtime: O(2n 2log(n)) -> O(n log(n))
# O(n) to loop over names_1 and insert every element into binary search tree
# O(log(n)) to insert into binary search tree, it checks to see if it can insert element once per level
# O(n) to loop over names_2 to check for matches
# O(log(n)) to check for match inside of binary search tree
# O(1) to append to the end of solution list
# runtime: 0.1812 seconds
search_tree = BinarySearchTree("str")
duplicates = []
for name_1 in names_1:
search_tree.insert(name_1)
for name_2 in names_2:
# search tree for match
if search_tree.contains(name_2):
duplicates.append(name_1)
end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")
|
29a21b7d3b694268ebc6362f1dc4bb044c2b3883 | luispaulojr/cursoPython | /semana_01/aula01/parte02_condicionais.py | 309 | 4.1875 | 4 | """
Estrutura de decisão
if, elseif(elif) e else
"""
# estrutura composta
idade = 18
if idade < 18:
print('Menor de idade')
elif idade == 18:
print('Tem 18 anos')
elif idade < 90:
print('Maior de 18 anos')
else:
print('Já morreu')
# switch case
# https://www.python.org/dev/peps/pep-0634/
|
28773cc4eaa5297aae60a2dc1acc20eb2c05bf21 | luispaulojr/cursoPython | /semana_01/exercicios/exercicio_12.py | 227 | 3.6875 | 4 | distancia = float(input(
'Informe a distância em milhas para ser convertida em quilometros: ').replace(',', '.'))
print(
f'A conversão da distancia {distancia} em milhas para quilometros é: {(distancia * 1.61)} km') |
a39d746b7b7b615e54c0266aba519956a96c492c | luispaulojr/cursoPython | /semana_02/aula/tupla.py | 871 | 4.40625 | 4 | """
Tuplas são imutáveis
arrays - listas são mutáveis
[] utilizado para declaração de lista
() utilizado para declaração de tupla
"""
"""
# declaração de uma tupla utilizando parenteses
"""
tupla1 = (1, 2, 3, 4, 5, 6)
print(tupla1)
"""
# declaração de uma tupla não utilizando parenteses
"""
tupla2 = 1, 2, 3, 4, 5, 6
print(type(tupla2))
"""
# a tupla pode ser heterogêneco
"""
tupla3 = (4, 'senac')
print(type(tupla3[0]))
print(type(tupla3[1]))
print(type(tupla3))
# desempacotamento
tupla4 = 'Curso de python', 'para os melhores professores'
curso, elogio = tupla4
print(curso)
print(elogio)
"""
# a tupla pode ser heterogêneco
"""
tupla5 = (1, 2, 3, 4, 5, 6)
print(sum(tupla5))
print(max(tupla5))
print(min(tupla5))
print(len(tupla5))
"""
# a tupla pode ser incrementada
"""
tupla6 = 23, 10, 2021
tupla6 += 'Python',
print(tupla6) |
9f09ea8be016ddd8d651fdf91381e826abb9788d | luispaulojr/cursoPython | /semana_01/exercicios/exercicio_19.py | 221 | 3.78125 | 4 | volume = float(input(
'Informe o volume em litros para ser convertido em metros cubicos (m³): ').replace(',', '.'))
print(
f'A conversão do volume {volume} litros para metros cubicos é: {(volume / 1000)}m³')
|
ca10ff118b97f6e0b3f5fd6bd62dbebea98b230a | zongxinwu92/leetcode | /CombinationSumIii.py | 473 | 3.6875 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases."
'''
|
5ea3f9bd83548d755afa8c5ab0a4c940b41fab68 | zongxinwu92/leetcode | /ValidateBinarySearchTree.py | 578 | 3.59375 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node s key.
The right subtree of a node contains only nodes with keys greater than the node s key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
"
'''
|
1bb6b866223412e18ffe84f85031b02342cde01a | zongxinwu92/leetcode | /FindAllDuplicatesInAnArray.py | 352 | 3.609375 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
"
'''
|
acf4f0a175a94b5018db65165371936c07522515 | zongxinwu92/leetcode | /BurstBalloons.py | 978 | 3.796875 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a
number on it represented by array nums.
You are asked to burst all the balloons. If the you burst
balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left
and right are adjacent indices of i. After the burst, the left and right
then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:
Given [3, 1, 5, 8]
Return 167
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases."
'''
|
f2b92a220d6de5472fe1e3cbfbd1e375f3212397 | zongxinwu92/leetcode | /FindTheDifference.py | 382 | 3.765625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
e is the letter that was added.
"
'''
|
f6e831f5b6d40a09a10f174f4ee1f6211ff56ebb | zongxinwu92/leetcode | /AddStrings.py | 410 | 3.703125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"
'''
|
6d519be24d58b2bef610f2fd28248a7724eeb5fb | zongxinwu92/leetcode | /UniqueSubstringsInWraparoundString.py | 975 | 3.828125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.
Note: p consists of only lowercase English letters and the size of p might be over 10000.
Example 1:
Input: "a"
Output: 1
Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:
Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in the string s.
Example 3:
Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
"
'''
|
b9c060c072cbe48f0762f2d07fe5d28ed1f6b6e3 | zongxinwu92/leetcode | /FractionToRecurringDecimal.py | 839 | 3.515625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
Credits:Special thanks to @Shangrila for adding this problem and creating all test cases."
'''
|
d0249ae72e0a0590cffda71a48c5df0993d1ee18 | zongxinwu92/leetcode | /CountTheRepetitions.py | 788 | 4.125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".
On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.
You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.
Example:
Input:
s1="acb", n1=4
s2="ab", n2=2
Return:
2
"
'''
|
b6516ea8f501f2041d8ca93640ee566bd5551b2c | zongxinwu92/leetcode | /AddDigits.py | 701 | 3.65625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases."
'''
|
56e51b84f4c740eeed8f8882968e7f12f06c98f6 | zongxinwu92/leetcode | /PartitionList.py | 358 | 3.5625 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
"
'''
|
4f52b64412a86577dd635a47ff9c589a1e4f98d3 | jamalshah5111996/Py-Assignment-3 | /Assignment#3.py | 2,795 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
#TASK1:
print("\nTASK1:\n");
Poem= "Twinkle, twinkle, little star,\n\t How I wonder what you are! \n\t\t Up above the world so high,\n\t\t Like a diamond in the sky.\nTwinkle, twinkle, little star,\n\t How I wonder what you are!\n"
print(Poem);
#TASK2:
print("\nTASK2:\n");
from platform import python_version
print("Python-Version=",python_version());
#TASK3:
print("\nTASK3:\n");
import datetime
now = datetime.datetime.now()
print ("Current date and time :",now.strftime("%Y-%m-%d %H:%M:%S"))
#TASK4:
print("TASK4:\n");
radius = int(input("Write the radius of the circle:"))
pi = 3.146
area = pi*radius*radius
print("Area of the Circle:",area,"square units")
#TASK5:
print("\nTASK5:\n");
first_name = input("Write your first Name:")
last_name = input("Write your Last Name:")
print(last_name,first_name)
#TASK6:
print("\nTASK6:\n");
a=int(input("\nwrite the value of a:"))
b=int(input("write the value of b:"))
print("sum of a+b=",a+b)
#TASK7:
print("\nTASK7:\n");
eng = int(input("Write your English Marks out of 100:"));
isl = int(input("Write your Islamiat Marks out of 100:"));
math = int(input("Write your Mathematics Marks out of 100:"));
phy =int(input("Write your Physics Marks out of 100:"));
chem =int(input("Write your Chemistry Marks out of 100:"));
total =500;
obt_total = eng + isl + math+ phy + chem;
percent = obt_total/total *100;
percentage =round(percent);
if obt_total <=500 and obt_total >=0:
print("Total Obtained Marks:",obt_total,"/",total);
if percentage <=100 and percentage >=0:
print("Your Percentage is:",percentage,"%");
else:
print("Invalid Marks!");
if percentage <= 100 and percentage >=80:
print("Grade: A+")
elif percentage <= 79 and percentage >=70:
print("Grade: A")
elif percentage <= 69 and percentage >=60:
print("Grade: B")
elif percentage <= 59 and percentage >=50:
print("Grade: C")
elif percentage <= 49 and percentage >=40:
print("Grade: D")
elif percentage <= 39 and percentage >=0:
print("Failed")
else:
print("Review Your Marks.");
# TASK8:
print("\nTASK8:\n");
number=int(input("Write a number to check it is Even or Odd:"))
if number %2 ==0:
print("it is even number")
else:
print("it is odd number")
# TASK9:
print("\nTASK9:\n");
cars= ["Tesla","Toyota","Honda","Chevorlet","Range rover","Cadillac"];
leng= len(cars);
print("Total Cars:",leng);
# TASK10:
print("\nTASK10:\n");
nums=[10,20,100,200,500,300,800,900];
Summ =sum(nums);
print("Sum of all numbers in the list is:",Summ)
# TASK11:
print("\nTASK11:\n");
list=[80,404,556,60,87,1000,20,800,600];
largNo=max(list)
print("Largest Number in the list is:",largNo)
# TASK12:
print("\nTASK12:\n");
e = [1, 2, 3, 4, 5, 6, 8, 7, 8, 9, 10, 11]
for y in e:
if y < 5:
print(y);
|
096ea5546286513cd271082345a9522c9426dfab | bhawanabhatt538/numpy | /numpy_exercise.py | 1,576 | 4 | 4 | import pandas as pd
import numpy as np
# Create an array of 10 zeros
print('array of 10 zeros=',np.zeros(10))
print('array of 10 ones=',np.ones(10))
#Create an array of 10 fives
print('an array of 10 fives=',np.ones(10)*5)
print('array of the integers from 10 to 50=',np.arange(10,51))
print('array of all the even integers from 10 to 50=',
np.arange(10,51,2))
print(np.arange(0,9).reshape([3,3]))
print('3x3 identity matrix=\n',np.eye(3))
# Use NumPy to generate a random number between 0 and 1
print(np.random.rand(1))
print('\n')
print('an array of 25 random numbers sampled from a standard normal distribution=',np.random.randn(25))
# print(np.arange(0.01,0,01,0.01).reshape(10,10))
# print('array of 20 linearly spaced points between 0 and 1=',np.linspace(0,1,20))
# Numpy Indexing and Selection
# Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs:
# Deepak = np.arange(1,26).reshape(5,5)
# print(Deepak)
print('\n\n')
mat = np.arange(1,26).reshape(5,5)
print(mat)
print('\n')
print(mat[2:,1:])
print('\n\n')
print(mat[3,4])
# WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW
# BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T
# BE ABLE TO SEE THE OUTPUT ANY MORE
print('\n')
print(mat[:3,1:2])
print('\n')
print(mat[3:,:])
# print('\n\n')
# Now do the following
# Get the sum of all the values in mat¶
# print('sum of all the values in mat=',mat.sum())
print('standard deviation of the values in mat=',np.std(mat))
print('\n')
print('sum of all the columns in mat=',np.sum(mat,axis=0))
|
Subsets and Splits