blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2ea26df8a399edb18cdf6e654ca59e4666d5ee57 | TrellixVulnTeam/Demo_933I | /leetcode/1051.Height Checker.py | 1,566 | 3.921875 | 4 | # Students are asked to stand in non-decreasing order of heights for an annual p
# hoto.
#
# Return the minimum number of students that must move in order for all student
# s to be standing in non-decreasing order of height.
#
# Notice that when a group of students is selected they can reorder in any poss
# ible way between themselves and the non selected students remain on their seats.
#
#
#
# Example 1:
#
#
# Input: heights = [1,1,4,2,1,3]
# Output: 3
# Explanation:
# Current array : [1,1,4,2,1,3]
# Target array : [1,1,1,2,3,4]
# On index 2 (0-based) we have 4 vs 1 so we have to move this student.
# On index 4 (0-based) we have 1 vs 3 so we have to move this student.
# On index 5 (0-based) we have 3 vs 4 so we have to move this student.
#
#
# Example 2:
#
#
# Input: heights = [5,1,2,3,4]
# Output: 5
#
#
# Example 3:
#
#
# Input: heights = [1,2,3,4,5]
# Output: 0
#
#
#
# Constraints:
#
#
# 1 <= heights.length <= 100
# 1 <= heights[i] <= 100
#
# Related Topics Array
# 👍 390 👎 1808
# region data
# 2021-03-23 14:34:17
# endregion
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def heightChecker(self, heights: List[int]) -> int:
res = 0
for x, y in zip(heights, sorted(heights)):
if x != y:
res += 1
return res
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
n = [1, 1, 4, 2, 1, 3]
print(Solution().heightChecker(n))
|
d73d35256c21331087554a753da1f35229fc84bb | nerunerunerune/kenkyushitukadai | /12.py | 453 | 3.96875 | 4 | #ITP1_3_D: How Many Divisors?
#3つの整数 a,b,cを読み込み、aからbまでの整数の中に、cの約数がいくつあるかを求めるプログラムを作成
#Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.
l = input().split()
a = int(l[0])
b = int(l[1])
c = int(l[2])
count = 0
for x in range(a,b+1):
if(c % x == 0):
count = count + 1
print(count) |
d5771aeeb0c5c227ab7905e2a25f704e9d30548b | Quintus-Zhang/Tracer | /cal_ce.py | 5,824 | 3.625 | 4 | from scipy.interpolate import CubicSpline
import pandas as pd
import os
import numpy as np
from functions import utility
from constants import *
from scipy.stats import bernoulli
import matplotlib.pyplot as plt
import sys
def c_func(c_df, COH, age):
""" Given the consumption functions and cash-on-hand at certain age, calculate the corresponding consumption using
the cubic spline interpolation
:param c_df: DataFrame, consumption functions from age 100 to 22
:param COH: array, cash-on-hand in every possible scenario
:param age: scalar
:return: array with same size as COH, consumption
"""
COH = np.where(COH < UPPER_BOUND_COH, COH, UPPER_BOUND_COH) # prevent extrapolation
COH = np.where(COH > 1, COH, 1) # prevent extrapolation
spline = CubicSpline(c_df[str(END_AGE)], c_df[str(age)], bc_type='natural')
C = spline(COH)
if any(C < 0):
# set coeffs of 2nd and 3rd order term to 0, 1st order term to the slope between the first two points
spline.c[:2, 0] = 0
spline.c[2, 0] = (c_df.loc[1, str(age)] - c_df.loc[0, str(age)]) / (c_df.loc[1, str(END_AGE)] - c_df.loc[0, str(END_AGE)])
C = spline(COH) # redo the interpolation
return C
def generate_consumption_process(income_bf_ret, sigma_perm_shock, sigma_tran_shock, c_func_df, *, flag='orig'):
""" Simulate the consumption process and income process
:param income_bf_ret: array with size of (44,), deterministic component of income over the working period
:param sigma_perm_shock: float64, standard deviation of the permanent shock in the log term
:param sigma_tran_shock: float64, standard deviation of the transitory shock in the log term
:param c_func_df: DataFrame, consumption functions from age 100 to 22
:param flag: string, flag var to choose adding details of ISA or Loan or nothing(just the original model)
:return:
c: array with size of N_SIM-by-79, consumption process
inc: array with size of N_SIM-by-79, income process
"""
YEARS = END_AGE - START_AGE + 1
###########################################################################
# simulate income process #
# include both income risks and unemployment risks #
###########################################################################
# add income risks - generate the random walk and normal r.v.
# - before retirement
rn_perm = np.random.normal(MU, sigma_perm_shock, (N_SIM, RETIRE_AGE - START_AGE + 1))
rand_walk = np.cumsum(rn_perm, axis=1)
rn_tran = np.random.normal(MU, sigma_tran_shock, (N_SIM, RETIRE_AGE - START_AGE + 1))
inc_with_inc_risk = np.multiply(np.exp(rand_walk) * np.exp(rn_tran), income_bf_ret)
# - retirement TODO: wrong here but not affect the CE, get rid of the transitory shock
ret_income_vec = ret_frac[AltDeg] * np.tile(inc_with_inc_risk[:, -1], (END_AGE - RETIRE_AGE, 1)).T
inc_with_inc_risk = np.append(inc_with_inc_risk, ret_income_vec, axis=1)
# add unemployment risks - generate bernoulli random variables
p = 1 - unempl_rate[AltDeg]
r = bernoulli.rvs(p, size=(RETIRE_AGE - START_AGE + 1, N_SIM)).astype(float)
r[r == 0] = unemp_frac[AltDeg]
ones = np.ones((END_AGE - RETIRE_AGE, N_SIM))
bern = np.append(r, ones, axis=0)
inc = np.multiply(inc_with_inc_risk, bern.T)
# ISA, Loan or orig
if flag == 'rho':
inc[:, :TERM] *= rho
elif flag == 'ppt':
inc[:, :TERM] -= ppt
else:
pass
################################################################################
# COH_t+1 = (1 + R)*(COH_t - C_t) + Y_t+1 #
# wealth = (1 + R)*(COH_t - C_t) #
################################################################################
cash_on_hand = np.zeros((N_SIM, YEARS))
c = np.zeros((N_SIM, YEARS))
cash_on_hand[:, 0] = INIT_WEALTH + inc[:, 0] # cash on hand at age 22
# 0-77, calculate consumption from 22 to 99, cash on hand from 23 to 100
for t in range(YEARS - 1):
c[:, t] = c_func(c_func_df, cash_on_hand[:, t], t + START_AGE)
cash_on_hand[:, t+1] = (1 + R) * (cash_on_hand[:, t] - c[:, t]) + inc[:, t+1] # 1-78
c[:, -1] = c_func(c_func_df, cash_on_hand[:, -1], END_AGE) # consumption at age 100
# # GRAPH - Average Cash-on-hand & consumption over lifetime
# plt.plot(cash_on_hand.mean(axis=0), label='cash-on-hand')
# plt.plot(c.mean(axis=0), label='consumption')
# plt.title(f'Average Cash-on-hand and Consumption over the life cycle\n UPPER_BOUND_COH = {UPPER_BOUND_COH}')
# plt.xlabel('Age')
# plt.ylabel('Dollar')
# plt.legend()
# plt.grid()
# plt.show()
return c, inc
def cal_certainty_equi(prob, c):
""" Calculate consumption CE and wealth CE
:param prob: array with size of (78,), conditional survival probability
:param c: array with size of , consumption process
:return:
c_ce: float64, consumption CE
total_w_ce: float64, total wealth CE
"""
# discount factor
YEARS = END_AGE - START_AGE + 1
delta = np.ones((YEARS, 1)) * DELTA
delta[0] = 1
delta = np.cumprod(delta)
util_c = np.apply_along_axis(utility, 1, c, GAMMA)
simu_util = np.sum(np.multiply(util_c[:, :44], (delta * prob)[:44]), axis=1)
if GAMMA == 1:
c_ce = np.exp(np.mean(simu_util) / np.sum((delta * prob)[:44])) # inverse function of CARA
else:
c_ce = ((1 - GAMMA) * np.mean(simu_util) / np.sum((delta * prob)[:44]))**(1 / (1-GAMMA)) # inverse function of CARA
total_w_ce = prob[:44].sum() * c_ce # 42.7
return c_ce, total_w_ce
|
32886398095c9b89930372cbd0b81743e34f8a99 | bvsbrk/Algos | /src/Codeforces/round__463/A.py | 250 | 3.625 | 4 | def isPal(s):
for i in range(len(s) // 2):
if s[i] != s[len(s) - i - 1]:
return False
return True
if __name__ == '__main__':
s = input().strip()
if isPal(s):
print(s)
else:
print(s + s[::-1])
|
63156d3bcd6a9e1f65c9cca8c86eca4f35816a1d | AyushPandhi/Pandhi_Ayush_Assignment1 | /question1/replace.py | 462 | 3.59375 | 4 | #!/usr/bin/env python
import os
import sys
import glob
if len(sys.argv) != 3:
raise ValueError('replace.py takes 2 arguments')
find = sys.argv[1]
replace = sys.argv[2]
if not os.path.exists(replace):
os.mkdir(replace)
for filename in glob.glob('*.txt'):
with open(filename, 'r') as f:
text = f.read()
replaced = text.replace(find, replace)
with open(os.path.join(replace, filename), 'w') as f:
f.write(replaced)
|
4bcd949f491bd5839bc9aa630ac3ed37bd810b4c | NiaOrg/NiaPy | /niapy/util/random.py | 759 | 3.5 | 4 | import math
import numpy as np
__all__ = ['levy_flight']
def levy_flight(rng, alpha=0.01, beta=1.5, size=None):
"""Compute levy flight.
Args:
alpha (float): Scaling factor.
beta (float): Stability parameter in range (0, 2).
size (Optional[Union[int, Iterable[int]]]: Output size.
rng (numpy.random.Generator): Random number generator.
Returns:
Union[float, numpy.ndarray]: Sample(s) from a truncated levy distribution.
"""
sigma = (math.gamma(1 + beta) * np.sin(np.pi * beta / 2) / (math.gamma((1 + beta) / 2) * beta * 2 ** ((beta - 1) / 2))) ** (1 / beta)
u = rng.normal(0, sigma, size)
v = rng.normal(0, 1, size)
sample = alpha * u / (np.abs(v) ** (1 / beta))
return sample
|
3539b478637f459f5f2e8aecb9d7b5bb02303ba5 | textvrbrln/monopoly | /mnp/pylogic/player.py | 2,902 | 4.03125 | 4 | #!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import random
"""Set up all players"""
player_minimum = 2
player_maximum = 4
first_player = 1
player_name_max_length = 12
playerlist = []
addplayer = []
onfield = [0]
double = [0]
move_fwd = 0
dice_result = [0]
def add_number_of_players():
chose_players = input(
"Zahl der Spieler "
"(["+str(player_minimum)+"] "
"bis ["+str(player_maximum)+"]): ")
check_input(chose_players)
def check_input(chose_players):
try:
chose_players = int(chose_players)
evaluate_input(chose_players)
except ValueError:
print("Bitte eine Zahl eingeben!")
add_number_of_players()
def evaluate_input(chose_players):
if int(chose_players) < player_minimum:
print("Zahl zu klein.")
add_number_of_players()
elif int(chose_players) > player_maximum:
print("Zahl zu groß.")
add_number_of_players()
else:
# we need to add one player for the range statement
number_of_players = ((int(chose_players)+1))
name_players(number_of_players)
def name_players(number_of_players):
for player in list(range(first_player,number_of_players)):
add_playernames(player)
def add_playernames(player):
addplayer = input(
"Bitte wähle einen Namen"
" für Spieler "+str(player)+" "
"(nur Buchstaben): ")
if addplayer and len(addplayer) > player_name_max_length:
print(
"Bitte nicht mehr als "
""+str(player_name_max_length)+" "
"Buchstaben eingeben.")
add_playernames(int(player))
else:
add_player(addplayer)
print("Spieler "+str(player)+" heißt "+str(addplayer)+"!")
def add_player(addplayer):
playerlist.append(addplayer)
return playerlist
class Playerclass:
def __init__(self, name, credit):
self.name = name
self.credit = credit
def throw_dice(self):
'''Throw two dice, add result and return'''
dice1 = random.randrange(1, 7)
dice2 = random.randrange(1, 7)
result_of_dices = ((dice1 + dice2))
# check for double
if dice1 == dice2:
double[0] = 1
else:
double[0] = 0
return result_of_dices
def move_forward(self):
dice_result[0] = Playerclass.throw_dice(self)
move_fwd = ((onfield[0] + dice_result[0]))
if move_fwd > 12:
move_fwd = ((onfield[0] + dice_result[0] - 12))
onfield[0] = move_fwd
return move_fwd
else:
onfield[0] = move_fwd
return move_fwd |
c04c7eecb8953c2befb50520f45bea4b0c76dde7 | Hammad214508/Quarantine-Coding | /30-Day-LeetCoding-Challenge/June/Week1/5-RandomPickWithWeight.py | 1,757 | 3.921875 | 4 | """
Given an array w of positive integers, where w[i] describes the weight of index i,
write a function pickIndex which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex will be called at most 10000 times.
Example 1:
Input:
["Solution","pickIndex"]
[[[1]],[]]
Output: [null,0]
Example 2:
Input:
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument,
the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any.
"""
import random
# TIME LIMIT EXCEEDED
# class Solution:
#
# def __init__(self, w: [int]):
# self.weight = w
# n = len(self.weight)
# self.newList = []
# for i in range(n):
# self.newList += self.weight[i]*[i]
# self.length = len(self.newList)
#
# def pickIndex(self) -> int:
# ran = random.randint(0, self.length-1)
# return self.newList[ran]
class Solution:
def __init__(self, w: [int]):
total = 0
self.sums = []
for weight in w:
total += weight
self.sums.append(total)
def pickIndex(self) -> int:
ran = self.sums[-1] * random.random()
low = 0
high = len(self.sums)
while low<high:
mid = low+(high-low)//2
if ran > self.sums[mid]:
low = mid+1
else:
high = mid
return low
w = [3, 1]
solution = Solution(w)
param_1 = solution.pickIndex()
print(param_1)
|
134368161257adf6f24f9aaa632fa033496cb746 | VanessaPC/Python-programs | /Python/guess-number/GuessNumber.py | 759 | 3.96875 | 4 | oGuesses = 0
print('Hello! What is your name?')
myName = input()
number = random.number(1,20)
print('Ok '+ myName + ', I am thinking of a number between 1 and 20. You have 5 guesses.')
while guessesTake < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
noGuesses +=1
if guess<number:
print('almost, try a bit higher.')
if guess>number:
print('almost, try a bit lower.')
if guess==number:
print('Excellent!You won!')
break
if guess==number:
guessesTaken = str(noGuesses)
print('This is the number of guesses it took you ' + guessesTaken +'Taken. Congrats')
if guess != number:
number = str(number)
print('Nope, the number you were looking for was' + number + 'Try
|
351b50731a8850b94e70e2d33b041e22969d8cb6 | DominikaJastrzebska/Kurs_Python | /02_instrukcje_sterujace/examples_break_continue.py | 866 | 3.875 | 4 | '''
Chcemy znaleźć liczby pierwsze, w tym celu potrzebujemy 2 pętli for:
'''
for current_num in range(2, 10):
for x in range(2, current_num):
if current_num % x == 0:
print(current_num, 'equals', x, '*', current_num // x)
# znaleziono dzielnik!!! - możemy przejść do kolejnej cuurrent_num
# pomijając sprawdzanie x
break
else:
# nie znaleziono dzielnika
print(current_num, 'can\'t be divided by', x)
print('-------------')
for val in "string":
if val == "i":
break
print(val)
print("Koniec")
print('--------------')
for val in "string":
if val == "i":
print('lalala')
continue
print(val)
print("Koniec")
print('---------------')
for val in "string":
if val == "i":
print('lalala')
print(val)
print("Koniec") |
4a02a800e0989094d4d13f7126d2cf7a407b51a7 | srinathalla/python | /algo/dfs/makingALargeIsland.py | 1,352 | 3.546875 | 4 | from typing import List
from collections import defaultdict
class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
map = defaultdict(int)
map[0] = 0
n = len(grid)
m = len(grid[0])
def paint(i, j, color):
if 0 <= i < n and 0 <= j < m and grid[i][j] == 1:
grid[i][j] = color
return 1 + paint(i+1, j, color) + paint(i-1, j, color) + paint(i, j+1, color) + paint(i, j-1, color)
else:
return 0
color = 2
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
map[color] = paint(i, j, color)
color += 1
res = map.get(2, 0)
for i in range(n):
for j in range(m):
if grid[i][j] == 0:
cells = set()
cells.add(grid[i+1][j] if i < n - 1 else 0)
cells.add(grid[i-1][j] if i > 0 else 0)
cells.add(grid[i][j + 1] if j < m - 1 else 0)
cells.add(grid[i][j - 1] if j > 0 else 0)
val = 1
for c in cells:
val += map[c]
res = max(res, val)
return res
s = Solution()
print(s.largestIsland([[1, 1], [1, 1]]))
|
bd963eac8996793ec8f6dc1727cbaff65bbce9c0 | daftstar/learn_python | /01_MIT_Learning/week_3/lectures_and_examples/more_dictionaries.py | 1,832 | 4.3125 | 4 | animals = {
'a': ['aardvark'],
'b': ['baboon'],
'c': ['coati'],
'd': ['donkey', 'dog', 'dingo']
}
# Return the sum of the number of values associated
# with a dictionary. For example: print(how_many(animals)) = 6
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
count = 0
for i in aDict.values():
count += len(i)
return (count)
# print(how_many(animals))
# print ()
# Return the key corresponding to the entry with the largest
# number of values associated to it. If there is more than one
# such entry, return any one of the matching keys.
# For example, biggest(animals) returns 'd'
def biggest(aDict):
result = None
biggest = 0
for key in aDict:
if len(aDict[key]) > biggest:
result = key
biggest = len(aDict[key])
return (result)
print (biggest(animals))
# ANOTHER WAY OF biggest :: LESS EFFICIENCT
# def biggest(aDict):
# '''
# aDict: A dictionary, where all the values are lists.
# returns: The key with the largest number of values associated with it
# '''
# myDict = {} # {lyric, instance}
# best = len(max(aDict.values()))
# # print (best)
# for key, value in aDict.items():
# if len(value) == best:
# myDict[key] = value
# for i in myDict:
# return i
# print (biggest(animals))
# ANOTHER WAY OF how_many :: LESS EFFICIENCT
# def how_many(aDict):
# '''
# aDict: A dictionary, where all the values are lists.
# returns: int, how many values are in the dictionary.
# '''
# count = 0
# for a, b in aDict.items():
# for i in b:
# count += 1
# return (count)
|
d1497f8d79d9045b52a2b2ca5184ba7855bf3c90 | Shivani-Kushwah-ML/PythonExercise | /vowels.py | 255 | 4.0625 | 4 | '''
5.Write a Python program to create all possible strings by
using 'a', 'e', 'i', 'o', 'u'. Use the characters exactly once.
'''
from itertools import permutations
l=['a','e','i','o','u']
p = permutations(l)
for i in list(p):
print (i)
|
bfd1205e472b77330dd5b44b8c6275b5483d38ed | jokamoto1/bank | /file.py | 1,529 | 3.828125 | 4 | class BankAccount:
def __init__(self, name):
self.int_rate = .01
self.balance = 0
self.name = name
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print(self.name + "'s balance: $" +str(self.balance))
return self
def yield_interest(self):
self.balance = self.balance + (self.balance * self.int_rate)
return self
def transfer(self, other_user, amount):
self.balance -= amount
other_user.balance += amount
return self
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.balance = 0
BankAccount
def make_deposit(self, amount):
self.balance += amount
return self
def make_withdrawl(self, amount):
self.balance -= amount
return self
def display_user_balance(self):
print(self.name + "'s balance: " +str(self.balance))
return self
def transfer_money(self, other_user, amount):
self.balance -= amount
other_user.balance += amount
return self
jeremy = BankAccount("Jeremy")
jeremy.deposit(500).deposit(300).deposit(200).withdraw(500).yield_interest().display_account_info()
bob = BankAccount("bob")
bob.deposit(4000).deposit(4000).withdraw(2000).withdraw(2000).withdraw(2000).withdraw(1000).yield_interest().display_account_info()
|
264c9eb4f5e97f6f2157939f4b09f595db28dbf2 | inwk6312fall2018/model-open-book-quiz-Adityapuni | /task1.py | 3,735 | 3.546875 | 4 | import sys
import pyCardDeck
from typing import List
from pyCardDeck.cards import PokerCard
class Player:
def __init__(self, name: str):
self.arm= []
self.naam = name
def __str__(self):
return self.naam
class BlackjackGame:
def __init__(self, players: List[Player]):
self.dome = pyCardDeck.Deck()
self.dome.load_standard_deck()
self.players = players
self.scores = {}
print("Created a game with {} players.".format(len(self.players)))
def blackjack(self):
"""
this is the sequence.
Each player gets 5 player
if every one didnt won the person closest to 21 won
"""
print("Settiing the cards")
print("Shuffling the cards")
self.dome.shuffle()
print("this is shuffled")
print("Dealing the cards")
self.deal()
print("\n now play")
for player in self.players:
print("{} its your turn".format(player.naam))
self.play(player)
else:
print("the last turn")
self.find_winner()
def deal(self):
"""
Deals five cards to each player.
"""
for _ in range(5):
for p in self.players:
newcard = self.dome.draw()
p.hand.append(newcard)
print("Dealt {} the {}.".format(p.naam, str(newcard)))
def find_winner(self):
"""
Finds the highest score, then finds which player(s) have that score,
and reports them as the winner.
"""
winners = []
try:
win_score = max(self.scores.values())
for key in self.scores.keys():
if self.scores[key] == win_score:
winners.append(key)
else:
pass
wins_tring = " & ".join(win.ners)
print("And the winner is...{}!".format(win.string))
except ValueError:
print("no one wins lets play again")
def hit(self, player):
"""
Adds a card to the player's hand and states which card was drawn.
"""
new_card = self.dome.draw()
player.hand.append(new_card)
print(" he Drew the {}.".format(str(newcard)))
def play(self, player):
'''based on their current score.'''
while True:
points = sum_hand(player.hand)
if points < 17:
print(" Hit.")
self.hit(player)
elif points == 21:
print(" {} wins!".format(player.naam))
sys.exit(0) # End if someone wins
elif points > 21:
print(" Bust!")
break
else: # Stand if between 17 and 20 (inclusive)
print(" this sitting at {} points.".format(str(points)))
self.scores[player.naam] = points
break
def sum_hand(hand: list):
vals = [card.rank for card in hand]
intvals = []
while len(vals) > 0:
value = vals.pop()
try:
intvals.append(int(value))
except ValueError:
if value in ['K', 'Q', 'J']:
intvals.append(10)
elif value == 'A':
intvals.append(1) # Keep it simple for the sake of example
if intvals == [1, 10] or intvals == [10, 1]:
print(" Blackjack!")
return(21)
else:
points = sum(intvals)
print(" Current score: {}".format(str(points)))
return(points)
if __naam__ == "__main__":
game = BlackjackGame([Player("jai"), Player("mata"), Player("di"),
Player("jaiho)])
game.blackjack()
|
91e1cc3c684df73cbddb8d46234825fa9a1eb9ff | dm36/interview-practice | /daily_practice/july_7th_2019/common_prefix_length.py | 2,493 | 4.03125 | 4 | # generate all suffixes of the string
# get the longest prefix match
#
# def commonPrefix(my_string):
# suffixes = []
# count = 0
# for i in range(len(my_string)):
# suffixes.append(my_string[i:])
#
# for suffix in suffixes:
# count += longest_prefix_match(my_string, suffix)
#
# return [count]
#
#
# def longest_prefix_match(my_string, suffix):
# i, j = 0, 0
# count = 0
#
# while i < len(my_string) and j < len(suffix) and my_string[i] == suffix[j]:
# i += 1
# j += 1
# count += 1
#
# return count
# def commonPrefix(my_string):
# suffixes = []
# count = 0
# for i in range(len(my_string)):
# suffixes.append(my_string[i:])
#
# for suffix in suffixes:
# count += longest_prefix_match(my_string, suffix)
#
# return count
#
#
# def longest_prefix_match(my_string, suffix):
# i, j = 0, 0
# count = 0
#
# while i < len(my_string) and j < len(suffix) and my_string[i] == suffix[j]:
# i += 1
# j += 1
# count += 1
#
# return count
# print longest_prefix_match("ababaa", "babaa")
#!/bin/python
# import math
# import os
# import random
# import re
# import sys
#
# Complete the 'commonPrefix' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts STRING_ARRAY inputs as parameter.
#
# def commonPrefix(my_string):
# suffixes = []
# final_arr = []
# count = 0
# my_string = my_string[0]
# for i in range(len(my_string)):
# suffixes.append(my_string[i:])
# print suffixes
# for suffix in suffixes:
# count += longest_prefix_match(my_string, suffix)
#
# return [count]
#
#
# def longest_prefix_match(my_string, suffix):
# i, j = 0, 0
# count = 0
#
# while i < len(my_string) and j < len(suffix) and my_string[i] == suffix[j]:
# i += 1
# j += 1
# count += 1
#
# return count
#
#
# if __name__ == '__main__':
#
def longestCommonPrefix(strs):
longest_pre = ""
if not strs: return longest_pre
shortest_str = min(strs, key=len)
for i in range(len(shortest_str)):
print x.startswith(shortest_str[:i+1])
# if all([x.startswith(shortest_str[:i+1]) for x in strs]):
# longest_pre = shortest_str[:i+1]
# else:
# break
return longest_pre
print longestCommonPrefix(["flower", "flow", "flight"])
# print commonPrefix("ababaa")
# print commonPrefix("aa")
|
0e7586bc645d8ba9daf0d6e0e54ccf6ac4fa55b2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4501/codes/1594_1805.py | 184 | 3.546875 | 4 | xA=float(input("Ax: "))
yA=float(input("Ay: "))
xB=float(input("Bx: "))
yB=float(input("By: "))
xm=(((xB) + (xA))/(2))
ym=(((yB) + (yA))/(2))
print(round(xm, 1))
print(round(ym, 1))
|
6774c0f53e6bb8b118f08e79ddc6346a083cf862 | amailk/MovieWebsite | /media.py | 1,411 | 3.640625 | 4 | import webbrowser
class Video():
"""Describes a Video"""
def __init__(self, title, main_actors, storyline, poster_image):
"""Initializes a Video object"""
self.title = title
self.main_actors = main_actors
self.storyline = storyline
self.poster_image_url = poster_image
def is_movie(self):
"""Determine if a Video is a Tvshow or a Movie"""
pass
class Tvshow(Video):
"""Describes a Video which is a Tvshow with channel information"""
def __init__(self, title, main_actors, storyline, poster_image, channel):
"""Initializes the Tvshow object"""
Video.__init__(self, title, main_actors, storyline, poster_image)
self.channel = channel
def is_movie(self):
"""Returns that this is not a movie"""
return False
class Movie(Video):
"""Describes a Video which is a Movie with a youtube trailer"""
def __init__(self, title, main_actors, storyline, poster_image,
trailer_youtube):
"""Initializes the Movie object"""
Video.__init__(self, title, main_actors, storyline, poster_image)
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
"""Opens the trailer of a Movie object"""
webbrowser.open(self.trailer_youtube_url)
def is_movie(self):
"""Returns that this is a movie"""
return True
|
9f0be72b00b104113a051a6fdc1fcec73ee9998c | tykm/grokking | /binary_search/binary_search.py | 872 | 3.78125 | 4 | from generate_ordered_array import generate
ordered_array = generate(100000000)
#print(ordered_array)
print("starting")
def binary_search_iter(arr: list[int], target: int):
low = 0
high = len(arr) - 1
guess_index = (low + high) // 2
guess = arr[guess_index]
while guess != target:
if guess > target:
high = guess_index - 1
else:
low = guess_index + 1
guess_index = (high + low) // 2
guess = arr[guess_index]
return guess
print(binary_search_iter(ordered_array, 90000000))
i = 0
num = ordered_array[i]
while num != 90000000:
i+=1
num = ordered_array[i]
print(num)
'''
Cases:
Array Even:
Target Lower:
Target Even:
arr = 8
target = 2
Target Odd:
arr = 8
target = 3
Array Odd:
''' |
4f3a4fd5e54f8ecb02d8ef51c3d31f254c906ae9 | xanderyzwich/Playground | /python/tools/lists/combine.py | 1,512 | 4.1875 | 4 | """
Combine Alternating Lists
Write a method that combines two lists by alternatingly taking elements.
For example: given the two lists [a, b, c] and [1, 2, 3]
the method should return [a, 1, b, 2, c, 3]
"""
from unittest import TestCase
def combine_alternating(input_a, input_b):
list_a, list_b = input_a[::-1], input_b[::-1]
list_c = []
for i in range(max(len(input_a), len(input_b))):
if i < len(input_a):
list_c.append(list_a.pop())
if i < len(input_b):
list_c.append(list_b.pop())
return list_c
def combine_alternating_alternate(input_a, input_b):
import itertools
# return [y for x in itertools.zip_longest(input_a, input_b) for y in x if y is not None]
return [y for x in itertools.zip_longest(input_a, input_b) for y in x if y]
class TestCombineAlternating(TestCase):
data = [
{
'arg1': ['a', 'b', 'c', 'd', 'e'],
'arg2': ['1', '2', '3'],
'expected': ['a', '1', 'b', '2', 'c', '3', 'd', 'e'],
},
{
'arg1': ['a', 'b', 'c'],
'arg2': ['1', '2', '3'],
'expected': ['a', '1', 'b', '2', 'c', '3']
}
]
def test_data(self):
for t in self.data:
assert combine_alternating(t['arg1'], t['arg2']) == t['expected']
# print('', combine_alternating(t['arg1'], t['arg2']))
# print('', combine_alternating_alternate(t['arg1'], t['arg2']))
|
a0af9f14151953fd38565282ad142dd49e638f51 | ExtraBoldDin/pythonCourse | /s1/s1e3.py | 95 | 3.84375 | 4 | #
# lesson 1 task 3
# division of apples
#
n = int(input())
k = int(input())
print(k//n, k%n) |
4af174ebf3f4f7cf968ec08ae76ba5fefa5fc306 | dlqjaen/Algorithm | /jy/hello.py | 2,238 | 4.125 | 4 | print("5"+"8")
# %는 나머지, 나누기는 소수형★
# 버림 나눗셈
# 큰따옴표는 작은 따옴표로 감쌀 수 있다. print('가나다라 "마바사" 아자차') 이런식으로
#역슬래시(\) 사용하면 문자열 내에서 따옴표를 제대로 인식할 수 있다.
#.format -> {:.1f} :소수점 첫째자리까지만
print(7//2)
print(8//3)
print(float(3))
print(int("2")+int("5"))
print(str(2)+str(5))
age=7
print("제 나이는 " +str(age)+ "살입니다")
print("저는 {},{} 를 좋아합니다".format("유재석","박지성"))
num_1=1
num_2=3
print("{0} 나누기 {1}은 {2:.1f}입니다.".format(num_1,num_2,num_1/num_2))
#불대수의 연산 And(하나라도 거짓이면 거짓), or(하나라도 참이면 참), not(참이면 거짓, 거짓이면 참)
print(True and True)
print(2!=2)
print(type(4/2))
def hello(name):
print(f"안녕하세요. {name}입니다")
return "만나서 반갑습니다."
#return 없으면 none으로 나옴
print(hello("영훈"))
x=2
#글로벌 변수:함수밖에서 정의 ,모든 곳에서 사용 가능
def my_function():
x=3
#로컬변수 :함수내에서만 사용할 수 있는 변수/ 함수에서 변수를 사용하면, 로컬 변수를 먼저 찾고 나서 글로벌 변수를 찾음음 print(x)
my_function()
print(x)
#파라미터도 로컬 변수
#상수(constant) -되도록 대문자로 표시(바꾸지 않겠다는 뜻)
PI=3.14
#반지름을 받아서 원의 넓이 계산
def calculate_area(r):
return PI*r*r
radius=4
print("반지름이 {}면, 넓이는 {}".format(radius,calculate_area(radius)))
#함수안에는 프린트문이 아닌 리턴문 사용
#추상화
#14.거스름돈 계산기
#yeonii
def calculate_change(payment, cost):
change = payment-cost
a = change//50000
b = (change-50000*a)//10000
c = (change-50000*a-10000*b)//5000
d = (change-50000*a-10000*b-5000*c)//1000
print("50000원 지폐 : {}장".format(a))
print("10000원 지폐 : {}장".format(b))
print("5000원 지폐 : {}장".format(c))
print("1000원 지폐 : {}장".format(d))
calculate_change(100000, 33000)
print()
calculate_change(500000, 378000)
#변수이름 잘 정의(fifty_count등)
#%이용하기
|
002254432c3cbd6fee0e6d7657b5d6a5f929a599 | IvanYerkinov/CS1.2GitRepo | /sourcetext.py | 631 | 3.5625 | 4 | import sys
def histogram(longstring):
string = longstring.split(" ")
di = dict()
for st in string:
if st in di:
di[st] += 1
else:
di[st] = 1
return di
def unique_words(hist):
i = 0
for key in hist:
if hist[key] == 1:
i += 1
return i
def frequency(hist, word):
return hist[word]
def get_file(filename):
with open(filename, 'r') as f:
data = f.read().replace("\n", "")
return data
if __name__ == "__main__":
his = histogram(get_file(sys.argv[1]))
print(unique_words(his))
print(frequency(his, "and"))
|
c6cd84b4880b4e4046596871f1b7e54b8ae239e2 | bigeast/ProjectEuler | /(#74)FactorialPattern.py | 885 | 3.5625 | 4 | import math
def main():
x=12
counter=0
array=[]
while x<1000000:
array=[]
if x==1000:
print time.time()-t
print "1000"
if x==10000:
print time.time()-t
print "10000"
if x==500000:
print time.time()-t
print "half"
#print x
y=str(x)
#print y
count=0
while not array.__contains__(y):
array.append(y)
fact=0
#print y
for b in y:
fact+=math.factorial(int(b))
count+=1
y=str(fact)
#print y
if count==60:
#print count
counter+=1
#print "counter plus 1"
break
#print x, count
x+=1
#print x
print counter
main()
|
4a0541c9381cfd553f8466e2742f470bd7991441 | JohannesBuchner/pystrict3 | /tests/expect-fail23/recipe-576686.py | 4,671 | 3.765625 | 4 | #!/usr/bin/env python
'''
A set of functions for quick financial analysis of an investment
opportunity and a series of projected cashflows.
For further details and pros/cons of each function please refer
to the respective wikipedia page:
payback_period
http://en.wikipedia.org/wiki/Payback_period
net present value
http://en.wikipedia.org/wiki/Net_present_value
internal rate of return
http://en.wikipedia.org/wiki/Internal_rate_of_return
'''
import sys, locale
def payback_of_investment(investment, cashflows):
"""The payback period refers to the length of time required
for an investment to have its initial cost recovered.
>>> payback_of_investment(200.0, [60.0, 60.0, 70.0, 90.0])
3.1111111111111112
"""
total, years, cumulative = 0.0, 0, []
if not cashflows or (sum(cashflows) < investment):
raise Exception("insufficient cashflows")
for cashflow in cashflows:
total += cashflow
if total < investment:
years += 1
cumulative.append(total)
A = years
B = investment - cumulative[years-1]
C = cumulative[years] - cumulative[years-1]
return A + (B/C)
def payback(cashflows):
"""The payback period refers to the length of time required
for an investment to have its initial cost recovered.
(This version accepts a list of cashflows)
>>> payback([-200.0, 60.0, 60.0, 70.0, 90.0])
3.1111111111111112
"""
investment, cashflows = cashflows[0], cashflows[1:]
if investment < 0 : investment = -investment
return payback_of_investment(investment, cashflows)
def npv(rate, cashflows):
"""The total present value of a time series of cash flows.
>>> npv(0.1, [-100.0, 60.0, 60.0, 60.0])
49.211119459053322
"""
total = 0.0
for i, cashflow in enumerate(cashflows):
total += cashflow / (1 + rate)**i
return total
def irr(cashflows, iterations=100):
"""The IRR or Internal Rate of Return is the annualized effective
compounded return rate which can be earned on the invested
capital, i.e., the yield on the investment.
>>> irr([-100.0, 60.0, 60.0, 60.0])
0.36309653947517645
"""
rate = 1.0
investment = cashflows[0]
for i in range(1, iterations+1):
rate *= (1 - npv(rate, cashflows) / investment)
return rate
# enable placing commas in thousands
locale.setlocale(locale.LC_ALL, "")
# convenience function to place commas in thousands
format = lambda x: locale.format('%d', x, True)
def investment_analysis(discount_rate, cashflows):
"""Provides summary investment analysis on a list of cashflows
and a discount_rate.
Assumes that the first element of the list (i.e. at period 0)
is the initial investment with a negative float value.
"""
_npv = npv(discount_rate, cashflows)
ts = [('year', 'cashflow')] + [(str(x), format(y)) for (x,y) in zip(
list(range(len(cashflows))), cashflows)]
print("-" * 70)
for y,c in ts:
print(y + (len(c) - len(y) + 1)*' ', end=' ')
print()
for y,c in ts:
print(c + ' ', end=' ')
print()
print()
print("Discount Rate: %.1f%%" % (discount_rate * 100))
print()
print("Payback: %.2f years" % payback(cashflows))
print(" IRR: %.2f%%" % (irr(cashflows) * 100))
print(" NPV: %s" % format(_npv))
print()
print("==> %s investment of %s" % (
("Approve" if _npv > 0 else "Do Not Approve"), format(-cashflows[0])))
print("-" * 70)
def main(inputs):
"""commandline entry point
"""
usage = '''Provides analysis of an investment and a series of cashflows.
usage: invest discount_rate [cashflow0, cashflow1, ..., cashflowN]
where
discount_rate is the rate used to discount future cashflows
to their present values
cashflow0 is the investment amount (always a negative value)
cashflow1 .. cashflowN values can be positive (net inflows)
or
negative (net outflows)
for example:
invest 0.05 -10000 6000 6000 6000
'''
try:
rate, cashflows = inputs[0], inputs[1:]
investment_analysis(float(rate), [float(c) for c in cashflows])
except IndexError:
print(usage)
sys.exit()
if __name__ == '__main__':
debug = False
if debug:
import doctest
doctest.testmod()
else:
main(sys.argv[1:])
|
bc659e6863b16e2b9119649db4913c4e87b6cb98 | ivnxyz/evaluador-expresiones-algebraicas | /Stack.py | 1,653 | 4.09375 | 4 | # Clase Nodo para el Stack
class Node:
# data es el dato a guardar y next es el siguiente nodo
def __init__(self, data, next = None):
self.data = data
self.next = next
# Estructura para el Stack
class Stack:
head:Node = None
# 'empuja' un nuevo nodo
def push(self, data):
# Crear nodo
new_node = Node(data)
# Empujar nodo
if self.is_empty():
self.head = new_node
else:
# Iterar hasta el último elemento
temp = self.head
while temp.next != None:
temp = temp.next
# Agregar nuevo nodo
temp.next = new_node
# Elimina el último nodo
def pop(self) -> Node:
# Verificar si hay nodos
if self.is_empty():
raise Exception("No hay elementos en el Stack")
# Iterar hasta el penúltimo nodo
last = self.head
current = self.head
while current.next != None:
last = current
current = current.next
# Eliminar último nodo
if last.next == None:
self.head = None
else:
last.next = None
return current
# Obtiene el último nodo sin eliminarlo
def last(self) -> Node:
last_node = self.head
while last_node.next != None:
last_node = last_node.next
return last_node
# Verifica si el stack está vacío
def is_empty(self) -> bool:
return self.head == None
# Sobreescribe la función str para imprimir un stack
def __str__(self):
node = self.head
string_representation = ''
while node != None:
string_representation = '[ {} ]\n'.format(node.data) + string_representation
node = node.next
return string_representation
|
8f006e7b1d646ebce395d9a4b4543f12c1613d3c | bhatkrishna/assignment | /assignment/pfun5.py | 305 | 4.46875 | 4 | # 5. Write a Python function to calculate the factorial of a number (a non-negative
# integer). The function accepts the number as an argument.
def factorial(a):
if a==0:
return 1
else:
return a*factorial(a-1)
n=int(input("input number:"))
print("the factorial isa:",factorial(n))
|
8ec45b75d06701a80efadd654746e443aa4cc36b | balajipcbe/vega | /coding/largest_row_value_tree.py | 993 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
largestvalues = []
queue = []
if root is None:
return list()
queue.append(root)
while len(queue) > 0:
largestvalues.append(find_max(queue))
n = len(queue)
for i in range(0,n):
if queue[i].left != None:
queue.append(queue[i].left)
if queue[i].right != None:
queue.append(queue[i].right)
queue = queue[n:]
return largestvalues
def find_max(queue):
max_element = -(sys.maxsize-1)
for i in range(len(queue)):
if max_element < queue[i].val:
max_element = queue[i].val
return max_element
|
84dffc02c5f474a303469ab891a0d4b7ba7a7f5c | dprgarner/codejam | /2017/qualification/stalls.py | 3,125 | 3.75 | 4 | from codejam import CodeJamParser
from math import log2
"""
When a person occupies a "block" (consecutive set of unoccupied stalls),
the block is divided into two parts, which differ in size by zero or one.
Given a number of stalls, we can draw a binary tree of the sizes of the
blocks and their consecutive dividings. As, within each level, the sizes of the
blocks can only differ by at most one, we can calculate iteratively
in logarithmic time the size of the block that the kth person will enter.
From this, we can read off the values of max {max(L_s, R_s)} and
max {min(L_s, R_s)}.
"""
def get_level(k):
"""
The kth person to enter the bathroom will pick a stall on this 'level',
with levels starting from zero.
If there are 2^(n-1) <= N < 2^n bathrooms, then there are n levels.
"""
return int(log2(k))
def get_next_level(c, p, q):
"""
If a 'level' has p blocks of stalls of size c and q blocks of stalls of
size c+1, then what is the value of c, p, q for the next level?
"""
return (
(int(c / 2) - 1, p, p + 2 * q)
if c % 2 == 0
else (int((c - 1) / 2), 2 * p + q, q)
)
def get_level_profile(n, l):
"""
Get respective stall sizes and numbers for level l, when there are n stalls.
"""
c, p, q = (n, 1, 0)
for i in range(l):
c, p, q = get_next_level(c, p, q)
return (c, p, q)
def get_position(k):
"""
Returns (l, r), where l is the level and r is the position in the level.
"""
l = get_level(k)
return (l, k - 2**l)
def get_block_size(n, k):
"""
The size of the block (set of consecutive unoccupied stalls)
that the kth person enters.
"""
l, r = get_position(k)
c, p, q = get_level_profile(n, l)
return c + 1 if r < q else c
def get_max_min(block_size):
"""
Given the size of a block that the person has occupied, find the
required values of max {max(L_s, R_s)} and max {min(L_s, R_s)}.
"""
return (int(block_size / 2), int((block_size - 1) / 2))
def _handle_case(stalls, people):
max_, min_ = get_max_min(get_block_size(stalls, people))
return '{} {}'.format(str(max_), str(min_))
class Stalls(CodeJamParser):
"""
2017, Qualification round, C
https://code.google.com/codejam/contest/3264486/dashboard#s=p2
This solution has a bug in it, somewhere... the output produced for the
large dataset was incorrect, although the smaller ones were correct.
From looking at the post-contest analysis, it looks like my approach
is similar, but their loop is much simpler... perhaps the error comes from
assuming that the largest possible block sizes always come in pairs, or
just some rounding error somewhere. Oh well.
"""
def get_cases(self):
cases = int(next(self.source))
for i in range(1, cases + 1):
case_line = next(self.source)
stalls, people = case_line.split(' ')
yield int(stalls), int(people)
def handle_case(self, stalls, people):
return _handle_case(stalls, people)
if __name__ == '__main__':
Stalls()
|
16789efd7c9c47f0bdaabd6be96d2069d5597e59 | pavanyendluri588/python_projects | /data.py | 925 | 3.734375 | 4 | list1=[["x00","x01","x02"],
["x10","x11","x12"],
["x20","x21","x22"]]
list2=[["_","_","_"],
["_","_","_"],
["_","_","_"]]
user1_symbol=None
user2_symbol=None
def welcome_function():
global user1_symbol
global user2_symbol
print("\tWelcome to the TIC_TAC_TOC game\t")
print("\t\tthis is 3*3 game\t\t")
print("""Game symbol is "x" or "o" """)
user1_symbol=input("enter your game symbol:")
print("===============================================")
if user1_symbol=="x":
print("""user1 symbol is "x" """)
user2_symbol="o"
print("""user2 symbol is "o" """)
elif user1_symbol=="o":
print("""user1 symbol is "o" """)
user2_symbol="x"
print("""user2 symbol is "x" """)
elif user1_symbol != "x" or user1_symbol != "o":
print("Entered symbol is invalied")
welcome_function()
|
cdba09b44842f286d5faf1066c7566a2bf522db7 | ravi4all/PythonAugMorning_21 | /BackUp/Functions/05-function.py | 244 | 3.59375 | 4 | # variable length argument
def add(*x):
sum = 0
for i in range(len(x)):
sum += x[i]
print("Sum is",sum)
x = [[4,5,7], [3,5,3]]
add(x[0][1],x[1][0])
add(3,4,6,7)
add(4,6,8,9,4,2)
add(1,2,5,7,8,5,6,9,7,5,4,5,7)
|
4057d7a7a92bf52d82220d79548d1d58d6b84edb | ngladkoff/2020P1 | /ejerciciosRegistros.py | 1,502 | 3.796875 | 4 | class Fecha:
def __init__(self, dia, mes, anio):
self.dia = dia
self.mes = mes
self.anio = anio
def __repr__(self):
return "{0}/{1}/{2}".format(self.dia, self.mes, self.anio)
def __str__(self):
return "{0:02d}-{1:02d}-{2:4d}".format(self.dia, self.mes, self.anio)
class Persona:
def __init__(self, nombre, sueldo, fecha_nacimiento):
self.nombre = nombre
self.sueldo = sueldo
self.f_nacimiento = fecha_nacimiento
def __repr__(self):
return self.nombre
def ordenar_lista(vector):
i_max = len(vector) - 1
for j in range(0,i_max):
for i in range(0,i_max):
if vector[i].nombre > vector[i + 1].nombre:
aux = vector[i]
vector[i] = vector[i + 1]
vector[i + 1] = aux
def main():
lista = [Persona("Nicolas", 2000, Fecha(1,1,1980)), Persona("Alejandro", 4000, Fecha(2,2,1981)), Persona("Carlos", 3000, Fecha(3,3,1982))]
print(lista)
ordenar_lista(lista)
print(lista)
print("{0:03d} | {1:0.2f}".format(5, 4.5))
persona = lista[0]
print("Nombre: " + persona.nombre)
print("Fecha: {0:02d}-{1:02d}-{2:4d}".format(persona.f_nacimiento.dia, persona.f_nacimiento.mes, persona.f_nacimiento.anio))
print(persona.f_nacimiento)
print(repr(persona.f_nacimiento))
dato = Fecha(4,4,2004)
print(dato)
persona.f_nacimiento = dato
print(persona.f_nacimiento)
if __name__ == "__main__":
main() |
bf6d2f7e04bada28224beca29587dfe070d81ded | RasmusBuntzen/Python-for-data-science | /Projekter/Øvelser/WhileLoopøvelse.py | 471 | 3.78125 | 4 | x = 1
#while x < 4: # Da x = 1 og den ikke ændres vil x<4 altid være sandt og loopet vil aldrig slutte
# print(x)
print("Øvelse 2")
while x <= 4: #Hvis x er 4 eller mindre
print(5-x) #For at få tallene i omvendt rækkefølge
x = x+1
x = 1
print("\nØvelse 3")
while x < 10: #Kører hvis x er mindre end 10
if x % 3 == 0: # Hvis der ikke er nogen rest nor tallet divideres med 3 så print tallet (ellers printes tallet ikke)
print(x)
x = x+1 |
eee79f15ec74002da45b8ea45a2c1557ba0a61e8 | Ever1ck/Tarea-10-ejercicios | /Nventas.py | 932 | 3.796875 | 4 | def VentasTotales():
Ventas = int()
V0A10000 = 0
V10000A20000 = 0
MV0A1000 = 0
MV10000A20000 = 0
MontoTotal = 0
print("Ingrese el numero de ventas")
Ventas =int(input())
for x in range(1, Ventas+1):
print("Venta: ",x)
print("Ingrese el valor")
venta =float(input())
if venta<=10000:
V0A10000 = V0A10000+1
MV0A1000 = MV0A1000+venta
if venta>10000 and venta<=20000:
V10000A20000 = V10000A20000+1
MV10000A20000 = MV10000A20000+venta
MontoTotal = MontoTotal+venta
print("Valor de ventas de 0 a 10000: ", V0A10000)
print("Valor de ventas de 10000 a 20000: ", V10000A20000)
print("Valor de monto ventas de 0 a 10000: ", MV0A1000)
print("Valor de monto ventas de 10000 a 20000: ", MV10000A20000)
print("Valor de monto global: ", MontoTotal)
VentasTotales() |
3e8bcb9a052cb131a863b55b09820f1b8c38a2d6 | icelighting/leetcode | /数组与字符串/斐波拉奇数列.py | 302 | 3.53125 | 4 |
class Feborlaqi():
def method(self,n):
f0 = 1
f1 = 1
for i in range(n-2):
temp = f1
f1 = f1 + f0
f0 = temp
return f1
if __name__ == '__main__':
n = 5
solute = Feborlaqi()
print(solute.method(n))
|
415689f4eab254222d268652f3864e177419e63c | FanghanHu/python-notes | /practice/shuffle.py | 2,145 | 4.09375 | 4 | # %%
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def navieStep(arr, i):
"simulate a step in a navie shuffle algorithm, return all possile result"
results = []
for j in range(len(arr)):
copy = arr.copy()
swap(copy, i, j)
results.append(copy)
return results
def navieShuffle(arr):
"return all possible results of a navie shuffle"
result = [arr]
# iterate through each step
for i in range(len(arr)):
# use temp to store result of each step
temp = []
for tempArr in result:
temp.extend(navieStep(tempArr, i))
# replace results from last step with results from this step
result = temp
return result
def fyStep(arr, i):
"simulate a step in Fisher-Yates shuffle, returning all possible results"
results = []
for j in range(0, i + 1):
copy = arr.copy()
swap(copy, j, i)
results.append(copy)
return results
def fyShuffle(arr):
"return all possible result of a Fisher-Yates shuffle"
result = [arr]
# 0 is omitted on purpose as it will always produce the same result as last step
for i in range(len(arr) - 1, 0, -1):
temp = []
for tempArr in result:
temp.extend(fyStep(tempArr, i))
result = temp
return result
def printResult(arr, result):
# setup a dict to count the number of times each item ends up at each position
count = {}
for item in arr:
count[item] = [0] * len(arr)
# counting
for seq in result:
for i, c in enumerate(seq):
count[c][i] += 1
# print column names
line = "item"
for i in range(len(arr)):
line += f"\t{i}"
print(line)
# print number of times for each item ending up in each spot
for key in count:
line = f"{key} : "
for n in count[key]:
line += f"\t{n}"
print(line)
# run the simulation
arr = ["A", "B", "C", "D", "E", "F"]
result = navieShuffle(arr)
print("Navie Shuffle:")
printResult(arr, result)
print("\nFisher-Yates Shuffle:")
result = fyShuffle(arr)
printResult(arr, result)
# %%
|
74d33033e53586e3a8e130b9026a326f761432c3 | WYoYao/PythoneStudy | /public.py | 2,601 | 4.25 | 4 |
# 在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑。
# 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
'''
class Student(object):
def __init__(self,name,like):
self.__name=name
self.__like=like
def print_like(self):
print('这个就是我的爱好%s' % self.__like)
leo=Student('leo','play')
leo.print_like()
# 改完后,对于外部代码来说,没什么变动,但是已经无法从外部访问实例变量.__name和实例变量.__score了
print(leo.__name)
# 这样就确保了外部代码不能随意修改对象内部的状态,这样通过访问限制的保护,代码更加健壮。
'''
'''
# 因为在方法中,可以对参数做检查,避免传入无效的参数
class Student(object):
def __init__(self,name,like):
self.__name=name
self.__like=like
def print_like(self):
print('这个就是我的爱好%s' % self.__like)
def get_name(self):
return self.__name
def get_like(self):
return self.__like
def set_score(self, score):
self.__score = score
'''
# 在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。
# 你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
'''
# 双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量
class Student(object):
def __init__(self,name,like):
self.__name=name
self.__like=like
person=Student('leo','play')
print(person._Student__name)
# 但是强烈建议你不要这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名。
# 总的来说就是,Python本身没有任何机制阻止你干坏事,一切全靠自觉。
'''
|
41b1071e541e84d8cd54d0a3b8738a555f168e3c | tejas1794/Scientific-and-Mathematical-Computing | /Data Plotting and Floating Point Numbers/DataPlotting.py | 607 | 3.59375 | 4 | import math
from pylab import *
def plottingData(inputFile,rowsToSkip):
'''returns plot of certain columns in the given data file after skipping a number of rows.'''
data = loadtxt(inputFile,skiprows = rowsToSkip)
mins = data[:,0]
print "Minutes: ",mins
secs = data[:,1]
print "Seconds: ",secs
temp = data[:,5]
print "Temperature: ",temp
time = mins + secs/60.
print "Time: ",time
plot(time,temp)
ylim(-30.1,27.5)
xlabel("Time (in min.)")
ylabel("Temperature (in C)")
title("Effect of Altitude on Balloon flight")
plottingData("balloon.dat",138) |
c8a1b8d6fde1c5b7cc4755a2b721cc4211e95b46 | mgfabia/randomPasswordGenerator | /random_password_generator.py | 1,143 | 3.859375 | 4 | import random
letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
digets = "0123456789"
symbols = "!@#$%^&*()-+"
password = ""
while True:
var = input("Create password (or done)?")
if (var == "y" or var == "yes" or var == "sure"):
letter = int(input("How many letters?"))
numbers = int(input("How many numbers?"))
symb = int(input("How many special characters?"))
length = letter + numbers + symb
letrs = random.choices(letters,k = letter)
num = random.choices(digets,k = numbers)
special = random.choices(symbols,k = symb)
#print(letrs)
#print(num)
#print(special)
password = letrs + num + special
random.shuffle(password)
print("Your password is: " + "".join(password))
elif (var == "done"):
print("exiting program")
break;
else:
print(var + " is not a valid input")
|
d062e59ec1b0f481acd02de581b1b1d103724894 | FRANCIS-CASIMIR/Python-root | /Nearest_2_among_N_numbers.py | 501 | 4.0625 | 4 | # Program to print the Nearest two numbers among n numbers
def PrintNear(a):
# "a" is a list of N numbers
# diff is the differnece of two numbers
# l is the length of a list
import math
diff = math.fabs(a[0]-a[1])
num1,num2 = a[0],a[1]
l =len(a)
for x in range(0,l-1):
for y in range(x+1,l):
if(diff>math.fabs(a[x]-a[y])):
diff = math.fabs(a[x]-a[y])
num1,num2 = a[x],a[y]
print(num1,num2)
|
aa7788ebdf1c41a86b80e40f51c4f9598bef07cb | vicety/LeetCode | /python/interview/2023-fulltime/tencent/1.py | 1,418 | 3.90625 | 4 | from util.ListNode import ListNode
def buildList(arr):
dummy = ListNode(-1)
now = dummy
for item in arr:
now.next = ListNode(item)
now = now.next
return dummy.next
def printList(li: ListNode):
if not li:
return
print(li.val)
printList(li.next)
class Solution:
def xorList(self, a: ListNode, b: ListNode) -> ListNode:
# write code here
def rev(a: ListNode):
now = a
nxt = a.next
now.next = None
while nxt:
nxtNxt = nxt.next
nxt.next = now
now = nxt
nxt = nxtNxt
return now
a = rev(a)
# printList(a)
# printList(b)
resDummy = ListNode(-1)
now = resDummy
aNow = a
bNow = b
while aNow and bNow:
now.next = ListNode(aNow.val ^ bNow.val)
now = now.next
aNow = aNow.next
bNow = bNow.next
while aNow:
now.next = ListNode(aNow.val)
now = now.next
aNow = aNow.next
while bNow:
now.next = ListNode(bNow.val)
now = now.next
bNow = bNow.next
ans = rev(resDummy.next)
while ans is not None and ans.val == 0:
ans = ans.next
if ans is None:
return ListNode(0)
return ans
|
f59e086a0d82a5e4625119e6c42c502381c832c2 | nishant-giri/450-DSA-Questions | /python/matrix/2_search_2d_matrix.py | 944 | 3.765625 | 4 | class Solution:
def findRow(self,matrix,target):
n = len(matrix[0])
exist = False
for row_index,row in enumerate(matrix):
if target >= row[0] and target<=row[n-1]:
exist=True
break
return exist,row_index
def searchMatrix(self, matrix, target) :
size = len(matrix)
n = len(matrix[0])
print(n, "n")
if size == 0:
print("zero size")
return False
if target < matrix[0][0] or target > matrix[size-1][n-1]:
print("not in matrix")
return False
exist,row_index = self.findRow(matrix,target)
if exist == True:
for i in range(n):
print(matrix[row_index][i])
if matrix[row_index][i] == target:
return True
print(row_index)
return False |
573450e4de5de85acd01c721643b5f2d5aeeeb1f | ghostbody/Yejq-online-judge | /data/remove.py | 619 | 3.75 | 4 | #-*-coding:utf-8-*-
import os
import os.path
#删除函数实现
def deletefunction():
for root, dirnames, files in os.walk("/home/vinzor/project2/data/submit/"):
for name in files:
pathName = os.path.splitext(os.path.join(root, name))
if (pathName[1] == '.txt' or pathName[1] == ''):
os.remove(os.path.join(root, name))
print(os.path.join(root, name))
#输入要删除文件的目录,删除后缀名为"txt"或没有后缀名的文件
print "本程序只支持删除制定目录下后缀名为'txt'或没有后缀名的文件"
deletefunction()
|
db1096acdf755b1c6b368b1fa8b06e1a0774cfd7 | alonsovidales/cracking_code_interview_1_6_python | /3_5.py | 729 | 4.0625 | 4 | # Implement a MyQueue class which implements a queue using two stacks.
class MyQueue(object):
def __init__(self):
self._arrs = ([], [])
def enqueue(self, v):
self._arrs[0].append(v)
def dequeue(self):
if len(self._arrs[1]) == 0:
while len(self._arrs[0]) > 0:
self._arrs[1].append(self._arrs[0].pop())
return self._arrs[1].pop()
mq = MyQueue()
mq.enqueue(1)
mq.enqueue(2)
mq.enqueue(3)
print mq.dequeue()
mq.enqueue(4)
mq.enqueue(5)
mq.enqueue(6)
print mq.dequeue()
mq.enqueue(7)
mq.enqueue(8)
mq.enqueue(9)
print mq.dequeue()
mq.enqueue(10)
mq.enqueue(11)
print mq.dequeue()
print mq.dequeue()
print mq.dequeue()
print mq.dequeue()
print mq.dequeue()
|
c4bfb618159346d423b19e0e7021e292933f0315 | Rosebotics/pymata-aio-examples | /RoseBot/sparkfun_experiments/Exp3_Turning.py | 1,127 | 3.9375 | 4 | """
Exp3_Turning -- RoseBot Experiment 3
Explore turning with the RoseBot by controlling the Right and Left motors
separately.
Hardware setup:
This code requires only the most basic setup: the motors must be
connected, and the board must be receiving power from the battery pack.
"""
import rosebot.rosebot as rb
def main():
board = rb.RoseBotConnection(ip_address="r01.wlan.rose-hulman.edu") # change the 'rXX' value
motors = rb.RoseBotMotors(board)
print("Driving forward")
motors.drive_pwm(150, 150)
board.sleep(1.0)
motors.brake()
print("Pivot-- turn to right")
motors.drive_pwm(100, -100) # Turn on left motor counter clockwise medium power (motorPower = 150)
board.sleep(0.5)
motors.brake()
print("Driving reverse")
motors.drive_pwm(-150, -150)
board.sleep(1.0)
motors.brake()
while True:
# Figure 8 pattern -- Turn Right, Turn Left, Repeat
print("Veering Right")
motors.drive_pwm(150, 80)
board.sleep(2.0)
print("Veering Left")
motors.drive_pwm(80, 150)
board.sleep(2.0)
main() |
eb547a0e700b24cf8ed03aa8bb8cce585be8a01c | CS196Illinois/lecture-activities-sp19 | /basics.py | 2,217 | 4.28125 | 4 |
"""This method should print 'hello world' to the screen. There is no return value for this method."""
def hello_world():
pass
"""
Given a list of integers, find the maximum element.
Input: A list of integers
Output: The maximum value in the list
"""
def find_max(my_list):
return 0
'''
Given a list of integers, determine the maximum number less n.
Input: [1,4,2,14, 11], n = 6
Output: 4
Hint: You may wish to use your find_max function in this function
'''
def find_max_less_than(my_list, n):
return 0
"""
Determine if all characters in the string are unique. Meaning no character occurs more than once.
Input: A string
Output:
True if it is unique
False if the string is not unique
"""
def is_unique(str_in):
pass
"""
Determine the character that occurs most frequently in the input string
Input: A string
Output:
The character that occurs most frequently
"""
def most_common_char(str_in):
pass
"""
Determine if n is prime.
Input: An integer n
Output:
True: if n is prime
False: if n is not prime
"""
def is_prime(n):
pass
'''
Given a string, print out the letters that are capitalized.
Input: 'HellO World'
We should print out the letters 'H', 'O', and 'W'
Hint: the lower() and upper() functions may be userful
'''
def find_capitals(str_in):
pass
"""
Given a series of words separated by spaces, split the statement up into a list where each element is a word.
Input:
'hello World how is it going'
Output:
['hello', 'World', 'how', 'is', 'it', 'going']
Hint: Look up the split() function
"""
def make_list(str_in):
pass
if __name__ == '__main__':
print("Welcome to the Basics Lecture")
hello_world()
list_a = [1,5,43,5,12,155,123]
if find_max(list_a) == 155:
print("You found the correct max value for the first list")
list_b = [i % 123 for i in range(100000)]
if find_max(list_b) == max(list_b):
print("You found the correct max value for the second list")
if(find_max_less_than(list_b, 125) == 122):
print("your find_max_less_than function found the correct value than less n")
#Try writing your own tests for the rest of the problem!
|
5ce4d7f7f249872bf080059551ba26e610449ab5 | alleeclark/ThinkLikeCompSci | /FifthChapter/Exercises/Ex2.py | 104 | 3.5625 | 4 | x = input("What day did you start on? ")
sleep = input("How many sleeps did you get? ")
if x%sleep:
|
ae921083f4ac84273801866e629b232e38deffaa | tking21/Comp_Phylo | /OOP_MCMC.py | 2,161 | 3.734375 | 4 | import random
class mChain(object):
"""
This class defines and runs a MC
"""
def __init__(self, nSteps, states, matrix, sampled):
"""
intitialize all variables of interest
"""
self.nSteps = nSteps
self.states = states
self.matrix = matrix
self.sampled = sampled
def run(self, nSteps, states, matrix, sampled):
"""
Run the chain
"""
#start at some random state within the "states" list
current_state = random.choice(states)
sampled.append(current_state)
#print("current state = " + str(current_state))
#determing what index this state correlates to
current_index = states.index(current_state)
#print(current_index)
#doing the same for proposed state
for _ in range(0,nSteps):
#print(_)
proposed_state = random.choice(states)
#print(proposed_state)
proposed_index = states.index(proposed_state)
#print(proposed_index)
if matrix[current_index][proposed_index] == 1:
#print(matrix[current_index][proposed_index])
current_state = proposed_state
sampled.append(current_state)
current_index = proposed_index
elif matrix[current_index][proposed_index] == 0:
sampled.append(current_state)
else:
rand_num = random.uniform(0,1)
#print(rand_num)
if rand_num <= matrix[current_index][proposed_index]:
current_index = proposed_index
sampled.append(proposed_state)
else:
sampled.append(current_state)
print(sampled)
def clear():
"""
clear the chain
"""
sampled = []
states = ["sunny", "rainy"]
Q = [[0,1],[0.7,0.3]]
sampled= []
test = mChain(10, states, Q, sampled)
test.run(test.nSteps, test.states, test.matrix, test.sampled)
|
8ac891ed017df450b7dabe54833c4d10b7466960 | Jamesdlove/Thinkful-stuff | /Some example stuff.py | 792 | 3.96875 | 4 | # void function, no return value, no parameters
def say_hello():
print "hello"
say_hello()
def my_sum(a, b):
""" Returns the sum of the two formal parameters."""
return a + b
print my_sum(2, 2)
print my_sum(my_sum(2,3), my_sum(5,5))
a = my_sum(10, 5)
b = 3
print my_sum(a, b)
print sum([1, 2, 3, 4, 5])
def my_sum2(l):
s = 0
for x in l:
s += x
return s
def greeter1(name):
print "Hello there {}".format(name)
def greeter2(name):
print "Howdy {}".format(name)
def greet(l, greeter):
for name in l:
greeter(name)
greet(["sam", "bob", "barney"], greeter2)
greet(["sam", "bob", "barney"], greeter1)
def make_adder(a):
def inner(x):
return a + x
return inner
two_adder = make_adder(2)
print two_adder(10)
#12
four_adder = make_adder(4)
print four_adder(20) |
8336cb3df417494250be61c1540562712bda579e | wql7654/bigdata2019 | /03. AI/03. Deep Learning/2. Tensorflow/1. perception/8.mnist_neural_network.py | 958 | 3.5 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
X=tf.placeholder(tf.float32,shape=[None,784])
Y=tf.placeholder(tf.float32,shape=[None,10])
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.random_normal([10]))
logit_y=tf.matmul(X,W)+b
softmax_y=tf.nn.softmax(logit_y)
cross_entoropy=tf.reduce_mean(-tf.reduce_sum(Y*tf.log(softmax_y),reduction_indices=[1]))
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(cross_entoropy)
init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
for i in range(500):
batch_xs,batch_ys=mnist.train.next_batch(100)
sess.run(train_step,feed_dict={X:batch_xs,Y:batch_ys})
correct_prediction=tf.equal(tf.argmax(softmax_y,1), tf.argmax(Y,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print("정확도:",sess.run(accuracy,feed_dict={X:mnist.test.images,Y:mnist.test.labels}))
|
23bc5ac36e5f8463ea257bd2fef8254bf355d89c | kirthigabalu/coding | /oddposeven.py | 206 | 3.703125 | 4 | #printing odd position seperately and even position separetly
s=input()
l=list(s)
l1=[]
l2=[]
for i in range(0,len(l)):
if i%2==0:
l1.append(l[i])
else:
l2.append(l[i])
print("".join(l1),"".join(l2))
|
94c04df6f483132ff08fa07400edaee5239933fc | OSYouth/PythonCrashCourse | /Chapter06/6-5.py | 973 | 4.0625 | 4 | riverCountries ={
'nile': 'egypt',
'nile': 'ethiopia',
'nile': 'sudan',
'amazon': 'brazil',
'amazon': 'peru',
'amazon': 'bolivia',
'amazon': 'columbia',
'amazon': 'ecuador',
'amazon': 'venezuela',
'amazon': 'guyana',
'nile': 'uganda',
'nile': 'nan sudan',
'yangtse': 'china',
'nile': 'tanzania',
'nile': 'rwanda',
'nile': 'burundi',
'nile': 'congo',
'nile': 'kenya',
'nile': 'eritrea',
}
for river, country in riverCountries.items():
print("The " + river.title() + " runs through " + country.title() + ".")
print()
for river in set(riverCountries):
print(river.title())
print()
for country in riverCountries.values():
print(country.title())
# 从该示例的运行结果也可以看出,键的重复只会有一组键值对生效
# 没运行之前,自己还傻傻地搜索三大河流流经的每一个国家,真的是……不过也可以尝试把键和值换过来进行遍历 |
c781236df01efbe15e2ff7537fb190dbfc11e65c | euler1337/advent_of_code_2019 | /7/program.py | 9,766 | 3.5 | 4 | #!/usr/bin/env python3
import copy
import queue
PROGRAM_START_ADDRESS=0
OUTPUT_ADDRESS = 0
NOUN_ADDRESS=1
VERB_ADDRESS=2
PROGRAM_STEP_LENGTH=4
PROGRAM_ADD_CODE=1
PROGRAM_MULT_CODE=2
PROGRAM_INPUT_CODE=3
PROGRAM_OUTPUT_CODE=4
PROGRAM_JUMP_TRUE_CODE=5
PROGRAM_JUMP_FALSE_CODE=6
PROGRAM_LESS_THAN_CODE=7
PROGRAM_EQUALS_CODE=8
PROGRAM_STOP_CODE=99
KNOWN_OPERATOR_CODES = [PROGRAM_ADD_CODE,
PROGRAM_MULT_CODE,
PROGRAM_INPUT_CODE,
PROGRAM_OUTPUT_CODE,
PROGRAM_JUMP_TRUE_CODE,
PROGRAM_JUMP_FALSE_CODE,
PROGRAM_LESS_THAN_CODE,
PROGRAM_EQUALS_CODE,
]
OPERATOR_NUMBER_OF_PARAMETERS = {
PROGRAM_ADD_CODE : 3,
PROGRAM_MULT_CODE : 3,
PROGRAM_INPUT_CODE : 1,
PROGRAM_OUTPUT_CODE : 1,
PROGRAM_JUMP_TRUE_CODE : 2,
PROGRAM_JUMP_FALSE_CODE : 2,
PROGRAM_LESS_THAN_CODE : 3,
PROGRAM_EQUALS_CODE : 3,
PROGRAM_STOP_CODE : 0
}
PROGRAM_OUTPUT_QUEUE = queue.Queue()
PROGRAM_INPUT_QUEUE = queue.Queue()
NON_INTERACTIVE_MODE = 'NON_INTERACTIVE'
INTERACTIVE_MODE = 'INTERACTIVE'
def reverse_string(string):
return string[len(string)::-1]
def get_address_pointer_increment(op_code):
return OPERATOR_NUMBER_OF_PARAMETERS[int(op_code)] + 1
def parse_instruction(program, address_pointer):
data = reverse_string(str(program[address_pointer]))
op_code = int(reverse_string(data[:2]))
parameter_modes = [0] * OPERATOR_NUMBER_OF_PARAMETERS[op_code]
for index, x in enumerate(data[2:]):
parameter_modes[index] = x
return op_code, parameter_modes
def is_positional(parameter_mode):
return int(parameter_mode) == 0
def is_immediate(parameter_mode):
return int(parameter_mode) == 1
def get_parameter_value(parameter_modes, parameter_index, program, address_pointer):
''' parameter_index is 1, 2, 3, ...'''
if is_positional(parameter_modes[parameter_index-1]):
val = get_positional_value(program, address_pointer+parameter_index)
elif is_immediate(parameter_modes[parameter_index-1]):
val = get_immediate_value(program, address_pointer+parameter_index)
else:
raise RuntimeError("parameter mode is not recognized: {}".format(parameter_modes[parameter_index-1]))
return int(val)
def get_positional_value(program, address):
target_address = program[address]
return program[target_address]
def get_immediate_value(program, address):
return program[address]
def set_program_output(item):
PROGRAM_OUTPUT_QUEUE.put(item)
def get_program_output():
if PROGRAM_OUTPUT_QUEUE.empty():
raise(RuntimeError("Output Queue is empty"))
return PROGRAM_OUTPUT_QUEUE.get()
def add_program_input(item):
return PROGRAM_INPUT_QUEUE.put(item)
def get_program_input():
if PROGRAM_INPUT_QUEUE.empty():
raise(RuntimeError("Input Queue is empty"))
return PROGRAM_INPUT_QUEUE.get()
def clear_program_input():
PROGRAM_INPUT_QUEUE.queue.clear()
def run_instruction(program, address_pointer, op_code, parameter_modes, mode):
output_written = False
if op_code is PROGRAM_ADD_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
value = val1 + val2
destination = program[address_pointer+3]
program[destination] = value
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_MULT_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
value = val1 * val2
destination = program[address_pointer+3]
program[destination] = value
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_INPUT_CODE:
destination = program[address_pointer+1]
if mode == NON_INTERACTIVE_MODE:
input_data = get_program_input()
elif mode == INTERACTIVE_MODE:
input_data = input("Enter your input value : ")
else:
raise(RuntimeError("DID NOT RECOGNIZE MODE: {}".format(mode)))
program[destination] = input_data
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_OUTPUT_CODE:
destination = program[address_pointer+1]
#print("OPCODE_4: Value={}".format(program[destination]))
set_program_output(program[destination])
address_pointer = address_pointer + get_address_pointer_increment(op_code)
output_written = True
elif op_code is PROGRAM_JUMP_TRUE_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
if val1 > 0:
address_pointer = val2
else:
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_JUMP_FALSE_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
if val1 == 0:
address_pointer = val2
else:
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_LESS_THAN_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
destination = program[address_pointer+3]
if val1 < val2:
program[destination] = 1
else:
program[destination] = 0
address_pointer = address_pointer + get_address_pointer_increment(op_code)
elif op_code is PROGRAM_EQUALS_CODE:
val1 = get_parameter_value(parameter_modes, 1, program, address_pointer)
val2 = get_parameter_value(parameter_modes, 2, program, address_pointer)
destination = program[address_pointer+3]
if val1 == val2:
program[destination] = 1
else:
program[destination] = 0
address_pointer = address_pointer + get_address_pointer_increment(op_code)
else:
raise RuntimeError("op_code: {} is not a supported operation".format(op_code))
return program, address_pointer, output_written
def run_program(program, mode, address_pointer=0):
done = False
while(True):
op_code, parameter_modes = parse_instruction(program, address_pointer)
if op_code in KNOWN_OPERATOR_CODES:
program, address_pointer, output_written = run_instruction(program, address_pointer, op_code, parameter_modes, mode)
if output_written:
break
elif op_code is PROGRAM_STOP_CODE:
done = True
break
else:
raise RuntimeError("Do not recognize instruction with code: {}, knows codes are {}".format(op_code, KNOWN_OPERATOR_CODES))
return program, done, address_pointer
def run_program_amplifier(program, phase, input_signal):
for x in phase:
add_program_input(x)
add_program_input(input_signal)
run_program(program.copy(), NON_INTERACTIVE_MODE)
input_signal = get_program_output()
return input_signal
def a(input_data):
# First input = phase setting
# Second input = input signal (output from previous program)
max_throttle = 0
start_input = 0
for num in range(0,43211):
x_list = [int(x) for x in str(num)]
if len(x_list) == 4:
x_list.append(0)
if 0 in x_list and 1 in x_list and 2 in x_list and 3 in x_list and 4 in x_list:
phase = x_list
output = run_program_amplifier(input_data.copy(), phase, start_input)
max_throttle = max(max_throttle, output)
print("A, answer={}".format(max_throttle))
def run_feedback_program_amplifier(program, phase, input_signal):
programs = [program.copy(), program.copy(), program.copy(), program.copy(), program.copy()]
address_pointers = [0,0,0,0,0]
first_run = True
done = False
print("SUM={}".format(sum([sum(x) for x in programs])))
while not done:
for index, program in enumerate(programs):
if first_run:
add_program_input(phase[index])
add_program_input(input_signal)
programs[index], done, address_pointers[index] = run_program(program, NON_INTERACTIVE_MODE, address_pointers[index])
if not done:
output = get_program_output()
input_signal = output
first_run = False
return output
def b(input_data):
max_throttle = 0
start_input = 0
for num in range(0,98766):
clear_program_input()
x_list = [int(x) for x in str(num)]
if len(x_list) == 4:
x_list.append(0)
if 5 in x_list and 6 in x_list and 7 in x_list and 8 in x_list and 9 in x_list:
phase = x_list
output = run_feedback_program_amplifier(input_data, phase, start_input)
max_throttle = max(max_throttle, output)
print("candidate, output={}, phase={}".format(output, phase))
print("A, answer={}".format(max_throttle))
if __name__ == '__main__':
f = open("input.txt", "r")
input_data = f.readline().split(',')
input_data = [int(x) for x in input_data]
a(input_data.copy())
b(input_data.copy())
|
20ba2df852e16d7564ec01101e1a09cfd41b6d59 | codeforcauseorg-archive/DSA-Live-Python-Jun-0621 | /lecture-06/linearSearch.py | 269 | 3.53125 | 4 | import random
li = [32, 12, 11, 32, 35]
# for i in range(5):
# li.append(random.randint(10, 50))
def linear_search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return None
print(linear_search(li, 33))
|
4347318e67d85cdb76b877b7c7932bbf6f9301e3 | AishwaryaJadhav9850/GeeksforGeeks-Mathematical- | /GeeksForGeek_Arithmetic Progression.py | 601 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 20:52:50 2020
@author: aishw
"""
#User function Template for python3
class Solution:
def nthTermOfAP(self,A1,A2,N):
#code here
if N == 1:
return A1
elif N==2:
return A2
else:
d=A2-A1
k=A2
k=k+((N-2)*d)
return k
if __name__=='__main__':
t=int(input())
for _ in range(t):
A1,A2,N=map(int,input().strip().split(' '))
ob=Solution()
print(ob.nthTermOfAP(A1,A2,N))
|
6b69343d9f639c8a04785991de88161d0833b031 | lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python | /chapter05/Exercise24_05.py | 1,881 | 4.4375 | 4 | '''
**5.24 (Financial application: loan amortization schedule)
The monthly payment for a given loan pays the principal and
the interest. The monthly interest is computed by multiplying
the monthly interest rate and the balance (the remaining principal).
The principal paid for the month is therefore the monthly payment
minus the monthly interest. Write a program that lets the user enter
the loan amount, number of years, and interest rate, and then displays
the amortization schedule for the loan.
/**
* @author BASSAM FARAMAWI
* @email tiodaronzi3@yahoo.com
* @since 2018
*/
'''
# Let the user enter loan amount
loanAmount = eval(input("Loan Amount: "))
# Let the user enter loan amount
numberOfYears = eval(input("Number of Years: "))
# Let the user enter annual interest rate
annualInterestRate = eval(input("Annual Interest Rate: "))
# The monthly interest rate
monthlyInterestRate = annualInterestRate / 1200
# The monthly payment
monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / \
pow(1 + monthlyInterestRate, numberOfYears * 12))
# The total payment
totalPayment = monthlyPayment * numberOfYears * 12
# Display the monthly payment and the total payment
print()
print("Monthly Payment: %" + format(monthlyPayment, "<.2f"))
print("Total Payment: %" + format(totalPayment, "<.2f"))
print()
balance = loanAmount
# Print the header
print(format("Payment#", "<15s"), format("Interest", "<15s"),
format("Principal", "<15s"), format("Balance", "<15s"))
# Loop for printing the table body
for n in range(1, numberOfYears * 12 + 1):
interest = monthlyInterestRate * balance
principal = monthlyPayment - interest
balance = balance - principal
# Display the results
print(format(n, "<15d"),
format(interest, "<15.2f"),
format(principal, "<15.2f"),
format(balance, "<15.2f"))
|
4a3a0324384fd52cc5dc7a41193946e4741a46cf | Jacksonleste/exercicios-python-curso-em-video | /ex030.py | 319 | 3.828125 | 4 | print('\033[31;1m{}VERIFICAR SE UM NÚMERO É IMPAR OU PAR{}'.format(6*'--=', 6*'=--'))
num = int(input('\033[30mInsira um número:'))
result = num%2
if result == 0:
print('O número \033[34m{}\033[30m é um número par.'.format(num))
else:
print('O número \033[34m{}\033[30m é um número impar.'.format(num)) |
f162d1d904703284c8f0a9581cad1e1a9f6deaec | dalianzhu/interval_tree | /interval_tree.py | 2,716 | 3.859375 | 4 | class Node(object):
def __init__(self):
self.left = None
self.right = None
self.count = 0
class IntervalTree(object):
def __init__(self, left, right):
self.nodes = [Node() for x in range(0, 2 * ((right - left) * 2 - 1))]
self._build_tree(left, right, 1)
def _build_tree(self, left, right, node_index):
try:
self.nodes[node_index].left = left
self.nodes[node_index].right = right
mid = (left + right) // 2
# print("left {} right {} node_index{} nodes length{}".format(left, right, node_index, len(self.nodes)))
if left != right - 1:
self._build_tree(left, mid, 2 * node_index)
self._build_tree(mid, right, 2 * node_index + 1)
except:
print("error left {} right {} node_index{} nodes length{}".format(left, right, node_index, len(self.nodes)))
def insert_line(self, left, right):
self._insert_line(left, right, 1)
def _insert_line(self, left, right, node_index):
mid = (self.nodes[node_index].left + self.nodes[node_index].right) // 2
if [self.nodes[node_index].left, self.nodes[node_index].right] == [left, right]:
self.nodes[node_index].count += 1
return
if right <= mid:
# 线段在左子树上
self._insert_line(left, right, 2 * node_index)
return
elif left >= mid:
# 线段在右子树上
self._insert_line(left, right, 2 * node_index + 1)
return
else:
# 一半在左,一半在右
self._insert_line(left, mid, 2 * node_index)
self._insert_line(mid, right, 2 * node_index + 1)
return
def search_line(self, left, right):
return self._search_line(left, right, 1)
def _search_line(self, left, right, node_index):
mid = (self.nodes[node_index].left + self.nodes[node_index].right) // 2
if [self.nodes[node_index].left, self.nodes[node_index].right] == [left, right]:
return self.nodes[node_index].count
if right <= mid:
# 线段在左子树上
return self._search_line(left, right, 2 * node_index)
elif left >= mid:
# 线段在右子树上
return self._search_line(left, right, 2 * node_index + 1)
else:
# 一半在左,一半在右
return self._search_line(left, mid, 2 * node_index) and \
self._search_line(mid, right, 2 * node_index + 1)
|
4af5302d96890b1e288c108f5ca5490f50233162 | Omoomupo/Atmmock | /MockATMupdated.py | 3,741 | 4.28125 | 4 |
#### ****** REGISTER ******
# To register for an account this are the details required:
# - First name, Last name, password and email
# - During registration we generate account account number for the account holder which you will use to log in to your account
#### ****** LOG IN ******
# To Log in to your account you will need this details:
# - Account number generated and the password you used while registering so keep both safe
#initializing the system
import random
database = {}
def init():
valid = False
print("**********Welcome to Omoomupo Bank**********")
print("The bank for the future")
while valid == False:
customer = int(input("Do you have account with us \n 1(yes) 2(no) \n"))
if(customer == 1):
valid = True
login()
elif(customer == 2):
valid = True
print(register())
else:
print("You have entered an invalid option")
init()
def login():
print("*****Login to your account*****")
#copy the account number generated, and input it when asked to input your account number for login
customerAccountNumber = int(input("Please input your account number. \n"))
#Make sure the account number you input here is the same as the one you registered with
password = input("input your password/pin \n")
for accountNumber,userDetails in database.items():
if(accountNumber == customerAccountNumber):
if(userDetails[3] == password):
bankOperation(userDetails)
#login()
def register():
print("******Register for an account with us.*******")
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input("What is your last name? \n")
password = input("Create a password for yourself \n")
accountNumber = generateAccountNumber()
database[accountNumber] = [first_name,last_name,email,password]
print("Your account has been created.")
print("You are now a customer of BankPHB")
print("This is your account number: %d \n Jot it down in your diary" % accountNumber)
login()
def bankOperation(user):
print("Welcome %s %s" % (user[0], user[1] ))
operation = int(input("What operation would you like to perform? \n 1 (Deposit) \n 2 (Withdraw) \n 3 (Check balance) \n 4 (complaint) \n 5 (Account information \n 6 (Logout) \n" ))
if(operation == 1):
deposit()
elif(operation == 2):
withdraw()
elif(operation == 3):
balance()
elif(operation == 4):
complaint()
elif(operation == 5):
print("""This are your account details
%s %s %s
""" % (user[0],user[1],user[2] ) )
elif(operation == 6):
logout()
pass
def deposit():
input("How much do you want to deposit \n ")
print("*****Thanks for banking with us.*****")
def withdraw():
input("How much do you want to withdraw \n ")
print("*****Thanks for banking with us.*****")
def balance():
print("Your account balance is \n ")
print("*****Thanks for banking with us.*****")
def complaint():
input("What is your complaint \n ")
print("*****Thanks for banking with us.*****")
def logout():
login()
def generateAccountNumber():
return random.randrange(1111111111,9999999999)
def money():
return random.randrange(111111,999999)
##### ACTUAL BANKING SYSTEM ####
#print(generateAccountNumber())
#print(money())
init()
|
ef0206e6332d51a07e639740d7b15c288cbf2ded | wangwenjun/python_fundamental | /lesson03/operator.py | 492 | 3.84375 | 4 | print(1+2)
print(1-2)
print(10*5,10.34*34.5)
print(1/3,10.34/4.2)
print(1//3,10.34//4.2)
x=10
print(-x)
y=-10
print(+y)
print(abs(y))
print(int(34.3))
print(float(45))
print(10%3)
print(divmod(10,3),type(divmod(10,3))) #x//y & x%y
print(pow(2,5))
print(2**5)
#def fun(a,b):
# return a+b,a-b
##
#
#result=fun(10,5)
#print(result)
print("*"*100)
x=10
x+=7
print(x)
x=10
x-=7
print(x)
x=10
x*=7
print(x)
x=10
x/=2
print(x)
x=10
x%=3
print(x)
x=2
x**=3
print(x)
x=10
x//=3
print(x)
|
cb513ee47a5f3c7426e4ddb09a9122621843f688 | herissonsilvahs/ListPy | /main.py | 380 | 3.6875 | 4 | from arraylist import ArrayList
from linkedlist import LinkedList
arl = ArrayList([1,2,3,4,5])
lkl = LinkedList()
lkl.append(4)
lkl.append(6)
lkl.append(5)
#lkl.insert(3, 9)
#print(lkl.size())
#lkl.showHead()
lkl.remove(5)
print(lkl.size())
print(lkl.indexOf(4))
element = lkl.getElement(1)
print(element)
rmElement = lkl.removeAt(0)
print(rmElement)
print(lkl.lenght) |
df725c99f82e3f3228fcb1b97ef0ef507d77d5be | MakinoAlan/W4156-Connect4 | /db.py | 2,604 | 3.9375 | 4 | import sqlite3
from sqlite3 import Error
import copy
'''
Initializes the Table GAME
Do not modify
'''
def init_db():
# creates Table
conn = None
try:
conn = sqlite3.connect('sqlite_db')
conn.execute('CREATE TABLE GAME(current_turn TEXT, board TEXT,' +
'winner TEXT, player1 TEXT, player2 TEXT' +
', remaining_moves INT)')
print('Database Online, table created')
except Error as e:
print(e)
finally:
if conn:
conn.close()
'''
move is a tuple (current_turn, board, winner, player1, player2,
remaining_moves)
Insert Tuple into table
'''
def add_move(move): # will take in a tuple
conn = None
try:
conn = sqlite3.connect('sqlite_db')
cur = conn.cursor()
board_to_save = copy.deepcopy(move.board)
for i in range(len(board_to_save)):
for j in range(len(board_to_save[i])):
if board_to_save[i][j] == 'red':
board_to_save[i][j] = 1
if board_to_save[i][j] == 'yellow':
board_to_save[i][j] = 2
cur.execute(f"INSERT INTO GAME VALUES('{move.current_turn}', '{board_to_save}'," +
f"'{move.game_result}', '{move.player1}', '{move.player2}', {move.remaining_moves})")
conn.commit()
except Error as e:
print(e)
finally:
if conn:
conn.close()
'''
Get the last move played
return (current_turn, board, winner, player1, player2, remaining_moves)
'''
def getMove():
conn = None
try:
conn = sqlite3.connect('sqlite_db')
cur = conn.cursor()
cur.execute("select * from GAME")
rows = cur.fetchall()
if len(rows) == 0:
return None
last_row = list(rows[-1])
last_row[1] = eval(last_row[1])
for i in range(len(last_row[1])):
for j in range(len(last_row[1][i])):
if last_row[1][i][j] == 1:
last_row[1][i][j] = 'red'
if last_row[1][i][j] == 2:
last_row[1][i][j] = 'yellow'
return last_row
except Error as e:
print(e)
return None
finally:
if conn:
conn.close()
'''
Clears the Table GAME
Do not modify
'''
def clear():
conn = None
try:
conn = sqlite3.connect('sqlite_db')
conn.execute("DROP TABLE GAME")
conn.commit()
print('Database Cleared')
except Error as e:
print(e)
finally:
if conn:
conn.close()
|
4bbbf558eb3fae88dd20d7c09aae8821d1ff8f00 | Schweinsei007/CSE4233-Group-Project-3 | /api.py | 2,107 | 3.546875 | 4 |
class Api:
""" Attempts to log in to the client.
:param uname: User name
:param pw: Password
:raises Api.LoginError: Invalid login
:return uid
"""
def login(self, uname: str, pw: str) -> int:
# Placeholder
if 2 == int("2"):
return 345
else:
raise self.LoginError
""" Gets items from the database by a specific category
:param uid: User id
:param category: Category, str (can be None)
:raises CategoryIDError: Category does not exist
:return A list of items
"""
def get_items_by_category(self, uid: int, category) -> list:
if uid == 345:
if category is None:
return [5, 6, 7, 8]
elif category is not "":
return [5, 6]
else:
raise self.CategoryError
else:
raise self.UserIdError
""" Gets items from the database by a specific category
:param uid: User id
:param item_id: Item id (integer)
:param count: Item count (optional, 1 by default)
:raises ItemIdError: item does not exist
:raises ValueError: count is too high or invalid
:raises ValueError: number of items added exceeds stock
:return if successful
"""
def add_item_to_cart(self, uid: int, iid:int, count=1):
if int(count) != count:
raise ValueError("Count must be an integer")
if uid == 345:
if iid not in [5, 6, 7, 8]:
raise self.ItemIdError
elif count > int(iid/2): # emulate stock
else:
raise self.UserIdError
pass
""" Gets items from user's cart by their id
:param uid: User id
"""
def get_cart_by_id(self, uid: int):
pass
def remove_item_from_cart(self, uid: int, param, param1):
pass
def get_item_info(self, iid: int):
pass
class UserIdError(Exception):
pass
class ItemIdError(Exception):
pass
class CategoryError(Exception):
pass
class LoginError(Exception):
pass
|
9483c5435a44b3b3f0e4a7f69e64a27623d1c429 | stuart-bradley/code_interview_practice | /Bit_Manipulation.py | 2,243 | 3.96875 | 4 | # Cracking the coding interview - C5 - Bit Manipulation
# Stuart Bradley
# 05-08-2016
# Inject one binary number into another, between positions.
# Doesn't use bitwise operations because fuck it.
def exercise_1(N, M, i, j):
position = i+1
str_N = list(str(N))
for bit in reversed(str(M)):
str_N[-position] = bit
position += 1
return int("".join(str_N))
# Decimal number to binary.
def exercise_2(decimal_number):
binary = "."
while decimal_number > 0:
r = decimal_number * 2
if r >= 1:
binary += "1"
decimal_number = r - 1
else:
binary += "0"
decimal_number = r
return binary
# Determine bit to flip to make longest sequence of 1s.
def exercise_3(sequence):
zero_pos = []
max_length = 0
sequence = list(sequence)
for i,char in enumerate(sequence):
if char == "0":
zero_pos.append(i)
for i in zero_pos:
tmp_sequence = sequence[:]
tmp_sequence[i] = 1
length = 0
for char in tmp_sequence:
if char == "0":
length = 0
else:
length += 1
if length > max_length:
max_length = length
return max_length
# Make biggest and smallest binary numbers.
def exercise_4(sequence):
bits = sequence.count("1")
biggest = int(sequence, 2)
while True:
biggest += 1
binary = "{0:b}".format(biggest)
if binary.count("1") == bits:
biggest = binary
break
smallest = int(sequence, 2)
while True:
smallest -= 1
binary = "{0:b}".format(smallest)
if binary.count("1") == bits:
smallest = binary
break
return (smallest, biggest)
# Check number of bits required to go from one number to another.
def exercise_6(n1, n2):
count = 0
c = n1 ^ n2
while c != 0:
count += 1
c = c & (c-1)
return count
# Pairwise bit swap.
def exercise_7(sequence):
sequence = list(sequence)
for i in range(0,len(sequence) - 1,2):
tmp = sequence[i]
sequence[i] = sequence[i+1]
sequence[i+1] = tmp
return "".join(sequence)
# Draw a horizontal line on a screen.
def exercise_8(screen, width, x1, x2, y):
chunks = [screen[x:x+width] for x in range(0, len(screen), width)]
for i in range(x1,x2+1):
chunks[y][i] = 1
screen = []
for chunk in chunks:
screen.extend(chunk)
return screen |
4c648491a76bf24975aa467256ea0a77b4798c07 | juannico007/laberinto-logica-proposicional | /functions.py | 12,047 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
##################################Variables globales#######################################################
letrasProposicionales=[chr(x) for x in range(256, 2706)] #Va de 256 hasta la letra 2450: la ultima
Conectivos = ['O','Y','>','='] #Lista de conectivos para inorder
negacion = ["-"] #Negacion para inorder
###########################################################################################################
#Arbol para guardar las formulas
class Tree(object):
def __init__(self, label, left, right):
self.left = left
self.right = right
self.label = label
#Conversion del arbol a forma inorderr
def inorder(self):
if self.label in letrasProposicionales:
return self.label
elif self.label in negacion:
return self.label + self.right.inorder()
elif self.label in Conectivos:
return "(" + self.left.inorder() + self.label + self.right.inorder() + ")"
else:
print("Rotulo incorrecto")
sys.exit(1)
#Funcion que convierte un string en polaca inversa a arbol. Recibe:
#Formula en polaca inversa a convertir: A
def String2Tree(A):
Pila = []
for c in A:
if c in letrasProposicionales:
Pila.append(Tree(c,None,None))
elif c=='-':
FormulaAux = Tree(c,None,Pila[-1])
del Pila[-1]
Pila.append(FormulaAux)
elif c in Conectivos:
FormulaAux = Tree(c,Pila[-1],Pila[-2])
del Pila[-1]
del Pila[-1]
Pila.append(FormulaAux)
else:
print(u"Hay un problema: el símbolo {0} no se reconoce".format(c))
return Pila[-1]
#Convierte un arbol a notación inorder. Recibe:
#Arbol de formula: f
#Numero de filas: Nf, numero de columnas: Nc y numero de turnos: Nt, como enteros
def Inorderp(f, Nf, Nc, Nt):
if f.right == None:
if ord(f.label) - 256 >= 49:
return str(Pinv(ord(f.label) - 256 - 49, Nf, Nc, Nt))
else:
return str(decodifica(ord(f.label) - 256, Nf, Nc))
elif f.label == '-':
return f.label + Inorderp(f.right, Nf, Nc, Nt)
else:
return "(" + Inorderp(f.left, Nf, Nc, Nt) + f.label + Inorderp(f.right, Nf, Nc, Nt) + ")"
#Pide posicion inicial y final al usuario. Recibe:
#Numero de filas: Nf y Numero de columnas: Nc como enteros
def inicio_final(Nf, Nc):
#pide inicio
print("\nPosicion inicial:")
f = int(input("Inserte la fila: "))
assert(f >= 0 and f <= Nf - 1), ("Fila invalida, debe ser un numero entre 0 y " + str(Nf - 1)
+ "\nse recibio " + str(f))
c = int(input("Inserte la columna: "))
assert(c >= 0 and f <= Nc - 1), ("Columna invalida, debe ser un numero entre 0 y " + str(Nc - 1)
+ "\nse recibio " + str(c))
inicio = (f, c)
#Pide final
print("\nPosicion final:")
f = int(input("Inserte la fila: "))
assert(f >= 0 and f <= Nf - 1), ("Fila invalida, debe ser un numero entre 0 y " + str(Nf)
+ "\nse recibio " + str(f))
c = int(input("Inserte la columna: "))
assert(c >= 0 and f <= Nc - 1), ("Columna invalida, debe ser un numero entre 0 y " + str(Nc)
+ "\nse recibio " + str(c))
final = (f, c)
return inicio, final
#Codifica dos valores en un numero. Recibe:
#valor 1: f, valor 2: c, maximos del primer valor: Nc y del segundo valor: Nf como enteros
def codifica(f, c, Nf, Nc):
#Nos aseguramos que los valores esten en el rango
assert((f >= 0) and (f <= Nf - 1)), ("Primer argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nf - 1) + "\n se recibio" + str(f))
assert((c >= 0) and (c <= Nc - 1)), ("Segundo argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nc - 1) + "\n se recibio" + str(c))
#codificamos
val = Nc * f + c
return val
#Decodifica un codigo en 2 valores. Recibe
#Codigo a decodificar: n, valores maximos para el primer numero: Nf y para el segundo numero: Nc como enteros
def decodifica(n, Nf, Nc):
#Nos aseguramos que el valor este en el rango
assert((n >= 0) and (n <= Nf * Nc - 1)), ("Primer argumento incorrecto! Debe ser un numro entre 0 y "
+ str(Nf * Nc -1) + "\n se recibio" + str(n))
#decodificamos
f = n // Nc
c = n % Nc
return f, c
#Codifica 3 elementos, recibe:
#valor 1: f, valor 2: c, , valor 3: t, maximos del primer valor: Nc, del segundo valor: Nf y del tercer valor: Nt como enteros
def P(f, c, t, Nf, Nc, Nt):
#nos aseguramos de que el valor este en el rango
assert((f >= 0) and (f <= Nf - 1)), ("Primer argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nf - 1) + "\n se recibio" + str(f))
assert((c >= 0) and (c <= Nc - 1)), ("Segundo argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nc - 1) + "\n se recibio" + str(c))
assert((t >= 0) and (t <= Nt - 1)), ("Tercer argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nt - 1) + "\n se recibio" + str(t))
#codificamos
v1 = codifica(f, c, Nf, Nc)
v2 = codifica(t, v1, Nt, Nf*Nc) + Nf*Nc
codigo = chr(v2 + 256)
return codigo
#Decodifica un codigo en 3 valores, recibe:
#Codigo a decodificar: n, valores maximos para el primer numero: Nf, para el segundo numero: Nc y para el tercer numero: Nt como enteros
def Pinv(n, Nf, Nc, Nt):
#Nos aseguramos de que los valores esten en la cuadricula
assert((n >= 0 and n <= Nf * Nc * Nt - 1)), ("Primer argumento incorrecto! Debe ser un numero entre 0 y "
+ str(Nf * Nc * Nt - 1) + "\n se recibio " + str(n))
t, v1 = decodifica(n, Nf * Nc, Nt)
f, c = decodifica(v1, Nf, Nc)
return f, c, t
#Condiciones iniciales, tomadas de una lista de muros, recibe
#Lista de casillas en las que hay muros: M
#Numero de filas: Nf, Numero de columnas: Nc
def cond_inicial(M, Nf, Nc):
inicial = True
r = ""
for f in range(Nf):
for c in range(Nc):
if(f, c) in M:
if inicial:
code = chr(codifica(f, c, Nf, Nc) + 256)
r += code
inicial = False
else:
code = chr(codifica(f, c, Nf, Nc) + 256)
r += code + "Y"
else:
if inicial:
code = chr(codifica(f, c, Nf, Nc) + 256)
r += code + "-"
inicial = False
else:
code = chr(codifica(f, c, Nf, Nc) + 256)
r += code + "-" + "Y"
return r
#Primera regla: debe iniciar en una casilla dada y terminar en una casilla dada, recibe:
#Inicio: i y final: f como tuplas de forma (fila, columna)
#Numero de turnos: Nt numero de filas: Nf y numero de columnas: Nc como enteros
def regla_1(i, f, Nf, Nc, Nt):
r1 = ""
r1 += P(i[0], i[1], 0, Nf, Nc, Nt)
r1 += P(f[0], f[1], Nt - 1, Nf, Nc, Nt) + "Y"
return r1
#Segunda regla: El agente no puede estar en 2 puntos a la vez, recibe:
#Numero de filas: Nf, Numero de columnas: Nc y Numero de turnos: Nt como enteros
def regla_2(Nf, Nc, Nt):
r2 = ""
inicial_3 = True
for t in range(Nt):
inicial_2 = True
for i in range(Nf):
for j in range(Nc):
inicial = True
for f in range(Nf):
for c in range(Nc):
if f == i and c == j:
end = "-" + P(f, c, t, Nf, Nc, Nt) + ">"
elif inicial:
r2 += P(f, c, t, Nf, Nc, Nt)
inicial = False
else:
r2 += P(f, c, t, Nf, Nc, Nt) + "O"
r2 += end
if inicial_2:
inicial_2 = False
else:
r2 += "Y"
if inicial_3:
inicial_3 = False
else:
r2 += "Y"
return r2
#Tercera regla: El jugador no puede estar parado en una pared. Recibe
#Numero de filas: Nf, Numero de columnas: Nc y Numero de turnos: Nt como enteros
def regla_3(Nf, Nc, Nt):
r3 = ""
inicial_2 = True
for f in range(Nf):
for c in range(Nc):
inicial = True
for t in range(Nt):
if inicial:
r3 += P(f, c, t, Nf, Nc, Nt)
inicial = False
else:
r3 += P(f, c, t, Nf, Nc, Nt) + "O"
if inicial_2:
r3 += "-" + chr(codifica(f, c, Nf, Nc) + 256) + ">"
inicial_2 = False
else:
r3 += "-" + chr(codifica(f, c, Nf, Nc) + 256) + ">" + "Y"
return r3
#Cuarta regla: El jugador solo se puede mover una casilla por turno, hacia arriba, abajo, izquierda o derecha. Recibe
#Numero de filas: Nf, Numero de columnas: Nc y Numero de turnos: Nt como enteros
def regla_4(Nf, Nc, Nt):
r4 = ""
inicial_3 = True
for t in range(Nt - 1):
inicial_2 = True
for i in range(Nf):
for j in range(Nc):
inicial = True
#Lista de adyacencia para el movimiento
#Si la casilla es una columna
if i == 0 and j == 0:
adj = [(i + 1, j), (i, j + 1)]
elif i == 0 and j == Nc - 1:
adj = [(i + 1, j), (i, j - 1)]
elif i == Nf - 1 and j == 0:
adj = [(i - 1, j), (i, j + 1)]
elif i == Nf - 1 and j == Nc - 1:
adj = [(i - 1, j), (i, j - 1)]
#Si la casilla esta en un borde
elif i == 0:
adj = [(i + 1, j), (i, j - 1), (i, j + 1)]
elif i == Nf - 1:
adj = [(i - 1, j), (i, j - 1), (i, j + 1)]
elif j == 0:
adj = [(i - 1, j), (i + 1, j), (i, j + 1)]
elif j == Nc - 1:
adj = [(i - 1, j), (i + 1, j), (i, j - 1)]
#Si se puede mover en todo sentido
else:
adj = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]
for (f, c) in adj:
if inicial:
r4 += P(f, c, t + 1, Nf, Nc, Nt)
inicial = False
else:
r4 += P(f, c, t + 1, Nf, Nc, Nt) + "O"
if inicial_2:
r4 += P(i, j, t, Nf, Nc, Nt) + "-" + "O"
inicial_2 = False
else:
r4 += P(i, j, t, Nf, Nc, Nt) + "-" + "O"+ "Y"
if inicial_3:
inicial_3 = False
else:
r4 += "Y"
return r4
#Quinta regla: Una vez el agente llegue a la ultima casilla, no se movera de ella. Recibe:
#casilla final: f como tupla de forma (fila, columna)
#Numero de filas: Nf, Numero de columnas: Nc y Numero de turnos: Nt como enteros
def regla_5(f, Nf, Nc, Nt):
r5 = ""
inicial_2 = True
for i in range(Nt - 1):
inicial = True
p = P(f[0], f[1], i, Nf, Nc, Nt)
for t in range(i + 1, Nt):
if inicial:
r5 += p + "-" + P(f[0], f[1], t, Nf, Nc, Nt) + "O"
inicial = False
else:
r5 += p + "-" + P(f[0], f[1], t, Nf, Nc, Nt) + "O" + "Y"
if inicial_2:
inicial_2 = False
else:
r5 += "Y"
return r5
|
7fb6a6fae3445fc7153d365506e5a0ccd85b643a | gnjardim/prog1_puc-rio | /Aulas/code/aula_repeticaoindeterminada.py | 3,304 | 4.09375 | 4 | '''
def Tabuada(n):
mult = 1
while mult <= 10:
print("%d x %d = %d" % (mult, n, mult*n))
mult += 1
return
num = int(input("Número? "))
while num != 0:
print("\n Tabuada do ", num)
Tabuada(num)
num = int(input("Número? ")) # se usuário quiser parar, diz 0
'''
'''
def TransfereFrasco(qt_orig):
qt_novo = 0
while (qt_orig - qt_novo > 10):
qt_orig -= 10
qt_novo += 10
evap1 = qt_orig*0.035
evap2 = qt_orig*0.012
qt_orig -= evap1
qt_novo -= evap2
print("Quantidade no frasco original: %.2f \n Quantidade no frasco final: %.2f" % (qt_orig, qt_novo))
return
def qtValida():
qt = float(input("Quantidade no frasco original? "))
while (qt < 40 or qt > 230):
print("Quantidade inválida. Digite um valor entre 40 e 230")
qt = float(input("Quantidade no frasco original? "))
return qt
frasco_original = qtValida()
TransfereFrasco(frasco_original)
'''
'''
def NotaValida(tipo_nota):
nota = float(input(tipo_nota))
while (nota < 0 or nota > 10): # enquanto não for valor correto
print("Nota inválida. Digite um valor entre 0 e 10")
nota = float(input(tipo_nota))
return nota
matric = int(input("Qual a matrícula? "))
n_alunos = 0
total_turma = 0
while matric != 0:
prova = NotaValida("Nota da prova? ")
trab = NotaValida("Nota do trabalho? ")
media_f = 0.8*prova + 0.2*trab
print("Média do aluno %d: %.1f" % (matric, media_f))
matric = int(input("Qual a matrícula? "))
n_alunos += 1
total_turma += media_f
media_turma = total_turma/n_alunos
print("\n Média da Turma: %.1f" % media_turma)
'''
def produto_vencido(dia_visita, mes_visita, ano_visita, dia_validade, mes_validade, ano_validade):
if ano_visita == ano_validade:
if mes_visita == mes_validade:
if dia_visita > dia_validade:
valid = True
else:
valid = False
elif mes_visita > mes_validade:
valid = True
else:
valid = False
elif ano_visita > ano_validade:
valid = True
else:
valid = False
return valid
def calcula_multa(qt_conf, qt_fora):
if qt_fora == 0:
multa = 0
elif qt_fora/qt_conf <= 0.1:
multa = 100
elif qt_fora/qt_conf <= 0.3:
multa = 10000
else:
multa = 100000
return multa
dia_v = int(input("Dia da visita? "))
mes_v = int(input("Mês da visita? "))
ano_v = int(input("Ano da visita? "))
nome = input("\n Nome do produto: ")
n_vencidos = 0
n_produtos = 0
while nome != '':
dia_val = int(input("Dia da validade? "))
mes_val = int(input("Mês da validade? "))
ano_val = int(input("Ano da validade? "))
if produto_vencido(dia_v, mes_v, ano_v, dia_val, mes_val, ano_val):
n_vencidos += 1
n_produtos += 1
nome = input("\n Nome do produto: ")
valor_multa = calcula_multa(n_produtos, n_vencidos)
if valor_multa == 0:
print("Supermercado isento de multas")
else:
print("Valor da multa: %d" % valor_multa)
|
df2bb91b11e1094906ce3a44ddfaa08e4ccc4a01 | arianaburga/Validadores-en-Python | /burga6.py | 429 | 4 | 4 | #calcuadora nro6
#esta calculadora realiza el calculo de la potencia
#declaracion de variables
fuerza,velocidad,potencia=0.0,0.0,0.0
#calculadora
fuerza=237
velocidad=16
potencia=(fuerza*velocidad)
#mostrar datos
print("fuerza= ",fuerza)
print("velocidad= ",velocidad)
print("potencia= ",potencia)
#verificador
potencia_reducida=( potencia<48 )
print("la potencia de un motor es reducida?:",potencia_reducida)
|
e15df8da97094a8ca8f1281ab3ff8fb7461822ac | janarqb/Notes_Week2 | /List.py | 724 | 3.890625 | 4 | # num = [1, 2, 4, 4, 5]
# num = list ((1, 2, 3, 4, 5, 6, 7))
# num = [5] * 6
# num = [1, 2, 3]
# num2 = [4, 5, 6]
# print (num + num2)
# num = []
# # print(num[-1])
# # print(num[1:3])
# num.append('Makers')
# print(num)
# num.append([1, 2])
# print(num)
# num[1].append(True)
# print(num)
# num.insert(0, 'Inserted obj')
# print(num)
# num = list(range(10))
list_ = [1, 2, 0.6, True, 'Makers','Bishkek', [3, 4, 5], 'ne nujen']
# vot_zdes = list_.pop()
# list2 = []
# # print('vot_zdes = ', vot_zdes)
# list2 = list_.copy()
# list_.remove('Makers')
# list_.clear()
# print(list2)
list_.extend([1,2,3,4])
list_.reverse()
print(list_)
# num = list (range(5, 16, 2))
# print(num)
# print(type(num))
# print(dir(num))
|
f68cda2645e4b0a81704662f2de37878b411920b | akbota123/BFDjango | /week1/hackerrank/hacker16.py | 233 | 3.796875 | 4 | #find a string from hackerrank EASY
def count_substring(string, sub_string):
count=0
for n in range(0, len(string)-len(sub_string)+1):
if string[n:n+len(sub_string)]==sub_string:
count+=1
return count |
2487b4abd14a2014a94579c747b2c2123d08e8b7 | q13245632/CodeWars | /WriteNumberinExpandedForm.py | 622 | 3.671875 | 4 | # -*-coding:utf8 -*-
# 自己的解法
def expanded_form(num):
n = len(str(num))
string = str(num)
lst = []
for i in xrange(n): # python3.4.3版本需将xrange改为range
if string[i] != "0":
lst.append(str(int(string[i])* (10**(n-1-i))))
return " + ".join(lst)
# 测试集
# test.assert_equals(expanded_form(12), '10 + 2');
# test.assert_equals(expanded_form(42), '40 + 2');
# test.assert_equals(expanded_form(70304), '70000 + 300 + 4');
# 一句话编程
def expanded_form(num):
return " + ".join([str(int(d) * 10**p) for p, d in enumerate(str(num)[::-1]) if d != "0"][::-1]) |
7878bdd36cd87c619c45301b617f63e6ed8c92f4 | bepstein111/Code-Class | /22-Audio/Code/Ball1_Collision/Ball.py | 995 | 3.609375 | 4 | class Ball():
def __init__(self,ballX,ballY,ballVX,ballVY,ballDiam, ballR,ballG,ballB):
self.ballX = ballX
self.ballY = ballY
self.ballVX = ballVX
self.ballVY = ballVY
self.ballDiam = ballDiam
self.ballCol = color(ballR,ballG,ballB)
def moveBall(self):
fill(self.ballCol)
if (self.ballX>width):
self.ballVX = -1 * 5
elif (self.ballX<0):
self.ballVX = 5
if (self.ballY>height):
self.ballVY = -1 * 5
elif (self.ballY<0):
self.ballVY = 5
self.ballX = self.ballX + self.ballVX
self.ballY = self.ballY + self.ballVY
ellipse(self.ballX,self.ballY,self.ballDiam,self.ballDiam)
def intersect(self, other):
distance = dist(self.ballX, self.ballY, other.ballX, other.ballY)
if (distance < self.ballDiam/2 + other.ballDiam/2):
return True
else:
return False |
722483a32f675f3d4c65bcce51a90d7fadca340c | leoparadise/MaximumFlowEdmondKarp | /longestPath.py | 1,312 | 4.0625 | 4 | """
used as a library to compute longest path
"""
"""
The parameters used throughout the code are:
G : It is the networkX graph object
v : It is the node of the graph to start DFS
path : path of the graph
seen : set of seen nodes
This function is used to calculate the DFS path from the vertex v
"""
seen=set()
def DFS(G,v,path=None):
#if seen is None: seen = set()
if path is None: path = [v]
seen.add(v)
#print(seen)
#path_list is to maintain the traversed path
path_list = []
for t in G[v]:
if t not in seen:
t_path = path + [t]
path_list.append(tuple(t_path))
path_list.extend(DFS(G, t, t_path))
return path_list
#This function is used as driver to calculate the longest path using the DFS
def run_the_algo(capMat):
# Run DFS, compute all paths in the graph
all_paths = [p for ps in [DFS(capMat, n) for n in set(capMat)] for p in ps]
# choose the path with max length
max_len = max(len(p) for p in all_paths)
# store the path with maximum length
max_paths = [p for p in all_paths if len(p) == max_len]
# Output
print("Longest Paths:")
for p in max_paths:
print(" -> ", p)
print("Longest Path Length:")
print(max_len)
return (all_paths, max_len, max_paths) |
f33672d034f026cd7e5c9f64ed1400398997f6ad | donaldscoon/biosys-analytics | /lectures/08-python-patterns/examples/name_args.py | 291 | 3.5625 | 4 | #!/usr/bin/env python3
import os
import sys
args = sys.argv[1:]
if len(args) != 2:
print('Usage: {} FILE NUM'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
file, num = args
file = args[0]
num = args[1]
print('FILE is "{}", NUM is "{}"'.format(file, num))
|
1e25cec3f4342a7dd5f7a6953c8b07717c95603f | osirislab/CSAW-CTF-2020-Quals | /crypto/modus_operandi/encrypt.py | 1,270 | 3.90625 | 4 | #!/usr/bin/env python3
from Crypto.Cipher import AES
import Crypto.Random
#flag = "flag{ECB_re@lly_sUck$}"
flag_binary = "01100110011011000110000101100111011110110100010101000011010000100101111101110010011001010100000001101100011011000111100101011111011100110101010101100011011010110010010001111101"
flag_dict = {"0" : "ECB", "1" : "CBC"}
print("Hello! For each plaintext you enter, find out if the block cipher used is ECB or CBC. Enter \"ECB\" or \"CBC\" to get the flag!")
def AESEncrypt(plaintext, i):
# Padding
length = 16 - (len(plaintext) % 16)
plaintext += bytes([length])*length
# Key
key = Crypto.Random.get_random_bytes(AES.block_size)
# ECB mode for 0, CBC for 1
if i == "0":
cipher = AES.new(key, AES.MODE_ECB)
else:
iv = Crypto.Random.get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(plaintext).hex()
def main():
for i in flag_binary:
print("Enter plaintext: ")
plaintext = input()
ciphertext = AESEncrypt(plaintext.strip().encode('utf-8'),i)
print("Ciphertext is: ", ciphertext)
print("ECB or CBC? ")
ECB_or_CBC = input()
if(ECB_or_CBC != flag_dict[i]):
return 1
return
if __name__ == "__main__":
main()
|
737f40caf1002ff6864013b15c895e9ac0de4163 | indianwebmaster/learning | /python/args_parsing/parse_args.py | 1,578 | 3.875 | 4 | #!/usr/bin/env python
import argparse
args_parser = argparse.ArgumentParser(description='Process user arguments.')
# -------------------------------------------------------------------------
# accept integer arguments after all the options are given.
# nargs='+' implies accept more than one argument
# arguments are saved as a list in the variable args.integers
args_parser.add_argument('integers', type=int, nargs='+', help='an integer')
# -------------------------------------------------------------------------
# accept integer argument after the --sum option
# argument is saved as a variable with the name args.sum
# default=max implies this is an optional argument, and if not given sum will be equal to internal value of max.
args_parser.add_argument('--sum', type=int, default=max)
# -------------------------------------------------------------------------
# accept string argument after the --name option
# argument is saved as a variable with the name args.name
# NO default means the value of args.name will be None if not specified
args_parser.add_argument('--name')
# -------------------------------------------------------------------------
# accept float argument after the --float option
# argument is saved as a variable with the name args.float
# required=True means the option is required
args_parser.add_argument('--float', type=float, required=True)
args = args_parser.parse_args()
# -------------------------------------------------------------------------
print (args)
print (args.integers)
print (args.sum)
print (args.name)
print (args.float)
|
4e40f41b770d9fa4b4d8a22416c49ca008d935f7 | agrawalshivam66/python | /lab5/q4.py | 227 | 4.15625 | 4 | def even_odd():
a=eval(input("Enter the number "))
even=list()
odd=list()
for i in a:
if i%2==0:
even.append(i)
else:
odd.append(i)
a=even+odd
print(a)
even_odd()
|
c018d52c30fafea913c6e01bce9847116546bf63 | Fortuneobiora7/python-challenge-solutions | /Obiora_Fortune/Phase1/Python Basic 1/Day6 Tasks Solution/Task9.py | 257 | 3.78125 | 4 | '''
9. Write a Python program to list all files in a directory in Python.
'''
from os import listdir
from os.path import isfile, join
list_files = [f for f in listdir('C:\\Users\\fortune\Desktop\Hash Analytics\KPMG\Day6 Tasks Solutions')]
print(list_files) |
4d4f1d08f0399baafb6b97e3358928e7e24b0f0a | N0TEviI/PythonCookbook | /chapter_12.py | 2,823 | 4.0625 | 4 | # /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "0LIN1ISA"
# Date:2018/3/11 22:38
"""
第12章 并发编程
"""
"""
12.1 启动与停止线程
"""
# 直接通过Thread方法来实现
import time
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()
# 通过继承Thread来实现,只要实现run方法
from threading import Thread
class CountDownThread(Thread):
def __init__(self, n):
super().__init__()
self.n = 0
def run(self):
while self.n > 0:
print('T-minus', self.n)
self.n -= 1
time.sleep(5)
# c = CountDownThread(5)
# c.start()
# multiprocessing多进程
import multiprocessing
c = CountDownThread(5)
p = multiprocessing.Process(target=c.run)
p.start()
"""
12.2 判断线程是否已经启动
"""
# 使用threading的event对象
from threading import Thread, Event
import time
# Code to execute in an independent thread
def countdown(n, started_evt):
print('countdown starting')
started_evt.set()
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
# Create the event object that will be used to signal startup
started_evt = Event()
# launch the thread and pass the startup event
print('Launching countdown')
t = Thread(target=countdown, args=(10, started_evt))
t.start()
# Wait for the thread to start
started_evt.wait()
print('countdown is running')
import threading
def do(event, name):
print(name + ':start')
event.wait()
print(name + ':execute')
event_obj = threading.Event()
for i in range(10):
t = threading.Thread(target=do, args=(event_obj, 'thread_' + str(i)))
t.start()
event_obj.clear()
inp = input('input:')
if inp == 'true':
event_obj.set()
# event对象通过set会唤醒所有等待他的线程,
# 如果只想唤醒单个线程,可以使用信号量或者Condition
# Worker thread
import threading
def worker(n, sema):
# wait to be signaled
sema.acquire()
# do some work
print('working', n)
# Create some threads
sema = threading.Semaphore(0)
nworkers = 10
for n in range(nworkers):
t = threading.Thread(target=worker, args=(n, sema,))
t.start()
sema.release()
sema.release()
"""
12.3 线程间通信
"""
# 通过Queue的put()和get()来操作
from queue import Queue
from threading import Thread
def producer(out_q):
while running:
for i in range(100):
out_q.put(i)
def consumer(in_q):
while True:
data = in_q.get()
print(data)
in_q.task_done()
q = Queue()
t1 = Thread(target=producer, args=(q,))
t2 = Thread(target=consumer, args=(q,))
t1.start()
t2.start()
q.join()
"""
12.4 给关键部分加锁
""" |
ab8a655a2122a8432b91815b80c96499a74372a6 | yyxlh/learn_some_thing | /python/exception.py | 1,401 | 3.75 | 4 | #!/usr/bin/python3
import sys
'''
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
# j = i * (1/0)
# io异常
except OSError as err:
print("OS error: {0}".format(err))
# 值转换异常
except ValueError:
print("Could not convert data to an integer.")
# 其他异常
except:
print("Unexpected error:", sys.exc_info()[0])
raise
# 如果没有异常,还需要做的工作
else:
print('Running ok, i is:', i)
print('\n--------------------------------------------------\n')
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
print('\n--------------------------------------------------\n')
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2 * 2)
except MyError as e:
print('My exception occurred, value:', e.value)
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
divide(2, 1)
divide(2, 0)
divide('2', '1')
for line in open("myfile.txt"):
print(line, end="")
print('\n--------------------------------------------------\n')
'''
with open("myfile.txt") as f:
for line in f:
print(line, end="")
|
86da7f366dff1dc7e27a303d86ed856d0ae05d48 | imankulov/zeromr | /zeromr/samples.py | 608 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import os
def word_count_map(key, value):
"""
"Mapper". Count number of words
"""
for word in value.split():
yield word, 1
def word_count_reduce(word, values):
"""
"Reducer". Count number of words
"""
yield word, sum(values)
def read_file(source):
"""
"Source reader". Read contents of the file line by line
Yield key, value in the form of (lineno, line)
"""
if not os.path.isfile(source):
return
with open(source) as fd:
for i, line in enumerate(fd.readlines()):
yield i, line.strip()
|
440f25e926f480b6f880a4977f153d437572ea70 | martybgit/python_samples | /read_csv_dictreader.py | 484 | 3.90625 | 4 | # Create an object that operates like a regular reader
# but maps the information in each row to an OrderedDict
# whose keys are given by the optional fieldnames parameter.
# As of Python 3.6 - Returned rows are type OrderedDict.
# https://docs.python.org/3/library/csv.html
import csv
with open('c:/Data/repos/python_scripts/data/names.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['first_name'], row['last_name'])
print(row) |
f9e3740ba1078e9acc1c860d37cf2f8d80ab8955 | deepika9294/PPL | /Assignment_4/shapes.py | 4,131 | 4.3125 | 4 |
import math
from parent import Shape
# base abstract class
class Rectangle(Shape):
sides = 4
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def printarea(self):
print("Area is:", self.length * self.breadth)
def printperimeter(self):
print("Perimeter is:", 2 * (self.length + self.breadth))
def get_sides(self):
print("Number of sides are:", self.sides)
# regPolygon is inherited from Shape
# Polymorphism is shown by printarea, printperimeter an get_sides function
class regPolygon(Shape):
def __init__(self, nsides=3, side=4):
self.n = nsides
self.l = side
def printarea(self, name):
p = self.l * self.n
a = p/math.tan(180/self.n)
A = p * a
print(f"Area of {name} is: ", A/2)
def printperimeter(self, name):
print(f"Perimeter of {name} is: ", self.n * self.l)
def get_sides(self, name):
print(f"Number of sides in a {name} are: ", self.n)
# Square is inherited from regPolygon
class Square(regPolygon):
def diagonal(self):
print("Length of diagonal is: ", math.sqrt(2) * self.l)
class Pentagon(regPolygon):
def no_diagonal(self):
print("Number of diagonal is: ", self.n*(self.n - 3) % 2)
class Hexagon(regPolygon):
def no_diagonal(self):
print("Number of diagonal is: ", self.n*(self.n - 3) % 2)
class Rhombus(Shape):
sides = 4
def __init__(self, height, base):
self.h = height
self.b = base
def printarea(self):
print("Area of rhombus is: ", self.b * self.h)
def printperimeter(self):
print("Perimeter of rhombus is: ", self.b * 4)
def get_sides(self):
print("Number of sides in a rhombus are:", self.sides)
class Trapezoid(Shape):
sides = 4
def __init__(self, height, base, s, c, d):
self.h = height
self.b = base
self.s = s
self.c = c
self.d = d
def printarea(self):
print("Area of trapezoid is: ", (self.b + self.s) * self.h / 2)
def printperimeter(self):
print("Perimeter of trapezoid is: ",
self.c + self.s + self.b + self.d)
def get_sides(self):
print("Number of sides in a trapezoid are:", self.sides)
class Circle:
def __init__(self, r):
self.radius = r
def area(self):
return math.pi * math.pow(self.radius, 2)
def circumference(self):
return 2 * math.pi * (self.radius)
class Ellipse(Circle):
def __init__(self, a, b):
self.a = a
self.b = b
def area(self):
return math.pi * (self.a) * (self.b)
def circumference(self):
return math.pi * ((self.a) + self.b)
class Sphere(Circle):
def surface_area(self):
return 4 * super().area()
if __name__ == "__main__":
r1 = Rectangle(40, 80)
r1.printarea()
r1.printperimeter()
r1.get_sides()
print("\n")
r2 = Rhombus(40, 80)
r2.printarea()
r2.printperimeter()
r2.get_sides()
print("\n")
t1 = Trapezoid(40, 80, 40, 20, 40)
t1.printarea()
t1.printperimeter()
t1.get_sides()
print("\n")
rp1 = regPolygon(9, 30)
rp1.printarea("Nonagon")
rp1.printperimeter("nonagon")
rp1.get_sides("nonagon")
print("\n")
s1 = Square()
s1.diagonal()
s1.printarea("Square")
s1.printperimeter("square")
print("\n")
p1 = Pentagon()
p1.no_diagonal()
p1.printarea("Pentagon")
p1.printperimeter("Pentagon")
p1.get_sides("nonagon")
print("\n")
h1 = Pentagon()
h1.no_diagonal()
h1.printarea("Hexagon")
h1.printperimeter("Hexagon")
h1.get_sides("nonagon")
print("\n")
c1 = Circle(25)
print("Printing area and circumference of Circle :")
print(c1.area())
print(c1.circumference())
print("\n")
e1 = Ellipse(25, 50)
print("Printing area and circumference of ellipse :")
print(e1.area())
print(e1.circumference())
print("\n")
s = Sphere(5)
print("Printing surface area of sphere:")
print(s.surface_area())
|
6864a712e5694eca28d9e5529e041924350adb96 | cbluth/ssh-ca | /ssh_ca/utils.py | 3,465 | 3.515625 | 4 | import sys
import time
import unittest
def convert_relative_time(time_string):
"""Takes a single +XXXX[smhdw] string and converts to seconds"""
last_char = time_string[-1]
user_value = time_string[0:-1]
if last_char == 's':
seconds = int(user_value)
elif last_char == 'm':
seconds = (int(user_value) * 60)
elif last_char == 'h':
seconds = (int(user_value) * 60 * 60)
elif last_char == 'd':
seconds = (int(user_value) * 60 * 60 * 24)
elif last_char == 'w':
seconds = (int(user_value) * 60 * 60 * 24 * 7)
else:
sys.stderr.write("Invalid time format: %s. "
"Missing s/m/h/d/w qualifier\n" % (time_string,))
sys.exit(-1)
return seconds
def parse_time(time_string, reference_time=int(time.time())):
"""Parses a time in YYYYMMDDHHMMSS or +XXXX[smhdw][...]
Returns epoch time. Just like ssk-keygen, we allow complex
expressions like +5d7h37m for 5 days, 7 hours, 37 minutes.
reference_time should be the epoch time used for calculating
the time when using +XXXX[smhdw][...], defaults to now.
"""
seconds = 0
if time_string[0] == '+' or time_string[0] == '-':
# parse relative expressions
sign = None
number = ''
factor = 's'
for c in time_string:
if not sign:
sign = c
elif c.isdigit():
number = number + c
else:
factor = c
seconds += convert_relative_time(
"%s%s%s" % (sign, number, factor))
number = ''
factor = 's'
# per ssh-keygen, if specifing seconds, then the 's' is not required
if len(number) > 0:
seconds += convert_relative_time("%s%ss" % (sign, number))
epoch = seconds + reference_time
else:
# parse YYYYMMDDHHMMSS
struct_time = time.strptime(time_string, "%Y%m%d%H%M%S")
epoch = int(time.mktime(struct_time))
return epoch
def epoch2timefmt(epoch):
"""Converts epoch time to YYYYMMDDHHMMSS for ssh-keygen
ssh-keygen accepts YYYYMMDDHHMMSS in the current TZ but doesn't
understand DST so it will add an hour for you. :-/
"""
struct_time = time.localtime(epoch)
if struct_time.tm_isdst == 1:
struct_time = time.localtime(epoch - 3600)
return time.strftime("%Y%m%d%H%M%S", struct_time)
class ParseTimeTests(unittest.TestCase):
def setUp(self):
self.now = int(time.time())
def test_one_week(self):
one_week = parse_time("+1w", self.now)
one_week_check = self.now + (60 * 60 * 24 * 7)
self.assertEqual(one_week_check, one_week)
def test_one_day(self):
one_day = parse_time("+1d3h15s", self.now)
one_day_check = self.now + (60 * 60 * 27) + 15
self.assertEqual(one_day_check, one_day)
def test_two_thirty(self):
two_thirty = parse_time("+2h30m", self.now)
two_thirty_check = self.now + (60 * 60 * 2.5)
self.assertEqual(two_thirty_check, two_thirty)
def test_epoch2timefmt(self):
struct_time = time.localtime(self.now)
offset = 0
if struct_time.tm_isdst == 1:
offset = 3600
longtime = epoch2timefmt(self.now + offset)
rightnow = parse_time(longtime)
self.assertEqual(rightnow, self.now)
if __name__ == '__main__':
unittest.main()
|
756776dc7c30864c53fc653b5188ef2a68686add | m5gnki5/algorithm_training_21 | /01/01c.py | 1,108 | 4.0625 | 4 | """
Задача просит сравнить телефонный номер из первого ввода с тремя следующими
с учётом префиксов и доп.символов. Подробнее по ссылке
https://contest.yandex.ru/contest/27393/problems/C/
"""
# ввод — три телефонных номера
num_in_question = input()
first = input()
second = input()
third = input()
sym_list = ["+", "-", "(", ")"]
# цикл приводит номера к единому формату
if all([num_in_question, first, second, third]):
nums = []
for num in num_in_question, first, second, third:
clean_num = []
for sym in num:
if sym not in sym_list:
clean_num.append(sym)
if len(clean_num) == 11 and (clean_num[0]=="7" or clean_num[0]=="8"):
clean_num.pop(0)
elif len(clean_num) == 7:
clean_num.insert(0, "495")
clean_num = "".join(clean_num)
nums.append(clean_num)
# цикл сверяет первый чистый номер с остальными
for i in nums[1:]:
if i == nums[0]:
print("YES")
else:
print("NO")
|
aacab4110d8bf137dd1d1b4119c0e2f2ffd3bbbc | wikilike7/python-crash-course | /chap2/name_cases.py | 448 | 4.1875 | 4 | name = 'Frod'
expr = ', would you like to learn some Python today ?'
hi = 'Hello '
print(hi + name + expr)
print(hi + name.lower() + expr)
print(hi + name.upper() + expr)
famous_person = 'Steven Jobs'
message = 'once said, "We\'re here to put a dent in the universe. Otherwise why else even be here?"'
print(famous_person + message)
name_frod = ' Frod Baggins '
print(name_frod)
print(name_frod.lstrip())
print(name_frod.rstrip())
print(name_frod.strip()) |
fdb326bdba0b0bd8c433a284ee94278b0b01d89f | alexcash09/100DaysOfCode | /python/ifelse.py | 88 | 3.90625 | 4 | x = 8
y = 5
if x > y:
print('x is greater ', x)
else:
print('y is greater ', y) |
5e99a5b8a09bc96d2f11acbb8c051758e903d779 | Ahmad-Magdy-Osman/IntroComputerScience | /Name/mOsmanAWk01.py | 893 | 3.671875 | 4 | #----------------------------------------------------------------------------------
#Author Name: Ahmad M. Osman
#File Name: OsmanAWk01.py
#Date: September 8, 2016
#Purpose: CS 150 - Worksheet #01
# Displaying my name in a box and displaying
# my initials in big initails of the same
# letters through the print function
#----------------------------------------------------------------------------------
#For code readability purposes, the output starts and ends with an empty line.
#Problem #1
print("""
+-------+
| Ahmad |
+-------+
""")
#Problem #2
print("""
AA MM MM OOOOOOOO
A A M M M M O O
A A M M M M O O
AAAAAAAA M M M O O
A A M M O O
A A M M O O
A A M M OOOOOOOO
""") |
2b61697a438d3e727888c83586e9066aa624b0e5 | nikitasurya/dictionary | /dictionary.py | 1,058 | 3.59375 | 4 | from sys import argv
from urllib2 import Request, urlopen, URLError
import json
#script, word = argv
#print argv, type(argv),
def internet_on():
try:
urlopen('http://216.58.192.142', timeout=1)
print "Internet is ON"
return True
except urllib2.URLError as err:
print "Internet is not working"
return False
class Dictionary(object):
def __init__(self, word):
self.meaning=word
def get_definition(self):
request = Request('http://api.pearson.com/v2/dictionaries/entries?headword=%r'%self.meaning)
response = urlopen(request)
read_response = response.read()
tmp = json.loads(read_response)
tmp.keys()
print tmp['results'][0]['senses'][0]['definition']
#https://www.codecademy.com/courses/python-intermediate-en-6zbLp/0/1?curriculum_id=50ecbb9b71204640240001bf
#http://developer.pearson.com/apis/dictionaries#/
x=internet_on()
if x==True:
meaning=Dictionary("autism")
meaning.get_definition()
else:
print"please turn on your internet" |
b86c24e0b667a773c81738769f97a526c6339c7f | maripaixao/PycharmProjects | /pythonteste/ex084.py | 803 | 3.578125 | 4 | # Lista Composta e Análise de Dados
temp = []
princ = []
maior = menor = 0
while True:
temp.append(str(input('Digite seu nome: ')))
temp.append(float(input('Informe seu peso: ')))
if len(princ) == 0:
maior = menor = temp[1]
else:
if temp[1] > maior:
maior = temp[1]
if temp[1] < menor:
menor = temp[1]
princ.append(temp[:])
temp.clear()
resp = str(input('Deseja continuar? [S/N] '))
if resp in 'Nn':
break
print('-=' * 30)
print(f'Você cadastrou {len(princ)} pessoas.')
print(f'O maior peso foi de {maior}kg. Peso de ', end='')
for p in princ:
if p[1] == maior:
print(f'{p[0]}')
print(f'O menor peso foi de {menor}kg. Peso de ', end='')
for p in princ:
if p[1] == menor:
print(f'{p[0]}') |
2d6597944cfeb06889aa95abddc28557db1ead62 | DiegoSusviela/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 154 | 3.53125 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
lis = my_list[:]
if 0 <= idx < len(my_list):
lis[idx] = element
return lis
|
f37395dd9cf63668f0323d6a22f7ae8f53d01cc6 | lingyun666/algorithms-tutorial | /others/FindNumberInArray/findOneNum.py | 976 | 4.03125 | 4 | # coding:utf8
'''
题目:一个整型数组里除了一个数字之外,其他的数字都出现了两次。请写程序找出这那个只出现一次的数字。
时间复杂度 O(n)
空间复杂度 O(1)
'''
# 解题思路:
# 思路很简单, 直接使用异或运算即可求出, 即 result = a^b^b^c^c = a
# 如果数组中只有一个数出现一次, 其它数均出现两次, 那么可以直接使用异或运算求出单数, 因为重复的数在异或运算下为 0
def find_one_num(arr):
result = 0
for i in range(0, len(arr)):
result ^= arr[i]
return result
if __name__ == '__main__':
print(find_one_num([1, 2, 3, 4, 5, 4, 3, 2, 1]))
# 补充:
# 异或运算其它用法(注: 异或运算满足交换律)
# 交换两个数而不占用新的空间
def swap(num1, num2):
num1 ^= num2
num2 ^= num1
num1 ^= num2
return (num1, num2)
# 判断两个数字是否相等
def equal(num1, num2):
return (num1 ^ num2) == 0 |
afac9e926aaeaad167af632bace2510737ac4cd2 | luozhaoyu/study | /lc/reconstruct_itinery_332.py | 2,662 | 3.84375 | 4 | from typing import List
import copy
class Solution:
"""
Algorithm:
backtrack to ensure all ticket will be used
BFS will find the shortest one
"""
def find_next_positions(self, position, past_tickets):
remain_positions = copy.copy(self.possible_destinations.get(position))
if not remain_positions:
return []
# remove position visited by previous ticket
for past_ticket in past_tickets:
start, end = past_ticket
if start == position and end in remain_positions:
# print(remain_positions, end)
remain_positions.remove(end)
# print(past_tickets, position, remain_positions)
return sorted(remain_positions)
def backtrack(self, position, past_tickets):
# exit if all ticket used
if past_tickets and len(past_tickets) == len(self.tickets):
return past_tickets
# find next possible position
for next_position in self.find_next_positions(position, past_tickets):
ticket = [position, next_position]
past_tickets.append(ticket)
result = self.backtrack(next_position, past_tickets)
if result:
return result
# come back to try next one
past_tickets.pop()
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
self.tickets = tickets
self.possible_destinations = {}
for ticket in tickets:
start, end = ticket[0], ticket[1]
if start in self.possible_destinations:
self.possible_destinations[start].append(end)
else:
self.possible_destinations[start] = [end]
# print(self.possible_destinations)
result = self.backtrack("JFK", [])
if not result:
return result
# print(result)
return [ticket[0] for ticket in result] + [result[-1][-1]]
s = Solution()
tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
tickets = [["EZE","AXA"],["TIA","ANU"],["ANU","JFK"],["JFK","ANU"],["ANU","EZE"],["TIA","ANU"],["AXA","TIA"],["TIA","JFK"],["ANU","TIA"],["JFK","TIA"]]
tickets = [["EZE","TIA"],["EZE","HBA"],["AXA","TIA"],["JFK","AXA"],["ANU","JFK"],["ADL","ANU"],["TIA","AUA"],["ANU","AUA"],["ADL","EZE"],["ADL","EZE"],["EZE","ADL"],["AXA","EZE"],["AUA","AXA"],["JFK","AXA"],["AXA","AUA"],["AUA","ADL"],["ANU","EZE"],["TIA","ADL"],["EZE","ANU"],["AUA","ANU"]]
s.findItinerary(tickets)
|
7af6179934e8d203f4bf737a83dbee44041b772e | rohith402/Practice | /String Module/src/PilingUp.py | 768 | 3.578125 | 4 | from collections import deque
n = 1
for i in range(n):
s = 3
d = deque([1,3,2])
exp = deque()
flag = True
while (len(d) != 0):
if(len(exp) != 0):
if (d[0] >= d[-1]) and (d[0] <= exp[0]):
exp.append(d[0])
d.popleft()
elif (d[-1] > d[0]) and (d[-1] <= exp[0]):
exp.append(d[-1])
d.pop()
else:
flag = False
break;
else:
if (d[0] > d[-1]):
exp.append(d[0])
d.popleft()
else:
exp.append(d[-1])
d.pop()
if flag:
print('Yes')
else:
print('No')
|
e51cacd62e2775cbaae2936c6164e8268d8f6db8 | S-Rosemond/Beginner0 | /0Algorithms/Tree/tree.py | 1,153 | 3.859375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
self.size = 0
def insert(self, value):
node = Node(value)
if not self.root:
self.root = node
self.size += 1
return self
else:
current = self.root
while(True):
if value == current.value:
return 'No duplicates allowed'
if value < current.value:
if current.left == None:
current.left = node
self.size += 1
return self
current = current.left
else:
if current.right == None:
current.right = node
self.size += 1
return self
current = current.right
tree = Tree()
tree.insert(50)
tree.insert(49)
tree.insert(52)
test = tree.root
print(test.value, test.left.value, test.right.value)
|
439d24ceb6a041848486f84af15ba2a10c428011 | Reetishchand/Leetcode-Problems | /01122_RelativeSortArray_Easy.py | 1,193 | 4.09375 | 4 | '''Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Constraints:
1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
All the elements of arr2 are distinct.
Each arr2[i] is in arr1.'''
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
myhash={}
k=0
for i in arr1:
try:
myhash[i]+=1
except:
myhash[i]=1
for i in range(len(arr2)):
rep = myhash[arr2[i]]
for j in range(rep):
arr1[k]=arr2[i]
k+=1
myhash.pop(arr2[i])
for i in sorted(myhash.keys()):
rep = myhash[i]
for j in range(rep):
arr1[k]=i
k+=1
return arr1
|
5cc1939e71703ea58c34be0e3c3a5d5bd83c7820 | meshack-mbuvi/Andelabs | /commandline_API.py | 1,046 | 4 | 4 | import requests
'''
This program use a weather api to obtain weather information for various cities across the world
The output contains the country code,city name,coordinates of the city,sunset and sunrise time,
minimum and maximum temperatures and pressure experienced in the city in question
:Author:Meshack Mbuvi
:Email:meshmbuvi@gmail.com
:Phone:+254719800509
'''
def get_weather_data(acity):
city=acity
resp = requests.get('http://api.openweathermap.org/data/2.5/weather?q=%s&APPID=c8c1059a447fa66e786c945155f30aa2' %(city))
weather=resp.json()
print('Country \t\t:{sys[country]} \
\nCity\t\t\t:{name} \
\nCoordinates\t\t:["latitude":{coord[lat]},"longitude":{coord[lon]}]\
\nSunrise\t\t\t:{sys[sunrise]}\
\nSunset\t\t\t:{sys[sunset]}\
\nTemperatures\t:["min_temp":{main[temp_min]},"max_temp":{main[temp_max]}]\
\nPressure\t\t:{main[pressure]}'.format(**weather))
print'*******************************************************'
if __name__=='__main__':
cities=['Nairobi','Kampala','London']
for city in cities:
get_weather_data(city) |
1b2c998edf258333cfc22e2e4dcee06dd2d8c64f | brianchiang-tw/leetcode | /No_0067_Add Binary/add_binary_by_int_and_fstring.py | 1,040 | 3.875 | 4 | '''
Description:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
class Solution:
def addBinary(self, a: str, b: str) -> str:
return f'{(int(a, 2) + int(b, 2)):b}'
# n : the max length between input a and b
## Time Compleixty:
#
# The overhead in time is type conversion from bit-string to decimal value, which is of O( n ).
# The cost of addition is of O( n ) also.
## Space Complexity:
#
# The overhead in space is the storage for output bit-string, which is of O( n ).
def test_bench():
test_data = [
('11', '1'),
('1010', '1011')
]
# expected output:
'''
100
10101
'''
for test_pair in test_data:
print( Solution().addBinary( *test_pair ) )
return
if __name__ == '__main__':
test_bench()
|
89197ec00128ef116c85a6ce10ce208e6c1300fd | balajisaikumar2000/Python-Snippets | /Lambda.py | 251 | 4.21875 | 4 | #lambda function is small anonymous function.
x = lambda a : a + 10
print(x(5))
#------------------
x = lambda a,b,c : a + b + c
print(x(5,10,15))
#---------------
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11)) |
834a9fbb5fa6cb72eb30879b9cb681fcc9931751 | Kalinga/pythonLearning | /tutorials/basic/playingWithRandom.py | 613 | 3.796875 | 4 | import random as rn
import string
print "randrange(1,10):"
for i in range(10):
print rn.randrange(1,10)
print "rn.randint(1, 10)"
for i in range(10):
print rn.randint(1, 10)
operations = ['Add', 'Sub', 'Mul', 'Div']
print "rn.choice(operations):"
for i in range(10):
print rn.choice(operations)
#Random Password
passwd = ''.join(rn.choice(rn.choice(string.ascii_letters + string.digits)) for x in range(50))
print "Generated Random Passwd: ", passwd
gen = lambda x: ''.join(rn.choice(rn.choice(string.ascii_letters + string.digits)) for y in range(x))
print "10 Letter random passwd: ", gen(10)
|
44c98306f60a8c63bcecc5264a2b9be0553e873e | ayoub-berdeddouch/Leet_Code_Problems_Solution | /Python Language/ProblemID_1929.py | 543 | 3.953125 | 4 | """
Link - https://leetcode.com/problems/concatenation-of-array/
Problem Description
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
"""
# Time Complexity Space Complexity
# O(1) O(1)
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums+nums
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.