text stringlengths 37 1.41M |
|---|
import random
class Deck():
'''
Represents a deck of 52 cards.
'''
def __init__(self):
class Card():
'''
Represents and individual card of a deck with attributes of a face (or number), suit, and value.
'''
def __init__(self, suit, value, face):
self.suit = suit
self.value = value
self.face = face
self.image_map = str(self.face) + "_of_" + self.suit + '.svg'
self.suits = ['clubs', 'spades', 'hearts', 'diamonds']
self.faces = ['jack', 'queen', 'king']
self.number_cards = [Card(suit, value, value) for value in range(2, 11) for suit in self.suits]
self.face_cards = [Card(suit, 10, face) for face in self.faces for suit in self.suits]
self.ace_cards = [Card(suit, 11, 'ace') for suit in self.suits]
self.cards = self.face_cards + self.number_cards + self.ace_cards
class Hand():
def __init__(self, id):
self.cards = []
self.id = id
self.total = 0
self.bust = False
self.door_value = None
self.bet = 0
self.active = False
self.can_double = True
def __check_bust(self):
'''
Updates the bust attribute to True if the total attribute exceeds 21
'''
if self.total > 21:
self.bust = True
def __update_door_value(self):
'''
Updates door value for the face value of the the first card in the hand.
This is the "door card" for the dealer in the first round
'''
self.door_value = self.cards[0].value
def __update_total(self):
'''
Recalculates the total attribute to include a new card. If the card is an ace it counts as 11 or 1 points,
whichever does not make the player bust
'''
if 'ace' in [card.face for card in self.cards]:
non_ace_total = sum([card.value for card in self.cards if card.face != 'ace'])
running_total = non_ace_total
for card in self.cards:
if card.face == 'ace':
if (running_total + card.value) > 21:
running_total += 1
else:
running_total += 11
self.total = running_total
else:
self.total = sum([card.value for card in self.cards])
def add_card(self, card):
'''
Adds a card to the hand
'''
self.cards.append(card)
self.__update_total()
self.__update_door_value()
self.__check_bust()
class Player:
'''
Represents a blackjack player
'''
def __init__(self):
self.hands = {}
self.total = 0
self.bust = False
self.bank = 100
def can_split(self):
'''
Determine if the first two cards dealt to the player are the same. If they are the same, the player
will be given the option to split
'''
return True if len(set([card.value for card in self.hands[0]])) == 1 else False
def split(self):
'''
Splits the players hand
'''
pass
def add_hand(self, hand_id):
'''
Adds a hand to the player object
'''
hand_key = hand_id
self.hands[hand_key] = Hand(hand_id)
def split_cards(self):
'''
Takes first card from first hand and moves it to the second hand
'''
hand_one = self.hands[1]
first_card = hand_one.cards[0]
second_card = hand_one.cards[1]
hand_one.total = first_card.value
hand_two = self.hands[2]
hand_two.cards.append(second_card)
hand_two.total = second_card.value
hand_two.bet = hand_one.bet
hand_one.cards.remove(second_card)
class Dealer(Player):
'''
Represents the dealer, inherits from the "Player" class.
'''
def __init__(self):
super().__init__()
self.hands = {1 : Hand(1)}
def get_hole_card(self):
'''
Returns the second card dealt to the dealers hand
'''
return self.hands[1].cards[1]
class Game():
'''
Represents the blackjack game.
'''
def __init__(self, Dealer, Deck, Player):
self.deck = Deck().cards
self.player = Player()
self.dealer = Dealer()
self.round = 1
def draw_card(self, target, hand_id):
'''
Draws a card from the deck and adds it to either the dealer or player (the target)
'''
card_draw = random.choice(self.deck)
self.deck.remove(card_draw)
if target == 'player':
self.player.hands[hand_id].add_card(card_draw)
elif target == 'dealer':
self.dealer.hands[hand_id].add_card(card_draw)
return card_draw
def new_deck(self):
'''
Adds a fresh deck to the game
'''
self.deck = Deck().cards
|
# constants
coins = [0.25, 0.1, 0.05, 0.01]
def main():
print(round(calc_change(get_input(), coins)))
def get_input():
"""Return positive float number as valid user input"""
while True:
try:
cash = float(input("Change owned: "))
except ValueError:
continue
else:
if cash <= 0:
continue
break
return cash
def calc_change(cash: float, coins: list):
"""Returns minimal number of coins for change"""
counter = 0
for i in coins:
counter = counter + (cash // i)
cash = round(cash % i, 2)
if cash == 0:
break
return counter
main() |
# -*- coding: utf-8 -*-
import urllib2
import urllib
import json
key = "39c4e5aceb68dafb76cddbdfdecf5520"
#pernw tis suntetagmenes
x = input("Geografiko platos?: ")
y = input("geografiko mhkos?:")
#metatroph tou float number h int pou tha eiselthei stis suntetagmenes se string
x = str(x)
y = str(y)
#phgenw kai pernw ta data apo to site
url = str("http://api.openweathermap.org/data/2.5/weather?lat=" + x +"&lon="+ y + "&APPID=" + key + "")
#basikes metatropes ne json gia na parw ta dedomena
result = urllib2.urlopen(url)
content = result.read()
data = json.loads(content.decode('utf8'))
term = "rain"
print (data)
temp = data['main']['temp'] - 273
weathernow = data['weather'][0]['description']
print (data ['main']['temp'])
print (data['weather'][0]['description'])
#ta statment gia ths epiloges
if weathernow == term :
print(" i am singing in the rain")
elif temp > 20 :
print("nice")
elif temp < 5 :
print("brrr") |
import os
#分岐確認
var_ = 9
if var_ < 10:
print("10未満")
else:
print("10以上")
#現在ディレクトリの一つ上のディレクトリ一覧を取得
for i in os.listdir("../"):
print(i) |
def funcao_numero(num = 0):
ultimo = num
primeiro = 1
while True:
for c in range(1,primeiro + 1):
print(f'{c} ',end=' ')
print()
primeiro += 1
if primeiro > ultimo:
break
num = int(input('Informe um número para ver uma tabela personaliada: '))
funcao_numero(num) |
# Python program to implement Diffie-Hellman key exchange
import random
def is_prime(n):
count = 0
for i in range(1, int(n/2)+1):
if (n % i == 0):
count += 1
if (count == 1):
return True
else:
return False
while(True):
p = int(input("Enter a prime number : "))
if (is_prime(p)):
break
g = int(input("Enter the primitive root of prime number : "))
Pr_A = random.randint(1,p)
print("\nPrivate key of A : {}".format(Pr_A))
Pr_B = random.randint(1,p)
print("Private key of B : {}".format(Pr_B))
Pu_A = (g**Pr_A) % p
print("\nPublic key of A : {}".format(Pu_A))
Pu_B = (g**Pr_B) % p
print("Public key of B : {}".format(Pu_B))
Se_A = (Pu_B**Pr_A) % p
Se_B = (Pu_A**Pr_B) % p
if(Se_A==Se_B):
print("\nThe shared secret is : {}".format(Se_A)) |
# Python program to generate pseudo-random numbers using the middle square method
seed = int(input("Enter a 4 digit number : "))
number = seed
print(f"The seed is {seed}.")
print("The random numbers are : ")
already_generated = set()
while(True):
already_generated.add(number)
Xi = str(int(number)**2)
# print(f"Square : {Xi}")
# Builtin function to fill zeros / prepend 0s.
# Xi.zfill(8)
zeros_to_be_added = 8 - len(Xi)
for i in range(zeros_to_be_added):
Xi = '0' + Xi
# print(f"After padding : {Xi}")
number = str(Xi)[2:6]
if(number in already_generated):
break
if (int(number)==0):
break
print(int(number)) |
from typing import Optional
class Node(object):
left: "Node"
right: "Node"
data: int
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class BST(object):
root: Optional[Node]
size: int
def __init__(self):
self.root = None
self.size = 0
def display(self):
self.__display(self.root)
print("*************************")
def __display(self, node: Node):
if node is None:
print("NULL => NULL <= NULL")
return
if node.left is not None:
print(str(node.left.data) + " => ", end="")
else:
print("NULL => ", end="")
print(str(node.data), end="")
if node.right is not None:
print(" <= " + str(node.right.data), end="")
else:
print(" <= NULL", end="")
print()
if node.left is not None:
self.__display(node.left)
if node.right is not None:
self.__display(node.right)
def insert(self, data: int):
self.root = self.__insert(self.root, data)
self.size += 1
def __insert(self, node: Node, data: int) -> Node:
if node is None:
return Node(data, None, None)
if data < node.data:
node.left = self.__insert(node.left, data)
else:
node.right = self.__insert(node.right, data)
return node
def remove(self, data: int):
self.root = self.__remove(self.root, data)
def __remove(self, node: Node, data: int) -> Optional[Node]:
if node is None:
return node
if data < node.data:
node.left = self.__remove(node.left, data)
elif data > node.data:
node.right = self.__remove(node.right, data)
else:
if node.left is None:
self.size -= 1
return node.right
elif node.right is None:
self.size -= 1
return node.left
else:
node.data = self.min_right(node).data
node.right = self.__remove(node.right, node.data)
return node
def min_right(self, node: Optional[Node]) -> Optional[Node]:
now: Node = node.right
if now is None:
return None
while now.left is not None:
now = now.left
return now
|
import random
import numpy as np
import pynmmso as nmmso
class Swarm:
"""
Represents a swarm in the NMMSO algorithm.
Arguments
---------
id : int
Id used to refer to the swarm
swarm_size : int
Maximum number of particles in the swarm
problem :
Instance of the problem class. Must implement get_bounds and fitness functions.
listener : subclass of nmmso.listeners.BaseListener
Listener object to receive notification of events. Optional.
Attributes
----------
id : int
A unique identification number of this swarm.
mode_location : numpy array
The location of this mode.
mode_value : float
The fitness of the mode location.
number_of_particles : int
Number of particles in the swarm.
history_locations : 2D Numpy array
The current locations of each particle in the swarm.
history_values : 1D Numpy array
The fitness values for current locations of each particle in the swarm.
velocities : 2D Numpy array
Current velocity of each particle in the swarm.
pbest_location : 2D Numpy array
The best location discovered for each particle.
pbest_value : 1D Numpy array
The fitness value associated with the best location for each particle in the swarm.
"""
def __init__(self, id, swarm_size, problem, listener=None):
self.id = id
self.swarm_size = swarm_size
self.problem = problem
self.listener = listener
self.mn = np.array(problem.get_bounds()[0])
self.mx = np.array(problem.get_bounds()[1])
self.changed = True
self.converged = False
self.num_dimensions = len(self.mn)
self.mode_location = None # Will be populated later on
self.new_location = None # Will be populated later on
self.mode_value = None # Will be populated later on
# Initialize locations for swarm elements
# current locations of swarm
self.history_locations = np.zeros((self.swarm_size, self.num_dimensions))
# current values of swarm
self.history_values = np.full(self.swarm_size, -np.inf)
# current best locations of swarm
self.pbest_locations = np.zeros((self.swarm_size, self.num_dimensions))
# current best values of swarm
self.pbest_values = np.full(self.swarm_size, -np.inf)
self.velocities = np.zeros((swarm_size, self.num_dimensions))
self.number_of_particles = 1
self.shifted_loc = None # Will be populated later on
self.dist = None # Will be populated later on
def set_initial_location(self):
"""Sets the initial location of a swarm."""
self.changed = True
self.new_location = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn
# random initial velocities of swarm
self.velocities[0, :] = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn
def set_arbitrary_distance(self):
"""Set an arbitrary distance - this is done when we only have one swarm"""
self.dist = np.min(self.mx-self.mn)
def increment(self):
""" Increments the swarm. """
new_location = self.mn - 1
d = self.dist
shifted = False
omega = 0.1
reject = 0
r = random.randrange(self.swarm_size) # select particle at random to move
while np.sum(new_location < self.mn) > 0 or np.sum(new_location > self.mx) > 0:
# if swarm is not yet at capacity, simply add a new particle
if self.number_of_particles < self.swarm_size:
usp = nmmso.Nmmso.uniform_sphere_points(1, self.num_dimensions)[0]
new_location = self.mode_location + usp * (d/2)
else:
# move an existing particle
shifted = True
self.shifted_loc = r
r1 = np.random.rand(self.num_dimensions)
r2 = np.random.rand(self.num_dimensions)
temp_vel = omega * self.velocities[self.shifted_loc, :] + \
2.0 * r1 * \
(self.mode_location - self.history_locations[self.shifted_loc, :]) + \
2.0 * r2 * \
(self.pbest_locations[self.shifted_loc, :] -
self.history_locations[self.shifted_loc, :])
if reject > 20:
# if we keep rejecting then put at extreme any violating design parameters
i_max = np.flatnonzero(
np.asarray(
self.history_locations[self.shifted_loc, :] + temp_vel > self.mx))
i_min = np.flatnonzero(
np.asarray(
self.history_locations[self.shifted_loc, :] + temp_vel < self.mn))
if i_max.size > 0:
temp_vel[i_max] = \
np.random.rand(i_max.size) * \
(self.mx[i_max] - self.history_locations[self.shifted_loc, i_max])
if i_min.size > 0:
temp_vel[i_min] = \
np.random.rand(i_min.size) * \
(self.history_locations[self.shifted_loc, i_min] - self.mn[i_min]) * -1
new_location = self.history_locations[self.shifted_loc, :] + temp_vel
reject = reject + 1
if shifted:
self.velocities[self.shifted_loc, :] = temp_vel
else:
# otherwise initialise velocity in sphere based on distance from gbest to next
# closest mode
self.number_of_particles = self.number_of_particles + 1
self.shifted_loc = self.number_of_particles - 1
temp_vel = self.mn - 1
reject = 0
while np.sum(temp_vel < self.mn) > 0 or np.sum(temp_vel > self.mx) > 0:
temp_vel = \
self.mode_location + \
nmmso.Nmmso.uniform_sphere_points(1, self.num_dimensions)[0] * (d / 2)
reject = reject + 1
if reject > 20: # resolve if keep rejecting
temp_vel = np.random.rand(self.num_dimensions)*(self.mx-self.mn) + self.mn
self.velocities[self.shifted_loc, :] = temp_vel
self.new_location = new_location
if self.listener is not None:
if shifted:
self.listener.swarm_moved_particle(self)
else:
self.listener.swarm_added_particle(self)
def initialise_with_uniform_crossover(self, swarm1, swarm2):
"""
Initialise a new swarm with the uniform crossover of the given swarms.
Arguments
---------
swarm1 : Swarm
swarm2 : Swarm
"""
self.new_location, _ = Swarm.uni(swarm1.mode_location, swarm2.mode_location)
self.evaluate_first()
self.changed = True
self.converged = False
def distance_to(self, swarm):
"""
Euclidean distance between this swarm and the given swarm, based on their mode locations.
Returns
-------
float
The distance between the two swarms.
"""
return np.linalg.norm(self.mode_location-swarm.mode_location)
def merge(self, swarm):
"""
Merges the give swarm into this swarm.
Arguments
----------
swarm : Swarm
Swarm to merge into this swarm.
"""
n1 = self.number_of_particles
n2 = swarm.number_of_particles
if n1 + n2 < self.swarm_size:
# simplest solution, where the combined active members of both populations
# are below the total size they can grow to
self.number_of_particles = n1 + n2
self.history_locations[n1:n1 + n2, :] = swarm.history_locations[0:n2, :]
self.history_values[n1:n1 + n2] = swarm.history_values[0:n2]
self.pbest_locations[n1:n1 + n2, :] = swarm.pbest_locations[0:n2, :]
self.pbest_values[n1:n1 + n2] = swarm.pbest_values[0:n2]
self.velocities[n1:n1 + n2, :] = swarm.velocities[0:n2, :]
else:
# select best out of combines population, based on current location (rather than pbest)
self.number_of_particles = self.swarm_size
temp_h_loc = \
np.concatenate((self.history_locations[0:n1, :], swarm.history_locations[0:n2, :]))
temp_h_v = \
np.concatenate((self.history_values[0:n1], swarm.history_values[0:n2]))
temp_p_loc = \
np.concatenate((self.pbest_locations[0:n1, :], swarm.pbest_locations[0:n2, :]))
temp_p_v = np.concatenate((self.pbest_values[0:n1], swarm.pbest_values[0:n2]))
temp_vel = np.concatenate((self.velocities[0:n1, :], swarm.velocities[0:n2, :]))
# get the indices of highest values
I = np.argsort(temp_h_v)[len(temp_h_v) - self.swarm_size:]
self.history_locations = temp_h_loc[I, :]
self.history_values = temp_h_v[I]
self.pbest_locations = temp_p_loc[I, :]
self.pbest_values = temp_p_v[I]
self.velocities = temp_vel[I, :]
def initialise_new_swarm_velocities(self):
"""Initialises velocities of a new swarm."""
reject = 0
temp_vel = self.mn - 1
while np.sum(temp_vel < self.mn) > 0 or np.sum(temp_vel > self.mx) > 0:
temp_vel = self.mode_location + \
nmmso.Nmmso.uniform_sphere_points(1, self.num_dimensions)[0] * \
(self.dist / 2)
reject += 1
if reject > 20:
temp_vel = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn
self.velocities[0, :] = temp_vel
def update_location_and_value(self, location, value):
"""
Updates the location and value of this swarm.
Arguments
---------
location : numpy arrya
New location of swarm
value : float
New fitness value at swarm location.
"""
previous_location = self.mode_location
previous_value = self.mode_value
self.mode_location = location
self.mode_value = value
if self.listener is not None:
self.listener.swarm_peak_changed(self, previous_location, previous_value)
def evaluate_first(self):
"""
Evaluates the new location. This is the first evaluation so no need to examine
if a shift has occurred
"""
# new location is the only solution thus far in mode, so by definition
# is also the mode estimate, and the only history thus far
y = self.problem.fitness(self.new_location)
if not np.isscalar(y):
raise ValueError("Problem class's fitness method must return a scalar value.")
if self.listener is not None:
self.listener.location_evaluated(self.new_location, y)
self.mode_location = self.new_location # gbest location
self.mode_value = y # gbest value
self.history_locations[0, :] = self.mode_location
self.history_values[0] = y
self.pbest_locations[0, :] = self.mode_location
self.pbest_values[0] = y
def evaluate(self, y):
"""
Takes the value at the new location and updates the swarm statistics and history.
Arguments
---------
y : float
fitness value at the new location.
"""
if y > self.mode_value:
self.update_location_and_value(self.new_location, y)
self.changed = True
self.history_locations[self.shifted_loc, :] = self.new_location
self.history_values[self.shifted_loc] = y
if y > self.pbest_values[self.shifted_loc]:
self.pbest_values[self.shifted_loc] = y
self.pbest_locations[self.shifted_loc, :] = self.new_location
def find_nearest(self, swarms):
"""
Finds the nearest swarm from the given set of swarms.
Returns
-------
swarm
The nearest swarm this this swarm.
"""
best_swarm = None
distance = np.inf
for s in swarms:
if self != s:
d = np.sum((self.mode_location - s.mode_location) ** 2)
if d < distance:
distance = d
best_swarm = s
self.dist = np.sqrt(distance) # track Euc distance to nearest neighbour
return best_swarm, self.dist
@staticmethod
def uni(x1, x2):
"""
Uniform binary crossover.
Arguments
---------
x1 : numpy array of parameters
x2 : numpy array of parameters
Returns:
numpy array
New array of parameters formed from uniform crossover.
"""
# simulated binary crossover
x_c = x1.copy()
x_d = x2.copy()
l = len(x1)
r = np.flatnonzero(np.random.rand(l, 1) > 0.5)
# ensure at least one is swapped
if r.size == 0 or r.size == l:
r = np.random.randint(l)
x_c[r] = x2[r]
x_d[r] = x1[r]
return x_c, x_d
|
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, K):
"""Shifts each value in A K times
:param A: Input array (int)
:param K: Number of shifts
:returns: new shiftes array [Int]
:rtype: Array (int)
"""
# write your code in Python 3.6
result = [0] * len(A) # prefill new array to avoid tmp memory solutions
for index in range(len(A)):
# calculate new position (current index + shift) and restart at 0 for values larger len(A)
shift = (index + K) % len(A)
result[shift] = A[index]
return result
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return self.val
class Solution(object):
def oddEvenList(self,head):
head2=head.next
h1=head
h2=head2
while h1 and h2:
h1.next= h2.next
h1=h1.next
if h1:
h2.next=h1.next
h2=h2.next
tail=head
while tail.next:
tail=tail.next
tail.next=head2
return head
def createlist(head,data):
p=head
for item in data:
p.next=ListNode(item)
p=p.next
return head
def printlist(head):
ls=[]
while head:
ls.append(head.val)
head=head.next
print(ls)
lhead=ListNode(1)
pl=createlist(lhead,[2,3,4,5,6,7,8])
printlist(pl)
s=Solution()
s.oddEvenList(pl)
printlist(pl)
|
from leetcode import TreeNode
class Solution(object):
def hasPathSum(self, root, sum):
if not root:
return False
if root.val==sum and root.left==None and root.right==None:
return True
else:
return self.hasPathSum(root.left,sum-root.val) or \
self.hasPathSum(root.right,sum-root.val)
|
# Definition for a binary tree node.
from leetcode import TreeNode
class Solution(object):
def levelOrderBottom(self, root):
if not root:
return []
res=[]
nodequeue1=[]
res.append([root.val])
nodequeue1.append(root)
nodequeue2=[]
while nodequeue1 or nodequeue2:
while nodequeue1:
currnode=nodequeue1.pop(0)
if currnode.left:
nodequeue2.append(currnode.left)
if currnode.right:
nodequeue2.append(currnode.right)
res.append([node.val for node in nodequeue2 if node])
nodequeue1=nodequeue2[:]
nodequeue2=[]
res.reverse()
res.pop(0)
return res
def createTree():
nd3 = TreeNode(1)
nd3.left = TreeNode(2)
nd3.right = TreeNode(3)
nd9=nd3.left
nd9.left=TreeNode(4)
nd9.right=None
nd20 = nd3.right
nd20.left = None
nd20.right = TreeNode(5)
return nd3
root=createTree()
s=Solution()
a=s.levelOrderBottom(root)
print(a)
|
from list import createlist
class Solution(object):
def removeNthFromEnd(self, head, n):
if n==1 and head.next==None:
return None
n=n-1
p=head
while n>0:
p=p.next
n-=1
if p.next:
self.deleteNode(p)
else:
pprev=head
while not pprev.next == p:
pprev.next=None
break
return head
def deleteNode(self,node):
if not node:
return None
node.val=node.next.val
node.next=node.next.next
s=Solution()
a=s.removeNthFromEnd(createlist([1,2]),1)
print(a)
|
from leetcode import ListNode
def createlist(data):
h=ListNode(data[0])
p=h
for item in data[1:]:
p.next=ListNode(item)
p=p.next
return h
def printlist(head):
ls=[]
while head:
ls.append(head.val)
head=head.next
print(ls)
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return self.val
class Solution(object):
def deleteDuplicates(self, head):
p=head
while p and p.next:
if p.val==p.next.val:
self.deleteNode(p)
else:
p=p.next
return head
def deleteNode(self,node):
node.val=node.next.val
node.next=node.next.next
lhead=ListNode(1)
pl=createlist(lhead,[1,2,2])
printlist(pl)
s=Solution()
w=s.deleteDuplicates(pl)
printlist(w) |
#!/usr/bin/python
import sys
# input from standard input
i = 0
for line in sys.stdin:
line = line.upper()
print line
# # remove whitespaces
# line = line.strip()
# # split the line into tokens
# tokens = line.split()
#
# for token in tokens :
# i = i + 1
# # write the results to standard output
# print '%s\t%s' % (token.upper() , i)
|
# -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 18 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Python *
* Professor : Thaís do Nascimento Viana *
* Nome do arquivo : questao_18.py *
***************************************************************************/
"""
class Questao_18():
""" This class implements the Pong game """
def __init__(self):
""" Constructor """
pygame.init()
pygame.display.set_caption('Questão 18')
self.FONTSIZE = 20
self.FONT = pygame.font.Font('freesansbold.ttf', self.FONTSIZE)
self.SCREEN_WIDTH = 500
self.SCREEN_HEIGHT = 400
self.SCREEN = pygame.display.set_mode(
(self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
self.FPS = 200
self.FPSCLOCK = pygame.time.Clock()
self.BORDER_SIZE = 5
self.finish = False
self.ball_x_dir = -1
self.ball_y_dir = -1
self.score_player_one = 0
self.score_player_two = 0
def init_game(self):
""" This function starts the game. """
player_one_pos = player().player_position()
player_two_pos = player().player_position()
player_one = pygame.Rect(70, player_one_pos, 5, 50)
player_two = pygame.Rect((430), player_two_pos, 5, 50)
_ball = pygame.Rect(245, 195, 5, 5)
while True:
self.SCREEN.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mouseX, mouseY = event.pos
player_one.y = mouseY
pygame.mouse.set_visible(1)
# creates the court
court().create_court(self.SCREEN)
# creates the players
player().create_player(self.SCREEN, self.SCREEN_HEIGHT, player_one)
player().create_player(self.SCREEN, self.SCREEN_HEIGHT, player_two)
# creates the ball
ball().create_ball(self.SCREEN, _ball)
# inits the ball movements
_ball = mov().ball_movement(_ball, self.ball_x_dir, self.ball_y_dir, self.score_player_one)
# verifies the collision existence
self.ball_x_dir, self.ball_y_dir = mov().verify_collision(_ball,
self.ball_x_dir,
self.ball_y_dir)
# verifies the ball collision
new_dir = mov().ball_collision(_ball, player_one, player_two, self.ball_x_dir)
# changes the direction accordingly with the direction's state
if new_dir == 1:
self.ball_x_dir *= new_dir
elif new_dir == -1:
self.ball_x_dir *= new_dir
else:
self.ball_x_dir = self.ball_x_dir
# computer movements
player_two = mov().computer_movements(_ball, self.ball_x_dir, player_two)
player_one = mov().computer_movements2(_ball, self.ball_x_dir, player_one)
# scores points for player one
self.score_player_one = mov().compute_score(
player_one, _ball, self.score_player_one, self.ball_x_dir, True)
# scores points for player two
self.score_player_two = mov().compute_score(
player_two, _ball, self.score_player_two, self.ball_x_dir, player_two=True)
# shows the score for both players
player().create_score(self.SCREEN, 'You', self.score_player_one, self.FONT, (100, 15))
player().create_score(self.SCREEN, 'PC', self.score_player_two, self.FONT, (300, 15))
pygame.display.update()
self.FPSCLOCK.tick(self.FPS)
Questao_18().init_game()
|
# -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 12 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Python *
* Professor : Thaís do Nascimento Viana *
* Nome do arquivo : questao_12.py *
***************************************************************************/
"""
import pygame
class Questao_12():
""" This function draws a circle capable of moving yourself on the
vertical and horizontal axis. """
def __init__(self):
""" Constructor. """
pygame.init()
self.DISPLAY_NAME = pygame.display.set_caption('Questão 12')
self.SCREEN_WIDTH = 400
self.SCREEN_HEIGHT = 400
self.SCREEN = pygame.display.set_mode(
(self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
self.FPS = 60
self.FPSCLOCK = pygame.time.Clock()
self.YELLOW = (255, 255, 0)
self.BLACK = (0, 0, 0)
self.x_pos = self.SCREEN_WIDTH // 2
self.y_pos = self.SCREEN_HEIGHT // 2
self.finish = False
def move_keys(self):
""" This functions moves a rectangle in place"""
key = pygame.key.get_pressed()
if self.x_pos > 350:
self.x_pos = 50
if key[pygame.K_RIGHT]:
self.x_pos += 5
elif self.x_pos < 50:
self.x_pos = 350
if key[pygame.K_LEFT]:
self.x_pos -= 5
elif self.y_pos > 350:
self.y_pos = 50
if key[pygame.K_UP]:
self.x_pos += 5
elif self.y_pos < 50:
self.y_pos = 350
if key[pygame.K_DOWN]:
self.x_pos -= 5
else:
if key[pygame.K_LEFT]:
self.x_pos -= 5
if key[pygame.K_RIGHT]:
self.x_pos += 5
if key[pygame.K_UP]:
self.y_pos -= 5
if key[pygame.K_DOWN]:
self.y_pos += 5
def draw_circle(self, surface, color, position, radius):
""" This functions draws a circle """
pygame.draw.circle(surface, color, position, radius)
def init_game(self):
""" This function starts the game. """
while not self.finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.finish = True
self.SCREEN.fill(self.BLACK)
self.draw_circle(self.SCREEN, self.YELLOW,
(self.x_pos, self.y_pos), 50)
self.move_keys()
pygame.display.update()
self.FPSCLOCK.tick(self.FPS)
pygame.display.quit()
Questao_12().init_game()
|
import random
from random import randint
def is_monotonic(nums):
result = False
increases = 0
decreases = 0
len_nums = len(nums)
for i in range(len_nums - 1):
if nums[i] > nums[i + 1]:
decreases += 1
elif nums[i] < nums[i + 1]:
increases += 1
if decreases == 0:
result = True
elif increases == 0:
result = True
return result
n = int(input())
nums = [randint(1, n) for i in range(n)]
#print(nums)
print(is_monotonic(nums)) |
#Loops - repetitive tasks
for number in range(10): #iterate through sequence of numbers
print(number)
for num in range(5):
print(num)
for num in range(1,11,2):
print(num)
# Use for loop to print numbers 0 to 100 (inclusive)
for num in range(101):
print(num)
#Use for loop to print numbers 0 to 100 (skip 5)
for num in range(0, 100, 5):
print(num)
letters = ["a", "b", "c", "d"]
result = ""
for letter in letters:
result = result + letter
print(result) #print every step
print(result) #print final result
chilli_wishlist = ["igloo", "chicken", "donut toy", "cardboard box"]
for item in range(len(chilli_wishlist)): # range(4)
print(chilli_wishlist[item])
for item in chilli_wishlist:
print(item)
# Adapt the foor loop to print a message
# for each item in the list eg "Chilli wants: "
for item in chilli_wishlist:
print(f"Chilli wants: {item}")
# print("Chilli wants " + chilli_wishlist[item]) # TypeError
# Use a for loop to print each item in a list
# from a previous exercise or example
for letter in letters:
print(letter)
numbers = [[1, 2, 3],[4],[5, 6]]
print(numbers[2] [-1])
for number in numbers:
for digit in number:
print(digit)
chilli_wishlist = [
["igloo"],
["donut toy", "tennis ball", "crocodile toy"],
["chicken", "peanut butter"],
["cardboard box", "kong", "dig mat"]
]
for category in chilli_wishlist:
for item in category:
print(item)
# While loops
guess = ""
while guess != "a":
guess = input("Guess a letter: ")
counter = 0
while counter <= 10:
print(counter)
counter = counter + 1
count = 0
while count < 5:
print("Hello")
#count = count + 1
count += 1 |
# Q1) Write a function that takes a temperature in fahrenheitand returns the temperature in celsius.
# Fahrenheit to Celsius formula: (°F – 32) x 5/9 = °C
# def convert_temperature(fahrenheit):
# '''Convert fahrenheit to celsius'''
# return (fahrenheit - 32) * 5.0/9.0
# print(convert_temperature(350))
# Q2) Write a function that accepts one parameter (an integer) and returns True when that parameter is
# odd and False when that parameter is even.
# ???????????????
def true_or_false(number):
number = int(number)
# Q3) Write a function that returns the mean of a list of numbers.
# list = [4, 3, 2, 6]
# def average(list):
# return sum(list) / len(list)
# print(average(list))
# Q4) Write a function that takes two parameters; the unit price of an item, and how many units were purchased.
# Return the total cost as a string. |
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrap(*args, **kw):
ts = time()
result = f(*args, **kw)
te = time()
print("func %r args:[%r, %r] took: %2.4f sec" % \
(f.__name__, args, kw, te-ts))
return result
return wrap
def memoize(f):
cache = {}
def helper(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return helper
@timing
def fib(x):
if x in (0, 1):
return x
return fib(x-1) + fib(x-2)
# notice the difference bwtween msfib and mfib:
# they look alike, but msfib is much slower than mfib
# because msfib call fib rather than itself, so it still
# does a lot of repetitive computation(fib doesn't use memoize)
msfib = memoize(fib)
@timing
@memoize
def mfib(x):
if x in (0, 1):
return x
return mfib(x-1) + mfib(x-2)
# now fib is same as mfib, we can compare it with msfib
fib = memoize(fib)
|
def combine_skipper(f, lst):
"""
>>> lst = [4, 7, 3, 2, 1, 8, 5, 6]
>>> f = lambda l: sum(l)
>>> lst = combine_skipper(f, lst)
>>> lst
[11, 1, 3, 2, 9, 5, 5, 6]
>>> lst2 = [4, 3, 2, 1]
>>> lst2 = combine_skipper(f, lst2)
>>> lst2
[7, 1, 2, 1]
"""
n = 0
while n < len(lst) // 4:
lst[n*4], lst[n*4+1] = f(lst[n*4 : n*4+2]), n*4+1
n += 1
return lst
# Tree ADT
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
"""Return the label value of a tree."""
return tree[0]
def branches(tree):
"""Return the list of branches of the given tree."""
return tree[1:]
def is_tree(tree):
"""Returns True if the given tree is a tree, and False otherwise."""
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
"""Returns True if the given tree's list of branches is empty, and False
otherwise.
"""
return not branches(tree)
def print_tree(t, indent=0):
"""Print a representation of this tree in which each node is
indented by two spaces times its depth from the root.
>>> print_tree(tree(1))
1
>>> print_tree(tree(1, [tree(2)]))
1
2
>>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
>>> print_tree(numbers)
1
2
3
4
5
6
7
"""
print(' ' * indent + str(label(t)))
for b in branches(t):
print_tree(b, indent + 1)
def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(label(t), [copy_tree(b) for b in branches(t)])
def largest_product_path(tree):
"""
>>> largest_product_path(None)
0
>>> largest_product_path(tree(3))
3
>>> t = tree(3, [tree(7, [tree(2)]), tree(8, [tree(1)]), tree(4)])
>>> largest_product_path(t)
42
"""
if not is_tree(tree):
return 0
elif is_leaf(tree):
return label(tree)
else:
paths = [largest_product_path(b) for b in branches(tree)]
return label(tree) * max(paths)
def level_order(tree):
"""
>>> level_order(tree(3))
[3]
>>> level_order(None)
[]
>>> t = tree(3, [tree(7), tree(8), tree(4)])
>>> level_order(t)
[3, 7, 8, 4]
>>> t = tree(3, [tree(7, [tree(2, [tree(8), tree(1)]), tree(5)])])
>>> level_order(t)
[3, 7, 2, 5, 8, 1]
>>> t = tree(5, [tree(8, [tree(7, [tree(6)])])])
>>> level_order(t)
[5, 8, 7, 6]
"""
if not is_tree(tree):
return []
current_level, next_level = [label(tree)], [tree]
while next_level:
find_next = []
for t in next_level:
find_next.extend([b for b in branches(t)])
next_level = find_next
current_level.extend([label(t) for t in next_level])
return current_level
|
# _*_ coding:utf8-
from math import *
from random import *
'''
#1.数学方面: 五角数
def getpen(n):
n=n*(3*n-1)/2
print("%.0f"%(n),end=" ")
s=0
for i in range(1,101):
getpen(i)
s=s+1
if(s%10==0):
print('')
'''
'''
#2.求一个整数各个数字的和
def sumdigits(n):
s=0
while(n%10!=0):
a=n%10
b=n//10
s=s+a
n=b
print(s)
a=eval(input("Enter a int:"))
sumdigits(a)
'''
'''
#3.对三个数排序
def displaysort(num1,num2,num3):
b=[num1,num2,num3]
b.sort()
print(b)
a,b,c=eval(input("Enter three numbers:"))
displaysort(a,b,c)
'''
from math import *
'''
#4.计算未来投资值
invested=eval(input("The amount inversted:"))
monthly=eval(input("Annual interest rate:"))
print("Annual\tFuture Value")
def funtureinver(invested,monthly,years):
return invested*pow((1+monthly/100/12),years*12)
for i in range(1,31):
c=funtureinver(invested,monthly,i)
print("%d\t%.2f"%(i,c),end=" ")
print()
'''
'''
#5.显示字符
def printchars(ch1,ch2,number):
m=0
a=ord(ch1)
b=ord(ch2)+1
for i in range(a,b):
print(chr(i),end=" ")
m=m+1
if(m%number==0):
print(" ")
a,b=input("Enter start to end ascii:").split(',')
c=eval(input("Enter number:"))
printchars('1','Z',10)
'''
'''
#6.一年的天数
def numberofdays(year):
if((year%4==0)&(year%100!=0))|(year%400==0):
print("%d:366"%(i))
else:
print("%d:365"%(i))
for i in range(2010,2021):
numberofdays(i)
'''
'''
#7.几何问题:显示角
def distance(x1,y1,x2,y2):
print(((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))**0.5)
x1,y1=eval(input("Enter x1 and x2 for point1: "))
x2,y2=eval(input("Enter x1 and x2 for point2: "))
distance(x1,y1,x2,y2)
'''
#8.梅森素数
print("p\t2^p-1:")
def s(a):
c=0
for j in range(2,int(sqrt(a)+1)):
if a%j==0:
c=0
else:
c=1
return c
print("2\t3")
for i in range(1,32):
c=pow(2,i)-1
if(s(c)):
print("%d\t%d"%(i,c))
'''
#9.当前时间和日期
from time import *
print(ctime(time()))
'''
'''
#10.游戏:掷骰子
a,b=eval(input("Enter one and two:"))
if(a+b==2)|(a+b==3)|(a+b==12):
print("You rolled %d+%d=%d"%(a,b,a+b))
print("You lose")
elif(a+b==7)|(a+b==11):
print("You rolled %d+%d=%d"%(a,b,a+b))
print("You win")
else:
while(1):
print("You rolled %d+%d=%d"%(a,b,a+b))
print("print is %d"%(a+b))
s=a+b
a,b=eval(input("Enter one and two:"))
if(a+b==7):
print("You rolled %d+%d=%d"%(a,b,a+b))
print("You lose")
break
elif(a+b==s):
print("You rolled %d+%d=%d"%(a,b,s))
print("You win")
break
else:
continue
''' |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
length = len(nums)
k = k % length
if k < 0:
k=k+length
self.reverse_array(nums,0,length-1)
self.reverse_array(nums,0,k-1)
self.reverse_array(nums,k,length-1)
def reverse_array(self,arr, start, end):
while start < end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start+=1
end-=1
'''
Your input
[1,2,3,4,5,6,7]
3
[-1,-100,3,99]
2
Output
[5,6,7,1,2,3,4]
[3,99,-1,-100]
Expected
[5,6,7,1,2,3,4]
[3,99,-1,-100]
Runtime: 220 ms, faster than 45.03% of Python3 online submissions for Rotate Array.
Memory Usage: 25.4 MB, less than 67.08% of Python3 online submissions for Rotate Array
'''
|
def moves_begin_zero(array):
if len(array) < 1:
return
length = len(array)
#we will assing the pointers of read and write index
r_ind = length-1
w_ind = length-1
#creating a loop where if read index is not zero, the read index value is stored in write index and write index is decremented towards the start
while(r_ind >=0):
if array[r_ind] !=0:
array[w_ind] = array[r_ind]
w_ind-=1
r_ind-=1
#when write idnex is >0 after read_index reaches -1, all indices left in the begninning are assigned zero
while(w_ind >=0):
array[w_ind]=0
w_ind-=1
def moves_end_zero(array):
if len(array)<1:
return
length = len(array)
r_ind = 0
w_ind=0
while(r_ind<=length-1):
if array[r_ind] !=0:
array[w_ind]=array[r_ind]
w_ind+=1
r_ind+=1
while(w_ind<=length-1):
array[w_ind]=0
w_ind+=1
array = [1,2,0,5,0,4,0,6]
array1 = array.copy()
print('Original array: ',array)
moves_end_zero(array)
print('Moving all zeros to the end: ',array)
moves_begin_zero(array1)
print('Moving all zeros to the beginning: ',array1)
'''
Runtime Complexity: O(n) and Memory Complexity is constant O(1)
In LeetCode, the problem is to move all zeros to the end of the array and we used the above function to do it
Runtime: 52 ms, faster than 48.98% of Python3 online submissions for Move Zeroes.
Memory Usage: 15.3 MB, less than 59.84% of Python3 online submissions for Move Zeroes.
Faster code for using for loop to read and write
'''
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
r_ind = 0
w_ind = 0
for i in nums:
if i == 0:
r_ind += 1
else:
nums[w_ind] = i
w_ind += 1
while r_ind:
nums[w_ind] = 0
w_ind += 1
r_ind -= 1
'''
Runtime: 48 ms, faster than 74.51% of Python3 online submissions for Move Zeroes.
Memory Usage: 15.4 MB, less than 17.16% of Python3 online submissions for Move Zeroes.
'''
|
def solution(dataset, a, b, c):
result=[] #initialize empty matrix to store transformed values
for i in range(len(dataset)): #loop to solve equation for each value of x
sol=a*(dataset[i]**2)+b*dataset[i]+c
result.append(sol) #store f(x) values in result array
b = sorted(result) #sort array by default ascending order
return b, min(b) #return sorted array and minimum value in sorted array
'''
dataset = [-4,-3,-2,2,3,4]
result_final = solution(dataset,-1,3,5)
print(result_final)
'''
|
l = ["big", "name", "happy", "hey", "give", "root", "doggy", "man", "sixer"]
def capitalize_nested(l):
n= []
for str in l:
n.append(str.upper())
return n
print(capitalize_nested(l))
|
import unittest
def is_leap_year(year):
# うるう年の判定をしてみましょう
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
class TestLeapYear(unittest.TestCase):
def test_is_leap_year_4(self):
"""4の倍数の年のテスト."""
self.assertTrue(is_leap_year(2020))
assrtEque = (True, is_leap_year(4))
def test_is_leap_year_100(self):
"""100の倍数の年のテスト."""
self.assertFalse(is_leap_year(2100))
def test_is_leap_year_400(self):
"""400の倍数の年のテスト."""
self.assertTrue(is_leap_year(2000))
def test_is_leap_year_2018(self):
"""その他のテスト."""
self.assertFalse(is_leap_year(2018))
if __name__ == '__main__':
unittest.main()
|
def Reverse():
while True:
A = input("Enter Your Text You Want To Reverse >>>")[::-1]
print(A)
Reverse()
|
class Ninja():
def __init__(self, first_name, last_name, pet, pet_food, treats):
self.first_name = first_name
self.last_name = last_name
self.pet = pet
self.pet_food = pet_food
self.treats = treats
def walk(self, Pet):
Pet.play()
return self
def feed(self, Pet):
Pet.eat()
return self
def bathe(self, Pet):
print("It's bath time!!")
Pet.noise()
return self
class Pet():
def __init__(self, name, type, tricks, health, energy):
self.name = name
self.type = type
self.tricks = tricks
self.health = health
self.energy = energy
def play(self):
self.health += 5
print(f"{self.name} looks excited to go for a walk, its health is now {self.health}")
return self
def eat(self):
self.energy += 5
self.health += 10
print(f"{self.name} is now fed! Its health is now {self.health} and its energy is {self.energy}")
return self
def noise(self):
print("ANGRY ANIMAL NOISE!")
print(f"{self.name} looks very upset!!")
return self
def sleep(self):
self.energy += 25
print("ZzZzzZzzzZzzzz")
print(f"{self.name}'s energy is now {self.energy}")
return self
John = Ninja("John", "Williams", "Dog", "dog_food", "dog_treats")
Doggo = Pet("Doggo", "dog", "none", 90, 80)
John.feed(Doggo).walk(Doggo).bathe(Doggo) |
class Rectangle:
def __init__(self,width,height):
self.set_width(width)
self.set_height(height)
def __str__ (self):
return "Rectangle(width="+str(self.width)+", height="+str(self.height)+")"
def set_width(self,width):
self.width=width
def set_height(self,height):
self.height=height
def get_area(self):
return (self.width*self.height)
def get_perimeter(self):
return 2 * self.width + 2 * self.height
def get_diagonal(self):
return (self.width ** 2 + self.height ** 2) ** .5
def get_picture(self):
output=""
if self.height>50 or self.width>50:
return "Too big for picture."
else:
for row in range(self.height):
for column in range(self.width):
output=output+"*"
output=output+"\n"
return output
def get_amount_inside(self,Rectangle):
if self.height<Rectangle.height or self.width<Rectangle.width:
return 0
else:
return (self.height//Rectangle.height)*(self.width//Rectangle.width)
class Square(Rectangle):
def __init__(self,side):
super().__init__(side,side)
def __str__(self):
return "Square(side="+str(self.width)+")"
def set_side(self,width):
self.set_width(width)
self.set_height(width)
|
# Models the number of new teams on each show of the BBC gameshow "Pointless"
# There are 4 teams on each episode.
# Teams get two chances to win the gameshow
# If a team wins the show they are replaced by a new team next episode
# If a team loses two episodes they are replaced by a new team next episode
# This program models that process assuming random winners
from random import randint
# Game object to handle progression of teams
class Game(object):
def __init__(self):
self.players = [1,1,1,1]
def episode(self):
self.who_wins()
self.next_state()
# Randomly assigns one team as winner
def who_wins(self):
winning_team = randint(0,3)
self.players[winning_team] = "W"
return self.players
# Moves onto the next show, bringing on new teams if they
# have been on twice or won
def next_state(self):
new_players = []
for team in self.players:
if team == 1:
new_players.append(2)
else:
new_players.append(1)
self.players = new_players
return new_players
def get_players(self):
return self.players
series1 = Game()
number_of_episodes = 10000000
# Run through the episodes and record the number of occurences
# of each possible number of new players
results_summary = []
for i in range(number_of_episodes):
series1.episode()
players = series1.get_players()
new_players = players.count(1)
results_summary.append(new_players)
#count and print number of occurences of each number of new players
for i in range(4):
occurences = results_summary.count(i+1)
percentage = float(occurences)/number_of_episodes
print ("Number " + str(i+1) + "- Occurences: " + str(occurences) + " Percentage: " + str(percentage)) |
"""
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
"""
#My solution, lol not Pythonic at all fml
def find_it(seq):
l = len(seq)
count = 0
for y in seq:
for x in seq:
if y == x:
count += 1
if count % 2 != 0:
return y
break
print(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]))
#correct output = 5
"""
The best solution someone else submitted:
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
"""
|
n = int(input())
words = []
for _ in range(n):
words.append(input())
words = list(set(words))
words.sort(key=lambda x:(len(x),x))
for w in words:
print(w) |
import sys
# 중복되는 것 제거한 풀이 : 틀림 ㅠㅠ
word = sys.stdin.readline().split()
lower_word = list(map(lambda x: x.lower(),word))
lower_word = set(lower_word)
print(len(lower_word))
# 중복되는 것도 모두 세기
word = sys.stdin.readline().split()
print(len(word)) |
def solution(n):
n = sorted(str(n),reverse=True)
answer = ''
for i in n:
answer += i
return int(answer)
# ls = list(str(n))
# ls.sort(reverse = True)
# return int("".join(ls)) |
"""
단, 코스요리 메뉴는 최소 2가지 이상의 단품메뉴로 구성하려고 합니다.
또한, 최소 2명 이상의 손님으로부터 주문된 단품메뉴 조합에 대해서만 코스요리 메뉴 후보에 포함하기로 했습니다.
"""
from itertools import combinations
def solution(orders, course):
# course의 수만큼 combination 있는지 확인.
dictionary = {}
for order in orders:
order = sorted(order)
for cnt in course:
for i in list(combinations(order, cnt)):
dictionary[''.join(i)] = dictionary.get(''.join(i), 0) + 1
dictionary = sorted(dictionary.items(), key= lambda x: (-len(x[0]), -x[1]))
result = []
max_v = -1
len_k = 0
for k, v in dictionary:
if max_v == -1:
len_k = len(k)
max_v = max(max_v, v)
if v >= 2 and max_v == v:
result.append((k,v))
if len_k != len(k):
len_k = len(k)
# print(list(*zip(result)))
return sorted(list(list(zip(*result))[0]))
print(solution(["ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"], [2,3,4]))
# 다른 사람 풀이
import collections
import itertools
def solution(orders, course):
result = []
for course_size in course:
order_combinations = []
for order in orders:
order_combinations += itertools.combinations(sorted(order), course_size)
most_ordered = collections.Counter(order_combinations).most_common()
result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ]
return [ ''.join(v) for v in sorted(result) ]
# 다른 사람 풀이 2
from itertools import combinations
from collections import Counter
def solution(orders, course):
answer = []
for c in course:
temp = []
for order in orders:
combi = combinations(sorted(order), c)
temp += combi
counter = Counter(temp)
if len(counter) != 0 and max(counter.values()) != 1:
answer += [''.join(f) for f in counter if counter[f] == max(counter.values())]
return sorted(answer) |
# stack
def solution(s):
stack = []
for i in s:
if not stack:
stack.append(i)
continue
if stack[-1] == i:
stack.pop()
else: # 어떻게 이 부분을 까먹니! 담에는 좀 더 꼼꼼히 살펴보자
stack.append(i)
return 0 if stack else 1
print(solution('baabaa'))
print(solution('zzz')) |
# 정렬할 변수
x = [3,6,2,8,1,4,9,10]
# 버블정렬 Bubble Sort
def bubble_swap(x, i, j):
x[i], x[j] = x[j], x[i]
def bubbleSort(x):
for size in reversed(range(len(x))):
for i in range(size):
if x[i] > x[i+1]:
bubble_swap(x, i , i+1)
# print(list(reversed(range(len(x)))))
# [7, 6, 5, 4, 3, 2, 1, 0]
# bubbleSort(x)
# 선택정렬 Selection Sort
def slection_swap(x, i, j):
x[i], x[j] = x[j], x[i]
def selectionSort(x):
for size in reversed(range(len(x))):
max_i = 0
for i in range(1, 1+size):
if x[i] > x[max_i]:
max_i = i
slection_swap(x, max_i, size)
# print(x)
# selectionSort(x)
# print(x)
# 삽입정렬 Insertion Sort
# 병합정렬
def mergeSort(x):
if len(x) > 1:
mid = len(x)//2
lx, rx = x[:mid], x[mid:]
mergeSort(lx)
mergeSort(rx)
li, ri, i = 0, 0, 0
while li < len(lx) and ri < len(rx):
if lx[li] < rx[ri]:
x[i] = lx[li]
li += 1
else:
x[i] = rx[ri]
ri += 1
i += 1
x[i:] = lx[li:] if li != len(lx) else rx[ri:]
|
def solution(n):
answer = ''
while n > 0:
a, b = n // 3, n % 3
answer += str(b)
n = a
# 0021
result = 0
for i in range(len(answer)):
result += (3**i)*int(answer[::-1][i])
return result
print(solution(125))
# 다른 사람 풀이
def solution2(n):
tmp = ''
while n:
tmp += str(n % 3)
n = n // 3
# 10진수는 int로 하면 됨!
answer = int(tmp, 3)
return answer |
# Algorithm to move all the negative element to front
"""
EXAMPLE:
INPUT : [1, 2, -3, -5, -3, 1, 4, 6, -5, 3]
OUTPUT : [-5, -3, -3, -5, 2, 1, 4, 6, 1, 3]
"""
"""
------------------------------------IMPORTANT NOTE------------------------------------------------
I also solved this problem using 2 pointer approach see 05_ii_)_Move_All_Negative_Element_To_Front
"""
# I solved this problem using DNF(Dutch Nation Flag) algorithm
# You can read about it here : https://users.monash.edu/~lloyd/tildeAlgDS/Sort/Flag/
def negative_to_front(arr):
"""
Time Complexity : O(n)
Space Complexity : O(1)
"""
low, mid = 0, 0
while mid < len(arr):
if arr[mid] < 0:
arr[mid], arr[low] = arr[low], arr[mid]
mid += 1
low += 1
else:
mid += 1
return arr
print(negative_to_front([1, 23, -4, -5, 3, -4, -2, 1]))
|
from math import sin, cos
theta = 0
theta_max = 3.14 / 2
theta_rmax = 0
d_theta = 0.01
dt = 0.001
g = 9.81
range_max = -1
v = 8.29
while theta < theta_max:
y = 1.5
x = 0
t = 0
while y > 0:
y = y + v*sin(theta)*t - 0.5*g*t*t
x = v*cos(theta)*t
t = t + dt
if(x > range_max):
theta_rmax = theta
theta = theta + d_theta
print("Angle for maximum range: ", theta_rmax) |
# 10までの3と5の倍数の和は、
# 3の倍数: 3 6 9
# 5の倍数: 5 10
# = 33
#
#
# 10000000の場合の和は?
#target = 1000
def multiple(thistarget = 10000000):
summary_three = 0
summary_five = 0
summary_total = 0
for f in range(0,thistarget+1,3): #1000万までの3の倍数を合計する
summary_three += f
print(summary_three)
for ff in range(0,thistarget+1,5): # ” 5の倍数を合計する
summary_five += ff
print(summary_five)
print("3と5の倍数の和は",summary_three + summary_five)
for fff in range(0,thistarget+1,15):
summary_total += fff
summary_t = summary_three + summary_five -summary_total
print(summary_t)
multiple()
# def anothersolusion():
# s_t
# s_f |
#script que calcula la tambla de multiplicar de un número
numero = input('que numero quieres multiplicar?')
# el dato ingresado por el usuario es una cdena "<str>"
# Se debe convertir a numero "<int>" para poder multiplicar
numero=int(numero)
for n in range(10):
r = numero * (n + 1)
print(r)
|
def combination(n, m):
if m == 0 or n == m:
return 1
return combination(n-1, m-1) + combination(n-1, m)
while True:
try:
n = int(input("집합의 모든 원소의 갯수를 입력하세요: "))
m = int(input("고르는 원소의 갯수를 입력하세요: "))
if n <= 0 or m <= 0:
print("원소의 개수가 0보다 작습니다. 다시 입력해주세요.")
continue
elif n < m:
print ("n보다 m이 더 큽니다. 다시 입력해주세요.")
continue
result = combination(n, m)
print("%dC%d = %d" %(n, m, result))
except ValueError:
print("올바른 정수를 입력하세요") |
"""
将ISBN号去重,并使用冒泡排序从小到大排序
输入:
10
9781234567890
9781241242123
9782141241223
9784689622528
9786904328539
9783462839468
9783849534054
9783426989053
9784032698743
9783462839468
输出:
9781234567890
9781241242123
9782141241223
9783426989053
9783462839468
9783849534054
9784032698743
9784689622528
9786904328539
"""
in_num = int(input("请输入书的个数: "))
sort_list = []
for i in range(in_num):
sort_list.append(int(input("请输入书号: ")))
for i in range(len(sort_list) - 1):
for j in range(len(sort_list) - 1 - i):
if sort_list[j] > sort_list[j + 1]:
sort_list[j], sort_list[j + 1] = sort_list[j + 1], sort_list[j]
for k in range(len(sort_list)):
if sort_list[k] != sort_list[k - 1]:
print(sort_list[k])
|
"""
将ISBN号去重,并使用快速排序从小到大排序
输入:
10
9781234567890
9781241242123
9782141241223
9784689622528
9786904328539
9783462839468
9783849534054
9783426989053
9784032698743
9783462839468
输出:
9781234567890
9781241242123
9782141241223
9783426989053
9783462839468
9783849534054
9784032698743
9784689622528
9786904328539
"""
def quick_sort(left, right):
if left > right:
return
base = left
i = left
j = right
while j != i:
while (sort_list[j] >= sort_list[base]) and (i < j):
j = j - 1
while (sort_list[i] <= sort_list[base]) and (i < j):
i = i + 1
if i < j:
sort_list[i], sort_list[j] = sort_list[j], sort_list[i]
sort_list[base], sort_list[j] = sort_list[j], sort_list[base]
quick_sort(left, j - 1)
quick_sort(j + 1, right)
in_num = int(input("请输入书的个数: "))
sort_list = []
for i in range(in_num):
sort_list.append(int(input("请输入书号: ")))
quick_sort(0, len(sort_list) - 1)
for k in range(len(sort_list)):
if sort_list[k] != sort_list[k - 1]:
print(sort_list[k])
|
user_number = int(input("Введите число:"))
double_number = user_number * 10 + user_number
triple_number = double_number * 10 + user_number
summ = user_number + double_number + triple_number
print(f" {user_number} + {double_number} + {triple_number} = {summ}")
|
#########################################################################
###### Name: Kenneth Emeka Odoh
###### Purpose: An example of using the Recursive Linear Regression
#########################################################################
from __future__ import division
import pandas as pd
import numpy as np
import sys
import os
sys.path.append(os.path.abspath('../ML'))
from utils import OnlineLinearRegression
if __name__ == "__main__":
X = np.random.rand(100,5)
olr = OnlineLinearRegression()
y = np.random.rand(1,5)
x = np.random.rand(1,15)
print x.shape, y.shape
olr.update(x, y)
print "A"
print olr.getA( )
print olr.getA( ).shape
print "B"
print olr.getB( )
print olr.getB( ).shape
"""
y = np.random.rand(1,5)
x = np.random.rand(1,15)
olr.update(x, y)
print "A"
print olr.getA( )
print "B"
print olr.getB( )
y = np.random.rand(1,5)
x = np.random.rand(1,15)
olr.update(x, y)
print "A"
print olr.getA( )
print "B"
print olr.getB( )
y = np.random.rand(1,5)
x = np.random.rand(1,15)
olr.update(x, y)
print "A"
print olr.getA( )
print "B"
print olr.getB( )
print "mean y"
print olr.getA().shape
print "Noise Matrix"
print olr.getCovarianceNoiseMatrix()
"""
|
# Ваш первый код на Python
# Задание 1
# С этого задания вы начинаете создавать собственного персонального помощника,
# вроде Алисы, Google Assistant, Siri или Alexa. Назовём её Анфиса.
# Для начала научите Анфису здороваться: код уже подготовлен, но Python не станет его выполнять,
# ведь он скрыт за символом комментария, «закомментирован».
# Сделайте так, чтобы Python увидел и выполнил код. Для этого уберите символ комментария и пробел
# в начале строки (это называют «раскомментировать» строку).
print('Привет, я Анфиса!')
# Задание 2
# Анфиса поздоровалась, но для светского разговора этого маловато. Пусть Анфиса немножко расскажет о себе.
# После строки print('Привет, я Анфиса!') добавьте новую строку кода, которая напечатает
# текст 'Я маленькая, но уже программа!'.
# Лайфхак: функцию print() (да и любую функцию вообще)
# можно вызывать в коде сколько угодно раз.
print('Привет, я Анфиса!')
print('Я маленькая, но уже программа!')
############
# Переменные и типы
# Задача 1
# Чтобы Анфиса стала более дружелюбной, научите её рассказывать о себе. Для начала напечатайте на экране фразу:
# 'Привет, я Анфиса, твой персональный помощник!'
# Вместо многоточий подставьте в код переменные name и job. Будьте внимательны, не пропустите запятую,
# восклицательный знак или пробел: при проверке задания это будет учитываться.
name = 'Анфиса' # Имя
job = 'персональный помощник' # Профессия
print('Привет, я ' + name + ', твой ' + job + '!')
# Задача 2
# Если бы Анфиса поселилась в фитнес-трекере, она могла бы подсчитывать количество шагов пользователя и
# сообщать ему результат.
# Научите Анфису подставлять в сообщение сумму шагов, пройденных за два дня.
# В переменных steps_today и steps_yesterday записано, сколько шагов прошёл незнакомый вам Геннадий вчера и сегодня.
# Вычислите в коде сумму шагов за два дня и сохраните результат в переменную steps_sum. А программа напечатает
# получившийся результат.
steps_yesterday = 8452
steps_today = 6783
# Вычислите сумму здесь: вместо многоточия напишите выражение,
# суммирующее количество шагов за два дня
steps_sum = steps_yesterday + steps_today
print('Сколько шагов сделал Геннадий за два дня?')
print(steps_sum)
############
# Преобразование типов
# Задание
# Научим Анфису информировать вас о новых сообщениях, которые вы могли бы получить.
# Выведите на экран строку 'У вас 8 новых сообщений', составленную из строки 'У вас ', значения переменной count
# и из строки ' новых сообщений'.
count = 8
message = 'У вас ' + str(count) + ' новых сообщений' # Допишите ваш код здесь
print(message)
############
# Именование переменных
# Задание: Переименуйте переменные правильно
name = 'Данил'
last_name = 'Марков'
print('Меня зовут ' + name + ' ' + last_name + '.')
############
# Вывод на экран
# Задание: начнём учить Анфису разговаривать о погоде.
temperature = -25
weather = 'солнечно'
# напишите ваш код ниже
print('Сегодня', weather)
print('Температура воздуха', temperature, 'градусов')
############
# Дробные числа
# Задача 1
# Скорость света равна 1 079 252 848,8 километров в час. Научите Анфису переводить скорость в другую
# величину — в километры в секунду.
# На основе переменной speed_kmh (скорость света в км/ч) вычислите значение переменной speed_kms
# (скорость света в км/с).
# Значение переменной speed_kms приведите к целому типу: отбросьте дробную часть.
speed_kmh = 1079252848.8
# переменную speed_kms сделайте типа int
speed_kms = int(speed_kmh / 3600)
print('Скорость света равна', speed_kms, 'км/с')
# Задача 2
# Длина Питона из известного советского мультфильма равна 38 попугаев и одно попугайское крылышко.
# Давайте считать, что крылышко равно 0.2 попугая.
# В проход пассажирского железнодорожного вагона можно уложить ровно шесть с половиной Питонов.
# Помогите Анфисе сосчитать, сколько попугаев поместится в этот проход.
# Попугаи бывают только целые, это важно. Поэтому переменная result должна быть типа int.
snake = '38.2'
length = 6.5
result = int(float(snake) * length)
print('В вагоне можно поставить в ряд', result, 'попугаев')
############
# Списки
# Задача 1
# Сообщите Анфисе, кто ваши друзья. Для этого создайте список friends с элементами в таком порядке:
# 'Сергей', 'Соня', 'Дима', 'Алина', 'Егор'.
# После того, как создадите список friends, напечатайте его содержимое.
print('Привет, я Анфиса!')
# допишите код ниже
friends = ['Сергей', 'Соня', 'Дима', 'Алина', 'Егор']
print(friends)
# Задача 2
# Пора Анфисе стать вежливой и научиться здороваться. Анфиса, для начала поздоровайся с Алиной!
# Допишите код так, чтобы ваша программа напечатала фразу Привет, Алина, я Анфиса!
friends = ['Сергей', 'Соня', 'Дима', 'Алина', 'Егор']
# присвойте переменной index такое значение,
# чтобы из списка friends была выбрана Алина
index = 3
print('Привет, ' + friends[index] + ', я Анфиса!')
# Задача 3
# Анфиса должна не только знать ваших друзей, но и рассказывать о каждом из них.
# В переменной index записан номер друга, информация о котором нас интересует. Получите из списка friends значение
# элемента с индексом, сохранённым в переменной index и научите Анфису печатать сообщение:
# {имя друга с номером index} живёт в Красноярске
print("Привет, я Анфиса!")
friends = ['Сергей', 'Соня', 'Дима', 'Алина', 'Егор']
# перед отправкой на проверку можете поменять индекс
# и посмотреть, как ведёт себя код
index = 2
# допишите свой код тут
print(friends[index], 'живёт в Красноярске')
# Задача 4
# Добавим Анфисе немного функциональности. Научим её считать и перечислять друзей.
# Объявите переменную count и сохраните в ней количество друзей. Посчитайте их вызовом функции len().
# Выведите на экран строку У тебя {количество} друзей, где {количество} — значение переменной count.
print("Привет, я Анфиса!")
friends = ['Сергей', 'Соня', 'Дима', 'Алина', 'Егор']
# допишите свой код сюда
count = len(friends)
print('У тебя', count, 'друзей')
|
# Задача 1
# Доработайте программу подсчёта тёплых дней в мае 2017 г. : допишите функцию comfort_count()
# так, чтобы она возвращала подсчитанное количество тёплых дней.
may_2017 = [24, 26, 15, 10, 15, 19, 10, 1, 4, 7, 7, 7, 12, 14, 17, 8, 9, 19, 21, 22, 11, 15, 19, 23, 15, 21, 16, 13, 25,
17, 19]
# Допишите эту функцию
def comfort_count(temperatures):
count = 0
for temp in temperatures:
if 22 <= temp <= 26:
count += 1
# Функция должна вернуть значение переменной count
return count
# Код ниже не изменяйте:
# вызовем функцию comfort_count(), передадим в неё список may_2017,
# результат работы сохраним в переменную nice_days
nice_days = comfort_count(may_2017)
# Напечатаем значение, сохранённое в nice_days
print('Количество тёплых дней в этом месяце:', nice_days)
# Задача 2
# Плотник Афанасий зачем-то решил построить из стекла и палок восемь одинаковых кубов; рёбра кубов будут из палок,
# а грани — из стекла. Ребро куба, по чертежам Афанасия, должно быть 3 метра.
# Допишите программу так, чтобы она печатала общую длину палок, необходимых для строительства восьми кубов.
# Функцию для подсчёта периметра одного куба Афанасий написал: эта функция принимает на вход длину ребра куба,
# а возвращает периметр куба — сумму длин всех его рёбер.
# Вызовите функцию calc_cube_perimeter() с аргументом 3 и присвойте возвращаемое функцией значение переменной
# one_cube_perimeter. Теперь в этой переменной будет храниться периметр одного куба.
# Вычислите суммарный периметр для восьми кубов и присвойте получившееся значение переменной full_length.
# Функция для вычисления периметра куба.
def calc_cube_perimeter(side):
return side * 12
# Присвойте переменной one_cube_perimeter значение,
# которое вернёт функция calc_cube_perimeter() с аргументом 3:
# 3 метра - это длина ребра куба.
one_cube_perimeter = calc_cube_perimeter(3)
# Вычислите общую длину палок, необходимых
# для строительства 8 кубов,
# и сохраните это значение в переменную full_length
full_length = one_cube_perimeter * 8
# А теперь напечатаем результат (в этой строке ничего изменять не нужно)
print('Необходимый метраж палок для 8 кубов:', full_length)
# Задача 3
# Вычислим площадь стекла, необходимого для постройки восьми кубов. Кубы все одинаковые, длина ребра у кубов —
# три метра. Афанасий начал писать функцию, вычисляющую площадь стекла для одного куба, но потом отвлёкся
# и не дописал часть расчётов и инструкцию return.
# Допишите программу: вычислите общую площадь стекла, необходимого для постройки восьми кубов.
# Функция для вычисления площади куба.
def calc_cube_area(side):
# Формулу для вычисления площади одной грани куба Афанасий написал:
one_face = side * side
# Вычислите полную площадь куба: у него шесть одинаковых граней.
cube_area = one_face * 6
# Удалите многоточие и допишите функцию так,
# чтобы она возвращала полную площадь куба
return cube_area
# Присвойте переменной one_cube_area значение,
# которое вернёт функция calc_cube_area() с аргументом 3:
# 3 метра - это длина ребра куба.
one_cube_area = calc_cube_area(3)
# Вычислите общую площадь стекла, необходимого
# для строительства 8 кубов,
# и сохраните это значение в переменную full_area
full_area = one_cube_area * 8
print('Необходимая площадь стекла для 8 кубов, кв.м:', full_area)
|
print("Muhammad Osama 18b-003-cs CS-(A)")
print("Lab-08 28/12/2018")
print("Programming Exercise: Q-3")
first = 'Muhammad'
last = 'Osama'
street = 'Main Street'
number = 123
city = 'Karachi'
state = 'Sindh'
zipcode = '78487'
print('{0} {1}\n{3} {2}\n{4} {5} {6}'.format(first,last,number,street,city,state,zipcode))
|
def scanner():
try:
file = open('inputfile.txt', 'r')
nextCharacter = file.read()
file.close()
return nextCharacter
except:
print("Error opening file")
scanner() |
import sys
import string
dict_words_counts = {}
file_to_count = open(sys.argv[1])
for line in file_to_count:
line_list = line.split()
for word in line_list:
word = string.strip(word, ",.?/;:\'\"[]{}-()&%$#!`")
word = word.lower()
dict_words_counts[word] = dict_words_counts.get(word, 0) + 1
unsorted_list = dict_words_counts.items()
for i in range(len(unsorted_list)):
unsorted_list[i] = unsorted_list[i][::-1]
sorted_list = sorted(unsorted_list)
for i in range(len(sorted_list)):
print sorted_list[i][1], sorted_list[i][0]
#quicksort |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
start = head
end = head
while end.next != None:
if end.next != None and end.next.next != None:
end = end.next.next
start = start.next
else:
end = end.next
rhead = start.next
start.next = None
start = head
flag = False
while start != None:
if flag == False:
flag = True
if rhead != None:
temp = rhead
prev = None
while temp.next != None:
prev = temp
temp = temp.next
temp.next = start.next
start.next = temp
if prev != None:
prev.next = None
else:
rhead = None
else:
flag = False
start = start.next
if __name__ == "__main__":
s = Solution()
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
# e = ListNode(5)
a.next = b
b.next = c
c.next = d
# d.next = e
r = s.reorderList(a)
while a != None:
print(a.val)
a = a.next |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def depth(self, root, d):
if root is None:
return d
if root.left and root.right:
return min(self.depth(root.left, d + 1), self.depth(root.right, d + 1))
elif root.left:
return self.depth(root.left, d + 1)
elif root.right:
return self.depth(root.right, d + 1)
else:
return d + 1
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.depth(root, 0)
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def count(self, l):
counta = 0
while l != None:
counta +=1
l = l.next
return counta
def add(self, l1, l2):
if l1.next is None and l2.next is None:
l1.val += l2.val
if l1.val > 9:
l1.val -= 10
return 1
return 0
extra = self.add(l1.next, l2.next)
l1.val += l2.val
if extra == 1:
l1.val += 1
if l1.val > 9:
l1.val -= 10
return 1
return 0
def addextra(self, temp, diff):
if diff == 1:
temp.val += 1
if temp.val>9:
temp.val -= 10
return 1
return 0
extra = self.addextra(temp.next, diff-1)
if extra == 1:
temp.val += 1
if temp.val > 9:
temp.val -= 10
return 1
return 0
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
count1 = self.count(l1)
count2 = self.count(l2)
temp = None
diff = abs(count1 - count2)
if count1 >= count2:
temp = l1
while count1-count2 != 0:
l1 = l1.next
count1 -= 1
elif count1 < count2:
temp = l2
while count2-count1 != 0:
l2 = l2.next
count2 -= 1
extra = self.add(l1, l2)
if diff == 0:
if extra == 1:
tempe = ListNode(1)
tempe.next = temp
temp = tempe
return temp
else:
return temp
else:
if extra == 1:
extra = self.addextra(temp, diff)
if extra == 1:
tempe = ListNode(1)
tempe.next = temp
temp = tempe
diff +=1
tempe = temp
while diff != 1:
tempe = tempe.next
diff -= 1
tempe.next = l1
return temp
if __name__ == "__main__":
s = Solution()
l = ListNode(9)
m = ListNode(9)
# n = ListNode(9)
# o = ListNode(3)
p = ListNode(2)
# q = ListNode(6)
# r = ListNode(4)
l.next = m
# m.next = n
# n.next = o
# p.next = q
# q.next = r
list1 = s.addTwoNumbers(p, l)
while list1 != None:
print(list1.val)
list1 = list1.next
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newData):
self.data=newData
def setNext(self, item):
self.next = item
class Unordered:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current is not None:
count += 1
current = current.getNext()
return count
def search(self, item):
current = self.head
flag = False
while current is not None and not flag:
if current.getData() == item:
flag = True
else:
current = current.getNext()
return flag
def remove(self, item):
current = self.head
previous = None
flag = False
while not flag:
if current.getData() == item:
flag = True
else:
previous = current
current = current.getNext()
if previous is None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def index(self, item):
try:
current = self.head
flag = False
count = 0
while not flag:
if current.getData() == item:
flag = True
else:
count += 1
current = current.getNext()
return count
except AttributeError:
return "Number not in list."
def append(self, item):
current = self.head
flag = False
while not flag:
if current.getNext() is None:
current.setNext(item)
flag = True
else:
current = current.getNext()
obj = Unordered()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(4)
obj.add(5)
print(obj.size())
print(obj.search(3))
print(obj.head.getNext().getNext().getData())
obj.remove(3)
print(obj.search(3))
print(obj.index(2))
obj.append(6)
print(obj.index(6)) |
#condicion=True
#while condicion:
# print("ejecutando cicclo while")
#else:
# print ("Fin ciclo while")
i=0
while i<3:
print(i)
i+=1
else:
print("Fin ciclo while") |
condicion = False
if condicion == True:
print("la condicion es verdadera")
elif condicion == False:
print ("la condicion es falsa")
else:
print("condicion no reconocida ")
numero=int(input("Proporciones un numero entre 1 y 3"))
if numero == 1:
numeroTexto= "numero uno"
elif numero == 2:
numeroTexto= "numero dos"
elif numero == 3:
numeroTexto="numero tres"
else:
numeroTexto="valor fuera de rango"
print("numero proporcionado:",numeroTexto)
|
# import statements
from bs4 import BeautifulSoup, Comment
import requests
import lxml
import re
from googlesearch import search
# global vars
titles = []
url_names = ['https://www.mckinsey.com/featured-insights/artificial-intelligence/notes-from-the-ai-frontier-modeling-the-impact-of-ai-on-the-world-economy']
url_soups = []
valuable_texts = []
def find_web_pages(query):
"""method gets the top urls returned by google when making a query"""
for url in search(query, tld='com', tbs='qdr:m', lang='en', num=10, start=0, stop=10):
# add the url to the url list.
url_names.append(url)
def get_url_names():
"""utility method which gives the user the link to each url acquired"""
return url_names
def create_soups():
"""method creates Beautiful Soup objects which are used to process the html version of the webpages."""
# iterate through the url list.
for url in url_names:
# requesting urls can result in exceptions, use a tru except block to avoid program crashes
try:
# get the request object from the webpage.
req = requests.get(url)
# get the html format of the page.
html_version_of_page = req.text
# create the soup using a parser and add it to the soup list.
url_soups.append(BeautifulSoup(html_version_of_page, 'lxml'))
except requests.exceptions.RequestException as e:
# not necessary to handle the error.
print(":(")
def tag_valuable(tag):
"""method returns true if the element of the html page is valuable, false otherwise."""
# we don't want any of the following tags in the processed html.
if tag.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]', 'footer']:
return False
elif isinstance(tag, Comment):
return False
return True
def clean_soups():
"""method cleans the Beautiful Soup objects (removes unnecessary tags etc)"""
for soup in url_soups:
title = soup.find('title')
titles.append(title.text)
# get the entire object
all_texts = soup.findAll(text=True)
# filter out the unwanted tags etc
valuable_text = filter(tag_valuable, all_texts)
# add the 'valuable text to the list'
valuable_texts.append(u" ".join(string.strip() for string in valuable_text))
def get_pure_texts():
"""utility method used to find the actual content (as best possible) and print out the contents obtained"""
counter = 0
completed_texts = []
for text in valuable_texts:
# the "cleaned" text still has many extra spaces, new lines etc.
# the extra spaces are often found between actual content and menu content etc.
title_index = find_title_index(text, counter)
if title_index != -1:
text = text[title_index:]
text_chunks = re.split(r'\s{2,}', text)
completed_texts.append(titles[counter]+'\n')
# process each chunk.
for chunk in text_chunks:
# discard small chunks (may have to adjust based on the formation of the web page)
if 4000 > len(chunk) > 150 and u'.' in chunk:
# Some chunks have unnecessary content after the last sentence of the valuable content.
last_full_stop = chunk.rfind('.')
completed_texts[counter] += (chunk[0:last_full_stop+1]+'\n')
counter = counter+1
return completed_texts
def find_title_index(text, counter):
my_title = titles[counter].strip()
title_elements = re.split('[-,|]', my_title)
try:
index = text.index(title_elements[0])
return index
except ValueError as e:
return -1
def print_completed_texts():
for final_text in completed_texts:
print(final_text+"\n")
|
"""Turing machine that accepts set of all strings of balanced parentheses consisting of (, {, } and )"""
from machines import TuringMachine
def main():
machine = TuringMachine(states={"q0", "q1", "q2", "q3", "q4"},
symbols={"(", ")", "{", "}", "B", "X"},
blank_symbol="B",
input_symbols={"(", ")", "{", "}", "B"},
initial_state="q0",
accepting_states={"q4"},
transitions={
("q0", ")"): ("q1", "X", -1),
("q0", "}"): ("q2", "X", -1),
("q0", "B"): ("q3", "B", -1),
("q0", "X"): ("q0", "X", 1),
("q0", "("): ("q0", "(", 1),
("q0", "{"): ("q0", "{", 1),
("q1", "X"): ("q1", "X", -1),
("q2", "X"): ("q2", "X", -1),
("q1", "("): ("q0", "X", 1),
("q2", "{"): ("q0", "X", 1),
("q3", "X"): ("q3", "X", -1),
("q3", "B"): ("q4", "B", 1),
})
machine.initialize(get_input())
if machine.simulate():
print("Balanced")
else:
print("Not balanced")
def get_input():
acceptable_inputs = {"(", ")", "{", "}"}
print("Enter a string consisting of characters", acceptable_inputs, " only: ", end="")
expr = input()
for symbol in expr:
if symbol not in acceptable_inputs:
print("Invalid input: ", symbol)
exit(1)
return dict(enumerate(expr))
if __name__ == "__main__":
main()
|
# You have deposited a specific amount of dollars into your bank account.
# Each year your balance increases at the same growth rate.
# Find out how long it would take for your balance
# to pass a specific threshold with the assumption
# that you don't make any additional deposits.
#
# Example
#
# For deposit = 100, rate = 20 and threshold = 170, the output should be
# depositProfit(deposit, rate, threshold) = 3.
#
# Each year the amount of money on your account increases by 20%. It means that throughout the years your balance would be:
#
# year 0: 100;
# year 1: 120;
# year 2: 144;
# year 3: 172,8.
def depositProfit(deposit, rate, threshold):
year = 0
while deposit < threshold:
year += 1
deposit += deposit*rate/100
return year |
# Consider integer numbers from 0 to n - 1
# written down along the circle in such a way that the distance
# between any two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too).
#
# Given n and firstNumber, find the number which is written in the radially
# opposite position to firstNumber.
#
# Example
#
# For n = 10 and firstNumber = 2, the output should be
# circleOfNumbers(n, firstNumber) = 7.
def circleOfNumbers(n, firstNumber):
return firstNumber + (n/2) if firstNumber < (n/2) else firstNumber - (n/2)
|
# You are given an array of integers.
# On each move you are allowed to increase exactly one of its element by one.
# Find the minimal number of moves required to obtain a strictly
# increasing sequence from the input.
#
# Example
#
# For inputArray = [1, 1, 1], the output should be
# arrayChange(inputArray) = 3.
def arrayChange(inputArray):
increase = 0
for i in range(1, len(inputArray)):
if inputArray[i-1] >= inputArray[i]:
increase += (inputArray[i-1] - inputArray[i]) + 1
inputArray[i] += (inputArray[i-1] - inputArray[i]) + 1
return increase
|
# ask user to select menu
select_menu = eval(input("1. Binary to Decimal\n2. Decimal to Binary\n3. Octal to Decimal\n4. Decimal to Octal\n\
5. Octal to Binary\n6. Binary to Octal\n7. Decimal to Hexadecimal\n8. Hexadecimal to Decimal\n\
9. Hexadecimal to Binary\n10. Binary to Hexadecimal\nPlease select a menu: "))
# binary to decimal
if select_menu == 1:
print("1. Binary to Decimal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", result_int + result_fra)
# for negative
else:
# integer loop
for int_num in binary_int_str:
if int_num == "-":
continue
result_int += eval(int_num) * pow(2, int_len - 2)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == "-":
continue
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", - (result_int + result_fra))
# decimal to binary
elif select_menu == 2:
print("2. Decimal to Binary")
# Decimal to binary
# ask user to enter decimal number
decimal_number = input("Enter a decimal number: ")
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
# for positive
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 2)
decimal_int = decimal_int // 2
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 2
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in binary is", eval(result_int[::-1]) + eval(result_fra))
# if 0 < x < 1
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 2
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in binary is", result_fra)
# octal to decimal
elif select_menu == 3:
print("3. Octal to Decimal")
# Octal to decimal
# ask user to input
octal_number = input("Enter a octal number: ")
octal_number_num = eval(octal_number)
len_octal = len(octal_number)
# integer part
octal_int = int(octal_number_num)
int_len = len(str(octal_int))
octal_int_str = str(octal_int)
# fractional part
octal_fra = round(octal_number_num - octal_int, len_octal - int_len - 1)
fra_len = len(str(octal_fra))
fra_len_to_sub = fra_len
octal_fra_str = str(octal_fra)
# result
result_fra = 0
result_int = 0
# for positive
if octal_number_num >= 0:
# integer loop
for int_num in octal_int_str:
result_int += eval(int_num) * pow(8, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in octal_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(8, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", result_int + result_fra)
# for negative
else:
# integer loop
for int_num in octal_int_str:
if int_num == "-":
continue
result_int += eval(int_num) * pow(8, int_len - 2)
int_len -= 1
# fractional loop
for fra_num in octal_fra_str:
if fra_num == "-":
continue
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(8, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", - (result_int + result_fra))
# decimal to octal
elif select_menu == 4:
print("4. Decimal to Octal")
# Decimal to octal
# ask user to enter decimal number
decimal_number = input("Enter a decimal number: ")
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
fra_len_to_sub = fra_len
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 8)
decimal_int = decimal_int // 8
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", eval(result_int[::-1]) + eval(result_fra))
# in range (0,1)
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", result_fra)
# octal to binary
elif select_menu == 5:
print("5. Octal to Binary")
# octal to binary
# ask user to input
oct_to_bin = (input("Enter a octal number: "))
oct_to_bin_int = int(eval(oct_to_bin))
length_full_oct = len(oct_to_bin)
oct_to_bin_fra = round(eval(oct_to_bin) - oct_to_bin_int, length_full_oct - len(str(oct_to_bin_int)) - 1)
oct_to_bin_fra_rep = str(oct_to_bin_fra).replace("0.", ".")
result_int = ""
result_fra = ""
for i in str(oct_to_bin_int):
if i == "0":
i = "000"
if i == "1":
i = "001"
if i == "2":
i = "010"
if i == "3":
i = "011"
if i == "4":
i = "100"
if i == "5":
i = "101"
if i == "6":
i = "110"
if i == "7":
i = "111"
result_int += i
# fractional part
for i in str(oct_to_bin_fra_rep):
if i == ".":
continue
if i == "0":
i = "000"
if i == "1":
i = "001"
if i == "2":
i = "010"
if i == "3":
i = "011"
if i == "4":
i = "100"
if i == "5":
i = "101"
if i == "6":
i = "110"
if i == "7":
i = "111"
result_fra += i
# result
print("Number in binary is:", str(int(result_int)) + "." + result_fra)
# binary to octal
elif select_menu == 6:
print("6. Binary to Octal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
# convert from decimal to octal
decimal_number = str(result_fra + result_int)
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
fra_len_to_sub = fra_len
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 8)
decimal_int = decimal_int // 8
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", eval(result_int[::-1]) + eval(result_fra))
# in range (0,1)
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", result_fra)
# decimal to hex
elif select_menu == 7:
print("7. Decimal to Hexadecimal")
# ask user to choose type
select_type = eval(input("Type:\n1 For integer number\n2 For float number in range (0,1)\
\nPlease select a type: "))
# integer number
if select_type == 1:
decimal_num = input("Enter a integer decimal number: ")
decimal_int = eval(decimal_num)
result_int = ""
# integer loop
while decimal_int >= 1:
remainder = decimal_int % 16
if remainder == 10:
remainder = "A"
if remainder == 11:
remainder = "B"
if remainder == 12:
remainder = "C"
if remainder == 13:
remainder = "D"
if remainder == 14:
remainder = "E"
if remainder == 15:
remainder = "F"
result_int += str(remainder)
decimal_int = decimal_int // 16
print("Number in hexadecimal is", result_int[::-1])
# range(0,1)
if select_type == 2:
# fractional loop
decimal_num_str = input("Enter a float decimal number in range (0,1): ")
decimal_num = eval(decimal_num_str)
loop_num = 0
int_int = ""
result = "0."
decimal_fra_num_to_loop = 0
while decimal_fra_num_to_loop < 10:
if str(decimal_num) == ".":
continue
decimal_num = decimal_num * 16
if decimal_num < 10:
int_int = int(decimal_num)
if 10 <= decimal_num < 11:
int_int = "A"
if 11 <= decimal_num < 12:
int_int = "B"
if 12 <= decimal_num < 13:
int_int = "C"
if 13 <= decimal_num < 14:
int_int = "D"
if 14 <= decimal_num < 15:
int_int = "E"
if 15 <= decimal_num < 16:
int_int = "F"
result += str(int_int)
decimal_num = round(decimal_num - int(decimal_num), len(decimal_num_str) - 2)
decimal_fra_num_to_loop += 1
print("Number in hexadecimal is", result)
# hex to decimal
elif select_menu == 8:
print("8. Hexadecimal to Decimal")
# ask user to input
hex_number = input("Enter a hexadecimal number: ")
int_hex_num = ""
for i in hex_number:
int_hex_num += i
if i == ".":
break
int_hex_num_strip = int_hex_num.strip(".")
int_len = len(int_hex_num_strip)
result_int = 0
fra_hex_num = hex_number.replace(int_hex_num, "0.")
fra_hex_len = len(fra_hex_num)
fra_len_to_sub = fra_hex_len
result_fra = 0
# integer loop
for int_num in int_hex_num_strip:
A, B, C, D, E, F = 10, 11, 12, 13, 14, 15
result_int += eval(int_num) * pow(16, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in fra_hex_num:
A, B, C, D, E, F = 10, 11, 12, 13, 14, 15
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(16, fra_len_to_sub - fra_hex_len)
fra_len_to_sub -= 1
# result both
print("Number in decimal is", result_int + result_fra)
# hex to bin
elif select_menu == 9:
print("9. Hexadecimal to Binary")
# hex to binary
# ask user to input
hex_to_bin = (input("Enter a hexadecimal number: "))
result = ""
# loop
for i in str(hex_to_bin):
if i == ".":
i = "."
if i == "0":
i = "0000"
if i == "1":
i = "0001"
if i == "2":
i = "0010"
if i == "3":
i = "0011"
if i == "4":
i = "0100"
if i == "5":
i = "0101"
if i == "6":
i = "0110"
if i == "7":
i = "0111"
if i == "8":
i = "1000"
if i == "9":
i = "1001"
if i == "A":
i = "1010"
if i == "B":
i = "1011"
if i == "C":
i = "1100"
if i == "D":
i = "1101"
if i == "E":
i = "1110"
if i == "F":
i = "1111"
result += i
# display result
print("Number in binary is: ", result)
# binary to hex (integer only)
if select_menu == 10:
print("10. Binary to Hexadecimal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a integer binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
# decimal to hexadecimal
decimal_num = str(result_int + result_fra)
decimal_int = eval(decimal_num)
result_int = ""
# integer loop
while decimal_int >= 1:
remainder = decimal_int % 16
if remainder == 10:
remainder = "A"
if remainder == 11:
remainder = "B"
if remainder == 12:
remainder = "C"
if remainder == 13:
remainder = "D"
if remainder == 14:
remainder = "E"
if remainder == 15:
remainder = "F"
result_int += str(remainder)
decimal_int = decimal_int // 16
print("Number in hexadecimal is", result_int[::-1])
again = input("Enter yes for again: ")
while again == "yes":
# ask user to select menu
select_menu = eval(input("1. Binary to Decimal\n2. Decimal to Binary\n3. Octal to Decimal\n4. Decimal to Octal\n\
5. Octal to Binary\n6. Binary to Octal\n7. Decimal to Hexadecimal\n8. Hexadecimal to Decimal\n\
9. Hexadecimal to Binary\n10. Binary to Hexadecimal\nPlease select a menu: "))
# binary to decimal
if select_menu == 1:
print("1. Binary to Decimal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", result_int + result_fra)
# for negative
else:
# integer loop
for int_num in binary_int_str:
if int_num == "-":
continue
result_int += eval(int_num) * pow(2, int_len - 2)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == "-":
continue
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", - (result_int + result_fra))
# decimal to binary
elif select_menu == 2:
print("2. Decimal to Binary")
# Decimal to binary
# ask user to enter decimal number
decimal_number = input("Enter a decimal number: ")
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
# for positive
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 2)
decimal_int = decimal_int // 2
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 2
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in binary is", eval(result_int[::-1]) + eval(result_fra))
# if 0 < x < 1
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 2
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in binary is", result_fra)
# octal to decimal
elif select_menu == 3:
print("3. Octal to Decimal")
# Octal to decimal
# ask user to input
octal_number = input("Enter a octal number: ")
octal_number_num = eval(octal_number)
len_octal = len(octal_number)
# integer part
octal_int = int(octal_number_num)
int_len = len(str(octal_int))
octal_int_str = str(octal_int)
# fractional part
octal_fra = round(octal_number_num - octal_int, len_octal - int_len - 1)
fra_len = len(str(octal_fra))
fra_len_to_sub = fra_len
octal_fra_str = str(octal_fra)
# result
result_fra = 0
result_int = 0
# for positive
if octal_number_num >= 0:
# integer loop
for int_num in octal_int_str:
result_int += eval(int_num) * pow(8, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in octal_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(8, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", result_int + result_fra)
# for negative
else:
# integer loop
for int_num in octal_int_str:
if int_num == "-":
continue
result_int += eval(int_num) * pow(8, int_len - 2)
int_len -= 1
# fractional loop
for fra_num in octal_fra_str:
if fra_num == "-":
continue
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(8, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
print("Number in decimal is", - (result_int + result_fra))
# decimal to octal
elif select_menu == 4:
print("4. Decimal to Octal")
# Decimal to octal
# ask user to enter decimal number
decimal_number = input("Enter a decimal number: ")
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
fra_len_to_sub = fra_len
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 8)
decimal_int = decimal_int // 8
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", eval(result_int[::-1]) + eval(result_fra))
# in range (0,1)
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", result_fra)
# octal to binary
elif select_menu == 5:
print("5. Octal to Binary")
# octal to binary
# ask user to input
oct_to_bin = (input("Enter a octal number: "))
oct_to_bin_int = int(eval(oct_to_bin))
length_full_oct = len(oct_to_bin)
oct_to_bin_fra = round(eval(oct_to_bin) - oct_to_bin_int, length_full_oct - len(str(oct_to_bin_int)) - 1)
oct_to_bin_fra_rep = str(oct_to_bin_fra).replace("0.", ".")
result_int = ""
result_fra = ""
for i in str(oct_to_bin_int):
if i == "0":
i = "000"
if i == "1":
i = "001"
if i == "2":
i = "010"
if i == "3":
i = "011"
if i == "4":
i = "100"
if i == "5":
i = "101"
if i == "6":
i = "110"
if i == "7":
i = "111"
result_int += i
# fractional part
for i in str(oct_to_bin_fra_rep):
if i == ".":
continue
if i == "0":
i = "000"
if i == "1":
i = "001"
if i == "2":
i = "010"
if i == "3":
i = "011"
if i == "4":
i = "100"
if i == "5":
i = "101"
if i == "6":
i = "110"
if i == "7":
i = "111"
result_fra += i
# result
print("Number in binary is:", str(int(result_int)) + "." + result_fra)
# binary to octal
elif select_menu == 6:
print("6. Binary to Octal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
# convert from decimal to octal
decimal_number = str(result_fra + result_int)
decimal_number_num = eval(decimal_number)
len_decimal = len(decimal_number)
# integer part
decimal_int = int(decimal_number_num)
int_len = len(str(decimal_int))
# fractional part
decimal_fra = round(decimal_number_num - decimal_int, len_decimal - int_len - 1)
fra_len = len(str(decimal_fra))
fra_len_to_sub = fra_len
decimal_fra_num_to_loop = 0
# result
result_fra = "0."
result_int = ""
if decimal_number_num >= 0:
if decimal_int > 0:
# integer loop
while decimal_int >= 1:
result_int += str(decimal_int % 8)
decimal_int = decimal_int // 8
# fractional loop
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", eval(result_int[::-1]) + eval(result_fra))
# in range (0,1)
elif decimal_int == 0:
while decimal_fra_num_to_loop < 10:
if str(decimal_fra) == ".":
continue
decimal_fra = decimal_fra * 8
result_fra += str(int(decimal_fra))
decimal_fra = round(decimal_fra - int(decimal_fra), fra_len - 2)
decimal_fra_num_to_loop += 1
print("Number in octal is", result_fra)
# decimal to hex
elif select_menu == 7:
print("7. Decimal to Hexadecimal")
# ask user to choose type
select_type = eval(input("Type:\n1 For integer number\n2 For float number in range (0,1)\
\nPlease select a type: "))
# integer number
if select_type == 1:
decimal_num = input("Enter a integer decimal number: ")
decimal_int = eval(decimal_num)
result_int = ""
# integer loop
while decimal_int >= 1:
remainder = decimal_int % 16
if remainder == 10:
remainder = "A"
if remainder == 11:
remainder = "B"
if remainder == 12:
remainder = "C"
if remainder == 13:
remainder = "D"
if remainder == 14:
remainder = "E"
if remainder == 15:
remainder = "F"
result_int += str(remainder)
decimal_int = decimal_int // 16
print("Number in hexadecimal is", result_int[::-1])
# range(0,1)
if select_type == 2:
# fractional loop
decimal_num_str = input("Enter a float decimal number in range (0,1): ")
decimal_num = eval(decimal_num_str)
loop_num = 0
int_int = ""
result = "0."
decimal_fra_num_to_loop = 0
while decimal_fra_num_to_loop < 10:
if str(decimal_num) == ".":
continue
decimal_num = decimal_num * 16
if decimal_num < 10:
int_int = int(decimal_num)
if 10 <= decimal_num < 11:
int_int = "A"
if 11 <= decimal_num < 12:
int_int = "B"
if 12 <= decimal_num < 13:
int_int = "C"
if 13 <= decimal_num < 14:
int_int = "D"
if 14 <= decimal_num < 15:
int_int = "E"
if 15 <= decimal_num < 16:
int_int = "F"
result += str(int_int)
decimal_num = round(decimal_num - int(decimal_num), len(decimal_num_str) - 2)
decimal_fra_num_to_loop += 1
print("Number in hexadecimal is", result)
# hex to decimal
elif select_menu == 8:
print("8. Hexadecimal to Decimal")
# ask user to input
hex_number = input("Enter a hexadecimal number: ")
int_hex_num = ""
for i in hex_number:
int_hex_num += i
if i == ".":
break
int_hex_num_strip = int_hex_num.strip(".")
int_len = len(int_hex_num_strip)
result_int = 0
fra_hex_num = hex_number.replace(int_hex_num, "0.")
fra_hex_len = len(fra_hex_num)
fra_len_to_sub = fra_hex_len
result_fra = 0
# integer loop
for int_num in int_hex_num_strip:
A, B, C, D, E, F = 10, 11, 12, 13, 14, 15
result_int += eval(int_num) * pow(16, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in fra_hex_num:
A, B, C, D, E, F = 10, 11, 12, 13, 14, 15
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(16, fra_len_to_sub - fra_hex_len)
fra_len_to_sub -= 1
# result both
print("Number in decimal is", result_int + result_fra)
# hex to bin
elif select_menu == 9:
print("9. Hexadecimal to Binary")
# hex to binary
# ask user to input
hex_to_bin = (input("Enter a hexadecimal number: "))
result = ""
# loop
for i in str(hex_to_bin):
if i == ".":
i = "."
if i == "0":
i = "0000"
if i == "1":
i = "0001"
if i == "2":
i = "0010"
if i == "3":
i = "0011"
if i == "4":
i = "0100"
if i == "5":
i = "0101"
if i == "6":
i = "0110"
if i == "7":
i = "0111"
if i == "8":
i = "1000"
if i == "9":
i = "1001"
if i == "A":
i = "1010"
if i == "B":
i = "1011"
if i == "C":
i = "1100"
if i == "D":
i = "1101"
if i == "E":
i = "1110"
if i == "F":
i = "1111"
result += i
# display result
print("Number in binary is: ", result)
# binary to hex (integer only)
if select_menu == 10:
print("10. Binary to Hexadecimal")
# Binary to decimal
# ask user to input
binary_number = input("Enter a integer binary number: ")
binary_number_num = eval(binary_number)
len_binary = len(binary_number)
# integer part
binary_int = int(binary_number_num)
int_len = len(str(binary_int))
binary_int_str = str(binary_int)
# fractional part
binary_fra = round(binary_number_num - binary_int, len_binary - int_len - 1)
fra_len = len(str(binary_fra))
fra_len_to_sub = fra_len
binary_fra_str = str(binary_fra)
# result
result_fra = 0
result_int = 0
# for positive
if binary_number_num >= 0:
# integer loop
for int_num in binary_int_str:
result_int += eval(int_num) * pow(2, int_len - 1)
int_len -= 1
# fractional loop
for fra_num in binary_fra_str:
if fra_num == ".":
continue
result_fra += eval(fra_num) * pow(2, fra_len_to_sub - fra_len)
fra_len_to_sub -= 1
# decimal to hexadecimal
decimal_num = str(result_int + result_fra)
decimal_int = eval(decimal_num)
result_int = ""
# integer loop
while decimal_int >= 1:
remainder = decimal_int % 16
if remainder == 10:
remainder = "A"
if remainder == 11:
remainder = "B"
if remainder == 12:
remainder = "C"
if remainder == 13:
remainder = "D"
if remainder == 14:
remainder = "E"
if remainder == 15:
remainder = "F"
result_int += str(remainder)
decimal_int = decimal_int // 16
print("Number in hexadecimal is", result_int[::-1])
again = input("Enter yes for again: ")
print("Bye!!!") |
"""
@Date: 14/04/2021 ~ Version: 1.1
@Group: RIDDLER
@Author: Ahmet Feyzi Halaç
@Author: Aybars Altınışık
@Author: Ege Şahin
@Author: Göktuğ Gürbüztürk
@Author: Zeynep Cankara
@Description: A rule based Zookeeper System from Winston chapter 7
- Contains classes Zookeeper, Rule
- Zookeeper class implements bacward-chaining
"""
class Rule(object):
def __init__(self, antecedents, consequents, rule_no=""):
"""Antecedent-consequent rules
Uses tree structure to find possible connections between rules
Args:
antecedents, type(list)
consequents, type(list)
antecedents_rules, type(list(Rule))
consequents_rules, type(list(Rule))
"""
self.antecedents = set(antecedents)
self.consequents = set(consequents)
# the list of rules leading to current rule
self.antecedents_rules = []
# the list of rules the current rule leads to
self.consequents_rules = []
self.rule_no = rule_no
def get_antecedents(self, consequents):
""" Returns the set of antecedents if all consequents satisfied
Args:
consequents: type(list(str))
Returns:
antecedents: type(set(str))
"""
if set(consequents) != self.consequents:
return None
return self.antecedents
def get_consequents(self, antecedents):
""" Returns the set of consequents if all antecedents satisfied
Args:
antecedents: type(list(str))
Returns:
consequents: type(set(str))
"""
if set(antecedents) != self.antecedents:
return None
return self.consequents
def set_consequents_rules(self, rules):
""" Sets possible rules can reached from the given rule
Args:
rules: type(list(Rule))
"""
for rule in rules:
for consequent in self.consequents:
if consequent in rule.antecedents:
self.consequents_rules.append(rule)
def set_antecedents_rules(self, rules):
""" Sets possible rules can reached to the current rule
Args:
rules: type(list(Rule))
"""
for rule in rules:
for antecedent in self.antecedents:
if antecedent in rule.consequents:
self.antecedents_rules.append(rule)
def __repr__(self):
return self.rule_no
def __str__(self):
"""String representation of the rule
Returns:
type(str), formatted string
"""
state_str = (self.rule_no + "\n")
state_str += "antecedents(" + str(self.antecedents) + ") -> "
state_str += "consequents( " + str(self.consequents) + ") \n"
return state_str
# define set of rules from Winston ch. 7 for the Zookeeper
Z1 = Rule(["?x has hair"], ["?x is a mammal"], "Z1")
Z2 = Rule(["?x gives milk"], ["?x is a mammal"], "Z2")
Z3 = Rule(["?x has feathers"], ["?x is a bird"], "Z3")
Z4 = Rule(["?x flies", "?x lays eggs"], ["?x is a bird"], "Z4")
Z5 = Rule(["?x is a mammal", "?x eats meat"], ["?x is a carnivore"], "Z5")
Z6 = Rule(["?x is a mammal", "?x has pointed teeth", "?x has claws",
"?x has forward-pointing eyes"], ["?x is a carnivore"], "Z6")
Z7 = Rule(["?x is a mammal", "?x has hoofs"], ["?x is an ungulate"], "Z7")
Z8 = Rule(["?x is a mammal", "?x chews cud"], ["?x is an ungulate"], "Z8")
Z9 = Rule(["?x is a carnivore", "?x has a tawny color",
"?x has dark spots"], ["?x is a cheetah"], "Z9")
Z10 = Rule(["?x is a carnivore", "?x has a tawny color",
"?x has black stripes"], ["?x is a tiger"], "Z10")
Z11 = Rule(["?x is an ungulate", "?x has long legs",
"?x has a long neck", "?x has a tawny color", "?x has dark spots"],
["?x is a giraffe"], "Z11")
Z12 = Rule(["?x is an ungulate", "?x has white color", "?x has black stripes"],
["?x is a zebra"], "Z12")
Z13 = Rule(["?x is a bird", "?x does not fly",
"?x has long legs", "?x has a long neck", "?x is black and white"],
["?x is an ostrich"], "Z13")
Z14 = Rule(["?x is a bird", "?x does not fly",
"?x swims", "?x is black and white"], ["?x is a penguin"], "Z14")
Z15 = Rule(["?x is a bird", "?x is a good flyer"],
["?x is an albatross"], "Z15")
class Zookeeper(object):
def __init__(self, wm, traceMode):
"""Rule based Zookeeper system constructor
Args:
wm: type(list), working memory
traceMode: type(bool), flag for enabling single stepping mode
Attributes:
wm: type(list), working memory
traceMode: type(bool), flag for enabling single stepping mode
rules: type(list(Rule)), list of rules for BC
"""
self.wm = wm
self.traceMode = traceMode
self.rules = [Z1, Z2, Z3, Z4, Z5, Z6, Z7,
Z8, Z9, Z10, Z11, Z12, Z13, Z14, Z15]
for i, rule in enumerate(self.rules):
rule.set_consequents_rules(
[Z for idx, Z in enumerate(self.rules) if idx != i])
rule.set_antecedents_rules(
[Z for idx, Z in enumerate(self.rules) if idx != i])
def backward_chaining(self, animalName, hypothesis):
"""Tests the animal against hypothesis
"""
for i in range(8, 15):
if ("?x " + hypothesis) in self.rules[i].consequents:
found = self.recursiveBackward(self.rules[i], animalName)
break
if not found:
i = -1
print("Animal is not found!")
else:
for final_conseq in self.rules[i].consequents:
print(animalName, final_conseq[3:])
print()
def recursiveBackward(self, rule, animalName):
if self.traceMode:
print('Checking for rule', rule.rule_no)
# Initially, assume all rules are satisfied. If there are any counter-examples, make this variable false, return true otherwise
rulesSatisfied = True
for antecedent in rule.antecedents:
if self.traceMode:
input()
print('Checking if', antecedent.replace('?x', animalName))
# Initially, assume specified antecedent is basic, meaning there are no rules whose consequent is this antecedent
# If there is any rule which disproves this assumption, make it false
basicAntecedent = True
# There can be multiple rules with same consequence equal to specified antecedent
# So, initially, assume there are no triggered rules whose consequence equals to specified antecedent
# If any rule returns true, make this variable true
validRuleExists = False
# Look for a rule whose consequence is specified antecedent
for antecedent_rule in rule.antecedents_rules:
if antecedent in antecedent_rule.consequents:
# Rule is found, so antecedent is not a basic one
basicAntecedent = False
# Call recursiveBackward with this rule
if self.recursiveBackward(antecedent_rule, animalName):
# Rule is triggered
validRuleExists = True
break
if basicAntecedent:
# Antecedent is a basic one, so, just search working memory for antecedent
if antecedent not in self.wm:
# Antecedent is not in working memory, so rule should not be satisfied
rulesSatisfied = False
if self.traceMode:
print('\'' + antecedent.replace('?x',
animalName) + '\' is wrong')
break
else:
# Antecedent is not a basic antecedent
if not validRuleExists:
# There are no satisfied rules whose consequence is specified antecedent
rulesSatisfied = False
if self.traceMode:
print('\'' + antecedent.replace('?x',
animalName) + '\' is wrong')
break
if self.traceMode:
if rulesSatisfied:
print(antecedent.replace('?x', animalName))
return rulesSatisfied
def __repr__(self):
return "Zookeeper()"
def __str__(self):
"""String representation of the zookeeper state
Returns:
type(str), formatted string
"""
state_str = "*** Zookeeper *** \n"
state_str += "working memory: \n" + str(self.wm) + "\n"
state_str += "rules: \n" + str(self.rules) + "\n"
return state_str
def __eq__(self, other):
"""Comparison function for Zookeepers
Args:
other: type(State), state to be compared
Returns:
type(bool) true if they are equal, false otherwise
"""
return (
self.wm == other.wm and self.rules == other.rules
)
def __hash__(self):
"""Calculates an hash number from the properties indicated.
Hash can be used in comparison of two instances.
Returns:
type(int) hash number
"""
return hash(
(
self.wm,
self.rules,
)
)
|
def moving_average(list_value, windows_size):
average_values = []
while(len(list_value) > windows_size):
sum = 0
index = 0
while(index < windows_size):
sum += list_value[index]
index += 1
average_values.append(sum / windows_size)
list_value.pop(0)
return average_values
def moving_average2(list_value, windows_size):
average_values = []
# Initialisation
sum = 0
init_index = 0
while(init_index < windows_size):
sum += list_value[init_index]
init_index += 1
average_values.append(sum / windows_size)
# Moving sum
index = 0
while(index + windows_size < len(list_value)):
# We just remove the element before and append the element after every iteration
# So we don't have to sum all the numbers in our windows size every time
sum -= list_value[index]
sum += list_value[index + windows_size]
average_values.append(sum / windows_size)
index += 1
return average_values
to_analyse = [n for n in range(20)]
to_analyse = [2, 4, 1, 8, 9, 14, 2, 46, 4, 36, 82, 12, 27, 23, 84, 63, 25, 60, 9]
print(moving_average2(to_analyse, 2))
|
#!/usr/bin/env python
import time
def display_digit(number):
for i in range(0, number):
display = '.'
print(display, sep='', end='', flush=True)
time.sleep(1)
print(" [x] Done !")
return number
|
import sqlite3 as sql
class Quote:
"""
this class defines a quote type
"""
def __init__(self, text,movie_name,movie_id,quote_id,interested,total_replies):
self.text = text
self.movie_name = movie_name
self.movie_id = movie_id
self.quote_id = quote_id
self.interested = interested
self.total_replies = total_replies
DB_PATH = "DB\\top_250_movie_quotes.db"
READ_TABLE_NAME = "top_quotes_db"
WRITE_TABLE_NAME = "top_question_quotes_db"
def parse_row_to_quote(row):
"""
:param row:
:return:
"""
#getting the quote attributes from the table row:
quote_id = int(row[0])
quote_text = row[1]
movie_name = row[2]
movie_id = row[3]
interested = int(row[4])
total_replies = int(row[5])
quote = Quote(quote_text,movie_name,movie_id,quote_id, interested,total_replies)
return quote
def get_quotes_from_table(db_path, table_name):
"""
:param db_path:
:param table_name:
:return:
"""
quote_lst = []
conn = sql.connect(db_path)
table = conn.execute("SELECT * FROM "+table_name)
for row in table: #going over all rows
#checking if the quote fits our purpose:
if (check_question_mark(row[1])):
quote_lst.append(parse_row_to_quote(row))
return quote_lst
def check_question_mark(quote_text):
"""
:param quote_text:
:return:
"""
return ("?" in quote_text)
def write_top_quotes(quotes_lst,db_path, table_name, n):
"""
:param quotes_lst:
:param db_path:
:param table_name:
:param n:
:return:
"""
conn = sql.connect(db_path)
#sorting the quotes list:
quotes_lst.sort(key = get_interested,reverse = True)
for i in range(n):
quote = quotes_lst[i]
#writing quote to the DB
conn.execute("INSERT INTO "+table_name+" (ID,QUOTE,MOVIE_NAME,MOVIE_ID,INTERESTED,"
"TOTAL_REP) VALUES " "(?,?,?,?,?,?)",(quote.quote_id,quote.text,
quote.movie_name, quote.movie_id,quote.interested,quote.total_replies))
conn.commit()
def get_interested(quote):
"""
:param quote:
:return:
"""
return quote.interested
def quote_handler(n):
"""
:param n:
:return:
"""
#getting the quotes
quotes_lst = get_quotes_from_table(DB_PATH,READ_TABLE_NAME)
write_top_quotes(quotes_lst, DB_PATH, WRITE_TABLE_NAME,n)
quote_handler(200) |
"""
This is a search command for doing ping lookups on results.
"""
import logging
from network_tools_app import ping
from network_tools_app.custom_lookup import CustomLookup
class PingLookup(CustomLookup):
"""
This class implements the functionality necessary to make a custom search command.
"""
def __init__(self):
"""
Constructs an instance of the ping lookup command.
"""
# Here is a list of the accepted fieldnames
fieldnames = ['sent', 'received', 'packet_loss', 'min_ping', 'max_ping', 'avg_ping',
'jitter', 'return_code', 'raw_output']
CustomLookup.__init__(self, fieldnames, 'ping_lookup_command', logging.INFO)
def do_lookup(self, host):
"""
Perform a ping against the given host.
"""
self.logger.info("Running ping against host=%s", host)
raw_output, return_code, output = ping(host=host, index=None)
output['return_code'] = return_code
output['raw_output'] = raw_output
return output
PingLookup.main()
|
import math
import os
import random
import re
import sys
def solve(m, t1, t2):
print(int(round(m+(m*t1/100)+(m*t2/100))))
if __name__ == '__main__':
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
solve(meal_cost, tip_percent, tax_percent)
|
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
if not str:
return 0
if not (str[0].isdigit() or str[0] == '-' or str[0] == '+'):
return 0
new_str = []
if str[0] == '-':
new_str.append('-')
str = str[1:]
elif str[0] == '+':
str = str[1:]
for char in str:
if not char.isdigit():
break
new_str.append(char)
try:
answer = int("".join(new_str))
except Exception as e:
answer = 0
if answer < -(2**31):
return -(2**31)
elif answer > 2**31 -1:
return 2**31 -1
else:
return answer
|
def fibonachi(x):
f1 = f2 = fs = 1
print(f1)
print(f2)
m = 0
t = True
while t is not False :
fs = f1 + f2
f1 = f2
f2 = fs
if fs > x :
t = False
else:
print(fs)
t = True
return f2
def fibonachi2(n):
f1 = f2 = fs = 1
m = 0
while m < n-2 :
fs = f1 + f2
f1 = f2
f2 = fs
m += 1
return fs
def recFibonacci(n):
if n <=1 :
return n
return recFibonacci(n-1) + recFibonacci(n-2)
d = fibonachi2(9)
print(d) |
def sort(lst):
n = len(lst)
for i in range(n):
#Выбираем ключ , то что будем перемещать
k = lst[i]
# Место для перемещения
j = i
# Пока ключ меньше предыдущих элементов или пока массив не закончится передвигаем
while (lst[j-1] > k) and (j > 0):
lst[j] = lst[j-1]
j = j - 1
lst[j] = k
#print(lst)
return lst
q = [2,6,4,3,1,5]
print(sort(q)) |
from csv import reader
import requests
def getrss(url, filename):
url = url
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)
# skip first line i.e. read header first and then iterate over each row od csv as a list
with open('feeds.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
header = next(csv_reader)
# Check file as empty
if header != None:
# Iterate over each row
# after the header in the csv
for row in csv_reader:
# row variable is a list that represents a row in csv
getrss(row[2], row[3]) |
import datetime as dt
DATE_FORMAT = '%d.%m.%Y'
class Calculator:
def __init__(self, limit):
self.limit = limit
self.records = []
def add_record(self, record):
self.records.append(record)
def get_today_stats(self):
today_date = dt.date.today()
return sum(
record.amount for record in self.records
if record.date == today_date
)
def get_week_stats(self):
today_date = dt.date.today()
week_ago = today_date - dt.timedelta(days=7)
return sum(
day.amount for day in self.records
if week_ago < day.date <= today_date
)
class Record:
def __init__(self, amount, comment, date=None):
self.amount = amount
self.comment = comment
if date is None:
self.date = dt.datetime.now().date()
else:
self.date = dt.datetime.strptime(date, DATE_FORMAT).date()
def show(self):
print(f"{self.amount}, {self.comment}, {self.date}.")
class CaloriesCalculator(Calculator):
THIN = (
'Сегодня можно съесть что-нибудь ещё,'
' но с общей калорийностью не более {value} кКал'
)
FAT = ('Хватит есть!')
def get_calories_remained(self):
remained = self.limit - self.get_today_stats()
if remained > 0:
return self.THIN.format(value=remained)
return self.FAT
class CashCalculator(Calculator):
USD_RATE = 60.0
EURO_RATE = 70.0
CURRENCIES = {
"rub": (1, "руб"),
"usd": (USD_RATE, "USD"),
"eur": (EURO_RATE, "Euro")
}
VALUE = ('Валюта "{value}" не поддерживается')
LIMIT = ('Денег нет, держись')
RICH = ('На сегодня осталось {value} {name}')
CREDIT = ('Денег нет, держись: твой долг - {value} {name}')
def get_today_cash_remained(self, currency):
if currency not in self.CURRENCIES:
raise ValueError(self.VALUE.format(value=currency))
if self.limit == self.get_today_stats():
return self.LIMIT
rate, price = self.CURRENCIES[currency]
today_balance = self.limit - self.get_today_stats()
currency_balance = round(
today_balance / rate, 2
)
if today_balance > 0:
return self.RICH.format(
value=currency_balance, name=price
)
currency_credit = abs(currency_balance)
return self.CREDIT.format(
value=currency_credit, name=price
)
if __name__ == "__main__":
calories_calculator = CaloriesCalculator(2000)
r4 = Record(amount=1200, comment="Кусок тортика. И ещё один.")
r5 = Record(amount=84, comment="Йогурт")
r6 = Record(amount=1140, comment="Баночка чипсов.", date="08.10.2020")
calories_calculator.add_record(r4)
calories_calculator.add_record(r5)
calories_calculator.add_record(r6)
print(calories_calculator.get_today_stats())
print(calories_calculator.get_calories_remained())
cach_calculator = CashCalculator(5000)
r1 = Record(amount=145, comment="Безудержный шопинг", date="08.10.2020")
r2 = Record(amount=5600, comment="Наполнение потребительской корзины")
r3 = Record(amount=691, comment="Катание на такси", date="07.10.2020")
cach_calculator.add_record(r1)
cach_calculator.add_record(r2)
cach_calculator.add_record(r3)
print(cach_calculator.get_week_stats())
print(cach_calculator.get_today_cash_remained("eur"))
|
"""
Functions for finding a mask on a lat/lon grid from an input boundary
=====================================================================
"""
import warnings
import numpy as np
import shapely as sh
import matplotlib.path as mplp
import geocontour.grid as gcg
import geocontour.maskutil as gcmu
def center(latitudes,longitudes,boundary,precision=1e-5):
"""
Find a mask on a lat/lon grid from an input boundary
Criteria for inclusion of a cell is whether the center of the cell
falls within the boundary
Parameters
----------
latitudes : ndarray
1D Nx1 array of latitude points (degrees)
longitudes : ndarray
1D Nx1 array of longitude points (degrees)
boundary : ndarray
2D Nx2 array of latitude/longitude points (degrees) with the
last point equal to the first
precision : float, default=1e-5
value by which `boundary` is expanded, capturing indeterminate
points that may fall on/near `boundary`
Returns
-------
mask : ndarray
2D MxN bool array where M=len(`latitudes`) and
N=len(`longitudes`)
See Also
--------
center2
nodes
nodes2
area
Notes
-----
Regarding `precision`: Shapely can't beat machine precision, and can
thus give "incorrect" results for very close points or shapes. The
`precision` input errs on being more inclusive, in particular to
capture points falling directly on a boundary. A decent rule is to
set the `precision` value as high as you can without impeding the
accuracy. For instance, the default of 1e-5 (degrees) translates to
roughly 1m precision at the equator. The buffer can be negated by
setting this input very low (to machine precision).
"""
latdir=gcg.clatdir(latitudes)
if latdir=='dec':
latitudes=np.flip(latitudes)
boxlatmin, boxlatmax, boxlonmin, boxlonmax = gcmu.bbox(latitudes,longitudes,boundary)
boxmask=np.full((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1),False)
boundpoly=sh.polygons(boundary).buffer(precision)
ysp, xsp = np.meshgrid(latitudes[boxlatmin:boxlatmax+1],longitudes[boxlonmin:boxlonmax+1], indexing='ij')
searchpoints=np.hstack((ysp.reshape((-1,1)), xsp.reshape((-1,1))))
shsearchpoints=sh.points(searchpoints)
boxmask=sh.contains(boundpoly,shsearchpoints)
mask=np.full((len(latitudes),len(longitudes)),False)
mask[boxlatmin:boxlatmax+1,boxlonmin:boxlonmax+1]=boxmask.reshape((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1))
if latdir=='dec':
mask=np.flip(mask,axis=0)
return mask
def center2(latitudes,longitudes,boundary,precision=1e-5):
"""
Find a mask on a lat/lon grid from an input boundary
Criteria for inclusion of a cell is whether the center of the cell
falls within the boundary
Functionally identical to `center()`, but utilizes matplotlib.path
functions, which are faster (possibly due to avoidance of overhead
in converting to shapely geometries)
Parameters
----------
latitudes : ndarray
1D Nx1 array of latitude points (degrees)
longitudes : ndarray
1D Nx1 array of longitude points (degrees)
boundary : ndarray
2D Nx2 array of latitude/longitude points (degrees) with the
last point equal to the first
precision : float, default=1e-5
value by which `boundary` is expanded, capturing indeterminate
points that may fall on/near `boundary`
Returns
-------
mask : ndarray
2D MxN bool array where M=len(`latitudes`) and
N=len(`longitudes`)
See Also
--------
center
nodes
nodes2
area
Notes
-----
Regarding `precision`: Matplotlib.Path can't beat machine precision,
and can thus give "incorrect" results for very close points or
shapes. The `precision` input errs on being more inclusive, in
particular to capture points falling directly on a boundary. A
decent rule is to set the `precision` value as high as you can
without impeding the accuracy. For instance, the default of 1e-5
(degrees) translates to roughly 1m precision at the equator. The
buffer can be negated by setting this input very low (to machine
precision).
"""
latdir=gcg.clatdir(latitudes)
if latdir=='dec':
latitudes=np.flip(latitudes)
boxlatmin, boxlatmax, boxlonmin, boxlonmax = gcmu.bbox(latitudes,longitudes,boundary)
boundpoly=mplp.Path(boundary)
ysp, xsp = np.meshgrid(latitudes[boxlatmin:boxlatmax+1],longitudes[boxlonmin:boxlonmax+1], indexing='ij')
searchpoints=np.hstack((ysp.reshape((-1,1)), xsp.reshape((-1,1))))
boxmask=boundpoly.contains_points(searchpoints,radius=2*precision)
mask=np.full((len(latitudes),len(longitudes)),False)
mask[boxlatmin:boxlatmax+1,boxlonmin:boxlonmax+1]=boxmask.reshape((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1))
if latdir=='dec':
mask=np.flip(mask,axis=0)
return mask
def nodes(latitudes,longitudes,boundary,nodes=2,precision=1e-5):
"""
Find a mask on a lat/lon grid from an input boundary
Criteria for inclusion of a cell is whether a given number of cell
nodes (corners) fall within the boundary
Parameters
----------
latitudes : ndarray
1D Nx1 array of latitude points (degrees)
longitudes : ndarray
1D Nx1 array of longitude points (degrees)
boundary : ndarray
2D Nx2 array of latitude/longitude points (degrees) with the
last point equal to the first
nodes : int, default=2
number of cell nodes (corners) to use as a criteria for
inclusion (1-4)
precision : float, default=1e-5
value by which `boundary` is expanded, capturing indeterminate
points that may fall on/near `boundary`
Returns
-------
mask : ndarray
2D MxN bool array where M=len(`latitudes`) and
N=len(`longitudes`)
See Also
--------
center
center2
nodes2
area
Notes
-----
Regarding `precision`: Shapely can't beat machine precision, and can
thus give "incorrect" results for very close points or shapes. The
`precision` input errs on being more inclusive, in particular to
capture points falling directly on a boundary. A decent rule is to
set the `precision` value as high as you can without impeding the
accuracy. For instance, the default of 1e-5 (degrees) translates to
roughly 1m precision at the equator. The buffer can be negated by
setting this input very low (to machine precision).
"""
if nodes<1:
warnings.warn('WARNING - valid input for nodes is 1-4, nodes<1 will result in all cells being selected')
if nodes>4:
warnings.warn('WARNING - valid input for nodes is 1-4, nodes>4 will result in no cells being selected')
latdir=gcg.clatdir(latitudes)
if latdir=='dec':
latitudes=np.flip(latitudes)
boxlatmin, boxlatmax, boxlonmin, boxlonmax = gcmu.bbox(latitudes,longitudes,boundary)
latgrdspc=gcg.spacing(latitudes)
longrdspc=gcg.spacing(longitudes)
boxmask=np.full((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1),False)
boundpoly=sh.polygons(boundary).buffer(precision)
yspMM, xspMM = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]-latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]-longrdspc/2, indexing='ij')
yspPM, xspPM = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]+latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]-longrdspc/2, indexing='ij')
yspMP, xspMP = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]-latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]+longrdspc/2, indexing='ij')
yspPP, xspPP = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]+latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]+longrdspc/2, indexing='ij')
spMM=np.hstack((yspMM.reshape((-1,1)),xspMM.reshape((-1,1))))
spPM=np.hstack((yspPM.reshape((-1,1)),xspPM.reshape((-1,1))))
spMP=np.hstack((yspMP.reshape((-1,1)),xspMP.reshape((-1,1))))
spPP=np.hstack((yspPP.reshape((-1,1)),xspPP.reshape((-1,1))))
searchpoints=np.stack((spMM,spPM,spMP,spPP)).reshape(-1,2)
shsearchpoints=sh.points(searchpoints)
nodesinmask=sh.contains(boundpoly,shsearchpoints).reshape(4,-1)
boxmask=(nodesinmask.sum(axis=0)>=nodes).reshape(boxmask.shape)
mask=np.full((len(latitudes),len(longitudes)),False)
mask[boxlatmin:boxlatmax+1,boxlonmin:boxlonmax+1]=boxmask
if latdir=='dec':
mask=np.flip(mask,axis=0)
return mask
def nodes2(latitudes,longitudes,boundary,nodes=2,precision=1e-5):
"""
Find a mask on a lat/lon grid from an input boundary
Criteria for inclusion of a cell is whether a given number of cell
nodes (corners) fall within the boundary
Functionally identical to `nodes()`, but utilizes matplotlib.path
functions, which are faster (possibly due to avoidance of overhead
in converting to shapely geometries)
Parameters
----------
latitudes : ndarray
1D Nx1 array of latitude points (degrees)
longitudes : ndarray
1D Nx1 array of longitude points (degrees)
boundary : ndarray
2D Nx2 array of latitude/longitude points (degrees) with the
last point equal to the first
nodes : int, default=2
number of cell nodes (corners) to use as a criteria for
inclusion (1-4)
precision : float, default=1e-5
value by which `boundary` is expanded, capturing indeterminate
points that may fall on/near `boundary`
Returns
-------
mask : ndarray
2D MxN bool array where M=len(`latitudes`) and
N=len(`longitudes`)
See Also
--------
center
center2
nodes
area
Notes
-----
Regarding `precision`: Matplotlib.Path can't beat machine precision,
and can thus give "incorrect" results for very close points or
shapes. The `precision` input errs on being more inclusive, in
particular to capture points falling directly on a boundary. A
decent rule is to set the `precision` value as high as you can
without impeding the accuracy. For instance, the default of 1e-5
(degrees) translates to roughly 1m precision at the equator. The
buffer can be negated by setting this input very low (to machine
precision).
"""
if nodes<1:
warnings.warn('WARNING - valid input for nodes is 1-4, nodes<1 will result in all cells being selected')
if nodes>4:
warnings.warn('WARNING - valid input for nodes is 1-4, nodes>4 will result in no cells being selected')
latdir=gcg.clatdir(latitudes)
if latdir=='dec':
latitudes=np.flip(latitudes)
boxlatmin, boxlatmax, boxlonmin, boxlonmax = gcmu.bbox(latitudes,longitudes,boundary)
latgrdspc=gcg.spacing(latitudes)
longrdspc=gcg.spacing(longitudes)
boxmask=np.full((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1),False)
boundpoly=mplp.Path(boundary)
yspMM, xspMM = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]-latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]-longrdspc/2, indexing='ij')
yspPM, xspPM = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]+latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]-longrdspc/2, indexing='ij')
yspMP, xspMP = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]-latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]+longrdspc/2, indexing='ij')
yspPP, xspPP = np.meshgrid(latitudes[boxlatmin:boxlatmax+1]+latgrdspc/2,longitudes[boxlonmin:boxlonmax+1]+longrdspc/2, indexing='ij')
spMM=np.hstack((yspMM.reshape((-1,1)),xspMM.reshape((-1,1))))
spPM=np.hstack((yspPM.reshape((-1,1)),xspPM.reshape((-1,1))))
spMP=np.hstack((yspMP.reshape((-1,1)),xspMP.reshape((-1,1))))
spPP=np.hstack((yspPP.reshape((-1,1)),xspPP.reshape((-1,1))))
searchpoints=np.stack((spMM,spPM,spMP,spPP)).reshape(-1,2)
nodesinmask=boundpoly.contains_points(searchpoints,radius=2*precision).reshape(4,-1)
boxmask=(nodesinmask.sum(axis=0)>=nodes).reshape(boxmask.shape)
mask=np.full((len(latitudes),len(longitudes)),False)
mask[boxlatmin:boxlatmax+1,boxlonmin:boxlonmax+1]=boxmask
if latdir=='dec':
mask=np.flip(mask,axis=0)
return mask
def area(latitudes,longitudes,boundary,area=0.5):
"""
Find a mask on a lat/lon grid from an input boundary
Criteria for inclusion of a cell is whether the area of the cell
enclosed by the boundary is greater than some fraction between 0 and
1
Parameters
----------
latitudes : ndarray
1D Nx1 array of latitude points (degrees)
longitudes : ndarray
1D Nx1 array of longitude points (degrees)
boundary : ndarray
2D Nx2 array of latitude/longitude points (degrees) with the
last point equal to the first
area : float, default=0.5
the fraction of the cell enclosed by the boundary to use as a
criteria for inclusion (0-1)
Returns
-------
mask : ndarray
2D MxN bool array where M=len(`latitudes`) and
N=len(`longitudes`)
See Also
--------
center
center2
nodes
nodes2
"""
if area>1:
warnings.warn('WARNING - valid input for area is 0-1, area>1 will result in no cells being selected')
if area<=0:
warnings.warn('WARNING - valid input for area is 0-1, area<=0 will result in all cells being selected')
latdir=gcg.clatdir(latitudes)
if latdir=='dec':
latitudes=np.flip(latitudes)
boxlatmin, boxlatmax, boxlonmin, boxlonmax = gcmu.bbox(latitudes,longitudes,boundary)
latgrdspc=gcg.spacing(latitudes)
longrdspc=gcg.spacing(longitudes)
boxmask=np.full((boxlatmax-boxlatmin+1,boxlonmax-boxlonmin+1),False)
boundpoly=sh.polygons(boundary)
for la in np.arange(boxlatmin,boxlatmax+1,1):
for lo in np.arange(boxlonmin,boxlonmax+1,1):
LL=[latitudes[la]-latgrdspc/2,longitudes[lo]-longrdspc/2]
HL=[latitudes[la]+latgrdspc/2,longitudes[lo]-longrdspc/2]
LH=[latitudes[la]-latgrdspc/2,longitudes[lo]+longrdspc/2]
HH=[latitudes[la]+latgrdspc/2,longitudes[lo]+longrdspc/2]
cell=sh.polygons([LL,HL,HH,LH])
if boundpoly.intersection(cell).area>=latgrdspc*longrdspc*area:
boxmask[la-boxlatmin,lo-boxlonmin]=True
mask=np.full((len(latitudes),len(longitudes)),False)
mask[boxlatmin:boxlatmax+1,boxlonmin:boxlonmax+1]=boxmask
if latdir=='dec':
mask=np.flip(mask,axis=0)
return mask
|
var_1 = int(input("Введите первое число a: "))
var_2 = int(input("Введите второе число b: "))
var_3 = int(input("Введите третье число c: "))
res = var_1 and var_2 and var_3 and 'Нет нулевых значений.'
print(res)
res = var_1 or var_2 or var_3 or 'Введены все нули.'
print(res)
if var_1 > (var_2 + var_3):
print(f'разность суммы a - b - c = {var_1 - var_2 - var_3}')
elif var_1 < (var_2 + var_3):
print(f'разность суммы b + c - а = {var_2 + var_3 - var_1}')
if var_1 > 50 and (var_2 > var_1 or var_3 > var_1):
print('Вася')
if var_1 > 5 and (var_2 == 7 and var_3 == 7):
print('Петя') |
# multiAgents.py
# --------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {North, South, West, East, Stop}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def evaluationFunction(self, currentGameState, action):
"""
Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving (newPos).
newScaredTimes holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet.
Print out these variables to see what you're getting, then combine them
to create a masterful evaluation function.
"""
# Useful information you can extract from a GameState (pacman.py)
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanPosition()
newFood = currentGameState.getFood()
newGhostStates = successorGameState.getGhostStates()
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
closestFood = float("inf")
ghostForce = 0
foodList = newFood.asList()
for pos in foodList:
d = manhattanDistance(newPos, pos)
if d < closestFood:
closestFood = d
for ghost in newGhostStates:
d = manhattanDistance(newPos, ghost.configuration.pos)
if d == 0:
return float("-inf")
if d < 2:
ghostForce = ghostForce + 0.25 / (d * d)
if closestFood == 0:
return float("inf")
result = 1 + 0.5 / (closestFood * closestFood) - ghostForce
return result
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This class provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
Note: this is an abstract class: one that should not be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn='scoreEvaluationFunction', depth='2'):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = util.lookup(evalFn, globals())
self.depth = int(depth)
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
Directions.STOP:
The stop direction, which is always legal
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
"""
"*** YOUR CODE HERE ***"
values = {}
legalMoves = gameState.getLegalActions(0)
for action in legalMoves:
nextState = gameState.generateSuccessor(self.index, action)
value = self.minimax(nextState, self.index + 1, self.depth)
values[value] = action
return values[max(values)]
def minimax(self, state, index, depth):
result = 0
if depth == 0 or state.isWin() or state.isLose():
result = self.evaluationFunction(state)
elif index == self.index:
result = self.maximize(state, index, depth - 1)
else:
result = self.minimize(state, index, depth)
return result
def maximize(self, state, index, depth):
result = float("-inf")
legalMoves = state.getLegalActions(index)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = max(result, self.minimax(nextState, (index + 1) % state.getNumAgents(), depth))
return result
def minimize(self, state, index, depth):
result = float("inf")
legalMoves = state.getLegalActions(index)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = min(result, self.minimax(nextState, (index + 1) % state.getNumAgents(), depth))
return result
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 3)
"""
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
"*** YOUR CODE HERE ***"
values = {}
legalMoves = gameState.getLegalActions(0)
alpha = float("-inf")
for action in legalMoves:
nextState = gameState.generateSuccessor(self.index, action)
value = self.minimax(nextState, self.index + 1, self.depth, alpha, float("inf"))
values[value] = action
alpha = max(alpha, value)
return values[max(values)]
def minimax(self, state, index, depth, alpha, beta):
result = 0
if depth == 0 or state.isWin() or state.isLose():
result = self.evaluationFunction(state)
elif index == self.index:
result = self.maximize(state, index, depth - 1, alpha, beta)
else:
result = self.minimize(state, index, depth, alpha, beta)
return result
def maximize(self, state, index, depth, alpha, beta):
result = float("-inf")
legalMoves = state.getLegalActions(index)
if Directions.STOP in legalMoves:
legalMoves.remove(Directions.STOP)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = max(result, self.minimax(nextState, (index + 1) % state.getNumAgents(), depth, alpha, beta))
alpha = max(alpha, result)
if result >= beta:
return result
return result
def minimize(self, state, index, depth, alpha, beta):
result = float("inf")
legalMoves = state.getLegalActions(index)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = min(result, self.minimax(nextState, (index + 1) % state.getNumAgents(), depth, alpha, beta))
beta = min(beta, result)
if result <= alpha:
return result
return result
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def getAction(self, gameState):
"""
Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves.
"""
"*** YOUR CODE HERE ***"
values = {}
legalMoves = gameState.getLegalActions(0)
if Directions.STOP in legalMoves:
legalMoves.remove(Directions.STOP)
for action in legalMoves:
nextState = gameState.generateSuccessor(self.index, action)
value = self.minimax(nextState, self.index + 1, self.depth)
values[value] = action
return values[max(values)]
def minimax(self, state, index, depth):
result = 0
if depth == 0 or state.isWin() or state.isLose():
result = self.evaluationFunction(state)
elif index == self.index:
result = self.maximize(state, index, depth - 1)
else:
result = self.expected(state, index, depth)
return result
def maximize(self, state, index, depth):
result = float("-inf")
legalMoves = state.getLegalActions(index)
legalMoves.remove(Directions.STOP)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = max(result, self.minimax(nextState, (index + 1) % state.getNumAgents(), depth))
return result
def expected(self, state, index, depth):
result = 0
legalMoves = state.getLegalActions(index)
for action in legalMoves:
nextState = state.generateSuccessor(index, action)
result = result + self.minimax(nextState, (index + 1) % state.getNumAgents(), depth)
return result/len(legalMoves)
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: model evaluation function as particules forces between pacman and food (attract ) or ghost (repel).
"""
"*** YOUR CODE HERE ***"
if currentGameState.isLose():
return -9999999
elif currentGameState.isWin():
return 9999999
position = currentGameState.getPacmanPosition()
foodList = currentGameState.getFood().asList()
ghostStates = currentGameState.getGhostStates()
foodForce = float("-inf")
ghostsForce = 0
foodCharge = 2.0
ghostsCharge = -8.0
scaredCharge = 8.0
for foodPos in foodList:
d = manhattanDistance(position, foodPos)
force = foodCharge/(d*d)
if force > foodForce:
foodForce = force
for ghost in ghostStates:
d = manhattanDistance(position, ghost.configuration.pos)
if ghost.scaredTimer < d - 0.1:
if d <= 2:
return -9999999
elif d <= 10:
ghostsForce += ghostsCharge/(d*d)
else:
if d == 0:
return 9999999
ghostsForce += scaredCharge/(d*d)
pacmanForce = currentGameState.getScore() + ghostsForce + foodForce
return pacmanForce
# Abbreviation
better = betterEvaluationFunction
class ContestAgent(MultiAgentSearchAgent):
"""
Your agent for the mini-contest
"""
def getAction(self, gameState):
"""
Returns an action. You can use any method you want and search to any depth you want.
Just remember that the mini-contest is timed, so you have to trade off speed and computation.
Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
just make a beeline straight towards Pacman (or away from him if they're scared!)
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
|
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class MyTopo( Topo ):
"Simple topology example."
def __init__( self ):
"Create custom topo."
# Initialize topology
Topo.__init__( self )
# Add hosts and switches
leftHost = self.addHost( 'h1' )
rightHost = self.addHost( 'h4' )
leftHost2 = self.addHost( 'h2' )
upHost = self.addHost( 'h3' )
downHost = self.addHost( 'h5' )
leftSwitch = self.addSwitch( 's1' )
rightSwitch = self.addSwitch( 's3' )
upSwitch = self.addSwitch( 's2' )
downSwitch = self.addSwitch( 's4' )
# Add links
self.addLink( leftHost, leftSwitch )
self.addLink( leftHost2, leftSwitch )
self.addLink( upHost, upSwitch )
self.addLink( rightHost, rightSwitch )
self.addLink( downHost, rightSwitch )
self.addLink( leftSwitch, upSwitch, bw=10 )
self.addLink( leftSwitch, downSwitch, bw=5 )
self.addLink( rightSwitch, upSwitch, bw=20 )
self.addLink( rightSwitch, downSwitch, bw=10 )
self.addLink( upSwitch, downSwitch, bw=10 )
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
#UNIT CONVERTER
#1km is 0.621371192 miles
while True:
print("Hello, we are about to convert kilometers into miles!")
km = float(input("Tell me the number in kilometers: "))
mile = 0.621371192
print("it is " + format(km * mile) + " miles")
another = input("Do you want to do another conversion? ")
if another.lower() != "yes" and another.lower() != "y":
print("Thanks till next time")
break
|
import random
country_capitals = {"Greece": "Athens", "Serbia": "Belgrade", "Germany": "Berlin", "Switzerland": "Bern",
"Slovakia": "Bratislava", "Belgium": "Brussels", "Romania": "Bucharest", "Hungary": "Budapest", "Moldova": "Chisinau",
"Denmark": "Copenhagen", "Ireland": "Dublin", "Finland": "Helsinki", "Ukraine": "Kiev", "Portugal": "Lisbon",
"Slovenia": "Ljubljana", "United Kingdom": "London", "Luxembourg": "Luxembourg", "Andorra": "Andorra la Vella",
"Spain": "Madrid", "Belarus": "Minsk", "Monaco": "Monaco", "Russia": "Moscow", "Cyprus": "Nicosia", "Greenland": "Nuuk",
"Norway": "Oslo", "France": "Paris", "Montenegro": "Podgorica", "Czech Republic": "Prague", "Iceland": "Reykjavik",
"Latvia": "Riga", "Italy": "Rome", "San Marino": "San Marino", "Bosnia": "Sarajevo", "North Macedonia": "Skopje",
"Bulgaria": "Sofia", "Sweden": "Stockholm", "Estonia": "Tallinn", "Albania": "Tirana", "Liechtenstein": "Vaduz",
"Malta": "Valletta", "Vatican": "Vatican city", "Austria": "Vienna", "Poland": "Warsaw", "Croatia": "Zagreb",
"Netherlands": "Amsterdam", "Lithuania": "Vilnius", "Armenia": "Yerevan", "Turkey": "Ankara", "Azerbaijan": "Baku",
"Georgia": "Tbilisi"}
drz = random.choice(list(country_capitals.keys()))
def drzave():
drz = random.choice(list(country_capitals.keys()))
print("What is the capital city of " + drz + "?")
drzave()
guess = input("Answer: ")
for city in drz:
if drz[city]:
print("congrats")
break
else:
print("Not good")
|
# FIZZBUZ
print(" Let's play a game of fizzbuzz")
num1 = int(input("Choose a number between 1-100: "))
for num1 in range(1, num1 + 1):
if num1 % 3 == 0:
print("fizz")
elif num1 % 3 and num1 % 5 == 0:
print("fizzbuzz")
elif num1 % 5 == 0:
print("buzz")
else:
print(num1) |
import json
import tkinter as tkinter
from tkinter import filedialog
from datetime import date
# Sets the month and year variable based on the current date
month = date.today().month
year = date.today().year
# Create function to output the month and year
def printMonthYear(month, year):
# Create table for the written month
if month == 1:
writtenMonth = "January"
elif month == 2:
writtenMonth = "February"
elif month == 3:
writtenMonth = "March"
elif month == 4:
writtenMonth = "April"
elif month == 5:
writtenMonth = "May"
elif month == 6:
writtenMonth = "June"
elif month == 7:
writtenMonth = "July"
elif month == 8:
writtenMonth = "August"
elif month == 9:
writtenMonth = "September"
elif month == 10:
writtenMonth = "October"
elif month == 11:
writtenMonth = "November"
else:
writtenMonth = "December"
# Output month and year at top of calendar
monthYear = tkinter.Label(calendarFrame, text = writtenMonth + " " + str(year), font= ("Arial", 20))
monthYear.grid(column = 2, row = 0, columnspan = 3)
# Function to switch month calendar (1 for forwards and -1 for backwards)
def switchMonths(direction):
global calendarFrame
global month
global year
#check if we are goint to a new year
if month == 12 and direction == 1:
month = 0
year += 1
if month == 1 and direction == -1:
month = 13
year -= 1
# Clears the old dictionarys so they can be used in the next month
textObjectDict.clear()
saveDict.clear()
# Reprint the calendar with the new values
calendarFrame.destroy()
calendarFrame = tkinter.Frame(window)
calendarFrame.grid()
printMonthYear(month + direction, year) # pylint: disable=E0601
makeButtons()
monthGenerator(dayMonthStarts(month + direction, year), daysInMonth(month + direction, year))
month += direction
# Change month buttons at top of the page
def makeButtons():
goBack = tkinter.Button(calendarFrame, text = "<", command = lambda : switchMonths(-1))
goBack.grid(column = 0, row = 0)
goForward = tkinter.Button(calendarFrame, text = ">", command = lambda : switchMonths(1))
goForward.grid(column = 6, row = 0)
# Creates most of the calendar
def monthGenerator(startDate, numberOfDays):
# Holds the names for each day of the week
dayNames = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
# Places the days of the week on the top of the calender
for nameNumber in range(len(dayNames)):
names = tkinter.Label(calendarFrame, text = dayNames[nameNumber], fg = "black")
names.grid(column = nameNumber, row = 1, sticky = 'nsew')
index = 0
day = 1
for row in range(6):
for column in range(7):
if index >= startDate and index <= startDate + numberOfDays-1:
# Creates a frame that will hold each day and text box
dayFrame = tkinter.Frame(calendarFrame)
# Creates a textbox inside the dayframe
t = tkinter.Text(dayFrame, width = 15, height = 5)
t.grid(row = 1)
# Adds the text object to the save dict
textObjectDict[day] = t
# Changes changes dayframe to be formated correctly
dayFrame.grid(row=row + 2, column=column, sticky = 'nsew')
dayFrame.columnconfigure(0, weight = 1)
dayNumber = tkinter.Label(dayFrame, text = day)
dayNumber.grid(row = 0)
day += 1
index += 1
# Creates the buttons to load and save JSON's
loadFrom = tkinter.Button(calendarFrame, text="load month from...", command = loadFromJSON)
saveToButton = tkinter.Button(calendarFrame, text="save month to...", command = saveToJSON)
# Places them below the calendar
loadFrom.grid(row = 8, column = 4)
saveToButton.grid(row = 8, column = 2)
def saveToJSON():
# Saves the raw text data from the text objects
for day in range(len(textObjectDict)):
saveDict[day] = textObjectDict[day + 1].get("1.0", "end - 1 chars")
# Asks the user for a file location and saves a JSON containg the text for each day.
fileLocation = filedialog.asksaveasfilename(initialdir = "/", title = "Save JSON to..")
if fileLocation != '':
with open(fileLocation, 'w') as jFile:
json.dump(saveDict, jFile)
def loadFromJSON():
# Asks the user for a JSON file to open
fileLocation = filedialog.askopenfilename(initialdir = "/", title = "Select a JSON to open")
if fileLocation != '':
f = open(fileLocation)
global saveDict
saveDict = json.load(f)
# Copies the saved text data to the current text objects
for day in range(len(textObjectDict)):
textObjectDict[day + 1].insert("1.0", saveDict[str(day)])
# Create function for calculating if it is a leap year
def isLeapYear(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
# Create function for calculating what day month starts
def dayMonthStarts(month, year):
# Get last two digits (default 21 for 2021)
lastTwoYear = year - 2000
# Integer division by 4
calculation = lastTwoYear // 4
# Add day of month (always 1)
calculation += 1
# Table for adding proper month key
if month == 1 or month == 10:
calculation += 1
elif month == 2 or month == 3 or month == 11:
calculation += 4
elif month == 5:
calculation += 2
elif month == 6:
calculation += 5
elif month == 8:
calculation += 3
elif month == 9 or month == 12:
calculation += 6
else:
calculation += 0
# Check if the year is a leap year
leapYear = isLeapYear(year)
# Subtract 1 if it is January or February of a leap year
if leapYear and (month == 1 or month == 2):
calculation -= 1
# Add century code (assume we are in 2000's)
calculation += 6
# Add last two digits to the caluclation
calculation += lastTwoYear
# Get number output based on calculation (Sunday = 1, Monday =2..... Saturday =0)
dayOfWeek = calculation % 7
return dayOfWeek
# Create function to figure out how many days are in a month
def daysInMonth (month, year):
# All months that have 31 days
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 12 or month == 10:
numberDays = 31
# All months that have 30 days
elif month == 4 or month == 6 or month == 9 or month == 11:
numberDays = 30
else:
# Check to see if leap year to determine how many days in Feb
leapYear = isLeapYear(year)
if leapYear:
numberDays = 29
else:
numberDays = 28
return numberDays
# Holds the raw text input for each day
saveDict = {}
# Holds the text objects on each day
textObjectDict = {}
# Creates the root window
window = tkinter.Tk()
window.title("Calender")
window.geometry("1000x800")
# Centers the calendar
window.columnconfigure(0, weight = 1)
# Creates frames from the main root window.
calendarFrame = tkinter.Frame(window)
# This makes the grid object appear
calendarFrame.grid()
today = date.today()
printMonthYear(month, year)
makeButtons()
monthGenerator(dayMonthStarts(month, year), daysInMonth(month, year))
window.mainloop()
|
"""Utility functions for multiprocessing cpu intensive map functions.
Example
-------
>>> from moonshot.utils import multiprocess as mp
>>> shared_arg_list = ("hello world", [1, 2], np.array([2, 1]))
>>> def func(x):
... return "{}! {} + {} * {} = {}".format(
... mp.SHARED_ARGS[0], mp.SHARED_ARGS[1], mp.SHARED_ARGS[2],
... x, np.asarray(mp.SHARED_ARGS[1]) + mp.SHARED_ARGS[2] * x)
>>> results = mp.multiprocess_map(func, range(4), *shared_arg_list)
>>> results
['hello world! [1, 2] + [2 1] * 0 = [1 2]',
'hello world! [1, 2] + [2 1] * 1 = [3 3]',
'hello world! [1, 2] + [2 1] * 2 = [5 4]',
'hello world! [1, 2] + [2 1] * 3 = [7 5]']
Author: Ryan Eloff
Contact: ryan.peter.eloff@gmail.com
Date: September 2019
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections.abc import Sequence
import multiprocessing as mp
# multiprocessing functions should access shared memory variables stored in
# global list multiprocess.SHARED_ARGS upon worker initialisation
SHARED_ARGS = None
def num_cpus():
return mp.cpu_count()
def init_worker(*shared_args_list):
"""Initialise worker with global shared memory arguments."""
global SHARED_ARGS
SHARED_ARGS = shared_args_list
def multiprocess_map(func, iterable, *worker_args, n_cores=None, mode="map", **pool_kwargs):
"""Multiprocess a function with shared memory arguments.
`mode`: one of "map", "imap" or "starmap"
TODO(rpeloff) notes on worker_args and global SHARED_ARGS
"""
results = []
with mp.Manager() as manager:
shared_args_proxy = None
if worker_args is not None:
shared_args_proxy = manager.list(worker_args)
with mp.Pool(processes=n_cores, initializer=init_worker,
initargs=shared_args_proxy, **pool_kwargs) as pool:
if mode == "map":
results = pool.map(func, iterable)
elif mode == "starmap":
results = pool.starmap(func, iterable)
elif mode == "imap":
for result in pool.imap(func, iterable):
results.append(result)
return results
|
#!/bin/python3
import math
import os
import random
import re
import sys
def binary_search(arr,V):
s = 0
e = len(arr)-1
while(s<=e):
mid = (s+e)//2
if arr[mid] < V:
s = mid + 1
elif arr[mid] > V:
e = mid - 1
else:
return mid
# Complete the introTutorial function below.
def introTutorial(V, arr):
return binary_search(arr,V)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
V = int(input())
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = introTutorial(V, arr)
fptr.write(str(result) + '\n')
fptr.close()
|
import os
def diagonalDifference(arr):
m = len(arr)
sum_1 = 0
sum_2 = 0
for i in range(m):
sum_1 += arr[i][i]
sum_2 += arr[n-i-1][i]
return abs(sum_1-sum_2)
# Write your code here
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
class Student:
def __int__(self,name,rollno,marks):
print('Creating instance variables and performing initialization...')
self.name=name
self.rollno=rollno
self.marks=marks
s1=Student('Ram',101,90)
s2=Student('Sita',102,95)
print(s1.name.s1.rollno,s1.marks)
print(s2.name.s2.rollno,s2.marks)
|
l=[1,2,3,4,5]
def squareIt(n):
return n*n
l1=list(map(squareIt,l))
print(l1) |
d={100:'A',200:'B ',300:'C',400:'D'}
value=input('Enter value to find key:')
available=False
for k,v in d.items():
if v==value:
print('The corresponding key',k)
available=True
if available==False:
print('The specified value not found in dict')
|
def fact(n):
print('Executing Factorial Function with n value:',n)
if n==0:
result=1
else:
result=n*fact(n-1)
print('Returning Result of fact({}) is {}'.format(n,result))
return result
print(fact(3))
|
a=888
b=999
def add(x,y) :
print('performing add operation...')
print('The sum:' ,x+y)
def product(x,y) :
print('performing multiplication operation...')
print('The product:' ,x*y)
|
mail=input('Enter your mail id:')
try:
i=mail.index('@')
print('mail id contains @ symbol, which is mandatory')
except ValueError:
print('mail id does not contain @ symbol') |
from abc import abstractmethod,ABC
class Vehicle(ABC):
@abstractmethod
def getNoofWheels(self):pass
class Bus(Vehicle):
def getNoofWheels(self):
return 6
class Auto(Vehicle):
def getNoofWheels(self):
return 3
b=Bus()
print(b.getNoofWheels())
a=Auto()
print(a.getNoofWheels()) |
class P:
def m1(self):
print('Parent Method')
class C1(P):
def m2(self):
print('Child1 Method')
class C2(P):
def m3(self):
print('Child2 Method')
c1=C1()
c1.m1()
c1.m2()
c2=C2()
c2.m1()
c2.m3() |
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) <= 2:
return True
return self.isPalindrome(s)
def isPalindrome(self, s, can_recure=True):
left = 0
right = len(s) - 1
while left <= right:
if s[left] != s[right]:
if can_recure:
return self.isPalindrome(s[left:right], can_recure=False) or self.isPalindrome(s[left+1:right+1], can_recure=False)
else:
return False
left += 1
right -= 1
return True
# aaacbcaaaa |
#!/usr/bin/python
"""
This script serves as the entry point for a simple sorting program
"""
import argparse
import sys
from algorithms import sort_fns
from algorithms import url_validation_fns
def main():
parser = argparse.ArgumentParser(description='Simple sort program')
parser.add_argument('-i', metavar='in-file', required=True,
type=argparse.FileType('r'),
help='input file of strings to sort, one per line')
parser.add_argument('-o', metavar='out-file', required=True,
type=argparse.FileType('w'),
help='output file for sorted strings, one per line')
# Create URL validation options
# Get available functions to use for url validation choices
# from the list of functions defined in __init__.py
#
url_validation_choices = tuple(url_validation_fns.keys())
# Set a default URL validation function
#
if 'all' in url_validation_fns:
default_url_validation_choice = 'all'
else:
default_url_validation_choice = url_validation_choices[0]
# Add command line argument options to parser
parser.add_argument('--validate-fn', dest='validate_fn',
choices=url_validation_choices,
default=default_url_validation_choice,
help='enable url validation type.')
# Get available sort functions to use for argument choices
choices = tuple(sort_fns.keys())
if 'selectionsort' in sort_fns:
default = 'selectionsort'
else:
default = choices[0]
parser.add_argument('--sort-fn', dest='sort_fn', choices=choices,
default=default,
help='sort function to use')
# Read parsed arguments
results = parser.parse_args()
infile = results.i
outfile = results.o
sort_fn = results.sort_fn
url_validate_fn = results.validate_fn
# read lines
try:
lines = infile.readlines()
except IOError, e:
parser.error(str(e))
finally:
infile.close()
infile = None
# argument parser guarantees a valid choice for url_validate_fn
lines = _validate(lines, url_validation_fns[url_validate_fn])
# argument parser guarantees a valid choice for sort_fn
lines = _sort(lines, sort_fns[sort_fn])
# write output
try:
for line in lines:
outfile.write(line)
except IOError, e:
parser.error(str(e))
finally:
outfile.close()
outfile = None
sys.exit(0)
def _validate(url_list, url_validation_fn):
"""Returns a validated copy of URLs list"""
validated_url = list(url_list)
url_validation_fn(validated_url)
## See url_validation.py for adding implementations for
## various validation functions
return validated_url
def _sort(str_list, sort_fn):
"""Return a sorted copy of str_list, using functionsort_fn"""
copy = list(str_list)
sort_fn(copy)
return copy
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.