blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3804829c4fbc476df069e3b6da3cb07448fb5c5c | MHagarGIS/FieldCalculator-repo | /FormatAddress.py | 1,182 | 3.625 | 4 | # Created by: MHagarGIS
# For: GEOG499
# Title: ArcMap Field Calculator Address Formatter in Python
#
#Converting street type to proper format
def converttype(oldtype): #Define function converttype that accepts argument oldtype
oldtype = oldtype.title() #Use the .title() function to make first letter uppercase and the rest lowercase
if oldtype == "Way": #If the old type is "Way" strip out the second letter (a) and assign to newtype
newtype = oldtype[0::2]
elif oldtype == "Ave": #If the old type is "Ave" strip out the third letter (3) and assign to newtype
newtype = oldtype[0:2]
else:
newtype = oldtype #If neither previous condition was met then oldtype is properly formatted. Assign to newtype.
return newtype #Return newtype
#Concatenating address components into FinalAddr
def convertaddr(CorrectNum,NewName,NewType,NewZip): #Define function convertaddr that accepts four arguments
newaddr = str(CorrectNum) + " " + NewName + " " + NewType + " " + str(NewZip) #Convert variables to strings, add spaces, and concatenate into proper form
return newaddr #Return the result
|
343f2a409f4c5c1919f33ac5587298bc4b773d92 | guzey/guzey.github.io1 | /evolution/evolution.py | 7,153 | 3.796875 | 4 | ### PROBLEM: NEED TO MAKE A TON OF ad hoc ASSUMPTIONS ABOUT e.g. FITNESS ADVANTAGES
# don't think there's a solution tho
# done:
# selection
# meiosis
# nucleotide mutation
# gene duplication
# to do:
# gene --> function map (genes encode body part, right after initial values)
# then there's a neural network learning
# and as result best initial values survive
# maybe add garbage genes for sexual selection?
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
def create_population(initial_population_size, initial_genome_size, initial_genome_size_spread):
# initially creatures are haploid, they become diploid during meiosis (like fungi)
population = [[] for _ in range(initial_population_size)]
# creating random variable for nucleotide value
lower, upper = -2, 2
mu, sigma = 0, 1
# truncated normal with mean mu, std sigma and lower and upper bounds
trunc_norm = stats.truncnorm(
(lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
# setting nucleotide values for first number_of_potent_genes for each creature
for creature in population:
potent_genome_size = np.random.randint(initial_genome_size-initial_genome_size_spread,
initial_genome_size+initial_genome_size_spread)
nucleotide_value = trunc_norm.rvs(potent_genome_size)
for gene in range(0, potent_genome_size):
creature.append(nucleotide_value[gene])
return population
# REPRODUCTIVE CYCLE BEGINS
def life(population, number_of_generations):
population_size = len(population)
# geometric distribution with mean of 1/fitness_pressure of the population size
# indicates relative probability of being picked for reproduction, based on
# fitness rank in the population (creatures should be pre-ranked on fitness)
# fitness_pressure increases the steepness of CDF
fitness_pressure = 4 # < population length
# probability of mutation per nucleotide is such that we expect
# mutation_rate mutations per creature per generation
mutation_rate = 1
gene_duplication_rate = 1
# demo fitness is just the sum of nucleotide weights
def sum_fitness_in_population(population):
fitness_in_population = [sum(creature) for creature in population]
return fitness_in_population
average_variance_in_population_over_life = []
average_fitness_in_population_over_life = []
size_of_population_over_life = []
genome_length_of_most_fit_creature = []
for generation in range(0, number_of_generations):
# during mating two haploid organisms create a diploid zygote
# creatures that mate are randomly paired (they're already shuffled
zygotes = []
# replication
while len(zygotes) < population_size:
first_creature_id = int(np.random.geometric(fitness_pressure / population_size, 1)-1)
# second creature is picked randomly
second_creature_id = int(np.random.randint(0, population_size))
# mutate and fertilize!
if first_creature_id < population_size and second_creature_id < population_size:
if first_creature_id != second_creature_id:
# gene duplication
# only first creature mutates
first_creature_genome_length = len(population[first_creature_id])
if np.random.random() < gene_duplication_rate / first_creature_genome_length:
duplication_start = np.random.randint(0, first_creature_genome_length)
duplication_end = min(duplication_start + np.random.randint(1, 3), first_creature_genome_length)
population[first_creature_id][duplication_start:duplication_start] =\
population[first_creature_id][duplication_start:duplication_end]
# mutation
# only first creature mutates
first_creature_genome_length = len(population[first_creature_id])
for nucleotide_id in range(0, first_creature_genome_length):
if np.random.random() < mutation_rate / first_creature_genome_length:
population[first_creature_id][nucleotide_id] =\
population[first_creature_id][nucleotide_id] + np.power(-1, np.random.randint(1, 3))
# fertilization
zygotes.append([population[first_creature_id], population[second_creature_id]])
# now we have diploid zygotes and we need to create haploid creatures out of them
# there's two chromosome only per diploid creature
population = []
for zygote in zygotes:
genetic_code = []
current_location = 0
# randomly get sequences of 1 to 16 nucleotides from each chromosome
while True:
which_homolog = np.random.randint(0, 2)
sequence_length = np.random.randint(1, 17)
genetic_code.extend(zygote[which_homolog][current_location:current_location+sequence_length])
current_location += sequence_length
if current_location >= len(zygote[which_homolog]):
break
population.append(genetic_code)
population_size = len(population)
population = sorted(population, reverse=True)
fitness_of_creatures = sum_fitness_in_population(population)
size_of_population_over_life.append(len(population))
average_variance_in_population_over_life.append(np.var(fitness_of_creatures))
average_fitness_in_population_over_life.append(np.mean(fitness_of_creatures))
genome_length_of_most_fit_creature.append(len(population[0]))
return size_of_population_over_life,\
average_variance_in_population_over_life,\
average_fitness_in_population_over_life,\
genome_length_of_most_fit_creature
def main():
population = create_population(initial_population_size=128,
initial_genome_size=128,
initial_genome_size_spread=8)
size, var, fit, gen_len = life(population, number_of_generations=3000)
# print("Size of the population: ", size)
# print("Variance of fitness in population: ", var)
# print("Average fitness of creatures in population: ", fit)
print("Genome length of the most fit creature: ", gen_len)
# plot of average fitness of population over time
plt.plot(fit)
plt.show()
# sum_fit = 0
# for _ in range(0,100):
# population = create_population(initial_population_size=128,
# initial_genome_size=128,
# initial_genome_size_spread=8)
# size, var, fit, gen_len = life(population, number_of_generations=200)
# sum_fit += fit[-1]
# sum_fit = sum_fit / 100
# print("avg fit over 100 gen: ", sum_fit)
if __name__ == "__main__":
main()
|
d322443df962b9c0c3dbb8528bacfac3eabee165 | BbsonLin/flask-filer | /flask_filer/exceptions.py | 381 | 3.5 | 4 |
class InvalidPathError(ValueError):
"""
Exception raised when a path is not valid.
"""
code = 'invalid-path'
template = 'Path {0.path!r} is not valid.'
def __init__(self, message=None, path=None):
self.path = path
message = self.template.format(self) if message is None else message
super(InvalidPathError, self).__init__(message)
|
c53a33b3173fce4c381c7247e52484a6e7051843 | Basavarajrp/Learning-Python | /dict.py | 6,138 | 4.59375 | 5 | #-------------------Declaring the dict in python and accessing the values using key:------
phonebook={
"Basu":2424,
"Pinki":2244,
"Punter":4422
}
print(phonebook["Pinki"])
print()
#------------------Creating the dict with comprehesion way:--------------------------------
squares = {i:i*i for i in range(10)}
print(squares)
print()
#--------------------Iterating or Traversing the dictonaries:------------------------------
students={"Name":"Basu","Age":23,"Height":5.8,"Weight":62}
#method1:Traversing the key..
for key in students:
print(key)
print()
#method2:Traversing the values..
for key in students:
print(students[key])
print()
#------OR-----------
for values in students.values():
print(values)
print()
#method3:Traversing the key and values both at a time..
for key,value in students.items():
print(key,' ',value)
#------------------------Coopy and Deep coopy----------------------------------------
"""If changes made in one dictonarie and other does not get effected
then it is called deep coopy..
If changes made in one and if other get effect then it is shallow copy.."""
#shallow copy..
a = {1:99,2:24,3:45,4:7}
b=a
print("a before changes:",a) #before changing..
print("b before changes:",b)
b[1]=1
print("a after changes:",a) #after changes made to a b also gets effected these is shallow copy..
print("b after changes:",b)
#deep copy
c = a.copy()
c[1]=4
print(a) #Here changes made to c, a will not get effected these is deep copy..
print(c)
print()
#Shallow copy and deep copy in nested dict..
std = {
'Name':"Basu",
'Age':23,
'Phno':{
"mobile":9090,
"Land":8080,
},
'Place':{
"Res":"Bangalore",
"Perm":"Hydrabad",
},
}
#shallow copy
a = std.copy()
a['Phno']['Land']= 2424
print(a) #changes made to a, but std also got effected this is shallow copy..
print(std)
print()
#deep copy
"""whenever there are nested dict the same references get copied
changes made to one will effect other therefore we make use of copy module.."""
import copy
b=copy.deepcopy(std)
b["Place"]["Perm"]="Mysore"
print(std) #changes made to b, will not effect the std this is deep copy
print(b) #make use of copy module whenever there is nested dict,list,tuples..
print()
#----------------------Collections module in python----------------------------------
print("collections.OrderedDict: Remember the Insertion Order of Keys...")
import collections
d = collections.OrderedDict(one=1,two=2,three=3)
print(d)
d['four']=4 #inserting new elements..
print(d)
print(d.keys())
print(d.values())
print()
print('------------------------------------------------------------------------------------')
print("colections.defaultdict:Return Default Values for Missing Keys..")
print("Example 1")
from collections import defaultdict
dd = defaultdict(list)
dd['dogs'].append("Rufus")
dd['dogs'].append("Kathrin")
dd['cat'].append("Black_Cat")
dd['cat'].append("White_Cat")
print(dd) #creats key and values of type-list..
print("Dogs :",dd['dogs'])
print("Creating the counter by normal method and also by defaultdict method...")
dic_counter = {}
lis = [1,2,3,4,5,4,3,6,6,7,8,9,4]
for i in range(len(lis)):
if lis[i] not in dic_counter:
dic_counter[lis[i]] = 1
else:
dic_counter[lis[i]] += 1
print("Total number of elements repeated :",dic_counter)
print()
print("---------------------------------")
print("using defaultdict method..")
print("Example 2:")
food_list = 'spam spam spam spam spam spam eggs spam'.split()
food_count = defaultdict(int) # default value of int is 0
for food in food_list:
food_count[food] += 1 # increment element's value by 1
print("---------------------------------")
print("Example 3:")
food_list = 'spam spam spam spam spam spam eggs spam'.split()
food_count = defaultdict(int) # default value of int is 0
for food in food_list:
food_count[food] += 1 # increment element's value by 1
#0r
print(food_count)
for i,j in food_count.items():
print(i," ",j)
print("-----------------------------------")
print("Example 4:")
city_list = [('TX', 'Austin'), ('TX', 'Houston'), ('NY', 'Albany'),
('NY', 'Syracuse'), ('NY', 'Buffalo'), ('NY', 'Rochester'),
('TX', 'Dallas'), ('CA', 'Sacramento'), ('CA', 'Palo Alto'),
('GA', 'Atlanta')]
cities_by_state = defaultdict(list)
for state, city in city_list:
cities_by_state[state].append(city)
#OR
for state, cities in cities_by_state.items():
print(state, ', '.join(cities))
print()
print("------------------------------------")
print("Example 5:")
from collections import defaultdict
food_list = [
"bread", "burger", "bread", "sandwich", "burger", "sandwich", "burger","donuts"
]
food_counter = defaultdict(int)
#default value of the int is zero
for i in food_list:
food_counter[i] += 1 #increment food value by one...
print(food_counter)
#------OR---------------
print()
for i, j in food_counter.items():
print(i, j)
print()
print()
print("------------------------------------------------------------------------")
print("collections.ChainMap-Search Multiple Dictionaries as a Single Mapping")
from collections import ChainMap
dict1={"one":1,"two":2}
dict2={"three":3,"four":4}
chain = ChainMap(dict1,dict2)
print(chain)
print(chain['three'])
print(chain['one'])
#print(chain['missing']) gives key error - KeyError:'missing'
print()
print()
print("----------------------------------------------------------------------------")
print("types.MappingProxyType - A Wrapper for Making Read-Only Dictionaries..")
from types import MappingProxyType
writable = {"one":1,"two":2} #this can be used to read as well as write..
read_only = MappingProxyType(writable) #this can be used to readonly..
print(read_only['one'])
print()
#read_only['one'] = 23 #Gives type error..
writable['one'] = 42 #will not give errox cause it is available for both reading and writting also...
print(read_only)
print('__________________________________________________________________________________________') |
9aadfd406f23d5c142029148835f4e1b60a80f70 | aguestuser/flupy | /fluent_python/french_deck.py | 1,618 | 3.671875 | 4 | """French Deck module"""
import collections
from typing import NamedTuple, List, Dict, Iterable, Iterator, cast
Card = NamedTuple('Card', [('rank', str), ('suit', str)])
class FrenchDeck:
ranks: List[str] = [str(n) for n in range(2, 11)] + list('JQKA')
suits: List[str] = 'spades diamonds clubs hearts'.split()
suit_values: Dict[str, int] = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def __init__(self) -> None:
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self) -> int:
return len(self._cards)
# we don't have to implement this if we cast in line 33
# def __iter__(self) -> Iterator[Card]:
# for card in self._cards:
# yield card
def __getitem__(self, position) -> Card:
return self._cards[position]
# __getitem__ allows indexing and slicing:
# >>> deck[0]
# Card(rank='2', suit='spades')
# >>> deck[-1]
# Card(rank='A', suit='hearts')
# >>> deck[:3]
# [Card(rank='2', suit='spades'), Card(rank='3', suit='spades'),
# Card(rank='4', suit='spades')]
# and:
# >>> for card in deck: # doctest: +ELLIPSIS
# ...
# print(card)
# Card(rank='2', suit='spades')
# Card(rank='3', suit='spades')
# Card(rank='4', suit=
def sorting(self, card: Card) -> int:
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(self.suit_values) + self.suit_values[card.suit]
def sorted(self) -> List[Card]:
return sorted(cast(Iterable[Card], self), key=self.sorting)
|
bc23256e91744036df92accf23c5dace00f9afe0 | MakavchikDenis/PythonTask_3.2.py | /CollectionClass/ClassInventory.py | 2,619 | 3.859375 | 4 |
class Inventory:
procent=10 #ежегодный процент амортизации
def __init__(self,nameInventory,year,pricePurch):
self.nameInventory=nameInventory
self.year=year
self.pricePurch=pricePurch
self.price=Inventory.funCountingPrice(self)
def funCountingPrice(self):
return self.pricePurch -self.pricePurch*(((2020-self.year)*Inventory.procent)/100)
def get(self):
return str(f"Название: {self.nameInventory}\n"
f"Год закупки: {self.year}\n"
f"Закупочная стоимость: {self.pricePurch} р.\n"
f"Остаточная стоимость: {self.price} р.")
class Bench(Inventory):
def __init__(self,nameInventory,year,pricePurch,color,lenght):
super(). __init__(nameInventory,year,pricePurch)
self.color=color
self.lenght=lenght
def get(self):
return str(f"Название: {self.nameInventory}\n"
f"Год закупки: {self.year}\n"
f"Закупочная стоимость: {self.pricePurch} р.\n"
f"Остаточная стоимость: {self.price} р.\n"
f"Цвет: {self.color}\n"
f"Длинна: {self.lenght}")
class Skids(Bench):
def __init__(self,nameInventory,year,pricePurch,color,lenght,width):
super().__init__(nameInventory,year,pricePurch,color,lenght)
self.width=width
def funGetSkids(self):
return str(super().get()+"\n"
f"Ширина: {self.width}")
class Ball(Inventory):
def __init__(self,nameInventory,year,pricePurch,color,nameModel):
super(). __init__(nameInventory,year,pricePurch)
self.color=color
self.nameModel=nameModel
def get(self):
return str(f"Название: {self.nameInventory} \n"
f"Год закупки:{self.year} \n"
f"Закупочная стоимость: {self.pricePurch} р.\n"
f"Остаточная стоимость: {self.price} р.\n"
f"Цвет: {self.color}\n"
f"Производитель: {self.nameModel}")
class Mates(Skids):
def __init__(self,nameInventory,year,pricePurch,color,lenght,width,nameModel):
super().__init__(nameInventory,year,pricePurch,color,lenght,width)
self.nameModel=nameModel
def funGetMates(self):
return str(super().funGetSkids()+"\n"
f"Производитель: {self.nameModel}")
|
074902903bf0036d263189463cd5728499909984 | CoaleryStudy/PythonStudy | /Defaults/_008.py | 413 | 3.703125 | 4 | i = 1
while i < 11: # While 루프
print("Hello", i)
i += 1
res = 0
while True: # 무한 루프
print("현재 값들의 합 : ", res)
hi = int(input("값을 입력해주세요! : "))
if hi == 0:
break
res += hi
py = "파이썬"
for s in py: # for 루프
print(s)
for col in range(2, 10): # 구구단
for row in range(1, 10):
print(col, "×", row, "=", col * row) |
e150c09ac72e6b10cd0b848e2ae3eef8a277d58a | CoaleryStudy/PythonStudy | /Defaults/_036.py | 136 | 3.90625 | 4 | import string
line = ' ' + input() + ' '
for unit in string.punctuation:
line = line.replace(unit, ' ')
print(line.count(' the ')) |
7017c9cdd9f32fe4364ca6e7ad420a96bd0ea207 | CoaleryStudy/PythonStudy | /Defaults/_009.py | 425 | 3.921875 | 4 | primes = [2, 3, 5, 7, 11]
for p in primes:
print(p)
print("Length :", len(primes))
primes.append(13)
print(primes)
hi = primes.copy()
hi.append(17)
print(hi, primes)
list1 = [1, 2, 3]
list2 = list((4, 5, 6))
print(list1 + list2)
print(list1 * 3)
list1.extend(list2)
print(list1)
list3 = [5, 2, 4, 1, 3]
list4 = list3.copy()
list3.reverse()
print(list3)
list3.sort()
print(list3)
print(sorted(list4))
print(list4) |
972dda604d209f412c2506c5aa9a7748348485cd | Wenbo11/hybrid-cp-rl-solver | /src/problem/portfolio/environment/portfolio.py | 4,769 | 3.5 | 4 | import random
class Portfolio:
def __init__(self, n_item, capacity, weights, means, deviations, skewnesses, kurtosis, moment_factors):
"""
Create an instance of the 4-moment portfolio optimization problem
:param n_item: number of items to add (or not) in the portfolio
:param capacity: maximal capacity of the portfolio
:param weights: list of weights of the items
:param means: list of mean values of the items
:param deviations: list of deviation values of the items
:param skewnesses: list of skewness vales of the items
:param kurtosis: list of kurtosis values of the items
:param moment_factors: list of factor coefficient for the moments (4 values)
"""
self.n_item = n_item
self.capacity = capacity
self.weights = weights
self.means = means
self.deviations = deviations
self.skewnesses = skewnesses
self.kurtosis = kurtosis
self.moment_factors = moment_factors
self.index_list = list(range(n_item))
self.object_list = list(zip(self.index_list, self.weights, self.means, self.deviations, self.skewnesses, self.kurtosis))
@staticmethod
def generate_random_instance(n_item, lb, ub, capacity_ratio, moment_factors, is_integer_instance, seed):
"""
:param n_item: number of items to add (or not) in the portfolio
:param lb: lowest value allowed for generating the moment values
:param ub: highest value allowed for generating the moment values
:param capacity_ratio: capacity of the instance is capacity_ratio * (sum of all the item weights)
:param moment_factors: list of factor coefficient for the moments (4 values)
:param is_integer_instance: True if we want the powed moment values to be integer
:param seed: seed used for generating the instance. -1 means no seed (instance is random)
:return: a 4-moment portfolio optimization problem randomly generated using the parameters
"""
rand = random.Random()
if seed != -1:
rand.seed(seed)
weights = [rand.uniform(lb, ub) for _ in range(n_item)]
means = [rand.uniform(lb, ub) for _ in range(n_item)]
deviations = [rand.uniform(lb, means[i]) ** 2 for i in range(n_item)]
skewnesses = [rand.uniform(lb, means[i]) ** 3 for i in range(n_item)]
kurtosis = [rand.uniform(lb, means[i]) ** 4 for i in range(n_item)]
if is_integer_instance:
weights = [int(x) for x in weights]
means = [int(x) for x in means]
deviations = [int(x) for x in deviations]
skewnesses = [int(x) for x in skewnesses]
kurtosis = [int(x) for x in kurtosis]
capacity = int(capacity_ratio * sum(weights))
final_moment_factors = []
for i in range(4):
if moment_factors[i] == -1:
moment_coeff = rand.randint(1, 15)
final_moment_factors.append(moment_coeff)
else:
final_moment_factors.append(moment_factors[i])
return Portfolio(n_item, capacity, weights, means, deviations, skewnesses, kurtosis, moment_factors)
@staticmethod
def generate_dataset(size, n_item, lb, ub, capacity_ratio, moment_factors, is_integer_instance, seed):
"""
Generate a dataset of instance
:param size: the size of the data set
:param n_item: number of items to add (or not) in the portfolio
:param lb: lowest value allowed for generating the moment values
:param ub: highest value allowed for generating the moment values
:param capacity_ratio: capacity of the instance is capacity_ratio * (sum of all the item weights)
:param moment_factors: list of factor coefficient for the moments (4 values)
:param is_integer_instance: True if we want the powed moment values to be integer
:param seed: seed used for generating the instance. -1 means no seed (instance is random)
:return: a dataset of '#size' 4-moment portfolio instances randomly generated using the parameters
"""
dataset = []
for i in range(size):
new_instance = Portfolio.generate_random_instance(n_item=n_item, lb=lb, ub=ub,
capacity_ratio=capacity_ratio,
moment_factors=moment_factors,
is_integer_instance=is_integer_instance,
seed=seed)
dataset.append(new_instance)
seed += 1
return dataset |
5391c451c33726ceb1f9b64f9d369f8e1a14815f | 654060747/Reptile_pbs | /pbs-master/app/haicj/test.py | 467 | 3.59375 | 4 | import codecs
# 写 csv
def write_csv(data):
file = "a.csv"
with codecs.open(file,'a',encoding='utf-8') as f:
f.write(data+"\n")
f.close()
string = "(大众 帕萨特 1.8T 手动 舒适版 2005款)"
data = string.split("(")[1].split(")")[0].split(" ")
print("品牌::"+data[0])
print("车系::"+data[1])
cx_all = ""
for x in range(2,len(data)):
cx = data[x]
cx_all = cx_all+cx+" "
print("型号::"+cx_all)
data = data[0]+","+data[1]+","+cx_all
|
41fdc8a89fb3e7ecdcfaec78e5c668fc0e6e4e80 | JoshuaShin/A01056181_1510_assignments | /A1/random_game.py | 2,173 | 4.28125 | 4 | """
random_game.py.
Play a game of rock paper scissors with the computer.
"""
# Joshua Shin
# A01056181
# Jan 25 2019
import doctest
import random
def computer_choice_translator(choice_computer):
"""
Translate computer choice (int between 0 - 2 inclusive) to "rock", "paper", or "scissors".
PARAM choice_computer int between 0 - 2
PRE-CONDITION choice_computer must be int between 0 - 2
POST-CONDITION translate computer choice to "rock", "paper", or "scissors"
RETURN return computer choice in "rock", "paper", or "scissors"
>>> computer_choice_translator(0)
'rock'
>>> computer_choice_translator(1)
'paper'
>>> computer_choice_translator(2)
'scissors'
"""
if choice_computer == 0:
return "rock"
elif choice_computer == 1:
return "paper"
else: # choice_computer == 2
return "scissors"
def rock_paper_scissors():
"""
Play a game of rock paper scissors with the computer.
"""
choice_computer = computer_choice_translator(random.randint(0, 2))
choice_player = input("Ready? Rock, paper, scissors!: ").strip().lower()
if not(choice_player == "rock" or choice_player == "paper" or choice_player == "scissors"):
print("Dont you know how to play rock paper scissors, ya loser!")
rock_paper_scissors()
return
print("Computer played:", choice_computer)
print("You played:", choice_player)
if choice_player == choice_computer:
print("TIED")
elif choice_player == "rock":
if choice_computer == "paper":
print("YOU LOSE")
elif choice_computer == "scissors":
print("YOU WIN")
elif choice_player == "paper":
if choice_computer == "scissors":
print("YOU LOSE")
elif choice_computer == "rock":
print("YOU WIN")
elif choice_player == "scissors":
if choice_computer == "rock":
print("YOU LOSE")
elif choice_computer == "paper":
print("YOU WIN")
def main():
"""
Drive the program.
"""
doctest.testmod()
rock_paper_scissors()
if __name__ == "__main__":
main()
|
20236a7f08ab85afc1f6195e470c80b78cf65365 | JoshuaShin/A01056181_1510_assignments | /A5/q02.py | 644 | 3.8125 | 4 | """
q02.py
Calculate greatest common divisor between two numbers.
"""
# Joshua Shin
# A01056181
# April 9th 2019
import doctest
def gcd(a: int, b: int) -> int:
"""
Calculate greatest common divisor.
PRE-CONDITION a must not be 0
PRE-CONDITION b must not be 0
RETURN greatest common divisor between a and b
>>> gcd(4, 12)
4
>>> gcd(4, -12)
4
>>> gcd(0, 12)
12
"""
if a == 0 and b == 0:
raise ValueError("Invalid Input.")
elif a % b == 0:
return abs(b)
else:
return gcd(b, (a % b))
def main():
doctest.testmod()
if __name__ == '__main__':
main()
|
5d14aa9005bb6f82e2309d3343ebbc5488589e35 | JoshuaShin/A01056181_1510_assignments | /A5/q01.py | 1,068 | 4.0625 | 4 | """
q01.py
Calculate the sum of all prime within given upper bound.
"""
# Joshua Shin
# A01056181
# April 15th 2019
import doctest
import math
def sum_of_primes(upperbound: int) -> int:
"""
Calculate the sum of all prime within given upper bound.
PRE-CONDITION upperbound must be larger than 0
RETURN sum of all prime within given upper bound
>>> sum_of_primes(1)
0
>>> sum_of_primes(10)
17
>>> sum_of_primes(100)
1060
"""
if upperbound < 1:
raise ValueError("Upperbound must be larger than 0.")
else:
prime = list(range(upperbound + 1))
for i in range(2, math.ceil(math.sqrt(upperbound + 1))):
if all(i % x for x in range(2, i)): # If prime
for j in range(i * 2, upperbound + 1, i):
prime[j] = 0
else:
for j in range(i, upperbound + 1, i):
prime[j] = 0
return sum(prime) - 1
def main():
doctest.testmod()
print(sum_of_primes(10))
if __name__ == '__main__':
main()
|
8de995f926ddb6ff14f587ff069eb391c12118d8 | JoshuaShin/A01056181_1510_assignments | /A1/lotto.py | 716 | 3.8125 | 4 | """
lotto.py.
Return length 6 unique sorted list of integers.
"""
# Joshua Shin
# A01056181
# Jan 25 2019
import random
def number_generator():
"""
Build length 6 unique sorted list of integers.
RETURN length 6 unique sorted integer list
"""
lotto_range = [1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
return sorted(random.sample(lotto_range, 6))
def main():
"""
Drive the program.
"""
print(number_generator())
if __name__ == "__main__":
main()
|
59830d6c27810a1c223eb12700126bd3edb6c65b | weiyinfu/learnTensorflow | /tensorflow_models/166-mnist-RNN.py | 4,114 | 4.15625 | 4 | """ Recurrent Neural Network.
最终精确度高达: 0.992188
A Recurrent Neural Network (LSTM) implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Links:
[Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)
[MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.nn import static_rnn
from tensorflow.nn.rnn_cell import BasicLSTMCell
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
learning_rate = 0.01
training_steps = 5000
batch_size = 128
display_step = 200
num_input = 28 # MNIST data input (img shape: 28*28)
timesteps = 28 # timesteps
num_hidden = 128 # hidden layer num of features
num_classes = 10 # MNIST total classes (0-9 digits)
X = tf.placeholder("float", [None, timesteps, num_input])
Y = tf.placeholder("float", [None, num_classes])
# 全连接层的权重,这里只有一层全连接
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, timesteps, n_input)
# Required shape: 'timesteps' tensors list of shape (batch_size, n_input)
# Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)
# x现在是(样本、时序、行)三维,需要改成(时序、样本、行)三维
# 也就是说在axis=1的方向上拆分,每隔timesteps拆分一个
x = tf.unstack(X, timesteps, axis=1) # 将一个一维数组拆分成多个数组
print('x type', type(x),x[0].shape) # x是一个张量列表
# Define a lstm cell with tensorflow
lstm_cell = BasicLSTMCell(num_hidden, forget_bias=1.0)
# Get lstm cell output
# 使用static_rnn,rnn长度不可变
outputs, states = static_rnn(lstm_cell, x, dtype=tf.float32)
print(outputs, states)
# 接上一个全连接
w = tf.Variable(tf.random_normal([num_hidden, num_classes]))
b = tf.Variable(tf.random_normal([num_classes]))
# Linear activation, using rnn inner loop last output
logits = tf.matmul(outputs[-1], w) + b
prediction = tf.nn.softmax(logits) # 这一步其实没有必要softmax
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
right_count_op = tf.reduce_sum(tf.cast(correct_pred, tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(training_steps):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Reshape data to get 28 seq of 28 elements
batch_x = batch_x.reshape((batch_size, timesteps, num_input))
sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
if step % display_step == 0:
# Calculate batch loss and accuracy
loss, acc = sess.run([loss_op, accuracy],
feed_dict={X: batch_x,
Y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
print("Optimization Finished!")
right_count = 0
for i in range(0, len(mnist.test.images), batch_size):
test_data = mnist.test.images[i:i + batch_size].reshape((-1, timesteps, num_input))
test_label = mnist.test.labels[i:i + batch_size]
now_right = sess.run(right_count_op, feed_dict={
X: test_data, Y: test_label
})
right_count += now_right
print("accuracy", right_count / len(mnist.test.images))
|
8d35ef9ebbce00986a3b8d0a0e21ea752602b0b4 | gochman/advent_of_code_19 | /day10/day10.py | 2,339 | 3.734375 | 4 | import math
class BoardUtilities:
def __init__(self):
with open(r"C:\Yoav's Disk\AdventOfCode\2019\day10\input.txt") as f:
self.raw_content = f.readlines()
self.raw_content = [x.strip() for x in self.raw_content]
self._board = []
for line in self.raw_content:
self._board.append(list(line))
def generate_board(self):
return self._board
def pretty_print(self):
for line in self._board:
for c in line:
print(c, end=" ")
print("")
def create_asteroids_list(board):
asteroids = [] # list of tuples
for i in range(len(board[0])):
for j in range(len(board)):
if board[i][j] == '#':
asteroids.append((i,j))
return asteroids
# def slope(a,b):
# if b[0] == a[0]:
# return math.inf
# return float((b[0] - a[0]) / (b[1] - a[1]))
def distance(a,b):
return math.hypot(b[0] - a[0], b[1] - a[1])
def all_points_between(asteroids, asteroid,suspect):
line_between = []
for betweener in asteroids:
if betweener == asteroid or betweener == suspect:
continue
if distance(asteroid, suspect) == distance(asteroid, betweener) + distance(betweener, suspect):
line_between.append(betweener)
return line_between
def is_line_clear(line,board):
clear = True
for point in line:
if board[point[0]][point[1]] == "#":
return False
return True
def main():
my_utilities = BoardUtilities()
board = my_utilities.generate_board()
asteroids = create_asteroids_list(board)
asteroids_friends_map = {k: 0 for k in asteroids} # friend means they are visible for each other
for asteroid in asteroids:
for suspect in asteroids:
if asteroid == suspect:
continue
line_between = all_points_between(asteroids, asteroid, suspect) # run time might be a problem double computation
if is_line_clear(line_between,board):
asteroids_friends_map[asteroid] += 1
result = max(asteroids_friends_map,key=asteroids_friends_map.get)
print("Result is asteroid at:", result[1],",",result[0], " With detected asteroids:", asteroids_friends_map[result])
if __name__ == "__main__":
main()
|
768ccca94902952995f3b0631707aef4cd45a554 | kory0005/python-lab-9 | /task2.py | 344 | 3.796875 | 4 | import csv
fileName = input('Enter a file name: ')
def readTextFile(name):
fin = open(name, "r")
lc = 1
moveOn = 1
while (moveOn == 1):
for line in fin:
c = line[-1]
# print(line)
print(list(line))
moveOn = 0
lc = lc + 1
fin.close()
readTextFile(fileName) |
22899b8f8a909a0ea2abd444750a4a00ea4dcbc9 | gusrochab/data-structure-algorithms | /Data Structures/Blockchain/linked_list.py | 1,691 | 3.96875 | 4 | from node import Node
class Linked_list():
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return out_string
def append(self, value):
if self.head == None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def size(self):
if not self.head:
return 0
size = 0
node = self.head
while node:
size +=1
node = node.next
return size
# retorna a união de duas listas
def union(self, other_list):
union_list = Linked_list()
node = self.head
# adiciona os nós da primeira lista
while node:
union_list.append(node.value)
node = node.next
# adiciona os nós da segunda lista
node = other_list.head
while node:
union_list.append(node.value)
node = node.next
return union_list
#retorna a interseção de duas listas
def intersection(self, other_list):
intersection_list = Linked_list()
other_node = other_list.head
while other_node:
node = self.head
while node:
if other_node.value == node.value:
intersection_list.append(other_node.value)
break
node = node.next
other_node = other_node.next
return intersection_list
|
b5ac4abea44139ef6c10455d5a558046f2d1b2e9 | slowmoh/urban_samples | /python/progress_bar/progress_bar.py | 935 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 20 20:33:09 2016
@author: Ben
Just a simple attempt to get a progress bar
"""
import time
import sys
def progress(curr, end):
sys.stdout.write("\rDoing thing " + str(curr) + " out of " + str(end))
sys.stdout.flush()
sys.stdout.write("\rDoing thing ")
sys.stdout.flush()
def progressBar(value, endvalue, bar_length=50):
percent = float(value) / endvalue
arrow = '#' * int(round(percent * bar_length))
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write("\rItem " + str(value) + " out of " + str(endvalue) +"|| Progress: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))))
sys.stdout.flush()
def testBar():
print("hello World")
size = 500
i = 1
for i in range(size):
progressBar(i, size-1)
time.sleep(0.3)
# uncomment testBar() to run a function
testBar()
|
e42ebaa9bded8df2b661ea483ac1aa1ab06ef84c | rdnaskelAvoramoK/homework | /home work#2/fizz_buzz.py | 426 | 3.78125 | 4 | print('input fizz number')
fizz = int(input())
print('input buzz number')
buzz = int(input())
print('input last number for calculation')
num = int(input())
list_f_z=""
for i in range(1, num+1):
if not i%fizz and i%buzz:
list_f_z += "F "
elif not i%buzz and i%fizz:
list_f_z += "B "
elif not i%buzz and not i%fizz:
list_f_z += "FB "
else:
list_f_z += str(i) + " "
print(list_f_z) |
57208923bf8ae03a9e6f32aaab9caa47efe1b531 | rdnaskelAvoramoK/homework | /home_work#30/score.py | 3,120 | 3.625 | 4 | class Product:
def __init__(self, name, cost, discount=20.0):
self.name = name
self.cost = cost
self.discount = discount
def discount_off(self):
discount = ((100 - self.discount) / 100)
return discount
def price_off(self):
return self.cost
class VipProduct(Product):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def discount_off(self):
return 1
class Warehouse(Product):
def __init__(self, name, cost, number=0):
super().__init__(name, cost)
self.__number = number
@property
def get_number(self):
return self.__number
@get_number.setter
def get_number(self, number):
if self.is_number(number):
self.__number += number
@staticmethod
def is_number(str):
try:
float(str)
return True
except ValueError:
print("value is not correct")
return False
class Bayer:
def __init__(self, name, budget):
self.name = name
self.budget = budget
@classmethod
def get_discount_cost(cls, prod):
return prod.price_off()
def calculator(self, prod):
qnt = self.budget // self.get_discount_cost(prod)
return qnt
def market(self, **products):
for key, num in products:
try:
if isinstance(key, Warehouse):
float(num)
else:
print("this item is not in warehouse")
except SyntaxError:
print("SyntaxError in entered data")
else:
key.get_number = - num
self.budget -= self.get_discount_cost(key) * num
class VipBayer(Bayer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@classmethod
def get_discount_cost(cls, prod):
return prod.discount_off() * prod.price_off()
def calculator(self, prod):
if isinstance(prod, VipProduct):
return super().calculator(prod)
qnt = self.budget // self.get_discount_cost(prod)
return qnt
class SuperVipBuyer(VipBayer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@classmethod
def get_discount_cost(cls, prod):
return super().get_discount_cost(prod) * prod.discount_off()
bread = Product("bread", 100, 50)
milk = Product("milk", 0.82, 10)
rice = Product("rice", 3.86, 0.5)
eggs = Product("eggs", 2.27)
tomato = Product("tomato", 4.04, 12)
oranges = VipProduct("oranges", 3.99)
#print('{:.2f}'.format(bread.price_off()))
bayer1 = Bayer("Petr1", 100)
bayer2 = VipBayer("Adam", 100)
bayer3 = SuperVipBuyer("Luke", 100)
# print(bayer1.calculator(milk))
# print(bayer2.calculator(milk))
# print(bayer3.calculator(milk))
warehouse_bread = Warehouse(bread, 5)
warehouse_tomato = Warehouse(tomato, 20)
warehouse_bread.get_number = 77
print(warehouse_bread.get_number)
|
302e6783e89ddf03693dd26f1ebef042e60610a5 | DlyanRutter/play-pig | /pig_game.py | 8,676 | 3.6875 | 4 | from functools import update_wrapper
from collections import defaultdict
import random
import math
def decorator(d):
"Make function d a decorator: d wraps a function fn."
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
@decorator
def memo(f):
"""Decorator that caches the return value for each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(args)
return _f
goal = 40
other = {1:0, 0:1}
def hold(state):
"""Apply the hold action to a state to yield a new state:
Reap the 'pending' points and it becomes the other player's turn.
p refers to the player whose turn it is"""
(p, me, you, pending) = state
return (other[p], you, me+pending, 0)
def roll(state, d):
"""Apply the roll action to a state (and a die roll d) to yield a new state:
If d is 1, get 1 point (losing any accumulated 'pending' points),
and it is the other player's turn. If d > 1, add d to 'pending' points."""
(p, me, you, pending) = state
if d == 1:
return (other[p], you, me+1, 0) # pig out; other player's turn
else:
return (p, me, you, pending+d) # accumulate die roll in pending
def clueless(state):
"A strategy that ignores the state and chooses at random from possible moves."
return random.choice(possible_moves)
def hold_at(x):
"""Return a strategy that holds if and only if
pending >= x or player reaches goal."""
def strategy(state):
p, me, you, pending = state
return 'hold' if pending >= x or me + pending >= goal else 'roll'
strategy.__name__ = 'hold_at(%d)' % x
return strategy
goal = 50
def dierolls():
"Generate die rolls."
while True:
yield random.randint(1, 6)
def play_pig(A, B, dierolls=dierolls()):
"""Play a game of pig between two players, represented by their strategies.
Each time through the main loop we ask the current player for one decision,
which must be 'hold' or 'roll', and we update the state accordingly.
When one player's score exceeds the goal, return that player."""
strategies = [A, B]
state = (0, 0, 0, 0)
while True:
p, me, you, pending = state
if me >= goal:
return strategies[p]
elif you >= goal:
return strategies[other[p]]
elif strategies[p](state) == 'hold':
state = hold(state)
else:
action = strategies[p](state)
if action == 'hold':
state = hold(state)
elif action == 'roll':
state = roll(state, next(dierolls))
else:
return strategies[other[p]]
million = 1000000
def quality(state, action, utility):
"The expected value of taking action in state, according to utility U."
if action == 'hold':
return utility(state + 1*million)
if action == 'gamble':
return utility(state + 3*million) * .5 + utility(state) * .5
def actions(state): return ['hold', 'gamble']
def identity(x): return x
U = math.log
def best_action(state, actions, Q, U):
"Return the optimal action for a state, given utility."
def EU(action): return Q(state, action, U)
return max(actions(state), key=EU)
def Q_pig(state, action, Pwin):
"""The expected value of choosing action in state. Pwin is porobability of
winning. If you win every time, the value would be 1. Pwin(hold(state)) in
second line refers to opponent's probability of winning. That means our
probability is 1 - that value. Top line in second return statement means that if
you roll 1, then your pobability is the same as holding"""
if action == 'hold':
return 1 - Pwin(hold(state))
if action == 'roll':
return (1 - Pwin(roll(state, 1))
+ sum(Pwin(roll(state, d)) for d in (2,3,4,5,6))) / 6.
raise ValueError
goal = 40
@memo
def Pwin(state):
"""The utility of a state; here just the probability that an optimal player
whose turn it is to move can win from the current state."""
# Assumes opponent also plays with optimal strategy.
(p, me, you, pending) = state
if me + pending >= goal:
return 1
elif you >= goal:
return 0
else:
return max(Q_pig(state, action, Pwin)
for action in pig_actions(state))
def max_wins(state):
"The optimal pig strategy chooses an action with the highest win probability."
return best_action(state, pig_actions, Q_pig, Pwin)
def pig_actions(state):
"The legal actions from a state."
_, _, _, pending = state
return ['roll', 'hold'] if pending else ['roll']
@memo
def win_diff(state):
"""The utility of a state: here the winning differential (pos or neg).
Tells you difference in score after the game is over"""
(p, me, you, pending) = state
if me + pending >= goal or you >= goal:
return (me + pending - you)
else:
return max(Q_pig(state, action, win_diff)
for action in pig_actions(state))
def max_diffs(state):
"""A strategy that maximizes the expected difference between my final score
and my opponent's"""
return best_action(state, pig_actions, Q_pig, win_diff)
goal = 40
states = [(0, me, you, pending)
for me in range(41) for you in range(41) for pending in range(41)
if me + pending <= goal]
r = defaultdict(int)
for s in states: r[max_wins(s), max_diffs(s)] += 1
print dict(r)
def story():
"""For all the states, group the states in terms of # of pending points in that
state and for each number of pending points find how many times max_wins decided
to roll vs how many times max_diffs rolls. Only consider times they differ."""
r = defaultdict(lambda: [0, 0])
for s in states:
w, d = max_wins(s), max_diffs(s)
if w != d:
_, _, _, pending = s
i = 0 if (w == 'roll') else 1
r[pending][i] += 1
for (delta, (wrolls, drolls)) in sorted(r.items()):
print '%4d: %3d %3d' % (delta, wrolls, drolls)
def test_hold_at():
assert hold_at(30)((1, 29, 15, 20)) == 'roll'
assert hold_at(30)((1, 29, 15, 21)) == 'hold'
assert hold_at(15)((0, 2, 30, 10)) == 'roll'
assert hold_at(15)((0, 2, 30, 15)) == 'hold'
return 'tests pass'
def test_hold_and_roll():
assert hold((1, 10, 20, 7)) == (0, 20, 17, 0)
assert hold((0, 5, 15, 10)) == (1, 15, 15, 0)
assert roll((1, 10, 20, 7), 1) == (0, 20, 11, 0)
assert roll((0, 5, 15, 10), 5) == (0, 5, 15, 15)
return 'tests pass'
def test_play_pig():
A, B = hold_at(50), clueless
rolls = iter([6,6,6,6,6,6,6,6,2])
assert play_pig(A, B, rolls) == A
return 'test passes'
def test_max_wins():
assert(max_wins((1, 5, 34, 4))) == "roll"
assert(max_wins((1, 18, 27, 8))) == "roll"
assert(max_wins((0, 23, 8, 8))) == "roll"
assert(max_wins((0, 31, 22, 9))) == "hold"
assert(max_wins((1, 11, 13, 21))) == "roll"
assert(max_wins((1, 33, 16, 6))) == "roll"
assert(max_wins((1, 12, 17, 27))) == "roll"
assert(max_wins((1, 9, 32, 5))) == "roll"
assert(max_wins((0, 28, 27, 5))) == "roll"
assert(max_wins((1, 7, 26, 34))) == "hold"
assert(max_wins((1, 20, 29, 17))) == "roll"
assert(max_wins((0, 34, 23, 7))) == "hold"
assert(max_wins((0, 30, 23, 11))) == "hold"
assert(max_wins((0, 22, 36, 6))) == "roll"
assert(max_wins((0, 21, 38, 12))) == "roll"
assert(max_wins((0, 1, 13, 21))) == "roll"
assert(max_wins((0, 11, 25, 14))) == "roll"
assert(max_wins((0, 22, 4, 7))) == "roll"
assert(max_wins((1, 28, 3, 2))) == "roll"
assert(max_wins((0, 11, 0, 24))) == "roll"
return 'tests pass'
def test_win_diffs():
assert(max_diffs((0, 36, 32, 5))) == "roll"
assert(max_diffs((1, 37, 16, 3))) == "roll"
assert(max_diffs((1, 33, 39, 7))) == "roll"
assert(max_diffs((0, 7, 9, 18))) == "hold"
assert(max_diffs((1, 0, 35, 35))) == "hold"
assert(max_diffs((0, 36, 7, 4))) == "roll"
assert(max_diffs((1, 5, 12, 21))) == "hold"
assert(max_diffs((0, 3, 13, 27))) == "hold"
assert(max_diffs((0, 0, 39, 37))) == "hold"
return 'tests pass'
print test_hold_and_roll()
#print test_hold_at()
print test_max_wins()
print test_win_diffs()
print (max_wins((0, 11, 0, 24)))
|
0ca8c1dc04f5e98a3d08b588e2a4c5903e7f61da | amit-kr-debug/CP | /Geeks for geeks/Heap/Sorting Elements of an Array by Frequency.py | 2,697 | 4.125 | 4 | """
Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher
frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases
follows. The first line of each test case contains a single integer N denoting the size of array. The second line
contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be
seperated by space.
Constraints:
1 ≤ T ≤ 70
30 ≤ N ≤ 130
1 ≤ Ai ≤ 60
Example:
Input:
2
5
5 5 4 6 4
5
9 9 9 2 5
Output:
4 4 5 5 6
9 9 9 2 5
Explanation:
Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then
smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6.
The output is 4 4 5 5 6.
Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 9 9 9 comes first. Now both 2
and 5 have same frequency. So we print smaller element first.
The output is 9 9 9 2 5
"""
"""
tCases = int(input())
for _ in range(tCases):
n = int(input())
arr = list(map(int, input().split()))
freq = {}
for i in arr:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
nDict = {}
for key, val in sorted(freq.items(), key = lambda kv:(kv[1], kv[0]), reverse=True):
# print(key, val)
if val not in nDict:
nDict.update({val: [key]})
else:
nDict[val].append(key)
for key, val in nDict.items():
val.sort()
for i in val:
for j in range(key):
print(i, end=" ")
print()
"""
# solution without heap in O(n*logn), first find freq of each element and make a new dict with value as key
# and values of that dict will be arr with that freq then sort each value and print it.
tCases = int(input())
for _ in range(tCases):
n = int(input())
arr = list(map(int, input().split()))
freq = {}
for i in arr:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
nDict = {}
for key, val in freq.items():
if val not in nDict:
nDict.update({val: [key]})
else:
nDict[val].append(key)
for key, val in sorted(nDict.items(), key=lambda kv: (kv[0], kv[1]), reverse=True):
val.sort()
for i in val:
for j in range(key):
print(i, end=" ")
print() |
b264b3ddb04fef9d689949fae125b00c8b3d6a9d | amit-kr-debug/CP | /Geeks for geeks/Dynamic Programming/Target sum.py | 1,788 | 4 | 4 | """
Count the number of subset with a given difference -- similar
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For
each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
Constraints:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
"""
class Solution:
def findTargetSumWays(self, nums: list, S: int) -> int:
TS = sum(nums)
if TS >= S:
nums.sort(reverse=True)
N = len(nums)
# print(TS)
if (TS+S)%2 == 0:
S = (TS + S)//2
dp = [[0 for x in range(S+1)] for y in range(N+1)]
# print(dp)
for i in range(N+1):
dp[i][0] = 1
for i in range(1, N+1):
for j in range(S+1):
if nums[i-1] <= j:
dp[i][j] = dp[i-1][j-nums[i-1]] + dp[i-1][j]
else:
dp[i][j] = dp[i-1][j]
return dp[N][S]
else:
return 0
else:
return 0
ob = Solution()
a = ob.findTargetSumWays([7,9,3,8,0,2,4,8,3,9], 0)
# a = ob.findTargetSumWays([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 0)
# a = ob.findTargetSumWays([1,1,1,1,1],3)
print(a) |
25250f8b7d247e2657b1e99ced5bdc0cee48a521 | amit-kr-debug/CP | /Geeks for geeks/array/Missing number in array.py | 1,195 | 3.78125 | 4 | """
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number
is to be found.
Input:
The first line of input contains an integer T denoting the number of test cases. For each test case first line contains
N(size of array). The subsequent line contains N-1 array elements.
Output:
Print the missing number in array.
Constraints:
1 ≤ T ≤ 200
1 ≤ N ≤ 107
1 ≤ C[i] ≤ 107
Example:
Input:
2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10
Output:
4
9
Explanation:
Testcase 1: Given array : 1 2 3 5. Missing element is 4.
"""
"""
# if the array is sorted
tCases = 1
for _ in range(tCases):
n = int(input())
arr = list(map(int, input().split()))
low = 0
high = n-2
if n > 2:
count = 0
while low < high:
# print(low, high)
# print(arr[low], arr[high])
mid = (low + high) // 2
if arr[mid] == mid+1:
low = mid+1
elif arr[mid] > mid+1:
high = mid
print(low+1)
elif n == 2:
if arr[0] == 1:
print(2)
elif arr[0] == 2:
print(1)
elif n == 1:
print(1)
"""
|
b88aa4030ca4dc30cd8c22d41e48ea48d7e162ea | amit-kr-debug/CP | /Geeks for geeks/array/Longest consecutive subsequence.py | 1,151 | 3.9375 | 4 | """
Given an array arr[] of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.
Input:
The first line of input contains T, number of test cases. First line of line each test case contains a single integer N.
Next line contains N integer array.
Output:
Print the output of each test case in a seprate line.
Constraints:
1 <= T <= 100
1 <= N <= 105
0 <= a[i] <= 105
Example:
Input:
2
7
2 6 1 9 4 5 3
7
1 9 3 10 4 20 2
Output:
6
4
Explanation:
Testcase 1: The consecutive numbers here are 1, 2, 3, 4, 5, 6. These 6 numbers form the longest consecutive subsquence.
Testcase2: 1, 2, 3, 4 is the longest consecutive subsequence.
"""
tCases = int(input())
for _ in range(tCases):
n = int(input())
arr = list(set(map(int, input().split())))
arr.sort()
count = 1
ans = 1
if n > 1:
for i in range(1, len(arr)):
if arr[i]-arr[i-1] == 1:
count += 1
else:
ans = max(ans, count)
count = 1
ans = max(ans, count)
print(ans)
|
aabfac917714563c628ac6b39c2c5b9cf730a99c | amit-kr-debug/CP | /LeetCode/Merge Intervals.py | 1,009 | 4.03125 | 4 | """
56. Merge Intervals
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
"""
class Solution:
def merge(self, intervals: list[list[int]]) -> list:
intervals.sort()
ans = [intervals[0]]
for i in range(1, len(intervals)):
if intervals[i][0] <= ans[len(ans) - 1][1]:
ans[len(ans) - 1][1] = max(ans[len(ans) - 1][1], intervals[i][1])
else:
ans.append(intervals[i])
return ans
|
f759b9ed999d0c0f7d984132db84587ef7df0044 | amit-kr-debug/CP | /Geeks for geeks/array/Median In a Row-Wise sorted Matrix.py | 764 | 3.796875 | 4 | """
We are given a row wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains two integers r and c, where r is the number of rows and c is the number of columns in the array a[]. Next r line contains space separated c elements each in the array a[].
Output:
Print an integer which is the median of the matrix.
Constraints:
1<= T <=100
1<= r,c <=150
1<= a[i][j] <=1000
Example:
Input:
1
3 3
1 3 5
2 6 9
3 6 9
Output:
5
"""
tCases = int(input())
for _ in range(tCases):
m, n = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
print(l[(n*m//2)]) |
f83e2beb26b7d9a8652d5c6fac6efb6b62248bdd | amit-kr-debug/CP | /CodeChef/june challenge - 2020/The Tom and Jerry Game! - EOEO.py | 2,018 | 3.59375 | 4 | """
As usual, Tom and Jerry are fighting. Tom has strength TS and Jerry has strength JS. You are given TS and your task is
to find the number of possible values of JS such that Jerry wins the following game.
The game consists of one or more turns. In each turn:
If both TS and JS are even, their values get divided by 2 and the game proceeds with the next turn.
If both TS and JS are odd, a tie is declared and the game ends.
If TS is even and JS is odd, Tom wins the game.
If TS is odd and JS is even, Jerry wins the game.
Find the number of possible initial values of JS such that 1≤JS≤TS, there is no tie and Jerry wins the game.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test
cases follows.
The first and only line of each test case contains a single integer TS.
Output
For each test case, print a single line containing one integer ― the number of values of JS such that Jerry wins the
game.
Constraints
1≤T≤105
1≤TS≤1018
Subtasks
Subtask #1 (20 points): T,TS≤100
Subtask #2 (80 points): original constraints
Example Input
2
1
11
Example Output
0
5
Explanation
Example case 1: We must have JS=TS=1, but in this case, the game ends and a tie is declared in the first turn.
Example case 2: If JS∈{2,4,6,8,10}, then JS is even and TS is odd, so Jerry wins the game in the first turn. Any odd
value of JS leads to a tie instead.
"""
tCases = int(input())
for _ in range(tCases):
TS = int(input())
if TS % 2 != 0:
print(int(TS//2))
else:
while TS % 2 == 0:
TS //= 2
print(int(TS//2))
"""
Explanatory Solution
tCases = int(input())
for _ in range(tCases):
TS = int(input())
if TS % 2 != 0:
print(int(TS//2))
else:
count = 1
TSO = TS
while TS % 2 == 0:
# used floor division because of python handling with bigger numbers are weird
TS //= 2
count += 1
print(int(TSO//2**count))
"""
|
e2fb43f0392cd69430a3604c6ddcf3b06425b671 | amit-kr-debug/CP | /Geeks for geeks/array/sorting 0 1 2.py | 1,329 | 4.1875 | 4 | """
Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.
Example 1:
Input:
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated
into ascending order.
Example 2:
Input:
N = 3
arr[] = {0 1 0}
Output:
0 0 1
Explanation:
0s 1s and 2s are segregated
into ascending order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr
and N as input parameters and sorts the array in-place.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 10^6
0 <= A[i] <= 2
"""
# User function Template for python3
class Solution:
def sort012(self,arr,n):
# code here
d = {0: 0,1: 0,2: 0}
index = 0
for i in range(n):
d[arr[i]] += 1
for key,val in d.items():
for i in range(val):
arr[index] = key
index += 1
# {
# Driver Code Starts
# Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
arr = [int(x) for x in input().strip().split()]
ob = Solution()
ob.sort012(arr,n)
for i in arr:
print(i,end = ' ')
print()
# } Driver Code Ends |
eaa50f1a239748e42e38ac0cb9eabe99784c126f | amit-kr-debug/CP | /RobinHood/infytq.py | 750 | 3.609375 | 4 | # cook your dish here
def check(n1):
return n1 == n1[::-1]
def getsum(num):
n1 = int(num)
flag = 1
numgr = 100000000000
numsm = 0
while flag == 1: # for finding palindrome greater than the num
if check(str(n1 + 1)):
flag = 0
numgr = n1 + 1
break
n1 += 1
n1 = int(num)
flag = 1
while flag == 1 and n1 >= 0: # for finding palindrome smaller than the num
if check(str(n1 - 1)):
flag = 0
numsm = n1 - 1
break
n1 -= 1
print(numsm, numgr)
return numsm + numgr
num = 464554545445
while check(str(getsum(num))) == False and num >= 0:
print(getsum(num))
num -= 1
sum1 = getsum(num)
print(sum1)
|
6069283e9388e6d1704f649d14b84e4a288f8d86 | amit-kr-debug/CP | /Cryptography and network security/lab - 2/Vigenere Cipher encrypt.py | 669 | 4.21875 | 4 | def encrypt(plain_text, key):
cipher_text = ""
# Encrypting plain text
for i in range(len(plain_text)):
cipher_text += chr(((ord(plain_text[i]) + ord(key[i]) - 130) % 26) + 65)
return cipher_text
if __name__ == "__main__":
# Taking key as input
key = input("Enter the key:")
# Taking plain text as input
plain_text = input("Enter the plain text:")
count = 0
key_updated = ""
# Updating Key
for _ in plain_text:
if count == len(key):
count = 0
key_updated += key[count]
count += 1
print("Cipher text:",end = "")
print(encrypt(plain_text.upper(),key_updated.upper()))
|
4d24ec86497d6380887a56b5093e4c7da184a4c7 | amit-kr-debug/CP | /Geeks for geeks/Tree/Preorder Traversal.py | 3,072 | 4.21875 | 4 | """
Given a binary tree, find its preorder traversal.
Example 1:
Input:
1
/
4
/ \
4 2
Output: 1 4 4 2
Example 2:
Input:
6
/ \
3 2
\ /
1 2
Output: 6 3 1 2 2
Your Task:
You just have to complete the function preorder() which takes the root node of the tree as input and returns an array
containing the preorder traversal of the tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 104
1 <= Data of a node <= 105
"""
# User function Template for python3
'''
# Node Class:
class Node:
def _init_(self,val):
self.data = val
self.left = None
self.right = None
'''
def traverse(root, l):
if root is not None:
l.append (root.data)
traverse (root.left,l)
traverse (root.right,l)
return l
def preorder(root):
'''
:param root: root of the given tree.
:return: a list containing pre order Traversal of the given tree.
{
class Node:
def _init_(self,val):
self.data = val
self.left = None
self.right = None
}
'''
arr = traverse (root,[])
return arr
# code here
# {
# Driver Code Starts
from collections import deque
# Tree Node
class Node:
def __init__(self,val):
self.right = None
self.data = val
self.left = None
# Function to Build Tree
def buildTree(s):
# Corner Case
if (len (s) == 0 or s[0] == "N"):
return None
# Creating list of strings from input
# string after spliting by space
ip = list (map (str,s.split ()))
# Create the root of the tree
root = Node (int (ip[0]))
size = 0
q = deque ()
# Push the root to the queue
q.append (root)
size = size + 1
# Starting from the second element
i = 1
while (size > 0 and i < len (ip)):
# Get and remove the front of the queue
currNode = q[0]
q.popleft ()
size = size - 1
# Get the current node's value from the string
currVal = ip[i]
# If the left child is not null
if (currVal != "N"):
# Create the left child for the current node
currNode.left = Node (int (currVal))
# Push it to the queue
q.append (currNode.left)
size = size + 1
# For the right child
i = i + 1
if (i >= len (ip)):
break
currVal = ip[i]
# If the right child is not null
if (currVal != "N"):
# Create the right child for the current node
currNode.right = Node (int (currVal))
# Push it to the queue
q.append (currNode.right)
size = size + 1
i = i + 1
return root
if __name__ == "__main__":
t = int (input ())
for _ in range (0,t):
s = input ()
root = buildTree (s)
res = preorder (root)
for i in res:
print (i,end=" ")
print ()
# } Driver Code Ends
|
027c6932e16cc43c2d81d5af1077547b489d2917 | amit-kr-debug/CP | /Geeks for geeks/array/Minimum element in a sorted and rotated array.py | 1,210 | 3.65625 | 4 | """
A sorted array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it.
Expected Time Complexity: O(Log n)
Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two lines. The first line of each test case consists of an integer N, where N is the size of array.
The second line of each test case contains N space separated integers denoting array elements.
Output:
Corresponding to each test case, in a new line, print the minimum element in the array.
Constraints:
1 ≤ T ≤ 200
1 ≤ N ≤ 500
1 ≤ A[i] ≤ 1000
Example:
Input
2
5
4 5 1 2 3
6
10 20 30 40 50 5 7
Output
1
5
"""
tCases = int(input())
for _ in range(tCases):
n = int(input())
arr = list(map(int, input().split()))
if arr[0] > arr[n-1]:
low = 0
high = n-1
while low < high:
mid = (low+high) // 2
# print(arr[low], arr[high], arr[mid])
if arr[low] > arr[mid] or arr[mid] < arr[high]:
high = mid
else:
low = mid+1
print(arr[low])
else:
print(arr[0]) |
3d6374a2d3a71afed34cc9d918829dc1f806ae50 | amit-kr-debug/CP | /LeetCode/15. 3Sum.py | 1,370 | 3.59375 | 4 | """
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
Constraints:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
"""
class Solution:
def threeSum(self,nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
ans = []
i = 0
while i < n - 2:
a = nums[i]
low = i + 1
high = n - 1
while low < high:
sumz = a + nums[low] + nums[high]
if sumz == 0:
temp = [a,nums[low],nums[high]]
ans.append(temp)
prevlow = nums[low]
prevhigh = nums[high]
while low < n and nums[low] == prevlow:
low += 1
while high > 0 and nums[high] == prevhigh:
high -= 1
elif sumz < 0:
low += 1
else:
high -= 1
while i < n and a == nums[i]:
i += 1
return ans
|
b8370b96f0b25819243c624e6c91dd0602af9200 | amit-kr-debug/CP | /Geeks for geeks/Dynamic Programming/Coin Change - maximum ways.py | 1,554 | 3.71875 | 4 | """
Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of
S = { S1, S2, .. , SM } valued coins.
Example 1:
Input:
n = 4 , m = 3
S[] = {1,2,3}
Output: 4
Explanation: Four Possible ways are:
{1,1,1,1},{1,1,2},{2,2},{1,3}.
Example 2:
Input:
n = 10 , m = 4
S[] ={2,5,3,6}
Output: 5
Explanation: Five Possible ways are:
{2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5}
and {5,5}.
Your Task:
You don't need to read input or print anything. Your task is to complete the function count() which accepts an array
S[] its size m and n as input parameter and returns the number of ways to make change for N cents.
Expected Time Complexity: O(m*n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n,m <= 103
"""
#User function Template for python3
#User function Template for python3
class Solution:
def count(self, S, m, n):
dp = [[0 for i in range(n+1)] for i in range(m+1)]
for i in range(m+1):
dp[i][0] = 1
for i in range(1, m+1):
for j in range(1, n+1):
if S[i-1] <= j:
dp[i][j] = dp[i][j-S[i-1]] + dp[i-1][j]
else:
dp[i][j] = dp[i-1][j]
return dp[m][n]
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n,m = list(map(int, input().strip().split()))
S = list(map(int, input().strip().split()))
ob = Solution()
print(ob.count(S,m,n))
# } Driver Code Ends |
c67c800a679c33ac609d50a2022bc8a31623502c | amit-kr-debug/CP | /RobinHood/advantage round infytq 1.py | 966 | 3.828125 | 4 | def mergeSlide(arr:list):
arr.sort()
print(arr)
countSequence = 0
tempSequence = 0
countRepeat = 0
tempRepeat = 0
flagRepeat = True
flagSequence = True
for i in range(1, len(arr)):
if arr[i-1] + 1 == arr[i]:
if flagRepeat:
tempRepeat = 0
flagRepeat = False
tempSequence += 1
tempSequence += 1
flagSequence = True
# print("s", arr[i], tempSequence)
if tempSequence >= 3:
countSequence += 1
if arr[i-1] == arr[i]:
if flagSequence:
tempSequence = 0
flagSequence = False
tempRepeat += 1
tempRepeat += 1
flagRepeat = True
# print("r", arr[i], tempRepeat)
if tempRepeat >= 3:
countRepeat += 1
return countRepeat+countSequence
print(mergeSlide([1,1,1,1,1,2,2,2,3,4,5])) |
4602c2628ae813e68f997f36b18d270316e42a43 | amit-kr-debug/CP | /hackerrank/Merge the Tools!.py | 1,835 | 4.25 | 4 | """
https://www.hackerrank.com/challenges/merge-the-tools/problem
Consider the following:
A string, , of length where .
An integer, , where is a factor of .
We can split into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string such that:
The characters in are a subsequence of the characters in .
Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string .
Given and , print lines where each line denotes string .
Input Format
The first line contains a single string denoting .
The second line contains an integer, , denoting the length of each subsegment.
Constraints
, where is the length of
It is guaranteed that is a multiple of .
Output Format
Print lines where each line contains string .
Sample Input
AABCAAADA
3
Sample Output
AB
CA
AD
Explanation
String is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in :
We then print each on a new line.
"""
def merge_the_tools(string, k):
import textwrap
s=string
n=k
lis=list(map(str,textwrap.wrap(s,n)))
for i in lis:
new=list(i[0])
for j in range(1,len(i)):
for k in range(len(new)):
if new[k] != i[j]:
flag = 0
else:
flag = 1
break
if flag == 0:
new.append(i[j])
for i in range(len(new)-1):
print(new[i],end="")
print(new[len(new)-1])
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k) |
024d73d02c3c36dd6d07e1ed80b1b1433fab8e6c | amit-kr-debug/CP | /CodeChef/august long challenge - 2020/Smallest KMP - SKMP.py | 2,824 | 3.875 | 4 | """
Chef has a string S. He also has another string P, called pattern. He wants to find the pattern in S, but that might be impossible. Therefore, he is willing to reorder the characters of S in such a way that P occurs in the resulting string (an anagram of S) as a substring.
Since this problem was too hard for Chef, he decided to ask you, his genius friend, for help. Can you find the lexicographically smallest anagram of S that contains P as substring?
Note: A string B is a substring of a string A if B can be obtained from A by deleting several (possibly none or all) characters from the beginning and several (possibly none or all) characters from the end.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single string S.
The second line contains a single string P.
Output
For each test case, print a single line containing one string ― the smallest anagram of S that contains P.
Constraints
1≤T≤10
1≤|P|≤|S|≤105
S and P contain only lowercase English letters
there is at least one anagram of S that contains P
Subtasks
Subtask #1 (20 points): |S|≤1,000
Subtask #2 (80 points): |S|≤105
Example Input
3
akramkeeanany
kaaaa
supahotboy
bohoty
daehabshatorawyz
badawy
Example Output
aaakaeekmnnry
abohotypsu
aabadawyehhorst
"""
"""
tCases = int(input())
for _ in range(tCases):
s = input()
p = input()
sDict = {}
for i in range(len(s)):
if s[i] in sDict:
sDict[s[i]] += 1
else:
sDict.update({s[i]: 1})
ans = ""
for i in range(len(p)):
sDict[p[i]] -= 1
left = ord(p[0])
for i in range(97, left+1):
if chr(i) in sDict:
r = sDict[chr(i)]
for j in range(r):
ans += chr(i)
sDict[chr(i)] = 0
ans += p
for i in range(left, 123):
if chr(i) in sDict:
r = sDict[chr(i)]
if r>0:
for j in range(r):
ans += chr(i)
print(ans)
"""
tCases = int(input())
for _ in range(tCases):
s = input()
p = input()
ans = ""
lis = ["" for i in range(26)]
for j in range(len(s)):
lis[ord(s[j])-97] += s[j]
for j in range(len(p)):
lis[ord(p[j])-97] = lis[ord(p[j])-97][:-1]
lis.append(p)
lis.sort()
# print(lis)
n = len(lis)
for i in range(n):
if lis[i] == p:
if i >= 1 and len(lis[i]) > 1:
x = lis[i-1][0]
o = 0
m = len(p)
while o < m and x == p[o]:
o += 1
if o < m and ord(x) > ord(p[o]):
lis[i-1], lis[i] = lis[i], lis[i-1]
for i in lis:
ans += i
print(ans) |
451bf94129d98c22c93c060d2f5e92d0f2522672 | amit-kr-debug/CP | /Geeks for geeks/Heap/k closest elements.py | 1,743 | 3.875 | 4 | """
Given a sorted array of numbers, value K and an index X in array, find the K closest numbers in position to X in array.
Example: Let array be 11 23 24 75 89, X be 24 and K be 2. Now we have to find K numbers closest to X that is 24. In this
example, 23 and 75 are the closest 2 numbers to 24.
Note: K should be even and in cases with less than k/2 elements on left side or right side, we need to print other side
elements. Like 2 4 5 6 7, X be 6 and K be 4 then answer is 2 4 5 7
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
The third line of each test case contains K and X.
Output:
Print K closest number in position to X in array.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ C[i] ≤ 1000
Example:
Input
1
5
2 11 23 24 25
3 11
Output
23 75
"""
tCases = int(input())
for _ in range(tCases):
n = int(input())
arr = list(map(int, input().split()))
k, x = map(int, input().split())
index = 0
for i in range(n):
if arr[i] == x:
index = i
if k/2 <= index and k/2 <= n-index-1:
# print(1)
for i in range(index-k//2, index):
print(arr[i], end=" ")
for i in range(index+1, index+k//2+1):
print(arr[i], end=" ")
elif k/2 >= index:
# print(2)
for i in range(0, index):
print(arr[i], end=" ")
for i in range(index + 1, k+1):
print(arr[i], end=" ")
else:
# print(3)
for i in range(n-k-1, index):
print(arr[i], end=" ")
for i in range(index + 1,n):
print(arr[i], end=" ") |
38ae00d04139fa2b0054828e80f26cfc02acedd6 | 1OSK/pigga | /дз/2.34.py | 208 | 3.921875 | 4 | V1=float(input("Скорость первого автомобиля "))
V2=float(input("Скорость второго автомобиля "))
S=float(input("Расстояние "))
V=V1+V2
T=S/V
print(T) |
57d8a30f08e8f538c8cfadc23a6674675636e6dd | 1OSK/pigga | /дз23.11.2020/4.py | 242 | 3.953125 | 4 | x = int(input("x"))
y = int(input("y"))
if x == 0 and y == 0:
print("лежит на обеих осях")
elif x > 0 and y > 0:
print("1")
elif x < 0 and y < 0:
print("3")
elif x > 0 and y < 0:
print("4")
else:
print("2") |
182c7263d4e5df5a42764515aaf5854cbacf841e | racterub/yzu_python | /python/static/exercise10/3.py | 943 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-12-12 10:28:51
# @Author : Racter Liu (racterub) (racterub@gmail.com)
# @Link : https://racterub.io
# @License : MIT
import csv
#建立空 list
def listCreate(n):
data = []
for i in range(n):
data.append([0])
return data
#從 2012/01/22 格式中取出年份
def getYear(n):
return int(n.strip().split("/")[0])
file = open("./a_Dengue_Daily_EN.csv")
reader = csv.DictReader(file)
result = listCreate(20) #拿來儲存答案
for row in reader:
if row["County_living"] == "Kaohsiung City":
year = getYear(row["Date_Onset"])
result[year-2000][0] += 1
print("Year num_cases")
for i in range(len(result)):
print("{:<8d}{:<d}".format(i+2000, result[i][0]))
file.close()
file = open("out.csv", "w")
writer = csv.writer(file)
writer.writerow(["Year", "num_cases"])
for i in range(len(result)):
writer.writerow([i+2000, result[i][0]]) |
94ca9916db1aa81a0d97231c319253e0ff55e198 | racterub/yzu_python | /python/static/exercise4/1.py | 424 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-10-23 18:49:22
# @Author : Racter Liu (racterub)
# @Mail : racterub@gmail.com
# @Link : https://racterub.io
# @License : MIT
from math import sqrt
for i in range(1, 1000001):
root = int(sqrt(i))
if (root*root == i):
data = i+268
root_new = int(sqrt(data))
if (root_new * root_new == data):
print(i, end=" ")
#輸出 4356 |
38a1d6273bd31c27b77d7497ddb8e7f1464424fe | racterub/yzu_python | /python/static/exercise4/2.py | 397 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-10-23 19:10:24
# @Author : Racter Liu (racterub)
# @Mail : racterub@gmail.com
# @Link : https://racterub.io
# @License : MIT
ROW = 10
print("Printing pattern C:")
for i in range(ROW):
print(' '*i, end='')
print('*'*( ROW-i))
print("Printing pattern D:")
for i in range(ROW):
print(' '*(ROW-i-1), end='')
print('*'*(i+1))
|
804aae6434be67922291464d7771417abe36f440 | racterub/yzu_python | /python/static/exercise2/1.py | 581 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-10-13 12:15:14
# @Author : Racterub (Racter Liu) (racterub@gmail.com)
# @Link : https://racterub.io
# @License : MIT
x = int(input('x: ')) #測資: 1
y = int(input('y: ')) #測資: 2
z = int(input('z: ')) #測資: 3
_avg = (x+y+z)/3
_min = x
if y < _min:
_min = y
if z < _min:
_min = z
_max = x
if x > z:
_max = x
else:
_max = z
elif z < _min:
_min = z
_max = y
else:
if y > z:
_max = y
else:
_max = z
print(_min, _avg, _max)
#輸出: 1, 2, 3 |
d5f87dda4e33427f9383d021d65a87d99d16c9d9 | racterub/yzu_python | /python/static/exercise5/2.py | 805 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-10-29 19:25:36
# @Author : Racter Liu (racterub)
# @Mail : racterub@gmail.com
# @Link : https://racterub.io
# @License : MIT
'''
IP 用點來分有四個部分,分別是 A class, B class, C class, D class,
A class 和 B class 指定要為 140.138
C class 和 D class 指定要 0 <= number <= 255
'''
ip = input("Input your IP: ")
#IP has 4 classes A.B.C.D
ip_segment = ip.split('.')
#Check if ip has 4 segments
if (len(ip_segment) == 4):
aclass, bclass, cclass, dclass = ip_segment
if (aclass == '140' or bclass == '138'):
if (0 <= int(cclass) <= 255 and 0 <= int(dclass) <= 255):
print("Valid IP")
else:
print("Invalid IP")
else:
print("Invalid IP")
else:
print("Invalid IP") |
f7ce9ae1f13ac6aa6012f85961bf778fc5378e1e | yirua/text_reading | /Module_functions.py | 991 | 4.09375 | 4 |
def check_line_length(lines):
check_col_is_7 = True
line_index = 1
for line in lines:
if (len(line) != 7):
check_col_is_7 = False
print "The line with not 7 columns: "
print "line_index {} : {}".format(line_index, line)
#else:
# print "The line with 7 columns: "
# print line
line_index += 1
return check_col_is_7
def allUnique(x):
seen = set()
return not any(i in seen or seen.add(i) for i in x)
#check if the elements in the list are all integers
def check_integers(aList):
check_int = True
for s in aList:
try:
int(s)
except ValueError:
check_int = False
return check_int
#get the number of certain string in a list
def check_num_string(list, input):
num_of_string =0
for line in list:
for s_str in line:
if (s_str == input):
num_of_string +=1
return num_of_string |
234be2c48ef43ab2a3734d31043818fcd846dcc4 | vishnu2914/Gramener-Product-Team | /Product team Solutions.py | 774 | 3.921875 | 4 |
# coding: utf-8
# # 1. Given two lists L1 = ['a', 'b', 'c'], L2 = ['b', 'd'], find common elements, find elements present in L1 and not in L2?
# In[ ]:
# Import numpy
import numpy as np
# In[2]:
L1 = ['a', 'b', 'c']
L2 = ['b', 'd']
# In[3]:
# Common_elements
common_elements = np.intersect1d(L1, L2)
# In[4]:
# Print common_elements
print(common_elements)
# In[5]:
# Elements in L1 and not in L2?
L1_elements = np.setdiff1d(L1,L2)
# In[6]:
# Print L1_elements
print(L1_elements)
# # 2. How many Thursdays were there between 1990 - 2000?
# In[8]:
# Import numpy
import numpy as np
# In[11]:
# Count num of Thursdays
num_thursdays = np.busday_count('1990', '2000', weekmask = 'Thu')
# In[12]:
# Print num_thursdays
print(num_thursdays)
|
49b757c7240082f56b8fdf0bb9ea301103a11633 | Queena-Zhq/leetcode_python | /53.maximum-subarray.py | 1,107 | 3.515625 | 4 | #
# @lc app=leetcode id=53 lang=python3
#
# [53] Maximum Subarray
#
# https://leetcode.com/problems/maximum-subarray/description/
#
# algorithms
# Easy (44.77%)
# Likes: 6927
# Dislikes: 318
# Total Accepted: 904.6K
# Total Submissions: 2M
# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
#
# Given an integer array nums, find the contiguous subarray (containing at
# least one number) which has the largest sum and return its sum.
#
# Example:
#
#
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
#
#
# Follow up:
#
# If you have figured out the O(n) solution, try coding another solution using
# the divide and conquer approach, which is more subtle.
#
#
# @lc code=start
class Solution:
def maxSubArray(self, nums: [int]) -> int:
my_max = 0
my_ans = nums[0]
for i in range(len(nums)):
my_max = max(nums[i],my_max+nums[i])
my_ans = max(my_max,my_ans)
return my_ans
# @lc code=end
if __name__ == "__main__":
test = Solution()
print(test.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
|
8449a17a67a84ac0f1bf5e6ddca5c9a56e006b2a | Queena-Zhq/leetcode_python | /49.group-anagrams.py | 1,135 | 3.75 | 4 | #
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# https://leetcode.com/problems/group-anagrams/description/
#
# algorithms
# Medium (49.87%)
# Likes: 3095
# Dislikes: 166
# Total Accepted: 621.5K
# Total Submissions: 1.1M
# Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
#
# 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.
#
#
#
# @lc code=start
class Solution:
def groupAnagrams(self, strs: [str]) -> [[str]]:
my_dict = {}
ans = []
for i in strs:
if str(sorted(i)) not in my_dict.keys():
my_dict[str(sorted(i))] = [i]
else:
my_dict[str(sorted(i))].append(i)
return list(my_dict.values())
# @lc code=end
if __name__ == "__main__":
Test = Solution()
print(Test.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
|
726fef0f48095d96d4f202b1b9e4e89f1791edd2 | Queena-Zhq/leetcode_python | /844.backspace-string-compare.py | 2,113 | 3.828125 | 4 | #
# @lc app=leetcode id=844 lang=python3
#
# [844] Backspace String Compare
#
# https://leetcode.com/problems/backspace-string-compare/description/
#
# algorithms
# Easy (46.67%)
# Likes: 1449
# Dislikes: 75
# Total Accepted: 189.4K
# Total Submissions: 407.4K
# Testcase Example: '"ab#c"\n"ad#c"'
#
# Given two strings S and T, return if they are equal when both are typed into
# empty text editors. # means a backspace character.
#
# Note that after backspacing an empty text, the text will continue empty.
#
#
# Example 1:
#
#
# Input: S = "ab#c", T = "ad#c"
# Output: true
# Explanation: Both S and T become "ac".
#
#
#
# Example 2:
#
#
# Input: S = "ab##", T = "c#d#"
# Output: true
# Explanation: Both S and T become "".
#
#
#
# Example 3:
#
#
# Input: S = "a##c", T = "#a#c"
# Output: true
# Explanation: Both S and T become "c".
#
#
#
# Example 4:
#
#
# Input: S = "a#c", T = "b"
# Output: false
# Explanation: S becomes "c" while T becomes "b".
#
#
# Note:
#
#
# 1 <= S.length <= 200
# 1 <= T.length <= 200
# S and T only contain lowercase letters and '#' characters.
#
#
# Follow up:
#
#
# Can you solve it in O(N) time and O(1) space?
#
#
#
#
#
#
#
# @lc code=start
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
str1 = self.tackle(S)
# print(str1)
str2 = self.tackle(T)
# print(str2)
if str1 == str2:
return True
else:
return False
def tackle(self,S: str):
list1 = list(S)
for i in range(len(list1)):
# print(list1)
if list1[i] == '#':
list1[i] = '0'
num = 1
j = 1
while i-j>-1 and num == 1:
if list1[i-j] != '0':
list1[i-j] = '0'
num = 0
j += 1
return [i for i in list1 if i != '0' ]
# @lc code=end
if __name__ == "__main__":
Test = Solution()
S = "y#fo##f"
T = "y#f#o##f"
print(Test.backspaceCompare(S,T))
|
297a485dbba01cb14a8849b5c8220f3059a0d0a0 | Queena-Zhq/leetcode_python | /107.binary-tree-level-order-traversal-ii.py | 1,957 | 4.03125 | 4 | #
# @lc app=leetcode id=107 lang=python3
#
# [107] Binary Tree Level Order Traversal II
#
# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
#
# algorithms
# Easy (51.00%)
# Likes: 1380
# Dislikes: 208
# Total Accepted: 324.9K
# Total Submissions: 621.1K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# Given a binary tree, return the bottom-up level order traversal of its nodes'
# values. (ie, from left to right, level by level from leaf to root).
#
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
#
# return its bottom-up level order traversal as:
#
# [
# [15,7],
# [9,20],
# [3]
# ]
#
#
#
# @lc code=start
# 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 levelOrderBottom(self, root: TreeNode) -> [[int]]:
if root:
next_list = []
current_list = []
ans = []
next_list.append(root)
while len(next_list) !=0:
current_list = next_list
next_list = []
level = []
while len(current_list) !=0:
node = current_list.pop(0)
if node:
next_list.append(node.left)
next_list.append(node.right)
level.append(node.val)
if len(level) !=0:
ans.append(level)
ans.reverse()
return ans
# @lc code=end
if __name__ == "__main__":
Test = Solution()
T1 = TreeNode(3)
T2 = TreeNode(9)
T3 = TreeNode(20)
T4 = TreeNode(15)
T5 = TreeNode(7)
T1.left = T2
T1.right = T3
T3.left = T4
T3.right = T5
print(Test.levelOrderBottom(T1))
|
2a07d75a18a765e6a38ecd22fdc30f9d9f4635f6 | Queena-Zhq/leetcode_python | /9.palindrome-number.py | 1,330 | 3.90625 | 4 | #
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# https://leetcode.com/problems/palindrome-number/description/
#
# algorithms
# Easy (45.20%)
# Likes: 2059
# Dislikes: 1500
# Total Accepted: 848.7K
# Total Submissions: 1.8M
# Testcase Example: '121'
#
# Determine whether an integer is a palindrome. An integer is a palindrome when
# it reads the same backward as forward.
#
# Example 1:
#
#
# Input: 121
# Output: true
#
#
# Example 2:
#
#
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it
# becomes 121-. Therefore it is not a palindrome.
#
#
# Example 3:
#
#
# Input: 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
#
#
# Follow up:
#
# Coud you solve it without converting the integer to a string?
#
#
# @lc code=start
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
else:
_x = x
ans = 0
while x>0:
ans = ans*10 + x%10
x = int(x/10)
if ans == _x:
return True
else:
return False
# @lc code=end
if __name__ == "__main__":
Test = Solution()
print(Test.isPalindrome(12211))
|
c6122c5c43a436364386c0085839c4f2c8c59d39 | rishav7037/intro-to-data-science-with-python | /assignment-03/question-13.py | 365 | 3.53125 | 4 | def answer_thirteen():
Top15 = answer_one()
Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15 = Top15['PopEst']
for i in range(len(Top15)):
country = Top15.keys()[i]
number = "{:,}".format((Top15.iloc[i]))
Top15.replace(Top15.iloc[i], number, inplace=True)
return Top15
answer_thirteen()
|
e4257bd84246cba390d4635229e711296f7079af | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/25-04/feira_de_boi.py | 697 | 3.671875 | 4 | ttboi=0 #contador das notas
jovem=1000 #para saber qual boi é mais jovem
pesado=0
soma_geral=0
nome=(input('Informe o nome do boi: '))
while nome!='fim':
peso=float(input('Informe o peso do boi em KG: '))
idade=int(input('Informe a idade do boi em meses: '))
soma_notas=0
for i in range (6):
i=float(input('Informe as notas do boi: '+str(i+1)))
soma_notas+=notas
media=soma_notas/6
soma_geral+=soma_notas
print ('Média %.2f'%(soma_notas))
ttboi+=1
if peso>pesado:
pesado=peso
nom_pes=nome
if idade<jovem:
jovem=idade
nom_jov=nome
nome=input('Nome: ')
print ('Boi mais jovem: ', nom_jov)
print ('Boi mais pesado: ', nom_pes)
print ('Média das notas: ', soma_geral/ttboi)
|
af6b5de148c6af4715d451e937c50c9a7b4bf253 | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/Primeira Lista De Exercícios/Exercicio4.py | 283 | 3.734375 | 4 | quant_tec=int(input('Informe a quantidade de pedaços de tecidos: '))
Sobra 1,65 de cada tececido
conta1=(1.65*quant_tec)
conta2=(conta1/1.87)
print('A quantidade de calças feitas é de: ', conta2)
#Cada calça utilizasse 1,87 já com os 15% de percas
#Sobra 1,65 de cada tececido
|
00a2c986bc88cd6e22c71ba2f6d056f9eec22a0e | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/URI/URI.py | 132 | 3.6875 | 4 | A, B=(input()).split()
A = int(A)
B = int(B)
if A % B == 0 or B % A == 0:
print('Sao Multiplos')
else:
print('Nao sao Multiplos')
|
0e6ecd5400cd38b2cc38691df4b0c982c4a6390f | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/Primeira Aula/meuprog3.py | 326 | 3.796875 | 4 | print('Meu terceiro programa em Python')
prc_prod=float(input('Informe o preço do produto: '))
jur=float(input('Infome o juro: '))
num_par=int(input('Informe o número de parcelas: '))
pr_jur=1+(jur/100)
vlr_juro=(pr_jur*prc_prod)
valor_parcela=(vlr_juro / num_par)
print('O valor das parcelas será de R$: ', valor_parcela)
|
47e1601014dd3ff75fc1a4920611bb9bca075203 | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/22-04/fatorial.py | 66 | 3.546875 | 4 | n=int(input(""))
f=1
for i in range (0,n) :
f=f*(n-i)
print(f)
|
b293d21020614905d98f43851727a490918287e5 | LinkaSofia/Algoritmo-I---Python | /Aulas e Exercícios - 2018/Primeira Lista De Exercícios/Exercicio6.py | 280 | 3.765625 | 4 | Com_base=float(input('Informe o comprimento da base: '))
Com_aresta1=float(input('Informe o comprimento da aresta da direita: '))
Com_aresta2=float(input('Informe o comprimento da aresta da esquerda: '))
soma=(Com_base+Com_aresta1+Com_aresta2)
print('O perímetro é de: ', soma)
|
df11bc1e05545abc15b0e5c0f2bcbf74a4cc842e | pmartel/Sudoku | /BoxTest.py | 118 | 3.828125 | 4 | """ test how to get row.col from box"""
for b in range(9):
print('b',b)
print('row',(b//3)*3)
print('col',(b*3)%9)
|
3f7db7b6136a51178cd4f8203881b29e3b99760b | vishmango117/CP1404-Practicals | /Week 4/repeated_strings.py | 365 | 3.953125 | 4 |
cache_string = []
repeated_string = []
while True:
user_input = input("Enter String:")
if(user_input == ""):
break
if(user_input in cache_string):
repeated_string.append(user_input)
else:
cache_string.append(user_input)
if(not(repeated_string)):
print("No repeated strings entered")
else:
print(repeated_string) |
b5c45c728fffa1f3d96aa4460dabc5a5abd54b02 | andersraberg/HackerRankPython | /src/lists.py | 592 | 3.875 | 4 | if __name__ == '__main__':
N = int(input())
the_list = []
for i in range(N):
op = input().strip().split(" ")
if op[0] == "insert":
the_list.insert(int(op[1]), int(op[2]))
elif op[0] == "print":
print(the_list)
elif op[0] == "remove":
the_list.remove(int(op[1]))
elif op[0] == "append":
the_list.append(int(op[1]))
elif op[0] == "sort":
the_list.sort()
elif op[0] == "pop":
the_list.pop()
elif op[0] == "reverse":
the_list.reverse()
|
a1ac31f633ac496bd5f68f57a974de23930f9308 | guoyunfei0603/lemon11 | /class_3/14/review_if.py | 1,429 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/27 16:41
# @Author : guoyunfei.0603
# @File : review_if.py
# 输入一个数字,判断能否整除2和3
# num = int(input("请输入一个数字:"))
# if num%2==0:
# if num%3==0:
# print("该数能整除2和3")
# else:
# print("能整除2但不能整除3")
# else:
# if num%3==0:
# print("能整除3但不能整除2")
# else:
# print("你输入的数字不能整除 2 和 3")
# while True:
# s =input("请输入你反馈的问题: 1:小程序相关 2:移动收银相关 3:云店通相关 4:其他问题 5:输入#结束:")
# if s == '1':
# print("这里是小程序相关的问题")
# elif s == '2':
# print("这里是移动收银相关的问题")
# elif s=='3':
# print("这里是云电通相关的问题")
# elif s =='4':
# print('请问有其他什么问题?')
# elif s == '#':
# print('结束程序~')
# break
# 输入num为四位数,对其按照如下的规则进行加密
# 1. 每一位分别加5,然后分别将其替换为该数除以10取余后的结果
# 2. 将该数的第1位和第四位互换,第二位和第三位互换
# 3. 最后合起来作为加密后的整数输出
num=input("请输入一个四位数:")
s = ''
for item in num:
result = (int(item)+5)%10
s+=str(result)
num_result = s[::-1]
print(num_result) |
874702335cc16c1e60f0aa6653ee7bd145a0234c | guoyunfei0603/lemon11 | /class_3/23/class_except.py | 886 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/23 23:45
# @Author : guoyunfei.0603
# @File : class_except.py
# 异常处理
# 第一种: try...except
# try:
# f = open('test_01.txt','a',encoding='utf-8')
# f.read('我们都一样')
# except Exception as e:
# print('****错误****',e)
# 第二种: try...except...finally
try:
f = open('test_01.txt','a',encoding='utf-8')
f.read('我们都一样')
except Exception as e: # 常用错误类:Exception , as相当于赋值给e
print('****错误****',e)
finally:
print('最终-------都要执行-----------')
# 第三种 try..except..else 不推荐
# try:
# f = open('test_01.txt','a',encoding='utf-8')
# f.write('我们都一样')
# except Exception as e:
# print('****错误****',e)
# else:
# print('try如果执行成功,我就执行')
print("\n程序正常执行---") |
a9ec757138eafbfde183925e66fd14cf1d1020a4 | mickeystone/Bitmsg | /base58.py | 1,228 | 3.90625 | 4 | """ base58 encoding / decoding functions """
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
base_count = len(alphabet)
def encode(num):
""" Returns num in a base58-encoded string """
encode = ''
if (num < 0):
return ''
while (num >= base_count):
mod = num % base_count
encode = alphabet[mod] + encode
num = num // base_count
if (num):
encode = alphabet[num] + encode
return encode
def decode(s):
""" Decodes the base58-encoded string s into an integer """
decoded = 0
multi = 1
s = s[::-1]
for char in s:
decoded += multi * alphabet.index(char)
multi = multi * base_count
return decoded
def decode_to_bytes(s):
v = decode(s)
result = b''
while v >= 256:
div, mod = divmod(v, 256)
result = bytes([mod]) + result
v = div
result = bytes([v]) + result
i = 0
while i < len(s) and s[i] == '1':
i += 1
result = (b'\x00' * i) + result
return result
def encode_from_bytes(v):
i = 0
while v[i] == 0:
i += 1
n = int.from_bytes(v[i:], 'big')
return ('1' * i) + encode(n)
|
2b54892f2bf83098b34d4279bc5942c05cb7db1c | redreceipt/advent-2020 | /day9/solve.py | 969 | 3.609375 | 4 | def get_numbers(lines):
return [int(line.strip()) for line in lines]
def one(preamble_length):
for i, number in enumerate(numbers):
found = False
if i < preamble_length:
continue
for first_number in numbers[i - preamble_length:i]:
for second_number in numbers[i - preamble_length:i]:
if first_number + second_number == number:
found = True
if not found:
return (i, number)
def two(error_number):
valid_numbers = numbers[:error_number[0]]
for i, first_number in enumerate(valid_numbers):
for j, last_number in enumerate(valid_numbers):
if sum(valid_numbers[i:j]) == error_number[1]:
sequence = valid_numbers[i:j]
return max(sequence) + min(sequence)
f = open("input.txt")
lines = f.readlines()
numbers = get_numbers(lines)
error_number = one(25)
print(error_number)
print(two(error_number))
|
3080de8f78481c3c7560e662702f7715fcbc9174 | IrmaGC/Mision-05 | /Menu.py | 6,417 | 3.546875 | 4 | # encoding: UTF-8
# Autor: Irma Gómez Carmona
# Menú que permite elegir entre 7 opciones, 4 son dibujos
import math
import random
import pygame # Librería de pygame
# Dimensiones de la pantalla
ANCHO = 800
ALTO = 800
# Colores
BLANCO = (255, 255, 255) # R,G,B en el rango [0,255], 0 ausencia de color, 255 toda la intensidad
VERDE_BANDERA = (27, 94, 32) # un poco de rojo, más de verde, un poco de azul
ROJO = (255, 0, 0) # solo rojo, nada de verde, nada de azul
AZUL = (0, 0, 255) # nada de rojo, ni verde, solo azul
NEGRO = ( 0, 0, 0)
# Funciones para cada opción
def dibujarCuadradosYCirculos(ventana): #el radio de los circulos se incrementan de 10 en 10 y los lados del cuadrado son el doble del tamaño que el anterior
delta=10
for cu in range (10,ALTO//2+10,delta):
pygame.draw.rect(ventana,NEGRO, (ANCHO//2-cu, ALTO//2-cu, 2*cu, 2*cu),1)
for ci in range (10,ALTO//2+10,delta):
pygame.draw.circle(ventana,NEGRO,(ANCHO//2,ALTO//2),ci,1)
def dibujarParabolas(ventana):
for y in range (0,ALTO//2,10): #composición de rombos que se alargan en x y disminuyen en y para diseñar parábolas
ALEATORIO1=random.randint(0,255)
ALEATORIO2 = random.randint(0, 255)
ALEATORIO3 = random.randint(0, 255)
ColorAleatorio=(ALEATORIO1,ALEATORIO2,ALEATORIO3)
pygame.draw.lines(ventana, ColorAleatorio, True, [(ANCHO//2, y), (ANCHO//2+y, ALTO//2), (ANCHO//2, ALTO-y),(ANCHO//2-y,ALTO//2)], 1)
def dibujarCirculos(ventana): #el angulo aumenta de 30 y 30 y mediante los oomponentes x, y se designa el centro de los circulos
angulo=0
radio=150
for circulo in range (12):
x=int(radio*math.cos(angulo*math.pi/180))
y=int(radio*math.sin(angulo*math.pi/180))
pygame.draw.circle(ventana,NEGRO,(ANCHO//2+x,ALTO//2+y),radio,1)
angulo +=30
def calcularDivisiblesEntre19(): #números de tres digitos que son exactamente divisibles (residuo=0) entre 19
sum=0
for num in range(100,1001):
if num%19==0:
sum=sum+1
return sum
def calcularAproximacionPI(parametro): #calcular aproximación de Pi, el máximos denominador lo teclea el usuario
sum=0
for num in range (1,parametro+1):
sum+= 1/num**4
aprox=(sum*90)**0.25
return aprox
def hacerSecuencia1(): #el factor uno es un acumulador de factor1*10+factor3
factor1=0
factor2=8
for factor3 in range (1,10):
factor1 = factor1 * 10 + factor3
multiplicacion= factor1*factor2+factor3
print("%d * %d + %d = %d" %(factor1,factor2,factor3,multiplicacion))
def hacerSecuencia2(): #factor se obtiene mediante la cumulación del mismo valor *10 +1
factor=1
for num in range(9):
multiplicacion=factor*factor
print("%d * %d = %d" %(factor,factor,multiplicacion))
factor=factor*10+1
def dibujarEspiral(ventana): #la segunda coordenada de una linea es la primera de la siguiente linea que forma la espiral
for linea in range(0, ANCHO + 1, 10):
if linea <= 399:
pygame.draw.line(ventana, NEGRO, (linea, linea), (ANCHO - linea, linea), 1)
pygame.draw.line(ventana, NEGRO, (ANCHO - linea, linea), (ANCHO - linea, ANCHO - linea), 1)
pygame.draw.line(ventana, NEGRO, (ANCHO - linea, ANCHO - linea), (linea + 10, 800 - linea), 1)
pygame.draw.line(ventana, NEGRO, (linea + 10, 800 - linea), (linea + 10, linea + 10), 1)
def dibujar(opcion):
# Inicializa el motor de pygame
pygame.init()
# Crea una ventana de ANCHO x ALTO
ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará
reloj = pygame.time.Clock() # Para limitar los fps
termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no
while not termina: # Ciclo principal, MIENTRAS la variabel termina sea False, el ciclo se repite automáticamente
# Procesa los eventos que recibe
for evento in pygame.event.get():
if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir
termina = True # Queremos terminar el ciclo
# Borrar pantalla
ventana.fill(BLANCO)
# Dibujar, aquí haces todos los trazos que requieras
# Normalmente llamas a otra función y le pasas -ventana- como parámetro, por ejemplo, dibujarLineas(ventana)
# Consulta https://www.pygame.org/docs/ref/draw.html para ver lo que puede hacer draw
if opcion==1:
dibujarCuadradosYCirculos(ventana)
elif opcion==2:
dibujarParabolas(ventana)
elif opcion==3:
dibujarEspiral(ventana)
elif opcion==4:
dibujarCirculos(ventana)
pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)
reloj.tick(40) # 40 fps
# Después del ciclo principal
pygame.quit() # termina pygame
# Función principal, aquí resuelves el problema
def main():
opcion=1
while opcion != 0:
print("Misión 5. Seleccione que quiere hacer ")
print("1. Dibujar cuadros y círculos")
print("2. Dibujar parábolas")
print("3. Dibujar espiral")
print("4. Dibujar círculos")
print("5. Aproximar PI")
print("6. Contar divisibles entre 19 ")
print("7. Imprimir pirámides de números")
print("0. Salir")
opcion = int(input("¿Qué desea hacer?"))
if opcion>=1 and opcion<=4:
dibujar(opcion)
elif opcion==5:
parametro=int(input("Valor del último divisor: "))
total=calcularAproximacionPI(parametro)
print("PI: ", total)
print("")
elif opcion==6:
numeros=calcularDivisiblesEntre19()
print("Números de tres cifras divisibles entre 19: ", numeros)
print("")
elif opcion==7:
hacerSecuencia1()
print("")
hacerSecuencia2()
print("")
elif opcion<0 or opcion>7:
print("---Opción no válida, vuelva a intentarlo---")
print("")
print("*** Programa terminado :) ***")
# Llamas a la función principal
main() |
f39b5bf8985d27b972d10dcc06671303c0ac4ed8 | rc2030/gitdemo | /gitdemon.py | 215 | 3.59375 | 4 | import sys
if len(sys.argv) < 3:
print('You must give two command line arguments.')
exit(1)
else
print('You have provided', len(sys.argv) - 1, 'command line arguments.')
print('They are: ',sys.argv[1:])
|
1af1fe79704106a2026f6783cf80d5cbbb17268c | rajathans/cp | /CodeChef/fctrl.py | 124 | 3.5625 | 4 | a = raw_input()
for da in range(int(a)):
f = int(raw_input())
i = 5
r = 0
while (f//i > 0):
r += f//i
i*=5
print r |
7b742399e68f9591dcb0154b50b187c58d6d4ce9 | canhetingsky/LeetCode | /Python3/73.set-matrix-zeroes.py | 929 | 3.625 | 4 | #
# @lc app=leetcode id=73 lang=python3
#
# [73] Set Matrix Zeroes
#
# @lc code=start
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row, column = [], []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
if i not in row:
row.append(i)
if j not in column:
column.append(j)
for i in row:
for j in range(len(matrix[0])):
matrix[i][j] = 0
for j in column:
for i in range(len(matrix)):
matrix[i][j] = 0
# @lc code=end
# Accepted
# 159/159 cases passed(136 ms)
# Your runtime beats 99.87 % of python3 submissions
# Your memory usage beats 92.31 % of python3 submissions(13.4 MB)
|
e7e707856d241e685c50db43d830624019d30aad | canhetingsky/LeetCode | /Python3/102.binary-tree-level-order-traversal.py | 1,001 | 3.828125 | 4 | #
# @lc app=leetcode id=102 lang=python3
#
# [102] Binary Tree Level Order Traversal
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res, level = [], [root]
while root and level:
node_value = []
next_level = []
for node in level:
node_value.append(node.val)
# find the next level of node
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
res.append(node_value)
level = next_level
return res
# @lc code=end
# Accepted
# 34/34 cases passed(44 ms)
# Your runtime beats 51.22 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions(13 MB)
|
b4487e2f505fe30ec91776daf3c26c18f2067947 | Northwestern-CS348/assignment-3-part-2-uninformed-solvers-brndnwrd | /student_code_uninformed_solvers.py | 5,775 | 3.515625 | 4 |
from solver import *
class SolverDFS(UninformedSolver):
def __init__(self, gameMaster, victoryCondition):
super().__init__(gameMaster, victoryCondition)
def solveOneStep(self):
"""
Go to the next state that has not been explored. If a
game state leads to more than one unexplored game states,
explore in the order implied by the GameMaster.getMovables()
function.
If all game states reachable from a parent state has been explored,
the next explored state should conform to the specifications of
the Depth-First Search algorithm.
Returns:
True if the desired solution state is reached, False otherwise
"""
### Student code goes here
# print(self.currentState.state[0])
# print(self.currentState.state[1])
# print(self.currentState.state[2])
# print('')
if self.currentState not in self.visited:
self.visited[self.currentState] = True
if self.currentState.state == self.victoryCondition:
return True
moves = self.gm.getMovables()
if moves:
for move in moves:
self.gm.makeMove(move)
new_child = GameState(self.gm.getGameState(), self.currentState.depth+1, move)
if new_child not in self.visited:
new_child.parent = self.currentState
self.currentState.children.append(new_child)
self.gm.reverseMove(move)
if self.currentState.children:
self.visitNextChild()
else:
self.findNextChild()
def findNextChild(self):
while self.currentState.nextChildToVisit < len(self.currentState.children):
child = self.currentState.children[self.currentState.nextChildToVisit]
if child not in self.visited:
self.visitNextChild()
return
self.unvisit()
def unvisit(self):
# return to parent if no unvisited moves in children
self.gm.reverseMove(self.currentState.requiredMovable)
self.currentState = self.currentState.parent
self.findNextChild()
def visitNextChild(self):
self.currentState = self.currentState.children[self.currentState.nextChildToVisit]
self.currentState.parent.nextChildToVisit += 1
self.gm.makeMove(self.currentState.requiredMovable)
class SolverBFS(UninformedSolver):
def __init__(self, gameMaster, victoryCondition):
super().__init__(gameMaster, victoryCondition)
def solveOneStep(self):
"""
Go to the next state that has not been explored. If a
game state leads to more than one unexplored game states,
explore in the order implied by the GameMaster.getMovables()
function.
If all game states reachable from a parent state has been explored,
the next explored state should conform to the specifications of
the Breadth-First Search algorithm.
Returns:
True if the desired solution state is reached, False otherwise
"""
### Student code goes here
if self.currentState not in self.visited:
self.visited[self.currentState] = True
if self.currentState.state == self.victoryCondition:
return True
if self.currentState.depth == 0:
self.populate_children()
self.visitNextChild()
elif self.currentState.parent.nextChildToVisit < len(self.currentState.parent.children):
# return to parent
self.gm.reverseMove(self.currentState.requiredMovable)
self.currentState = self.currentState.parent
self.visitNextChild()
else:
self.common_root()
def populate_children(self):
moves = self.gm.getMovables()
if moves:
for move in moves:
self.gm.makeMove(move)
new_child = GameState(self.gm.getGameState(), self.currentState.depth + 1, move)
if new_child not in self.visited:
new_child.parent = self.currentState
self.currentState.children.append(new_child)
self.gm.reverseMove(move)
def common_root(self):
while self.currentState.depth > 0:
if self.currentState != self.currentState.parent.children[-1]:
self.gm.reverseMove(self.currentState.requiredMovable)
self.currentState = self.currentState.parent
break
self.currentState.nextChildToVisit = 0
self.gm.reverseMove(self.currentState.requiredMovable)
self.currentState = self.currentState.parent
self.currentState.nextChildToVisit = 0
self.find_next_child()
def find_next_child(self):
while self.currentState.nextChildToVisit < len(self.currentState.children):
self.visitNextChild()
if not self.currentState.children:
self.populate_children()
if self.currentState.children:
if self.currentState.children[self.currentState.nextChildToVisit] not in self.visited:
self.visitNextChild()
return
else:
self.unvisit()
def unvisit(self):
# return to parent
self.gm.reverseMove(self.currentState.requiredMovable)
self.currentState = self.currentState.parent
self.find_next_child()
def visitNextChild(self):
self.currentState = self.currentState.children[self.currentState.nextChildToVisit]
self.currentState.parent.nextChildToVisit += 1
self.gm.makeMove(self.currentState.requiredMovable)
|
b912587a5ad3c58fc59cc09aaef76d2d2a215044 | hakbailey/advent-of-code-2019 | /day_3_part_1.py | 2,165 | 3.859375 | 4 | START = (0, 0)
with open("day_3_input.txt", "r") as f:
input = f.read().split('\n')
wire_1_path = input[0].split(',')
wire_2_path = input[1].split(',')
def all_coords_traveled(start_coords, wire_path):
all_coords = [start_coords]
for i, path in enumerate(wire_path):
new_coords = get_path_coords(all_coords[-1], path)
all_coords.extend(new_coords)
return all_coords
def get_path_coords(start_coords, path):
dir = path[0]
steps = int(path[1:]) + 1
if dir == 'R':
path_coords = [(start_coords[0] + i, start_coords[1])
for i in range(1, steps)]
elif dir == 'L':
path_coords = [(start_coords[0] - i, start_coords[1])
for i in range(1, steps)]
elif dir == 'U':
path_coords = [(start_coords[0], start_coords[1] + i)
for i in range(1, steps)]
elif dir == 'D':
path_coords = [(start_coords[0], start_coords[1] - i)
for i in range(1, steps)]
return path_coords
def get_intersections(path_1_coords, path_2_coords):
return list(set(path_1_coords) & set(path_2_coords))
def manhattan_distance(point_a, point_b):
x = abs(point_a[0] - point_b[0])
y = abs(point_a[1] - point_b[1])
return x + y
def find_shortest_distance(start, intersections):
distances = []
for i in intersections:
distances.append(manhattan_distance(start, i))
return min(distances)
def find_steps_to_point(coords_traveled_in_order, point):
return coords_traveled_in_order.index(point)
def find_closest_intersection_by_steps(points, paths):
step_counts = []
for point in points:
wire_1_steps = find_steps_to_point(paths[0], point)
wire_2_steps = find_steps_to_point(paths[1], point)
total_steps = wire_1_steps + wire_2_steps
if __name__ == '__main__':
wire_1_coords = all_coords_traveled(START, wire_1_path)
wire_2_coords = all_coords_traveled(START, wire_2_path)
intersections = get_intersections(wire_1_coords, wire_2_coords)
intersections.remove(START)
print(find_shortest_distance(START, intersections))
|
efa3c5294a1274ba4c2133c34b6aaa32fb3ad590 | ayatullah-ayat/py4e_assigns_quizzes | /chapter-10_assignment-10.2.py | 921 | 4.125 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email_sender_list = list()
for line in handle:
word_list = line.split()
if len(word_list) < 2:
continue
if not word_list:
continue
if not line.startswith('From '):
continue
email_sender_list.append(word_list[5])
item_dict = dict()
for item in email_sender_list:
item = item.split(':')
it = item[0]
item_dict[it] = item_dict.get(it, 0) + 1
for key, value in sorted(item_dict.items()):
print(key, value)
|
05dff35a6018954c4184e233d82b226bb4389e21 | smrigney/Python-Challenge- | /pybank/main.py | 3,686 | 3.84375 | 4 | # total number of months in data set (column 0)
# the net total amount of profit/losses over the entire period (column 1)
# calculate the changes in profit/losses over the entire period, then find average
# the greatest increase in profits (date and amount) over the entire period
# the greatest decrease in profits (date and amount) over the entire period
#find the cvs file
import csv
#find csv file
csvfile = open("onedrive/desktop/python-challenge/pybank/resources/budget_data.csv","r+")
reader = csv.reader(csvfile)
#count number of lines in csv file
lines=len(list(reader))
#remove header from lines count
linesfinal = lines - 1
print("Total Months: ", linesfinal)
#send to word file
answer1 = str("Total Months: ") + str(linesfinal)
worddoc = open("onedrive/desktop/python-challenge/pybank/analysis/pybank_analysis.txt","w")
worddoc.write(str(answer1) + '\n')
#close csvfile
csvfile.close()
# add total profit / losses
csvfile = open("onedrive/desktop/python-challenge/pybank/resources/budget_data.csv","r+")
#skip the header row
next(csvfile)
#set total to 0
total = 0
#sum column 1
for row in csv.reader(csvfile):
total +=int(row[1])
#print check
print("Total: $", total) #Answer#2
#send to word file
answer2 = str("Total: $") + str(total)
worddoc.write(str(answer2) + '\n')
csvfile.close()
# calculate the changes in profit/losses over the entire period,
# then find average
csvfile = open("onedrive/desktop/python-challenge/pybank/resources/budget_data.csv","r+")
#create reader
diffile = csv.reader(csvfile)
#create list to store differences
numlist = []
#pulling from csv to create list of profit/loss column
for col in diffile:
numlist.append(col[1])
#print(numlist)
#remove header from list
del numlist[0]
#making numlist integers
numlist = list(map(int, numlist))
#setting new list for differences
numdiffs = []
#finding all differences and adding to new list
for i in range(len(numlist)):
diff = numlist[i] - numlist[i -1]
numdiffs.append(diff)
#removing first diff to ensure correct mean
del numdiffs[0]
#finding mean via statistics
import statistics
meandiff = statistics.mean(numdiffs)
#print check
print("Average Change: $ %0.2f" % (meandiff))#Answer#3
#write answer 3 to txt file
answer3 = str("Average Change: $ ") + str( "%.02f" % meandiff)
worddoc.write(answer3 + '\n')
csvfile.close()
# the greatest increase in profits (date and amount)
# over the entire period
csvfile = open("onedrive/desktop/python-challenge/pybank/resources/budget_data.csv","r+")
maxminlist = csv.reader(csvfile)
#sort list
maxdiff = max(numdiffs)
mindiff = min(numdiffs)
#print(maxdiff, mindiff)
#create month list
monthlist = []
for col in maxminlist:
monthlist.append(col[0])
i = 0
countmaxdiff = 0
for i in numdiffs:
if i is not maxdiff:
countmaxdiff = countmaxdiff + 1
else:
break
#account for header and add one month
countmaxdiff = countmaxdiff + 2
#print check
print("Greatest Increase in Profits: ",monthlist[countmaxdiff], maxdiff) #Answer#4
#answer 4 to txt file
answer4 = str("Greatest Increase in Profits: ") + str(monthlist[countmaxdiff] + " " + str(maxdiff))
worddoc.write(answer4 + "\n")
i = 0
countmindiff = 0
for i in numdiffs:
if i is not mindiff:
countmindiff = countmindiff + 1
else:
break
#account for header and add one month
countmindiff = countmindiff + 2
#print check
print("Greatest Decrease in Profits: ", monthlist[countmindiff], mindiff) #answer#5
#answer 5 into txt doc
answer5 = str("Great Decrease in Profits: ") + str(monthlist[countmindiff]) + " " + str(mindiff)
worddoc.write(str(answer5))
#close worddoc
worddoc.close() |
585e5e7603ccccfd95ed6a557fd8b54b07c7334d | prisings/python | /bin/1기초문법.py | 474 | 3.796875 | 4 | print('test') # 파이썬에서 주석은 # 그리고 컨트롤 쉬프트 / 는 자바와 같아 그냥 사용가능 (물론 표시되는 문자는 다름)
""" 아
야
어
여 """
n = 10
if n % 2 == 0:
print("짝")
else:
print("홀")
""" 파이썬의 경우 들여쓰기에 매우 민감하다 하나라도 틀리면 error? """
print("plus를 안해도 이어지나?","이게 말이되나?", "유용한 기능")
name = input("이룸 : ")
print("eroom : ", name) |
207e582862dc710a2a6b5901346070a1d300feac | 8787ooo/Python200818 | /guessonetime.py | 274 | 3.84375 | 4 | import random
n = random.randint(1,10)
a = input("num:")
if a == "1" or a =="2"or a =="3" or a =="4"or a =="5" or a =="6"or a == "7" or a == "8"or a =="9" or a == "10":
if n == a:
print("yes")
else:
print('no')
else:
print('error')
|
01ebc37bf5000576214cbf71140dba070dbb4f2a | sdtimothy8/Coding | /Python_projects/small_useful_tools/excel_process/split.py | 214 | 3.546875 | 4 | #!/usr/bin/env python
#coding: utf-8
import os
testfile = 'test.txt'
f = open(testfile, 'r+')
row_list = []
for row in f:
row_list.append(row.split())
print row_list
a = "love"
b = "jiale"
print join(a,b)
|
a804aaae0bee17aafdb0376dad0449156a84b4af | LeonardoArcanjo/Praticas-Python | /parking.py | 2,569 | 3.984375 | 4 | """
Tarifa do estacionamento:
1a a 2a hora: R$ 1.00 cada
3a e 4a hora: RS 1.40 cada
5a hora e seguintes horas: R$ 2.00 cada
O numero de horas a pagar é sempre inteiro e arrendondado por excesso. Quem estacionar por 61 min, pagará por 2 horas,
que é o mesmo que alguém pagaria se tivesse permanecido por 120 min. O momento de chegada e partida são apresentados em
forma de pares inteiros. Por exemplo 12 50 (dez para as 1 da tarde). Pretende-se criar um programa que, lidos pelo
teclado os horarios de chegada e partida, escreva na tela o preço cobrado pelo estacionamento. Admite-se que a chegada
e a partida se dão com intervalo não superior a 24 horas, isso não é uma situação de erro, antes significará que a
partida ocorreu no dia seguinte ao da chegada
"""
# entrada dos valores em formato de string
chegada = input("Digite o horario da chegada: ")
partida = input("Digite o horario da partida: ")
# converter a string para uma lista
chegada = chegada.split(" ")
partida = partida.split(" ")
# conversao de string para inteiro do dados
hora_chegada = int(chegada[0])
min_chegada = int(chegada[1])
hora_partida = int(partida[0])
min_partida = int(partida[1])
# converter as horas para minutos e somar com os minutos
mins_chegada = hora_chegada * 60 + min_chegada
mins_partida = hora_partida * 60 + min_partida
# Calculo da diferenca do horario de chega e de partida em minutos
dif_partida_chegada = mins_partida - mins_chegada
qtd_hora = int(dif_partida_chegada / 60)
qtd_min = dif_partida_chegada % 60
valor_pagar = 1
if 60 < dif_partida_chegada < 121:
valor_pagar += 1
elif 120 < dif_partida_chegada < 181:
valor_pagar += 2.4
elif 180 < dif_partida_chegada < 241:
valor_pagar += 3.8
elif dif_partida_chegada > 240 and qtd_min == 0:
valor_pagar = 4.8 + 2 * (qtd_hora - 4)
elif dif_partida_chegada > 240 and qtd_min != 0:
valor_pagar = 4.8 + 2 * (qtd_hora - 3)
elif dif_partida_chegada <= 0: # Caso a pessoa fique de um dia para outro nao ultrapassando as 24 hrs
dif_partida_chegada = (24 * 60) - mins_chegada + mins_partida # converte quando dá 00 horas
qtd_hora = int(dif_partida_chegada / 60)
qtd_min = dif_partida_chegada % 60
if dif_partida_chegada > 240 and qtd_min == 0:
valor_pagar = 4.8 + 2 * (qtd_hora - 4)
elif dif_partida_chegada > 240 and qtd_min != 0:
valor_pagar = 4.8 + 2 * (qtd_hora - 3)
print(f"Valor a pagar: R$ {valor_pagar:.2f}")
print(f"Tempo passado: {qtd_hora}:{qtd_min:02d}") # {:02d}: 0 - indica que tem zero na frente, 2: 2 casas, d: inteiro
|
3d76c24a7f88f83bbda0bb40f5c426709fd48288 | rexlinster/PYLN | /1.py | 352 | 3.734375 | 4 | import sys
print("中文")
str1 = "this is srring"
print(str1.isalpha())
print(max(str1))
while 1 :
user = input("輸入你的姓名:")
pwd = input("passwd:")
if user == "badman" and pwd == "123" :
print("login success")
break
else :
print("login fail")
continue
print(sys.getdefaultencoding())
list |
ab52124ad89b97b019dbe3f64132a1a83edeb1fe | alexleversen/AdventOfCode | /2020/03-1/main.py | 397 | 3.65625 | 4 | file = open('input.txt', 'r')
lines = file.readlines()
treeCount = 0
index = 0
rightSlope = 3
for line in lines:
lineList = list(line)
if(line[index] == '#'):
treeCount += 1
lineList[index] = 'X'
else:
lineList[index] = 'O'
print(''.join(lineList))
index += rightSlope
if (index >= len(line) - 1):
index -= (len(line) - 1)
print(treeCount) |
246130cc6d8d3b7c3fee372774aa2f93018f4e35 | alexleversen/AdventOfCode | /2020/08-2/main.py | 1,119 | 3.625 | 4 | import re
file = open('input.txt', 'r')
lines = list(file.readlines())
def testTermination(swapLine):
if(lines[swapLine][0:3] == 'acc'):
return False
instructionIndex = 0
instructionsVisited = []
acc = 0
while(True):
if(instructionIndex == len(lines)):
return acc
if(instructionIndex in instructionsVisited):
return False
instructionsVisited.append(instructionIndex)
match = re.match('(\w{3}) ([+-]\d+)', lines[instructionIndex])
instruction, value = match.group(1, 2)
if(instructionIndex == swapLine):
if(instruction == 'jmp'):
instruction = 'nop'
elif(instruction == 'nop'):
instruction = 'jmp'
if(instruction == 'acc'):
acc += int(value)
instructionIndex += 1
elif(instruction == 'jmp'):
instructionIndex += int(value)
else:
instructionIndex += 1
for i in range(len(lines)):
terminationValue = testTermination(i)
if(terminationValue != False):
print(terminationValue)
|
4b012637f522fe239ec5897f144b476da96ae2c6 | natlin/Learning | /morestring.py | 149 | 3.875 | 4 | name="john"
print "Hello %s!" % name
age=25
print "Hello %s, you are %d years old" %(name, age)
list2=[1,2,3]
print 'this is a list: %s' % list2
|
1df5a6d22eaec8d8e15451b13c296c0eff843916 | SenyaSumkin/python_train | /checkio/github/expand_intervals.py | 1,009 | 3.90625 | 4 | from typing import Iterable
def expand_intervals1(items: Iterable) -> Iterable:
answer = []
for pair in items:
addition_number = pair[0]
if pair[0] == pair[1]:
answer.append(addition_number)
else:
for i in range(pair[1]-pair[0]+1):
answer.append(addition_number)
addition_number += 1
return answer
def expand_intervals(items: Iterable) -> Iterable:
return [num for upper, lower in items for num in range(upper, lower+1)]
if __name__ == '__main__':
print("Example:")
print(list(expand_intervals([(1, 3), (5, 7)])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(expand_intervals([(1, 3), (5, 7)])) == [1, 2, 3, 5, 6, 7]
assert list(expand_intervals([(1, 3)])) == [1, 2, 3]
assert list(expand_intervals([])) == []
assert list(expand_intervals([(1, 2), (4, 4)])) == [1, 2, 4]
print("Coding complete? Click 'Check' to earn cool rewards!")
|
f1cd7c740d556ceede291f2b725d1a15b20b4864 | alter4321/Goodline_test_app_dev | /task_3_gl.py | 1,021 | 4 | 4 | quantity = int(input('Количество элементов массива'))
numbers = [int(i) for i in input('Введите значения через пробел').split(' ')]
# Проверка соответсвия указанного и фактического количества элементов массива
if quantity != len(numbers):
print('Указанное количество элементов не соответсвует фактическому')
else:
pass
sign = []
result = []
# Каждый элемент из массива попадает в 2 списка, если он уже
# есть в списке 'sign', тогда удаляется по индексу из
# результирующего списка
for el in numbers:
if el not in sign:
sign.append(el)
result.append(el)
else:
if el in result:
i = result.index(el)
del result[i]
print(' '.join(str(i) for i in result))
|
2836445a3619bd8f3a5554d962f079cc0de9cd9a | sooty1/Javascript | /main.py | 1,240 | 4.1875 | 4 |
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']
names_and_dogs_names = zip(names, dogs_names)
print(list(names_and_dogs_names))
# class PlayerCharacter:
# #class object attribute not dynamic
# membership = True
# def __init__(self, name="anonymous", age=0):
# if (age > 18):
# self.name = name
# self.age = age
# def run(self):
# print('run')
# def shout(self):
# print(f'my name is {self.name}')
# player1 = PlayerCharacter('Tom', 10)
# player2 = PlayerCharacter()
# player2.attack = 50
# print(player1.shout())
# print(player2.age)
#Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
def oldest(*args):
return max(args)
cat1= Cat("Tom", 3)
cat2= Cat('Jerry', 5)
cat3= Cat("filbert", 2)
def oldest(*args):
return max(args)aaaa
print(f"The oldest cat is {oldest(cat1.age, cat2.age, cat3.age)} years old.")
# 1 Instantiate the Cat object with 3 cats
# 2 Create a function that finds the oldest cat
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 |
18e0d40be585f1280c75fe50400a2493ce047262 | kkkyan/leetcode | /problem-string-easy/125.验证回文串.py | 1,223 | 3.84375 | 4 | #
# @lc app=leetcode.cn id=125 lang=python3
#
# [125] 验证回文串
#
# https://leetcode-cn.com/problems/valid-palindrome/description/
#
# algorithms
# Easy (40.77%)
# Likes: 106
# Dislikes: 0
# Total Accepted: 49.7K
# Total Submissions: 121.6K
# Testcase Example: '"A man, a plan, a canal: Panama"'
#
# 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
#
# 说明:本题中,我们将空字符串定义为有效的回文串。
#
# 示例 1:
#
# 输入: "A man, a plan, a canal: Panama"
# 输出: true
#
#
# 示例 2:
#
# 输入: "race a car"
# 输出: false
#
#
#
class Solution:
def isPalindrome(self, s: str) -> bool:
if s == "": return True
import re
s = re.sub(r"[^a-zA-Z0-9]","",s)
s = s.lower()
start = 0
end = len(s) - 1
while start < end:
while s[start] == " " and start < end:
start += 1
while s[end] == " " and start < end:
end -= 1
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
|
c0bedffaf20af532c719397c0c67b3111472e682 | kkkyan/leetcode | /problem-math-easy/9.回文数.py | 1,928 | 3.953125 | 4 | #
# @lc app=leetcode.cn id=9 lang=python3
#
# [9] 回文数
#
# https://leetcode-cn.com/problems/palindrome-number/description/
#
# algorithms
# Easy (56.52%)
# Likes: 704
# Dislikes: 0
# Total Accepted: 150.3K
# Total Submissions: 265.9K
# Testcase Example: '121'
#
# 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
#
# 示例 1:
#
# 输入: 121
# 输出: true
#
#
# 示例 2:
#
# 输入: -121
# 输出: false
# 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
#
#
# 示例 3:
#
# 输入: 10
# 输出: false
# 解释: 从右向左读, 为 01 。因此它不是一个回文数。
#
#
# 进阶:
#
# 你能不将整数转为字符串来解决这个问题吗?
#
#
class Solution:
def isPalindrome(self, x: int) -> bool:
### 字符串比较
def solve2(self, x: int) -> bool:
if (x <0):
return False
x_s = str(x)
x_r = x_s[::-1]
return x_s == x_r
'''
用头尾比较方法做(不转化字符串)
'''
def solve1(self, x: int) -> bool:
# 负数一定不是
if (x < 0):
return False
if (x < 10):
return True
# 不用反转字符串 -> 正数头尾比较
# 首先判断x有几位
div_n = 1
p_n = 0
while x >= div_n:
p_n += 1
div_n *= 10
div_n /= 10
# flag 判断是奇数位还是偶数位
flag = p_n % 2
# 对 x 进行头尾判断
while div_n != flag:
header = x // div_n
ender = x % 10
if header != ender:
return False
# x去除头尾
x = x % div_n
x = x // 10
div_n /= 100
return True
|
f7f585f584f0a6b4ccdb708608640d9ba154673c | matherique/trabalhos-edd | /lista_2/test.py | 2,095 | 4.15625 | 4 | #!/usr/bin/env python3
import unittest
from Fraction import *
class TestFractionClass(unittest.TestCase):
def testNumeradorCorreto(self):
""" Numerador correto """
n, d = 1, 2
fr = Fraction(n, d)
self.assertEqual(fr.num, n)
def testDenominadorCorreto(self):
""" Denominador correto """
n, d = 1, 2
fr = Fraction(n, d)
self.assertEqual(fr.den, d)
def testSoma(self):
""" Soma de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
res = Fraction(2, 1)
self.assertEqual(f1 + f2, res)
def testSubtracao(self):
""" Subtracao de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
res = Fraction(-1, 1)
self.assertEqual(f1 - f2, res)
def testMultiplicacao(self):
""" Multiplicacao de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
res = Fraction(3, 4)
self.assertEqual(f1 * f2, res)
def testDivisao(self):
""" Divisao de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
res = Fraction(1, 3)
self.assertEqual(f1 / f2, res)
def testPotenciacao(self):
""" Potenciacao de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
n = 1 ** (3/2)
d = 2 ** (3/2)
res = Fraction(n, d)
self.assertEqual(f1 ** f2, res)
def testIgualdade(self):
""" Potenciacao de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(1, 2)
self.assertEqual(f1, f2)
def testMaior(self):
"""Maior de fracoes """
f1 = Fraction(3, 2)
f2 = Fraction(1, 2)
self.assertGreater(f1, f2)
def testMaiorIgual(self):
"""Maior igual de fracoes """
f1 = Fraction(3, 2)
f2 = Fraction(1, 2)
self.assertGreaterEqual(f1, f2)
def testMenor(self):
"""Menor igual de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
self.assertLess(f1, f2)
def testMenorIgual(self):
"""Menor igual de fracoes """
f1 = Fraction(1, 2)
f2 = Fraction(3, 2)
self.assertLessEqual(f1, f2)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
a61cb09d4db306db4f1f273b43632f340a55cb2d | matherique/trabalhos-edd | /lista_2/Fraction.py | 2,185 | 3.609375 | 4 | #!/usr/bin/env python3
class Fraction:
__slots__ = ['__num', '__den']
def __init__(self, num, den):
self.__den = den
self.__num = num
@property
def num(self):
return self.__num
@property
def den(self):
return self.__den
def __str__(self):
return f"{self.num} / {self.den}"
# mdc da fracao
def __mdc(self, a, b):
return a if b == 0 else self.__mdc(b, a % b)
# simplifica e retorna a nova fracao
def __simplify(self, num, den):
mdc = self.__mdc(num, den)
newnum = num // mdc
newden = den // mdc
return Fraction(newnum, newden)
# adicao
def __add__(self, other):
num = (self.num * other.den) + (other.num * self.den)
den = self.den * other.den
return self.__simplify(num, den)
# subtracao
def __sub__(self, other):
num = (self.num * other.den) - (other.num * self.den)
den = self.den * other.den
return self.__simplify(num, den)
# multiplicacao
def __mul__(self, other):
num = self.num * other.num
den = self.den * other.den
return self.__simplify(num, den)
# divisao
def __truediv__(self, other):
num = self.num * other.den
den = self.den * other.num
return self.__simplify(num, den)
# potenciacao
def __pow__(self, other):
num = self.num ** (other.num / other.den)
den = self.den ** (other.num / other.den)
return Fraction(num, den)
# = igual
def __eq__(self, other):
no = self.__simplify(other.num, other.den)
ns = self.__simplify(self.num, self.den)
return no.num == ns.num and no.den == ns.den
# > maior
def __gt__(self, other):
rescurrent = self.num / self.den
resother = other.num / other.den
return rescurrent > resother
# >= maior igual
def __ge__(self, other):
rescurrent = self.num / self.den
resother = other.num / other.den
return rescurrent >= resother
# < menor
def __lt__(self, other):
rescurrent = self.num / self.den
resother = other.num / other.den
return rescurrent < resother
# <= menor igual
def __le__(self, other):
rescurrent = self.num / self.den
resother = other.num / other.den
return rescurrent <= resother
|
67f2f60471945c0b4b0d87a3273b55429bc2f276 | alxfed/hadamard | /hadamard_sylvester.py | 392 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""...
"""
import numpy as np
def hadamard(n): # n is the order of Sylvester construction, not the dimension of the matrix as the idiots did it.
H = np.array([[1]], dtype=int)
for i in range(0, n):
H = np.block([[H, H], [H, -H]])
return H
def main():
print(hadamard(2))
return
if __name__ == '__main__':
main()
print('\ndone')
|
babcf24c8692cdad95ce95911bb52958f0852f07 | jhocepSan/LlavesTkReg | /uri1008.py | 127 | 3.53125 | 4 | # -*- coding: utf-8 -*-
a=int(input())
b+float(raw_input())
c=float(raw_input())
print "NUMBER = "+a
print "SALARY = U$ "+(b*c) |
4836460fdc68c01eaf60d760a1851fae4debfd49 | TessieMeng/python-practise | /advobj.py | 2,521 | 3.59375 | 4 | class Student(object): #a empty class
pass
s = Student()
s.name = 'lwd'
## 给一个对象绑定一个方法
def set_age(self, age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s) #attach set_age fun to instance set_age.
## 给某一个对象绑定方法后,其他同类对象不具备此方法
s2 = Student()
s2.set_age(25) #it is invalid.
## 给类绑定方法
def set_score(self, score):
self.score = score
Student.set_score = set_score #attach set_score fun to class Student.
## 使用__slots__属性定义子对象可以定义的属性
class Student(object):
__slots__ = ('name', 'age')
s = Student()
s.name = 'lwd'
s.age = 25
s.score = 99 # invalid
## 父类定义的__slots__属性对于其子类没有影响
class Senior(Student):
pass
s1 = Senior()
s1.score = 99 # 合法
s1.age = 32
## 在类中定义方法
## 参数检查
class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('Score must be an interger!')
if value < 0 or value > 100:
raise ValueError('score must between 0~100!')
self._score = value
## 装饰器:将一个方法变成属性调用
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('Score must be an interger!')
if value < 0 or value > 100:
raise ValueError('score must between 0~100!')
self._score = value
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._width * self._height
## 多重mixIn继承
class Animal(object):
pass
class Mammal(Animal):
pass
class Bird(Animal):
pass
# class Dog(Mammal):
# pass
# class Bat(Mammal):
# pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
class FlyableMixIn(object):
def fly(self):
print('flying...')
class RunnableMixIn(object):
def run(self):
print('Running...')
class Dog(Mammal, RunnableMixIn):
pass
class Bat(Mammal, FlyableMixIn):
pass
|
575156aae3b6f2350d617421a1260d323df3ae16 | TessieMeng/python-practise | /advanced.py | 4,751 | 3.640625 | 4 | # 高阶函数
def abs_add(x, y, abs):
return abs(x) + abs(y)
# 映射方法
def f(x):
return x**2
r = map(f, [1,2,3,4,5,6,7,8,9])
list(r)
list(map(str, [1,2,3,4,5]))
# reduce方法
from functools import reduce
def fn(x, y):
return x*10 + y
reduce(fn, [1,2,3,4,5])
# map和reduce组合用法
def str2int(str):
def chr2num(chr):
a = {'1':1, '2':2, '3':3, '4':4,\
'5':5, '6':6, '7':7, '8':8, '9':9, '0':0 }
return a[chr]
def fn(x,y):
return x*10 + y
return reduce(fn, map(chr2num,str))
## lambda表达式用法
def str2int(str):
def chr2num(chr):
a = {'1':1, '2':2, '3':3, '4':4,\
'5':5, '6':6, '7':7, '8':8, '9':9, '0':0 }
return a[chr]
return reduce(lambda x,y : x*10 + y, map(chr2num,str))
## 字符串数组每个元素首字母大写
def normalize(name):
return name[0].upper() + name[1:].lower()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
## 数组中的所有元素相乘
def prod(L):
import functools
return reduce(lambda x,y:x*y , L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
def str2float(s):
s1 = s[:s.find('.')] + s[s.find('.')+1:]
pd = s[::-1].find('.')
def chr2num(c):
a = {}
for i in range(10):
a[chr(0x30+i)] = i
return a[c]
return 10**(-pd)*reduce(lambda x,y:10*x+y , map(chr2num, s1))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
# 过滤器
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1,2,3,4,5,6]))
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A','','B',None, 'C',' ']))
def prime(lim):
a = [x for x in range(2,lim+1)]
def delnp(num):
# define a odd sequence.
def _odd_iter()
n = 1
while True:
n += 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it)
def is_palindrome(n):
return str(n) == str(n)[::-1]
# sort
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def sortregu1(tup):
return tup[0].lower()
def sortregu2(tup):
return tup[1]
# key指定一个函数fun,每个元素会按照map(fun, L)映射的结果来排序
# reverse指定反向排序
sorted(L, key = sortregu, reverse = True)
#closure
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax += n
return ax
return sum
# 装饰器
def log(func):
def wrapper(*args, **kw):
print('call %s():'% func.__name__)
return func(*args, **kw)
return wrapper
## 相当于执行了now=log(now)=wrapper语句
@log
def now():
print('2018-09-19')
# 高阶装饰器
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('call %s():'% func.__name__)
return func(*args, **kw)
return wrapper
return decorator
## 相当于执行了log('execute'),返回decorator函数,然后执行decorator(log)
@log('execute')
def now():
print('2015-3-25')
## now=log('execute')(log)=decorator(log)=wrapper
## now()=wrapper()=print,log()
# Hanno Tower
def move(n, a, b, c):
if n == 1:
print(a,'>>', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
def cal(num, s=1):
if num == 1:
return s
else:
return cal(num-1, 2*s+1)
a = [[0 for i in range(8)] for i in range(8)]
b = [0 for i in range(8)]
method = 0
def add(x, y):
b[x] = y
for i in range(8):
for j in range(8):
if i == x or j == y or i+j == x+y or x-i == y-j:
a[i][j] += 1
def clear(x, y):
for i in range(8):
for j in range(8):
if i == x or j == y or i+j == x+y or x-i == y-j:
a[i][j] -= 1
def queen(colum):
global method
for i in range(8):
if a[colum][i] == 0:
add(colum, i)
if colum <= 6:
queen(colum+1)
else:
print(b)
method += 1
clear(colum, i)
queen(0)
print('total method:%d'%method)
def queen(A, cur=0):
if cur == len(A):
print(A)
return 0
for col in range(len(A)):
A[cur], flag = col, True
for row in range(cur):
if A[row] == col or abs(col - A[row]) == cur - row:
flag = False
break
if flag:
queen(A, cur+1)
queen([None]*8)
|
5b2267600ac663d2493599080b5bf482511015d3 | nehaDeshp/Python | /Tests/setImitation.py | 623 | 4.25 | 4 | '''
In this exercise, you will create a program that reads words from the user until the
user enters a blank line. After the user enters a blank line your program should display
each word entered by the user exactly once. The words should be displayed in
the same order that they were entered. For example, if the user enters:
first
second
first
third
second
then your program should display:
first
second
third
[ use list ]
'''
list=[]
print("Enter Integers:")
while True:
num = input("")
if(num == " "):
break
elif(list.__contains__(num)):
pass
else:
list.append(num)
print(list) |
a15d13da749137921a636eb4acf2d56a4681131a | nehaDeshp/Python | /Tests/Assignment1.py | 559 | 4.28125 | 4 | '''
Write a program that reads integers from the user and stores them in a list. Your
program should continue reading values until the user enters 0. Then it should display
all of the values entered by the user (except for the 0) in order from smallest to largest,
with one value appearing on each line. Use either the sort method or the sorted
function to sort the list
'''
list=[]
print("Enter Integers:")
while True:
num = int(input(""))
if(num == 0):
break
else:
list.append(num)
#sort
list.sort()
for i in list:
print(i)
|
e5fe9fcfda6f7a9806e45d010088812dd02b030f | Blakeinstein/Python-dev | /sudoku/sudoku.py | 1,839 | 3.640625 | 4 | class Sudoku:
def __init__(self, arr=[[0 for i in range(9)] for j in range(9)]):
self.arr = arr
self.node = [0, 0]
def find(self):
for i in range(0, 9):
for j in range(0, 9):
if self.arr[i][j] == 0:
self.node[0] = i
self.node[1] = j
return True
return False
def ccr(self, row, num):
for i in range(0, 9):
if self.arr[row][i] == num:
return False
return True
def ccc(self, col, num):
for i in range(0, 9):
if self.arr[i][col] == num:
return False
return True
def ccb(self, row, col, num):
for i in range(3):
for j in range(3):
if self.arr[row + i][col + j] == num:
return False
return True
def check(self, row, col, num):
return self.ccr(row, num) and self.ccc(col, num) and self.ccb(row - row%3, col - col%3, num)
def solve(self):
self.node = [0, 0]
if not self.find():
return True
row = self.node[0]
col = self.node[1]
for num in range(0, 10):
if self.check(row, col, num):
self.arr[row][col] = num
if self.solve():
return True
self.arr[row][col] = 0
return False
if __name__ == "__main__":
BOARD = Sudoku([
[8, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 6, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 9, 0, 2, 0, 0],
[0, 5, 0, 0, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 4, 5, 7, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 3, 0],
[0, 0, 1, 0, 0, 0, 0, 6, 8],
[0, 0, 8, 5, 0, 0, 0, 1, 0],
[0, 9, 0, 0, 0, 0, 4, 0, 0]
])
BOARD.solve()
print(BOARD.arr)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.