blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
e58e2b78b45e66a480d412af07ec8ee954230556 | BreeBot/IntroToProg-Python | /Assigment07.py | 986 | 4.40625 | 4 | #-------------------------------------------------#
# Title: Working with Dictionaries
# Dev: Breana K. Merriweather
# Date: August 26, 2019
# ChangeLog:
#-------------------------------------------------#
#1). Create a simple example of how you would use Python Exception Handling.
#Demonstrate handling exceptions
Miles = int(input("Please Enter Total Miles Driven: "))
Gallon = int(input("Please Enter Gallons of Gas Used: "))
MPG = 0
try:
MPG = int(Miles/Gallon)
except ZeroDivisionError:
print("Please Try Again.")
print("Your MPG is: ",MPG)
#2). Create a simple example of how you would use Python Pickling.
#import pickle
import pickle
#ask user for personal information
fstName = str(input("Enter your First Name: "))
lstName = str(input("Enter your Last Name: "))
userInfo = [fstName, lstName]
print(userInfo)
#Store data with the pickle.dump
objFile = open("users.dat", "ab")
pickle.dump(userInfo, objFile)
objFile.close()
|
37e447400336b7c839e1b305b66ce5f228edf7e4 | MihirMore/Fun-Python-Projects | /Guess_the_number/user-guess.py | 789 | 4.40625 | 4 | # Guess the number is a game where user is asked to guess a number, the computer then comments if the number is high, low or the correct number.
# Here we are using the random function to generate a random number betwwen x to y.
import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = int(input(f"Guess a integer between 1 and {x}: "))
if guess < random_number:
print("Oops!, guess again. You guessed too low.")
elif guess > random_number:
print("Oops!, guess again. You guessed too high.")
print(f"Yay! Congrats you've guessed the number {random_number}.")
guess(10)
|
efc1f55a43fd4532c3b6cde9276d996e0faa304e | cyclades1/Python-Programs | /p11.py | 107 | 3.53125 | 4 | '''input
12
3
'''
n = int(input())
c = int(input())
if(n%c==0):
print("YES")
else:
print("No")
|
597f7f559071465f21323f205d4ec503b5efec5f | Dpalazzari/codeChallenges | /Python/basic_stack/basic_stack.py | 810 | 3.65625 | 4 | from itertools import chain
class BasicStack(object):
def push_to_array(self, arr, num):
return list(chain.from_iterable([arr, [num]]))
def push_to_array_with_append(self, arr, num):
arr.append(num)
return arr
def remove_last_element(self, arr):
arr = arr[0:-1]
return arr
def remove_last_element_with_pop(self, arr):
arr.pop()
return arr
def count_elements_in_list(self, arr):
count = 0
for index in arr:
count += 1
return count
def count_elements_in_list_with_len(self, arr):
return len(arr)
def maximum_number_in_list(self, arr):
max_num = 0
while (len(arr) > 0):
num = arr.pop()
if num > max_num:
max_num = num
return max_num
def maximum_number_in_list_with_max(self, arr):
return max(arr) |
e9479627d41cb048285a0af07494884aa295ff6b | Alex-Wei-bot/python-learning-diary | /exercise code/day3.1.py | 304 | 4.1875 | 4 | #英尺厘米换算
i=float(input('input an number'))
j=input('is it inch or centimeter?')
if j == 'inch':
inch=i
centimeter=inch*2.54
print(f'the length in centimeter is {centimeter:.2}')
else:
centimeter=i
inch=centimeter/2.54
print('the length in inch is %.2f' %inch) |
1f496a7e604f3449f03d945b34a3517741b198a0 | nikithasake/Python | /python coding(prep)/fibonnaci.py | 134 | 4.09375 | 4 | #fibonaci
def fib(n):
if n==1:
return 0
if n==2:
return 1
return fib(n-1)+fib(n-2)
n=int(input("Enter input:"))
print(fib(n))
|
38945d14315783bf445d82814180c28b7f9dfc0e | alysonla/Full-Stack | /names.py | 830 | 4.46875 | 4 | # Open names.txt file
# Write a Python script which loads the names from the file, and converts your own name to a
# superhero (or supervillain) name by picking the name corresponding to your first name's position
# in the alphabet (there are 26 superheroes in the list). For example, if your name starts with A,
# you want superhero name #1. Mine (J) is name #10.
with open('names.txt') as f:
data = f.readlines()
# for name in data:
# print name.strip()
# Figure out how to put all in list & access the list
# Here's a snippet of code to help with the letter part of this:
import string
uppers = string.uppercase
# print uppers # this will help you figure out what this is
a_position = uppers.find('A') # .find shows you what position the letter is in.
print a_position
print data[a_position].strip()
|
b07323b38c4b60f7da1307ca9d870fbc059a9d51 | greend6807/cti110 | /CTI 110/P4T1A_Green/P4T1A_Green.py | 689 | 4.125 | 4 | #CTI-110
#P4T1A_Green
#Darius Green
#11/20/18
import turtle #Allows us to use turtle.
wn = turtle.Screen() #Creates a playground for turtles
blues = turtle.Turtle() #Create a turtle, assign to blues
#Display options
blues.pensize(3)
blues.pencolor("blue")
blues.shape("turtle")
#Have the turtle draw out the shape you want.
#Square first.
#Use for or whole loops to execute.
for i in [0, 1, 2, 3]:
blues.forward(100)
blues.left(90)
#Reposition
blues.left (150)
blues.penup()
blues.forward(50)
blues.pendown()
blues.left (90)
#Triangle Second.
for x in [0, 1, 2, 3]:
blues.forward(100)
blues.left(120)
|
d449d303b2831c9198b4018dcacd1fa7b1a9fa30 | Kapo4eso4i/CheckIO | /Home/Pawn Brotherhood.py | 363 | 3.609375 | 4 | def safe_pawns(pawns):
letters = [' ', 'a', 'b', 'c', 'd', 'e' , 'f', 'g', 'h', ' ']
safe_place = []
for pawn in pawns:
next_row = str(int(pawn[1])+1)
safe_place += [letters[letters.index(pawn[0])+1] + next_row,
letters[letters.index(pawn[0])-1] + next_row]
return len([x for x in pawns if x in safe_place])
|
e9e60f5bbaad2e4111ba98e77d0605ff628c76a8 | SeungpilHan/Python_Tutorial | /Desktop/Coding/Jump to Python/practice.py | 69 | 3.765625 | 4 | for a in [1,2,3]:
print(a)
i = 0
while i < 3:
i=i+1
print(i) |
d8355d46dc6b0aac828f6c6249e7ce07d507b28a | ZhengweiHou/python-learn-hzw | /optionSYS_test/进程同步/mutex_lock_demo_lock.py | 980 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
lock = threading.Lock() # 定义一个互斥量-互斥锁
num = 0
def producer():
global num
times = 1000000
while times >0 :
global lock
lock.acquire() # 加锁
num += 1
lock.release() # 解锁
times -= 1
print('producer end!!')
def comsumer():
global num
times = 1000000
while times >0 :
global lock
lock.acquire() # 加锁
num -= 1
lock.release() # 解锁
times -= 1
print('comsumer end!!')
if __name__ == '__main__':
print('start in main function.')
p = threading.Thread(target=producer)
c = threading.Thread(target=comsumer)
p.start()
c.start()
p.join() # main wait p end
c.join() # main wait c end
print('Print in mian function: num = %d' % num)
# 输出:
# start in main function.
# producer end!!
# comsumer end!!
# Print in mian function: num = 0
|
a60249008de805cbb06538751ceddfa93568d9d1 | oereo/Algorithm_thursday | /YounJongSu/mid_hw/quick_sort.py | 577 | 3.8125 | 4 | def partition(arr, l, h):
i = l-1
piv = arr[h]
for j in range(l, h):
if arr[j]<piv:
i+=1
arr[i],arr[j]=arr[j],arr[i]
print(arr)
arr[i+1],arr[h] = arr[h], arr[i+1]
print(arr)
print("pt end")
print(i+1)
return i+1
def quickSort(arr, l, h):
if l<h:
pi = partition(arr, l, h)
quickSort(arr, l, pi-1)
quickSort(arr, pi+1, h)
print("qs end")
arr = [10, 7, 1, 8]
n = len(arr)
print("given arr: {}".format(arr))
quickSort(arr,0,n-1)
print("Sorted arr: {}".format(arr))
|
ff733043a6af1f002e7fc938b53947ad137bbc94 | thomasmontoya123/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/9-Adam.py | 1,116 | 3.703125 | 4 | #!/usr/bin/env python3
"""Adam module"""
def update_variables_Adam(alpha, beta1, beta2, epsilon, var, grad, v, s, t):
"""
updates a variable in place using the Adam optimization algorithm
Parameters
----------
alpha : float
learning rate
beta1 : float
weight used for the first moment
beta2 : float
weight used for the second moment
epsilon : float
small number to avoid division by zero
var : numpy.ndarray
contains the variable to be updated
grad : numpy.ndarray
contains the gradient of var
v : previous first moment of var
s : is the previous second moment of var
t : time step used for bias correction
"""
v = (v * beta1) + ((1 - beta1) * grad)
v_hat = v / (1 - (beta1 ** t))
s = (s * beta2) + ((1 - beta2) * (grad ** 2))
s_hat = s / (1 - (beta2 ** t))
var = var - ((alpha * v_hat) / (s_hat ** (1 / 2) + epsilon))
return var, v, s
|
47e7512a8c8dec280aab01d06218cc8b5a37c808 | Marie-EveGauthier/whatIShouldWatch | /bin/tag-analysis/process_categories.py | 867 | 4.3125 | 4 | import pandas as pd
filename1 = raw_input("Enter the name of the file you want to process categories from:\n")
#Import the data in file as a pandas object
data = pd.read_csv(filename1, names = ['name', 'categories'])
#get a list of names who don't have entries in wikipedia
no_categories = data[data.categories.isnull()]['name'].tolist()
#and saves it to a file
filename2 = raw_input("Enter a filename to save the list of names with no entries on wikipedia:\n")
with open(filename2, 'wb') as h:
for name in no_categories:
h.write(name +'\n')
have_cats = data[data.categories.notnull()]
women = have_cats[have_cats['categories'].str.contains("women")]['name'].tolist()
filename3 = raw_input("Enter a filename to save the list of names of people who are women:\n")
with open(filename3, 'wb') as h:
for name in women:
h.write(name +'\n')
|
9c171f0dbca62bec644364ebb504ec5818ee3c2f | TuongTuan3T/PythonNC | /Lab05/Bai03.py | 364 | 3.75 | 4 | class Student:
def __init__(self, name:str, number: str, course:str, mail:str):
self.name = name
self.number = number
self.course = course
self.mail = mail
def __str__(self):
return ('{}\n{}\n{}\n{} '.format(self.name, self.number, self.course, self.mail))
pupil = Student('TuongTuan', '187it07012', '[email protected]', 'K10' )
##Câu a
print(pupil) |
95715c18eb0ec9519b481b0a667e38cb7b87e5bd | allankeiiti/Learning_Pytest | /modulo_2_validando_teste_com_erros_esperados.py | 1,087 | 3.875 | 4 | """
Aqui temos funções cujo possuem condições que caso sejam ou não atendidas, um erro é invocado e isso é esperado.
Portanto aqui é utilizado o pytest.raises(<Tipo de Erro>) para falar pro Pytest que este erro é esperado e que deve
ser invocado. Pois quando é testado um software também é necessário tentar quebrá-lo e ver como ele se comporta.
"""
import pytest
def validar_idade(idade: int):
if isinstance(idade, int):
if idade < 0:
raise ValueError(f'O valor passado: {idade} é inválido (Valor menor que 0)')
else:
raise ValueError(f'O valor passado: {idade}, não é um inteiro, por favor passe um valor do tipo Integer')
def test_validar_idade_valida():
"""
Item 1
:return:
"""
validar_idade(10)
def test_validar_idade_nao_valida():
"""
Item 2
:return:
"""
with pytest.raises(ValueError):
validar_idade(-1)
def test_validar_idade_string():
"""
Item 3
:return:
"""
with pytest.raises(ValueError):
validar_idade('allan')
|
5f377bc81345db5adaa1a3a32c3170f669048194 | alters-mit/tdw_sound20k | /tdw_scene_size.py | 837 | 3.65625 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
from numpy.random import RandomState
class TDWSceneSize(ABC):
"""
The size of a TDW scene room.
"""
@abstractmethod
def get_size(self) -> Tuple[int, int]:
"""
:return: The dimensions of the room.
"""
raise Exception()
class StandardSize(TDWSceneSize):
"""
A "normal-sized" room.
"""
def get_size(self) -> Tuple[int, int]:
return 12, 12
class SmallSize(TDWSceneSize):
"""
A small room.
"""
def get_size(self) -> Tuple[int, int]:
return 4, 4
class RandomSize(TDWSceneSize):
"""
A randomly-sized room.
"""
_RNG = RandomState(0)
def get_size(self) -> Tuple[int, int]:
return RandomSize._RNG.randint(4, 16), RandomSize._RNG.randint(4, 16)
|
215cd0b991f514076a58152eed8e2c2cd4839853 | hwins/triangle-puzzle-python3 | /TrianglePuzzlePython3/src/Triangle.py | 5,956 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
class Node_Tree_Element(object):
"""individual element of the node tree
These objects contain node information such as left child, right child,
level on the tree and node integer value
"""
def __init__(self, node_value):
assert isinstance(node_value, int)
self.__node_level = None
self.__node_value = node_value
self.__best_path_down = None
self.__left_child = None
self.__right_child = None
def get_nl(self):
return self.__node_level
def set_nl(self, node_level):
assert isinstance(node_level, int)
assert node_level > -1
self.__node_level = node_level
def del_nl(self):
pass
node_level = property(get_nl, set_nl, del_nl)
def get_nv(self):
return self.__node_value
def set_nv(self, node_value):
assert isinstance(node_value, int)
assert node_value > -1
self.__node_value = node_value
def del_nv(self):
pass
node_value = property(get_nv, set_nv, del_nv)
def get_bpd(self):
return self.__best_path_down
def set_bpd(self, best_path_down):
assert isinstance(best_path_down, str)
self.__best_path_down = best_path_down
def del_bpd(self):
pass
best_path_down = property(get_bpd, set_bpd, del_bpd)
def get_lc(self):
return self.__left_child
def set_lc(self, left_child):
assert isinstance(left_child, int)
assert left_child > 0
self.__left_child = left_child
def del_lc(self):
pass
left_child = property(get_lc, set_lc, del_lc)
def get_rc(self):
return self.__right_child
def set_rc(self, right_child):
assert isinstance(right_child, int)
assert right_child > 0
self.__right_child = right_child
def del_rc(self):
pass
right_child = property(get_rc, set_rc, del_rc)
class Node_Tree(list):
"""this class is an extension of the list class
set to only allow Node_Tree_Elements in it
"""
def append(self, *args, **kwargs):
assert isinstance(args[0], Node_Tree_Element)
return list.append(self, *args, **kwargs)
def insert(self, *args, **kwargs):
assert isinstance(args[0], Node_Tree_Element)
return list.insert(self, *args, **kwargs)
def main(argv=None):
file_name = argv
number_of_levels = 0
number_of_elements = 0
nt = Node_Tree()
# load text files into the tree by creating elements based on input
# file contains lines with numbers, each line new level
# file must contain only valid integers with separating space
with open(file_name, encoding='utf-8') as file_in:
for line_in in file_in:
# remove trailing newline, etc.
line_in = line_in.rstrip()
split_line = line_in.split(" ")
for value_in in split_line:
nte = Node_Tree_Element(int(value_in))
nte.node_level = number_of_levels
number_of_elements += 1
nt.append(nte)
number_of_levels += 1
# now that all of the values are in the tree the left and right children
# locations need to be set so the tree can be traversed
# the last level - leaf nodes will be left null
this_element = 0
this_level = 0
add_child_pointers_below_these_levels = number_of_levels - 1
# only up to last level
while this_level < add_child_pointers_below_these_levels:
# left and right children are determined by a calculation to determine
# position in the tree based on input file
lc_position = this_element + this_level + 1
rc_position = lc_position + 1
nt[this_element].left_child = lc_position
nt[this_element].right_child = rc_position
this_element += 1
this_level = nt[this_element].node_level
# start at last node and roll up the best path for each node based on
# the either the left or right child
# use number of elements for relative subscript so decrease by 1
max_nodes = number_of_elements - 1
for i in range(max_nodes, -1, -1):
lc = nt[i].left_child
rc = nt[i].right_child
new_node_value = 0
if ((lc == None) or (rc == None)):
# the bottom nodes have no children
new_node_value = nt[i].node_value
new_best_path_down = "\n" \
+ str(nt[i].node_value) \
+ " at node " \
+ str(i) \
+ " on level " \
+ str(nt[i].node_level)
else:
if (nt[lc].node_value > nt[rc].node_value):
new_node_value = nt[i].node_value + nt[lc].node_value
new_best_path_down = "\n" \
+ str(nt[i].node_value) \
+ " at node " \
+ str(i) \
+ " on level " \
+ str(nt[lc].node_level) \
+ str(nt[lc].best_path_down)
else:
new_node_value = nt[i].node_value + nt[rc].node_value
new_best_path_down = "\n" \
+ str(nt[i].node_value) \
+ " at node " \
+ str(i) \
+ " on level " \
+ str(nt[rc].node_level) \
+ str(nt[rc].best_path_down)
nt[i].node_value = new_node_value
nt[i].best_path_down = new_best_path_down
with open("solution.txt", "w") as solution_file:
solution_file.write("Max Value is " + str(nt[0].node_value) + "\n")
solution_file.write("The Best Path chosen was: " \
+ str(nt[0].best_path_down))
return 0
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.stderr.write("no file name provided")
else:
main(sys.argv[1])
sys.exit()
|
0500416f388df1a6a047545b2e8432f7dd1ca24f | chao-ji/LeetCode | /python/string/lc49.py | 1,189 | 4.0625 | 4 | """49. Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
"""
from string import ascii_lowercase
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
# The idea:
# We need to map each string in `strs` to a key, then group
# strings by the key
# To compute the key, we use the counting method:
# 'eat' ==> [1, 0, 0, 0, 1, ..., 1, ... 0]
# a e t
# 'tea' ==> [1, 0, 0, 0, 1, ..., 1, ... 0]
# a e t
# So 'eat' and 'tea' map to the same key.
# string is converted to its 'one-hot' encoding
anagrams = {}
for s in strs:
if self.key(s) not in anagrams:
anagrams[self.key(s)] = []
anagrams[self.key(s)].append(s)
return list(anagrams.values())
def key(self, s):
return tuple([s.count(c) for c in ascii_lowercase])
|
a8c5e28379d9f4d8b39e6ed35b775f06d00a6e48 | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/estrutura-de-decisao/ex15.py | 997 | 4.25 | 4 | #Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
# Dicas:
# Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro;
# Triângulo Equilátero: três lados iguais;
# Triângulo Isósceles: quaisquer dois lados iguais;
# Triângulo Escaleno: três lados diferentes;
lado_a = float(input('informe a medida do lado a: '))
lado_b = float(input('informe a medida do lado b: '))
lado_c = float(input('informe a medida do lado c: '))
if lado_a == lado_b == lado_c:
print('o triangulo é equilátero')
elif lado_a == lado_b or lado_a == lado_c or lado_b == lado_c:
print('o triangulo é isósceles')
elif lado_a + lado_b < lado_c or lado_b + lado_c < lado_a or lado_c + lado_a < lado_b:
print('nO SE PODE FORMAR UM TRIANGULO')
else:
print('o triangulo é escaleno') |
965313b0c4a2748bdd1e6ede0ac8bec04b79956f | gabriellaec/desoft-analise-exercicios | /backup/user_242/ch162_2020_06_15_19_06_37_199855.py | 321 | 3.65625 | 4 | lista = [1,3,7,9]
def verifica_lista(lista):
par = True
impar = True
for i in lista:
if lista%2 == 0:
impar = False
else:
par = False
if par and not impar:
return 'par'
elif impar and not par:
return 'impar'
return 'misturado'
|
7b7a97d7dc33fa33d73a7e3ce823a960d8432d74 | shanminlin/Cracking_the_Coding_Interview | /chapter-1/6_string_compression.py | 3,620 | 4.21875 | 4 | """
Chapter 1 - Problem 1.6 - String Compression
Problem:
Implement a method to perform basic string compression using the counts of repeated characters. For example,
the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the
original string, your method should return the original string. You can assume the string has only uppercase
and lowercase letters (a - z).
Solution:
1. Clarify the question:
Rephrase the question: We are given a string. And we need to compress the string using character counts.
Clarify assumptions: - only uppercase and lowercase letters. So there will be no confusion when we have 10 or more
consecutive identical characters.
- case sensitive? (We will assume case sensitivity.)
2. Inputs and outputs:
input: a string
output: a compressed string, or original string if the compressed string is not shorter than the original string.
3. Test and edge cases:
edge: So we can also take in an empty string or None object as an input.
test: We can also have regular input like this: 'aaaabbbaacccc' -> 'a4b3a2c4'
4. Brainstorm solution:
We iterate through the string, check if the current character is the same as the previous character. If so, add count
to the previous character; Otherwise, add previous character and count to the compressed string.
As python string is immutable, string concatenation (adding to a string) involves creating a copy of that string,
particulary for long string where there is no overallocation of space. Then at each iteration a reallocation (linear time)
would be performed, and the full runtime would be quadratic in worse-case. So we will append to a list instead.
For very long string, we can also use generator to save memory.
5. Runtime analysis:
Time complexity: O(N) in always-case as we need to iterate through the whole string.
Space complexity: O(N) as we need to allocate space for the compressed string. In the worst case where there are no
consecutive characters, we need twice as long as the input.
6. Code
"""
# Solution 1
def compress1(input_str):
if (input_str is None) or (len(input_str) < 3):
return input_str
compressed_str = []
prev_char = input_str[0]
count = 1
for char in input_str[1:]:
if char == prev_char:
count += 1
else:
compressed_str.append(prev_char + str(count))
prev_char = char
count = 1
# Add last character count
compressed_str.append(prev_char + str(count))
compressed_str = ''.join(compressed_str)
if len(compressed_str) >= len(input_str):
return input_str
return compressed_str
# Solution 2
from itertools import groupby
def compress2(input_str):
if (input_str is None) or (len(input_str) < 3):
return input_str
compressed_str = ''.join(char + str(sum(1 for _ in group)) for char, group in groupby(input_str))
return min(input_str, compressed_str, key=len)
# 7. Test and debug
def test():
solutions = [compress1, compress2]
test_cases = [('aaaabbbaacccc', 'a4b3a2c4'),
('aaaabbbbcde', 'a4b4c1d1e1'),
('', ''),
(None, None)]
for solution in solutions:
for (test_input, result) in test_cases:
if test_input is None:
assert solution(test_input) is result
try:
assert solution(test_input) == result
print('Passed')
except AssertionError:
print(solution.__name__, test_input, 'Failed')
test()
|
1dc43e7491a4f1701f4f7da8dd48e7c257e4dcb5 | adnan-mehremic/guess-phrase | /guess_phrase.py | 3,223 | 3.53125 | 4 | import random
population_size = 150
target = "Machine learning is awesome."
genes = '''qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM1234567890 ,.-_;:?!@$'''
# percente value of elitism to be performed
elitism_factor = 10
mating_percent = 50
class Individual(object):
def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness_score = self.calculate_fitness()
@classmethod
def mutated_genes(self):
# create a competely random chromosome
global genes
rand_gene = random.choice(genes)
return rand_gene
@classmethod
def create_gnome(self):
# create a new choromosome
global target
gnome_length = len(target)
return [self.mutated_genes() for _ in range(gnome_length)]
def mate(self, second_parent):
# create a new offspring (using 2 parents)
child_chromosome = []
for gp1, gp2 in zip(self.chromosome, second_parent.chromosome):
probability = random.random()
if probability < 0.45:
child_chromosome.append(gp1)
elif probability < 0.90:
child_chromosome.append(gp2)
else:
child_chromosome.append(self.mutated_genes())
return Individual(child_chromosome)
def calculate_fitness(self):
global target
fitness_score = 0
# cg - character from generation
# ct - character from text
for cg, ct in zip(self.chromosome, target):
if cg != ct:
fitness_score += 1
return fitness_score
def main():
global population_size
global elitism_factor
global mating_percent
population = []
is_solved = False
generation_number = 1
# create the initial population
for _ in range(population_size):
# generate a new chromosome
gnome = Individual.create_gnome()
# generate a new individual
new_individual = Individual(gnome)
population.append(new_individual)
while not is_solved:
population = sorted(population, key=lambda x: x.fitness_score)
# if we have solved the problem break out of the loop
if population[0].fitness_score <0:
is_solved = True
break
new_population = []
# elitism
s = int((elitism_factor*population_size)/100)
new_population.extend(population[:s])
# perform the process of mating
mating_factor = 100 - elitism_factor
s = int((mating_factor * population_size) / 100)
for _ in range(s):
real_population = int((mating_percent*population_size)/100)
parent_1 = random.choice(population[:real_population])
parent_2 = random.choice(population[:real_population])
child = parent_1.mate(parent_2)
new_population.append(child)
population = new_population
print("Generation: {}\tString: {}\t Fitness: {}". \
format(generation_number,
"".join(population[0].chromosome),
population[0].fitness_score))
generation_number += 1
if __name__ == '__main__':
main()
|
8c60164ae99a06f82d08bb538af4449bfacdd421 | rajlath/rkl_codes | /Best_algo/Flying_with_Numbers/anagrams.py | 621 | 3.984375 | 4 | str1 = "marina"
str2 = "anaram"
def verify_anagrams(s1, s2):
'''
verify if two strings are anagram to each other
'''
dicts = {}
if len(s1) != len(s2):return False
for i in range(len(s1)):
dicts[s1[i]] = dicts.get(s1[i], 0) + 1
dicts[s2[i]] = dicts.get(s2[i], 0) - 1
return all([ x == 0 for x in dicts.values()])
def verify_anagrams_1(s1, s2):
if len(s1) != len(s2): return False
sum1 = sum([ord(x) for x in str1]) % 11
sum2 = sum([ord(x) for x in str2]) % 11
return sum1 == sum2
print(verify_anagrams(str1, str2))
print(verify_anagrams_1(str1, str2))
|
968ac463970b4f45b4d03d147e779c5246ee845f | grigorescu/Pygminion | /trunk/pygminion/utils.py | 996 | 3.671875 | 4 | import string
def cmpMoney(a, b):
try:
a = a.lower()
b = b.lower()
return cmp(int(a), int(b))
except ValueError:
# Something has a potion in the cost...
a_coins = sum([int(c) for c in a if c in string.digits])
b_coins = sum([int(c) for c in b if c in string.digits])
a_potions = sum([1 for c in a if c == 'p'])
b_potions = sum([1 for c in b if c == 'p'])
# Equal?
if a_coins == b_coins and a_potions == b_potions: return 0
elif a_coins < b_coins or a_potions < b_potions: return -1
else: return 1
def addMoney(a, b):
a = a.lower()
b = b.lower()
a_coins = sum([int(c) for c in a if c in string.digits])
b_coins = sum([int(c) for c in b if c in string.digits])
a_potions = sum([1 for c in a if c == 'p'])
b_potions = sum([1 for c in b if c == 'p'])
return str(a_coins + b_coins) + "p"*(a_potions + b_potions)
|
f76c559b08c7075f299f09f0af0d6fe160857508 | alexisbird/BC2repo | /madlibs.py | 1,022 | 4.625 | 5 | """Make a simple madlib, you can look one up. Ask for three words, save them in variables, fill in the madlib, then print the final madlib."""
# Create a variable for each word the user must input via input prompt
word1_person = input("Please enter a person: ")
word2_person = input("Please enter another person: ")
word3_noun = input("Please enter a noun: ")
word4_plural_noun = input("Please enter a plural noun: ")
word5_place = input("Please enter a place: ")
# The madlib passage, using string concatination to put the variables (user input) at the appropriate places
madlib = "Tennis News: The Miami Open\nSeemingly in control of his opening match at the Miami Open on Saturday, " + word1_person + " fell ill and promptly retired against No. 94 " + word2_person + ". It was a disappointment for the fifth-ranked " + word3_noun + ", who has always enjoyed playing in front of his large contingent of " + word4_plural_noun + " in " + word5_place + "."
# Print completed madlib with user's word choices
print(madlib) |
f1c3d643764fc6661f4d46f044cfd179599200b9 | kiranmaipuli/DATA-STRUCTURES | /trees/binarySearchTree/leftNRightView.py | 2,718 | 3.84375 | 4 | """ finding left and right view in a binary search tree """
# inputArray = [50,30,20,40,70,60,80,10,59]
inputArray = [50,30,70,40,60,80,59]
levelDict = {}
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
# inserting nodes in a binary search tree
def insertBinaryTree(self,node,key):
if node != None:
if node.value > key.value:
if node.left == None:
node.left = key
else:
self.insertBinaryTree(node.left,key)
elif node.value < key.value:
if node.right == None:
node.right = key
else:
self.insertBinaryTree(node.right,key)
else:
print("duplicates not allowed")
def inOrderTraversal(self,node):
if node == None:
return
self.inOrderTraversal(node.left)
print(node.value)
self.inOrderTraversal(node.right)
def leftViewOfBinaryTree(self,node,level):
if node == None:
return
if level not in levelDict:
levelDict[level] = 0
print(node.value,"left")
self.leftViewOfBinaryTree(node.left,level + 1)
self.leftViewOfBinaryTree(node.right,level + 1)
def rightViewOfBinaryTree(self,node,level):
if node == None:
return
if level not in levelDict:
levelDict[level] = 0
print(node.value,"right")
self.rightViewOfBinaryTree(node.right,level + 1)
self.rightViewOfBinaryTree(node.left,level + 1)
root = p = Node(inputArray[0])
for i in range(1,len(inputArray)):
node = Node(inputArray[i])
root.insertBinaryTree(root,node)
#root.inOrderTraversal(root)
#root.leftViewOfBinaryTree(root,1)
#levelDict = {}
#root.rightViewOfBinaryTree(root,1)
########################################################################################
# right view of binary tree using breadth first search (level order traversal)
def rightViewWithBFS():
queue = [p]
queue1 = []
queueLeft = []
queueRight = []
while len(queue) != 0:
queueRight.append(queue[-1].value)
queueLeft.append(queue[0].value)
for i in queue:
if i.left != None:
queue1.append(i.left)
if i.right != None:
queue1.append(i.right)
queue = queue1
queue1 = []
print("right view of the binary search tree",queueRight)
print("left view of the binary search tree",queueLeft)
rightViewWithBFS()
|
be0c0eac2694290e053d394c3d83829b8ed17404 | tamoghnaaa2012/P342_Assignment-5 | /Own_library.py | 4,494 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
def bisection_method(f,a,b,tol,file):
step = 0 #iteration counter
for i in range(1,200):
if f(a)*f(b)<0:
continue
else:
if (abs(f(a)) < abs(f(b))):
a=a - 0.5*(b-a)
else:
b=b + 0.5*(b-a) #upto this portion we are bracketing
print("{:<12} {:<12}".format("Iterations", "Absolute error")) #This is used to tabulate the output
while(b-a)/2.0 >tol and step<200:
mid_point = (a+b)/2.0
#print("Iteration-%d ,mid_point= %f ,f(mid_point) =%f)" %(step,mid_point,f(mid_point)))
#print('Iteration-%d,')
if f(mid_point)==0:
return(mid_point) #The midpoint is the root;
elif f(a)*f(mid_point) < 0:
b = mid_point
else:
a= mid_point
step = step+1
#print(f(a))
#print(a)
#print(f(b))
#print(b)
#print(f(a)*f(b))
error=abs(b-a)
file.write("{:^12} {:<12.3e}\n".format(step, error))
print("{:^12} {:<12.3e}".format(step, error))
file.close()
return(mid_point)
def regula_falsi(f,a,b,tol,file):
step=0
## a,b is initial guess
for i in range(1,200):
if f(a)*f(b)<0:
continue
else:
if (abs(f(a)) < abs(f(b))):
a=a - 0.5*(b-a)
else:
b=b + 0.5*(b-a) ## Upto this portion we are bracketing.
last_c=a
c=a+1*tol
condition = True
print("{:<12} {:<12}".format("Iterations", "Absolute error")) #This is used to tabulate the output
while condition and step<200:
last_c=c
c = b - ((b-a)*f(b))/(f(b)-f(a))
#print(c)
if f(a)*f(c)<0:
b=c
else:
a=c
step =step+1
error =abs(c-last_c)
#print(error)
condition = abs(f(c))>tol
file.write("{:^12} {:<12.3e}\n".format(step, error))
print("{:^12} {:<12.3e}".format(step, error))
file.close()
return (c)
def N_raphson(f,derivative, x0, tol,file):
step=0
last_X = x0
next_X = last_X + 1* tol # "different than lastX so loop starts OK
print("{:<12} {:<12}".format("Iterations", "Absolute error"))
while (abs(next_X - last_X) >= tol) and step<200: # this is how you terminate the loop - note use of abs()
new_Y = f(next_X)
step =step+1
last_X = next_X
next_X = last_X - new_Y / derivative(f, last_X, tol) # update estimate using N-R
error = abs(next_X-last_X)
file.write("{:^12} {:<12.3e}\n".format(step, error))
print("{:^12} {:<12.3e}".format(step, error))
file.close()
return next_X
def laguerre(f,f_derivative,s_derivative,alpha,n,tol,file):
if f(alpha)== 0:
print("The root is",alpha)
else:
alpha1=alpha+ 1*tol # "different than lastX so loop starts OK
step=0
print("{:<12} {:<12}".format("Iterations", "Absolute error"))
while abs(alpha1-alpha)>tol and step<200:
step = step+1
G = f_derivative(alpha,0.4,f)/f(alpha)
H = G*G-(s_derivative(alpha,0.4)/f(alpha))
F =math.sqrt((n-1)*(n*H-(G*G)))
if abs(G+F)<abs(G-F):
a = n/(G-F)
else:
a = n/(G+F)
alpha1=alpha
alpha = alpha -a
error= (alpha1-alpha)
file.write("{:^12} {:<12.3e}\n".format(step, error))
print("{:^12} {:<12.3e}".format(step, error))
#print(step,error)
print()
file.write("{:^12} {:<12}\n".format("Iter number", "error"))
print("The root is",alpha)
return (alpha)
def synthetic_div(coeff,alpha):
while abs(coeff[0])!=1:
for k in range(len(coeff)):
coeff[k]=coeff[k]/coeff[0]
for l in range(1,len(coeff)):
coeff[l]=coeff[l]+alpha*coeff[l-1]
#print("Coeff",coeff)
return (coeff)
|
8c5c86d9b0a165f027b8e1a7a61adcd9ad85730e | Chelton-dev/ICTPRG-Python | /temp.py | 169 | 3.8125 | 4 | mylist =["Fred:123", "Smith:475" ]
checkUser = "Smith"
for i in mylist:
arr=i.split(":")
if arr[0] == checkUser:
print("found")
|
3993e5446723b8592aa4adb1f70c3bdfd6c2018f | ipcoo43/algorithm | /lesson127.py | 176 | 3.609375 | 4 | print('행고정 열변화')
import pprint
matrix = [[0]*5 for i in range(5)]
i=0
for row in range(5):
for col in range(5):
i=i+1
matrix[row][col]=i
pprint.pprint(matrix) |
d1c54e8551de9f15f053da7e61a4d6d615de0e15 | thomashigdon/puzzles | /scratch/properties.py | 178 | 3.515625 | 4 | class A(object):
def __init__(self, foo):
self.foo = foo
@property
def bar(self):
print "returning foo"
return self.foo
print A('blah').bar
|
495ebdb2ba4cc43717338fdf255efc6ebed8e85e | 8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions | /Chapter05/0002_palindrome.py | 348 | 4.375 | 4 | """
Program 5.1
Determine whether a Given String is a
Palindrome or not using slicing
"""
def main():
user_string = input("Enter string:\n")
if user_string == user_string[::-1]:
print("User entered string is a palindrome")
else:
print("User entered string is not a palindrome")
if __name__ == "__main__":
main()
|
a058ec6561d9d7dac2e7df081fd943a9bf2c77bd | elidaniel/chore-tracker | /calc.py | 612 | 3.875 | 4 |
import sys
num = raw_input('Enter the first number: ')
opr = raw_input('Enter operator + - / *: ')
den = raw_input('enter the other number: ')
try:
num = int(num)
except ValueError:
print "You did not enter a good first number"
sys.exit()
try:
den = int(den)
except ValueError:
print "You did not enter a good other number"
sys.exit()
if opr == '+':
ans = num + den
elif opr == '-':
ans = num - den
elif opr == '/':
ans = num / den
elif opr == '*':
ans = num * den
else:
print "You did not enter a good operator."
sys.exit()
print
print "The answer is: ", ans
print
|
a2249dc39675c8b55e4216b590683dee0cfb46a2 | mbravofuentes/Codingpractice | /python/round.py | 95 | 3.96875 | 4 | print("Enter an input: ")
x = input()
if (int(x) > 3):
print("Sup")
else:
print("hey")
|
f80a25ff7e401e7a65d2516156a047725f859cb9 | kscott94/qBio | /project_submissions/cp_upper_beginner.py | 1,625 | 3.828125 | 4 | gene1 = "gtgggagacatagtggtcaaggtccccccgagtgtggacgaaaagctggccgatttgatagcaaagactatcgcggagagactgaaaaccctcgcaaggctcaatgagatgctcaagaactccgaactctcagaagaggatgcaatagaactcggacggaaggcgaaaatgggaaggggcgagtaccttgagagaagatattcttctcgtagttaa"
gene2 = "atgagagaagatattcttctcgtagttaacacaaacgtgctattctctttcttcgggaaatcaacagtaaccagagagctcgtgttcttggtatcagggagacttataagtcccgagtttgcactggaagagcttcacgagcacagggacgaagtcctgaaaaaagcaaagatcggagagaaagagttcgaggaaatactgtccgttcttaaagagcatgtcatattcgtaaacgaggggttctacgccgagttcatacctctagcactcgaataa"
gene3 = "atggaagttatccgtctgctgaagagaaagtcccaagacaaggttgagttcgtgcgcgatctggtagttttcatggcttctcccgacgttgatttttccaacgaggttctgtttaaggacgccgttgatgagatatactcaatcctgagggaggaagtcattgaaaatgggaacaaagagctagccagcgcgtatgaaaaagccgttctccttagagctgcggtttttggagaggaaatggatccgaaaaagctccttaagggtattctcgaggagctgaggtga"
def rev_comp(sequence):
complement_dictionary = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'a': 't', 'c': 'g', 'g': 'c', 't': 'a'}
rev_complement = "".join(complement_dictionary.get(base, base) for base in reversed(sequence))
return rev_complement
## write a script to print the sequence of the forward and reverse primers in fasta format.
## '\n' will print a new line. You could also stack two print statements on separate lines to separate the fasta header from the sequence.
gene_list = [gene1,gene2,gene3]
gene_number = 1
for gene in gene_list:
print("Forward primer",number)
print(gene[:-18:-1])
print("Reverse primer",number)
print(rev_comp(gene)[0:18])
gene_number = gene_number + 1 #add a number to gene_number after each loop to keep track of which gene we are on
|
ad2e63d83ee9c4ef6b21a27e7ccce92afc589cab | AdamZhouSE/pythonHomework | /Code/CodeRecords/2882/58586/253698.py | 503 | 3.515625 | 4 | nums=int(input())
arr=list(map(int,input().split(" ")))
if nums==1:
print("YES")
else:
peek=-1
index=-1
for i in range(0,nums-1):
if arr[i]>=arr[i+1]:
index=i
break
if index==-1:
print("YES")
else:
flag=True
peek=arr[index]
for i in range(index,nums-1):
if arr[i]<arr[i+1]:
flag=False
break
if flag:
print("YES")
else:
print("NO")
|
4d7603a1000d64888815bbfa55176464b8aeaaad | rebekahorth/Week-Two-Assignment | /convert.py | 258 | 3.703125 | 4 | __author__ = 'Rebekah Orth'
# CIS 125 Fall 2015
# Temperature Table
def main():
F=eval(input("Please enter a temperature in Fahrenheit:"))
C= (F-32) * 5 / 9
print("The temperature ", F , " in Fahrenheit is equal to ", C , " Celsius")
main() |
dc3c6a4189b86147d9bd2629d582d31536586eb0 | lyc192130/MCTS-with-OCBA | /inventory/inventory_control.py | 8,835 | 3.65625 | 4 | """
An example implementation of the abstract Node class for use in MCTS
for the inventory control problem
"""
from numpy.random import random
from collections import namedtuple, defaultdict
from monte_carlo_tree_search import MCTS, Node
from numpy import sqrt
import os
import argparse
import dill # pip install dill
_Tree = namedtuple(
"_Tree", "state terminal num_actions stage action node_type cap horizons")
class Tree(_Tree, Node):
def find_children(self):
# If the game is finished then no moves can be made
if self.terminal:
return set()
# Otherwise, you can make a move in the next empty spots
elif self.node_type == 's':
return {
self.make_move(i) for i in range(self.num_actions+1) if self.state + i <= self.cap
}
else:
raise "NOT a state node!"
def find_random_child(self):
if self.terminal:
return None # If the game is finished then no moves can be made
if self.node_type == 's':
# faster than np.random.randint(1+self.cap - self.state)
return self.make_move(int((1+self.cap-self.state) * random() ))
else:
return self.sample_next_state()
def reward(self, randomness=None):
D = randomness
cost = h*max([0, self.state + self.action - D]) \
+ p * max([0, D-self.state-self.action]) + K * (self.action > 0)
return -cost
def is_terminal(self):
return self.terminal
def make_move(self, k):
assert self.node_type == 's', "The current node is not a state node!"
state = self.state
action = k
stage = self.stage
is_terminal = (stage == self.horizons)
return Tree(state=state, stage=stage, terminal=is_terminal, num_actions=self.num_actions,
action=action, node_type='a', cap=20, horizons=self.horizons)
def sample_next_state(self, path_reward={}):
assert self.node_type == 'a', "The current node is not an action node!"
D = int(10*random())
path_reward[self] = self.reward(D)
stage = self.stage+1
state = max(self.state + self.action - D, 0)
is_terminal = (stage == self.horizons)
return Tree(state=state, stage=stage, terminal=is_terminal, num_actions=self.num_actions,
action=None, node_type='s', cap=20, horizons=self.horizons)
def play_game_uct(budget=1000, exploration_weight=1, optimum=0, n0=2, sigma_0=1):
mcts = MCTS(policy='uct', exploration_weight=exploration_weight,
budget=budget, n0=n0, sigma_0=sigma_0)
tree = new_tree()
for _ in range(budget):
mcts.do_rollout(tree)
next_tree = mcts.choose(tree)
return (mcts, tree, next_tree)
def play_game_ocba(budget=1000, optimum=0, n0=5, sigma_0=1):
mcts = MCTS(policy='ocba', budget=budget,
optimum=optimum, n0=n0, sigma_0=sigma_0)
tree = new_tree()
for _ in range(budget):
mcts.do_rollout(tree)
next_tree = mcts.choose(tree)
return (mcts, tree, next_tree)
def new_tree():
horizons = 3
root = 5
return Tree(state=root, stage=0, num_actions=20, terminal=False, action=None, node_type='s', cap=20, horizons=horizons)
if __name__ == "__main__":
os.makedirs("results", exist_ok=True)
os.makedirs("ckpt", exist_ok=True)
parser = argparse.ArgumentParser()
parser.add_argument('--rep', type=int,
help='number of replications', default=2000)
parser.add_argument('--budget_start', type=int,
help='budget (number of rollouts) starts from (inclusive)', default=50)
parser.add_argument('--budget_end', type=int,
help='budget (number of rollouts) end at (inclusive)', default=200)
parser.add_argument('--step', type=int,
help='stepsize in experiment', default=10)
parser.add_argument(
'--n0', type=int, help='initial samples to each action', default=2)
parser.add_argument('--sigma_0', type=int,
help='initial variance', default=10)
parser.add_argument(
'--p', type=int, help='invetory control penalty cost', default=1)
parser.add_argument(
'--K', type=int, help='invetory control fixed ordering cost', default=5)
parser.add_argument(
'--checkpoint', type=str, help='relative path to checkpoint', default='')
args = parser.parse_args()
rep = args.rep
budget_start = args.budget_start
budget_end = args.budget_end
step = args.step
budget_range = range(budget_start, budget_end+1, step)
n0 = args.n0
sigma_0 = args.sigma_0
p = args.p
K = args.K
results_uct = []
results_ocba = []
uct_selection = []
ocba_selection = []
exploration_weight = 1
h = 1
if p == 1 and K == 5:
optimum = 0
elif p == 10 and K == 0:
optimum = 4
else:
raise ValueError('p and K must be either (1, 5) or (10, 0)')
uct_visit_ave_cnt_list, ocba_visit_ave_cnt_list = [], []
uct_ave_Q_list, ocba_ave_Q_list = [], []
uct_ave_std_list, ocba_ave_std_list = [], []
ckpt = args.checkpoint
if ckpt != '':
dill.load_session(ckpt)
# start experiment from the last finished budget
budget_range = range(budget+step, budget_end+1, step)
for budget in budget_range:
PCS_uct = 0
PCS_ocba = 0
uct_visit_cnt, ocba_visit_cnt = defaultdict(int), defaultdict(int)
uct_ave_Q, ocba_ave_Q = defaultdict(int), defaultdict(int)
uct_ave_std, ocba_ave_std = defaultdict(int), defaultdict(int)
for i in range(rep):
uct_mcts, uct_root_node, uct_cur_node =\
play_game_uct(budget=budget, exploration_weight=exploration_weight,
optimum=optimum, n0=n0, sigma_0=sigma_0)
PCS_uct += (uct_cur_node.action == optimum)
ocba_mcts, ocba_root_node, ocba_cur_node = play_game_ocba(
budget, n0=n0, optimum=optimum, sigma_0=sigma_0)
PCS_ocba += (ocba_cur_node.action == optimum)
'''
Update the cnt dict
'''
uct_visit_cnt.update(dict(
(c, uct_visit_cnt[c]+uct_mcts.N[c]) for c in uct_mcts.children[uct_root_node]))
ocba_visit_cnt.update(dict(
(c, ocba_visit_cnt[c]+ocba_mcts.N[c]) for c in ocba_mcts.children[ocba_root_node]))
uct_ave_Q.update(dict(
(c, uct_ave_Q[c]+uct_mcts.ave_Q[c]) for c in uct_mcts.children[uct_root_node]))
ocba_ave_Q.update(dict(
(c, ocba_ave_Q[c]+ocba_mcts.ave_Q[c]) for c in ocba_mcts.children[ocba_root_node]))
uct_ave_std.update(dict((c, uct_ave_std[c]+sqrt(
uct_mcts.std[c]**2 - sigma_0**2 / uct_mcts.N[c])) for c in uct_mcts.children[uct_root_node]))
ocba_ave_std.update(dict((c, ocba_ave_std[c]+sqrt(
ocba_mcts.std[c]**2 - sigma_0**2 / ocba_mcts.N[c])) for c in ocba_mcts.children[ocba_root_node]))
if (i+1) % 20 == 0:
print('%0.2f%% finished for budget limit %d' %
(100*(i+1)/rep, budget))
print('Current PCS: uct=%0.3f, ocba=%0.3f' %
(PCS_uct/(i+1), (PCS_ocba/(i+1))))
uct_visit_cnt.update(
dict((c, uct_visit_cnt[c]/rep) for c in uct_mcts.children[uct_root_node]))
ocba_visit_cnt.update(
dict((c, ocba_visit_cnt[c]/rep) for c in ocba_mcts.children[ocba_root_node]))
uct_ave_Q.update(dict((c, uct_ave_Q[c]/rep)
for c in uct_mcts.children[uct_root_node]))
ocba_ave_Q.update(dict((c, ocba_ave_Q[c]/rep)
for c in ocba_mcts.children[ocba_root_node]))
uct_ave_std.update(
dict((c, uct_ave_std[c]/rep) for c in uct_mcts.children[uct_root_node]))
ocba_ave_std.update(
dict((c, ocba_ave_std[c]/rep) for c in ocba_mcts.children[ocba_root_node]))
uct_visit_ave_cnt_list.append(uct_visit_cnt)
ocba_visit_ave_cnt_list.append(ocba_visit_cnt)
uct_ave_Q_list.append(uct_ave_Q)
ocba_ave_Q_list.append(ocba_ave_Q)
uct_ave_std_list.append(uct_ave_std)
ocba_ave_std_list.append(ocba_ave_std)
results_uct.append(PCS_uct/rep)
results_ocba.append(PCS_ocba/rep)
print("Budget %d has finished" % (budget))
print('PCS_uct = %0.3f, PCS_ocba = %0.3f' %
(PCS_uct/rep, PCS_ocba/rep))
ckpt_output = 'ckpt/Inventory_K{}_p{}_budget_{}.pkl'.format(K, p, budget)
dill.dump_session(ckpt_output)
print('checkpoint saved!')
|
c5a0b1053620d5e32705ed4b47c7710669454144 | CafeYuzuHuang/coding | /MaximumDepthofBinaryTree.py | 2,574 | 3.796875 | 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 maxDepth(self, root: TreeNode) -> int:
# 2021.03.19
# Max depth ~10^4, extreme unbalanced binary tree!
# For fully balanced tree: ~14
# 1st solution: Use iterative method and scanning
# Time complexity: O(N) = O(2^n); where N is # of nodes, n is the max depth
# Space complexity: min O(1), max O(2^n-1) = O(N/2)
# Balanced: 1 -> 2 -> 4 -> 8 ...
# Unbalanced: e.g. 1 -> 2 -> 3 -> 6 ...
"""
if root is None:
return 0
queue = list([root, ])
max_depth = 1
max_count = 2
count_val = 0
count_none = 0
while len(queue) > 0:
p = queue.pop(0)
if p.left:
queue.append(p.left)
count_val += 1
else:
count_none += 1
if p.right:
queue.append(p.right)
count_val += 1
else:
count_none += 1
if (count_val + count_none) == max_count and count_val > 0:
max_depth += 1
max_count = 2 * count_val
count_val = 0
count_none = 0
return max_depth
"""
# 3rd solution: breadth-first search (BFS)
# more elegant and simple than 1st solution
"""
if not root:
return 0
max_depth, queue = 0, [(root, 1)]
while queue:
p, depth = queue.pop(0)
max_depth = max(depth, max_depth)
if p.left: queue.append((p.left, depth + 1))
if p.right: queue.append((p.right, depth + 1))
return max_depth
"""
# 4th solution: recursive, depth-first search (DFS)
# The most elegant approach
# Pre-order, in-order, or post-order DFS does not matter here
if not root:
return 0
return self.dfs(root)
def dfs(self, p, depth = 0):
if not p:
return depth
return max(depth,
self.dfs(p.left, depth + 1),
self.dfs(p.right, depth + 1))
# 1st solution: 40 ms (77%) and 15.3 MB (97%)
# 3rd solution: 40 ms (77%) and 15.3 MB (92%)
# 4th solution: 36 ms (92%) and 16.7 MB (5%)
|
fa8741b975be7fa8adfad1ed56cc2e1812425d80 | danielzhangau/Data-Mining | /wk11_tutorial/decisiontreec/dataset.py | 6,149 | 3.8125 | 4 | from collections import Counter
class DatasetInstance:
"""
Class that represents an instance of a dataset
"""
# CONSTRUCTOR
def __init__(self, attributes_names, attributes_values, target_name, target_value):
"""
Build a new instance
Parameters:
- attributes_names: names of the attributes (list of Strings)
- attributes_values: values of the attributes (list of values)
- target_name: the name of the target (String)
- target_value: target value (value)
"""
self.attributes = {}
for index, name in enumerate(attributes_names):
self.attributes[name] = attributes_values[index]
self.target_name = target_name
self.target_value = target_value
# GETTERS
def get_attribute_value(self, attribute_name):
"""
Return the value related to the specified attribute (value)
Parameters:
- attribute_name: the name of the desired attribute
"""
return self.attributes[attribute_name]
def get_target_name(self):
"""
Return the name of the target (String)
"""
return self.target_name
def get_target_value(self):
"""
Return the value of the target (value)
"""
return self.target_value
class Dataset:
"""
Class that represents a dataset
"""
# CONSTRUCTOR
def __init__(self, attributes_names, target_name):
"""
Build a new empty dataset
Parameters:
- attributes_names: names of the attributes (list of Strings)
- target_name: name of the target (String)
"""
self.attributes_names = attributes_names
self.target_name = target_name
self.instances = []
# ITERATOR
def __iter__(self):
return iter(self.instances)
# GETTERS
def get_attributes_names(self):
"""
Return the names of the attributes (list of Strings)
"""
return self.attributes_names
def get_target_name(self):
"""
Return the name of the target (String)
"""
return self.target_name
def get_instance(self, index):
"""
Return the instance at the specified index (DatasetInstance)
Parameters:
- index: the index of the desired instance (int)
"""
return self.instances[index]
# SETTERS
def add_instance(self, attributes_values, target_value):
"""
Add a new instance to the dataset
Parameters:
- attributes_values: values of the attributes (list of values)
- target_value: target value (value)
"""
self.instances.append(DatasetInstance(self.attributes_names, attributes_values,
self.target_name, target_value))
# AGGREGATORS
def get_target_values(self):
"""
Return a set of all the target values in the dataset (set of values)
"""
return set(instance.get_target_value() for instance in self)
def get_most_common_target(self):
"""
Return the most common target value in the dataset (value)
"""
return Counter([instance.get_target_value() for instance in self]).most_common(1)[0][0]
def get_attribute_values(self, attribute_name):
"""
Return a set of all the values that a specified attribute has in the dataset (set of values)
Parameters:
- attribute_name: the name of the attribute (String)
"""
return set(instance.get_attribute_value(attribute_name) for instance in self)
def count_instances(self, target=None, attribute=None):
"""
Return the number of instances the dataset contains, subject to some constraints
Parameters:
- target: the value of the target, default to None (value)
- attribute: object with name of an attribute and the related value, default to None
({"name": String, "value": value})
"""
return len(self._get_instances(target=target, attribute=attribute))
# PRIVATE METHODS
# These methods should not be used outside the module
def _get_instances(self, target=None, attribute=None):
"""
Return the instances the dataset contains, subject to some constraints
(list of DatasetInstance)
Parameters:
- target: the value of the target, default to None (value)
- attribute: object with name of an attribute and the related value, default to None
({"name": String, "value": value})
"""
instances = [instance for instance in self]
if target is not None:
instances = [instance for instance in instances
if instance.get_target_value() == target]
if attribute is not None:
instances = [instance for instance in instances
if instance.get_attribute_value(attribute["name"]) == attribute["value"]]
return instances
# UTILITY FUNCTIONS
def copy_dataset(dataset, target=None, attribute=None):
"""
Return a copy of the dataset, taking into account only the instances that satisfy certain
constraints (Dataset)
Parameters:
- target: the value of the target, default to None (value)
- attribute: object with name of an attribute and the related value, default to None
({"name": String, "value": value})
"""
instances = dataset._get_instances(target=target, attribute=attribute)
attributes_names = [attribute_name for attribute_name in dataset.get_attributes_names()]
if attribute is not None:
attributes_names.remove(attribute["name"])
new_dataset = Dataset(attributes_names, dataset.get_target_name())
for instance in instances:
new_dataset.add_instance([instance.get_attribute_value(attribute_name)
for attribute_name in attributes_names],
instance.get_target_value())
return new_dataset |
5fbc02eecd4c13a07780b8a0c66c42f7dd554b8e | Allen-C-Guan/Leetcode-Answer | /python_part/Leetcode/DP/Greedy Alg/1221. Split a String in Balanced Strings/Solution.py | 452 | 3.625 | 4 | '''
边走边看,凑成一对算一对,这就是贪心!!丝毫不管以后发生什么。
这里用R和L计数,其实用一个就行,遇见R, +1, 遇见L, -1
'''
class Solution:
def balancedStringSplit(self, s: str) -> int:
R = L = cnt = 0
for c in s:
if c == "R": R += 1
else:L += 1
if R == L and R != 0:
R = L = 0
cnt += 1
return cnt
|
03283ef494ca975db2c4808dc73fe8440429ba6d | karoscha/python-study | /PycharmProjects/study/lecture-inheri.py | 331 | 3.875 | 4 | # -*- coding: utf-8 -*-
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def personInfo(self):
print('name={}, age={}, gender={}'.format(self.name,self.age,self.gender))
person = Person('karoscha', '36', '남')
person.personInfo()
|
7819f16c7bc6118496d9321c3fc4c702026d03f4 | arnabs542/DS-AlgoPrac | /bitmanupulations/shops.py | 3,074 | 3.625 | 4 | """Open minimum shops
Problem Description
There are A shops numbered 1 to A and B items numbered 1 to B. Shop contains different items denoted by 2-D array C of size N x 2 where C[i][0] denotes shop number and C[i][1] denotes item number. There are D people number 1 to D which wants to buy item.
Need of the people is denoted by a 2-D array E of size M x 2 where E[i][0] denotes person number and E[i][1] denotes item number. Find the minimum number of shops that needs to be opened such that demand of each and every person is fulfilled. Return -1 if not possible. NOTE: The shopkeeper has an infinte number of supplies for the item number he contains.
Problem Constraints
1 <= A, B, D <= 20
1 <= N, M <= 400
Input Format
First argument is an integer A denoting number of shops.
Second argument is an integer B denoting number of items.
Third argument is a 2-D array C of size N x 2 denoting the items shop contains.
Fourth argument is an integer D denoting the number of people.
Fifth argument is a 2-D array E of size M x 2 denoting the items people need.
Output Format
Return an integer denoting the minimum number of shops needs to be opened such that demand of each and every person is fulfilled. Return -1 if not possible.
Example Input
Input 1:
A = 4
B = 5
C = [ [1, 2],
[1, 3],
[2, 1],
[2, 2],
[3, 4] ]
D = 4
E = [ [1, 3],
[1, 2],
[2, 3],
[2, 1],
[4, 1] ]
Input 2:
A = 2
B = 3
C = [ [1, 2],
[2, 1] ]
D = 2
E = [ [1, 2],
[2, 3],
[2, 1] ]
Example Output
Output 1:
2
Output 2:
-1
Example Explanation
Explanation 1:
Each shopkeeper has the following items:
Shop 1 : [2, 3]
Shop 2 : [1, 2]
Shop 3 : [4]
Shop 4 : [] (has nothing)
Items we need = [1, 2, 3]
We need 2 shops i.e Shop 1 and 2, to be kept open so that demands of all people is satisfied.
Explanation 2:
Items we need = [1, 2, 3].
No shop has item 3. So will return -1."""
import math
class Solution:
# @param A : integer
# @param B : integer
# @param C : list of list of integers
# @param D : integer
# @param E : list of list of integers
# @return an integer
def countSetBits(self, ele):
n = int(math.log2(ele))+1
ans = 0
for i in range(n):
if (1<<i) & ele:
ans += 1
return ans
def solve(self, A, B, C, D, E):
from collections import defaultdict
merchant = defaultdict(int)
for m, it in C:
merchant[1 << (m-1)] += (1<<(it-1))
req = 0
for p, it in E:
if (1<<(it-1) & req) == 0:
req += (1 << (it-1))
ans = []
for mer in range(2**A-1):
till = 0
for bit in range(A):
till = till | merchant[(1<<bit)&(mer)]
if till & req == req:
ans.append(mer)
if not ans:
return -1
return min([self.countSetBits(i) for i in ans])
|
b24848c4cee3b4def1e7108c935d64ce6a413232 | tntterri615/Pdx-Code-Guild | /Python/lab20creditcardvalidation.py | 580 | 3.828125 | 4 | # write fn to determine if cc# is valid (as a boolean)
def check_credit_card(card):
check_digit = card.pop()
# print(check_digit)
# print(card) # list w/o check digit
card.reverse()
# print(card)
# double every other element AND sub 9 fr/nums > 9
for i in range(0, len(card), 2):
card[i] *= 2
if card[i] > 9:
card[i] -= 9
return sum(card) % 10 == check_digit
card = list(input('enter your cc: '))
# convert the string into a list
for i in range(len(card)):
card[i] = int(card[i])
print(check_credit_card(card))
|
ee461243895da3bd84bfbc8551d9dc3887dcfe71 | vedant-2103/nand2tetris | /ex8/Parser.py | 2,495 | 3.53125 | 4 | __author__ = 'Itay'
class Parser:
CommandTypes = {"C_ARITHMETIC", "C_PUSH", "C_POP", "C_LABEL", "C_GOTO", "C_IF", "C_FUNCTION", "C_CALL", "C_RETURN"}
def __init__(self, file):
"""
Opens the input file/stream and gets ready
to parse it
"""
self.file = open(file)
self.lineCount = 0
self.currCommand = ""
self.lines = self.file.readlines() # split lines
self.lines = [line.replace('\n', '').replace('\t', '') for line in self.lines] # removes '\n' and '\t'
self.lines = [line.split("//")[0].strip() for line in self.lines]# if "//" in line]
self.lines = [line for line in self.lines if line != ''] # removes empty lines
def hasMoreCommands(self):
"""
Are there more commands in the input?
"""
return self.lineCount < len(self.lines)
def advance (self):
"""
Reads the next command from the input and
makes it the current command. Should be
called only if hasMoreCommands() is
true. Initially there is no current command.
"""
self.currCommand = self.lines[self.lineCount]
self.lineCount += 1
return self.currCommand
arithmeticCodes = {"sub", "add", "neg", "eq", "gt", "lt", "and", "or", "not"}
def commandType(self):
"""
Returns the type of the current command.
C_ARITHMETIC is returned for all the
arithmetic VM commands
"""
if self.currCommand in self.arithmeticCodes:
return "C_ARITHMETIC"
elif "push" in self.currCommand:
return "C_PUSH"
elif "pop" in self.currCommand:
return "C_POP"
elif "goto" in self.currCommand:
if "if" in self.currCommand:
return "C_IF"
return "C_GOTO"
elif "function" in self.currCommand:
return "C_FUNCTION"
elif "call" in self.currCommand:
return "C_CALL"
elif "return" in self.currCommand:
return "C_RETURN"
elif "label" in self.currCommand:
return "C_LABEL"
else:
print("error in commandType")
def arg1(self):
"""
Returns the first argument of the current command
"""
return self.currCommand.split(" ")[1]
def arg2(self):
"""
Returns the second argument of the current command
"""
return self.currCommand.split(" ")[2] |
4323c1f3a05e9698f1df34c0f6b925052e544e6b | ddnimara/KTH_Projects | /Artificial Neural Networks/DD2437_Artificial_Neural_Network_Lab_3/functions.py | 17,392 | 3.765625 | 4 | # Import libraries
import numpy as np
import itertools
import load_data as ld
import matplotlib.pyplot as plt
import seaborn as sns
"""
This lab is addressed to:
- Explain the principles underlying the operation and functionality of au-
toassociative networks;
- Train the Hopfield network;
- Explain the attractor dynamics of Hopfield networks the concept of energy
function;
- Demonstrate how autoassociative networks can do pattern completion and
noise reduction;
- Investgate the question of storage capacity and explain features that help
increase it in associative memories.
"""
def fit(training, method = 'self_connection'):
M = training.shape[1]
weights = np.zeros((M,M))
N = training.shape[0]
for i in range(M):
for j in range(M):
if method == 'self_connection':
weights[i, j] = 1/M * np.dot(training[:,i],training[:,j])
else:
if i == j:
weights[i, j] = 0
else:
weights[i, j] = 1/M * np.dot(training[:,i],training[:,j])
return weights
def sparse_fit(training,method='self_connection'):
M = training.shape[1]
weights = np.zeros((M, M))
N = training.shape[0]
rho = training.mean()
#print('rho',rho)
for i in range(M):
for j in range(M):
if method == 'self_connection':
weights[i, j] = np.dot(training[:, i]-rho, training[:, j]-rho)
else:
if i == j:
weights[i, j] = 0
else:
weights[i, j] = np.dot(training[:, i]-rho, training[:, j]-rho)
#print('weights', weights.mean())
#print('training size ', N)
#print('max weight ', np.max(weights))
return weights
def sparse_activation(x,bias,weight_row):
print("activation magnitude ",np.dot(weight_row,x))
return 0.5 + 0.5*sign(np.dot(weight_row,x)-bias)
def sparse_predict(weights,bias,test_original,max_iterations=100):
M = weights.shape[0]
previous_test = np.zeros((1, M))
counter = 0
np.random.seed(42)
test = test_original.copy()
while(counter<max_iterations):
previous_test = test.copy()
#update_index = np.random.randint(M)
#updated_bit = sign(np.dot(weights[update_index],test))
for i in range(M):
update_bit = sparse_activation(test,bias,weights[i])
test[i] = update_bit
if (np.array_equal(previous_test,test)):
break
counter+=1
#print("Total number of iterations ",counter)
return test
def sign(x):
if x>=0:
return 1
else:
return -1
def sign_vec(x):
for i in range(x.shape[0]):
if (x[i]>=0):
x[i]=1
else:
x[i]=-1
return x
def predict_little_model(weights,test_original,max_iterations=100):
M = weights.shape[0]
previous_test = np.zeros((1, M))
counter = 0
np.random.seed(42)
test = test_original.copy()
while (counter < max_iterations):
previous_test = test.copy()
# update_index = np.random.randint(M)
# updated_bit = sign(np.dot(weights[update_index],test))
test = sign_vec(np.dot(weights,previous_test))
if (np.array_equal(previous_test, test)):
break
counter += 1
# print("Total number of iterations ",counter)
return test
def predict(weights,test_original,max_iterations=200,energy = False):
M = weights.shape[0]
previous_test = np.zeros((1,M))
counter=0
np.random.seed(42)
test = test_original.copy()
if (not energy):
while(counter<max_iterations):
previous_test = test.copy()
#update_index = np.random.randint(M)
#updated_bit = sign(np.dot(weights[update_index],test))
for i in range(M):
update_bit = sign(np.dot(weights[i],test))
test[i] = update_bit
if (np.array_equal(previous_test,test)):
break
counter+=1
#print("Total number of iterations ",(counter+M))
return test
else:
energy_vector = []
energy_vector_step = []
energy_vector_step.append(compute_lyapunov_energy(test,weights))
energy_vector.append(compute_lyapunov_energy(test,weights))
while(counter<max_iterations):
previous_test = test.copy()
for i in range(M):
immediate_previous = test.copy()
update_bit = sign(np.dot(weights[i],test))
test[i] = update_bit
energy_vector_step.append(compute_lyapunov_energy(test,weights)) #Every time we run through the for loop we compute the energy. If the
#pattern does not change we will see a plateu and, therefore, a stepped plot until reaching the minimum
if(not np.array_equal(immediate_previous,test)):
energy_vector.append(compute_lyapunov_energy(test,weights)) #In this case, the energy is stored everytime the pattern changes in order to
#get a more continuous plot. In the end, both lists will be returned and the one explaining the data in a better format can be plotted
if (np.array_equal(previous_test,test)):
break
counter+=1
print("Total number of iterations ",counter)
return test, np.array(energy_vector),np.array(energy_vector_step)
def number_of_attractors(weights):
lst = np.array(list(itertools.product([-1, 1], repeat=8)))
results = []
for i in range(lst.shape[0]):
results.append(predict(weights,lst[i],100))
results=np.array(results)
return results
def compute_lyapunov_energy(x,w):
return -x@[email protected]
def compute_accuracy(real,predicted):
return real[real==predicted].shape[0]/real.shape[0]
def get_random_image(pixels=1024,p=[0.5,0.5]):
return np.random.choice([-1,1],size=pixels,p=p)
def three_point_five_first_bullet():
# Load data
filepath = r"data/pict.dat"
pictures_matrix = ld.get_pictures(filepath)
# Learning
max_training_num = [3,4, 5, 6, 7]
training = np.zeros((max_training_num[-1], pictures_matrix.shape[1] * pictures_matrix.shape[2]))
for i in range(max_training_num[-1]):
training[i] = np.ravel(pictures_matrix[i])
np.random.seed(42)
max_iter = 5
percentage_check = np.arange(15, 20, 5)
accuracy_mean = accuracy_with_sample_images(percentage_check, max_training_num, max_iter, training)
plt.plot(max_training_num, accuracy_mean[0, :, 0],label='p1')
plt.plot(max_training_num, accuracy_mean[0, :, 1],label='p2')
plt.plot(max_training_num, accuracy_mean[0, :, 2],label='p3')
plt.title("Accuracy as a function of Number of Pictures Memorized")
plt.legend()
plt.xlabel("Number of Patterns memorized-trained on")
plt.ylabel("Accuracy (% pixels)")
plt.show()
def three_point_five_second_bullet():
filepath = r"data/pict.dat"
pictures_matrix = ld.get_pictures(filepath)
# Learning
number_of_random_samples = 15
max_training_num = np.arange(3, 4 + number_of_random_samples, 1) # [3,4, 5, 6, 7]
np.random.seed(42)
max_iter = 1
percentage_check = np.arange(15, 20, 5)
training = np.zeros((3 + number_of_random_samples, pictures_matrix.shape[1] * pictures_matrix.shape[2]))
for i in range(3):
training[i] = np.ravel(pictures_matrix[i])
for i in range(number_of_random_samples):
training[i + 3] = get_random_image()
accuracy_mean = accuracy_with_sample_images(percentage_check, max_training_num, max_iter, training)
plt.plot(max_training_num, accuracy_mean[0, :, 0],label='p1')
plt.plot(max_training_num, accuracy_mean[0, :, 1],label='p2')
plt.plot(max_training_num, accuracy_mean[0, :, 2],label='p3')
plt.title("Accuracy as a function of Number of Pictures Memorized")
plt.legend()
plt.xlabel("Number of Patterns memorized-trained on")
plt.ylabel("Accuracy (% pixels)")
plt.show()
def three_point_five_fourth_bullet():
number_of_random_samples = 300
max_training_num = np.arange(1, number_of_random_samples + 1, 1) # [3,4, 5, 6, 7]
np.random.seed(1)
max_iter = 1
percentage_check = np.arange(0, 55, 5)
training = np.zeros((number_of_random_samples, 10 * 10))
for i in range(number_of_random_samples):
training[i] = get_random_image(pixels=100)
print(training.shape)
stable_patterns = np.zeros(number_of_random_samples)
for i in range(number_of_random_samples):
examined_trainining = training[:i + 1].copy()
weights = fit(examined_trainining, method='self_connection')
if i == 0 or i == 99 or i == 199 or i == 299:
sns.heatmap(weights, cmap = 'winter')
plt.title('Heatmap after stack %i patterns' %(i+1))
plt.show()
stable_points = 0
for j in range(examined_trainining.shape[0]):
output = predict(weights, examined_trainining[j], max_iterations=1)
if (np.array_equal(examined_trainining[j], output)):
stable_points += 1
stable_patterns[i] = stable_points / examined_trainining.shape[0]
print(stable_patterns)
plt.plot(np.arange(1, 301, 1), stable_patterns, label='Stable Points %')
plt.vlines(13.8, 0, 1, linestyles='dashed', label='0.138*N')
plt.title('Stable Pattern Percentage as a function of the training size')
plt.xlabel('Number of Training Patterns')
plt.ylabel('Stable Pattern Percentage')
plt.legend()
plt.show()
def three_point_five_fifth_bullet(method='self_connection'):
number_of_random_samples = 300
max_training_num = np.arange(1, number_of_random_samples + 1, 1) # [3,4, 5, 6, 7]
np.random.seed(42)
max_iter = 1
percentage_check = np.arange(0, 55, 5)
training = np.zeros((number_of_random_samples, 10 * 10))
for i in range(number_of_random_samples):
training[i] = get_random_image(pixels=100)
print(training.shape)
stable_patterns = np.zeros(number_of_random_samples)
percentage = 0.1
for i in range(number_of_random_samples):
examined_trainining = training[:i + 1].copy()
weights = fit(examined_trainining, method)
stable_points = 0
for j in range(examined_trainining.shape[0]):
M = examined_trainining.shape[1]
examined_trainining_noise = examined_trainining[j].copy()
noise_magnitude = int(percentage * M)
flipped_indeces = np.random.choice(M, noise_magnitude, replace=False)
examined_trainining_noise[flipped_indeces] = -examined_trainining_noise[flipped_indeces]
output = predict(weights, examined_trainining_noise, max_iterations=100)
if (np.array_equal(examined_trainining[j], output)):
stable_points += 1
stable_patterns[i] = stable_points / examined_trainining.shape[0]
print(stable_patterns)
plt.plot(np.arange(1,301,1), stable_patterns,label='Stable Points %')
plt.vlines(13.8,0,1,linestyles='dashed',label='0.138*N')
plt.legend()
plt.title('Stable Pattern Percentage as a function of the training size')
plt.xlabel('Number of Training Patterns')
plt.ylabel('Stable Pattern Percentage')
plt.show()
def three_point_five_sixth_bullet(method='self_connection',p=[0.1,0.9]):
number_of_random_samples = 300
max_training_num = np.arange(1, number_of_random_samples + 1, 1) # [3,4, 5, 6, 7]
np.random.seed(42)
max_iter = 1
percentage_check = np.arange(0, 55, 5)
training = np.zeros((number_of_random_samples, 10 * 10))
for i in range(number_of_random_samples):
training[i] = get_random_image(pixels=100,p=p)
print(training.shape)
stable_patterns = np.zeros(number_of_random_samples)
percentage = 0.1
for i in range(number_of_random_samples):
examined_trainining = training[:i + 1].copy()
weights = fit(examined_trainining, method)
stable_points = 0
for j in range(examined_trainining.shape[0]):
M = examined_trainining.shape[1]
examined_trainining_noise = examined_trainining[j].copy()
noise_magnitude = int(percentage * M)
flipped_indeces = np.random.choice(M, noise_magnitude, replace=False)
examined_trainining_noise[flipped_indeces] = -examined_trainining_noise[flipped_indeces]
output = predict(weights, examined_trainining_noise, max_iterations=100)
if (np.array_equal(examined_trainining[j], output)):
stable_points += 1
stable_patterns[i] = stable_points / examined_trainining.shape[0]
print(stable_patterns)
plt.plot(np.arange(1 / 300, 1 + 1 / 300, 1 / 300), stable_patterns)
plt.show()
def accuracy_with_sample_images(percentage_check,max_training_num,max_iter,training):
accuracy = np.zeros((percentage_check.shape[0], max_iter, len(max_training_num), max_training_num[-1]))
for per in range(percentage_check.shape[0]):
print('percentage:',percentage_check[per])
for k in range(len(max_training_num)):
print('model:',str(k+1))
print('with size',max_training_num[k])
for it in range(max_iter):
#distort image
sub_train = training[:max_training_num[k]]
weights = fit(sub_train)
for j in range(sub_train.shape[0]):
train = sub_train[j]
training_noise = train.copy()
M = training_noise.shape[0]
noise_magnitude = int(percentage_check[per]/100 * M)
if(percentage_check[per]>0):
print(noise_magnitude)
flipped_indeces = np.random.choice(M, noise_magnitude, replace=False)
training_noise[flipped_indeces] = -training_noise[flipped_indeces]
output = predict_little_model(weights,training_noise)
accuracy[per,it,k,j] = compute_accuracy(train,output)
print('accuracies ', accuracy[per,it,k])
print(accuracy)
accuracy_mean = accuracy.mean(axis=1)
return accuracy_mean
def three_point_six(activity=10,bias_low=0,bias_high=6,bias_step=0.5):
number_of_random_samples = 300
training = np.zeros((number_of_random_samples, 100))
skeleton = np.zeros(100)
skeleton[:activity] = 1
np.random.seed(42)
if(activity==1):
training = np.zeros((100, 100))
number_of_random_samples=100
for i in range(100):
training[i][i]=1
else:
for i in range(training.shape[0]):
training[i] = np.random.permutation(skeleton)
print("Unique samples ", np.unique(training,axis=0).shape[0])
print('training size', training.shape)
bias_range = np.arange(bias_low, bias_high, bias_step)
capacity_size = np.zeros(bias_range.shape[0])
count=0
for bias in bias_range:
stable_patterns = np.zeros(number_of_random_samples)
for i in range(number_of_random_samples-1):
examined_training = training[:i + 1].copy()
weights = sparse_fit(examined_training, method='self_connection')
stable_points = 0
for j in range(examined_training.shape[0]):
output = sparse_predict(weights, bias, examined_training[j], max_iterations=100)
# print('outputs ratio',output[output==1].shape[0]/output.shape[0])
if (np.array_equal(examined_training[j], output)):
stable_points += 1
stable_patterns[i] = stable_points / examined_training.shape[0]
if (stable_patterns[i]<1):
break
print(stable_patterns)
capacity_size[count] = measure_capacity(stable_patterns)
print('capacity size',capacity_size[count])
'''
plt.plot(np.arange(1, 301, 1), stable_patterns, label='Stable Points %')
plt.vlines(13.8, 0, 1, linestyles='dashed', label='0.138*N')
plt.legend()
plt.title('Stable Pattern Percentage as a function of the training size')
plt.xlabel('Number of Training Patterns')
plt.ylabel('Stable Pattern Percentage')
plt.show()
'''
count+=1
plt.plot(bias_range, capacity_size, label = 'Capacity Size')
position = bias_low + np.argmax(capacity_size)*bias_step
plt.vlines(position,0,np.max(capacity_size),linestyles='dashed',label='At '+str(round(position,1)))
plt.title("Capacity size as a function of the bias")
plt.xlabel("Bias")
plt.ylabel("Capacity Size")
plt.legend()
plt.show()
def measure_capacity(stable_patterns):
counter=0
for num in stable_patterns:
if (num==1):
counter+=1
else:
break
return counter |
f656e6c8eef37eff82d83c98c1352b9322d3bc53 | green-fox-academy/RudolfDaniel | /[week-02]/[day-01]/Exercise-26.py | 208 | 4.03125 | 4 | nr1 = int(input("Type in number one: "))
nr2 = int(input("Type in number two: "))
if nr2 <= nr1:
print("The second number should be bigger")
elif nr2 > nr1:
for i in range(nr1, nr2):
print(i) |
4f9bf5d5e60b078e314bb4d6008a58e1b1a18713 | BohdanLiuisk/python-course-beginner | /Solution/seqLen.py | 115 | 3.8125 | 4 | n = int(input())
len = 0
while n > 0:
len += 1
n = int(input())
if n == 0:
continue
print(len)
|
07eb56181e2314aa54c7002756290c07dc8109d5 | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH07/EX7.8.py | 803 | 4.34375 | 4 | # 7.8 (Stopwatch) Design a class named StopWatch. The class contains:
# ■ The private data fields startTime and endTime with get methods.
# ■ A constructor that initializes startTime with the current time.
# ■ A method named start() that resets the startTime to the current time.
# ■ A method named stop() that sets the endTime to the current time.
# ■ A method named getElapsedTime() that returns the elapsed time for the
# stop watch in milliseconds.
# Draw the UML diagram for the class, and then implement the class. Write a test
# program that measures the execution time of adding numbers from 1 to
# 1,000,000.
from CH7.StopWatch import StopWatch
sw = StopWatch()
res = 0
sw.start()
for i in range(1, 1000001):
res += i
sw.end()
print("The elapsed time is:", sw.getElapsedTime())
|
4e50553975988dcc877118df84d9a86710261f7c | Bachatero/AKOB | /assignments/assignment10.2_last.py | 275 | 3.546875 | 4 |
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
distrib = dict()
for line in handle:
if not line.startswith("From "):
continue
lst = list()
lst = distrib.items()
lst.sort()
for key,val in lst:
print key, val
|
6a13372dcd83864ece8e00dbfd29d6af2603086a | YiwenCui/Interview_questions | /string_to_int.py | 1,179 | 3.671875 | 4 | # interview step 1: clarifying questions/High level discussion
# step 2: chooose approach, list potential solutions and approach
def add_one(given_array):
carry = 1
result = []
for i in range(len(given_array)-1,-1, -1):
total = given_array[i] + carry
if total == 10:
carry = 1
else: carry = 0
result.insert(0,total%10)
if carry ==1:
result.insert(0,1)
return result
def list_to_int_add_one(given_list):
concatenate = ""
for int_element in given_list:
concatenate += str(int_element)
concatenate_sum = int(concatenate)+1
return_list =[]
for char in str(concatenate_sum):
return_list.append(int(char))
return return_list
def list_add_one (given_list):
sum_int=0
for index, integer in enumerate(given_list[::-1]):
res = integer * 10**index
sum_int += res
sum_int += 1
return_list =[]
for char in str(sum_int):
return_list.append(int(char))
return return_list
print(list_add_one([2,3,4]))
#see link https://www.youtube.com/watch?v=uQdy914JRKQ&list=PLBZBJbE_rGRVnpitdvpdY9952IsKMDuev&index=4" |
8054031756b9245f7f3c2e129032f47f00c7dd29 | guojixu/interview | /leetcode/0. 树的非递归遍历.py | 1,686 | 3.953125 | 4 |
def preorder(root): # 先序
stack = []
while stack or root:
while root:
print(root.val)
stack.append(root)
root = root.lchild
root = stack.pop()
root = root.rchild
def inorder(root): # 中序
stack = []
while stack or root:
while root:
stack.append(root)
root = root.lchild
root = stack.pop()
print(root.val)
root = root.rchild
def inorder(root):
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
root = root.rchild
def postorder(root):
res = deque()
stack = deque()
p = root
while p != None or len(stack) > 0:
while p != None:
res.appendleft(p.val)
stack.append(p)
p = p.right
p = stack.pop()
p = p.left
def postorder(root): # 后序
stack = []
while stack or root:
while root:
stack.append(root)
root = root.lchlid if root.lchild else root.right
root = stack.pop()
print(root.val)
if stack and stack[-1].lchild == root:
root = stack[-1].rchild
else:
root = None
from collections import deque
def postorderTraversal(self, root):
res = deque()
stack = deque()
p = root
while p != None or len(stack) > 0:
while p != None:
res.appendleft(p.val)
stack.append(p)
p = p.right
p = stack.pop()
p = p.left
return res
|
8e35ccb2fbb118864f471113ddb871f20ed757de | zhaoxuyan/LeetCode_Python | /058_Length_of_Last_Word.py | 515 | 3.75 | 4 | # 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
# 如果不存在最后一个单词,请返回 0 。
# 输入: "Hello World"
# 输出: 5
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == ' ':
return 0
elif len(s) == 1 and s != ' ':
return 1
else:
split_res = s.rstrip().split(' ')
return len(split_res[::-1][0])
|
b7fb18b1d37df291a7a7bc9a71d268ca99ea36ba | nirajan5/Demo | /TupleIndexingAndSlicing.py | 207 | 4.15625 | 4 | tuple = (1, 2, 3, 4, 5, 6, 7)
# element 1 to end
print(tuple[1:])
# element 0 to 3 element
print(tuple[:4])
# element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])
|
e364ac3e891692b1066ceca38079c37619abe4ee | Aru09/JangoRepo | /Week1/HackerRank/ifelse.py | 280 | 4.09375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
if(n%2!=0):
print("Weird")
if(n%2==0 and n in range(1,6)):
print ("Not Weird")
if(n%2==0 and n in range(5,21)):
print("Weird")
if (n%2==0 and n>20):
print ("Not Weird") |
2072a01629b678332f5b02d2542744186413f162 | jaina-sunny/jsm | /a.py | 223 | 4.03125 | 4 | s = raw_input("enter a string ")
n = input("enter a key ")
st=""
def encrypt(s,n):
st=""
for i in range(0,len(s)):
char=s[i]
st=st+ chr((ord(char) + n - 97) % 26 + 97)
return st
print "the result:" + encrypt(s,n)
|
c5efd7729a34d5dcac5f1766a4f08e57092bceaa | rafaelperazzo/programacao-web | /moodledata/vpl_data/445/usersdata/323/103287/submittedfiles/matriz2.py | 900 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
z = int(input('Digite a dimensão da matriz(i=j): '))
m = []
for i in range(0,z,1):
n=[]
for j in range(0,z,1):
n.append(float(input('Digite o valor da linha%d e da coluna%d: '%((j+1),(i+1)))))
m.append(n)
if z<=2:
med1=0
med1=med1+m[0][0]+m[0][1]
med1=med1/2.0
med2=0
med2=med2+m[0][0]+m[1][1]
med2=med2/2.0
if med1!=med2:
print('N')
else:
print('S')
else:
med1=0
for i in range(0):
for j in range(0,z,1):
med1=med1+m[i][j]
med1=med1/3
med2=0
for i in range(1):
for j in range(0,z,1):
med2=med2+m[i][j]
med2=med2/3
med3=0
for i in range(2):
for j in range(0,z,1):
med3=med3+m[i][j]
med3=med3/3
if med1==med2 and med2==med3 and med1==med3:
print('N')
else:
print('S') |
f79acaf2c487d74eb9c0bfbc1f16aa19a1708eed | babiswas/Tree | /test18.py | 917 | 3.90625 | 4 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def inorder(node):
if node:
if node.left:
inorder(node.left)
print(node.value)
if node.right:
inorder(node.right)
def delete_full_tree(node):
if node:
node=delete_tree(node)
node=None
return node
def delete_tree(node):
if not node:
return
else:
delete_tree(node.left)
delete_tree(node.right)
print(f"deleting{node.value}")
node.left=None
node.right=None
del node
node=None
if __name__=="__main__":
node=Node(12)
node.left=Node(21)
node.right=Node(22)
node.left.left=Node(25)
node.left.right=Node(27)
node.right.left=Node(16)
node.right.right=Node(19)
inorder(node)
node=delete_tree(node)
inorder(node)
|
77ec9d228c98accedd08f7b9078163cd6e43273f | gabriellaec/desoft-analise-exercicios | /backup/user_374/ch28_2020_03_23_19_55_07_100940.py | 126 | 3.59375 | 4 | n = 0
calcula = 0
while n < 100:
calcula = calcula + (1/(2**n))
n = n + 1
if n == 99:
print(calcula)
|
45bc9c1e656eb9d947b90f10532b7c64d51b3f85 | BlogBlocks/jupnote | /searcH.py | 285 | 3.6875 | 4 | # Simple File Search
#import searcH
#searcH.search()
def search(filename, term):
datafile = open(filename, "r")
data = datafile.readlines()
for line in data:
if term in line:
print line,
if __name__ == "__main__":
search(filename, term) |
f6064c35bc8dbbcfff2efcc2717b91034bf9891c | yanomateus/loan-calculator | /loan_calculator/irr.py | 7,513 | 3.90625 | 4 | def newton_raphson_solver(
target_function,
target_function_derivative,
initial_point,
maximum_relative_error=0.0000000001,
max_iterations=100,
):
"""Numerical solver based on Newton-Raphson approximation method.
The Newton-Raphson method allows algorithmic approximation for the root
of a differentiable function, given its derivative and an initial point at
which this derivative does not vanish.
Let :math:`f:\\left[a,b\\right]\\longrightarrow\\mathbb{R}` a
differentiable function, :math:`f^{\\prime}` its derivative function and
:math:`x_0\\in\\left[a,b\\right]`. A root of :math:`f` is then iteratively
approximated by the recurrence
.. math::
x_n := x_{n-1} - \\frac{f(x_{n-1})}{f^{\\prime}(x_{n-1})}, n\\geq 1.
The *relative error* associated with the :math:`n`-th iteration of the
recurrence above is defined as
.. math::
e_n := | \\frac{x_n - x_{n-1}}{x_{n-1}} |, n \\geq 1.
The approximation stops if either :math:`e_n` > `maximum_relative_error`
or :math:`n` > `max_iterations`.
"""
def _iterating_function(x):
return x - target_function(x) / target_function_derivative(x)
def _error_function(reference_point, new_point):
return abs((new_point - reference_point) / reference_point)
past_point = initial_point
iterating_point = _iterating_function(past_point)
relative_error = _error_function(past_point, iterating_point)
num_iterations = 1
while (
relative_error >= maximum_relative_error and
num_iterations < max_iterations
):
past_point, iterating_point = (
iterating_point, _iterating_function(iterating_point)
)
relative_error = _error_function(past_point, iterating_point)
num_iterations += 1
return iterating_point
def return_polynomial_factory(net_principal, returns, return_days):
"""Factory for a callable with point evaluation of the return polynomial.
The return polynomial for a loan with net principal :math:`s_\circ`,
returns :math:`r_1,r_2,\ldots,r_k` to be paid :math:`n_1,n_2,\ldots,n_k`
days after the loan is granted, respectively, is given by
.. math::
f(c) = s_\\circ (1 + c)^{n_k} - r_1 (1 + c)^{n_k-n_1} - \\cdots
- r_{k-1} (1 + c)^{n_k-n_{k-1}} - r_k.
This function builds and returns a callable implementing such polynomial.
Parameters
----------
net_principal : float, required
The net principal of a grossed up loan.
returns : list of floats, required
Due payments that completely pay off the grossed up principal when
respectively applied for the given return days.
return_days : list of ints, required
List with the number of days since the taxable event (which is usually
a "loan granted" event) happened.
Returns
-------
Callable
Python callable implementing the return polynomial for the given
parameters
"""
coefficients_vec = [net_principal] + [-1 * r for r in returns]
def return_polynomial(irr_):
powers_vec = [
(1 + irr_) ** (return_days[-1] - n) for n in [0] + return_days
]
return sum(
coef * power
for coef, power in zip(coefficients_vec, powers_vec)
)
return return_polynomial
def return_polynomial_derivative_factory(net_principal, returns, return_days):
"""
Factory for a callable implementing point evaluation of the derivative of
the return polynomial for the given parameters.
The return polynomial for a loan with net principal :math:`s_\circ`,
returns :math:`r_1,r_2,\ldots,r_k` to be paid :math:`n_1,n_2,\ldots,n_k`
days after the loan is granted, respectively, is given by
.. math::
f(c) = s_\\circ (1 + c)^{n_k} - r_1 (1 + c)^{n_k-n_1} - \\cdots
- r_{k-1} (1 + c)^{n_k-n_{k-1}} - r_k.
Therefore, the derivative of :math:`f(c)` is given by
.. math::
f^\\prime (c) = n_k s_\\circ (1 + c)^{n_k - 1}
- \\sum_{i=1}^{k-1} (n_k - n_i) r_i (1 + c)^{n_k - n_i - 1}.
Parameters
----------
net_principal : float, required
The net principal of a grossed up loan.
returns : list of floats, required
Due payments that completely pay off the grossed up principal when
respectively applied for the given return days.
return_days : list of ints, required
List with the number of days since the taxable event (which is usually
a "loan granted" event) happened.
Returns
-------
Callable
Python callable implementing the return polynomial for the given
parameters
"""
derivative_coefficients_vec = [
net_principal * (return_days[-1] - return_days[-2])
] + [
r * (return_days[-1] - r_day)
# last term does not need to be evaluated
for r, r_day in zip(returns[:-1], return_days[:-1])
]
def return_polynomial_derivative(irr_):
powers_vec = [
(1 + irr_) ** (return_days[-1] - r_day - 1)
for r_day in return_days
]
return sum(
coef * power
for coef, power in zip(derivative_coefficients_vec, powers_vec)
)
return return_polynomial_derivative
def approximate_irr(
net_principal,
returns,
return_days,
daily_interest_rate,
):
"""Approximate the internal return rate of a series of returns.
Use a Newton-Raphson solver implementation to approximate the IRR for the
given loan parameters.
Let :math:`s_\\circ` be a net principal (i.e., a principal with eventual
taxes and fees properly deduced), :math:`r_1,r_2\\ldots,r_k` a sequence of
returns and :math:`n_1,n_2,\\ldots,n_k` the due days for these returns. The
*internal return rate* :math:`c` is then defined as the least positive root
of the polynomial
.. math::
f(X) = s_\\circ X^{n_k} - r_1 X^{n_k-n_1} - \\cdots
- r_{k-1} X^{n_k-n_{k-1}} - r_k
on the real unknown
.. math::
X = 1 + c.
The derivative of :math:`f` is given by
.. math::
f^\\prime (X) = n_k s_\\circ X^{n_k - 1}
- \\sum_{i=1}^{k-1} (n_k - n_i) r_i X^{n_k - n_i - 1}.
The polynomial :math:`f` and its derivative derivative :math:`f^\\prime`
are implemented as Python callables and passed to the Newton-Raphson
search implementation with the daily interest rate as initial approximation
for the IRR.
Parameters
----------
net_principal: float, required
The principal used as reference to evaluate the irr, i.e., this is the
amount of money which is, from the perspective of the borrower,
affected by the irr.
returns: list, required
List of expected returns or due payments.
return_days: list, required
List of number of days since the loan was granted until each expected
return.
daily_interest_rate: float, required
Loan's daily interest rate (for the grossed up principal), used as the
start point for the approximation of the IRR.
"""
return_polynomial = return_polynomial_factory(
net_principal, returns, return_days)
return_polynomial_derivative = return_polynomial_derivative_factory(
net_principal, returns, return_days)
return newton_raphson_solver(
return_polynomial, return_polynomial_derivative, daily_interest_rate
)
|
4c72949e80eb904540d38e66e04bbf0725084afb | cherry-wb/quietheart | /codes/trunk/codes/pythonDemo/14_queue_simple.py | 1,295 | 3.96875 | 4 | #!/usr/bin/python
from Queue import Queue
from Queue import PriorityQueue
a1='a1'
a2='a2'
a3='a3'
a4='a4'
a5='a5'
b1='b1'
b2='b2'
b3='b3'
b4='b4'
b5='b5'
q = Queue()
pq = PriorityQueue()
for i in xrange(5):
p = 5 - i
q.put("a"+str(p))
q.put("b"+str(p))
pq.put((p,"a"+str(p)))
pq.put((p,"b"+str(p)))
for i in xrange(5):
p = 5 - i
q.put("a"+str(p)+str(i+5))
q.put("b"+str(p)+str(i+5))
pq.put((p,"a"+str(p)+str(i+5)))
pq.put((p,"b"+str(p)+str(i+5)))
size = q.qsize()
print "queue item size:%s" %size
print "queue items:"
for i in xrange(size):
print q.get()
size = pq.qsize()
print "priority queue item size:%s" %size
print "priority queue items:"
for i in xrange(size):
print pq.get()
#"but priority queue with same priority is not queue, if we want so, do the following:"
import itertools
count = itertools.count()
poq = PriorityQueue()
for i in xrange(5):
p = 5 - i
poq.put((p,count.next(),"a"+str(p)))
poq.put((p,count.next(),"b"+str(p)))
for i in xrange(5):
p = 5 - i
poq.put((p,count.next(),"a"+str(p)+str(i+5)))
poq.put((p,count.next(),"b"+str(p)+str(i+5)))
size = poq.qsize()
print "priority ordered queue item size:%s" %size
print "priority ordered queue items:"
for i in xrange(size):
print poq.get()
|
4aa2258db3db6eda84e9eb2cf80f007e434a0461 | syurskyi/Algorithms_and_Data_Structure | /_temp/Python for Data Structures Algorithms/template/16 Trees/Tree Representation Implementation (Lists).py | 754 | 3.5 | 4 | # Tree Representation Implementation (Lists)
#
# Below is a representation of a Tree using a list of lists. Refer to the video lecture for an explanation and
# a live coding demonstration!
___ BinaryTree(r
r_ [r, # list, []]
___ insertLeft(root,newBranch
t _ root.p.. 1)
__ l..(t) > 1:
root.i.. (1,[newBranch,t,[]])
____
root.i.. (1,[newBranch, # list, []])
r_ root
___ insertRight(root,newBranch
t _ root.p.. 2)
__ l..(t) > 1:
root.i.. (2,[newBranch, # list,t])
____
root.i.. (2,[newBranch, # list,[]])
r_ root
___ getRootVal(root
r_ root[0]
___ setRootVal(root,newVal
root[0] _ newVal
___ getLeftChild(root
r_ root[1]
___ getRightChild(root
r_ root[2] |
65e84d6c8775c43a2046b0ad3200e97ceb5474ed | SimonSlominski/Codewars | /3_kyu/3_kyu_The Lift.py | 4,696 | 4.03125 | 4 | """ All tasks come from www.codewars.com """
"""
TASK: The Lift
Synopsis
A multi-floor building has a Lift in it.
People are queued on different floors waiting for the Lift.
Some people want to go up. Some people want to go down.
The floor they want to go to is represented by a number (i.e. when they enter the Lift this is the button they will press)
1. Rules
1.1 Lift Rules
- The Lift only goes up or down!
- Each floor has both UP and DOWN Lift-call buttons (except top and ground floors which have only DOWN and UP respectively)
- The Lift never changes direction until there are no more people wanting to get on/off in the direction it is already travelling
- When empty the Lift tries to be smart. For example,
- If it was going up then it may continue up to collect the highest floor person wanting to go down
- If it was going down then it may continue down to collect the lowest floor person wanting to go up
- The Lift has a maximum capacity of people
- When called, the Lift will stop at a floor even if it is full, although unless somebody gets off nobody else can get on!
- If the lift is empty, and no people are waiting, then it will return to the ground floor
1.2 People Rules
- People are in "queues" that represent their order of arrival to wait for the Lift
- All people can press the UP/DOWN Lift-call buttons
- Only people going the same direction as the Lift may enter it
- Entry is according to the "queue" order, but those unable to enter do not block those behind them that can
- If a person is unable to enter a full Lift, they will press the UP/DOWN Lift-call button again after it has departed without them
Kata Task
- Get all the people to the floors they want to go to while obeying the Lift rules and the People rules
- Return a list of all floors that the Lift stopped at (in the order visited!)
NOTE: The Lift always starts on the ground floor (and people waiting on the ground floor may enter immediately)
I/O
Input
- queues a list of queues of people for all floors of the building.
- The height of the building varies
- 0 = the ground floor
- Not all floors have queues
- Queue index [0] is the "head" of the queue
- Numbers indicate which floor the person wants go to
- capacity maximum number of people allowed in the lift
Parameter validation - All input parameters can be assumed OK. No need to check for things like:
- People wanting to go to floors that do not exist
- People wanting to take the Lift to the floor they are already on
- Buildings with < 2 floors
- Basements
Output
- A list of all floors that the Lift stopped at (in the order visited!)
"""
class Dinglemouse(object):
def __init__(self, queues, capacity):
self.queues = [list(person) for person in queues]
self.capacity = capacity
def theLift(self):
visited_floors = [0]
elevator = []
people_waiting = True
while people_waiting:
people_waiting = False
# Going up
for floor in range(0, len(self.queues)):
stop_at_floor = False
for person in elevator[:]:
if person == floor:
elevator.remove(person)
stop_at_floor = True
for person in self.queues[floor][:]:
if person > floor:
stop_at_floor = True
if self.capacity > len(elevator):
elevator.append(person)
self.queues[floor].remove(person)
else:
people_waiting = True
if stop_at_floor and not visited_floors[-1] == floor:
visited_floors.append(floor)
# Going down
for floor in range(len(self.queues) -1, -1, -1):
stop_at_floor = False
for person in elevator[:]:
if person == floor:
elevator.remove(person)
stop_at_floor = True
for person in self.queues[floor][:]:
if person < floor:
stop_at_floor = True
if self.capacity > len(elevator):
elevator.append(person)
self.queues[floor].remove(person)
else:
people_waiting = True
if stop_at_floor and not visited_floors[-1] == floor:
visited_floors.append(floor)
if visited_floors[-1] != 0:
visited_floors.append(0)
return visited_floors
|
43b246b5e1b9dcf1dcbdc8424581343b7d3aee12 | AlexTheKing/python-course | /classes.py | 266 | 3.71875 | 4 | class Cat:
def __init__(self, name):
self.name = name
def meow(self):
print('Meow!')
def drink(self, beverage):
print('Meow! I drink {}!'.format(beverage))
cat = Cat('Tom')
cat.color = 'black'
print(cat.name)
print(cat.color)
cat.meow()
cat.drink('milk') |
aad023c862faceb058b0dfbe3e3c9dbf2a138f9e | le-birb/advent-of-code_2020 | /day3.py | 907 | 3.71875 | 4 |
from math import prod as mult
from itertools import zip_longest, product
infile = open('day3-input', 'r')
trees = [[c == '#' for c in line.strip()] for line in infile]
infile.close()
height = len(trees)
width = len(trees[0])
def count_trees(right, down):
tree_count = 0
for i in range(0, height//down):
tree_count += trees[down*i][(right*i) % width]
return tree_count
# part 1
right= 3
down = 1
print(count_trees(right, down))
# part 2
rights = [1, 3, 5, 7, 1]
downs = [1, 1, 1, 1, 2]
slopes = zip_longest(rights, downs)
print(mult(count_trees(*slope) for slope in slopes))
# for fun, determine a slope with minimum tree collisions
rights = range(width*height//2)
downs = range(1, height//2)
curr_min = (height, ())
for slope in product(rights, downs):
count = count_trees(*slope)
if count < curr_min[0]:
curr_min = (count, slope)
print(curr_min) |
6fca13066743f2dffe8d51ced7843dea0664cb18 | signoreankit/PythonLearn | /set.py | 556 | 4.375 | 4 | #Sets - Unordered collections of unique elements
# To Define Set
set_1 = set()
# To add element to a set
set_1.add('Ankit')
set_1.add('Ankit') # It wont take duplicate items. Try it!
set_1.add('Dell Xps 15')
set_1.add('Python 3.6')
set_1.add('Machine Learning')
print("Set_1: ", set_1)
# Casting a list with duplicate items into Set - To get only unique values, It can be unordered.
list_toCast = [1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2, 2]
new_set = set(list_toCast)
print('Our list is: {l}\nOur set from that list is: {s}'.format(l = list_toCast, s = new_set)) |
0ecc206f18e17e5df485c4437a10c4ee4692aae7 | gustavo621/projetos-em-python | /projetos em python/exercicio45.py | 871 | 3.8125 | 4 | import random
pc = ["pedra", "papel", "tesoura"]
pc2 = random.choice(pc)
print('''suas opções:
[ 1 ] pedra
[ 2 ] papel
[ 3 ] tesoura''')
seu = int(input("escolha uma opção: "))
if pc2 == "pedra" and seu == 3:
print("você perdeu! o pc escolheu pedra")
elif pc2 == "papel" and seu == 1:
print("você perdeu! o pc escolheu papel")
elif pc2 == "tesoura" and seu == 2:
print("você perdeu! o pc scolheu tesoura")
elif pc2 == "pedra" and seu == 2:
print("você ganhou! o pc escolheu pedra")
elif pc2 == "papel" and seu == 3:
print("você ganhou! o pc escolheu papel")
elif pc2 == "tesoura" and seu == 1:
print("você ganhou! o pc escolheu tesoura")
elif pc2 == "pedra" and seu == 1:
print("o jogo deu empate!")
elif pc2 == "papel" and seu == 2:
print("o jogo deu empate!")
elif pc2 == "tesoura" and seu == 3:
print("o jogo deu empate!") |
84f65c3cec5d670f35cacd817dbb9f1741e4059c | Saranya2616/hello-world | /power.py | 137 | 3.8125 | 4 | a=int(input())
b=int(input())
if a & b is int:
c=a**b
print(c)
else:
c=int(a)
d=int(b)
e=c**d
print(e)
|
9620f5ab669734e1ec5082416d09b00cd2606fc3 | anonymint/euler | /python/euler002.py | 994 | 4.03125 | 4 | """
Project Euler #2: Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first terms will be:
1,2,3,5,8,13,21,34,55,89,...
By considering the terms in the Fibonacci sequence whose values do not exceed , find the sum of the even-valued terms.
"""
def solution(n: int):
"""
pass integer and loop while keep buffer(last one before) and current and keep updating
the value of current fibonacci = current + buffer which current = fibonacci and buffer = current
:param n: input
:type n: int
:return: sum of value that's even and not over n
:rtype: int
"""
if n < 2:
return 0
buffer = 1
current = 1
count = 0
while current < n:
temp = current + buffer
if temp % 2 == 0 and temp < n:
count += temp
buffer = current
current = temp
return count
if __name__ == '__main__':
print(solution(100)) |
08e33e4645bfb1716171c6fdf0f895e5eaf4e002 | zmalpq/CodeWars | /take a ten minute walk.py | 2,873 | 4.40625 | 4 | #You live in the city of Cartesia where all roads are laid out in a perfect grid.
#You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk.
#The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']).
#You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block,
#so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
#Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only).
#It will never give you an empty array (that's not a walk, that's standing still!).
#solution
def is_valid_walk(walk):
# two conditions to meet:
# 1. walk must take exactly 10 minutes. This means that the length of the directions provided must be equal to 10 (1 minute for each direction).
# 2. walk must bring you back to original position. This means that number of north values must be equal to number of south values (sum equal to zero) and number of east values must be equal to number of west values.
# First: create dictionary with "x" key to track sum of north/south values and "y" key to track sum of east/west values
dict = {"x": 0, "y": 0}
# first condition: walk must take exactly 10 minutes. if length of directions is less than or greater than 10, return False.
if len(walk) < int(10):
return False
elif len(walk) > int(10):
return False
# if length of directions is equal to 10, we can now take a look at the second condition (walk must bring you back to original position).
elif len(walk) == int(10):
# use a for loop to iterate over the elements 'n', 's', 'e', 'w' in the list:
for i in walk:
# if i is equal to 'n' (north), add a count of +1 to the value of the key 'x' in the dictionary previously created. if equal to 's' (south), subtract 1.
if i == "n":
dict["x"] += 1
if i == "s":
dict["x"] -= 1
# if i is equal to 'e' (east), add a count of +1 to the value of the key 'y' in the dictionary. if equal to 'w' (west), subtract 1.
if i == "e":
dict["y"] += 1
if i == "w":
dict["y"] -= 1
# if north and south balance out to 0, and east and west balance out to 0, this means that the walk has brought you back to your original position.
if dict == {"x": 0, "y": 0}:
return True
else:
return False
|
cf2fb52172448eac18f83428de4e4d6cd7d6b605 | Nahidjc/python_problem_solving | /armstrong.py | 182 | 3.84375 | 4 | N= int(input())
temp=N
sum=0
while N != 0:
rem = N%10
N = N//10
sum = sum+ (rem**3)
if sum == temp:
print("the Number is armstrong")
else:
print("Not Armstrong") |
8a2041d7aee907757a2cbf5e650047ef6feaaad0 | ayushiagarwal99/leetcode-lintcode | /leetcode/depth_first_search/124.binary_tree_maximum_path_sum/124.BinaryTreeMaximumPathSum_zheyuuu.py | 1,315 | 3.828125 | 4 | # Source : https://leetcode.com/problems/binary-tree-maximum-path-sum
# Author : zheyuuu
# Date : 2020-08-05
#####################################################################################################
#
# Given a non-empty binary tree, find the maximum path sum.
#
# For this problem, a path is defined as any sequence of nodes from some starting node to any node in
# the tree along the parent-child connections. The path must contain at least one node and does not
# need to go through the root.
#
# Example 1:
#
# Input: [1,2,3]
#
# 1
# / \
# 2 3
#
# Output: 6
#
# Example 2:
#
# Input: [-10,9,20,null,null,15,7]
#
# -10
# / \
# 9 20
# / \
# 15 7
#
# Output: 42
#
#####################################################################################################
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.ans = float("-inf")
self.helper(root)
return self.ans
def helper(self, node):
if not node:
return 0
left = self.helper(node.left)
right = self.helper(node.right)
lval = left if left>=0 else 0
rval = right if right>=0 else 0
self.ans = max(node.val+lval+rval, self.ans)
return max(node.val+lval, node.val+rval) |
f6c3bc55ec38fefd1cf9b8dd646f6bf5135716d4 | itsanti/gbu-ch-py-algo | /hw2/hw2_task5.py | 489 | 3.6875 | 4 | """HW2 - Task 5
Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке.
"""
i = 1
for code in range(32, 128):
end = '\n' if i % 10 == 0 else '\t'
print(f'{code:3}-{chr(code)}', end=end)
i += 1
|
f0122e83bce6f99185eca3ff20c799b5d5e0a09a | mkorycinski/algorithms-and-data-structures | /searching/binary_search.py | 1,175 | 3.84375 | 4 | import unittest
def binary_search(arr, ele):
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if arr[mid] == ele:
found = True
else:
if ele < arr[mid]:
last = mid - 1
else:
first = mid + 1
return found
def binary_search_rec(arr, ele):
if len(arr) == 0:
return False
else:
mid = len(arr) // 2
if arr[mid] == ele:
return True
else:
if ele < arr[mid]:
return binary_search_rec(arr[:mid], ele)
else:
return binary_search_rec(arr[mid+1:], ele)
class TestSearches(unittest.TestCase):
def setUp(self):
self.arr = [1,2,3,4,5,6,7,8,9,10]
def test_binary_search(self):
self.assertFalse(binary_search(self.arr, 25))
self.assertTrue(binary_search(self.arr, 5))
def test_binary_search_rec(self):
self.assertFalse(binary_search_rec(self.arr, 25))
self.assertTrue(binary_search_rec(self.arr, 5))
if __name__ == '__main__':
unittest.main() |
31f855cac904eea71623dd33aa6ab3ef7fb855fe | Pshinde100/Natural-language-processing | /NLP.py | 2,765 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 10:24:02 2019
@author: Pranit
"""
import nltk
nltk.download()
import re
sent1 = "this is my first sentense. this sentense has some lines and words. this is the third sentense"
# split para into words
# \s = space
re.split(r"\s", sent1)
# split at a letter - exlcude letter
re.split("e", sent1)
## spilt at word
re.split("sentense",sent1)
## spilt on range of characters
re.split(r"[a-z]",sent1)
## spilt on combination of words
re.split(r"is [a-z]",sent1)
# 2) pattern matching
sent2 = "The Cat is chasing the Mouse in the Room"
# extract all capital letters
re.findall(r'[A-Z][a-z]+',sent2)
re.findall(r'[A-Z][a-z]*',sent2) # *for stating with zero
# extract all word start with small letters
re.findall(r'\s[a-z]+',sent2)
re.findall(r'\s[a-z]*',sent2)
# get all email ids from yhe sentence
sent3 = "primary email id is [email protected], secondary email id [email protected]"
re.findall(r'\s[\w]+@[\w]+', sent3)
# find one particular pattern of email eg : gmail
sent4 = "primary email id is [email protected], secondary email id [email protected], [email protected]"
re.findall(r"\s[\w]+@gmail[\w.]+", sent4)
# find values within an XMl tag
sent5 = "<itemcode>BK100IM10018</itemcode>"
re.findall(r'>(\w+)</', sent5)
# 3) extract number from sentence
sent6 = "there are 7 days , 12 week , 3600, 54862"
re.findall(r"\d{5}", sent6) # all 5 digit
re.findall(r'\d{4}', sent6)
re.findall(r'(?<=\s)\d{4}(?![0-9])', sent6)
re.findall(r'(?<=\s)\d{1}(?![0-9])', sent6)
#################################################
## NLTK
import nltk
sent1 = "the resources can be classified as Natural and aman-made.Natural resources are unlimited .man made resources can get depleted sooner or later "
nltk.word_tokenize(sent1) # word split
nltk.sent_tokenize(sent1) # sentence
# stop words
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
stop_words.update({"|-","--", ">"})
print(stop_words)
sent2 = "the boy was behaving badly and very impolite "
words = nltk.word_tokenize(sent2)
set(words).difference(stop_words)
## Part of speech tagging POS
sent3 = "the old man is walking on the road slowly"
words = nltk.word_tokenize(sent3)
print(words)
pos_words = nltk.pos_tag(words)
print(pos_words)
## get only the Nouns
nouns = ['NN', 'NNS', 'NNP', 'NNPS']
for w,p in pos_words:
if (p in nouns):
print("{0} is a noun". format(w))
## similarly extract the adjective adverbs, verbs
## n-grams
from textblob import TextBlob as tb
blob = tb(sent3)
n1 = blob.ngrams(n=1)
n2 = blob.ngrams(n=2)
n3 = blob.ngrams(n=3)
n4 = blob.ngrams(n=4)
n2
|
be1b22931d637df369df2b0450eae036baebdccc | espazo/sicp-in-python | /2 使用对象构建抽象/列表和字典的实现.py | 2,678 | 4.28125 | 4 | empty_rlist = None
def make_rlist(first, rest):
"""Make a recursive list from its first element and the rest."""
return (first, rest)
def first(s):
"""Return the first element of a recursive list s."""
return s[0]
def rest(s):
"""Return the rest of the elements of a recursive list s."""
return s[1]
def len_rlist(s):
"""Return the length of recursive list s."""
length = 0
while s != empty_rlist:
s, length = rest(s), length + 1
return length
def getitem_rlist(s, i):
"""Return the element at index i of recursive list s."""
while i > 0:
s, i = rest(s), i - 1
return first(s)
def make_mutable_rlist():
"""Return a functional implementation of a mutable recursive list."""
contents = empty_rlist
def dispatch(message, value=None):
nonlocal contents
if message == 'len':
return len_rlist(contents)
elif message == 'getitem':
return getitem_rlist(contents, value)
elif message == 'push_first':
contents = make_rlist(value, contents)
elif message == 'pop_first':
f = first(contents)
contents = rest(contents)
return f
elif message == 'str':
return str(contents)
return dispatch
def to_mutable_rlist(source):
"""Return a functional list with the same contents as source."""
s = make_mutable_rlist()
for element in reversed(source):
s('push_first', element)
return s
# 消息传递
def make_dict():
"""Return a functional implementation of a dictionary."""
records = []
def getitem(key):
for k, v in records:
if k == key:
return v
def setitem(key, value):
for item in records:
if item[0] == key:
item[1] = value
return
records.append([key, value])
def dispatch(message, key=None, value=None):
if message == 'getitem':
return getitem(key)
elif message == 'setitem':
return setitem(key, value)
elif message == 'keys':
return tuple(k for k, _ in records)
elif message == 'values':
return tuple(v for _, v in records)
return dispatch
if __name__ == '__main__':
suits = ['heart', 'diamond', 'apade', 'club']
s = to_mutable_rlist(suits)
print(type(s))
print(s('str'))
print(s('pop_first'))
d = make_dict()
d('setitem', 3, 9)
d('setitem', 4, 16)
print(d('getitem', 3))
print(d('getitem', 4))
print(d('keys'))
print(d('values'))
c = make_dict()
print('c', c('keys'))
|
d6c668f74590864614fbe19db2d0a00dc6495003 | wly6250/Python3.6 | /Python-base/list2.py | 200 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# 从0到99的100个数中,删除所有的偶数!
r=list(range(100))
for i in range(len(r)//2):
r.pop(i)
print('循环条件i:',i)
print('处理后的list:',r)
|
09878b9c10dcf97f9b056fe97d2d7bc0bca76bf1 | Mararsh/yard | /docs/algorithms/selection_sort.py | 5,068 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Title : Selection Sorting
Objective : Show each step of comparing and movement in intuitive way
Created by: Mara
Created on: 2018/3/19 21:01
"""
import random
ODATA = []
DATA_LENGTH = 20
def generate_data(number):
while len(ODATA) < number:
data = random.randint(0, number-1)
if data not in ODATA:
ODATA.append(data)
print("\nDATA: " + str(ODATA))
def selection_sort_find_max():
DATA = ODATA.copy()
compare_count = 0
move_count = 0;
print("\n** selection_sort_find_max")
print("** This algorithm always finds the largest data and move it to end.")
print("DATA: " + str(DATA))
for i in range(0, DATA_LENGTH):
current_index = DATA_LENGTH - 1 - i
print("i=" + str(current_index))
max_index = current_index
for j in range(0, DATA_LENGTH - 1 - i):
compare_count = compare_count + 1
print(" j=" + str(j) + " comparing:'" + str( DATA[j]) + "' and '"+ str( DATA[max_index]) + "'")
if DATA[j] > DATA[max_index]:
max_index = j
print(" max=" + str(DATA[max_index]) )
if max_index == current_index:
continue
tmp1 = DATA[max_index]
tmp2 = DATA[current_index]
DATA[max_index] = tmp2
DATA[current_index] = tmp1
move_count = move_count + 1
print(" exchanging:'" + str( DATA[max_index]) + "' and '"+ str( DATA[current_index]) + "'")
print(" DATA: [", end="")
for m in range(0, DATA_LENGTH):
if m==current_index:
print('\033[1;33;40m', end="")
print(str(DATA[m]), end="")
if m!=(DATA_LENGTH-1):
print(", ", end="")
print("\033[0m", end="")
elif m == max_index:
print('\033[1;33;m', end="")
print(str(DATA[m]), end="")
if m != (DATA_LENGTH - 1):
print(", ", end="")
print("\033[0m", end="")
elif m >= DATA_LENGTH - 1 - i:
print('\033[1;32;40m', end="")
print(str(DATA[m]), end="")
if m != (DATA_LENGTH - 1):
print(", ", end="")
print("\033[0m", end="")
else:
print(str(DATA[m]), end="")
if m!=(DATA_LENGTH-1):
print(", ", end="")
print("]")
return compare_count, move_count
def selection_sort_find_min():
DATA = ODATA.copy()
compare_count = 0
move_count = 0;
print("\n** selection_sort_find_min")
print("** This algorithm always finds the smallest data and move it to front.")
print("DATA: " + str(DATA))
for i in range(0, DATA_LENGTH):
current_index = i
print("i=" + str(current_index))
min_index = current_index
for j in range(i+1, DATA_LENGTH):
compare_count = compare_count + 1
print(" j=" + str(j) + " comparing:'" + str(DATA[j]) + "' and '" + str(DATA[min_index]) + "'")
if DATA[j] < DATA[min_index]:
min_index = j
print(" min=" + str(DATA[min_index]))
if min_index == current_index:
continue
tmp1 = DATA[min_index]
tmp2 = DATA[current_index]
DATA[min_index] = tmp2
DATA[current_index] = tmp1
move_count = move_count + 1
print(" exchanging:'" + str(DATA[min_index]) + "' and '" + str(DATA[current_index]) + "'")
print(" DATA: [", end="")
for m in range(0, DATA_LENGTH):
if m==current_index:
print('\033[1;33;40m', end="")
print(str(DATA[m]), end="")
if m!=(DATA_LENGTH-1):
print(", ", end="")
print("\033[0m", end="")
elif m == min_index:
print('\033[1;33;m', end="")
print(str(DATA[m]), end="")
if m != (DATA_LENGTH - 1):
print(", ", end="")
print("\033[0m", end="")
elif m <= i:
print('\033[1;32;40m', end="")
print(str(DATA[m]), end="")
if m != (DATA_LENGTH - 1):
print(", ", end="")
print("\033[0m", end="")
else:
print(str(DATA[m]), end="")
if m != (DATA_LENGTH - 1):
print(", ", end="")
print("]")
return compare_count, move_count
if __name__ == '__main__':
generate_data(DATA_LENGTH)
compare_count, move_count = selection_sort_find_max()
print("## Data size: " + str(DATA_LENGTH))
print("## Total compared: " + str(compare_count))
print("## Total moved: " + str(move_count))
compare_count, move_count = selection_sort_find_min()
print("## Data size: " + str(DATA_LENGTH))
print("## Total compared: " + str(compare_count))
print("## Total moved: " + str(move_count))
|
4e69f55ec7e9e0a3a870ba03bc7b0c0ebe7de417 | rajababulukka/PythonPrograms | /recursive_string_permutation.py | 446 | 3.765625 | 4 | def permutation(str_1):
if len(str_1)<=1:
return set([str_1])
all_permutations=[]
for i in range(len(str_1)):
first=str_1[i]
rest=str_1[:i]+str_1[i+1:]
permutations=permutation(rest)
for permute in permutations:
all_permutations.append(first+permute)
return set(all_permutations)
print(permutation("ab"))
print(permutation("abc"))
print(permutation("raja"))
|
2f7b84480815942d4f30111de08783577c18d61a | parwez6969/fossproject | /python 786.py | 167 | 4 | 4 | a=int(input('enter the first number'))
b=int(input('enter the second number'))
addition=a+b
multipliction=a*b
print('addition=',a+b)
print('multipliction=',a*b)
|
c5027a7c2c5f14c446f6e294e309fd68e603fca8 | loxygenK/blin-tool | /scripts/lib/color.py | 655 | 3.625 | 4 | class Color:
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
PINK = 5
CYAN = 6
WHITE = 7
@classmethod
def colored(cls, string, color, bold=False):
if type(color) == int:
return cls.__colored(string, color, bold)
elif type(color) == str:
color_code = eval("Color." + color)
return cls.__colored(string, color_code, bold)
raise TypeError("color should be int or str.")
@classmethod
def __colored(cls, string, color_code, bold=False):
return "\033[38;5;{}{}m{}\033[m".format(
color_code, ";1" if bold else "", string
)
|
9a29fe6f20d13d587327bf84001979425224cd9b | Aasthaengg/IBMdataset | /Python_codes/p03803/s724674653.py | 200 | 3.609375 | 4 | strength = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1]
A, B = [strength.index(n) for n in map(int, input().split())]
if A > B:
print('Alice')
elif A < B:
print('Bob')
else:
print('Draw')
|
893ae9a7901c8ce7030ca0efdb4c81dba293c3ba | nicolealdurien/Assignments | /week-02/day-1/user_address.py | 1,673 | 4.4375 | 4 | # Week 2 Day 1 Activity - User and Address
# Create a User class and Address class, with a relationship between
# them such that a single user can have multiple addresses.
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.addresses = []
def get_first_name(self, first_name):
return self.first_name
def get_last_name(self, last_name):
return self.last_name
def add_address(self, address):
str_address = str(address)
self.addresses.append(str_address)
def display_addresses(self):
print(f"""Addresses listed for {self.first_name} {self.last_name}:\n {self.addresses}""")
def __str__(self):
return f"{str(self.first_name)} {str(self.last_name)}"
class Address:
def __init__(self, street, city, state, zip_code):
self.street = street
self.city = city
self. state = state
self.zip_code = zip_code
def get_street(self, street):
return self.street
def get_city(self, city):
return self.city
def get_state(self, state):
return self.state
def get_zip_code(self, zip_code):
return self.zip_code
def __str__(self):
return f"{str(self.street)}, {str(self.city)}, {str(self.state)} {str(self.zip_code)}"
mickey_mouse = User('Mickey', 'Mouse')
magic_kingdom = Address('1180 Seven Seas Dr', 'Lake Buena Vista', 'FL', '32836')
epcot = Address('200 Epcot Center Dr', 'Orlando', 'Florida', '32821')
mickey_mouse.add_address(magic_kingdom)
mickey_mouse.add_address(epcot)
mickey_mouse.display_addresses()
|
c0e1994cf06d96f0b03dfb3c9469748bf63772d6 | rmfaber/FootballPredictions | /getgames.py | 3,521 | 3.5 | 4 | import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import pandas as pd
import time
def start_browser(url='https://www.voetbal.com/'):
browser = webdriver.Chrome()
browser.get(url)
# agree to use cookies
time.sleep(2)
browser.find_element_by_css_selector('button[mode="primary"]').click()
return browser
def get_teamslist_games(browser,season,roundnr):
"""Get all the games for a given season and roundnr
Parameters
-------------
browser, Selenium browserobject
season, str
String with format: {firstyear}-{secondyear}
roundnr, str
String of the roundnr (digit between 1 and 34)"""
url = f"https://www.voetbal.com/wedstrijdgegevens/ned-eredivisie-{season}-spieltag/{roundnr}/"
browser.get(url)
data = requests.get(browser.current_url)
soup = BeautifulSoup(data.text,'html.parser')
games = soup.select("a[title*=Wedstrijddetails]")
table = soup.findAll('table', { 'class' : 'standard_tabelle' })
teams = table[1].select("a[href*=teams]")
teams
teamslist = []
for team in teams:
teamslist.append(team.get_text())
return teamslist, games
def get_teamslist(soup):
"""Find all teams that participate in this year of the Eredivisie"""
table = soup.findAll('table', { 'class' : 'standard_tabelle' })
teams = table[1].select("a[href*=teams]")
teams
teamslist = []
for team in teams:
teamslist.append(team.get_text())
return(teamslist)
def team_identification(game,teamslist):
"""Identify the home and awayteams of a game"""
for team in teamslist:
if team in game['title'].split(' -')[0]:
hometeam = team
elif team in game['title'].split(' -')[1]:
awayteam = team
return hometeam,awayteam
def goals(game):
"""Identify the goals scored and the result of the game"""
goals_scored = game.get_text().split()[0]
homegoals = goals_scored.split(':')[0]
awaygoals = goals_scored.split(':')[1]
if homegoals>awaygoals:
return([homegoals,awaygoals,1])
elif awaygoals>homegoals:
return([homegoals,awaygoals,2])
else:
return([homegoals,awaygoals,3])
def gamestats(game, teamslist):
"""Combine the team identification and result"""
hometeam, awayteam = team_identification(game, teamslist)
resultlist = goals(game)
homegoals = resultlist[0]
awaygoals = resultlist[1]
result = resultlist[2]
if result == 1:
homepoints = 3
awaypoints = 0
elif result == 2:
homepoints = 0
awaypoints = 3
else:
homepoints = 1
awaypoints = 1
return({"Home":hometeam,"Away":awayteam,"HomeGoals":homegoals,"AwayGoals":awaygoals,"Result":result,
"HomePoints":homepoints,"AwayPoints":awaypoints})
def create_df(browser,columns,roundnrs,startjaar,eindjaar):
df = pd.DataFrame(columns=columns)
jaar = startjaar
while jaar <= eindjaar:
season = f"{jaar}-{jaar+1}"
for roundnr in roundnrs:
teamslist, games = get_teamslist_games(browser,season=season,roundnr=str(roundnr))
for game in games:
resultdict = gamestats(game,teamslist)
resultdict["Season"] = season
resultdict["Round"] = roundnr
df = df.append(resultdict,ignore_index=True)
jaar+=1
return df
def test(a,b):
return a + b |
595cebfd880642511997f4b352e431e30b11600e | Vanid64/atbspython | /ch5/inventory.py | 1,113 | 3.859375 | 4 | def displayInventory(inventory):
if type(inventory) != dict:
print('Please pass a dictionary as an inventory.')
return
totalItems = 0
print("Inventory:")
for k, v in inventory.items():
print(str(v) + ' ' + k)
totalItems += v
print("Total number of items: " + str(totalItems))
def addToInventory(inventory, addedItems):
if type(inventory) != dict or type(addedItems) != list:
print('Invalid arguments passed.')
return
for item in addedItems:
inventory.setdefault(item, 0)
inventory[item] += 1
inventory1 = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
inventory2 = 'hello!'
# displayInventory(inventory1)
# displayInventory(inventory2)
adding1 = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
adding2 = ['gold coin', 'dagger', 'dagger', 'bow', 'potion']
adding3 = 'hello!'
# addToInventory(inventory1, adding1)
# displayInventory(inventory1)
# addToInventory(inventory1, adding2)
# displayInventory(inventory1)
# addToInventory(inventory1, adding3)
# displayInventory(inventory1) |
95e032f227acf2e3ac2e818aaa7e38f6950095f4 | HuangPengcheng-0207/file-transfer-python | /FTPClientUsingTCP.py | 2,590 | 4.25 | 4 | """ FTPClientUsingTCP.py
[STUDENTS FILL IN THE ITEMS BELOW]
Libin Feng, Yuqi Liu
CISC-650 Fall 2014
Sep 26, 2014
This module will:
a. start a TCP control connection to the server
b. ask the client to input the name of a file
c. receive the response from server. If the response is 'yes', then start using TCP
transfer to receive the file. If the response is 'no', then give the client a
prompt and exit.
"""
from socket import *
# server machine's name
serverName = "hostname"
# port numbers of server
serverPort_ctrl = 12306
serverPort_transf= 12307
# start using TCP transfer to transfer the file
def start_transfer():
# create TCP transfer socket on client to use for connecting to remote
# server. Indicate the server's remote listening port
clientSocket_transf = socket(AF_INET,SOCK_STREAM)
# open the TCP transfer connection
clientSocket_transf.connect((serverName,serverPort_transf))
# connection prompt
print("TCP transfer connected. | Server: %s, Port: %d" % (serverName, serverPort_transf))
# get the data back from the server
filedata = clientSocket_transf.recv(5000)
# creat a file named "filename" and ready to write binary data to the file
filehandler = open(filename, 'wb')
# write the data to the file
filehandler.write(filedata)
# close the file
filehandler.close()
# close the TCP transfer connection
return clientSocket_transf.close()
# create TCP socket on client to use for connecting to remote
# server. Indicate the server's remote listening port
clientSocket_ctrl = socket(AF_INET, SOCK_STREAM)
# open the TCP control connection
clientSocket_ctrl.connect((serverName,serverPort_ctrl))
# connection prompt
print("TCP control connected. | Server: %s, Port: %d" % (serverName, serverPort_ctrl))
# input the file name client wants
filename = input("Input file name: ")
# send the file name to the server
clientSocket_ctrl.send(bytes(filename, "utf-8"))
# get the status of the file from server "yes" or "No"
filestatus = clientSocket_ctrl.recv(1024).decode("utf-8").strip()
# check whether the file is on the server. If yes, receive the file.
# If no, do give a prompt
if filestatus == "yes":
# download prompt
print("Start downloading..")
# start using TCP transfer
start_transfer()
# success prompt
print("Done!")
else:
# cannot find the file on the server
print("No such file found on the server!")
# close the TCP control connection
clientSocket_ctrl.close() |
6a822e550a8f3e51efc7bdca386b078d7f6a559f | yusif-ifraimov/TowerDefense | /source/button.py | 3,755 | 3.75 | 4 | # Button class
#
# Rectangular object that displays an image,
# can respond to mouse-overs, and
# send a message on click
#
# 2014/4/9
# written by Michael Shawn Redmond
from config import *
import pygame
import rectangle
class Button(rectangle.Rectangle):
def __init__(self, position, width, height, image, image_hover):
# image shown when the mouse is on the button
self.image_hover = pygame.image.load(image_hover)
rectangle.Rectangle.__init__(self, KIND_BUTTON, position, width, height, image)
# mouse-over data
self.message = None
self.hover = False
# message shown on mouse-over
self.description = ""
# object to be sent on click
self.item = None
def paint(self, surface):
# display the hover image on mouse-overs
if self.hover:
surface.blit(self.image_hover, self.position)
# otherwise use the normal image
else:
surface.blit(self.image, self.position)
def game_logic(self, keys, newkeys, mouse_pos, newclicks):
actions = []
# if the mouse is on the button, set the hover data member
if self.is_inside(mouse_pos):
self.hover = True
# if the button was clicked, send a message with the applicable item
if MOUSE_LEFT in newclicks:
actions.append((self.message, self.item))
# reset the hover data member if the mouse is not on the button
else:
self.hover = False
return actions
def get_description(self):
return self.description
def set_description(self, description):
self.description = description
def get_item(self):
return self.item
def set_item(self, item):
self.item = item
# Button-specific child classes
# Only changes needed are the message, image, dimensions, message, and item
class NewWave(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_NEW_WAVE_WIDTH, BUTTON_NEW_WAVE_HEIGHT, BUTTON_NEW_WAVE_IMG, BUTTON_NEW_WAVE_HOVER_IMG)
self.message = BUTTON_NEW_WAVE_MSG
self.item = None
class Upgrade(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_UPGRADE_WIDTH, BUTTON_UPGRADE_HEIGHT, BUTTON_UPGRADE_IMG, BUTTON_UPGRADE_HOVER_IMG)
self.message = BUTTON_UPGRADE_MSG
self.item = None
class Sell(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_SELL_WIDTH, BUTTON_SELL_HEIGHT, BUTTON_SELL_IMG, BUTTON_SELL_HOVER_IMG)
self.message = BUTTON_SELL_MSG
self.item = None
class Play(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_PLAY_WIDTH, BUTTON_PLAY_HEIGHT, BUTTON_PLAY_IMG, BUTTON_PLAY_HOVER_IMG)
self.message = BUTTON_PLAY_MSG
self.item = None
class Quit(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_QUIT_WIDTH, BUTTON_QUIT_HEIGHT, BUTTON_QUIT_IMG, BUTTON_QUIT_HOVER_IMG)
self.message = BUTTON_QUIT_MSG
self.item = None
class Help(Button):
def __init__(self, position = (0, 0)):
Button.__init__(self, position, BUTTON_HELP_WIDTH, BUTTON_HELP_HEIGHT, BUTTON_HELP_IMG, BUTTON_HELP_HOVER_IMG)
self.message = BUTTON_HELP_MSG
self.item = None
class Level(Button):
def __init__(self, position = (0, 0), name = ""):
Button.__init__(self, position, BUTTON_LEVEL_WIDTH, BUTTON_LEVEL_HEIGHT, BUTTON_LEVEL_IMG, BUTTON_LEVEL_HOVER_IMG)
self.message = BUTTON_LEVEL_MSG
# where self.item is the name of the map file
self.item = name
|
7ad8f7dffba52c64a8bab06e8be920967d6c6d31 | apalala/exercism | /python/sublist/sublist.py | 527 | 3.9375 | 4 |
SUBLIST = 1
SUPERLIST = 2
EQUAL = 3
UNEQUAL = 4
def check_lists(alist, blist):
if alist == blist:
return EQUAL
elif _has_sublist(blist, alist):
return SUBLIST
elif _has_sublist(alist, blist):
return SUPERLIST
else:
return UNEQUAL
def _has_sublist(alist, sub):
# See:
# http://stackoverflow.com/a/12576755/545637
return not sub or any(
sub[0] == alist[i] and
sub == alist[i:i + len(sub)]
for i in range(1 + len(alist) - len(sub))
)
|
f72f94385f029819972e2d72d975af5d9788f538 | jcohen66/python-sorting | /questions/easy/two_sum_hash_better.py | 545 | 4.09375 | 4 | def two_sum(nums, target):
'''
Given an array of integers and a target
integer, return an array containing the
indexes of the elements that add up to
the target.
>>> two_sum([2,7,11,15], 9)
[0, 1]
>>> two_sum([3, 2, 4], 6)
[1, 2]
>>> two_sum([3,3], 6)
[0]
'''
result = []
num_elems = len(nums)
dict = {}
for i in range(num_elems):
complement = target - nums[i]
if complement in dict.keys():
result.append(i)
dict[nums[i]] = i
return result
|
50783ab670ce256cb473c3cb184c5f34fee312c0 | paalso/mipt_python_course | /7_pictures_1/2/spec_figures.py | 961 | 3.59375 | 4 | import pygame
def draw_bordered_ellipsis(
screen, ellipse_rect, ellipse_color, border_color, border_width=0):
rect_topleft_x, rect_topleft_y, rect_width, rect_height = ellipse_rect
inner_rect = (rect_topleft_x + border_width,
rect_topleft_y + border_width,
rect_width - 2 * border_width,
rect_height - 2 * border_width)
pygame.draw.ellipse(screen, ellipse_color, inner_rect)
pygame.draw.ellipse(screen, border_color, ellipse_rect, border_width)
def draw_triangle(
screen, bottom_left, base, leg, color, border_color, border_width=0):
bottom_left_x, bottom_left_y = bottom_left
bottom_right = bottom_left_x + base, bottom_left_y
half_base = base // 2
top = bottom_left_x + half_base, \
bottom_left_y - (leg ** 2 + half_base ** 2) ** 0.5
pygame.draw.polygon(screen, color, (bottom_left, bottom_right, top))
|
6b362adfd78d92e5820996ec6a4e7a269664e23f | ernie0423/introprogramacion | /practico2/practico2_ejercicio2.py | 246 | 4.125 | 4 | def numeroMax (num1, num2, num3):
MAX = max(num1,num2,num3)
print("El mayor es:", MAX)
num1 = int(input("ingrese un numero: "))
num2 = int(input("ingrese un numero: "))
num3 = int(input("ingrese un numero: "))
numeroMax(num1, num2, num3) |
adc2f4ac9d674fd85ffe2fe225e3102e5096345e | imdangodaane/tetris | /test.py | 242 | 4.125 | 4 | #!/usr/bin/env python3
def rotate(m):
b = list(zip(*reversed(m)))
for i in range(len(b)):
b[i] = list(b[i])
for i in b:
print(i)
return b
rotate([
[0, 1, 1],
[1, 1, 0]
])
rotate([
[0, 1],
[0, 1],
[1, 1]
])
|
77d9f49b82e3bbdf949e70339d893fe17f77111d | DKanyana/PythonProblems | /4_UniqueOne.py | 218 | 3.953125 | 4 | def find_one_uniq(numbers):
uniq =0
for num in numbers:
uniq ^= num
return uniq
numbers= [1,2,2,3,3,4,4,5,5,1,7]
print(find_one_uniq(numbers))
#Time complexity - O(n)
#Space complexity - O(1) |
1e48a33617e37c016b85b40d94355c74e54abe3c | Ayesha116/piaic.assignment | /q7.py | 230 | 4 | 4 | #Write a Python program to get the difference between a given number and 17, difference cannot be negative
a = int(input("enter any number: "))
if a>=17:
print("difference is ",a-17)
elif a<17:
print("difference is ",17-a) |
09769295bee9a4c84307241bd8a0b1932d94d621 | eronekogin/leetcode | /2022/cinema_seat_allocation.py | 939 | 3.6875 | 4 | """
https://leetcode.com/problems/cinema-seat-allocation/
"""
from collections import defaultdict
class Solution:
def maxNumberOfFamilies(
self,
n: int,
reservedSeats: list[list[int]]
) -> int:
# Build seats.
seats = defaultdict(int)
for r, c in reservedSeats:
seats[r] |= 1 << (c - 1)
# Check groups.
# A row with no reserved seat can have maximum 2 groups.
cnt = (n - len(seats)) << 1
l = int('0111100000', 2)
r = int('0000011110', 2)
m = int('0001111000', 2)
for row in seats.values():
group = 0
group += (row & l) == 0
group += (row & r) == 0
group += (row & m) == 0 and group == 0
cnt += group
return cnt
print(Solution().maxNumberOfFamilies(3,
[[1, 2], [1, 3], [1, 8], [2, 6], [3, 1], [3, 10]]))
|
9f35dadd26f47c77978f42018a9d7f73326b1c5b | elvisliyx/python-learn | /learn-day3/encode.py | 212 | 3.796875 | 4 | #-*- coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())
s = '你好'
print(s.encode())
s_gbk = s.encode('gbk')
print(s_gbk)
s_to_utf = s_gbk.decode('gbk').encode('utf-8')
print('utf-8',s_to_utf)
|
9e61dd627bb4ba4fc285271eadd0fd599854561e | sunil10000/outlab7 | /prep_stmt.py | 3,220 | 3.578125 | 4 | import sqlite3
table_no = int(input())
def insert_team():
team_id = int(input())
team_name = input()
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("INSERT INTO TEAM (team_id, team_name) VALUES (?, ?);", (team_id, team_name))
conn.commit()
conn.close()
def insert_match():
match_id = int(input())
season_year = int(input())
team1 = int(input())
team2 = int(input())
battedfirst = int(input())
battedsecond = int(input())
venue_name = input()
city_name = input()
country_name = input()
toss_winner = input()
match_winner = input()
toss_name = input()
win_type = input()
man_of_match = int(input())
win_margin = int(input())
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("""INSERT INTO MATCH (match_id, season_year, team1, team2, battedfirst, battedsecond, venue_name,
city_name, country_name, toss_winner, match_winner, toss_name, win_type, man_of_match, win_margin)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""",
(match_id, season_year, team1, team2, battedfirst,
battedsecond, venue_name,city_name, country_name, toss_winner,
match_winner, toss_name,
win_type, man_of_match, win_margin))
conn.commit()
conn.close()
def insert_player():
player_id = int(input())
player_name = input()
dob = input()
batting_hand = input()
bowling_skill = input()
country_name = input()
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("""INSERT INTO PLAYER (player_id, player_name, dob, batting_hand,
bowling_skill, country_name) VALUES (?, ?, ?, ?, ?, ?);""",
(player_id, player_name, dob, batting_hand,bowling_skill, country_name))
conn.commit()
conn.close()
def insert_player_match():
playermatch_key = int(input())
match_id = int(input())
player_id = int(input())
batting_hand = input()
bowling_skill = input()
role_desc = input()
team_id = int(input())
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("""INSERT INTO PLAYER_MATCH (playermatch_key, match_id, player_id, batting_hand, bowling_skill,
role_desc, team_id) VALUES (?, ?, ?, ?, ?, ?, ?);""",
(playermatch_key, match_id, player_id, batting_hand, bowling_skill, role_desc, team_id))
conn.commit()
conn.close()
def insert_ball():
match_id = int(input())
innings_no = int(input())
over_id = int(input())
ball_id = int(input())
striker_batting_position = int(input())
runs_scored = int(input())
extra_runs = int(input())
out_type = input()
striker = int(input())
non_striker = int(input())
bowler = int(input())
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("""INSERT INTO BALL_BY_BALL (match_id, innings_no, over_id, ball_id, striker_batting_position, runs_scored, extra_runs,\
out_type, striker, non_striker, bowler) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""",
(match_id, innings_no, over_id, ball_id,
striker_batting_position, runs_scored, extra_runs,
out_type, striker, non_striker, bowler))
conn.commit()
conn.close()
if table_no == 1:
insert_team()
elif table_no == 2:
insert_player()
elif table_no == 3:
insert_match()
elif table_no == 4:
insert_player_match()
elif table_no == 5:
insert_ball()
else:
print("wrong_input")
|
8d32ec8f4c75c6eb1436122c45aa5680391dfef5 | Ian100/Curso_em_Video-exercicios- | /desafio_49.py | 372 | 4.0625 | 4 | # Refaça o desafio 09, mostrando a tabuada de um número que o usuário escolher,
# só que agora utilizando um laço for.
n = int(input('Digite um número inteiro para ver sua tabuada: '))
print('=' * 40, end='\n\t\t\t\t')
print('TABUADA DO {}'.format(n))
print('=' * 40)
for i in range(1, 11):
print('{} x {:2} = {}'.format(n, i, i*n))
print('=' * 40)
|
55a1fe608743ef248e9b6e7b0691571784640cb9 | liqueur/leetcode | /sol_Add_Two_Numbers.py | 1,017 | 3.59375 | 4 |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
_sum = 0
l1stk = []
l2stk = []
while l1 or l2:
if l1:
l1stk.append(l1.val)
l1 = l1.next
if l2:
l2stk.append(l2.val)
l2 = l2.next
i = 0
while l1stk or l2stk:
l1v = l1stk.pop(0) if l1stk else 0
l2v = l2stk.pop(0) if l2stk else 0
_sum += (l1v + l2v) * (10 ** i)
i += 1
root = pre = None
while _sum or (root is None):
v = _sum % 10
_sum //= 10
if pre is None:
root = pre = ListNode(v)
else:
cur = ListNode(v)
pre.next = cur
pre = cur
return root
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.