blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
05708062fd83c6c3c742e1cf5d3beb80b9f5ab56 | Zjx01/IBI1_2018-19 | /Practical4/power of 2.py | 817 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 17:08:11 2019
@author: Jessi
"""
n=eval(input("input a integer:",))
n0=n
sign=0 #to store whether the number input is an odd or even
answer=str(n) + "="
l1= []
if n%2 != 0:
n = n-1
#to change the odd number into even, and the minused 1 will be added by sign a the end of the function
sign = 1
while n != 0:#the garantee of the function
j=0
while j <= 13:
if n0/2 >= 1:#to find the biggest 2**n in the n given, by dividing 2 continuoyly and compare with 1
n0 = n0/2
j = j+1
else:
break
l1.append("2**" + str(j))
n = n - 2**j #the remaining value after getting rid of the biggest 2**n
n0 = n
#if sign == 1:
answer = answer + '+'.join(l1)
print(answer)
|
61aa806beb82a52d92319bb1fb2c5e03dce09eb4 | mx2013713828/leetcodeTest | /Middle.py | 539 | 3.65625 | 4 |
class Node(object):
def __init__(self,elem= -1,lchild=None,rchild = None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class middle(object):
def __init__(self):
self.root = Node()
def front_digui(self,root):
if root == None:
return
self.front_digui(root.lchild)
print root.elem,
self.front_digui(root.rchild)
root = Node(elem=4)
root.rchild = Node(elem=2)
root.rchild.lchild = Node(elem=3)
middle = middle()
middle.front_digui(root) |
09063b6b8c585c741335003592b115be76edbd6b | pdturney/open-ended-immigration-games | /immigration-rules/rule_generator.py | 6,705 | 3.703125 | 4 | #
# Rule Generator
#
# Peter Turney, October 30, 2019
#
# Read in a list of totalistic life-like rules of the
# form "B37/S236" and generate Golly rule files for
# playing the Immmigration Game with the given rules.
# The Immigration Game requires odd numbers for birth
# (for example, "B37" but not "B47"), in order to break
# ties between the two colours (red and blue).
#
#
# import regular expressions (re)
#
import re
#
# read in a list of rules from a file
#
# - each line in the file should be one rule
# of the form "B37/S236"
#
input_rule_file_name = "group3-rules.txt"
output_rule_file_prefix = "Group-3-"
#
input_rule_handle = open(input_rule_file_name, "r")
rule_list = []
#
for rule in input_rule_handle:
# born numbers must be odd
born_search = re.search(r'(B[1357]+)/', rule)
assert born_search
# survive numbers range from 0 to 8
survive_search = re.search(r'(S[012345678]+$)', rule)
assert survive_search
# if the assertions are true, then add the rule to the list
born = born_search.group(1)
survive = survive_search.group(1)
# replace "/" with "-" because "/" is not legal in a file name
rule_list.append(born + "-" + survive)
#
input_rule_handle.close()
#
# iterate through the list of rules
#
for rule in rule_list:
#
# create a file name for the current rule
#
output_rule_file_base = output_rule_file_prefix + rule
output_rule_file_name = output_rule_file_base + ".rule"
#
# open output file for writing
#
output_rule_handle = open(output_rule_file_name, "w")
#
# write the file header
#
output_rule_handle.write("@RULE " + output_rule_file_base + "\n")
#
output_rule_handle.write("@TABLE\n" + \
"n_states:3\n" + \
"neighborhood:Moore\n" + \
"symmetries:permute\n" + \
"var a={1,2}\n" + \
"var b={1,2}\n" + \
"var c={1,2}\n" + \
"var d={1,2}\n" + \
"var e={1,2}\n" + \
"var f={1,2}\n" + \
"var g={1,2}\n" + \
"var h={1,2}\n" + \
"var i={1,2}\n")
#
# parse the rule into born and survive
#
born_search = re.search(r'B([1357]+)-', rule)
survive_search = re.search(r'S([012345678]+$)', rule)
born = born_search.group(1)
survive = survive_search.group(1)
#
# write out rules for born
#
# - these should all involve odd numbers
#
for num in list(born):
if (num == "1"):
output_rule_handle.write("# B1\n")
output_rule_handle.write("0,1,0,0,0,0,0,0,0,1\n")
output_rule_handle.write("0,2,0,0,0,0,0,0,0,2\n")
elif (num == "3"):
output_rule_handle.write("# B3\n")
output_rule_handle.write("0,a,1,1,0,0,0,0,0,1\n")
output_rule_handle.write("0,a,2,2,0,0,0,0,0,2\n")
elif (num == "5"):
output_rule_handle.write("# B5\n")
output_rule_handle.write("0,a,b,1,1,1,0,0,0,1\n")
output_rule_handle.write("0,a,b,2,2,2,0,0,0,2\n")
else:
assert num == "7"
output_rule_handle.write("# B7\n")
output_rule_handle.write("0,a,b,c,1,1,1,1,0,1\n")
output_rule_handle.write("0,a,b,c,2,2,2,2,0,2\n")
#
# write out the rules for survive
#
for num in list(survive):
if (num == "0"):
output_rule_handle.write("# S0\n")
output_rule_handle.write("1,0,0,0,0,0,0,0,0,1\n")
output_rule_handle.write("2,0,0,0,0,0,0,0,0,2\n")
elif (num == "1"):
output_rule_handle.write("# S1\n")
output_rule_handle.write("1,a,0,0,0,0,0,0,0,1\n")
output_rule_handle.write("2,a,0,0,0,0,0,0,0,2\n")
elif (num == "2"):
output_rule_handle.write("# S2\n")
output_rule_handle.write("1,a,b,0,0,0,0,0,0,1\n")
output_rule_handle.write("2,a,b,0,0,0,0,0,0,2\n")
elif (num == "3"):
output_rule_handle.write("# S3\n")
output_rule_handle.write("1,a,b,c,0,0,0,0,0,1\n")
output_rule_handle.write("2,a,b,c,0,0,0,0,0,2\n")
elif (num == "4"):
output_rule_handle.write("# S4\n")
output_rule_handle.write("1,a,b,c,d,0,0,0,0,1\n")
output_rule_handle.write("2,a,b,c,d,0,0,0,0,2\n")
elif (num == "5"):
output_rule_handle.write("# S5\n")
output_rule_handle.write("1,a,b,c,d,e,0,0,0,1\n")
output_rule_handle.write("2,a,b,c,d,e,0,0,0,2\n")
elif (num == "6"):
output_rule_handle.write("# S6\n")
output_rule_handle.write("1,a,b,c,d,e,f,0,0,1\n")
output_rule_handle.write("2,a,b,c,d,e,f,0,0,2\n")
elif (num == "7"):
output_rule_handle.write("# S7\n")
output_rule_handle.write("1,a,b,c,d,e,f,g,0,1\n")
output_rule_handle.write("2,a,b,c,d,e,f,g,0,2\n")
else:
assert num == "8"
output_rule_handle.write("# S8\n")
output_rule_handle.write("1,a,b,c,d,e,f,g,h,1\n")
output_rule_handle.write("2,a,b,c,d,e,f,g,h,2\n")
#
# write out the rules for die
#
# - die equals NOT survive
#
die = ""
for i in range(9):
if (str(i) not in survive):
die = die + str(i)
#
for num in list(die):
if (num == "0"):
output_rule_handle.write("# D0\n")
output_rule_handle.write("a,0,0,0,0,0,0,0,0,0\n")
elif (num == "1"):
output_rule_handle.write("# D1\n")
output_rule_handle.write("a,b,0,0,0,0,0,0,0,0\n")
elif (num == "2"):
output_rule_handle.write("# D2\n")
output_rule_handle.write("a,b,c,0,0,0,0,0,0,0\n")
elif (num == "3"):
output_rule_handle.write("# D3\n")
output_rule_handle.write("a,b,c,d,0,0,0,0,0,0\n")
elif (num == "4"):
output_rule_handle.write("# D4\n")
output_rule_handle.write("a,b,c,d,e,0,0,0,0,0\n")
elif (num == "5"):
output_rule_handle.write("# D5\n")
output_rule_handle.write("a,b,c,d,e,f,0,0,0,0\n")
elif (num == "6"):
output_rule_handle.write("# D6\n")
output_rule_handle.write("a,b,c,d,e,f,g,0,0,0\n")
elif (num == "7"):
output_rule_handle.write("# D7\n")
output_rule_handle.write("a,b,c,d,e,f,g,h,0,0\n")
else:
assert num == "8"
output_rule_handle.write("# D8\n")
output_rule_handle.write("a,b,c,d,e,f,g,h,i,0\n")
#
# set the colours
#
output_rule_handle.write("@COLORS\n")
output_rule_handle.write("0 255 255 255 white\n")
output_rule_handle.write("1 255 0 0 red\n")
output_rule_handle.write("2 0 0 255 blue\n")
#
# close output file
#
output_rule_handle.close()
#
#
#
# |
21f10cbab8ebb5c699b63212e5f3174a81ee6555 | marmotmarsh/euler-project | /python/completed/euler0019.py | 395 | 4.1875 | 4 | ###
#
# Created by Holden on 12/18/2015
#
# SOLVED on 12/18/2015
#
# Problem 19 - Counting Sundays
#
###
import datetime
def counting_sundays(start, end):
count = 0
for year in range(start, end + 1):
for month in range(1, 13):
date = datetime.date(year, month, 1)
if date.weekday() == 6:
count += 1
return count |
f322ab867fe80a7ba1e948d64adf712e20dc62db | krishnajaV/luminarPythonpgm- | /oops/ExceptionHandling/addition.py | 244 | 3.796875 | 4 |
try:
a = int(input("enter the number"))
b = int(input("enter the number"))
sum= a+b
print(sum)
except:
print("please enter the integer")
finally:
print("finally")
#in this case try and except and finally work at a time. |
11c00fcb70018a8f5b03c4c6c61af0a4037d454f | michaelhuo/pcp | /653_2.py | 1,134 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
def recursive(root: TreeNode, nums:List[int]) -> None:
if root.left:
recursive(root.left, nums)
nums.append(root.val)
if root.right:
recursive(root.right, nums)
queue = []
nums = []
node = root
while queue or node:
if node:
queue.append(node)
node = node.left
else:
node = queue.pop()
nums.append(node.val)
node = node.right
#recursive(root, nums)
low, high = 0, len(nums) - 1
while low < high:
value = nums[low] + nums[high]
if value == k:
return True
elif value < k:
low += 1
else:
high -= 1
return False
|
9a60d1950251c4c15010a1651c921d6e387cc317 | michelleferns/python | /school.py | 290 | 3.859375 | 4 | my_name=input("enter your name>")
my_age=input("enter your age>")
my_class=input("enter your class>")
my_mark=input("enter your marks>")
print("My name is ",my_name,"fernandes")
print("My age is ",my_age,"years")
print("My class is ",my_class,"A")
print("My marks is ",my_mark,"%")
|
37fff59e31bd213786d385be5bed493d7c9fa366 | Alexander-Stanley/Programming-II | /Prac 4/quick_pick_lotto.py | 774 | 4.09375 | 4 | import random
NUMBERS_PER_LINE = 6
MIN_NUM = 1
MAX_NUM = 45
def main():
num_of_picks = int(input("How many Quick Picks(TM):"))
while num_of_picks <0 :
print("Come on now, give in to the capitalist game to keep lining our pockets, forget about feeding your kids.")
num_of_picks = int(input("Now we aren't going to ask again, HOW MANY QUICK PICKS?!"))
for i in range(num_of_picks):
quick_pick = []
for j in range(NUMBERS_PER_LINE):
number = random.randint(MIN_NUM, MAX_NUM)
while number in quick_pick:
number = random.randint(MIN_NUM, MAX_NUM)
quick_pick.append(number)
quick_pick.sort()
print(" ".join("{:2}".format(number) for number in quick_pick))
main() |
779e4d74c545936c268b0f92b7a41fc8297ad34b | shahid31202/expert-system | /project9.py | 9,069 | 3.515625 | 4 | print('--------------------------------------------------------')
print('--------WELCOME TO HOMEOPATHIC EXPERT SYSTEM---------- |')
print('enter which category do you want diagnosis |')
print('1.children |')
print('2.digestive |')
print('3.fever and general |')
print('4.joints and muscles |')
print('5.respiratory diseases |')
print('6.skin diseases |')
print('7.Lifestyle diseses |')
print('--------------------------------------------------------')
b=[]
while(1):
a=int(input())
if(a==1):
print('eneter which in which problems you want diagnosis')
print('1.hyper active')
print('2.bedwetting')
print('3.cold')
print('4.growth deficiency')
print('5.fever')
print('6.clacium deficiency')
print('7.cough')
b1=input().split(' ')
if '1' in b1:
b.append('KINDIVAL')
if '2' in b1:
b.append('ENUKIND')
if '3' in b1:
b.append('NISIKIND')
if '4' in b1:
b.append('ANEKIND')
if '5' in b1:
b.append('ECHINACEA ANGUSTIFOLIA 1X')
if '6' in b1:
b.append('CALCIOKIND')
if '7' in b1:
b.append('TUSSIKIND')
print('the count is ',len(b))
print('the medicine list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==3):
print('enter which in which problems you want diagnosis')
print('1.fever')
print('2.immune boosters')
print('3.tonsilities')
print('4.vomiting sensation')
print('5.chill')
print('6.cold')
print('7.cough')
b1=input().split()
if '1' in b1:
b.append('ACONITUM PENTARKAN')
if '2' in b1:
b.append('MUNOSTIM')
if '3' in b1:
b.append('ALPHA-TONS')
if '4' in b1:
b.append('ALPHA-LIV')
if '5' in b1:
b.append('ALPHA-WD')
if '6' in b1:
b.append('NUSIKIND')
if '7' in b1:
b.append('TUSSIKIND')
print('the count is ',len(b))
print('the medicine list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==2):
print('enter which in which problems you want diagnosis')
print('1.diarrhoea')
print('2.vomitings')
print('3.acidity')
print('4.colic')
print('5.nausea')
print('6.motion sickness')
print('7.loss of apetetite')
print('8.travel sickness')
print('9.constipation')
print('10.dysentry')
b1=input().split()
if '1' in b1:
b.append('BIOCOMBINATION NO. 08')
if '2' in b1:
b.append('ALPHA-MS')
if '3' in b1:
b.append('ALPHA-ACID')
if '4' in b1:
b.append('COLIKIND')
if '5' in b1:
b.append('KINDIGEST')
if '6' in b1:
b.append('ALPHA-MS')
if '7' in b1:
b.append('ALPHA-LIV')
if '8' in b1:
b.append('ALPHA-MS')
if '9' in b1:
b.append('NATRUM MURIATICUM')
if '10' in b1:
b.append('HOLARRHENA ANTIDYSENTERICA 1X')
print('the count is ',len(b))
print('the list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==4):
print('enter which in which problems you want diagnosis')
print('1.cramps')
print('2.muscular pain')
print('3.rheamtic pain')
print('4.bone problems')
print('5.body ache')
print('6.joints')
print('7.inflammation')
print('8.muscles')
print('9.spasms')
print('10.Osteoarthritis')
b1=input().split()
if '1' in b1:
b.append('MAGNESIUM PHOSPHORICUM')
if '2' in b1:
b.append('Alpha-MP')
if '3' in b1:
b.append('Alpha-MP')
if '4' in b1:
b.append('Calcarea phosphorica')
if '5' in b1:
b.append('TOPI ARNICA CREAM')
if '6' in b1:
b.append('Topi MP Gel')
if '7' in b1:
b.append('Topi Heal Cream')
if '8' in b1:
b.append('Kali phosphoricum')
if '9' in b1:
b.append('Magnesium Phosphoricum Pentarkan')
if '10' in b1:
b.append('Biocombination No. 19')
print('the count is ',len(b))
print('the list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==5):
print('enter which in which problems you want diagnosis')
print('1.Chronic Cough')
print('2.Spasmodic cough')
print('3.Cough syrup')
print('4.Irritating cough')
print('5.Nasal congestion')
print('6.Sneezing')
print('7.Stuffiness of nostrils')
print('8.Breathlessness')
print('9.Coryza')
print('10.respiratory congestion')
b1=input().split()
if '1' in b1:
b.append('Alpha-CC')
if '2' in b1:
b.append('Alpha-Coff')
if '3' in b1:
b.append('Aconitum Pentarkan')
if '4' in b1:
b.append('Glycyrrhiza glabra 1X')
if '5' in b1:
b.append('Alpha-NC')
if '6' in b1:
b.append('Alpha-RC')
if '7' in b1:
b.append('Alpha-NC2')
if '8' in b1:
b.append('Alpha-RC1')
if '9' in b1:
b.append('BIOCOMBINATION NO. 05')
if '10' in b1:
b.append('Biocombination No. 13')
print('the count is ',len(b))
print('the list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==6):
print('enter in which of the following you want diagnosis')
print('1.Acne')
print('2.pimples')
print('3.psoriasis')
print('4.bed sores')
print('5.boils')
print('6.cuts')
print('7.itching')
print('8.scabies')
print('9.dermatities')
print('10.fungal infection')
b1=input().split()
if '1' in b1:
b.append('TOPI BERBERIS CREAM')
if '2' in b1:
b.append('Calcarea sulphurica')
if '3' in b1:
b.append('Alpha-WD')
if '4' in b1:
b.append('Topi Heal Cream')
if '5' in b1:
b.append('Silicea')
if '6' in b1:
b.append('Hepar Sulphuris Pentarkan')
if '7' in b1:
b.append('Graphites Pentarkan')
if '8' in b1:
b.append('Topi Sulphur Cream')
if '9' in b1:
b.append('B&T Akne - Sor Soap')
if '10' in b1:
b.append('B&T CALENDULA & ALOE VERA MULTIPURPOSE CREAM')
print('the count is ',len(b))
print('the list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
elif(a==7):
print('enter in which of the following you want diagnosis')
print('1.weight loss')
print('2.tension and stress')
print('3.insomnia')
print('4.erectile disfunction')
print('5.hyper tension')
print('6.mental stress')
print('7.obesity')
print('8.alcoholism')
print('9.thyroid disorder')
print('10.stress bustor')
b1=input().split()
if '1' in b1:
b.append('Phytolacca Berry Tablets')
if '2' in b1:
b.append('Alpha-TS')
if '3' in b1:
b.append('Kali phosphoricum')
if '4' in b1:
b.append('Damiaplant')
if '5' in b1:
b.append('Essentia aurea')
if '6' in b1:
b.append('Ginseng 1X')
if '7' in b1:
b.append('Phytolacca Berry Tablets*')
if '8' in b1:
b.append('Quercus robur 1x')
if '9' in b1:
b.append('Thyroidinum 3X (LATT)')
if '10' in b1:
b.append('Biocombination No. 03')
print('the count is ',len(b))
print('the list is ',b)
print('even after the use of medicines you are not comfortable consult the doctor')
break
else:
print('please enter a valid option')
|
1602836a9a261b23e89369798e7d462c6c672949 | kajal1301/python | /ifElse.py | 391 | 4 | 4 | #if Else and Elif in python
var= 4
var1= 44
var2= int(input()) #takes user input
if var2>var1 :
print("Greater than",var1)
elif var2== var1:
print("Equal")
else:
print("Lesser")
#to check if the element is present in a list or not
list1= [5,6,7]
if 5 in list1:
print("Yes it is in the List")
if 15 not in list1:
print("Its not in the list")
|
db3eef5c222c469ea296bd13d77dabd63d4d9050 | magikitty/GetPythonBookPractice | /25.Lists/AddingItems25.4.py | 731 | 4.4375 | 4 | """
This is Lesson 25: Working with lists
Get Programming: Learn to Code With Python
There are three ways to add items to lists: append, insert, and extend
"""
# Append adds one item to the end of the list (last index position)
grocery_list = ["boinky beans", "milk"]
grocery_list.append("bananas")
print(grocery_list)
# Insert adds one item into the specified index position
cat_breeds = ["Persian", "Scottish fold", "Wild cat"]
cat_breeds.insert(2, "Super fluffy cat")
print(cat_breeds)
# Extend adds all items from one list to the end of another list
fun_things = ["My Beboo", "Nintendo Switch", "swimming", "songs"]
more_fun_things = ["TV shows", "warm houses", "parks"]
fun_things.extend(more_fun_things)
print(fun_things)
|
df0db37b7b9eb3d02b3b3de5dbd92c01b1509569 | Yozi47/Data-Structure-and-Algorithms-Class | /Final Exam/Question no 4.py | 668 | 3.546875 | 4 | '''
Let us consider the base case as H = 0.
Here a binary tree has height 0 which has single node.
so we get, 1=2^(0+1) -1
Therefore, the base case is satisfied as of the induction hypothesis.
Using Induction
Suppose the max modes in a binary tree of height h is
2**(h+1) -1 where h = 1, 2, .... , k
Assuming, T be a binary tree of height k+1.
So, the subtrees of binary trees of height <= k,
using Induction Hypothesis it has at most 2^(k+1)-1 nodes.
Total no of root node gives max modes in a binary tee of height k+1,
that means
2(2**(k+1)-1 + 1
2*2**(k+1)-2 + 1
2**((k+1)+1) - 1
Hence the hypothesis holds for k+1, so the theorem is proved.
''' |
00e2b99fedecde6ebc45b719e626eaa4d3c98100 | jeancharlles/orientacao-objeto | /modificadores_de_acesso/classe_BaseDeDados.py | 1,381 | 3.640625 | 4 |
class BaseDeDados:
def __init__(self):
self._dados = {}
def inserir_cliente(self, id, nome):
if 'clientes' in self._dados:
self._dados['clientes'].update({id: nome})
else:
self._dados['clientes'] = {id: nome}
def lista_clientes(self):
for id, nome in self._dados['clientes'].items():
print(id, nome)
def apaga_cliente(self, id):
del self._dados['clientes'][id]
@property
def dados(self):
return self._dados
if __name__ == '__main__':
bd = BaseDeDados()
print(f'-'*60)
print(bd)
print(bd.dados) # Aqui eu consigo acessar por que foi usado @property de forma correta
bd.inserir_cliente(1, 'joão')
bd.inserir_cliente(2, 'jonas')
print(f'-'*60)
print(bd._dados) # Aqui eu consigo acessar por que é protegido mas nem tanto, e não é a forma Pythonica
print(f'-'*60)
bd.lista_clientes()
print(f'-'*60)
bd.apaga_cliente(1)
bd.lista_clientes()
# Se esta linha abaixo for ativada, bagunçará a classe pois está protegida mas pode ser alterada
# bd.__dados = 'Qualquer coisa'
print(f'-'*60)
print(bd.dados) # Aqui eu consigo acessar por que foi usado @property de forma correta
bd.inserir_cliente(3, 'ana')
bd.inserir_cliente(4, 'maria')
print(f'-'*60)
bd.lista_clientes()
|
9b8a4ee54b0c3c29224594f3ea16239c2a22e6af | asoonyii/python-challenge | /PyPoll/main.py | 2,090 | 3.90625 | 4 | #Onyinyechi Asoluka
#Python homework2- PyPoll
#8th September 2018
import os
import csv
#Collect data
csvpath= os.path.join("election_data.csv")
# Set initial counters, candidates, and winners
total_votes = 0
unique_candidate_list = []
candidate_vote = {}
count_winner= 0
# Read the csv and account for header
with open(csvpath,'r') as csvfile:
csvlines = csv.reader(csvfile, delimiter=',')
csvheader= next(csvlines)
# Loop through rows
for row in csvlines:
# Get total votes by counting rows
total_votes = total_votes + 1
# Get list of named candidates
candidatename = row[2]
# Get list of unique candidates and add to candidate list
if candidatename not in unique_candidate_list:
unique_candidate_list.append(candidatename)
# Get the candidate vote list for each candidate
candidate_vote[candidatename] = 0
candidate_vote[candidatename] = candidate_vote[candidatename] + 1
with open("main.txt", "w") as textfile:
#Put result and vote on terminal and text file
print("")
print("Election Results")
print("--------------------")
print("Total Votes: "+str(total_votes))
print("----------------------")
textfile.write("")
textfile.write("\nElection Results")
textfile.write("\n--------------------")
textfile.write("\nTotal Votes: "+ str(total_votes))
textfile.write("\n-----------------------\n")
for candidate in candidate_vote:
# calculates vote and percentage and winner
votes = candidate_vote.get(candidate)
percent= (votes) / (total_votes) * 100
if (votes > count_winner):
count_winner = votes
winner = candidate
candidate_all = f"{candidate}: {percent:.3f}% ({votes})\n"
print(candidate_all)
textfile.write(candidate_all)
print("--------------------")
print("Winner: " + winner)
print("--------------------")
textfile.write("\n--------------------")
textfile.write("\nWinner: " + winner)
textfile.write("\n--------------------")
|
e6643ba272fe8514fdb32368e9cdd2d2fad53a78 | yejinee/Algorithm | /Solve Algorithm/1523_startriangle1.py | 1,341 | 3.671875 | 4 | """
삼각형의 높이 n과 종류 m을 입력받은 후 다음과 같은 삼각형 형태로 출력하는 프로그램을 작성.
INPUT
삼각형의 크기 n(n의 범위는 100 이하의 자연수)과 종류 m(m은 1부터 3사이의 자연수)을 입력받는다.
OUTPUT
위에서 언급한 3가지 종류를 입력에서 들어온 높이 n과 종류 m에 맞춰서 출력한다.
입력된 데이터가 주어진 범위를 벗어나면 "INPUT ERROR!"을 출력한다.
EXAMPLE
type1) type2) type3)
* *** | *
** ** | ***
*** * |*****
"""
n,m=map(int,input().split())
if n<=100:
if m==1:
for i in range(1,n+1):
for j in range(1,i+1):
print('*',end='')
print()
elif m==2:
for i in range(n+1,1,-1):
for j in range(i,1,-1):
print('*',end='')
print()
elif m==3:
for j in range(1,n*2,2):
print((' '*((2*n-1-j)//2))+('*'*j))
else:
print('INPUT ERROR!')
else:
print('INPUT ERROR!') |
8873d6570cba92896418f8cef3fa1a8ebf39ac9f | zz-zhang/some_leetcode_question | /Mock Interview/6/Critical Connections in a Network.py | 3,450 | 3.859375 | 4 | '''
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
'''
# class Solution:
# def criticalConnections(self, n, connections):
# circles = []
# for node in range(n):
# q = []
# route = []
# used_node = []
# for conn in connections:
# if node == conn[0]:
# q.append(conn[1])
# route.append([node, conn[1]])
# if node == conn[1]:
# q.append(conn[0])
# route.append([node, conn[0]])
# while len(q) > 0:
# # print(q, route)
# tgt_node = q[0]
# for conn in connections:
# if tgt_node == conn[0]:
# if conn[1] == node and len(route[0]) > 2:
# if not self.list_exist(circles, route[0]):
# circles.append(route[0])
# elif conn[1] not in route[0]:
# q.append(conn[1])
# # used_node.append(used_node[0] + conn[1])
# route.append(route[0] + [conn[1]])
# # print(tgt_node, route[0])
# # breakpoint()
# if tgt_node == conn[1]:
# if conn[0] == node and len(route[0]) > 2 :
# if not self.list_exist(circles, route[0]):
# circles.append(route[0])
# elif conn[0] not in route[0]:
# q.append(conn[0])
# # used_node.append(used_node[0] + conn[0])
# route.append(route[0] + [conn[0]])
# q = q[1:]
# route = route[1:]
# # circles = [sorted(c) for c in circles if len(c) > 2]
# print(circles)
# res = []
# for conn in connections:
# for c in circles:
# if conn[0] in c and conn[1] in c:
# break
# else:
# res.append(conn)
# return res
# def list_exist(self, lst, tgt):
# for l in lst:
# for n1, n2 in zip(sorted(l), sorted(tgt)):
# if n1 != n2:
# break
# else:
# return True
# return False
class Solution:
def criticalConnections(self, n, connections):
color = [0 for _ in range(len(connections))]
for conn in connections:
pass
def dfs(self, target, connections):
if __name__ == '__main__':
sol = Solution()
n = 10
connections = [[1,0],[2,0],[3,0],[4,1],[5,3],[6,1],[7,2],[8,1],[9,6],[9,3],[3,2],[4,2],[7,4],[6,2],[8,3],[4,0],[8,6],[6,5],[6,3],[7,5],[8,0],[8,5],[5,4],[2,1],[9,5],[9,7],[9,4],[4,3]]
n = 4
connections = [[0,1],[1,2],[2,0],[1,3]]
print(sol.criticalConnections(n, connections)) |
bbc2190d5f7c22df9112331fb0bfb0ed9ddd3344 | ShaneRich5/fti-programming-training | /solutions/labs/lab2.1/indexing.py | 303 | 3.828125 | 4 | a = 'New York'
b = 'Grand Rapids'
c = 'San Francisco'
d = 'Houston'
e = 'Atlanta'
f = 'Boston'
#print the word 'Chicago' by only concatenating indexes from the variables above
result = c[c.find('c')].upper() + d[0].lower() + b[b.find('i')] + c[c.find('c')] + e[-1] + b[0].lower() + f[1]
print(result) |
9e8a000a85c65879900155aae6870a5385d5e218 | dlara10/DanielLara_hw13 | /DL_MontyHall.py | 1,274 | 3.84375 | 4 |
# coding: utf-8
# In[1]:
import numpy as num
import random
# In[6]:
#Funcion que definira lo que hay dentro de las puertas
def sort_doors():
a = ['goat', 'goat', 'car']
#Se usa la funcion random.shuffle para desordenar la lista
return random.shuffle(a)
print (sort_doors())
# In[10]:
#Funcion para escoger la puerta aleatoriamente
def choose_door():
#Se usa la funcion random.randrange para deolver un numero aleatorio
return random.randrange(3)
print (choose_door())
# In[ ]:
#Funcion que revelara lo que hay detras de a puerta
def reveal_door(lista, choice):
for i in range(len(lista)):
#Cuando la posicion sea distinta de la posicion actual cambiar el valor por el de cabra
if i != choice:
if lista[i] == 'goat':
lista[i] = 'GOAT_MONTY'
return lista
break
# In[ ]:
#Funcion que definira si el jugador cambio o no cambio de puerta
def finish_game(lista, choice, change):
if change == 'False':
return lista[choice]
else:
for i in range(len(lista)):
a = lista[choice]
if lista[i] == 'GOAT_MONTY':
b = lista[i]
lista.remove(b)
lista.remove(a)
return lista
|
9ce17714f2dbdfd1e2f4209b2e267bd18ce16252 | swiggins83/codeeval | /prime.py | 576 | 3.765625 | 4 | import sys
def primes(pathname):
dontuse = []
for line in open(pathname,'r').readlines():
n = int(line.split("\n")[0])
for i in range(1,n):
if i in dontuse:
print 'dont'
else:
if isprime(i, dontuse):
print i
def isprime(n, dontuse):
if n is 2:
return True
else:
for j in range(3,n):
if n % j is 0:
dontuse.append(j)
return False
return True
if __name__ == "__main__":
primes(sys.argv[1:])
|
2f210d2c95c9691de97826edc6deae7092877758 | danilodelucio/Exercicios_Curso_em_Video | /ex058.py | 606 | 3.84375 | 4 | from random import randint
print(('-' * 10) + ' JOGO DE ADIVINHAÇÃO ' + ('-' * 10))
n = int(randint(0, 5))
palpites = 0
user = int(input('Qual número que estou pensando? '))
done = False
while not done:
user = int(input('Que pena, você errou sonso!\nTente outra vez: '))
palpites += 1
if user == n:
done = True
else:
if user > n:
print('Quase... menos!')
elif user < n:
print('Quase... mais!')
print('Parabéns mizeravi, você acertou!')
print('O número pensado foi {}, e você acertou na {}ª tentativa.'.format(n, palpites + 1))
|
f41d9c423ead3ab6fd4fda15e8479fde85b78648 | saulo-lir/processamento-de-imagens-com-python-e-opencv | /processamento-de-imagens/01-introducao.py | 1,082 | 3.5625 | 4 | import cv2
'''
- Uma imagem colorida é formada por 3 canais de cores: Red, Green, Blue (RGB)
- Cada canal possui de 0 a 255 valores
- Ex.: Uma imagem que possui os canais: [255, 0, 0], terá a cor vermelha,
pois 255 na primeira posição equivale a cor máxima do vermelho, enquanto que
0 nas outras posições indica o valor nulo das suas respectivas cores.
- Cada pixel de uma imagem contém uma lista com os 3 canais RGB.
- Uma imagem é composta por uma matriz tridimensional. É como se tivéssemos uma
matriz em cima de outra matriz 3 vezes.
-- Na biblioteca Open CV, ao invés de ser usado o padrão RGB, é usado o BGR. Então,
na lista [255, 255, 255], temos Azul, Verde e Vermelho (que juntando fica branco).
'''
# Lendo uma imagem e transformando ela numa matriz tridimensional
image = cv2.imread('images/piscina-bolinhas.jpg')
print(image)
# Exibindo a imagem lida:
# Nome da janela, variável que contém os píxeis da imagem
cv2.imshow('Exibindo Imagem', image)
# Permite que a janela com a imagem fique aberta até pressionarmos qualquer tecla
cv2.waitKey(0) |
a1ef6e8c35ea2f9d1856de592b698f5e79228e15 | curiousguy13/project_euler | /pe14.py | 644 | 3.515625 | 4 |
def collatz(x):
'''brute force method '''
l=[]
while x!=1:
l.append(x)
if x%2==0:
x=x/2
else:
x=3*x+1
l.append(x)
return l
#print collatz(7)
l={1:1}
def collatz2(x):
'''dp method'''
count=0
if x in l :
return count+int(l[x])
else:
if x%2==0:
ans=x/2
else:
ans=3*x+1
l[x]=collatz2(ans)+1
return int(l[x])
print collatz2(1)
maxLen=0
maxPoint=0
for i in range(3,999999,2):
n=(collatz2(i))
if n>maxLen:
maxLen=n
maxPoint=i
print maxPoint
|
d09eb268c07099a82139981151793f539ea81272 | nemishzalavadiya/fake-news-predictor-NLP-Scikit-learn | /DataPreprocessing_with_countvectorizer.py | 869 | 3.734375 | 4 | # Import the necessary modules
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
# Print the head of df
print(df.head())
# Create a series to store the labels: y
y = df.label
# Create training and test sets
X_train, X_test, y_train, y_test = train_test_split(df['text'],y,test_size=0.33,random_state=53)
# Initialize a CountVectorizer object: count_vectorizer
count_vectorizer = CountVectorizer(stop_words='english')
# Transform the training data using only the 'text' column values: count_train
count_train = count_vectorizer.fit_transform(X_train)
# Transform the test data using only the 'text' column values: count_test
count_test = count_vectorizer.transform(X_test)
# Print the first 10 features of the count_vectorizer
print(count_vectorizer.get_feature_names()[:10]) |
b18923b3488d1c1f9838949e4a66cfe6f5e63672 | toberge/python-exercises | /exams/actual/tee.py | 1,602 | 3.609375 | 4 | #!/usr/bin/env python3
import sys # for args and stdin
import argparse
def print_usage():
print('Usage: tee [-a] [FILE]\n-a: Append to file\nIf -a is set FILE must be present')
def read_and_output(outfile=None):
"""Read from stdin and write to stdout + file if any"""
for line in sys.stdin:
# Using write() to avoid having end=''
sys.stdout.write(line)
if outfile:
outfile.write(line)
if __name__ == '__main__':
# Set default values for variables...
file_mode = 'w+'
filename = ''
# Check for the only cmd-option and wether a file is provided or not
# (this is simple enough that argparser is not needed)
if len(sys.argv) == 3 and sys.argv[1] == '-a':
# Append!
file_mode = 'a+'
filename = sys.argv[2]
elif len(sys.argv) == 2:
# Overwrite!
filename = sys.argv[1]
elif len(sys.argv) != 1:
# Without a file, there should be no arguments!
print_usage()
exit(1)
# Write to file if and only if a file is provided!
if filename:
try:
# try opening file (with automatically closes it afterwards)
with open(filename, file_mode) as file:
read_and_output(outfile=file)
except OSError as error:
# This would happen if, say, the user does not have permission to access that file
# or there is an I/O error of some kind
print(f'Error: Could not write to file!\nReason: {error}')
exit(1)
else:
# Otherwise, no file.
read_and_output() |
074660b121de73f1b2450bc2eb34849d49e798c8 | sherryxiata/zcyNowcoder | /lucky.py | 3,609 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/18 11:23
# @Author : wenlei
# 队列和栈(collections包中的deque双向队列,性能最好)
import collections
deque = collections.deque() # 创建双向队列/栈
deque.append(x) # 插入元素到队尾(队列)
deque.appendleft(x) # 插入元素到队头(栈)
# deque.pop() # 弹出队尾元素
deque.popleft() # 从队头弹出元素(√)
deque[0] # 队头/栈顶元素
len(deque) # 队列/栈大小
# 栈
class Stack():
def __init__(self):
self.arr = []
def push(self, num):
self.arr.append(num)
def pop(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr.pop())
def peek(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr[-1])
def isEmpty(self):
if not self.arr or len(self.arr) < 1:
return True
# 队列
class Queue():
def __init__(self):
self.arr = []
def push(self, num):
self.arr.append(num)
def pop(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr.pop(0))
def peek(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr[0])
def isEmpty(self):
if not self.arr or len(self.arr) < 1:
return True
def size(self):
return len(self.arr)
# 队列(queue包中的Queue)
import queue
q = queue.Queue() # 创建队列
q.put(1) # 插入元素
q.get() # 弹出元素
q.qsize() # 队列大小
q.empty() # 判断队列是否为空
# 判断队列是否为空
# 小根堆(python默认为小根堆)
import heapq
heap = [] # 初始化一个空堆
heapq.heapify(heap) # 将某个数组初始化为小根堆
heapq.heappush(heap, x) # 插入元素
heapq.heappop(heap) # 弹出堆顶元素(最小值)
heap[0] # 获得堆顶元素
len(heap) # 堆的大小
not heap # 堆为空
# 大根堆(需要取反放入小根堆)
import heapq
heap = [] # 初始化一个空堆
heapq.heapify(heap) # 将某个数组初始化为小根堆,此时heap中的元素应该取反
heapq.heappush(heap, - x) # 插入元素
- heapq.heappop(heap) # 弹出堆顶元素(最大值)
- heap[0] # 获得堆顶元素
len(heap) # 堆的大小
not heap # 堆为空
# 比较器1
import functools
def myComparator(s1, s2):
if (s1 + s2) < (s2 + s1):
return -1 # s1比较小
elif (s1 + s2) > (s2 + s1):
return 1 # s1比较大
else:
return 0
def lowestString(strs):
sort_strs = sorted(strs, key = functools.cmp_to_key(myComparator))
# 比较器2
students_tuples = [('join', 'a', 15), ('kane', 'b', 20), ('pole', 'c', 30)]
sorted(students_tuples, key = lambda student: student[2])
print(students_tuples)
# 交换
def swap(arr, i, j):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
def swap(arr, i, j):
arr[i] = arr[i] ^ arr[j]
arr[j] = arr[i] ^ arr[j]
arr[i] = arr[i] ^ arr[j]
a, b = b, a
# 读文件操作
f = open('./practice/article.txt')
data1 = f.read() # 一次性读出整个文件
while True:
data2 = f.read(10) # 每次读长度为10的字符串
if not data2: break
# 每次读一行
for line in f.readlines():
print(line)
# 将文件作为一个迭代器读取
with open('./practice/article.txt') as f:
for line in f:
print(line)
# 遍历dict
dic = {'a': 1, 'b': 2, 'c': 3}
dic.keys()
dic.values()
dic.pop('b')
for k, v in dic.items():
print(k, v)
|
1de49b4cdfe20e30d5f223e3a0e355d56003a158 | tkqlzz/baekjoon | /1197.py | 1,079 | 3.609375 | 4 | parent = dict()
rank = dict()
def make_set(v):
parent[v] = v
rank[v] = 0
def find(v):
if parent[v] != v:
parent[v] = find(parent[v])
return parent[v]
def union(v1, v2):
root1 = find(v1)
root2 = find(v2)
if root1 != root2:
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
parent[root1] = root2
if rank[root1] == rank[root2]:
rank[root2] += 1
def kruskal():
for v in vertices:
make_set(v)
minimum_spanning_tree = set()
edges.sort()
for edge in edges:
w, v1, v2 = edge
if find(v1) != find(v2):
union(v1, v2)
minimum_spanning_tree.add(edge)
return minimum_spanning_tree
v, e = map(int, input().split())
vertices = [i for i in range(1, v + 1)]
edges = []
for i in range(e):
v1, v2, w = map(int, input().split())
edges.append((w, v1, v2))
graph = {'vertices': vertices,
'edges': edges
}
mst = kruskal()
s = 0
for w, v1, v2 in mst:
s += w
print(s)
print(parent) |
6777724ebd2e33d497df8b5ed4ebb2bd488f9b5c | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_37/153.py | 922 | 3.546875 | 4 | #!/usr/bin/env python
import sys
import pdb
def base10toN(num, n):
s = ''
while 1:
remainder = num % n
s = str(remainder) + s
num = num / n
if num == 0:
break
return s
def happytest(num, base, numlist=[]):
if num == 1:
return True
else:
if num in numlist:
return False
numlist.append(num)
string = base10toN(num, base)
next = sum([int(char)**2 for char in string])
return happytest(next, base, numlist)
def printer(result, num):
print 'Case #%d: %d' % (num, result)
f = open (sys.argv[1], 'r')
T = int(f.readline())
for i in range(T):
bases = f.readline().split()
inte = 2
while True:
happy = True
for base in bases:
happy &= happytest(inte, int(base), [])
if happy:
printer(inte, i + 1)
break
inte += 1
|
6363867f69aa003b838c0c64e726ef00abb06a69 | abdul8117/igcse-cs | /Programming Challenges/N4-Q10.py | 378 | 3.890625 | 4 | par3 = int(input("How many par 3 holes are there?\n"))
par4 = int(input("How many par 4 holes are there?\n"))
par5 = int(input("How many par 5 holes are there?\n"))
par3 = par3 * 3
par4 = par4 * 4
par5 = par5 * 5
difficulty = int(input("What is the difficulty adjustment for the course?\n"))
print(f"The Standard Scratch for the course is: {par3 + par4 + par5 + difficulty}") |
6ce561986eb820cb01e4a4b6708387233c18f5df | AndrewFendrich/Mandelbrot | /gradient4.py | 2,313 | 3.6875 | 4 | #def gradient_list((R1,G1,B1),(R2,G2,B2),steps):
#import sys,os
def gradient_list(Color1,Color2,steps):
gradientList = []
if Color2[0] > Color1[0]:
rinterval = (Color2[0]-Color1[0])/steps*6
else:
rinterval = (Color1[0]-Color2[0])/steps*6
if Color2[1] > Color1[1]:
ginterval = (Color2[1]-Color1[1])/steps*6
else:
ginterval = (Color1[1]-Color2[1])/steps*6
if Color2[2] > Color1[2]:
binterval = (Color2[2]-Color1[2])/steps*6
else:
binterval = (Color1[2]-Color2[2])/steps*6
### Need to make up the difference between the loops and the total number
### of colors to be created "steps"
redsteps = 1 + int(steps/6)
greensteps = 1 + int(steps/6)
bluesteps = 1 + int(steps/6)
# print("redsteps:",redsteps," greensteps:",greensteps," bluesteps:",bluesteps)
# missingsteps = steps - (2*redsteps) - (2*greensteps) - (2*bluesteps)
# if not (missingsteps == 0):
# redsteps = redsteps + missingsteps
# if not (rinterval+ginterval+binterval == steps):
# print("steps:",steps,"steps/6:",steps/6)
# print("missingsteps:",missingsteps)
# print("redsteps:",redsteps," greensteps:",greensteps," bluesteps:",bluesteps)
# print("rinterval:",rinterval,"ginterval:",ginterval,"binterval:",binterval)
for i in range(redsteps):
rc1 = int(Color1[0] +rinterval)
gradientList.append(((rc1*i,0,0)))
for i in range(redsteps):
if i % 2 > 0:
rc2 = int(rinterval * i)
gradientList.append((rc2,rc2,rc2))
elif i % 2 > 0:
rc2 = (Color2[0] - int(rinterval * i))
gradientList.append((rc2,rc2,rc2))
for i in range(greensteps):
gc1 = int(Color1[1] +ginterval)
gradientList.append((0,gc1*i,0))
for i in range(greensteps):
gc2 = Color2[1] - int(ginterval * i)
gradientList.append((gc2,gc2,gc2))
for i in range(bluesteps):
bc1 = int(Color1[2] +binterval)
gradientList.append((0,0,bc1*i))
for i in range(bluesteps):
bc2 = Color2[2] - int(binterval * i)
gradientList.append((bc2,bc2,bc2))
missingcolors = steps - len(gradientList)
for i in range(missingcolors):
gradientList.append((255,200,60))
return gradientList
|
88e8668381f49943898eb7f2ca10056479ed3d0d | ChikusMOC/Exercicios-Capitulo-5 | /cap5_ex2.py | 138 | 4.09375 | 4 | """
Exercicio 2
"""
numero = float(input("Digite um numero:"))
if numero >= 0:
print(numero**0.5)
else:
print('numero invalido') |
21a9bfcb8a6c41e72bfea1d538fd2cf3360f9651 | sarahvestal/ifsc-1202 | /Unit 2/02.10 First Digit After Decimal.py | 294 | 4.21875 | 4 | #Prompt for a positive real number
#Print the first digit to the right of the decimal point.
#Enter Number: 1.79
#Tenths Value: 7
number = float(input("Enter a positive real number: "))
onedigitright = int(number % 1 * 10)
print ("First digit to right of decimal: {}".format (onedigitright,1)) |
5613367aed64de5744756afec88e8f010125a21c | dsli208/CSE-307-Programming | /simplecalc/SimpleCalc/calcparser.py | 1,667 | 3.6875 | 4 | # -----------------------------------------------------------------------------
# calcparser.py
#
# A simple calculator with variables.
# The example from http://www.dabeaz.com/ply/example.html
# broken down into separate lexer, parser, and main (top-level) files
#
# This is the parser
#
# -----------------------------------------------------------------------------
import ply.yacc as yacc
from calclexer import tokens
# Parsing rules
precedence = (
('left','PLUS','MINUS'),
('left','TIMES','DIVIDE'),
('nonassoc','UMINUS'),
)
# dictionary of names
names = {}
def p_statement_assign(t):
'statement : NAME EQUALS expression'
names[t[1]] = t[3]
print t[3]
def p_statement_expr(t):
'statement : expression'
print(t[1])
def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression'''
if t[2] == '+' : t[0] = t[1] + t[3]
elif t[2] == '-': t[0] = t[1] - t[3]
elif t[2] == '*': t[0] = t[1] * t[3]
elif t[2] == '/': t[0] = t[1] / t[3]
def p_expression_uminus(t):
'expression : MINUS expression %prec UMINUS'
t[0] = -t[2]
def p_expression_group(t):
'expression : LPAREN expression RPAREN'
t[0] = t[2]
def p_expression_number(t):
'expression : NUMBER'
t[0] = t[1]
def p_expression_name(t):
'expression : NAME'
try:
t[0] = names[t[1]]
except LookupError:
print("Undefined name '%s'" % t[1])
t[0] = 0
def p_error(t):
print("Syntax error at '%s'" % t.value)
parser = yacc.yacc()
|
c818a88b124ee3ec277d628aca09819c3a7be742 | BryantHall/Enigma | /analysis.py | 2,310 | 3.625 | 4 | #Attempt to decrpyt the cipher using frequency based probability
import csv
#List of character frequency
alphabetTable = [' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
conversionTable = [' ','e','t','a','o','n','r','i','s','h','d','l','f','c','m','u','g','y','p','w','b','v','k','x','j','q','z']
#punctuationTable = [',',':','(',')',';','.','?','!']
charSum = [0] * 27
oldSum = [0] * 27
#read in .csv file
with open('dataF.csv') as csvfile:
fileData = csv.reader(csvfile,delimiter=',')
#sum number of characters
for column in fileData:
for i in range(0,len(alphabetTable)):
if column[1] == alphabetTable[i]:
charSum[i] = charSum[i] + 1
#save old fequency table and newly sorted frequency table
for i in range(0,len(charSum)):
oldSum[i] = charSum[i]
charSum.sort(reverse = True)
#debug
print(charSum)
#This will be the decrypting cipher
key = []
for i in range(0,len(alphabetTable)):
for j in range(0,len(conversionTable)):
#every a goes to t
#if(j > 0 and j < (len(conversionTable) - 1) and charSum[j] == charSum[j-1]):
#key.append(conversionTable[j + 1])
# charSum[j-1] = -1
# break
if(oldSum[i] == charSum[j]):
key.append(conversionTable[j])
charSum[j] = -1
break
#write out file
with open('dataF.csv') as csvfile:
fileData = csv.reader(csvfile,delimiter=',')
#open output file
output = open("converted.txt", "w")
for column in fileData:
for i in range(0,len(alphabetTable)):
if(column[1] == alphabetTable[i]):
cipherChar = key[i]
output.write(cipherChar)
break
output.close()
#write to csv file
#with open('converted.csv', 'w',newline='') as file:
# writer = csv.writer(file)
# for i in range(0,360):
# for j in range(0,len(alphabetTable)):
# if(oldSum[] == charSum[]):
## column[0] = conversionTable[]
# writer.writerow(column[0])
## break
##
#debug
print(key)
print(oldSum)
print(charSum)
#['t', 'j', 'y', 'm', 's', 'i', 'p', 'w', 'n', 'd', 'k', 'v', 'l', 'u', 'e', 'h', 'b', 'z', 'r', 'o', 'f', 'a', 'x', 'g', 'q', 'c'] |
a1c3160d5d04457d0ec97610f5680403c3d8ee80 | MichelleZ/leetcode | /algorithms/python/binaryTreePaths/binaryTreePaths.py | 873 | 4.0625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/binary-tree-paths/
# Author: Miao Zhang
# Date: 2021-01-29
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
self.dfs(root, '', res)
return res
def dfs(self, node: TreeNode, path: str, res: List[str]) -> None:
if not node: return
if not node.left and not node.right:
res.append(path + str(node.val))
return
if node.left:
self.dfs(node.left, path + str(node.val) + '->', res)
if node.right:
self.dfs(node.right, path + str(node.val) + '->', res)
|
91bf845015a139150522d63df93a2d3aae3f05e0 | Matheus654/ifpi_ads_2020 | /Q13_F2b_crime.py | 749 | 3.875 | 4 | def main():
a = input("Telefonou para a vítima?")
b = input("Esteve no local do crime?")
c = input("Mora perto da vítima?")
d = input("Devia para a vítima?")
e = input("Já trabalhou com a vítima?")
verifica_crime(a, b, c, d, e)
def verifica_crime(a, b, c, d, e):
x = 0
if a == "sim":
x = 1
if b == "sim":
x += 1
if c == "sim":
x = x + 1
if d =="sim":
x += 1
if e == "sim":
x += 1
if x == 5:
print("Você é o assassino")
if x == 4 or x == 3:
print("Você é cúmplice")
if x == 2:
print("Você é suspeito")
if x == 1 or x == 0:
print("Você é inocente")
main() |
ff94cc873510e1e7de440adcdbe16507ce9b51fe | sethi-bhumika/RISC-V-Simulator | /Phase1/src/MachineCodeParser.py | 2,001 | 3.828125 | 4 | # module to parse instructions in machine code and store them in PC_INST
import sys
PC_INST={} # dictionary with key as PC, value as instruction
# function to parse the instructions
# comments start with #
# comment feature is just for ease to paste code from venus
def parser(FileName):
instructions=open(FileName,'r') # file containing the instructions
# format-
# PC INST -> in hex format
line_number=0
for line in instructions:
line_number=line_number+1
line=line.strip() # removing unnecessary whitespaces \t, \n etc
if line=='' or line[0]=='#': # ignores empty lines and commented lines.
continue
line=line.split('#')[0] # splitting the string into PC and INST word and ignoring comments
line=line.strip().split()
if len(line)!=2: # line should contain exactly 2 items.
print(f"Line {line_number}: Invalid syntax")
sys.exit()
# parser will treat numbers entered without 0x as decimal, and with 0x as hexadecimal
try:
line[0]=int(line[0]) # interpreted as base 10
except: # number entered is not decimal
try:
line[0]=int(line[0],16) # interpreted as base 16
except: # str is neither decimal nor hex
print(f"Line {line_number}: Invalid program counter (PC)")
sys.exit()
try:
line[1]=int(line[1]) # interpreted as base 10
except:
try:
line[1]=int(line[1], 16) # interpreted as base 16
except:
print(f"Line {line_number}: Invalid instruction format")
sys.exit()
if(line[0]>0xffffffff):
print(f"Line {line_number}: PC out of range")
sys.exit()
if(line[1]>0xffffffff):
print(f"Line {line_number}: Instruction word out of range")
sys.exit()
PC_INST[line[0]]=line[1]
instructions.close()
#print(line)
|
118e671fa96bc010cb1dcef83a6faf7b74eaba02 | ariscon/DataCamp_Files | /22-introduction-to-time-series-analysis-in-python/03-autoregressive-ar-models/02-compare-the-acf-for-serval-ar-time-series.py | 1,411 | 3.53125 | 4 | '''
Compare the ACF for Several AR Time Series
The autocorrelation function decays exponentially for an AR time series at a rate of the AR parameter. For example, if the AR parameter, ϕ=+0.9
ϕ
=
+
0.9
, the first-lag autocorrelation will be 0.9, the second-lag will be (0.9)2=0.81
(
0.9
)
2
=
0.81
, the third-lag will be (0.9)3=0.729
(
0.9
)
3
=
0.729
, etc. A smaller AR parameter will have a steeper decay, and for a negative AR parameter, say -0.9, the decay will flip signs, so the first-lag autocorrelation will be -0.9, the second-lag will be (−0.9)2=0.81
(
−
0.9
)
2
=
0.81
, the third-lag will be (−0.9)3=−0.729
(
−
0.9
)
3
=
−
0.729
, etc.
The object simulated_data_1 is the simulated time series with an AR parameter of +0.9, simulated_data_2 is for an AR paramter of -0.9, and simulated_data_3 is for an AR parameter of 0.3
INSTRUCTIONS
100XP
Compute the autocorrelation function for each of the three simulated datasets using the plot_acf function with 20 lags (and supress the confidence intervals by setting alpha=1).
'''
# Import the plot_acf module from statsmodels
from statsmodels.graphics.tsaplots import plot_acf
# Plot 1: AR parameter = +0.9
plot_acf(simulated_data_1, alpha=1, lags=20)
plt.show()
# Plot 2: AR parameter = -0.9
plot_acf(simulated_data_2, alpha=1, lags=20)
plt.show()
# Plot 3: AR parameter = +0.3
plot_acf(simulated_data_3, alpha=1, lags=20)
plt.show() |
4e564ab3ca5dbe4e45ffc8cc3c2afcfe072f11ca | rjamadar/python | /lab 3.2.py | 623 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 16:23:49 2020
@author: Russell
"""
#read the number from user input
userInput = float(input("Enter a number:"))
#nested condition
if userInput == 0.0 :
print("zero")
else :
#display positive or negative
if userInput > 0:
print("positive")
else :
print("negative")
#display the absolute
if abs(userInput) > 1000000:
print("Its a large number")
elif abs(userInput < 1) :
print("Its a small number")
else:
print("Not too big or not too small") |
cab24c0eeb9632efdcc718ab9f388483f8941a6a | tomhel/AoC | /2022/day18/1.py | 432 | 3.734375 | 4 | def load():
with open("input") as f:
for row in f:
yield tuple(int(x) for x in row.strip().split(","))
def surface_area():
cubes = set(load())
count = 0
for x, y, z in cubes:
for dx, dy, dz in ((0, 0, 1), (0, 0, -1), (0, 1, 0), (0, -1, 0), (1, 0, 0), (-1, 0, 0)):
if (x + dx, y + dy, z + dz) not in cubes:
count += 1
return count
print(surface_area())
|
3ce0163059f9ae725371954b061f1b9ad217acde | pb593/cam | /II/BioInf/lcs.py | 708 | 3.734375 | 4 | #!/usr/bin/python
# Longest Common Subsequence using dynamic programming
import pprint, time, os
pp = pprint.PrettyPrinter()
if __name__ == "__main__":
s1 = "abdce"
s2 = "abecdx"
l1 = len(s1)
l2 = len(s2)
mtx = [[0 for x in range(l2 + 1)] for x in range(l1 + 1)]
for i in range(1, l1 + 1):
for j in range(1, l2 + 1):
mtx[i][j] = max(mtx[i-1][j], mtx[i][j-1], mtx[i-1][j-1] + 1 if s1[i-1] == s2[j-1] else 0)
os.system("clear")
pp.pprint(mtx)
time.sleep(0.5)
print "The longest common subsequence of %s and %s has length %d" % (s1, s2, mtx[l1][l2])
|
a909f8cf80fba0e5e1a72abe28f6e75f00b7faa6 | alexandredorais/project-euler-solutions | /Pb 6 - Sum square difference/main.py | 1,826 | 3.921875 | 4 | """
From : https://projecteuler.net/problem=6
Context : The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
3025 − 385 = 2640.
Goal : Find the difference between the sum of the squares of the first one hundred natural numbers and the square of
the sum.
Author : Alexandre Dorais
"""
# This problem could seem complicated at first glance, especially if we replace the first hundred natural numbers by the
# first thousand, or the first million natural numbers. Then, it would seem like we would have to calculate the two
# gigantic sums and then find their difference. However, there actually exists a closed-form expression to calculate the
# sum of the first n natural numbers. We have that sum(1,2,3,...,n) = n*(n+1)/2. For example, sum(1) = 1*2/2 = 1;
# sum(1,2) = 2*3/2=3; sum(1,2,3) = 3*4/2 = 6, etc. In the same way, there also exists a simple expression to calculate
# the sum of the first n square numbers. We have that sum(1^2,2^2,3^2,...,n^2) = n*(n+1)*(2n+1)/6. For example
# sum(1^2) = 1*2*3/6 = 1; sum(1^2,2^2) = 2*3*5/6 = 5; sum(1^2,2^2,3^2) = 3*4*7/6 = 14, etc. This problem has thus become
# ridiculously easy with this simple trick.
# Input the upper number (100 in our case)
M = int(input('We want the difference between the sum of the squares and the square of the sum of the numbers from 1 to : '))
# Calculate sum of squares
sum_squares = M*(M+1)*(2*M+1)/6
# Calculate square of the sum
square_of_sum = (M*(M+1)/2)**2
# Calculate the difference between the two
answer = int(square_of_sum - sum_squares)
print(answer)
|
ab73dd5665004c86af1f878613c333fc2a2a499b | mKleinCreative/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 188 | 3.5625 | 4 | #!/usr/bin/python3
for value in range(1, 80):
if (int(str(value).zfill(2)[1]) - int(str(value).zfill(2)[0])) > 0:
print('{}'.format(str(value)).zfill(2), end=', ')
print('89')
|
5ba5b8428a7de0d0c617cb0c5097dcfa1d382db0 | murdock07/raspi | /keypassing.py | 786 | 4.28125 | 4 | #!/usr/bin/python3
#keypassing.py
import encryptdecrypt as ENC
KEY1 = 20
KEY2 = 50
print ("Please enter text to scramble:")
#Get user input
user_input = input()
#Send message out
encodeKEY1 = ENC.encryptText(user_input,KEY1)
print ("USER1: Send message encrypted with KEY1 (KEY1): " + encodeKEY1)
#Reciever encrypts the message again
encodeKEY1KEY2 = ENC.encryptText(encodeKEY1,KEY2)
print ("USER2: Encrypt with KEY2 & returns it (KEY1+KEY2): " + encodeKEY1KEY2)
#Remove the original encoding
encodeKEY2 = ENC.encryptText(encodeKEY1KEY2,-KEY1)
print ("USER1: Removes KEY1 & returns it with just KEY2 (KEY2): " + encodeKEY2)
#Reciever removes their encryption
message_result = ENC.encryptText(encodeKEY2, -KEY2)
print ("USER2: Removes KEY2 & Message received: " + message_result)
#END
|
f60123efd3e4a66196f80638a8fcbfe9ea3806fa | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex11_2.py | 670 | 4.1875 | 4 | # Chapter 11
# Exercise 2: Write a program to look for lines of the form
# `New Revision: 39772`
# and extract the number from each of the lines using a regular expression and
# the findall() method. Compute the average of the numbers and print out the
# average.
# Enter file:mbox.txt
# 38549.7949721
# Enter file:mbox-short.txt
# 39756.9259259
import re
count = 0
total = 0
fname = input('Enter file name: ')
fh = open(fname)
for line in fh:
line = line.rstrip()
x = re.findall('^New Revision:',line)
if len(x)>0:
count = count+1
x = line.split()
total = total + float(x[2])
avg = total/count
print(avg)
|
5c1d605dc760b118213f7fe38045938bb6d8da1c | Aayuayushi/python-codes | /practice.py | 159 | 3.8125 | 4 |
list1 = [11, 5, 17, 18, 23]
print("Sum of all elements in given list: ")
def add():
return(+)
def total(list1):
return(add(list1))
y=total(list1)
print(y)
|
8ea627a29aff928a515e60e98137b5066c6c8ecd | kristen-schneider/friendship_algorithm | /kate_bubar.py | 2,905 | 4.21875 | 4 | import sys
## Function to play friendship algorithm game
def play_game():
## START GAME
# initialize the user input to 0
user_entry = 0
# ask the user to make their own input (1 to play or 2 to exit):
while user_entry != 1 and user_entry != 2:
user_entry = int(input('Select Option!\n1. Play Game\n2. Exit Game\n\nYour Selection: '))
while user_entry == 1:
## STEP 1 HERE
total_points = 0
answer_one = int(input("Which TV Show is better?\n1. Friends\n2. How I Met Your Mother\n3. I don't like either\n4. I can't decide\n5. I haven't seen either\n"))
## STEP 2&3 HERE
if answer_one == 1: total_points += 4
elif answer_one == 2: total_points += 0
elif answer_one == 3: total_points -= 4
elif answer_one == 4: total_points += 2
else: total_points -= 2
## STEP 4 HERE
# print(total_points)
## STEP 1 HERE
answer_two = int(input("How do you feel about kombucha?\n1. LOVE \n2. It's fine\n3. it's gross\n4. what is kombucha?\n5. it's SUPER gross\n"))
## STEP 2&3 HERE
if answer_two == 1: total_points += 4
elif answer_two == 2: total_points += 2
elif answer_two == 3: total_points -= 2
elif answer_two == 4: total_points -= 2
else: total_points -= 4
## STEP 4 HERE
# print(total_points)
## STEP 1 HERE
answer_three = int(input("Do you like to hike?\n1. yes\n2. kinda \n3. naw not really my thing\n4. absolutely not\n"))
## STEP 2&3 HERE
if answer_three == 1: total_points += 4
elif answer_three == 2: total_points += 2
elif answer_three == 3: total_points -= 2
else: total_points -= 4
## STEP 4 HERE
# print(total_points)
if answer_three == 1:
answer_four = int(input("what is your general hiking attitude?\n1. let's RUN up the mountain\n2. I like a good workout but let's not die\n3. pretty leisurely\n4. not a lot of hiking, BUT let's take a million pictures\n"))
if answer_four == 1: total_points += 0
elif answer_four == 2: total_points += 4
elif answer_four == 3: total_points +=2
else: total_points -= 4
answer_five = int(input("Do you like dogs?\n1. yes\n2. kinda\n3. no"))
if answer_five == 1: total_points += 4
elif answer_five == 2: total_points += 2
else: total_points -= 4
# print(total_points)
## Find out if you can be friends!!
if total_points >= 10: print("\nYAY best friend material")
elif total_points >= 6: print("\nsweeeeeeeeet we can be friends!")
else: print("\n Yikes friendship could be rough\n")
user_entry = input('\nSelect Option!\n1. Play Game\n2. Exit Game\n\nYour Selection: ')
## Function call to play friendship algorithm game
play_game()
|
0c293e479c533185fe79401556a2fd3105e6a907 | Aasthaengg/IBMdataset | /Python_codes/p03252/s955553615.py | 426 | 3.78125 | 4 | def main():
dic1 = {}
dic2 = {}
S = list(input().rstrip())
T = list(input().rstrip())
for s, t in zip(S, T):
if s not in dic1:
dic1[s] = t
elif dic1[s] != t:
print('No')
exit()
if t not in dic2:
dic2[t] = s
elif dic2[t] != s:
print('No')
exit()
print('Yes')
if __name__ == '__main__':
main()
|
18b4adf9fe34cfe7b1881222db2e567256480eb8 | mehlj/challenges | /reduce_to_zero/reduce_to_zero.py | 656 | 4.21875 | 4 | def numberOfSteps(num):
"""
Determines the amount of iterations needed to reach zero starting from num
Ex: numberOfSteps(16) --> 5
@param num: Integer that needs to reach zero
@return: Number of iterations needed to reach zero
"""
counter = 0
while num != 0:
if num % 2 == 0:
print(str(num) + " is even; divide by 2 and obtain " + str((num // 2)) + ".")
counter += 1
num = num // 2
else:
print(str(num) + " is odd; subtract 1 and obtain " + str((num - 1)) + ".")
counter += 1
num = num - 1
return counter
print(numberOfSteps(16)) |
434a92e1dd8b91569caf3240524845ec061fa275 | rajlath/rkl_codes | /LeetCode_Top_100/max_dept_BT_133.py | 1,149 | 4.21875 | 4 | '''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest
leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
'''
# -*- coding: utf-8 -*-
# @Date : 2018-09-25 09:09:17
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : link
# @Version : 1.0.0
from sys import stdin
max_val=int(10e12)
min_val=int(-10e12)
def read_int() : return int(stdin.readline())
def read_ints() : return [int(x) for x in stdin.readline().split()]
def read_str() : return input()
def read_strs() : return [x for x in stdin.readline().split()]
# 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return 1 + max(self.maxDepth(root.left) , self.maxDepth(root.right)) |
d15b16b6302cd426d7c1ad4d935bb9304c160974 | MadhuriSarode/Python | /ICP1/Source Code/Replace.py | 478 | 4.65625 | 5 | # Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
string_a = input("Enter the string to be replaced: ") # Accept the string from user
string_b = string_a.replace("python", "pythons") # replace the python word with pythons
print("Original string = ", string_a) # print the string
print("Replaced string = ", string_b) # print replaced string
|
48c01674c092c13209e109ce99bd91f1015220e4 | qhuydtvt/C4E3 | /Assignment_Submission/hant/7.2.py | 615 | 3.71875 | 4 | n = [int(x) for x in input('input point one and point two:').split()]
m= input('operation:')
def calculate(number1,number2,operation):
if m=='add':
a=n[0]+n[1]
print(str.format('{0} + {1} = {2}',n[0],n[1],a))
return a
if m=='subtract':
a=n[0]-n[1]
print(str.format('{0} - {a} = {2}',n[0],n[1],a))
return a
if m=='multiply':
a=n[0]*n[1]
print(str.format('{0} x {1} = {2}',n[0],n[1],a))
return a
if m=='divede':
a=n[0]+n[1]
print(str.format('{0} : {1} = {2}',n[0],n[1],a))
return a
calculate(n[0],n[1],m)
|
fd96ad5f776c0c010dddd6e42da93e3ae19f9e8c | HANEESH-TANNERU/CS-5590-PYTHON | /ICP 1/first.py | 101 | 3.53125 | 4 | h = input("enter the string:")
g= h[::-1]
n = g[:2] + g[3:]
w=n[:1] + n[2:]
print ("",g)
print("",w)
|
c34dc6299063eb6ba425a7ce3a16e710f9411dbd | StefiOs/Python_Shapes | /rectangle.py | 755 | 3.96875 | 4 | name = input('What is the name of the customer? ')
address = input('What is the address of the customer? ')
length = eval(input('What is the length of the room (in feet)? '))
width = eval(input('What is the width of the room (in feet)?'))
area = length*width
flooring = (2)
installation = (1.5)
print('Estimate for', name)
print('Address:', address)
print('Circle room with an area of', area, 'square feet.')
print('Estimated cost for flooring is ','$',flooring*area,'.', sep='')
print('Estimated cost for installation is ', '$', installation*area,'.', sep='')
flooringcost= flooring*area
installationcost= installation*area
print('Total estimate is ','$', flooringcost+installationcost,'.', sep='')
print('Thank you for your business!')
|
fb691d6b6e44a03b64c14c27d465cd7025fbe2b6 | The-Mad-Pirate/Clyther | /doc/perfpy/core.py | 2,153 | 3.59375 | 4 | '''
Created on Dec 22, 2011
@author: sean
'''
class Grid(object):
"""A simple grid class that stores the details and solution of the
computational grid."""
def __init__(self, np, nx=10, ny=10, xmin=0.0, xmax=1.0,
ymin=0.0, ymax=1.0):
self.np = np
self.xmin, self.xmax, self.ymin, self.ymax = xmin, xmax, ymin, ymax
self.dx = float(xmax - xmin) / (nx - 1)
self.dy = float(ymax - ymin) / (ny - 1)
self.u = np.zeros((nx, ny), 'f')
# used to compute the change in solution in some of the methods.
self.old_u = self.u.copy()
def setBC(self, l, r, b, t):
"""Sets the boundary condition given the left, right, bottom
and top values (or arrays)"""
self.u[0, :] = l
self.u[-1, :] = r
self.u[:, 0] = b
self.u[:, -1] = t
self.old_u = self.u.copy()
def setBCFunc(self, func):
"""Sets the BC given a function of two variables."""
xmin, ymin = self.xmin, self.ymin
xmax, ymax = self.xmax, self.ymax
x = self.np.arange(xmin, xmax + self.dx * 0.5, self.dx)
y = self.np.arange(ymin, ymax + self.dy * 0.5, self.dy)
self.u[0 , :] = func(xmin, y)
self.u[-1, :] = func(xmax, y)
self.u[:, 0] = func(x, ymin)
self.u[:, -1] = func(x, ymax)
def computeError(self):
"""Computes absolute error using an L2 norm for the solution.
This requires that self.u and self.old_u must be appropriately
setup."""
v = (self.u - self.old_u).flat
return self.np.sqrt(self.np.dot(v, v))
class TimeSteper(object):
@classmethod
def create_grid(cls, nx=500, ny=500):
import numpy as np
g = Grid(np, nx, ny)
return g
@classmethod
def finish(cls, grid):
pass
timestep_methods = {}
get_title = lambda func: func.__doc__.splitlines()[0].strip()
def available(test):
def decorator(func):
func.available = bool(test)
timestep_methods[get_title(func)] = func
return func
return decorator
|
08d7206c4f2848babd17ec330bea8895e06d0076 | isabellahenriques/Python_Estudos | /ex070.py | 1,172 | 4.0625 | 4 | '''Crie um programa que leia o nome e o preço de vários produtos.
O programa deverá perguntar se o usuário vai continuar ou não.
No final, mostre:
A) qual é o total gasto na compra.
B) quantos produtos custam mais de R$1000.
C) qual é o nome do produto mais barato
'''
print("-" * 32)
print("LOJA SUPER BARATÃO")
print("-" * 32)
total = 0
totMil = 0
menorPreco = 0
contador = 0
barato = " "
while True:
produto = str(input("Nome do produto: "))
preco = float(input("Preco R$ "))
contador = contador + 1
total = total + preco
if preco > 1000:
totMil = totMil + 1
if contador == 1:
menorPreco = preco
barato = produto
else:
if preco < menorPreco:
menorPreco = preco
barato = produto
continuar = " "
while continuar not in "SN":
continuar = str(input("Quer continuar: [S/N] ")).upper()[0].strip()
if continuar == "N":
break
print("-" * 8 + "FIM DO PROGRAMA" + "-" * 8)
print(f"O total de compras foi R$ {total:.2f}")
print(f"Temos {totMil} produtos custando mais de R$ 1000.00")
print(f"O produto mais barato foi {barato} que custou R$ {menorPreco:.2f}")
|
8ef3756c10763eb16f373099f6238de90210657a | Chencheng78/python-learning | /checkio/robot-sort.py | 331 | 4.03125 | 4 | def swapsort(sequence):
seq = list(sequence)
count = []
while seq != sorted(seq):
for i in range(0,len(seq)-1):
a,b = seq[i],seq[i+1]
if a > b :
seq[i],seq[i+1] = b,a
count.append(str(i) + str(i+1))
return ','.join(count)
print(swapsort((6, 4, 2)))
print(swapsort((1,2,3,4,5)))
print(swapsort((1, 2, 3, 5, 3))) |
f68e476cf1e344cb0e10e3080ac7c7f19cb74d8c | eth-ait/ComputationalInteraction17 | /Andrew/Thrid/code.py | 9,068 | 3.765625 | 4 | # PLEASE NOTE THAT THIS IS NOT ALL THE CODE USED WITHIN THE THIRD TUTORIAL, SEE TUTORIAL FOR FULL CODE.
import numpy as np
import random
import matplotlib.pyplot as plt
np.set_printoptions(suppress=True)
def __init__(self):
# array for storing reward values
self.r = np.array([[-1, -10, -30, -1], # State S0
[-1, -1, -30, 90], # State S1
[-1, -1, -1, -1], # State S2
[-1, -1, -1, -1]]) # State S3
# current reward
self.reward = -1
# keep track of total reward
self.total_reward = 0.0
# list of states
self.state_list = [0, 1, 2, 3]
# belief state, all same to start
self.belief_state = [0.3, 0.3, 0.3, 0.3] # Choice to be made in s0 and s1
# set up belief table
self.belief_table = []
for s0 in range(0, 11):
for s1 in range (0, 11):
for s2 in range (0, 11):
for s3 in range (0, 11):
self.belief_table.append([s0, s1, s2, s3, 0, 0])
# convert to array
self.belief_table = np.vstack(self.belief_table)
# divide all by 10
self.belief_table = self.belief_table/10.0
# index of belief table corresponding to belief state
self.belief_table_index = -1
# index of belief table corresponding to previous belief state
self.previous_belief_table_index = -1
# keep track of real state
self.real_state = -1
# action number: 0 = Pull lever, 1 = Enter magazine
self.action_number = -1
# state to move to next
self.next_state = -1
# list to keep track of expected value
self.expected_value_array = []
def reset(self, initial_state):
print "Reset"
self.belief_state = [0.3, 0.3, 0.3, 0.3]
self.real_state = initial_state
def observe(self, observation_chance):
rand_num = random.random()
if rand_num < observation_chance:
return self.real_state
else:
random_state = random.choice(self.state_list)
while random_state == self.real_state:
random_state = random.choice(self.state_list)
return random_state
def update_belief_state(self, observation_state, observation_chance):
# Temporary list
temp_belief_state = [0.0, 0.0, 0.0, 0.0]
# Use Bayes' Rule to update belief state
for n in range(len(temp_belief_state)):
if observation_state == n:
temp_belief_state[n] = observation_chance * self.belief_state[n]
else:
temp_belief_state[n] = ((1 - observation_chance) / (len(self.state_list) - 1)) * self.belief_state[n]
# Normalise so the belief state sums to 1
temp_total = sum(temp_belief_state)
self.belief_state = list(n / temp_total for n in temp_belief_state)
# Round to 1 decimal place
self.belief_state = [round(n, 1) for n in self.belief_state]
def choose_next_action(self, epsilon):
# get the q_values of the two actions
q_value_a0 = (self.belief_table[self.belief_table_index, 4])
q_value_a1 = (self.belief_table[self.belief_table_index, 5])
# choose an action using epsilon greedy
rand_num = random.random()
if q_value_a0 > q_value_a1:
if rand_num > epsilon:
self.action_number = 0 # Exploit
else:
self.action_number = 1 # Explore
elif q_value_a1 > q_value_a0:
if rand_num > epsilon:
self.action_number = 1 # Exploit
else:
self.action_number = 0 # Explore
else:
self.action_number = random.randint(0, 1)
# get corresponding next state from current state and action number
def get_next_state(self):
if self.real_state == 0:
if self.action_number == 0:
self.next_state = 1
elif self.action_number == 1:
self.next_state = 2
elif self.real_state == 1:
if self.action_number == 0:
self.next_state = 2
elif self.action_number == 1:
self.next_state = 3
def get_belief_table_index(self):
self.belief_table_index = np.where((self.belief_table[:, 0] == self.belief_state[0])
& (self.belief_table[:, 1] == self.belief_state[1])
& (self.belief_table[:, 2] == self.belief_state[2])
& (self.belief_table[:, 3] == self.belief_state[3]))[0]
# get highest Q-value in belief state
def calculate_max_q_value(self):
# get the Q-values of the two actions
q_value_a0 = self.belief_table[self.belief_table_index, 4]
q_value_a1 = self.belief_table[self.belief_table_index, 5]
# return the highest
if q_value_a0 > q_value_a1:
return q_value_a0
else:
return q_value_a1
def update_belief_table(self, alpha, gamma):
# get correct element index for the select action
if self.action_number == 0:
location = 4
else:
location = 5
max_q_value = self.calculate_max_q_value()
previous_q = self.belief_table[self.previous_belief_table_index, location]
print "Real state: ", self.real_state
print "Action number: ", self.action_number
print "Max Q: ", max_q_value
print "Reward: ", self.reward
print "Before update: ", self.belief_table[self.previous_belief_table_index]
# update Q-value
self.belief_table[self.previous_belief_table_index, location] = previous_q + alpha * (self.reward + gamma * max_q_value - previous_q)
# round to 1 decimal place
self.belief_table[self.previous_belief_table_index, location] = round(self.belief_table[self.previous_belief_table_index, location], 1)
print "After update: ", self.belief_table[self.previous_belief_table_index]
def run_experiment(self, initial_state, observation_chance, alpha, gamma, epsilon, num_runs_wanted):
# set current state to initial state wanted
self.real_state = initial_state
# make an initial run
# make an observation
observation = self.observe(observation_chance)
# update belief state with observation
self.update_belief_state(observation, observation_chance)
# get the corresponding index in the belief table
self.get_belief_table_index()
# choose next action
self.choose_next_action(epsilon)
# get the next state
self.get_next_state()
# get the reward for moving from current state to next state
self.reward = self.r[self.real_state][self.next_state]
# update total reward
self.total_reward += self.reward
# move to the next state
self.real_state = self.next_state
self.belief_state = [0.3, 0.3, 0.3, 0.3]
print "Real state update: ", self.real_state, " --> ", self.next_state
# variables to keep track
num_rewards_received = 0
num_fails = 0
num_runs = 0
while num_runs < num_runs_wanted:
print ""
# make an observation
observation = self.observe(observation_chance)
# update belief state with observation
self.update_belief_state(observation, observation_chance)
# keep track of the previous belief_table_index
self.previous_belief_table_index = self.belief_table_index
# get the corresponding index in the belief table
self.get_belief_table_index()
print "Observation: ", observation
# update the belief table using Q-learning
self.update_belief_table(alpha, gamma)
# if terminal state reached
if self.real_state == 2 or self.real_state == 3:
if self.real_state == 2:
num_fails += 1
elif self.real_state == 3:
num_rewards_received += 1
num_runs += 1
self.expected_value_array = np.append(self.expected_value_array, self.total_reward / (80 * num_runs))
# reset to inital values
self.reset(initial_state)
# make an observation
observation = self.observe(observation_chance)
# update belief state with observation
self.update_belief_state(observation, observation_chance)
print "Observation: ", observation
# get the corresponding index in the belief table
self.get_belief_table_index()
# keep track of the previous belief_table_index
self.previous_belief_table_index = self.belief_table_index
# choose next action
self.choose_next_action(epsilon)
# get the next state
self.get_next_state()
# get the reward for moving from current state to next state
self.reward = self.r[self.real_state][self.next_state]
# update total reward
self.total_reward += self.reward
print "Real state update: ", self.real_state, " --> ", self.next_state
# move to the next state
self.real_state = self.next_state
self.belief_state = [0.3, 0.3, 0.3, 0.3]
print ""
print "Number of fails:"
print num_fails
print ""
print "Number of rewards:"
print num_rewards_received |
98283b4290d8ecdf2d0a0991af78844ece7488a0 | Anithakm/study | /list1.8.py | 292 | 3.796875 | 4 | #Find largest and smallest elements of a list.
a=[777,34,333,234]
i=0
largest=a[0]
while i<len(a):
if a[i]>largest:
largest=a[i]
i=i+1
print(largest)
j=0
smallest=a[0]
while j<len(a):
if a[j]<smallest:
smallest=a[j]
j=j+1
print(smallest)
|
a159d6db7738b70d1e7be005380f1b4b87ac7b5a | jojox6/Python3_URI | /URI 1117 - Validação de Nota.py | 213 | 3.859375 | 4 |
A=float(input())
while(A<0 or A>10):
print("nota invalida")
A=float(input())
B=float(input())
while(B<0 or B>10):
print("nota invalida")
B=float(input())
print("media = %.2f"%((A+B)/2))
|
212e8f951b9d452d0ef57559cb3314aaa3a1b50c | RODRIGOKTK/Python-exercicios | /EX 16numero aredondado.py | 502 | 4.0625 | 4 | #resolução #1
import math
num = float(input('Qual um valor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, math.trunc(num)))
#resolução #2
import math import trunc
num = float(input('Qual um valor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, trunc(num)))
#resolução #3 sem importação
num = float(input('Qual um valor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, int(num))) |
385ea025598fe6a9c833d54050a70bed5ed5a1e7 | slahmar/advent-of-code-2018 | /09-02.py | 1,009 | 3.640625 | 4 | from collections import deque
with open('09.txt', 'r') as file:
parameters = file.read()
players = int(parameters[:parameters.index('players')-1])
last_marble = int(parameters[parameters.index('worth')+6:parameters.index('points')-1])*100
print(f'{players} players, last marble: {last_marble}')
player = 0
marble_index = 0
marble = 0
marbles = deque([marble])
score = {}
while marble < last_marble:
marble += 1
player = player%(players)+1
if marble % 23 == 0:
#print(f'Marble {marble} is a multiple of 23')
if player not in score:
score[player] = 0
score[player] += marble
marbles.rotate(7)
score[player] += marbles.pop()
marbles.rotate(-1)
#print(f'Player {player} has now {score[player]} points')
else:
marbles.rotate(-1)
marbles.append(marble)
print(f'High score {sorted(score.values())[-1]}')
|
09b05ca636407d5df2261bae14752c7a1756f09f | sumeetmishra199189/Applied-Algorithms | /Brute Force vs Divide and Conquer/Assignment2.py | 5,185 | 3.515625 | 4 | #reading inputs and initializing variables
input=open('/Users/sumeetmishra/Desktop/Applied_Algorithms/Assignment/Programing Assignment-2/input.txt','r+')
input1=input.read()
input2=input1.strip().split()
input2= list(map(int, input2))
#test_3=[]
test_1=input2[:60] #taking 1000 elements from input2 which can be modified
#for i in range(0,len(test_1)):
#test_3.append(-1*abs(test_1[i]))
#test_1=abs(test_1)
#test_1=-1*(test_1)
#print(test_3)
#test_2=input2[:]
l=int(len(test_1)/2) #taking elements 500 at a time,total 20 iterations
#l1=int(len(test_2)/5000)
#l2=int(len(w)/2)
no_of_inputs = []
#import numpy as np
import matplotlib.pyplot as plt
import time
d_t_all1 = []
d_t_all2 = []
avg_time1=[]
avg_time2=[]
#brute force function
def brute_force(A):
s=-999999999
left_index=0
right_index=0
for i in range (0,len(A)):
s1=0
for j in range(i,len(A)):
s1=s1+A[j]
if(s1>s):
s=s1
#s1=0
left_index=i
right_index=j
# else:
# s1=0
#print("max subarray:A["+str(left_index)+".."+str(right_index)+"]")
#print("max sum:"+str(s))
return(left_index,right_index,s)
#function that calls brute force 3 times
def time_and_3_observations_for_brute_force(A):
for a in range(3):
for k in range(1, l + 1):
result = A[0:(k * 2)]
t1 = time.clock()
(a,b,c) = brute_force(result)
t2 = time.clock()
d_t_all1.append(t2 - t1)
print("max subarray:A[" + str(a) + ".." + str(b) + "]")
print("max sum:" + str(c))
d_t1 = []
d_t2 = []
d_t3 = []
#d_t1 = np.array(d_t_all1[0:20])
#d_t2 = np.array(d_t_all1[20:40])
#d_t3 = np.array(d_t_all1[40:60])
#avg_time1=((d_t1 + d_t2 + d_t3) / 3)
for i in range(0,len(d_t_all1),3):
d_t1.append(d_t_all1[i])
for i in range(1,len(d_t_all1),3):
d_t2.append(d_t_all1[i])
for i in range(2,len(d_t_all1),3):
d_t3.append(d_t_all1[i])
for i in range(0,len(d_t1)):
avg_time1.append((d_t1[i]+d_t2[i]+d_t3[i])/3)
#print(avg_time1)
# divide and conquer function,logic refered from text book CLRS
def divide_and_conquer_cross(A,low,mid,high):
left_sum=-999999999
right_sum=0
max_left=0
max_right=0
sum1=0
sum2=0
for i in range(mid,low,-1):
sum1=sum1+A[i]
if sum1>=left_sum:
left_sum=sum1
max_left=i
for j in range(mid+1,high+1):
sum2 = sum2 + A[j]
if sum2 >= right_sum:
right_sum = sum2
max_right = j
return (max_left,max_right,left_sum+right_sum)
def maximum_subarray(A,low,high):
if (high == low):
#print(low,high,A[low])
return (low,high,A[low])
else:
mid = int((high + low)/2)
#print 'mid is:',mid
(left_low,left_high,left_sum) = maximum_subarray(A,low,mid)
(right_low,right_high,right_sum) = maximum_subarray(A,mid+1,high)
(cross_low,cross_high,cross_sum) = divide_and_conquer_cross(A,low,mid,high)
if (left_sum >= right_sum and left_sum >= cross_sum):
#print(left_low, left_high, left_sum)
#print("max subarray:A[" + str(left_low) + ".." + str(left_high) + "]")
#print("max sum:" + str(left_sum))
return (left_low, left_high, left_sum)
elif (right_sum >= left_sum and right_sum >= cross_sum):
return (right_low,right_high,right_sum)
else:
return (cross_low,cross_high,cross_sum)
#function that calls divide and conquer 3 times
def time_and_3_observations_for_divide_and_conquer(A):
for a in range(3):
for k in range(1, l + 1):
result = A[0:(k * 2)]
t1 = time.clock()
low = 0
high = len(result) - 1
(a, b, c) = maximum_subarray(result, low, high)
t2 = time.clock()
d_t_all2.append(t2 - t1)
print("max subarray:A[" + str(a) + ".." + str(b) + "]")
print("max sum:" + str(c))
d_t4 = []
d_t5 = []
d_t6 = []
for i in range(0,len(d_t_all2),3):
d_t4.append(d_t_all2[i])
for i in range(1,len(d_t_all2),3):
d_t5.append(d_t_all2[i])
for i in range(2,len(d_t_all2),3):
d_t6.append(d_t_all2[i])
for i in range(0,len(d_t4)):
avg_time2.append((d_t4[i]+d_t5[i]+d_t6[i])/3)
#calling the functions
time_and_3_observations_for_brute_force(test_1)
time_and_3_observations_for_divide_and_conquer(test_1)
#taking input as x
no_of_inputs = []
for n in range(1, l + 1):
no_of_inputs.append(n * 2)
#plot refered from the below site
#https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure-in-matplotlib
plt.plot(no_of_inputs, avg_time1, 'r',label='Brute Force')
plt.plot(no_of_inputs, avg_time2, 'b',label='Divide and Conquer')
plt.xlabel('Number of Inputs')
plt.ylabel('Average Time in Seconds')
plt.title('Brute Force Vs Divide and Conquer')
plt.legend(loc='upper right')
plt.show()
|
cc08dc0ba575971a118b7847d61700d1b3a892fc | Akshay-jain22/Mini-Python-Projects | /Calculator_GUI.py | 4,529 | 4.21875 | 4 | from tkinter import *
# Creating Basic Window
window = Tk()
window.geometry('312x324')
# window.resizable(0,0) # This prevents from resizing the window
window.title("Calculator")
########################## Functions ##########################
# btn_click Function will continuously update the input field whenever you enter a number
def btn_click(item) :
global expression
expression = expression + str(item)
input_text.set(expression)
# brn_clear function will clear the input field
def btn_clear() :
global expression
expression = ''
input_text.set(expression)
def btn_equal() :
global expression
result = str(eval(expression))
input_text.set(result)
expression = ''
def btn_dash() :
global expression
if expression=='' :
return
else :
expression = expression[:-1]
input_text.set(expression)
expression = ''
# 'StringVar()' is used to get the instance of input field
input_text = StringVar()
# Creating a frame for the input field
input_frame = Frame(window, width=312, height=50, bd=0, highlightbackground='black', highlightcolor='black')
input_frame.pack(side=TOP)
# Creating a input field inside the 'Frame'
input_field = Entry(input_frame, font=('arial', 10, 'bold'), textvariable=input_text, width=50, bg='#eee', bd=0)
input_field.grid(row=0, column=0)
input_field.pack(ipady=10) # ipday is internal padding to increase the height of input field
# Creating another frame for the button below the input frame
btn_frame = Frame(window, width=312, height=274, bg='grey')
btn_frame.pack()
# First Row
clear = Button(btn_frame, text='C', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=btn_clear).grid(row=0, column=0)
dash = Button(btn_frame, text='<--', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=btn_dash).grid(row=0, column=1)
divide = Button(btn_frame, text='/', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('/')).grid(row=0, column=2)
# Second Row
seven = Button(btn_frame, text='7', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('7')).grid(row=1, column=0)
eight = Button(btn_frame, text='8', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('8')).grid(row=1, column=1)
nine = Button(btn_frame, text='9', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('9')).grid(row=1, column=2)
multiply = Button(btn_frame, text='X', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('*')).grid(row=1, column=3)
# Third Row
four = Button(btn_frame, text='4', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('4')).grid(row=2, column=0)
five = Button(btn_frame, text='5', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('5')).grid(row=2, column=1)
six = Button(btn_frame, text='6', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('6')).grid(row=2, column=2)
minus = Button(btn_frame, text='-', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('-')).grid(row=2, column=3)
# Fourth Row
one = Button(btn_frame, text='1', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('1')).grid(row=3, column=0)
two = Button(btn_frame, text='2', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('2')).grid(row=3, column=1)
three = Button(btn_frame, text='3', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('3')).grid(row=3, column=2)
plus = Button(btn_frame, text='+', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('+')).grid(row=3, column=3)
# Fifth Row
zero = Button(btn_frame, text='0', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('0')).grid(row=4, column=0)
point = Button(btn_frame, text='.', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=lambda : btn_click('.')).grid(row=4, column=1)
equals = Button(btn_frame, text='=', fg='black', width=10, height=3, bd=0, bg='white', cursor='hand2', command=btn_equal).grid(row=4, column=2)
window.mainloop() |
e2b76213912f4f7eeaf48f06f0629b1672544015 | saimadhu-polamuri/CodeevalSolutions | /Lowercase/lowercase.py | 651 | 3.890625 | 4 | # Solution for codeeval lowercase problem
__autor__ = 'Saimadhu Polamuri'
__website__ = 'www.dataaspirant.com'
__createdon__ = '27-Feb-2015'
import sys
class Lowercase():
""" Solution for codeeval lowercase problem """
def __init__(self,filename):
""" Initial function in Lowercase class """
self.filename = filename
def readfile(self):
""" Reads the input file """
with open(self.filename,'r') as f:
for line in f:
print line.lower()
def main():
""" Main function create Lowercase instance and get use of it """
filename = sys.argv[1]
lowercase = Lowercase(filename)
lowercase.readfile()
if __name__ == "__main__":
main() |
035b354d06bc23257f54b1e64a60e31b4b8b4ce7 | SebasRaveg/Introduccion_a_la_Programacion_con_Python_Universidad_Austral | /Trabajo_Curso_1/suma_dados.py | 664 | 3.8125 | 4 | import random
def suma_dados():
preguntar = input('¿Desea tirar los dados? (s/n): ')
while preguntar!= 's' and preguntar!= 'n':
preguntar = input('Por favor, teclee "s" o "n": ')
dado = [1, 2, 3, 4, 5, 6]
while preguntar == 's':
num1 = random.choice(dado)
num2 = random.choice(dado)
print('El primer número es: ' + str(num1))
print('El segundo número es: ' + str(num2))
print('La suma es: ' + str(num1 + num2))
preguntar = input('¿Desea tirar los dados de nuevo? (s/n): ')
while preguntar!= 's' and preguntar!= 'n':
preguntar = input('Por favor, teclee "s" o "n": ') |
10009f65d1e1c67732076eea969b8a3beadeb7f2 | Adityanagraj/infytq-previous-year-solutions | /Prefix and Suffix.py | 493 | 3.890625 | 4 | """
A non empty string containing only alphabets. Print length of longest prefix in the string
which is same as suffix without overlapping.Else print -1 if no prefix or suffix exists.
>>Input 1
Racecar
>>Output 1
-1
>>Input 2
aaaa
>>Output 2
2
"""
string=input()
length=len(string)
mid=int(length)//2
m=-1
for i in range(mid,0,-1):
pre=string[0:i]
suf=string[length-i:length]
if (pre==suf):
print(len(suf))
break
else:
print(m) |
076991188de6809d7e108686b35eb3edba6dde47 | mooyeon-choi/TIL | /problemSolving/swExpertAcademy/python/sw_4047_카드카운팅.py | 844 | 3.53125 | 4 | from collections import deque
t = int(input())
for tc in range(1, t + 1):
answer = []
s = input()
deck = deque([])
string = ''
dic = {'S':[], 'D':[], 'H':[], 'C':[]}
for i in range(len(s) + 1):
if i == len(s):
deck.append(string)
elif not i % 3:
deck.append(string)
string = s[i]
else:
string += s[i]
deck.popleft()
while deck:
now = deck.popleft()
if now[1:3] not in dic[now[0]] or int(now[1:3]) > 13 or int(now[1:3]) < 1:
dic[now[0]] += [now[1:3]]
else:
answer = 'ERROR'
if not answer:
answer = [13 - len(dic['S']), 13 - len(dic['D']), 13 - len(dic['H']), 13 - len(dic['C'])]
print('#{}'.format(tc), *answer) if type(answer) == type([]) else print('#{} '.format(tc), answer) |
9bb278ee41858f4c9e550545042f88508d554218 | jackandsnow/LeetCodeCompetition | /hot100/78subsets.py | 706 | 4.28125 | 4 | """
78. 子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
def subsets(nums):
"""
递归法
:type nums: List[int]
:rtype: List[List[int]]
"""
# 初始子集为空
result = [[]]
# 每一步向子集添加新的整数,并生成新的子集
for num in nums:
result += [res + [num] for res in result]
return result
if __name__ == '__main__':
ans = subsets([1, 2, 3])
print(ans)
|
c67b04edef3ca83450a0cec7dda79a67799e7ac7 | dualfame/YZUpython | /0429 lesson04/forloop demo4.py | 403 | 3.75 | 4 | em1 = {'name': 'John', 'salary': 60000, 'program': ['Python', 'Java']}
em2 = {'name': 'Mark', 'salary': 70000, 'program': ['C++', 'Java', 'R']}
em3 = {'name': 'Dan', 'salary': 50000, 'program': ['Python']}
emps = [em1, em2, em3]
#求會Python的員工?
language= 'Python'
names = []
for n in emps :
for p in n['program'] :
if p == language :
names.append(n['name'])
print(names) |
799e907d8890bc5851426ba46d358fe9f5adc31d | imsaksham-c/Udacity-DataStructuresAndAglorithms | /Project-2/Problem2.py | 1,659 | 4.25 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
path_list = list()
try:
dir_path = os.listdir(path)
except:
return ""
for item in dir_path:
full_path = os.path.join(path, item)
if os.path.isdir(full_path):
path_list += find_files(suffix, full_path)
elif os.path.isfile(full_path) and item.endswith(suffix):
path_list.append(path + "\\" + item)
return path_list
returned_path_list = find_files(".c", ".")
for item in returned_path_list:
print(item)
'''
.\testdir\subdir1\a.c
.\testdir\subdir3\subsubdir1\b.c
.\testdir\subdir5\a.c
.\testdir\t1.c
'''
returned_path_list = find_files(".h", ".")
for item in returned_path_list:
print(item)
'''
.\testdir\subdir1\a.h
.\testdir\subdir3\subsubdir1\b.h
.\testdir\subdir5\a.h
.\testdir\t1.h
'''
returned_path_list = find_files(".gitkeep", ".")
for item in returned_path_list:
print(item)
'''
.\testdir\subdir2\.gitkeep
.\testdir\subdir4\.gitkeep
'''
returned_path_list = find_files(".c", ".\releasedir")
if len(returned_path_list) > 0:
for item in returned_path_list:
print(item)
else:
print("File Not Found / Invalid directory")
'''
File Not Found / Invalid directory
''' |
066dcb0b4a3dd070b677c7bf4a92c54c217480a0 | smwelisson/Exercicio_CeV | /18 - Listas 2 - 84 a 89/88.py | 306 | 3.828125 | 4 | from random import randint
jogos = 5
for quantidade_jogos in range(1, jogos+1):
mega = []
while len(mega) < 6:
num_aleatorios = randint(1, 60)
if num_aleatorios not in mega:
mega.append(num_aleatorios)
mega.sort()
print(f"Jogos {quantidade_jogos}: {mega}")
|
5dfa9cdc508f5994b6fcd16ad938c8a0f890877a | ElsieBL/STP-Portfolio | /Objective_Programming.py | 461 | 3.9375 | 4 | class Rectangle:
def __init__(self, w, l):
self.width = w
self.length = l
def calculate_perimeter(self):
return 2 *(self.width + self.length)
class Square:
def __init__(self, s):
self.s1 = s
def calculate_perimeter(self):
return 4 * self.s1
a_rectangle = Rectangle(2,3)
print (a_rectangle.calculate_perimeter())
b_square = Square(3)
print (b_square.calculate_perimeter())
|
a649c22ed1a9b1958147bc1c14954ab75a5e2600 | steveding1/CS-1 | /task2.2-exer2.py | 98 | 3.84375 | 4 | #CS-1 Task 2.2 - Exercise 2 from Steve Ding
name = input('Enter your name:')
print ('Hello '+name)
|
f5297ce2110544c443235a7c989e33b27b8b3d9c | arpandhakal/python_powerworkshop | /jan 19/string/17.py | 112 | 4.0625 | 4 | a=input("enter a string")
count=0
for i in a:
count += 1
print ("the length of the string is ",count)
|
5410c409558f08ad06cf09763026fa9d91eee821 | RettPop/csvexcerptor | /csvexcerptor.py | 1,493 | 3.75 | 4 | import argparse
# <input file>
# <output file>
# series of <column_name:value> parameters,
# series of <source_column:new_column_name>
# [dst_id_column_name:dst_id_value]
# reads input file looking for a row with given columns value
# takes value of the source_column of the row
# open/create output_file
# add to the file value from the source_column of input_file to the new_column_name column
# add to output_file dst_id_column_name column with dst_id_value value
# prints the line to output file or to stdout
# throw if output_file exists and contains any of dst_column's.
# throw if output_file exists and contains more than 1 values row
if __name__ == '__main__':
args_parser = argparse.ArgumentParser("Extracts specified cells from input CSV file")
args_parser.add_argument("-i", "--input-file", dest="input_file", action="store")
args_parser.add_argument("-o", "--output-file", dest="output_file", action="store")
args_parser.add_argument("-s", "--src-col-value", dest="source_cells", action="append")
args_parser.add_argument("-d", "--dst-columns", dest="dst_columns", action="append")
args_parser.add_argument("-c", "--id-column", dest="id_column", action="store")
args_parser.add_argument("-v", "--id-value", dest="id_value", action="store")
# args = args_parser.parse_args(["-id", "'Col name':'host name'", "--src-col-value", "1-2", "--src-col-value", "1:2", "--dst-columns", "1:2"])
args = args_parser.parse_args()
print(args)
|
87cb8f7a4c02ce4fd94140e39416c06ea623100f | Imranabdi/Training101 | /cardExample.py | 625 | 3.78125 | 4 | class Card:
balance = 0
# created a constructor
def __init__(self,bal):
self.balance = bal
#create a method for withdrawal
def withdraw(self,amount):
if self.balance >= amount:
self.balance -= amount + (0.2 * amount)
return self.printReceipt(self.balance,amount)
else:
return "Insufficient balance!"
# method to print out the receipt
def printReceipt(self,balance,withdraw):
return """
RECEIPT
WITHDRAWN AMOUNT:........{}
BALANCE:.......{}
""".format(withdraw,balance)
|
142eaa246ccacbacdbfae5bab04ae30e26fb67f8 | ecjuncal/stats-project-dataset | /predict.py | 1,031 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, plot_confusion_matrix
df = pd.read_csv(r'C:\Users\Jujin\Desktop\stats-project-dataset\data\heart_failure_clinical_records_dataset.csv')
x = df[['ejection_fraction', 'serum_creatinine', 'serum_sodium', 'age', 'diabetes', 'high_blood_pressure', 'anaemia', 'sex', 'smoking']]
y = df['DEATH_EVENT']
#Spliting data into training and testing data
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, test_size=0.2)
scorelist = []
knn = None
for i in range(1, 21):
knn = KNeighborsClassifier(n_neighbors = i)
knn.fit(x_train, y_train)
predict = knn.predict(x_test)
score = accuracy_score(y_test, predict)
scorelist.append(round(100 * score, 2))
print("K Nearest Neighbors Top 5 Success Rates: ")
print(sorted(scorelist, reverse=True)[:5])
plot_confusion_matrix(knn, x_test, y_test)
plt.show()
|
5faa783c075b34d65548f4d8cbe2397e6888049e | jakubchudon/Matura | /rozne/tablice 2d.py | 295 | 3.640625 | 4 | def print2d(lista):
for i in range(len(lista)):
for j in range(len(lista)):
print(lista[i][j], end=' ')
print(' ')
tablica2d=[]
tab=[]
for i in range(1,11):
for j in range(1,11):
tab.append(i*j)
tablica2d.append(tab)
tab=[]
print2d(tablica2d)
|
e508d569ccc02071ce01530f2017f9ea0d14f8fb | w2116o2115/FirstScrip | /best/day03/课上练习.py | 1,171 | 3.59375 | 4 | __author__ = 'zw'
#注册,死循环
#账号、密码、密码确认
#非空
#已经存在的不能注册
# all_user = {'lily':123,'zhaosi':123}
# while True:
# username = input('username:').strip()
# pwd = input('pwd:').strip()
# cpwd = input('cpwd').strip()
# if username and pwd and cpwd:
# if username in all_user:
# print('用户名已经存在,请重新输入')
# else:
# if pwd==cpwd:
# all_user[username]=pwd
# print('注册成功')
# break
# else:
# print('两次输入密码不一致')
# else:
# print('账号密码不能为空')
#登录
#非空
#如输入用户名不存在,提示
all_user = {'lily':123,'zhaosi':123}
while True:
username = input('username:').strip()
pwd = input('pwd:').strip()
if username and pwd:
if username in all_user:
if all_user[username]==pwd:
print('登录成功')
else:
print('密码错误')
else:
print('用户名不存在')
else:
print('输入用户名密码为空')
|
ce31701aeed72025bfc2e4b8262297f4d93ab9c5 | Furgololoo/PythonZadania | /zad1.py | 335 | 3.71875 | 4 |
def Second(arr):
arr.sort()
for second in arr:
if second != arr[0]:
break
a = arr.index(second)
foo = []
for i in arr:
if i == arr[a]:
foo.append(i)
return foo
arr = [5,234,54,23,213,54,76,346,98,23,5,5,23,65,342]
secondmin = Second(arr)
print(secondmin)
|
f3c684fe349a0e6db21f11d7c67f73e435a6c611 | zftan0709/DL_HW | /HW1/CPSC8810_HW1-3 Parameters vs Generalization.py | 25,497 | 3.703125 | 4 |
# coding: utf-8
# # ** CPSC 8810 Deep Learning - HW1-3 **
# ---
#
# ## Introduction
# _**Note:** This assignment makes use of the MNIST dataset_
#
# The main objective of this assignments:
# * Fit network with random labels
# * Compare number of parameters vs generalization
# * Compare flatness vs generalization
# In[1]:
import tensorflow as tf
import cv2
from tensorflow.examples.tutorials.mnist import input_data
from sklearn.decomposition import PCA
tf.__version__
import numpy as np
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
# ## MNIST Dataset Preparation and Visualization
# In[2]:
data = input_data.read_data_sets('data/MNIST/', one_hot=True);
train_num = data.train.num_examples
valid_num = data.validation.num_examples
test_num = data.test.num_examples
img_flatten = 784
img_size = 28
num_classes = 10
print("Training Dataset Size:",train_num)
print("Validation Dataset Size:",valid_num)
print("Testing Dataset Size:",test_num)
# In[3]:
fig, axs = plt.subplots(2,5)
fig.set_size_inches(12,4)
for i in range(10):
idx = np.where(np.argmax(data.train.labels,1)==i)[0][0]
axs[int(i/5),i%5].imshow(data.train.images[idx].reshape(28,28))
axs[int(i/5),i%5].set_title(str(i))
axs[int(i/5),i%5].axis('off')
# ### CIFAR-10 Data Distribution Before Augmentation
# In[4]:
bar_fig = plt.figure(figsize=[10,5])
unique, counts = np.unique(np.argmax(data.train.labels,1), return_counts=True)
plt.bar(unique,counts)
plt.title("Data Distribution Before Data Augmentation")
plt.xticks(unique,np.arange(10));
# ### Parameter Count Function
# In[5]:
def parameter_count():
total_parameters = 0
for variable in tf.trainable_variables():
print(variable)
shape = variable.get_shape()
variable_parameters = 1
for dim in shape:
variable_parameters *= dim.value
#print("parameter num:",variable_parameters)
total_parameters += variable_parameters
print("Total Parameter: ",total_parameters)
return total_parameters
# ## 1.1 Model 1 Architecture
# In[6]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=8,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=16,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=2,strides=2);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=128,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param1 = parameter_count()
# In[7]:
flat1.shape
# ### 1.2 Training Model 1
# In[181]:
train_loss_list1 = []
train_acc_list1 = []
test_loss_list1 = []
test_acc_list1 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
train_loss_list1.append(train_loss)
train_acc_list1.append(train_acc)
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
test_loss_list1.append(test_loss)
test_acc_list1.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 2.1 Model 2 Architecture
# In[204]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=6,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=24,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=2,strides=2);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=32,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param2 = parameter_count()
# ### 2.2 Model 2 Training
# In[207]:
train_loss_list2 = []
train_acc_list2 = []
test_loss_list2 = []
test_acc_list2 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
train_loss_list2.append(train_loss)
train_acc_list2.append(train_acc)
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
test_loss_list2.append(test_loss)
test_acc_list2.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 3.1 Model 3 Architecture
# In[208]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=8,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=2,strides=2);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=32,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param3 = parameter_count()
# ### 3.2 Model 3 Training
# In[211]:
train_loss_list3= []
train_acc_list3 = []
test_loss_list3 = []
test_acc_list3 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list3.append(train_loss)
train_acc_list3.append(train_acc)
test_loss_list3.append(test_loss)
test_acc_list3.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 4.1 Model 4 Architecture
# In[152]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=8,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=2,strides=2);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param4 = parameter_count()
# ### 4.2 Model 4 Training
# In[153]:
train_loss_list4= []
train_acc_list4 = []
test_loss_list4 = []
test_acc_list4 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list4.append(train_loss)
train_acc_list4.append(train_acc)
test_loss_list4.append(test_loss)
test_acc_list4.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 5.1 Model 5 Architecture
# In[154]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=2,strides=2);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param5 = parameter_count()
# ### 5.2 Model 5 Training
# In[155]:
train_loss_list5= []
train_acc_list5 = []
test_loss_list5 = []
test_acc_list5 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list5.append(train_loss)
train_acc_list5.append(train_acc)
test_loss_list5.append(test_loss)
test_acc_list5.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 6.1 Model 6 Architecture
# In[156]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=6,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=4,strides=4);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param6 = parameter_count()
# ### 6.2 Model 6 Training
# In[157]:
train_loss_list6= []
train_acc_list6 = []
test_loss_list6 = []
test_acc_list6 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list6.append(train_loss)
train_acc_list6.append(train_acc)
test_loss_list6.append(test_loss)
test_acc_list6.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 7.1 Model 7 Architecture
# In[158]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=2,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=4,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=4,strides=4);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param7 = parameter_count()
# ### 7.2 Model 7 Architecture
# In[159]:
train_loss_list7= []
train_acc_list7 = []
test_loss_list7 = []
test_acc_list7 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list7.append(train_loss)
train_acc_list7.append(train_acc)
test_loss_list7.append(test_loss)
test_acc_list7.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 8.1 Model 8 Architecture
# In[160]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=2,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=2,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=4,strides=4);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param8 = parameter_count()
# ### 8.2 Model 8 Training
# In[161]:
train_loss_list8= []
train_acc_list8 = []
test_loss_list8 = []
test_acc_list8 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list8.append(train_loss)
train_acc_list8.append(train_acc)
test_loss_list8.append(test_loss)
test_acc_list8.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 9.1 Model Architecture
# In[162]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=1,kernel_size=5,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=1,kernel_size=5,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=4,strides=4);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param9 = parameter_count()
# # 9.2 Model 9 Training
# In[163]:
train_loss_list9= []
train_acc_list9 = []
test_loss_list9 = []
test_acc_list9 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list9.append(train_loss)
train_acc_list9.append(train_acc)
test_loss_list9.append(test_loss)
test_acc_list9.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# ___
# ## 10.1 Model 10 Architecture
# In[214]:
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, img_flatten], name='x')
input_x = tf.reshape(x,[-1,img_size,img_size,1])
y = tf.placeholder(tf.float32, shape=[None, num_classes], name='y')
y_cls = tf.argmax(y,dimension=1)
conv1 = tf.layers.conv2d(inputs=input_x,filters=1,kernel_size=3,padding="same",activation=tf.nn.relu);
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=2,strides=2);
conv2 = tf.layers.conv2d(inputs=pool1,filters=1,kernel_size=3,padding="same",activation=tf.nn.relu);
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=4,strides=4);
flat1 = tf.layers.flatten(pool2);
fc1 = tf.layers.dense(inputs=flat1,units=10,activation=tf.nn.relu);
logits = tf.layers.dense(inputs=fc1,units=num_classes,activation=None);
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits);
loss = tf.reduce_mean(cross_entropy);
# Accuracy
softmax = tf.nn.softmax(logits=logits);
pred_op = tf.argmax(softmax,dimension=1);
acc_op = tf.reduce_mean(tf.cast(tf.equal(pred_op, y_cls), tf.float32));
optimizer = tf.train.AdamOptimizer(learning_rate=0.005);
train_op = optimizer.minimize(loss);
param10 = parameter_count()
# ### 10.2 Model 10 Training
# In[215]:
train_loss_list10= []
train_acc_list10 = []
test_loss_list10 = []
test_acc_list10 = []
session = tf.Session()
session.run(tf.global_variables_initializer())
BATCH_SIZE = 64
EPOCH = 1
for i in range(EPOCH):
for j in range(int(data.train.num_examples/BATCH_SIZE)):
x_batch, y_true_batch = data.train.next_batch(BATCH_SIZE)
session.run(train_op, feed_dict={x: x_batch,y: y_true_batch})
train_loss, train_acc = session.run([loss,acc_op],feed_dict={x:x_batch,y:y_true_batch})
test_loss, test_acc = session.run([loss,acc_op],feed_dict={x:data.test.images,y:data.test.labels})
train_loss_list10.append(train_loss)
train_acc_list10.append(train_acc)
test_loss_list10.append(test_loss)
test_acc_list10.append(test_acc)
msg = "Epoch: {0:>6}, Training Loss: {1:>1.6}, Training Accuracy: {2:>6.1%}, Test Loss: {3:>1.6}, Test Accuracy: {4:>6.1%}"
print(msg.format(i, train_loss, train_acc, test_loss, test_acc))
# In[216]:
train_loss_list = np.concatenate([train_loss_list10,train_loss_list9,train_loss_list8,train_loss_list7,train_loss_list6,train_loss_list5,train_loss_list4,train_loss_list3,train_loss_list2,train_loss_list1])
train_acc_list = np.concatenate([train_acc_list10,train_acc_list9,train_acc_list8,train_acc_list7,train_acc_list6,train_acc_list5,train_acc_list4,train_acc_list3,train_acc_list2,train_acc_list1])
test_loss_list = np.concatenate([test_loss_list10,test_loss_list9,test_loss_list8,test_loss_list7,test_loss_list6,test_loss_list5,test_loss_list4,test_loss_list3,test_loss_list2,test_loss_list1])
test_acc_list = np.concatenate([test_acc_list10,test_acc_list9,test_acc_list8,test_acc_list7,test_acc_list6,test_acc_list5,test_acc_list4,test_acc_list3,test_acc_list2,test_acc_list1])
param_num = np.array([param10,param9,param8,param7,param6,param5,param4,param3,param2,param1])
# In[219]:
plt.scatter(param_num,train_loss_list)
plt.scatter(param_num,test_loss_list)
plt.xlabel('Parameters')
plt.ylabel('Loss')
plt.legend(['Train','Test'])
plt.pause(0.1)
plt.scatter(param_num,train_acc_list)
plt.scatter(param_num,test_acc_list)
plt.xlabel('Parameters')
plt.ylabel('Accuracy')
plt.legend(['Train','Test'])
|
ec78b41416ee5bdccdab0c342ea4b6c49f841694 | C-SON-TC1028-001-2113/listas---tarea-6-Diego0103 | /assignments/17MenoresANumero/src/exercise.py | 598 | 3.625 | 4 | def resultado(m):
listafinal=[]
for i in range (len(m)):
if m[i]<10:
listafinal.append(m[i])
return listafinal
def datos(r,c):
valores=[]
matriz=[]
listacompleta=[]
for i in range(r):
for i in range (c):
valor=int(input())
valores.append(valor)
matriz.append(valores)
listacompleta=listacompleta+valores
valores=[]
return resultado(listacompleta)
def main():
renglones=int(input())
columnas=int(input())
print (datos(renglones,columnas))
if __name__=='__main__':
main()
|
4cd78138720e58bed49c4c7cc18411edd8363fd5 | houhailun/data_struct_alrhorithm | /data_struct/BinaryTree.py | 9,516 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Time : 2019/6/28 13:08
@Author : Hou hailun
@File : BinaryTree.py
"""
print(__doc__)
"""
节点的高度:节点到叶子节点的最长路径(边数)
节点的深度:根节点到叶子节点所经历的边的个数
节点的层数:节点的深度 + 1
树的高度:根节点的高度
"""
class TNode(object):
"""二叉树节点类"""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BTree(object):
"""二叉树类"""
def __init__(self, node=None):
self.root = node
def add(self, item=None):
"""构建完全二叉树"""
node = TNode(item)
if not self.root: # 空树,添加到根节点
self.root = node
return
# 不为空,则按照 左右顺序 添加节点,这样构建出来的是一棵有序二叉树,且是完全二叉树
my_queue = []
my_queue.append(self.root)
while True:
cur_node = my_queue.pop(0)
if not cur_node.left: # 左孩子为空
cur_node.left = node
return
elif not cur_node.right: # 右孩子为空
cur_node.right = node
return
else:
my_queue.append(cur_node.left)
my_queue.append(cur_node.right)
def add_v2(self, item=None):
"""构建一般二叉树"""
node = TNode(item)
if not self.root and self.root.data is None:
self.root = node
return
my_queue = []
my_queue.append(self.root)
while True:
cur_node = my_queue.pop(0)
# 如果当前节点为空节点则跳过它,起到占位的作用
if cur_node.data is None:
continue
if not cur_node.left:
cur_node.left = node
return
elif not cur_node.right:
cur_node.right = node
return
else:
my_queue.append(cur_node.left)
my_queue.append(cur_node.right)
# 二叉树的遍历:表示的是节点与其左右子树节点遍历打印的先后顺序
# 时间复杂度为O(n)
def pre_travel(self, node):
"""前序遍历: 根-左-右"""
if not node: # 空树
return
print(node.data, end=', ')
self.pre_travel(node.left)
self.pre_travel(node.right)
def mid_travel(self, node):
"""中序遍历: 左-根-右"""
if not node:
return
self.mid_travel(node.left)
print(node.data, end=', ')
self.mid_travel(node.right)
def post_travel(self, node):
"""后序遍历: 左-右-根"""
if not node:
return
self.post_travel(node.left)
self.post_travel(node.right)
print(node.data, end=', ')
def bread_travel(self):
"""层次遍历,广度遍历"""
if self.root is None:
return
my_queue = [self.root]
while my_queue:
cur_node = my_queue.pop(0)
print(cur_node.data, end=', ')
if cur_node.left is not None:
my_queue.append(cur_node.left)
if cur_node.right is not None:
my_queue.append(cur_node.right)
def pre_travel_stack(self, root):
"""利用堆栈实现树的先序遍历"""
stack = [root]
while stack:
s = stack.pop() # 弹出末尾元素
if s:
print(s.val)
stack.append(s.right) # 因为上面是弹出末尾元素,因此这里先加右节点再加左节点
stack.append(s.left)
def mid_travel_stack(self, root):
"""利用堆栈实现中序遍历"""
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
print(root.val)
root = root.right
def post_travel_stack(self, root):
"""利用堆栈实现后序遍历"""
if not root:
return
my_stack1 = []
my_stack2 = []
node = root
my_stack1.append(node)
while my_stack1: # 这个while循环的功能是找出后序遍历的逆序,存在myStack2里面
node = my_stack1.pop()
if node.left:
my_stack1.append(node.left)
if node.right:
my_stack1.append(node.right)
my_stack2.append(node)
while my_stack2: # 将myStack2中的元素出栈,即为后序遍历次序
print(my_stack2.pop().data, end=', ')
class BSTree(object):
"""
二叉搜索树类:左节点值小于根节点值,右节点值大于根节点值
"""
def __init__(self, node=None):
self.root = node
self.size = 0
def insert(self, val):
"""
二叉树插入操作: 若插入节点的值比根节点值小,则将其插入根节点的左子树;
若比根节点值大,则插入到根节点右子树
"""
if self.root is None:
self.root = TNode(val)
else:
self.insert_node(val, self.root)
def insert_node(self, val, bt_node):
if val < bt_node.data:
if bt_node.left is None:
bt_node.left = TNode(val)
return
self.insert_node(val, bt_node.left)
elif val > bt_node.data:
if bt_node.right is None:
bt_node.right = TNode(val)
return
self.insert_node(val, bt_node.right)
def insert_loop(self, key):
"""循环版本"""
node = TNode(key)
if self.root is None:
self.root = node
self.size += 1
else:
cur_node = self.root
while True:
if key < cur_node.data:
if cur_node.left:
cur_node = cur_node.left
else:
cur_node.left = node
self.size += 1
break
elif key > cur_node.data:
if cur_node.right:
cur_node = cur_node.right
else:
cur_node.right = node
self.size += 1
break
else:
break
def find_min(self, root):
"""查询最小值: 最左节点"""
if root.left:
return self.find_min(root.left)
return root
def find_max(self, root):
"""查询最大值: 最右子节点"""
if root.right:
return self.find_max(root.right)
return root
def delete(self, root, key):
"""
case1:待删除节点为叶子节点,直接删除
case2:待删除节点只有左子树或只有右子树,则把其左子树或右子树代替为待删除节点
case3:待删除节点既有左子树又有右子树,那么该节点右子树中最小值节点,使用该节点代替待删除节点,然后在右子树中删除最小值节点。
:param key:
:return:
"""
if root is None:
return
if key < root.data:
root.left = self.delete(root.left, key)
elif key > root.data:
root.right = self.delete(root.right, key)
else:
# 叶子节点,直接删除
if root.left is None and root.right is None:
root = None
# 只有左子树或右子树
elif root.left is None:
root = root.right
elif root.right is None:
root = root.left
# 既有左子树又有右子树
elif root.left and root.right:
tmp_node = self.find_min(root.right) # 找到右子树中最小值节点
root.data = tmp_node.data # 替换待删除节点值
root.right = self.delete(root.right, tmp_node.data) # 删除右子树中最小值节点
return root
def print_tree(self, node):
if node is None:
return
print(node.data, end=', ')
self.print_tree(node.left)
self.print_tree(node.right)
def BTree_test():
tree = BTree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
print('前序遍历:\n')
tree.pre_travel(tree.root)
print('\n')
tree.pre_travel_stack(tree.root)
print('\n')
print('中序遍历:\n')
tree.mid_travel(tree.root)
print('\n')
tree.mid_travel_stack(tree.root)
print('\n')
print('后续遍历:\n')
tree.post_travel(tree.root)
print('\n')
tree.post_travel_stack(tree.root)
print('\n')
print('层次遍历:\n')
tree.bread_travel()
def BSTree_test():
tree1 = BSTree()
for i in [17, 5, 2, 16, 35, 29, 38]:
tree1.insert_loop(i)
tree1.print_tree(tree1.root)
print('\n')
tree2 = BSTree()
for i in [17, 5, 2, 16, 35, 29, 38]:
tree2.insert(i)
tree2.print_tree(tree2.root)
print('\n删除节点:\n')
tree1.delete(tree1.root, 35)
tree1.print_tree(tree1.root)
if __name__ == "__main__":
# BTree_test()
BSTree_test() |
e21672469f7cae4648e349b22855e6e33229faaa | jonasluz/mia-cana | /Playground/radix_sort.py | 1,082 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 20 15:52:57 2017
@author: Jonas de A. Luz Jr <unifor@jonasluz.com>
"""
import array
def findK(A):
"""
Determina o valor de k, caso não seja conhecido (em geral, o é).
"""
assert len(A) > 0
k = A[0]
for i in range(0, len(A)):
if A[i] > k:
k = A[i]
return k
def countSort(A, k=None):
"""
Ordenação por contagem.
"""
if k == None:
# Encontra o valor de k.
k = findK(A)
k += 1
## Criação e inicialização dos arrays.
# @see http://stackoverflow.com/questions/521674/initializing-a-list-to-a-known-number-of-elements-in-python
length = len(A)
B, C = array.array('I',(0,)*length), array.array('I',(0,)*k)
for i in range(0, length):
C[A[i]] += 1
for i in range(1, k):
C[i] += C[i-1]
for i in range(length-1, -1, -1):
B[C[A[i]]-1] = A[i]
C[A[i]] -= 1
return list(B)
## TODO: radix sort.
"""
Rotinas de teste
"""
test = [2, 8, 7, 1, 13, 5, 6, 4]
test = countSort(test)
print(test) |
b7500140246800cc60a4abd6dc39d4801e6e872d | jedzej/tietopythontraining-basic | /students/serek_wojciech/lesson_03_functions/fibonacci_numbers.py | 294 | 3.8125 | 4 | #!/usr/bin/env python3
"""Fibonacci numbers"""
def fib(value):
"""Fibonacci numbers"""
if value == 1 or value == 2:
return 1
return fib(value - 1) + fib(value - 2)
def main():
"""Main function"""
print(fib(int(input())))
if __name__ == '__main__':
main()
|
3679b632cdafaac2d55d2dd377d498e80e8dbfc8 | kennyfrc/pybasics | /codewars/phone_number2.py | 159 | 3.671875 | 4 |
def phone_number(num):
num_str = ''.join(map(str,num))
return '(%s) %s-%s'%(num_str[:3],num_str[3:6],num_str[6:])
print(phone_number([1,2,3,4,5,6,7,8,9])) |
20bb6d298aa025b38641983432afa2937481e376 | fredichisar/p3-OC-MacGyver | /classes.py | 5,470 | 4.03125 | 4 | #!/usr/bin/python3
# -*- coding: Utf-8 -*
"""Classes of MacGyver maze"""
import pygame
from pygame.locals import *
from constants import *
from random import sample, choice
class Level:
"""Class to create a level (map)"""
def __init__(self, file):
self.file = file
self.structure = 0
def create(self):
"""Method to create a level from a file.
We create a global list containing a list per line to display"""
# Open the file
with open(self.file, "r") as file:
level_structure = []
# Travel across file lines
for line in file:
level_line = []
# Travel across sprites (letters) inside the file
for sprite in line:
# Ignore "\n" from end lines
if sprite != '\n':
# Add sprites to the line list
level_line.append(sprite)
# Add line to level list
level_structure.append(level_line)
# Save the level structure
self.structure = level_structure
# Select randomly 3 lines
rand_lines = sample([r for r in range(len(self.structure))], 3)
# Select randomly a 0 from 1st random line
ether = sample([i for i, val in enumerate(
self.structure[rand_lines[0]]) if '0' in val], 1)
# Select randomly a 0 from 2nd random line
needle = sample([i for i, val in enumerate(
self.structure[rand_lines[1]]) if '0' in val], 1)
# Select randomly a 0 from 3rd random line
plastic_tube = sample([i for i, val in enumerate(
self.structure[rand_lines[2]]) if '0' in val], 1)
# Replace old 0 by our items letters
self.structure[rand_lines[0]][ether[0]] = 'e'
self.structure[rand_lines[1]][needle[0]] = 'n'
self.structure[rand_lines[2]][plastic_tube[0]] = 'p'
def display(self, window):
"""Method to display the level from the list returned by create()"""
# Load assets
wall = pygame.image.load(img_wall).convert()
finish = pygame.image.load(img_guardian).convert_alpha()
ether = pygame.image.load(image_ether).convert_alpha()
needle = pygame.image.load(image_needle).convert_alpha()
plastic_tube = pygame.image.load(image_plastic_tube).convert_alpha()
syringe = pygame.image.load(image_syringe).convert_alpha()
# Travel across level list
lin_number = 0
for line in self.structure:
# Travel across line lists
num_case = 0
for sprite in line:
# Compute real position in pixels
x = num_case * sprite_size
y = lin_number * sprite_size
if sprite == 'w': # w = Wall
window.blit(wall, (x, y))
elif sprite == 'f': # f = Finish
window.blit(finish, (x, y))
elif sprite == 'e': # e = Ether
window.blit(ether, (x, y))
elif sprite == 'n': # n = Needle
window.blit(needle, (x, y))
elif sprite == 'p': # f = Plastic tube
window.blit(plastic_tube, (x, y))
elif sprite == 'g': # f = Plastic tube
window.blit(syringe, (x, y))
num_case += 1
lin_number += 1
class Player:
"""Class to create a character"""
def __init__(self, img, level):
# Character sprites
self.character = pygame.image.load(img_mac_gyver).convert_alpha()
# Character posdition in boxes and and pixels
self.case_x = 0
self.case_y = 0
self.x = 0
self.y = 0
# Default direction
self.direction = self.character
# Character level
self.level = level
def move(self, direction):
"""Method to move the character"""
# Move to the right
if direction == 'right':
# Check for screen size
if self.case_x < (sprite_side_number - 1):
# Check next box isn't a wall
if self.level.structure[self.case_y][self.case_x+1] != 'w':
# Move for 1 box
self.case_x += 1
# Compute real position in pixels
self.x = self.case_x * sprite_size
self.direction = self.character
# Move to the left
if direction == 'left':
if self.case_x > 0:
if self.level.structure[self.case_y][self.case_x-1] != 'w':
self.case_x -= 1
self.x = self.case_x * sprite_size
self.direction = self.character
# Move up
if direction == 'up':
if self.case_y > 0:
if self.level.structure[self.case_y-1][self.case_x] != 'w':
self.case_y -= 1
self.y = self.case_y * sprite_size
self.direction = self.character
# Move down
if direction == 'down':
if self.case_y < (sprite_side_number - 1):
if self.level.structure[self.case_y+1][self.case_x] != 'w':
self.case_y += 1
self.y = self.case_y * sprite_size
self.direction = self.character
|
354924dc3d6950e4e623d9b8d6575bec19373fe7 | someoneb100/my_termux_env | /python_modules/timer.py | 530 | 3.53125 | 4 | from time import process_time as pt
#has 4 keyword parameters
#pre - function to be called before timing
#func - timed function
#post - called after timing
#n - number of execution for averaging time
def timer(pre = None, func = None, post = None, n = 1):
suma, t = 0.0, 0
a = lambda x: (lambda: _) if x is None else x
pre, func, post = a(pre), a(func), a(post)
for _ in range(n):
pre()
temp = pt()
func()
suma += pt() - temp
post()
return suma/n
|
2004c168f87c1e1d4bb401fcb5bc6216a7305c98 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Tickets.py | 358 | 3.75 | 4 | for _ in range(int(input())):
"""s=input().upper()
if s[0]!=s[1]:
if (s.count(s[0]+s[1]))*2<=len(s):
print("YES")
continue
print("NO")"""
s=set(input())
if len(s)==2:
print("YES")
else:
print("NO")
#WRONG QUESTION/TEST CASES BRO.. LOL.. ABBABA SHOULD GIVE "NO" BUT 100pts FOR "YES" LMAO |
9e3f1329d9d28770488ff772039f466956e29894 | mouraa0/python-exercises | /exercises/ex070.py | 762 | 3.703125 | 4 | def ex070():
preco_total = 0
maior = 0
mais_barato = None
condicao = 'S'
while condicao == 'S':
nome = input('Nome do produto: ')
preco = float(input('Valor do produto: R$'))
preco_total += preco
if mais_barato is None:
mais_barato = nome
preco_barato = preco
elif preco < preco_barato:
preco_barato = preco
mais_barato = nome
if preco > 1000:
maior += 1
condicao = input('Deseja continuar? [S/N]: ').upper()
print('-'*20)
print(f'Preço total: R${preco_total:.2f}\nProdutos com mais de R$1000.00: {maior}\nProduto mais barato: {mais_barato}')
ex070()
|
b29fc02bb1aac85072cd6cb47b0fb97734409404 | Rob174/detection_nappe_hydrocarbures_IMT_cefrem | /main/src/data/balance_classes/BalanceClassesNoOther.py | 1,496 | 3.703125 | 4 | """Balance classes by excluding patches where there is only the other class"""
import numpy as np
from main.src.data.balance_classes.AbstractBalance import AbstractBalance
from main.src.param_savers.BaseClass import BaseClass
class BalanceClassesNoOther(BaseClass, AbstractBalance):
def __init__(self, other_index):
"""Balance classes by excluding patches where there is only the other class
Args:
other_index: index of the class other
"""
super().__init__()
self.attr_other_index = other_index
self.attr_num_accepted = 0
self.attr_name = self.__class__.__name__ # save the name of the class used for reproductibility purposes
self.attr_global_name = "balance" # save a more compehensible name
def filter(self, classification_label):
"""method called during training to know if we have to filter this sample or not based on its classification_label
Args:
classification_label: label with ones of a class is on the image and 0 if not. !! Must be provided by NoLabelModifier make_classification_label method for the shape of the labels (with full details)
Returns:
bool, tell if the sample is accepted or rejected
"""
if len(classification_label[classification_label > 0]) == 1 and np.argmax(
classification_label) == self.attr_other_index:
return True
self.attr_num_accepted += 1
return False
|
a81c0672c4a0af43b5778417e4c026ba39489dcb | 4ar0n/fifthtutorial | /homework2.1_a2_day.py | 5,304 | 3.546875 | 4 |
import csv
from pprint import pprint
from datetime import datetime
from collections import OrderedDict
def get_csv_dict(file):
data = []
with open(file) as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
for row in csv_reader:
data.append(dict(row))
# pprint (data)
return data
# return data
def post_csv_dict(data,csv_columns,filename):
try:
with open(output_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for row in data:
writer.writerow(row)
except IOError:
print("I/O error")
def make_sma_dict(data,field_name,day):
#trimmed_day_data is declared for to hold only the last data of the day
trimmed_day_data=OrderedDict()
#sma_dict is the ultimate product of this function which provides a lookup table for "date" to "sma"
sma_dict={}
for entry in data:
if entry['datetime'][11:] in ["11:00:00","20:00:00","21:00:00","22:00:00","23:00:00"]:
trimmed_day_data[entry['datetime'][:10]]=float(entry[field_name])
# {'2018-01-01':1433,'2018-01-02',1455}
#create an empty dictionary with only date keys e.g. {"2017-01-09":0,"2017-01-10":0,.... }
sma_dict[entry['datetime'][:10]] = "None"
#below is the loop to insert the sma value into the dictionary.
for date , sma in sma_dict.items():
#1 . mark down the position of the array found for later use
pos = None
#2. for every date in the sma_dict , loop the trimmed data to find the index of the trimmed data where the date is found.
for i in range (0,len(trimmed_day_data)):
# its a little bit complicated because, unlike list its its not that straight forward to get the KEY of the dictionary,
# list(trimmed_day_data.items()) is the ith element , and then we need to turn it to the list, so that the key becomes the [0] of the list
if date == list(trimmed_day_data.items())[i][0]:
pos = i
#once found, break the loop
break
# to make sure pos is found
if pos is not None:
first_day_str = (list(trimmed_day_data.items())[0][0])
first_day = datetime.strptime(first_day_str, '%Y-%m-%d')
today = datetime.strptime(date, '%Y-%m-%d')
#list(trimmed_day_data).index(date) returns the index of the date in the trimmed_day_data
# make sure there are day-number of data because calculating day-sma
if list(trimmed_day_data).index(date) >= day :
total = 0
for j in range(pos-day,pos):
# when pos is 7, j is 0
# then j is 1
# then j is 2... until j is 6, when 7 data is added to the total and the sma is calculated.
total += list(trimmed_day_data.items())[j][1]
sma_dict[date] = round(total / day,2)
return sma_dict
def insert_sma(data,day,field_name):
for i in range (0,len(data)):
data[i][field_name+"_sma"] = sma_dict.get(data[i]['datetime'][:10],None)
return data
def trade(data,percentage,day,field_name):
data = insert_sma( data , day , field_name )
asset = profit = lot = 0
for i in range( 0,len(data) ):
if data[i][field_name+"_sma"] != "None":
if float(data[i][field_name]) > data[i][field_name+"_sma"]*(1+percentage):
data[i]["decision"] = "Buy"
lot +=1
asset += float(data[i]['close'])
elif float(data[i][field_name]) < data[i][field_name+"_sma"]*(1-percentage):
if lot>0:
data[i]["decision"] = "Square"
cost = asset
asset = 0
revenue = float(data[i]['close'])*lot
lot = 0
profit += (revenue - cost)
else:
data[i]["decision"] = "Hold"
else:
data[i]["decision"] = "Hold"
output = {
"csv" : data,
"profit" : profit,
"asset" : asset,
"lot" : lot,
}
return output
au_raw_file = "/Users/aaronlee/pycourse/lesson2/datasets/FX_XAUUSD_intraday_60.csv"
au_raw_data = get_csv_dict(au_raw_file)
# pprint (au_raw_data)
day = 3
sma_dict = make_sma_dict(au_raw_data,"close",day)
au_trade_data = trade(au_raw_data,0.01,day,"close")
# max_profit = best_rate = best_day = 0
# start = 1
# end = 30
# for i in range (start,end):
# rate = i/1000
# for day in range(3,21):
# # print (rate,day)
# au_trade_data = trade(au_raw_data,rate,day,"close")
# if au_trade_data["profit"] > max_profit:
# max_profit = au_trade_data["profit"]
# best_day = day
# best_rate = rate
# print (max_profit , best_rate , best_day)
csv_columns=[]
# pprint (au_trade_data)
for k, v in au_trade_data['csv'][-1].items():
csv_columns.append(k)
# pprint (csv_columns)
output_file = au_raw_file[:-4]+"_results.csv"
post_csv_dict(au_trade_data['csv'],csv_columns,output_file)
|
8e6e3387704b63262edbf3d44949a2e3e7d1e804 | RobinsonTran/rt-django-repo | /lpthw/ex6.py | 892 | 4.28125 | 4 | types_of_people = 10 # variable for x
x = f"There are {types_of_people} types of people." # 1st verison of string formatting
binary = "binary" # variable for f-stringing stuff
do_not = "don't" # variable for f-stringing stuff
y = f"Those who know {binary} and those who {do_not}." # both previous variables used for y string statement formatting
print(x) # printing "x" with f-string
print(y) # printing "y" with f-string
print(f"I said: {x}") # writing f-string with x statement
print(f"I also said: '{y}'") # writing f-string with y statement
hilarious = False # stored variable
joke_evaluation = "Isn't that joke so funny?! {}" # first part to f-string statment below
print(joke_evaluation.format(hilarious)) # f-string statement with hilarious and joek_evaluation variables used
w = "This is the left side of ..." # simple string tie
e = "a string with a right side."
print(w + e)
|
f341989002cfa56c43b94b5d294d107c6329b03d | PDXCodeGuildJan/CourseAssignments | /merge_sort.py | 853 | 3.71875 | 4 | __author__ = "Tiffany Caires"
"""Implements the merge sort algorithm, recursively, in Python."""
def main():
"""Take a random list and use merge_sort to sort it"""
unsorted = [4, 7, 14, 2, 94, 38, 2]
sorted = merge_sort(unsorted)
print(sorted)
def merge_sort(unsorted):
"""Implement the merge sort algorithm"""
# Third Simplest
pass
# merge_sort
# Split the list into two halves, if list length more than 1
# first_sorted = sort the first half using merge_sort
# second_sorted = sort the second half using merge_sort
# merge the two sorted halves back together into a merged list
# return the merged, sorted list
def merge(list_1, list_2):
"""Given two lists, merge them together into a third list,
which is sorted."""
# Second Simplest
pass
if __name__ == '__main__':
main() |
d088308e4527bb250fdedffbb9eb50819a8b8e44 | MrunalPuram/gamma-ai | /pairidentification/heptrkx-gnn-tracking/models/cnn_classifier.py | 1,581 | 3.515625 | 4 | """
This module defines a generic CNN classifier model.
"""
# Externals
import torch.nn as nn
class CNNClassifier(nn.Module):
"""
Generic CNN classifier model with convolutions, max-pooling,
fully connected layers, and a multi-class linear output (logits) layer.
"""
def __init__(self, input_shape, n_classes, conv_sizes, dense_sizes, dropout=0):
"""Model constructor"""
super(CNNClassifier, self).__init__()
# Add the convolutional layers
conv_layers = []
in_size = input_shape[0]
for conv_size in conv_sizes:
conv_layers.append(nn.Conv2d(in_size, conv_size,
kernel_size=3, padding=1))
conv_layers.append(nn.ReLU())
conv_layers.append(nn.MaxPool2d(2))
in_size = conv_size
self.conv_net = nn.Sequential(*conv_layers)
# Add the dense layers
dense_layers = []
in_height = input_shape[1] // (2 ** len(conv_sizes))
in_width = input_shape[2] // (2 ** len(conv_sizes))
in_size = in_height * in_width * in_size
for dense_size in dense_sizes:
dense_layers.append(nn.Linear(in_size, dense_size))
dense_layers.append(nn.ReLU())
dense_layers.append(nn.Dropout(dropout))
in_size = dense_size
dense_layers.append(nn.Linear(in_size, n_classes))
self.dense_net = nn.Sequential(*dense_layers)
def forward(self, x):
h = self.conv_net(x)
h = h.view(h.size(0), -1)
return self.dense_net(h)
|
5f68ce5a34d7aee154428d6fdd3dafc2b3830fbd | MaxLavrinenko/Python_okten | /hw4.py | 4,434 | 4.40625 | 4 | # Создать класс Rectangle:
# -конструктор принимает две стороны x,y
# -описать арифметические методы:
# + сума площадей двух экземпляров класса
# - разница площадей
# == или площади равны
# != не равны
# >, < меньше или больше
# при вызове метода len() подсчитывать сумму сторон
# class Rectangle:
# def __init__(self, x, y):
# self.y = y
# self.x = x
#
# def area(self):
# return self.x * self.y
#
# def __add__(self, other):
# return self.area() + other.area()
#
# def __sub__(self, other):
# return self.area() - other.area()
#
# def __eq__(self, other):
# return self.area() == other.area()
#
# def __ne__(self, other):
# return self.area() != other.area()
#
# def __lt__(self, other):
# return self.area() < other.area()
#
# def __gt__(self, other):
# return self.area() > other.area()
#
# def __len__(self):
# return (self.x + self.y) * 2
#
# rectangle1 = Rectangle(3,4)
# rectangle2 = Rectangle(2,3)
# print(rectangle1.area())
# print(rectangle2.area())
# print(rectangle1 + rectangle2)
# print(rectangle1 - rectangle2)
# print(rectangle1 == rectangle2)
# print(rectangle1 != rectangle2)
# print(rectangle1 > rectangle2)
# print(rectangle1 < rectangle2)
# print(len(rectangle1))
# print(len(rectangle2))
########################################################################################
# Це завдання на наслідування... все максимально розбити по классах
#
# 1) написати програму для запису відомостей про пасажирські перевезення
# 2) перевезення відбувається трьома способами, літаком, машиною, поїздом,
# 3) дані які треба буде зберігати:
# - вартість квитка(літак, поїзд)
# - кількість пасажирів(машина)
# - час в дорозі(всі)
# - час реєстрації(літак)
# - клас:перший,другий(літак)
# - вартість пального(машина)
# - км(машина)
# - місце: купе,св(поїзд)
# 4) методи:
# - розрахунок вартості доїзду(машина)
# - загальний час перельоту(літак)
# - порівняти час в дорозі між двома будь якими транспортними засобами(двома об'єктами) - наприклад"літак на 5 годин швидше за поїзд"
# - вивести всі дані про перевезення(поїзд)
######################################################################
# 1)Створити пустий list
# 2)Створити клас Letter
# 3) створити змінну класу __count.
# 4) при створенні об'єкта має створюватись змінна об'єкта(пропертя) __text, для цієї змінної мають бути гетер і сетер
# 5) при створені об'єкта __count має збільшуватися на 1
# 6) має бути метод(метод класу) для виводу __сount
# 7) має бути метод який записує в наш ліст текст з нашої змінної __text
#
# l = []
#
#
# class Letter:
# __count = 0
#
# def __init__(self, text):
# self.__text = text
# self.__up_count()
#
# def set_text(self, text):
# self.__text = text
#
# def get_text(self):
# return str(self.__text)
#
# @classmethod
# def __up_count(cls):
# cls.__count += 1
#
# @classmethod
# def get_count(cls):
# return cls.__count
#
# def text_to_list(self):
# l.append(self.__text)
#
#
# letter1 = Letter('text1')
# letter2 = Letter('text2')
# print(letter1.get_text())
# print(letter2.get_text())
# letter1.text_to_list()
# letter2.text_to_list()
# print(l)
# print(Letter.get_count())
# letter1.set_text('textset1')
# print(letter1.get_text())
# letter2.set_text('settext2')
# print(letter2.get_text()) |
052af12e6487a076f1d71ec4c76c2553a18a73e9 | ImaniNgugi50/Data-Science-projects | /p1.py | 141 | 3.6875 | 4 | import pandas as pd
d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9,5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print(df)
|
fe4823fc78f1d7aba084f79ccbc1dde4baccd40a | Siyuan-Liu-233/Python-exercises | /python小练习/017田忌赛马.py | 924 | 3.90625 | 4 | # 这题也是华为面试时候的机试题:
# “ 广义田忌赛马:每匹马都有一个能力指数,齐威王先选马(按能力从大到小排列),田忌后选,马的能力大的一方获胜,若马的能力相同,也是齐威王胜(东道主优势)。”
# 例如:
# 齐威王的马的列表 a = [15,11,9,8,6,5,1]
# 田忌的马的候选表 b = [10,8,7,6,5,3,2]
# 如果你是田忌,如何在劣势很明显的情况下,扭转战局呢?
# 请用python写出解法,输出田忌的对阵列表 c及最终胜败的结果
# 评分
a = [8,15,1,11,6,5,9]
b = [2,8,6,7,5,3,10]
import numpy as np
a,b=np.array(np.sort(a)),np.array(np.sort(b))
x=np.shape(a)[0]
print(a,b)
time=0
print((a-b)>0)
while (((a-b)>0).sum())>=x/2 and time<x:
temp=b[-1-time]
b[0:-1-time],b[-1-time]=b[1:x-time],b[0]
time+=1
if ((a-b)>0).sum()<x/2:
print("获胜方案为:",a,b)
else:
print('无法获胜')
|
1dcc11ab5a82fce16aed96854ac5dc5862b8777f | HandeulLy/CodingTest | /Programmers/짝수와홀수.py | 190 | 3.828125 | 4 | # Solution 1
def solution1(num):
if num%2==0 : return "Even"
else : return "Odd"
############
# Solution 2
def solution2(num):
return "Even" if num%2 == 0 else "Odd" |
ef9be9e92e1ded6a556a4a0b663d1cac3b510fe3 | ledbagholberton/holbertonschool-higher_level_programming | /0x08-python-more_classes/chess.py | 1,899 | 4.15625 | 4 | #!/usr/bin/python3
"""Queen Chess challenge
"""
def printSolution(board, n):
for i in range(n):
for j in range(n):
print(board[i][j]),
print()
def isSafe(board, row, col, n):
""" Found if a position is safe or atacked by other Queen
Arguments:
board: Position of other queens
row: row position to analyze
col: col position to analyze
Return: True if position is safe for a new Queen
"""
""" veriying the row on left side """
for i in range(col):
if board[row][i] == 1:
return False
""" veriying upper diagonal on left side """
for i,j in zip(range(row,-1,-1), range(col,-1,-1)):
if board[i][j] == 1:
return False
""" veriying upper diagonal on left side """
for i,j in zip(range(row, n, 1), range(col,-1,-1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col, n):
""" Found if a queen was placed on the column
Arguments:
board: Position of other queens
col: col position to analyze
Return: True if all queens has been placed
false if the queen cannot be placed in all the col
"""
if col >= n:
return True
""" Iter by col tryng to place the Queen row by row"""
for i in range(n):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col+1) == True:
return True
board[i][col] = 0
return False
def solveNQ(n):
""" Starting in an empty board, the function look for an arrange
of Queens complying the challenge"""
board = []
for i in range(n):
for j in range(n):
board[i][j].append(0)
if solveNQUtil(board, 0, n) == False:
print("Solution does not exist")
return False
printSolution(board)
return True
solveNQ(4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.