text stringlengths 37 1.41M |
|---|
i = 10
while i>0 :
print('*' * i)
i=i-1
print('Down') |
name = input('Please set up your name: ')
namelen=len(name)
if namelen < 3:
print('name mast be at least 3 characters')
elif namelen >50:
print('name mast be a maxmum of 50 characters')
else :
print("It's a good name!") |
#print("Hello World")
#print(5+5)
'''Rules for creating variables'''
# 1. Variable should start with a letter or an underscore
# 2. Variable cannot start with a number
# 3. It can only contain alpha numeric characters
# 4. Variable names are case sensitive (e.g Yousuf and yousuf are two difference variables)
#a = 3
#b = "Yousuf"
#c = 23.3
#print (a + c)
#print (type(a))
#print (type(b))
#print (type(c))
#typeA = type(a)
#typeB = type(b)
#print(typeA,typeB)
#name = '''Amir
#is a good boy'''
#name = "Yousuf"
#var = name.upper()
#var = name.replace("u", "l")
#print(name[2:5])
#print(var)
#print(len(name))
'''
name1 = "Salim"
name2 = "Kashif"
template = "This is a {1} and he is a good boy named {0}". format (name1, name2)
print(template)
'''
#Turte move program
'''import turtle
my_turtle = turtle.Turtle()
def square(length,angle):
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
for i in range(10):
square(100, 90)'''
'''my_turtle = turtle.Turtle()
def circle(length,angle):
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
my_turtle.left(angle)
my_turtle.forward(length)
for i in range(50):
circle(70, 45)
'''
'''
full_name = 'John Smith'
age = 20
is_new = True
name = input('What is your name? ')
fav_color = input('What is your favourite color? ')
print (name + ' likes ' + fav_color)
'''
#Birth Year Program
''' birth_year = input ('Your Birth Year: ')
current_year = input ('Current Year: ')
print(int(current_year) - int(birth_year)) '''
#Pound to Kgs Program
''' weight_lbs = input('Weight (lbs): ')
weight_kg = int(weight_lbs) * 0.45
print(weight_kg) '''
#Three quote (''') also use to break lines
#email = '''Hi John,
#Here is our first email to you.
#Thank you,
#Support Team'''
#print(email)
# Slicing [#START:STOP:STEP]
'''course = 'Python for Beginners'
print(course)
print(course[0])
print(course[1])
print(course[-1])
print(course[-2])
print(course[0:3]) #Prints starts index 0 to 3 but exclude index 3, it prints upto index 2
print(course[1:]) #Print upto last index in variables
print(course[:5]) #If we not write start index then python will assume 0 is starting index
name = 'Yousuf'
print(name[1:-1])
'''
#Formated string
'''first = 'Yousuf'
last = 'Hanif'
message = first + ' [' + last + '] is a coder'
print(message)
msg = f'{first} [{last}] is a coder' #Foramted string
print(msg) '''
#
'''name = 'Muhammad Yousuf'
print(len(name))
print(name[::-1]) #Reverses name
print(name.upper())
print(name.find('Y'))
print(name.replace('Yousuf', 'Yousuf Hanif'))
'''
'''import math
x = 2.9
print(round(x))
'''
#IF STATEMENT
#1
'''
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day") #Second msg
#2
price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f"Down Payment: ${down_payment}")
#3
has_high_income = True
has_good_credit = False
if has_good_credit and has_high_income:
print('Eligible for loan')
if has_good_credit or has_high_income:
print('Eligible for loan')
has_good_credit = True
has_criminal_record = False
if has_good_credit and not has_criminal_record:
print('Eligible for loan')
#4
temperature = 40
if temperature >= 30:
print("It's a hot day")
else:
print("It's not a hot day")
#5
name = input("Enter Your Name: ")
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 10:
print("Name must be a maximum of 10 characters")
else:
print("Name looks good!")
'''
#Weight conversion lbs & kgs
'''
weight = int(input('Weight: '))
unit = input('(L)bs or (K)g: ')
if unit.upper() == "L":
converted = weight * 0.45
print(f"You are {converted} kilos")
else:
converted = weight / 0.45
print(f"You are {converted} pounds")
'''
#Loop
'''
i = 1
while i <= 10:
print( i)
i = i + 1
print("Done")
'''
#Guess number
'''secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count +=1
if guess == secret_number:
print('You won!')
break
else:
print('Sorry, you failed!')
'''
#Car game
'''
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if started:
print("Car is already started!")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("Car is already stopped!")
else:
started = False
print("Car stopped.")
elif command == "help":
print("""
start - to star the car
stop - to stop the car
quit - to quit
""")
elif command == "quit":
break
else:
print("Sorry, I don't understand that!")
'''
#print("Harry is \n good boy \t1") #Escape sequence charachters (\n used for new line & \t used for tab space)
#print(10 * "Yousuf\n")
'''Num1 = input("Enter first number: ")
Num2 = input("Enter second number: ")
print("Sum: ", int(Num1) + int(Num2))'''
'''
name = "Muhammad Yousuf".lower()
print(name.endswith("yousuf"))
print(name.count("m"))
print(name.find("yousuf"))
print(name.replace("yousuf","Yousuf Hanif"))'''
#List
'''grocery = ["Harpic", "vim bar", "deodran", "Bhindi", "Lollypop"] #List
print(grocery)
print(grocery[0])
numbers = [2, 7, 2, 4, 26, 27, 24, 12] #List
numbers[1] = 4 #List can changeable
numbers.sort() #to sort out numbers
numbers.reverse() #to reverser numbers
print(numbers)
print(numbers[3])
print(max(numbers))
numbers.append(9) #through append values add only in end of list
numbers.insert(2, 45) #Insert use for add value any where in list (1st write index no & second write values you want to add in bracket)
numbers.remove(27)
print(numbers)
numbers.pop() #last value remove throught pop
print(numbers)'''
#list can change (List should be make throught square bracket[])
#Tupple cannot change (Tuppe should be make throught paranthesis () )
#Tupple
'''nos = (1, 3, 5, 6, 4)
print(nos)
#nos[1] = 3 #tupple value cant change
noslist = list(nos) #Throught this method we can change tuple valuse
noslist[1] = 5
nos = tuple(noslist)
print(nos)
del nos #del keyword can delete the tuple completely
print(nos) #this will raise an error because the tuple no longer exists
''' |
arr = [1,2,3,4,5,6,7,9,10]
def first_non_consecutive(arr):
if not arr: return 0
for i, value in enumerate(arr[:-1]):
print value
if value + 1 != arr[i + 1]:
return arr[i + 1]
print first_non_consecutive(arr)
# arrayList = ['Apples','Banna','Orange']
# def testing(list):
# for index, value in enumerate(arrayList):
# print('index is %d and value is %s' %(index,value))
# testing(arrayList) |
class doubleEndedQueue:
def __init__(self):
self.limit = 6
self.front = None
self.rear = None
self.db_queue = []
def enq_front(self,ele):
if(self.front == 0):
print("Cannot insert at front")
else:
if(self.front == None and self.rear == None):
self.front = 0
self.rear=0
else:
self.front-=1
self.db_queue.insert(0,ele)
def deq_front(self):
if(self.front == None):
print("Queue underflow")
else:
print(self.db_queue.pop(0))
if(self.front ==0 and self.rear ==0):
self.front=self.rear=None
else:
self.front+=1
def enq_rear(self,ele):
if(self.rear == self.limit-1):
print("Cannot insert at rear")
elif(self.rear == None and self.front==None):
self.rear=0
self.front = 0
else:
self.rear+=1
self.db_queue.append(ele)
def deq_rear(self):
if(self.rear == None):
print("Cannot delete element")
else:
if(self.front==self.rear):
self.front = None
self.rear= None
else:
print(self.db_queue.pop())
self.rear-=1
def display(self):
if(len(self.db_queue)==0):
print("Queue empty")
for i in self.db_queue:
print(i,end=" ")
db = doubleEndedQueue()
db.enq_rear(6)
db.display()
db.enq_front(7)
db.display()
db.enq_front(8)
db.display()
db.deq_front()
db.display()
db.deq_rear()
db.display()
|
# Write a function that take in an array of integers, and an integer representing a target sum.
# The function should return all the triplets that sum up to the target sum
def three_number_sum(array, targetSum):
array.sort()
triplets = []
for i in range(len(array) - 2):
left = i + 1
right = len(array) - 1
while left < right:
currentSum = array[i] + array[left] + array[right]
if currentSum == targetSum:
triplets.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif currentSum < targetSum:
left += 1
elif currentSum > targetSum:
right -= 1
return triplets
print(three_number_sum([12,3,1,2,-6,5,-8,6],0))
# The key here is to sort the array and traverse it once. At each number, place a left pointer immediately to the right of the current number, and a right point on the final number in the array.
|
class LinkedList:
def __init__(self, head=None):
self.head = head
def prepend(self, value):
# head # head
# \ # \
# \ # \
# [23]->[12]->null # [4]->[23]->[12]->null
self.head = Node(value=value, next=self.head)
def append(self, value):
# head # head
# \ # \
# \ # \
# [23]->[12]->null # [23]->[12]->[4]->null
node = self.head
while node.next:
node = node.next
node.next = Node(value=value)
def __repr__(self):
node = self.head
nodes = []
while node:
nodes.append(repr(node))
node = node.next
return '[' + ', '.join(nodes) + ']'
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return repr(self.value)
firstNode = Node(23)
ll = LinkedList(firstNode)
ll.append(Node(44))
ll.append(Node(54))
print(repr(ll))
|
# An XOR linked list is a more memory efficient doubly linked list.
# Instead of each node holding next and prev fields,
# it holds a field named both, which is an XOR of the next node and the previous node.
# Implement an XOR linked list;
# it has an add(element) which adds the element to the end,
# and a get(index) which returns the node at index.
# If using a language that has no pointers (such as Python),
# you can assume you have access to get_pointer and dereference_pointer functions that
# converts between nodes and memory addresses.
# For the head, both will just be the address of next,
# and if it's the tail, it should just be the address of prev.
import ctypes
class Node(object):
def __init__(self, val):
self.val = val
self.both = 0
class XorLinkedList(object):
def __init__(self):
self.head = self.tail = None
self.__nodes = [] # This is to prevent garbage collection in python
def add(self, node):
if self.head is None:
self.head = self.tail = node
else:
self.tail.both = id(node) ^ self.tail.both
node.both = id(self.tail)
self.tail = node
# Without this line, Python thinks there is no way to reach nodes between
# head and tail.
self.__nodes.append(node)
def get(self, index):
prev_id = 0
node = self.head
for i in range(index):
next_id = prev_id ^ node.both
if next_id:
prev_id = id(node)
node = _get_obj(next_id)
else:
raise IndexError('Linked list index out of range')
return node
# this just allows you to pass the memory id and get the value at that address returned
def _get_obj(id):
return ctypes.cast(id, ctypes.py_object).value
|
# given a list of positive integers, what is the largest sum of non-adjacent items?
# 1 - inefficient recursive solution (maybe 2^n time)
def maxSubsetSumNoAdjacent(lst, idx=0):
# for every number I can either take it, OR the next one. I want to use DP to find the max up to that point.
if idx >= len(lst):
return 0
largest = max(lst[idx] + maxSubsetSumNoAdjacent(lst, idx+2), maxSubsetSumNoAdjacent(lst, idx+1))
return largest
# 2 - Better solution (n time and space)
def maxSubsetSumNoAdjacent(lst):
# for every number I can either take it, OR the next one. I want to use DP to find the max up to that point.
if len(lst) == 0:
return 0
if len(lst) == 1:
return lst[0]
dp = [0]*(len(lst))
dp[0] = lst[0]
dp[1] = max(lst[0], lst[1])
for i in range(2, len(lst)):
# max is either...
# the max up to the one before last plus current
# OR the max up to the last one
dp[i] = max(dp[i-2]+lst[i], dp[i-1])
return dp[-1]
# 3 - Even better - we don't need the whole dp array, just the previous two numbers
def maxSubsetSumNoAdjacent(lst):
# for every number I can either take it, OR the next one. I want to use DP to find the max up to that point.
if len(lst) == 0:
return 0
if len(lst) == 1:
return lst[0]
dp = [lst[0], max(lst[0], lst[1])]
for i in range(2, len(lst)):
# max is either...
# the max up to the one before last plus current
# OR the max up to the last one
curr_largest = max(dp[0]+lst[i], dp[1])
dp[0] = dp[1]
dp[1] = curr_largest
return dp[-1]
maxSubsetSumNoAdjacent([75,105,120,75,90,135])
|
def find_longest_word(lword:list):
length_value = []
for i in lword:
length_value.append(len(i))
length_value.sort()
for i in lword:
if max(length_value)==len(i):
return i
return "There are two or more elements with equal amount of characters"
print(find_longest_word(["hello","hieee","xdo"]))
|
def make_forming(verb:str):
special = ["be","see","flee","knee"]
consonant = "bcdfghjklmnpqrstvwxyz"
vowel = "aiueo"
if verb[-2:] == "ie":
verb = verb[:-2] + "ying"
return verb
if verb[-1] == "e" and verb not in special:
verb = verb[:-1] + "ing"
return verb
if consonant.find(verb[-3]) != -1:
if vowel.find(verb[-2]) != -1:
if consonant.find(verb[-1]) != -1:
verb = verb + verb[-1] + "ing"
return verb
return verb+"ing"
print(make_forming("fhloc"))
|
import os
from InputCreation.TestImage import TestImage
class TestImagePair:
''' TestImagePair holds two TestImage objects-- TestImage member 'BEFORE' as \
the logical first TestImage, and TestImage member 'AFTER' as the logical \
second TestImage
`This class operates at the Test Image level`
Optical Flow usually operates on just two images at a time, one image at
time 't' and another image at 't+1' so the goal of TestImagePairs
is to make accessing these sequential images easy. The idea is that
one Optical Flow Operation will only interact with one TestImagePair
at a time.
'''
storageDelimiter='#separator#' # Used to separate TestImage paths when storing in a text file
def __init__(self, before, after):
''' constructor: Takes two input TestImage objects and stores them
as a TestImagePair.
:param before: The TestImage that is logically before the AFTER TestImage
:type before: TestImage
:param after: The TestImage that is logically after the BEFORE TestImage
:type after: TestImage
'''
self.BEFORE=before
self.AFTER=after
def asStorageString(self, delimiterString=storageDelimiter, long=True):
''' asStorageString() generates a string to best store the contents of \
the TestImagePair.
TestImagePairs can be generated from only two TestImages and TestImages
can be generated from just an absolute path to the image file so we
will store TestImagePairs as two absolute paths in one line separated
by a delimiter
'''
#storageString=self.BEFORE.IMAGE_PATH+delimiter+self.AFTER.IMAGE_PATH
if long:
storageString=self.BEFORE.IMAGE_PATH+delimiterString+self.AFTER.IMAGE_PATH
else:
collectionName=self.BEFORE.IMAGE_PARENT
frame_a=self.BEFORE.IMAGE_NAME
frame_b=self.AFTER.IMAGE_NAME
storageString=collectionName+'/'+frame_a+delimiterString+frame_b
return storageString
# End TestImagePair
|
for i in range(1, 13):
print("{0:2} -> {1:^3} -> {2:4}".format(i, i ** 2, i ** 3))
print()
print("-" * 50)
print()
pi = 22 / 7
print("pi is {0}".format(pi))
print("pi is {0:<12f}|".format(pi))
print("pi is {0:<12.50f}|".format(pi))
print("pi is {0:<12.2f}|".format(pi))
print("pi is {0:52.50f}|".format(pi))
print("pi is {0:62.50f}|".format(pi))
print("pi is {0:72.50f}|".format(pi))
# para rellenar con ceros los espacios
print("pi is {0:<72.72f}|".format(pi))
|
import os
# Função que verifica todas as possibilidades de vencedor e retorna se venceu ou não
def verificaCampeao(tabuleiro, simbolo):
if tabuleiro[0] == simbolo and tabuleiro[1] == simbolo and tabuleiro[2] == simbolo:
return simbolo
elif tabuleiro[3] == simbolo and tabuleiro[4] == simbolo and tabuleiro[5] == simbolo:
return simbolo
elif tabuleiro[6] == simbolo and tabuleiro[7] == simbolo and tabuleiro[8] == simbolo:
return simbolo
elif tabuleiro[0] == simbolo and tabuleiro[3] == simbolo and tabuleiro[6] == simbolo:
return simbolo
elif tabuleiro[1] == simbolo and tabuleiro[4] == simbolo and tabuleiro[7] == simbolo:
return simbolo
elif tabuleiro[2] == simbolo and tabuleiro[5] == simbolo and tabuleiro[8] == simbolo:
return simbolo
elif tabuleiro[0] == simbolo and tabuleiro[4] == simbolo and tabuleiro[8] == simbolo:
return simbolo
elif tabuleiro[2] == simbolo and tabuleiro[4] == simbolo and tabuleiro[6] == simbolo:
return simbolo
else:
return None
# Função para exibir o tabuleiro de exemplo e o tabuleiro de jogo
def imprimiTabuleiro(tabuleiro, simboloHumano, simboloIa):
print("Humano = " + simboloHumano)
print("Inteligencia Artificial = " + simboloIa + "\n")
print(" Jogo\t\t Posições do tabuleiro")
print(str(tabuleiro[0])+" | "+str(tabuleiro[1])+" | "+str(tabuleiro[2]) + "\t\t1 | 2 | 3")
print("--+---+--\t\t--+---+--")
print(str(tabuleiro[3])+" | "+str(tabuleiro[4]) +
" | "+str(tabuleiro[5]) + "\t\t4 | 5 | 6")
print("--+---+--\t\t--+---+--")
print(str(tabuleiro[6])+" | "+str(tabuleiro[7]) +
" | "+str(tabuleiro[8]) + "\t\t7 | 8 | 9")
# Função para pegar a posição da jogada do humano, e verificar se ela é válida, e retorna a posição se ela for válida
def validaPosicao(tabuleiro):
posicao = int(input("\nQual posição deseja jogar ? "))
while (posicao < 1 or posicao > 9) and tabuleiro != ".":
posicao = int(input("\nQual posição deseja jogar ? "))
return posicao-1
# Função para verificar se ocorreu empate no jogo
def verificaEmpate(tabuleiro, simboloHumano, simboloIa):
if not "." in tabuleiro:
os.system('clear')
print("EMPATE\n\n")
imprimiTabuleiro(tabuleiro, simboloHumano, simboloIa)
return True
|
myVar = input("What is your answer to my 1st question? (yes/no) ")
if myVar == "yes":
myNextVar = input("What is your answer to my 2nd question? (yes/no) ")
if myNextVar == "yes":
[another 1st "then" clause]
elif myNextVar == "no":
[another 2nd "then" clause]
else:
print("Answer my question! You didn't type yes or no.")
elif myVar == "no":
[our 2nd "then" clause here]
else:
print("Answer my question! You didn't type yes or no.")
|
class Player:
def __init__(self, name, startingRoom, startingItems=[]):
self.name = name
self.currentRoom = startingRoom
self.items = startingItems
def travel(self, direction):
nextRoom = self.currentRoom.getRoomInDirection(direction)
if nextRoom is not None:
self.currentRoom = nextRoom
nextRoom.printRoomDescription(self)
else:
print("You cannot move in that direction.")
def look(self, direction=None):
if direction is None:
self.currentRoom.printRoomDescription(self)
else:
nextRoom = self.currentRoom.getRoomInDirection(direction)
if nextRoom is not None:
nextRoom.printRoomDescription(self)
else:
print("There is nothing there.")
def printStatus(self):
print(f"Your name is {self.name}")
def printInventory(self):
print("You are carrying:\n")
for item in self.items:
print(f" {item.name} - {item.description}\n")
def addItem(self, item):
self.items.append(item)
def removeItem(self, item):
self.items.remove(item)
def findItemByName(self, name):
for item in self.items:
if item.name.lower() == name.lower():
return item
return None
def dropItem(self, itemName):
itemToDrop = self.findItemByName(" ".join(itemName))
if itemToDrop is not None:
self.removeItem(itemToDrop)
self.currentRoom.addItem(itemToDrop)
itemToDrop.on_drop()
else:
print("You are not holding that item.")
|
#List-6
#Dylan and Avi
#12/13/17
def main():
print "You will be asked for a string and the number of non-space characters will be displayed."
string = raw_input("Enter a string: ")
count = len(string)
countSpace = 0
for i in string:
if i == " ":
countSpace += 1
countNon = count - countSpace
print "The numer of non-space characters is:", countNon
main()
|
"""
https://adventofcode.com/2018/day/2
"""
from collections import Counter
from itertools import product
from pathlib import Path
def solve_a(codes):
pairs = triplets = 0
for code in codes:
occurrences = Counter(code).values()
pairs += any(count == 2 for count in occurrences)
triplets += any(count == 3 for count in occurrences)
return pairs * triplets
def solve_b(codes):
for code_a, code_b in product(codes, codes):
diff = sum(c != c2 for c, c2 in zip(code_a, code_b))
if diff == 1:
common = ''.join(c for c, c2 in zip(code_a, code_b) if c == c2)
return common
if __name__ == '__main__':
assert 12 == solve_a([
'abcdef',
'bababc',
'abbcde',
'abcccd',
'aabcdd',
'abcdee',
'ababab',
])
assert 'fgij' == solve_b([
'abcde',
'fghij',
'klmno',
'pqrst',
'fguij',
'axcye',
'wvxyz',
])
codes = Path('day02.txt').read_text().strip().splitlines()
print('A:', solve_a(codes))
print('B:', solve_b(codes))
|
from __future__ import annotations
import sys
from typing import Iterable, Iterator
class Reader:
"""This class provides methods for reading strings, numbers and
boolean from file inputs and standard input.
"""
def __init__(self, stream: Iterable[str]):
self._stream = stream
@classmethod
def from_file(cls, file: str) -> Reader:
return cls(open(file, "rt"))
@classmethod
def from_stdin(cls) -> Reader:
return cls(sys.stdin)
def read_as_bool(self) -> Iterator[bool]:
yield from (bool(item) for item in self._read())
def read_as_float(self) -> Iterator[float]:
yield from (float(item) for item in self._read())
def read_as_int(self) -> Iterator[int]:
yield from (int(item) for item in self._read())
def read_as_strings(self) -> Iterator[str]:
yield from (item for item in self._read())
def _read(self) -> Iterator[str]:
for line in self._stream:
yield line
|
# #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on August 11, 2021
# Last edited on August 22, 2021
# Runs the tic-tac-toe game
import os
import sys
import random
def screen_clear():
# for mac and linux(here, os.name is 'posix')
if os.name == 'posix':
_ = os.system('clear')
else:
# for windows platfrom
_ = os.system('cls')
def game_startup():
# Function for startup
game_state = False
screen_clear()
print("Welcome to Malcolm's Tic-Tac-Toe game!")
start_var = (input("Press b for intructions\nPress a to start "))
if start_var == "a":
main()
elif start_var == "b":
intructions()
screen_clear()
return game_state
def game_terminatation(game, team):
# Function for ending the game
screen_clear()
print("Game Over!")
if game == 0:
print("{}'s Wins!".format(team))
if game == 1:
print("No contest")
end_var = (input("Press a to restart\nPress b to exit "))
if end_var == "a":
game_startup()
if end_var == "b":
sys.exit()
else:
print("Unknown input")
game_terminatation(team)
def intructions():
# Function for intructions
screen_clear()
print("To start your turn, enter a location from 1-9: ")
print("1|2|3\n4|5|6\n7|8|9")
return_key = (input("Press any button to return to the home screen "))
screen_clear()
main()
def grid_creation():
# Function for grid generation
row_list = []
start_state = " "
for row_number in range(0, 3):
row = []
row_list.append(row)
for column_number in range(0, 3):
row.append(start_state)
for row in row_list:
print("|".join(row))
return row_list
def game_logic(row_list, player_slot, team):
# Function for the tic-tac-toe game logic
player_slot -= 1
game = -1
row1 = row_list[0]
row2 = row_list[1]
row3 = row_list[2]
slot1 = row1[0]
slot2 = row1[1]
slot3 = row1[2]
slot4 = row2[0]
slot5 = row2[1]
slot6 = row2[2]
slot7 = row3[0]
slot8 = row3[1]
slot9 = row3[2]
slot_list = []
slot_list.append(slot1)
slot_list.append(slot2)
slot_list.append(slot3)
slot_list.append(slot4)
slot_list.append(slot5)
slot_list.append(slot6)
slot_list.append(slot7)
slot_list.append(slot8)
slot_list.append(slot9)
slot_list[player_slot] = team
column1 = [slot_list[0], slot_list[1], slot_list[2]]
column2 = [slot_list[3], slot_list[4], slot_list[5]]
column3 = [slot_list[6], slot_list[7], slot_list[8]]
row_1 = [slot_list[0], slot_list[3], slot_list[6]]
row_2 = [slot_list[1], slot_list[4], slot_list[7]]
row_3 = [slot_list[2], slot_list[5], slot_list[8]]
diagonal1 = [slot_list[0], slot_list[4], slot_list[8]]
diagonal2 = [slot_list[2], slot_list[4], slot_list[6]]
if column1.count("x") > 2:
game = 0
if column1.count("0") > 2:
game = 0
if column2.count("x") > 2:
game = 0
if column2.count("0") > 2:
game = 0
if column3.count("x") > 2:
game = 0
if column3.count("0") > 2:
game = 0
if row_1.count("x") > 2:
game = 0
if row_1.count("0") > 2:
game = 0
if row_2.count("x") > 2:
game = 0
if row_2.count("0") > 2:
game = 0
if row_3.count("x") > 2:
game = 0
if row_3.count("0") > 2:
game = 0
if diagonal1.count("x") > 2:
game = 0
if diagonal1.count("0") > 2:
game = 0
if diagonal2.count("x") > 2:
game = 0
if diagonal2.count("0") > 2:
game = 0
if slot_list.count(" ") == 0:
game = 1
if game > -1:
game_terminatation(game, team)
return slot_list
def grid_changes(slot_list):
# Function for changes to the original grid based on game logic
counter = -1
new_list = []
for row_number in range(0, 3):
row = []
new_list.append(row)
for column_number in range(0, 3):
counter = counter + 1
row.append(slot_list[counter])
for row in new_list:
print("|".join(row))
return new_list
def cpu_process(move_list, turn_counter, row_list, cpu_move_list):
# Function for cpu moves
# Figure this shit out holy fuck
while True:
cpu_win_cond = []
player_win_cond = []
last_move = []
defend = -1
win_cond = -1
move = 0
cpu_move = 0
slot_1_adj = (2, 4, 5)
slot_2_adj = (1, 3, 5)
slot_3_adj = (2, 5, 6)
slot_4_adj = (1, 5, 7)
slot_5_adj = (1, 2, 3, 4, 6, 7, 8, 9)
slot_6_adj = (3, 5, 9)
slot_7_adj = (4, 5, 8)
slot_8_adj = (5, 7, 9)
slot_9_adj = (5, 6, 8)
slot_adjs = []
slot_adjs.append(slot_1_adj)
slot_adjs.append(slot_2_adj)
slot_adjs.append(slot_3_adj)
slot_adjs.append(slot_4_adj)
slot_adjs.append(slot_5_adj)
slot_adjs.append(slot_6_adj)
slot_adjs.append(slot_7_adj)
slot_adjs.append(slot_8_adj)
slot_adjs.append(slot_9_adj)
row1 = row_list[0]
row2 = row_list[1]
row3 = row_list[2]
slot1 = row1[0]
slot2 = row1[1]
slot3 = row1[2]
slot4 = row2[0]
slot5 = row2[1]
slot6 = row2[2]
slot7 = row3[0]
slot8 = row3[1]
slot9 = row3[2]
slot_list = []
slot_list.append(slot1)
slot_list.append(slot2)
slot_list.append(slot3)
slot_list.append(slot4)
slot_list.append(slot5)
slot_list.append(slot6)
slot_list.append(slot7)
slot_list.append(slot8)
slot_list.append(slot9)
column1 = [slot_list[0], slot_list[1], slot_list[2]]
column2 = [slot_list[3], slot_list[4], slot_list[5]]
column3 = [slot_list[6], slot_list[7], slot_list[8]]
row_1 = [slot_list[0], slot_list[3], slot_list[6]]
row_2 = [slot_list[1], slot_list[4], slot_list[7]]
row_3 = [slot_list[2], slot_list[5], slot_list[8]]
diagonal1 = [slot_list[0], slot_list[4], slot_list[8]]
diagonal2 = [slot_list[2], slot_list[4], slot_list[6]]
# If statements for win options
if column1.count("0") == 2:
if column1.count(" ") == 1:
win_cond = 0
cpu_win_cond.append(column1)
if column2.count("0") == 2:
if column2.count(" ") == 1:
win_cond = 1
cpu_win_cond.append(column2)
if column3.count("0") == 2:
if column3.count(" ") == 1:
win_cond = 2
cpu_win_cond.append(column3)
if row_1.count("0") == 2:
if row_1.count(" ") == 1:
win_cond = 3
cpu_win_cond.append(row_1)
if row_2.count("0") == 2:
if row_2.count(" ") == 1:
win_cond = 4
cpu_win_cond.append(row_2)
if row_3.count("0") == 2:
if row_3.count(" ") == 1:
win_cond = 5
cpu_win_cond.append(row_3)
if diagonal1.count("0") == 2:
if diagonal1.count(" ") == 1:
win_cond = 6
cpu_win_cond.append(diagonal1)
if diagonal2.count("0") == 2:
if diagonal2.count(" ") == 1:
win_cond = 7
cpu_win_cond.append(diagonal2)
# If statements for defend options
if column1.count("x") == 2:
if column1.count(" ") == 1:
defend = 0
player_win_cond.append(column1)
if column2.count("x") == 2:
if column2.count(" ") == 1:
defend = 1
player_win_cond.append(column2)
if column3.count("x") == 2:
if column3.count(" ") == 1:
defend = 2
player_win_cond.append(column3)
if row_1.count("x") == 2:
if row_1.count(" ") == 1:
defend = 3
player_win_cond.append(row_1)
if row_2.count("x") == 2:
if row_2.count(" ") == 1:
defend = 4
player_win_cond.append(row_2)
if row_3.count("x") == 2:
if row_3.count(" ") == 1:
defend = 5
player_win_cond.append(row_3)
if diagonal1.count("x") == 2:
if diagonal1.count(" ") == 1:
defend = 6
player_win_cond.append(diagonal1)
if diagonal2.count("x") == 2:
if diagonal2.count(" ") == 1:
defend = 7
player_win_cond.append(diagonal2)
if turn_counter == 2:
if 5 == move_list[0]:
move = random.randint(1, 9)
else:
move = 5
if turn_counter >= 4:
adj_check = True
last_move = cpu_move_list[0] - 1
last_move_adj = slot_adjs[last_move]
for var1 in move_list:
for var2 in last_move_adj:
if var2 == var1:
adj_check = False
break
break
for var1 in cpu_move_list:
for var2 in last_move_adj:
if var2 == var1:
adj_check = False
break
break
if win_cond >= 0:
if win_cond == 0:
win_slot = cpu_win_cond[0]
loop_counter = 1
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 1
if win_cond == 1:
win_slot = cpu_win_cond[0]
loop_counter = 4
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 1
if win_cond == 2:
win_slot = cpu_win_cond[0]
loop_counter = 7
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 1
if win_cond == 3:
win_slot = cpu_win_cond[0]
loop_counter = 1
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 3
if win_cond == 4:
win_slot = cpu_win_cond[0]
loop_counter = 2
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 3
if win_cond == 5:
win_slot = cpu_win_cond[0]
loop_counter = 3
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 3
if win_cond == 6:
win_slot = cpu_win_cond[0]
loop_counter = 1
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 4
if win_cond == 7:
win_slot = cpu_win_cond[0]
loop_counter = 3
for var in win_slot:
if var == " ":
move = loop_counter
break
loop_counter += 2
elif defend >= 0:
if defend == 0:
def_cond = player_win_cond[0]
loop_counter = 1
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 1
if defend == 1:
def_cond = player_win_cond[0]
loop_counter = 4
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 1
if defend == 2:
def_cond = player_win_cond[0]
loop_counter = 7
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 1
if defend == 3:
def_cond = player_win_cond[0]
loop_counter = 1
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 3
if defend == 4:
def_cond = player_win_cond[0]
loop_counter = 2
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 3
if defend == 5:
def_cond = player_win_cond[0]
loop_counter = 3
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 3
if defend == 6:
def_cond = player_win_cond[0]
loop_counter = 1
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 4
if defend == 7:
def_cond = player_win_cond[0]
loop_counter = 3
for var in def_cond:
if var == " ":
move = loop_counter
break
loop_counter += 2
elif adj_check == True:
last_move = move_list[0] - 1
last_move_adj = slot_adjs[last_move]
move = random.choice(last_move_adj)
else:
move = random.randint(1,9)
return move
def main():
# Function for UI
game_mode = input("Press a for a player vs player match\nPress b for player vs Ai match: ")
if game_mode == "a":
game_mode = 0
elif game_mode == "b":
game_mode = 1
else:
print("Unknown input")
main()
turn_counter = 1
users_moves = []
slot_location = 0
cpu_move_list = []
move_list = []
row_list = grid_creation()
while True:
slot_check = True
if game_mode == 0:
# Section for pvp game
if (turn_counter % 2) == 0:
print("Player 2's turn")
team = "0"
else:
print("Player 1's turn")
team = "x"
player_slot_location = (input("Which box?: "))
try:
slot_location = int(player_slot_location)
try:
slot_location in range(0, 9)
users_moves.append(slot_location)
if users_moves.count(slot_location) > 1:
print("That spot is taken, choose another location")
continue
slot_list = game_logic(row_list, slot_location, team)
row_list = grid_changes(slot_list)
turn_counter += 1
except Exception:
print("{} is not a number from 1-9".format(slot_location))
continue
except Exception:
print("{} is not an integer".format(player_slot_location))
continue
if game_mode == 1:
# Section for pvCPU game
if (turn_counter % 2) == 1:
print("Player 1's turn")
team = "x"
player_slot_location = (input("Which box?: "))
try:
slot_location = int(player_slot_location)
try:
slot_location in range(0, 9)
for var in move_list:
if slot_location == var:
slot_check = False
break
for var in cpu_move_list:
if slot_location == var:
slot_check = False
break
if slot_check == False:
print("You cannot move there")
continue
move_list.append(slot_location)
slot_list = game_logic(row_list, slot_location, team)
row_list = grid_changes(slot_list)
turn_counter += 1
except Exception:
print("{} is not a number from 1-9")
continue
except Exception:
print("{} is not an integer".format(player_slot_location))
continue
else:
print("CPU's Turn")
team = "0"
while True:
slot_check = True
cpu_location = cpu_process(move_list, turn_counter, row_list, cpu_move_list)
cpu_move_list.append(cpu_location)
if cpu_location == slot_location:
continue
for var in move_list:
if cpu_location == var:
slot_check = True
else:
slot_check = False
else:
slot_check = False
if slot_check == False:
break
slot_list = game_logic(row_list, cpu_location, team)
row_list = grid_changes(slot_list)
turn_counter += 1
if __name__ == "__main__":
game_startup()
|
# Realice una FUNCIÓN en Python que calcule el índice de masa corporal de una persona y diga el estado en que se encuentre. Debe recibir los parámetros necesarios.
weightKg = int(input("Enter your weight in Kg (example 76): "))
heightM = float(input("Enter your height in meters (example 1.80):"))
def calculateIMC(weightKg, heightM):
imc = weightKg / pow(heightM, 2)
imc = round(imc, 2)
if imc < 18.5:
print(f"Your IMC is {imc} and your classification is insufficient")
if imc >= 18.5 and imc <= 24.9:
print(f"Your IMC is {imc} and your classification is normal")
if imc >= 25 and imc <= 26.9:
print(f"Your IMC is {imc} and your classification is overweight grade 1")
if imc >= 27 and imc <= 29.9:
print(f"Your IMC is {imc} and your classification is overweight grade 2 (pre-obesity)")
if imc >= 30 and imc <= 34.9:
print(f"Your IMC is {imc} and your classification is obesity type 1")
if imc >= 35 and imc <= 39.9:
print(f"Your IMC is {imc} and your classification is obesity type 2")
if imc >= 40 and imc <= 49.9:
print(f"Your IMC is {imc} and your classification is obesity type 3 (morbid)")
if imc > 50:
print(f"Your IMC is {imc} and your classification is obesity type 4")
return
calculateIMC(weightKg, heightM)
|
class FiguraGeometrica:
def __init__(self, ancho, alto):
self.__ancho = ancho
self.__alto = alto
def area(self):
return self.__alto * self.__ancho
#def get_ancho(self):
# return self.__ancho
#def set_ancho(self, ancho):
# self.__ancho = ancho
#def get_alto(self):
# return self.__alto
#def set_alto(self, alto):
# self.__alto = alto
#def __str__(self):
# return "el ancho es: " + str(self.__ancho) + "\nel alto es: " + str(self.__alto)
#figurageometrica = FiguraGeometrica(1, 2)
#print(figurageometrica)
|
class BinaryTree:
def __repr__(self):
return "Binary Tree, Key is " + self.key
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
if self.left_child == None:
self.left_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.left_child = self.left_child
self.left_child = t
def insert_right(self, new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.right_child = self.right_child
self.right_child = t
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self, obj):
self.key = obj
def get_root_val(self):
return self.key
def inorder(self, argu):
if self != None:
if self.get_left_child() != None:
if self.get_left_child().inorder(argu):
return True
if (self.get_root_val() == argu):
return True
if self.get_right_child() != None:
if self.get_right_child().inorder(argu):
return True
return False
root = BinaryTree("A")
root.insert_left("B")
root.insert_right("C")
b = root.get_left_child()
b.insert_left("D")
b.insert_right("E")
c = root.get_right_child()
c.insert_left("F")
c.insert_right("G")
argu = str(input("Enter Some One Alphabet : "))
root.inorder(argu)
if root.inorder(argu):
print("Found")
else:
print("Not Found")
"""for i in arr:
if alpha == "A":
print("True")
else:
print("False")"""
|
import sqlite3,hashlib,getpass
from password_strength import PasswordPolicy
def userCheck(username):
result= cur.execute("SELECT EXISTS(SELECT 1 FROM users WHERE username=?)",(username,)).fetchone()[0]
return result
def passwordPolicyCheck(password):
policy = PasswordPolicy.from_names(
length=8,
uppercase=2,
numbers=2,
special=2,
nonletters=2,
entropybits= 30,
)
Result = policy.test(password)
return Result
con = sqlite3.connect('file:./db/ppab6.db?mode=rw', uri=True)
cur = con.cursor()
username=input("Please enter your username: ")
userExists = userCheck(username)
while userExists:
username = input("The username you entered is already in use! Please type in another username. ")
userExists = userCheck(username)
else:
password=getpass.getpass(prompt="Please enter your password: ")
passwordPolicyCheckResult = passwordPolicyCheck(password)
while passwordPolicyCheckResult != []:
password=getpass.getpass(prompt=f"Your password does not satisfy the password policy criteria. Please create a password as per the following criteria: {passwordPolicyCheckResult}")
passwordPolicyCheckResult = passwordPolicyCheck(password)
else:
hashedPassword=hashlib.sha256(password.encode()).hexdigest()
cur.execute('''INSERT INTO users VALUES (?,?)''',(username,hashedPassword))
con.commit()
print(f"Your user has been created successfully {username}!")
con.close() |
import time
import os
def selection():
os.system('clear')
print("Selection Sort")
print("Masukkan array angka")
print('(pisahkan dengan koma)')
inp = input()
A = inp.split(',')
print("Array Awal : %s" % A)
start = time.time()
for i in range(len(A)):
min_idx = i
for j in range(len(A)):
min_idx= i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
temp = A[i]
A[i] = A[min_idx]
A[min_idx] = temp
print("#%i - %s" % (i,A))
end = time.time()
print("Array akhir : %s" % A)
print()
print("Selesai dalam %f detik" % (end - start))
input("Enter untuk melanjutkan)")
def bubble():
os.system('clear')
def bubblesort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
print('#%i-%i - %s" % (i, j, arr)')
print("Bubble Sort")
print("Masukkan array angka")
print('(pisahkan dengan koma)')
inp = input()
A = inp.split(',')
print("Bubble Sort")
print()
print("Array awal : %s" % A)
start = time.time()
bubblesort(A)
end = time.time()
print("Array akhir : %s" % A)
print()
print("Selesai dalam %f detik" % (end - start))
input("(Enter untuk melanjutkan)")
while True:
os.system('clear')
print("Pilih Algoritma Sorting")
print("1. Selection Sort")
print("2. Bubble Sort")
print("3. Exit")
pil = int(input("Masukkan pilihan : "))
if pil == 1 :
selection()
elif pil == 2 :
bubble()
elif pil == 3 :
exit()
else:
os.system('clear')
print("Pilihan salah...")
input("(Enter untuk melanjutkan)")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
An example of a Markov model that uses
a dictionary instead of a matrix, which
makes it more readable and easier to specify
"""
import numpy as np
def pick_random_element(prob):
"""
Parameters
----------
prob: {string: double}
A dictionary of all transition
probabilities from some state
we're in to all other states
Returns
-------
The next character, sampled according
to the probabilities
"""
keys = list(prob.keys())
probs = np.array(list(prob.values()))
probs = np.cumsum(probs)
r = np.random.rand()
idx = np.searchsorted(probs, r)
return keys[idx]
probs = {
'a':{'a':0.3,
'b':0.5,
'c':0.2
},
'b':{'b':0.9,
'c':0.1},
'c':{'a':0.5,
'd':0.5
},
'd':{'d':1}
}
state = 'a'
num_samples = 100
for i in range(num_samples):
print(state, end='')
state = pick_random_element(probs[state])
|
def square(nums):
results=[]
for num in nums:
yield(num ** 2)
mynums = (x**2 for x in [5,4,3,2,8])
print(mynums)
for num in mynums:
print(num) |
import math
def isPower(N):
sqrt = math.floor(math.sqrt(N))
for p in range(2,33):
for A in range(2, sqrt+1 ):
if A**p == N:
print(A,"**",p)
return True
return False
print(isPower(625)) |
# Python 2.7.13
#
# Author: Ryan Vinyard
#
# Purpose: The Tech Academy - Python Course, concept drill
# I've tried to model this script off of the nice/mean drill, to build good habits.
def start(name="", number=0, decimal=0, array=[]):
#This start function allows us to smoothly go from function to function as we pass the relevant information.
name = get_name(name)
number = get_number(name, number)
decimal = get_decimal(name, decimal)
array = short_list(name, array)
fun_facts(number,decimal, array)
def get_name(name):
#In this function we get the user's name, assign the string to a variable, and use .format to print it back.
name = raw_input("\nHello my dude! I want to play a game. The rules are simple. Just do everything I ask. First of all, what is your name? ").capitalize()
print("\n{}, what a great name!".format(name))
return name
def get_number(name, number):
#In this function we assign the user's number to a variable and start a while loop to make sure they give a relevant number.
stop = False
while stop == False:
try:
number = int(input(("\nAnother question, what is your favorite number? Don't get snarky and put in like 55.667 because I'll just make it a whole number. ")))
except NameError:
print("That's not a number")
continue
if number == 69 or number == 420:
# Using the or operator to make sure you're not a JUVENILE
print("No dude, we're not doing that. Give me literally any other number.")
elif number == 0:
print("That's 0, try again")
else:
print("\n{}, cool, neat-o, real nice number. The best number.".format(number))
stop = not stop
#This is a bit of a sloppy place to put the not operator.
#I just wanted to show that I understand that if stop is false, it will return true.
return number
def get_decimal(name, decimal):
#In this function we assign the user's float to decimal, because float is already an expression.
#We also use the and operator to make sure decimal is between 0 and 1.
#In addition, we have an if statement with elif and else to make the user keep inputting until they get it right.
stop = False
while stop == False:
try:
decimal = float(raw_input(("\nOk, this one's a bit silly, but give me a decimal number between 0 and 1 noninclusive. ")))
except ValueError:
print("Yo, that's not a sweet decimal number, try again")
continue
if decimal<1 and decimal>0:
print("\n{}, alright, I like that.".format(decimal))
stop = True
elif decimal>1:
print("That's too high, try something between 0 and 1")
else:
print("That's too low, try again")
return decimal
def short_list(name, array):
array = []
print("\nOk {}, I'm gonna ask you about some people you like.".format(name))
stop = False
while stop == False:
author = raw_input("\nCan you tell me an author you like, please? ").title()
array.append(author)
figure = raw_input("Now, can you tell me the name of someone who inspires you? ").title()
array.append(figure)
comedian = raw_input("Finally, who is a favorite comedian of yours? ").title()
array.append(comedian)
for i in array:
print(i)
answer = raw_input("Are these the people? Type yes if this is correct. ").capitalize()
if answer == 'Yes':
print("Well that's great, because I also like those people!")
stop = True
else:
print("Then let's try again.")
array = []
return array
def fun_facts(number, decimal, array):
#In this function we'll use all those math operators, +,-,*,/,+=,-, and %
#Then we'll take those answers and put them into a tuple, and iterate through it with a for loop
print("\nHey now, you remember those numbers you told me? {} and {}? Check this out, here's some fun facts: ".format(number,decimal))
print("\nDid you know that if you add {} and my favorite number, 17, you get {}?".format(number,(number+17)))
number += 17
answer1 = number
print("Then, if you subtract {} from {}, you get {}?".format(decimal,number,(number-decimal)))
new_number= number-decimal
answer2 = new_number
print("Now if you multiply that by your favorite decimal number, you get {}.".format(new_number*decimal))
new_number= new_number*decimal
answer3 = new_number
print("Now divide that by 2, and you get {} with a remainder of {}.".format(new_number/2,(new_number%2)))
answer4 = new_number/2
answer5 = new_number%2
tup = (answer1, answer2, answer3, answer4, answer5)
print("\nSo now we have these numbers:")
for i in tup:
print(i)
print("\nIt turns out, if you add all these numbers, you get {}".format(answer1+answer2+answer3+answer4+answer5))
print("As it just so happens, this is the exact favorite number of your favorite author...")
print("\nAnd that person's name is... {}!".format(array[0]))
print("\nThank you for indulging me for a bit in this fun exercise. Have a nice day!")
answer = raw_input("If you'd like to do this again, type again. Enter anything else to exit. ").lower()
if answer == 'again':
name=""
start(name,number,decimal,array)
else:
exit()
if __name__ == "__main__":
start()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 28 14:35:20 2021
@author: pablo
Problem
Given two strings s and t, t is a substring of s if t is contained as a contiguous
collection of symbols in s (as a result, t must be no longer than s).
The position of a symbol in a string is the total number of symbols found to its
left, including itself (e.g., the positions of all occurrences of 'U' in
"AUGCUUCAGAAAGGUCUUACG" are 2, 5, 6, 15, 17, and 18). The symbol at position i
of s is denoted by s[i].
A substring of s can be represented as s[j:k], where j and k represent the starting
and ending positions of the substring in s; for example, if s = "AUGCUUCAGAAAGGUCUUACG",
then s[2:5] = "UGCU".
The location of a substring s[j:k] is its beginning position j; note that t will
have multiple locations in s if it occurs more than once as a substring of s
(see the Sample below).
Given: Two DNA strings s and t (each of length at most 1 kbp).
Return: All locations of t as a substring of s.
"""
# Function
def find_motifs(sequence, motif):
"""This function is going to return the initial index (1-based) of all motifs
found in a sequence"""
if len(motif) >= len(sequence): # check motif is not longer than the sequence
print("Error: motif cann't have the same or longer lenght than the sequence")
else: # find motifs
motifs_index = []
start = 0 # define initial index
for nt in sequence: # parse the sequence to find motifs
if nt == motif[0]:
end = start + len(motif) # define end index
if sequence[start:end] == motif: # check if sequence contains motif
motifs_index.append(start+1) # python indexes are 0 based, correct that to return a 1-based index
start = start + 1 # update index
return print(*motifs_index, sep = " ")
# Test
s = "TAAGCTGAGATATGAGATAGTGAGATAATGAGATAGATGAGATAATGAGATACTTGAGATATGAGATATGAGATATGAGATACGGTCCCTGAGATATCTGAGATATGAGATATGTGAGATAGGTGAGATATGAGATATGAGATAACTGAGATAAGGGCCTGAGATAGTTGAGATAAAATGAGATACCGATGCTGAGATATGAGATAGAAACCTGAGATACAATGAGATATTCTCATCTAGCATTGAGATACTGAGATAGGAAATAATGGCTGAGATAACATTCTCCTGAGATAATTTTGAGATAGTGAGATATGAGATATGAGATACTGAGATATGAGATATGCCGCGAGTTTGAGATAGAACTGAGATATGAGATAGTGAGATATACTGAGATACGGAGCGGATGAGATACTCATATGAGATAGATCAGCTCAGACGACTGAGATAGCCTTGGATGAGATATGAGATAGTAATGAGATATTGAGATACGAGAGTTGAGATAGTCCGACGCGCTGAGATAGATGAGATATGCTTTCTTACCCCTGAGATAATAAGTGAGATACCTGAGATAGTGAGATATGAGATAGGGGTTTTCATTTGATTGAGATATGAGATATGAGATAATTGAGATAAGAGTTTGAGATACGCTATCTGAGATAAAAGCCTGAGATAATTTGAGATATTGAGATAGATGAGATACTGAGATAGCTAAGGCCCATTGAGATATTGAGATACCTACGTCCATGAGATAATATGAGATAGTGAGATACCCTGAGATAAATCAAGATGAGATAACTCTGAGATAATGAGATATGAGATATAATGAGATAATGAGATACCGTTCTGAGATAATGAGATATTACTGAGATACTGAGATACGATTGAGATAAATGTGAGATAAATTGAGATAAGAATGAGATATACTGAGATACACTGAGATA"
t = "TGAGATATG"
find_motifs(s,t)
|
item = ''
itens = []
maior_item = ''
maior = ''
while item != '0 0 0':
item = input()
itens.append(item)
for x in itens:
compra = x.split(' ')
total = int(compra[1])*float(compra[2])
if maior_item == '':
maior_item = x + ' ' + str(total)
else:
maior = maior_item.split(' ')
if float(maior[3]) < total:
maior_item = x + ' ' + str(total)
maior_split = maior_item.split(' ')
if maior_split[0] == '0':
print('nao tem compras')
else:
print('Item mais caro')
print('Codigo: {}'.format(maior_split[0]))
print('Quantidade: {}'.format(maior_split[1]))
print('Custo: {:.2f}'.format(round(float(maior_split[3]),2)))
|
q = 0
n = str(input())
m = str(input())
a = list(n)
for i in a:
if i == m:
q += 1
if q == 0:
print('Caractere nao encontrado.')
else:
print('O caractere buscado ocorre {} vezes na sequencia.'.format(q))
|
def Credito(Valor):
Valor = Valor * 2
return Valor
def Debito(Valor):
Valor = Valor / 10
return Valor
ValorFinanceiro = 10
print(Credito(ValorFinanceiro))
print(Debito(ValorFinanceiro)) |
def encontrarMultiplus(n,m):
i = 0
multiplus = []
while i <= n:
if i % m == 0:
multiplus.append(i)
i = i + 1
else:
i = i + 1
return multiplus
numero1 = int(input())
numero2 = int(input())
multiplus = encontrarMultiplus(numero1,numero2)
print('Os multiplus de',numero2,'são: ',multiplus)
|
salario = float(input())
desconto = 0
if salario<=1751.81:
desconto=0.08*salario
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
elif salario>1751.81 and salario<=2919.72:
desconto=0.09*salario
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
elif salario>2919.72 and salario<=5839.45:
desconto=0.11*salario
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
else:
desconto=5839.45*0.11
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
|
def somaDigitos():
x = int(input())
soma = 0
while (x != 0):
resto = x % 10
x = (x - resto)//10
soma = soma + resto
print(soma)
somaDigitos()
|
num = float(input())
num = num*100
while num <= 70 or num >= 620 or num%10!=0:
print('Preco invalido, refaca a leitura do pacote.')
num = float(input())
num = num*100
|
# Candidate.py
# Ben Hazlett
# 1/22/2018
# Description:
# Written for the Asymmetric programming challenge. This file
# contains a class written to hold a word called a candidate
class Candidate():
# Constructor: inititalizes dictionaries to empty
def __init__(self, word, confidence):
self.word = word
self.confidence = confidence
# get_confidence()
# Input: word (string)
# Output: confidence (int)
def getConfidence(self):
return self.confidence
# get_word()
# Input: word_frag (string)
# Ouput: auto_complete (string)
def getWord(self):
return self.word
# increase_confidence_by_1()
# Input: None
# Output: None
def increaseConfidenceByOne(self):
self.confidence += 1
# stringify()
# Input: None
# Output: the information of the class (string)
def stringify(self):
return str(self.getWord() + " (" + str(self.getConfidence()) + ")")
|
from flask import Flask
app = Flask(__name__) # Flask --> class --> object --> app
# __name__ ??
# make object of PWD so that later it will read everything from current working directory
@app.route("/") # route --> decorator --> takes path as an argument
# / --> domain , / --> localhost(127.0.0.1)
def index():
return "WELCOME TO MY FLASK PROJECT"
@app.route("/home/") # localhost/home/
def home():
return "<h1 style='color:red'>This is my first flask project welcome to my home</h1>"
@app.route("/home/<name>")
def home_name(name):
return f"<h1 style='color:red'>This is my first flask project welcome to my home <i>{name.upper()}</i></h1>"
@app.route("/home/<name>/<int:age>/")
def check_vote(name, age):
if age>=18:
return f"<h1 style='color:blue'>{name.upper()} can vote"
else:
return f"<h1 style='color:blue'>{name.upper()} cannot vote"
# task
# localhost/simran/80/90/100
# return string simran got 80+90+100/3 and got so and so grade
app.run(host="localhost", port=80, debug=True)
# debug --> Show the errors on browser |
#!/usr/bin/env python3
user_input = input("Please enter an IPv4 IP address:")
print("You told me the PIv4 address is:" + user_input)
|
"""
Points:
- Stones can be attached to existing rows, stones can be moved if all rows stay valid
Valid rows:
- Jokers can be used everywhere; they count for the same number as they represent
- If no valid row can be made; the user picks up a stone from the pot.
Play ends if:
- One of the players placed all his stones on the table
- Pot is empty; if so, the player with the least points on its rack wins.
"""
import numpy as np
from random import randint
from player import Player
from table import Table
import settings
class Game:
def __init__(self, max_players):
""" Rummikub Game initializer. """
self.game_id = randint(100000, 999999)
#: :obj:`Table`: Table where the game takes place.
self.table = Table()
#: :obj:`int` Maximum number of players.
self.max_players = max_players
#: :obj:`list` of :obj:`Player`: Players that are in the game.
self.players = []
def add_player(self, _id, username):
self.players.append(Player(_id, username, self.table))
def find_by_id(self, _id):
for player in self.players:
if player._id == _id:
return player
return False
def remove_player(self, player):
""" Remove given player from game """
self.players.remove(player)
def start(self):
""" Starts the game by filling the pot and giving every player a defined amount of stones. """
self.prepare_table()
for player in self.players:
player.addStones(self.table.pick_stones(
settings.STONES_PER_PLAYER))
def prepare_table(self):
""" Fills the pot attached to the :obj:`Table` with all cards. (106 stones; 2x 1-13, red, yellow, blue, black + two jokers) """
NUMBERS = np.arange(1, settings.HIGHEST_NUMBER + 1)
COLORS = np.arange(settings.NUMBER_OF_COLORS)
combinations = np.array(np.meshgrid(
NUMBERS, COLORS)).T.reshape(-1, 2)
all_stones = np.vstack((combinations, combinations))
jokers = [[99, 99], [99, 99]]
self.table.add_to_pot(np.append(all_stones, jokers, axis=0))
def __dict__(self):
return {
'game_id': self.game_id,
'players': [
{
'_id': player._id
}
for player in self.players
]
}
def __str__(self):
""" String which represents :obj:`Game` object when converted to :obj:`str`. """
userStones = '\n '.join(
[f"Player {player._id}: {player.rack.shape[0]} stones " for player in self.players])
return f"Pot: {self.table.pot.shape[0]} stones" \
"Players:" + userStones
def __repr__(self):
""" String which represents :obj:`Game` object when printed out on CLI. """
return self.__str__()
|
socks = "socks"
jeans = "jeans"
laptop = "laptop"
toiletries="toiletries"
luggage = []
item1 = raw_input("what you like to pack?")
luggage.append(item1)
item2 = raw_input("next item to pack?")
luggage.append(item2)
for items in luggage:
print(items.upper())
grades = [
96.0,
100.0,
75.5,
89.5
]
sum = 0
for grade in grades:
sum = sum + grade
print(sum)
|
import pylab
from random import shuffle
def bubblesort_anim(a):
x = range(len(a))
imgidx = 0
# bubble sort algorithm
swapped = True
while swapped: # until there's no swapping
swapped = False
for i in range(len(a)-1):
if a[i] > a[i+1]:
a[i+1], a[i] = a[i], a[i+1] # swap
swapped = True
pylab.plot(x,a,'k.',markersize=6)
pylab.savefig("bubblesort/img" + '%04d' % imgidx + ".png")
pylab.clf() # figure clear
imgidx = imgidx + 1
# running the algorithm
a = range(300)
shuffle(a)
bubblesort_anim(a)
|
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
GREY = '\033[90m'
RESET = '\033[1m'
print(RESET)
grade = float(raw_input("Enter the grade you got on a quiz"))
#todo fill in - and +'s
if(grade >= 90.0):
print(BLUE+"you got an A")
if(grade >= 80.0 and grade < 90.0):
print(GREEN+"you got a B")
if(grade >= 70.0 and grade < 80.0):
print(PURPLE+"you got a C")
if(grade >= 60.0 and grade < 70.0):
print(YELLOW+"you got a D")
if(grade < 60.0):
print(RED+"you got an F")
|
n=int(input(':'))
list1=list(map(int,str(n)))
list2=sorted(list(map(int,str(n))))
if list1==list2:
print('DA')
else:
print('NU') |
#simple GUI registration form.
#importing tkinter module for GUI application
from tkinter import *
#Creating object 'root' of Tk()
root = Tk()
#Providing Geometry to the form
root.geometry("800x700")
#Providing title to the form
root.title('Registration form')
#this creates 'Label' widget for Registration Form and uses place() method.
label_0 =Label(root,text="Registration Form", width=20,font=("bold",20))
#place method in tkinter is geometry manager it is used to organize widgets by placing them in specific position
label_0.place(x=90,y=60)
#this creates 'Label' widget for Fullname and uses place() method.
label_1 =Label(root,text="Employee ID", width=20,font=("bold",10))
label_1.place(x=80,y=130)
#this will accept the input string text from the user.
entry_1=Entry(root)
entry_1.place(x=240,y=130)
#this creates 'Label' widget for Email and uses place() method.
label_3 =Label(root,text="Contact Number", width=20,font=("bold",10))
label_3.place(x=68,y=180)
entry_3=Entry(root)
entry_3.place(x=240,y=180)
#this creates 'Label' widget for Gender and uses place() method.
label_4 =Label(root,text="Gender", width=20,font=("bold",10))
label_4.place(x=70,y=230)
#the variable 'var' mentioned here holds Integer Value, by deault 0
var=IntVar()
#this creates 'Radio button' widget and uses place() method
Radiobutton(root,text="Male",padx= 5, variable= var, value=1).place(x=235,y=230)
Radiobutton(root,text="Female",padx= 20, variable= var, value=2).place(x=290,y=230)
##this creates 'Label' widget for country and uses place() method.
label_5=Label(root,text="Country",width=20,font=("bold",10))
label_5.place(x=70,y=280)
#this creates list of countries available in the dropdownlist.
list_of_country=[ 'India' ,'US' , 'UK' ,'Germany' ,'Austria',"China"]
#the variable 'c' mentioned here holds String Value, by default ""
c=StringVar()
droplist=OptionMenu(root,c, *list_of_country)
droplist.config(width=15)
c.set('Select Your Country')
droplist.place(x=240,y=280)
##this creates 'Label' widget for Language and uses place() method.
label_6=Label(root,text="Language",width=20,font=('bold',10))
label_6.place(x=75,y=330)
#the variable 'var1' mentioned here holds Integer Value, by default 0
var1=IntVar()
#this creates Checkbutton widget and uses place() method.
Checkbutton(root,text="English", variable=var1).place(x=230,y=330)
#the variable 'var2' mentioned here holds Integer Value, by default 0
var2=IntVar()
Checkbutton(root,text="German", variable=var2).place(x=300,y=330)
#the variable 'var2' mentioned here holds Integer Value, by default 0
var3=IntVar()
Checkbutton(root,text="Hindi", variable=var2).place(x=380,y=330)
#this creates button for submitting the details provides by the user
Button(root, text='SUBMIT' , width=20,bg="black",fg='white').place(x=180,y=380)
#this will run the mainloop.
root.mainloop() |
import random
number=random.randint(1,9)
chances=0
print("Guess a number ")
while chances<5:
guess=int(input("Enter your guess "))
if guess==number:
print("Congratulations")
break
elif guess<number:
print("too low ")
else:
print("too high ")
chances=chances+1
if not chances<5:
print("You lose ") |
#import panad
import pandas as pd
import numpy as np
#Read data
other_path = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/auto.csv"
df = pd.read_csv(other_path, header=None)
# show the first 5 rows using dataframe.head() method
print("The first 5 rows of the dataframe")
df.head(5)
# show last 10 rows
print("The last 10 rows of the dataframe")
df.tail(10)
#add Headers
headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style",
"drive-wheels","engine-location","wheel-base", "length","width","height","curb-weight","engine-type",
"num-of-cylinders", "engine-size","fuel-system","bore","stroke","compression-ratio","horsepower",
"peak-rpm","city-mpg","highway-mpg","price"]
print("headers\n", headers)
df.columns = headers
df.head(10)
#Replacing "?" with NaN values
df1=df.replace('?',np.NaN)
df=df1.dropna(subset=["price"], axis=0)
df.head(20)
#retreving cloumns names
print(df.columns)
#Saving the Dataset
df.to_csv("automobile.csv", index=False)
|
import maxflow
# Create a graph with integer capacities.
g = maxflow.Graph[int](2, 2)
# Add two (non-terminal) nodes. Get the index to the first one.
n0 = g.add_nodes(2)
# Create two edges (forwards and backwards) with the given capacities.
# The indices of the nodes are always consecutive.
g.add_edge(n0, n0 + 1, 1, 2)
# Set the capacities of the terminal edges...
# ...for the first node.
g.add_tedge(n0, 2, 5)
# ...for the second node.
g.add_tedge(n0 + 1, 9, 4)
# Find the maxflow.
flow = g.maxflow()
print "Maximum flow:", flow
# Print the segment of each node.
print "Segment of the node 0:", g.get_segment(n0)
print "Segment of the node 1:", g.get_segment(n0 + 1)
|
"""
Imagine you have a call center with three levels of employees: fresher, technical lead
(TL), product manager (PM). There can be multiple employees, but only one TL or PM.
An incoming telephone call must be allocated to a fresher who is free. If a fresher
can’t handle the call, he or she must escalate the call to technical lead. If the TL is
not free or not able to handle it, then the call should be escalated to PM. Design the
classes and data structures for this problem. Implement a method getCallHandler()
"""
class Employee:
def __init__(self, name, manager):
self.name, self.manager, self.call = name, manager, None
def take_call(self, call):
pass
def escalate(self, call):
pass
def finish_call(self, call):
pass
class TechnicalLead(Employee):
def __init__(self):
pass |
"""
Implement an algorithm to print all valid (e.g., properly opened and closed) combi-
nations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
"""
import unittest
def parens(n):
parens_of_length = [[""]]
if n == 0:
return parens_of_length[0]
for length in range(1, n + 1):
parens_of_length.append([])
for i in range(length):
for inside in parens_of_length[i]:
for outside in parens_of_length[length - i - 1]:
parens_of_length[length].append("(" + inside + ")" + outside)
return parens_of_length[n]
class Test(unittest.TestCase):
def test_parens(self):
self.assertEqual(parens(1), ["()"])
self.assertEqual(parens(2), ["()()", "(())"])
self.assertEqual(parens(3), ["()()()", "()(())", "(())()", "(()())", "((()))"])
if __name__ == "__main__":
unittest.main() |
"""
Problem: Given 10 identical bottles of identical pills (each bottle contain hundred of pills).
Out of 10 bottles 9 have 1 gram of pills but 1 bottle has pills of weight of 1.1 gram.
Given a measurement scale, how would you find the heavy bottle? You can use the scale only once.
"""
import unittest
def pill_bottle(bottles):
pills = []
for i, bottle in enumerate(bottles):
pills += [bottle.pill()]*i
weight = weight_scale(pills)
index = (weight - (len(pills)*1.0))*10
return int(index+0.1)
def weight_scale(weight):
return sum(weight)
class Bottle:
def __init__(self, pill_weight=1.0):
self.pill_weight = pill_weight
def pill(self):
return self.pill_weight
class Test(unittest.TestCase):
def test_pill_bottle(self):
bottles = [Bottle(), Bottle(), Bottle(), Bottle(), Bottle(),
Bottle(), Bottle(1.1), Bottle(), Bottle(), Bottle(),
Bottle(), Bottle(), Bottle(), Bottle(), Bottle(),
Bottle(), Bottle(), Bottle(), Bottle(), Bottle()]
self.assertEqual(pill_bottle(bottles), 6)
if __name__ == "__main__":
unittest.main() |
#1: write different list
listofnumber=[1,2,4,5,6,7,8,8,9,7]
print(listofnumber)
listofname=["bishal","bubun","banti","chuni"]
print(listofname)
listofboth=[1,3,"name","book"]
print(listofboth)
#2:accesing element from tuple
tupleof_number=(1,2,3,4)
print(tupleof_number)
#access element
print(tupleof_number[0])
print(tupleof_number[1])
print(tupleof_number[2])
print(tupleof_number[3])
#3:del item from dictionary
dictionary={"name":"bishal","title":"patel","rollnumber":12}
print(dictionary)
#accent key value with name
print(dictionary["name"])
# del item with key name
del dictionary["name"]
print(dictionary)
|
# Special is a Prey similar to Special and floater
# except it moves faster and has a larger radius.
# It starts off as an orange circle but changes
# to a random color every 15 cycles.
from prey import Prey
import random
class Special(Prey):
radius = 10
max_count = 15
def __init__(self, x, y):
Prey.__init__(self, x, y, Special.radius*2, Special.radius*2, 0, 10)
Special.randomize_angle(self)
self.counter = 0
self.color = 'Orange'
def update(self, model):
self.counter += 1
if self.counter == Special.max_count:
self.color = "#"+str(hex(random.randint(20,255)))[2:]+str(hex(random.randint(20,255)))[2:]+str(hex(random.randint(20,255)))[2:]
self.counter = 0
self.move()
def display(self, canvas):
canvas.create_oval(self._x-Special.radius, self._y-Special.radius, self._x+Special.radius, self._y+Special.radius, fill=self.color)
|
class Stack:
def __init__(self):
self._data = []
def push(self, x):
self._data.append(x)
def pop(self):
x = self._data[-1]
self._data = self._data[:-1]
return x
def isEmpty(self, ):
return len(self._data) == 0
def clear(self):
self._data = []
class Queue(Stack):
def __init__(self):
super().__init__()
def pop(self):
x = self._data[0]
self._data = self._data[1:]
return x
class PriorityQueue(Stack):
def __init__(self, function=lambda x: x, maximize=True):
super().__init__()
self.fn = function
self.maximize = maximize
def pop(self):
iteration = max if self.maximize else min
x = iteration(self._data, key=self.fn)
self._data.remove(x)
return x
|
"""
File: Project2
Author: Cole Crase
This will allow the user to naviagte the liens of text in a file.
"""
fileName = input("Enter the file name: ")
f = open(fileName, 'r')
Counter = 0
for n in f:
if n:
Counter += 1
print("The number of lines in this file is", Counter)
while True:
number = int(input("Enter a line number or press 0 to quit: "))
if number > 0 and number < Counter +1:
print(f.readline)
elif number == 0:
print("The program is done.")
|
# Hesap Makinesi
print("Toplama = 1 \n"
"Çıkarma = 2 \n"
"Çarpma = 3 \n"
"Bölme = 4")
islem = input("İşlemi Seçiniz: ")
sayi1 = int(input("Sayi 1: "))
sayi2 = int(input("Sayi 2: "))
if islem == "1":
sonuc = int(sayi1) + int(sayi2)
print("Sonuç: ", str(sonuc))
elif islem == "2":
sonuc = int(sayi1) - int(sayi2)
print("Sonuç: ", str(sonuc))
elif islem == "3":
sonuc = int(sayi1) * int(sayi2)
print("Sonuç: ", str(sonuc))
elif islem == "4":
if sayi2 > 0:
sonuc = int(sayi1) / int(sayi2)
print("Sonuç: ", str(sonuc))
elif sayi2 == 0:
print("!!!Sayi 2 = 0(sıfır) olamaz!!!")
else:
print("!!!Hatalı işlem seçimi!!!")
|
# Ekrana çift sayı yazdır
sayi = int(input("Çift sayılar için üst sınır giriniz: "))
for i in range(0, sayi, 2):
print(i)
|
'''
同余定理和次方求模
'''
import math
def congruence(*args, **kwargs):
a = args[0]
b = args[1]
m = args[2]
return m % (a-b) == 0
def powmod(*args, **kwargs):
'''
a^v mod c
'''
a = args[0]
b = args[1]
c = args[2]
if b == 0:
return 1
if b == 1:
return a % c
temp = powmod(a, b >> 1, c)
temp = temp*temp % c
if b % 2:
temp = temp*a % c % c
return temp
if __name__ == "__main__":
print(congruence(13, 17, 2))
print(powmod(11, 12345, 12345))
|
#EXEMPLO DE CLASSE QUE PRECISA DOS ATRIBUTOS/MÉTODOS DE OUTRA CLASSE PARA FUNCIONAR
class Cart:
def __init__(self):
#LISTA ONDE SERÃO INSERIDOS OS DADOS DE OUTRA CLASSE
self.produtos = []
#RESPONSÁVEL POR INSERIR PRODUTOS NA LISTA
def inserir_produto(self, produto):
self.produtos.append(produto)
#RESPONSÁVEL POR LISTAR OS PRODUTOS DA LISTA
def lista_produto(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
#RESPONSÁVEL POR SOMAR OS PRODUTOS DA LISTA
def soma_produto(self):
total = 0
for produto in self.produtos:
total += produto.valor
return total
#CLASSE QUE IRÁ FORNECER DADOS PARA A CLASSE PRINCIPAL
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
|
from random import randint
print('Jogo do Par ou Ímpar')
print('-='*11)
c = 0
while True:
jogador = int(input('Digite um valor: '))
computador = randint(0, 11)
soma = jogador + computador
tipo =' '
while tipo not in 'PI':
tipo = str(input('Par ou Ímpar? [P/I] ')).strip().upper()[0]
print(f'Voce jogou {jogador} e o computador jogou {computador} o total é {soma}')
if tipo == 'P':
if soma % 2 == 0:
print('Você venceu!')
c += 1
else:
print('Você perdeu!')
break
elif tipo == 'I':
if soma % 2 == 1:
print('Você venceu!')
c +=1
else:
print('Você perdeu!')
break
print('Vamos jogar novamente!')
print('Game Over')
print(f'Você ganhou {c} vezes') |
n=input("Enter the name of item")
q=int(input("Enter the cost of one unit"))
r=int(input("Enter the number of item purchased"))
t=q*r
print("The total expenditure incured by purchasing: ",n,"is",t)
|
## @package File_Decryption_Example
# This project is an example of file decryption using Python. In this
# example, Advanced Encryption Standard (AES) from the Crypto library.
# AES uses a 16, 24, or 32-byte key to decrypt information. In this case, the user must provide
# the key and input file name including location. Any type of file can
# be encrypted as far as I have tested.
#
## \n Author: Mr. Reeses
## \n Date: 9/24/2015
## \n Version: 1.0
#
## \n Example of how to type in prompt:
## \n decrypt_file('abcde12345f6g7h8', 'C:\Users\Owner\Desktop\hello_world_encrypt.txt',
# 'C:\Users\Owner\Desktop\hello_world_decrypt', 4096)
import os, random, struct
from Crypto.Cipher import AES
## This function is used to decrypt a file using AES (CBC mode) with the
# given key that was used to encrypt the file.
#
# @param key
# The decryption key - a string that must be
# either 16, 24 or 32 bytes long. Longer keys
# are more secure.
#
# @param in_filename
# Name of the encrypted input file. <in_filename>.enc
#
# @param out_filename
# If None, '<in_filename>' will be used.
#
# @param chunksize
# Sets the size of the chunk which the function
# uses to read and encrypt the file. Larger chunk
# sizes can be faster for some files and machines.
# chunksize must be divisible by 16.
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
|
import numpy as np
from math import asin, pi
# Classe para representar um ponto/vetor, facilitar codigo para as funcoes de operacoes geometricas
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return str(self.x) + " " + str(self.y)
# Soma de dois pointos
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
# Subtracao de dois pointos
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
# Multiplicacao de ponto por escalar
def __mul__(self, t):
return Point(self.x * t, self.y * t)
# Tamanho do vetor (0,0)->(self.x,self.y)
def len(self):
return np.sqrt(self.x*self.x + self.y*self.y)
def tuple(self):
return int(self.x), int(self.y)
# Projecao do vetor self em other
def relative_proj(self, other):
return dot(self,other)/(other.len() * other.len())
# Retorna o ponto da linha que liga self a reta representada que passa por a e b
def intersect_line(self, a, b):
p = self
if(a == b):
return a
ap = p - a
ab = b - a
u = ap.relative_proj(ab)
return a + ab*u
# Produto escalar entre pontos a e b
def dot(a, b):
return a.x*b.x + a.y*b.y
|
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
while exp > 0:
result = result * base
exp -= 1
return result
print iterPower(2, 3)
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp == 0:
return 1
else:
return base * recurPower(base, exp - 1)
print recurPower(2, 10)
def recurPowerNew(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float; base^exp
'''
if exp == 0:
return 1
elif exp % 2 == 0:
return recurPowerNew(base * base, exp/2)
else:
return base * recurPowerNew(base, exp - 1)
print recurPowerNew(2, 10)
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
smaller = min(a, b)
while a >= 1:
if a % smaller == 0 and b % smaller == 0:
return smaller
else:
smaller -= 1
print gcdIter(8, 12)
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
if b == 0:
return a
else:
return gcdRecur(b, a % b)
print gcdRecur(8, 12)
def lenIter(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
num = 0
for i in aStr:
num += 1
return num
print lenIter('Piotr')
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
if aStr == '':
return 0
else:
return 1 + lenRecur(aStr[1:])
print lenRecur('Piotr')
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
aStr = aStr.lower()
char = char.lower()
middle = len(aStr)/2
if aStr == '':
return False
elif char == aStr[middle]:
return True
else:
if char < aStr[middle]:
return isIn(char, aStr[:middle])
else:
return isIn(char, aStr[middle+1:])
print isIn('a', 'hijklmnopr')
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
False otherwise.
'''
if len(str1) != len(str2):
return False
if str1 == '' or str2 == '':
return True
elif str1[0] != str2[-1]:
return False
else:
return semordnilap(str1[1:], str2[:-1])
print semordnilap('nametag', 'hateman')
def fibMetered(x):
global numCalls
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fibMetered(x-1) + fibMetered(x-2)
def testFib(n):
for i in range(n+1):
global numCalls
numCalls = 0
print('fib of ' + str(i) + ' = ' + str(fibMetered(i)))
print ('fib called ' + str(numCalls) + ' times')
testFib(5) |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from collections import Counter
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return None
root = head
cnt = Counter()
while root:
cnt[root.val] +=1
root = root.next
root = head
root2 = root
while root:
if cnt[root.val]>1 and root == root2:
root2 = root2.next
root = root.next
elif root.next and cnt[root.next.val]>1:
root.next = root.next.next
else:
root = root.next
return root2
def printm(M):
for e in M:
print(e)
def buildList(a):
tail = None
for e in reversed(a):
if tail == None:
tail = ListNode(e)
else:
n = ListNode(e)
n.next = tail
tail = n
#printList(tail)
return tail
def printList(node: ListNode):
while node:
print(node.val,'->')
node = node.next
if __name__ == "__main__":
s = Solution()
printList(s.deleteDuplicates(buildList([1,2,3,3,4,4,5])))
# printList(s.deleteDuplicates(buildList([1,1,1,2,3])))
# print(s.deleteDuplicates()) |
import unittest
"""
https://www.youtube.com/watch?v=qli-JCrSwuk
"""
def num_ways(s):
if len(s) == 0:
return 0
elif s[0] == '0':
return 0
elif len(s) == 1:
return 1
nw = num_ways(s[1:])
print(f'nw1={nw} + {s[1]} + {s[1:3]}')
if int(s[1:3]) >9 and int(s[1:3])<27:
nw += num_ways(s[2:])
print(f'nw2={nw}')
return nw
class NumWays(unittest.TestCase):
def test_1(self):
self.assertEqual(0,num_ways(""))
def test_11(self):
self.assertEqual(2,num_ways("123"))
def test_12(self):
self.assertEqual(1,num_ways("456"))
def test_13(self):
self.assertEqual(3,num_ways("111"))
if __name__ == '__main__':
unittest.main() |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
if not head.next:
return True
if not head.next.next:
return head.val == head.next.val
if not head.next.next.next:
return head.val == head.next.next.val
root = head
cnt = 0
while root:
cnt+=1
root = root.next
root = head
i =0
half = cnt //2
if cnt %2 ==1:
half += 1
while root and i < half:
i+=1
root = root.next
nr = ListNode(root.val)
revtail = self.reverse(root.next,nr)
i = 0
h2 = head
while h2 and revtail and i < cnt//2:
if h2.val != revtail.val:
return False
h2 = h2.next
revtail = revtail.next
return True
def reverse(self, head: ListNode, tail: ListNode) -> ListNode:
if not head:
return tail
if not head.next:
head.next = tail
return head
nt = ListNode(head.val)
nt.next = tail
rest = self.reverse(head.next,nt)
return rest
#Print matrix
def printm(M):
for e in M:
print(e)
#Linked Lists:
def buildList(a):
tail = None
for e in reversed(a):
if tail == None:
tail = ListNode(e)
else:
n = ListNode(e)
n.next = tail
tail = n
#printList(tail)
return tail
def printList(node: ListNode):
while node:
print(node.val,'->')
node = node.next
if __name__ == "__main__":
s = Solution()
print(s.isPalindrome(buildList([1,2])))#false
print(s.isPalindrome(buildList([1,2,2,1])))#true
print(s.isPalindrome(buildList([1,0,0])))#false
print(s.isPalindrome(buildList([1,1,2,1])))#false |
from typing import List
#Print matrix
def printm(M):
for e in M:
print(e)
#Linked Lists:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def buildList(a):
tail = None
for e in reversed(a):
if tail == None:
tail = ListNode(e)
else:
n = ListNode(e)
n.next = tail
tail = n
#printList(tail)
return tail
def printList(node: ListNode):
while node:
print(node.val,'->')
node = node.next
if __name__ == "__main__":
s = Solution()
print(s.())
print(s.())
print(s.()) |
from typing import List
"""
From: https://www.youtube.com/watch?v=4UWDyJq8jZg
"""
class Person:
def __init__(self, b,d):
self.b = b
self.d = d
def get_year(persons: List[Person]) -> int:
years = [0 for i in range(2019)]
for p in persons:
years[p.b] +=1
years[p.d] -=1
mYear = 0
mCount =0
count = 0
for y, c in enumerate(years):
count += c
if count > mCount:
mCount = count
mYear = y
return mYear
p1 = [Person(1800,1820),Person(1819,1834)]
print(get_year(p1)) |
from typing import List
class NotWorkingRecursiveSolution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
return self.mergeR(intervals)
def mergeR(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals or not intervals[0]:
return []
if len(intervals)==1:
return intervals
if len(intervals)==2:
return self.helper(intervals[0],intervals[1])
else:
return self.mergeR([intervals[0]] + self.mergeR(intervals[1:]))
def helper(self,i1:List[int], i2:List[int])-> List[List[int]]:
if (i1[0]<= i2[1] and i1[0] >= i2[0]) or (i1[1]>= i2[0] and i1[1] <= i2[1]) or (i1[0]<=i2[0] and i1[1]>=i2[1]) or (i2[0]<=i1[0] and i2[1]>=i1[1]):
return[[min(i1[0],i2[0]),max(i1[1],i2[1])]]
else:
return[i1,i2]
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals = sorted(intervals, key=lambda x: x[0])
merged = []
for i in intervals:
if not merged or merged[-1][1] < i[0]:
merged.append(i)
else:
merged[-1][1] = max(merged[-1][1],i[1])
return merged
def printm(M):
for e in M:
print(e)
if __name__ == "__main__":
s = Solution()
print(s.merge([[1,3],[2,6],[8,10],[15,18]]))#[[1,6],[8,10],[15,18]]
print(s.merge([[1,4],[4,5]]))#[[1,5]]
print(s.merge([[1,4],[0,5]]))#[[0,5]]
print(s.merge([[2,3],[4,5],[6,7],[8,9],[1,10]]))#[[1,10]] |
from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
n = len(matrix)
m = len(matrix[0])
l = 0
r = n
mid = l + (r-l)//2
if matrix[n-1][0]<target:
mid = n-1
else:
while l<=r:
print(l,mid,r)
e = matrix[mid][0]
if e == target:
break
elif e <target:
l = mid
else:
r = mid
mid = l + (r-l)//2
if l == mid or r == mid:
break
print(mid)
row = mid
l =0
r = m
mid = l + (r-l)//2
while l<=r:
print(l,mid,r)
e = matrix[row][mid]
if e == target:
return True
elif e <target:
l = mid
else:
r = mid
mid = l + (r-l)//2
if l == mid or r == mid:
break
return matrix[row][mid] == target
if __name__ == "__main__":
s = Solution()
print(s.searchMatrix(matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
],target = 3))
print(s.searchMatrix(matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
],target = 13))
print(s.searchMatrix([[1,1]],2))
print(s.searchMatrix([[1,3]],1)) |
#!/usr/bin/env python
# coding: utf-8
# <p> This is my <b> first Python code </b>.
# $$Hello$$
# $$ c = \sqrt{a^2+b^2} $$
# $$ e^{i\pi} + 1 =0 $$
# $$ e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$
# $$ f(x) = a_0 + \sum_{n=1}^\infty (a_n cos \frac{n \pi x} L + $$
# $$ ( x + a ) ^n = \sum_{k=0} ^ n (k^n) x^k a^{n-k} $$
#
#
# In[ ]:
#
#
#
#
|
#!/usr/bin/env python
# coding: utf-8
# In[17]:
import numpy as np
a = np.arange(15).reshape(3,5)
a
# In[18]:
print(np.array([8,4,6,0,2]))
# In[ ]:
# In[19]:
print('create a 2-D array by passing a list of lists into array().')
A = np.array([[1,2,3],[4,5,6]])
print(A)
print('access elements of the array with brackets.')
print(A[0,1],A[1,2])
print('the elements of 2-D array are 1-D arrays.')
print(A[0])
# In[ ]:
# In[20]:
def example1():
A = np.array([[3, -1, 4],
[1, 5, -9]])
B = np.array([[2, 4, -5, 6],
[-1, 7, 9, 3],
[3, 2, -7, -2]])
return np.dot(A, B)
example1()
# In[19]:
A = np.array([[3,-1,4],[1,5,-9]])
B = np.array([[2,4,-5,6],[-1,7,9,3],[3,2,-7,-2]])
print('arrays' , 'A=',A ,'B=',B,'return the matrix product')
np.dot(A,B)
# In[22]:
arr = np.ndarray(shape = (5,1), dtype='int64')
arr = arr + 5
print(arr)
# In[23]:
print('addition concatenates lists togather')
print([1,2,3] + [4,5,6])
print('mutliplication cocatenates a list with itself a given number of times')
print([1,2,3] * 4)
# In[24]:
x = np.array([3, -4, 1])
y = np.array([5, 2, 3])
print(x + 10)
print(y * 4)
print(x + y)
print(x * y)
# In[25]:
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.dtype)
print(a.ndim)
print(a.shape)
print(a.size)
print(a[1,2])
# In[27]:
x = np.arange(10)
print(x)
print(x[3]) # slicing index 3
print(x[:4]) # slicing from index 0 to 4
print(x[4:]) # slicing from index 4 to the last index
print(x[4:8]) # slicing from index 4 to 8
# In[30]:
x= np.array([[0,1,2,3,4],
[5,6,7,8,9]])
print(x[1, 2])
print(x[:,2:])
# In[31]:
x = np.arange(0, 50, 10)
print(x)
index = np.array([3, 1, 4])
print(x[index])
# A boolean array extracts the elements of 'x' at the same places as 'True'
mask = np.array([True, False, False, True, False])
print(x[mask])
# In[32]:
y =np.arange(10,20,2)
print(y)
mask = y > 15
print(mask)
print(y[mask])
y[mask] = 100
print(y)
# In[33]:
from sklearn import datasets
iris = datasets.load_iris()
print(iris.filename)
# In[42]:
import numpy as np
iris_data = np.genfromtxt('C:\Users\W\Anaconda3\lib\site-packages\sklearn\datasets\data\iris.csv',
delimiter=",", skip_header=1)
print(iris_data)
# In[43]:
print('mean of {} is {}'.format(iris.feature_names[0], data[:,0].mean()))
# In[44]:
print('mean of {} is {}'.format(iris.feature_names[0], data[:,0].mean()))
print('std of {} is {}'.format(iris.feature_names[0], data[:,0].std()))
print('var of {} is {}'.format(iris.feature_names[0], data[:,0].var()))
print('max of {} is {}'.format(iris.feature_names[0], data[:,0].max()))
print('min of {} is {}'.format(iris.feature_names[0], data[:,0].min()))
# In[ ]:
# In[ ]:
|
# ========================
# Information
# ========================
# problem link : https://www.hackerrank.com/challenges/30-data-types/problem
# Language: Python
# ========================
# Solution
# ========================
# Declare second integer, double, and String variables.
ii =int(input())
dd =float(input())
ss =input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print(i+ii)
# Print the sum of the double variables on a new line.
print(d+dd)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s+ss)
|
#!/usr/bin/env python
# coding: utf-8
# In[8]:
#2
for i in range(1,21):
for j in range(i+1,21):
if (i+j)%2==0:
print("Sum is Even,Pair is: ",i,j,"The sum is: ",i+j)
else:
print("For",i,j,"Nothing can be done")
# In[21]:
#1
x=[1,2,3,4,[10,20,30,40,[100,200,300,400],'rishabh_',5+5j],4000]
print(x[4][0],x[4][1])
# In[26]:
#3
x='hello&*$$world'
c1=0
c2=0
c3=0
for char in x:
if char=='&':
c1=c1+1
elif char=='*':
c2=c2+1
elif char=='$':
c3=c3+1
print("&:",c1," ", "*:",c2," ","$:",c3)
# In[27]:
#4
for i in range(1,51):
if (i**3)%2!=0:
print("The numbers are: ",i)
# In[33]:
#6
x='Hello world I am learning Python'
words=x.split()
for i in words:
print("For: ",i,"length of: ",i, "is: ",len(i))
# In[60]:
#7
x=[12,'xyz',10,9]
all(isinstance(i,int) for i in x)
# In[62]:
#5
x=[1,2,3,4,5]
new_list=x.copy()
new_list
# In[64]:
#5
x=[33,66,99,3,12]
newlist = [i for i in x if i%3==0]
newlist
# In[ ]:
|
def knapsack(n, W):
if memo[n][W] != None:
return memo[n][W]
if n == 0 or W == 0:
result = 0
elif w[n] > W:
result = knapsack(n-1, W)
else:
temp1 = v[n] + knapsack(n-1, W-w[n])
temp2 = knapsack(n-1, W)
result = max(temp1, temp2)
memo[n][W] = result
return result
import random
W = 20
v = [None]
w = [None]
for i in range(5):
v.append(random.randint(1,20)*10)
w.append(random.randint(1,20))
n = len(v)-1
print("Values: " + str(v[1:]))
print("Weights: " + str(w[1:]))
print("Capacity: " + str(W))
memo = [[None] * (W+1)] * (n+1)
print(knapsack(n, W)) |
# max frequency with o(1)space and o(n) time
# condition no two max frequecny only one
# for more than one eg (1,1,2,2)
# check next program
# https://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
l = list(map(int,input("Enter Array : ").split(' ')))
#length
k = len(l)
for i in range(k):
l[l[i]%k] += k
max_fre = 0
result = 0
for i in range(k):
if l[i] > max_fre:
max_fre = l[i]
result = i
print(result)
# to retrieve array
for x in range(k):
l[x] = l[x]%k
print(l)
|
from turtle import Turtle
from car import Car
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_CAR_SPEED = 5
MOVE_INCREMENT = 3
LANE_POSITIONS = [ (300,-100) , ( 300,0) , (300 , 100 ) , (300, 200 ) ]
class CarManager(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.create_roadways()
self.car_positions = [ ]
self.cars = [ ]
self.car_speed = 1
self.number_of_cars = len(self.cars)
def create_cars(self , numb_of_car):
for _ in range(numb_of_car):
self.create_car()
def create_car(self):
car = Car()
self.set_car_position(car)
self.cars.append(car)
def move_cars(self):
for car in self.cars:
car.forward( STARTING_CAR_SPEED + MOVE_INCREMENT * self.car_speed )
def refresh_cars(self):
for car in self.cars:
car_position = car.position()
pos_x = car_position[0]
pos_y = car_position[1]
if pos_x > 320:
car.goto(-300 , pos_y)
def set_car_position(self,car):
pos_y = random.choice(LANE_POSITIONS)[1]
pos_x = random.randint(-300 , 300)
while not( self.is_position_proper(pos_x , pos_y)):
pos_y = random.choice(LANE_POSITIONS)[1]
pos_x = random.randint(-300 , 300)
self.car_positions.append((pos_x , pos_y))
car.goto( pos_x , pos_y)
def is_position_proper(self , pos_x , pos_y):
for position in self.car_positions:
if abs(position[0] - pos_x) <= 100 and pos_y == position[1]:
return False
return True
def increase_car_speed(self):
self.car_speed += 1
def is_there_collision(self , player):
for car in self.cars:
if abs(car.xcor() - player.xcor() ) < car.length / 2 and abs( car.ycor() - player.ycor() ) <= 20:
return True
return False
def create_roadways(self):
self.color('black')
self.setheading(180)
self.width(2)
for position in LANE_POSITIONS:
self.penup()
self.goto(position)
index = 0
# Draw roads
for length in range(300,-350,-50):
if index % 2 == 0:
self.pendown()
else:
self.penup()
self.goto(position[0] + length * 2 ,position[1])
index += 1
|
# more method with seatch(). search() will return an object
import re
pattern = r"colour"
text = "Blue is my favourite colour"
match = re.search(pattern, text)
if match:
print(match.start())
print(match.end())
print(match.span())
'''
start() - Returns the starting index of the match.
end() - Returns the index where the match ends.
span() - Return a tuple containing the (start, end) positions of the match.
''' |
n = int(input("Enter n = "))
sum =0
i=1
while i<=n :
sum = sum + i
i = i + 1
print(sum) |
file_open=open("Student.txt","r")
text=file_open.readlines()
# by using readlines(), we can make a list of Student.txt file's item.
print(text)
file_open.close()
file=open("Student.txt","r")
for line in file:
print(line)
file.close()
|
'''
Types of Inheritance:
i) Hierarchical Inheritance
ii) Multi-Level Inheritance
iii) Multiple Inheritance
'''
class A():
def display1(self):
print("I am inside A class")
class B(A):
#display1()
def display2(self):
print("I am inside B class")
class C(B):
#display1()
#display2()
def display3(self):
super().display1()
super().display2()
print("I am inside C class")
obj=C()
obj.display3() |
class Shape:
def __init__(self,Var1,Var2):
self.Var1=Var1
self.Var2=Var2
def area(self):
print("I am area method of Shape class")
class Traingle(Shape):
def area(self):
area=0.5*self.Var1*self.Var2
print("Area of Traingle=",area)
class Rectangle(Shape):
def area(self):
area=self.Var1*self.Var2
print("Area of Rectangle=",area)
T=Traingle(20,30)
T.area()
R=Rectangle(20,30)
R.area()
|
books=[]
books.append("Learn C") # append() is used to push value into the stack
books.append("Learn C++")
books.append("Learn Java")
print(books)
books.pop()
print(books)
print("The top most book is : ",books[-1])
# -1 index always show the last item
books.pop()
print(books)
print("The top most book is : ",books[-1])
books.pop()
if not books:
print("Not books left") |
'''
Two types of functions:
i) Library function
ii) User Defined Function
'''
def add(x,y):
sum=x+y
print("Summation is =",sum)
add(10,20)
add(78,89) |
try:
num1 = int(input("Enter 1st number ="))
num2 = int(input("Enter 2nd number ="))
result = num1 / num2
print(result)
except (ValueError,ZeroDivisionError):
print("You have to enter correct input")
finally:
print("Thanks")
|
name=input("Enter Your Name:") # by input(), we can take input from user.
age=input("Enter Your Age:") # by input(), we can only take string data type.
cgpa=input("Enter Your CGPA:")
print("Personal Information:")
print("========================")
print("Name= "+name)
print("Age= "+age)
print("Cgpa= "+cgpa) |
import itertools
def codebook(n):
pool = '0', '1'
o = open('binarylength' + str(n) + '.txt', 'w')
for item in itertools.product(pool, repeat=n):
o.write(str(item) + "\n")
return item
codebook(5)
def weight(n, s):
empty = []
for i in range(s):
empty.append(0)
for i in range(n+s):
empty.append(1 + empty[i] + empty[i+1])
for i in range(s):
empty.remove(0)
return empty
weight(5, 2)
#program computing the moment of a given codeword
def moment(s, x):
w = weight(len(x), s)
moment = 0
for i in range(len(x)):
moment += (x[i]*w[i])
print moment
moment(2, [0,1,1,0,1,0,0,0])
moment(2, [0,1,1,1,1])
#Generate helberg codebook n = 5, s = 2, a = 0. Should have moment 0 or 20.
def helbergcodebook(n, s, a):
file = codebook(n)
w = weight(n, s)
num = w[n]
print num
for t in file:
m = moment(s, t) #This is not working because the moment program only works if the number is a list of ints while the codebook program gives strings
print m
if m == a:
print t
if m == (num+a):
print t
else:
pass
helbergcodebook(5, 2, 0)
|
class Circle ():
'''
Calculates the circumference of a circle
Input radius
'''
pi = 3.14
def __init__(self,rad=1):
self.rad = rad
def calculate(self):
return self.rad * self.pi * 2
|
# File halve.py
# Enter a value and cut it half
#print ( "Enter a value : ", end='')
value = int(input("Enter a value : "))
print(value/2)
#print("Half of the " , value , " is " , int(value)/2) |
def triplet(text):
'''
PAPER DOLL: Given a string, return a string where for every character in
the original there are three characters
'Hello' -> HHHeeellllllooo
'''
res = ''
for c in text:
res += c*3
return res |
print ( " Enter the first Number " , end='')
num1 = int ( input() )
print ( "Enter the second number ", end='\n')
num2 = int ( input() )
print ( "\n Sum of two number is = " , num1+num2 , "\n Substraction of two number is = ", num1-num2 , "\n Multiplication of two number is = ", num1*num2 )
print (' ------------------------------------------------------------ ')
print ( 'Enter the 3rd number ' )
num3 = int ( float ( input () ) )
print ( "Enter the 4th Number ")
num4 = int ( float ( input() ) )
print ( "\n Sum of two number is = " , num3+num4 , "\n Substraction of two number is = ", num3-num4 , "\n Multiplication of two number is = ", num3*num4 )
|
def gen(n):
""" Generates the first n perfect squares, starting with zero:
0, 1, 4, 9, 16,..., (n - 1)2. """
for i in range(n):
yield i**2
for p in zip([10,20,30,40], gen(int(input('Enter the positive number in (0 to 10)')))):
print(p, end = ' ')
for p in zip([1,2,3,4,5,6],[6,5,4,3,2,1,0]):
print(p, end=' ' )
for (x,y) in zip([1,2,3,4,5,6],[6,5,4,3,2,1,0]):
print( (x,y) , ' ' , (x+y))
[x+y for(x,y)in zip([1,2,3,4,5,6,7],[1,2,3,4,5,6,7])]
|
#Drawing polygon
import turtle
import random
# Draws a regular polygon with the given number of sides.
# The length of each side is length.
# The pen begins at point(x, y).
# The color of the polygon is color.
def polygon(sides, length, x, y, color):
turtle.penup()
turtle.setposition(x,y)
turtle.pendown()
turtle.color(color)
turtle.begin_fill()
for i in range (sides):
turtle.forward(length)
turtle.left(360//sides)
turtle.end_fill()
turtle.hideturtle()
turtle.tracer(0)
# Main program
#polygon(4,5,2,10,"red")
for i in range(20):
polygon(random.randrange(3, 11), random.randrange(5, 51), random.randrange(-150, 151),
random.randrange(-150, 151), random.choice(("red", "green", "blue", "black", "yellow")))
turtle.update()
turtle.exitonclick()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .Vector import Vector
class Matrix(object):
""" 矩阵 """
def __init__(self, lst2d):
""" lst2d 是个二维数组"""
self._value = [row[:] for row in lst2d]
def __str__(self):
return "Matrix({})".format(self._value)
__repr__ = __str__
@classmethod
def zero(cls, r, c):
"""返回一个r行c列的零矩阵"""
# return cls([[0 for col in range(c)] for row in range(r)])
return cls([[0] * c for _ in range(r)])
def row_vector(self, index):
"""返回矩阵的第index个行向量"""
return Vector(self._value[index])
def col_vector(self, index):
"""返回矩阵的第index个列向量"""
return Vector([row[index] for row in self._value])
def __getitem__(self, pos):
"""返回矩阵pos位置的元素"""
r, c = pos
return self._value[r][c]
def shape(self):
"""返回矩阵的形状: (行数, 列数)"""
return len(self._value), len(self._value[0])
def row_num(self):
"""返回矩阵的行数"""
return self.shape()[0]
def col_num(self):
"""返回矩阵的列数"""
return self.shape()[1]
def size(self):
"""返回矩阵的元素个数"""
r, c = self.shape()
return r * c
__len__ = row_num
def __add__(self, other):
"""矩阵相加 返回结果"""
assert isinstance(other, Matrix) and self.shape() == other.shape(), \
"Error in adding. Shape of matrix must be same"
return Matrix([[a + b for a, b in zip(self.row_vector(i), other.row_vector(i))]
for i in range(self.row_num())])
def __sub__(self, other):
"""返回两个矩阵的减法结果"""
assert isinstance(other, Matrix) and self.shape() == other.shape(), \
"Error in subtracting. Shape of matrix must be same"
return Matrix([[a - b for a, b in zip(self.row_vector(i), other.row_vector(i))]
for i in range(self.row_num())])
def __mul__(self, k):
"""返回矩阵的数量乘结果: self * k"""
return Matrix([e * k for e in row] for row in self._value)
def __rmul__(self, k):
"""返回矩阵的数量乘结果: k * self"""
return self * k
def __truediv__(self, k):
"""返回数量除法的结果矩阵:self / k"""
return self * (1 / k)
def __pos__(self):
"""返回矩阵取正的结果"""
return 1 * self
def __neg__(self):
"""返回矩阵取负的结果"""
return -1 * self
def dot(self, other):
""" 矩阵的乘法, 与向量城 与矩阵乘"""
if isinstance(other, Vector):
# 矩阵和向量向乘
# 矩阵列 与 向量长度 数相等
assert self.col_num() == len(other), \
"Error in Matrix-Vector Multiplication."
return Vector([other.dot(self.row_vector(i)) for i in range(self.row_num())])
if isinstance(other, Matrix):
# 矩阵和矩阵相乘 self * other; (m*k) * (k*n) = (m*n)
assert self.col_num() == other.row_num(), \
"Error in Matrix-Vector Multiplication."
return Matrix([self.row_vector(i).dot(other.col_vector(j)) for j in range(other.col_num())]
for i in range(self.row_num()))
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 21:30:12 2019
@author: Tony Yang
@email: t2yang@eng.ucsd.edu
@github: erza0211064@gmail.com
Description:
Class Lidar_range deal with range filter, which crops all lidar data between given minimum and maximum.
There will be only one scan in each object.
Library used:
numpy: may be use in this problem
random: only for generate testing data
"""
import random
import numpy as np
class Lidar_range:
def __init__(self,lidar = np.zeros((0,0))):
'''
Input:
lidar: lidar data Type: numpy.ndarray, 1*N, where N is the data length between [200,1000]
Output:
self.lidar: lidar data. Type: numpy.ndarray, 1*N
self.N: length of data. Type: int, between [200,1000]
'''
#--check if input data is valid
if len(lidar.shape) != 2:
raise Exception("Must be 2D array with (1,N)")
if np.any(lidar < 0.03) or np.any(lidar > 50):
raise Exception("Range of lidar data must be between [0.03,50]")
if lidar.shape[1] < 200 or lidar.shape[1] > 1000:
raise Exception("Length of data must be between [200,1000]")
self.lidar = lidar
self.N = self.lidar.shape[1]
def range_filter(self, Min, Max):
'''
input:
Min: minimum lidar range. Type:int, between [0.03,50]
Max: maximum lidar range. Type:int, between [0.03,50]
Output:
res: lidar data after range filter. Type:numpy.ndarray, 1*N
'''
res = self.lidar
res[res >= Max] = Max
res[res <= Min] = Min
return res.ravel()
# For debug
def print_data(self):
print(len(self.lidar))
print(self.lidar.shape[0])
print(self.N)
def get_lidar(self):
return self.lidar
#--testing
if __name__ == "__main__":
#--generate data
print("generate data...")
N = 500 # number of lidar data in one scan
data_num = 10 # number of total lidar data scan
lidar_list = [] # all lidar test data
test_range = [] # result after range filter
for i in range(data_num):
a = [random.uniform(0.03,50) for i in range(N)]
lidar = np.array((a))
lidar_list.append(lidar)
lidar_list = np.array((lidar_list))
print("data generate complete...")
#--test case for range
print("test range...")
test1 = lidar_list.copy()
for i in range(data_num):
l1 = Lidar_range(lidar = test1[i,:].reshape(1,-1))
test_range.append(l1.range_filter(Min=5,Max=49))
test_range = np.array((test_range))
|
# No keyword replacement for abstract but it tells that interp. dah
# its gonna be implement in subclass and not here. daeway it works.
# thing to notice for polymorphism is that the employee
# creating an abstract base class
class Employee:
def determine_weekly_salary(self, weeklyHours, wage):
raise NotImplementedError("This method is not implemented by subclass.")
# Inherit from base class and define calculations for permanent employee
class Permanent(Employee):
#definition of method starts here
def determine_weekly_salary(self, weeklyHours, wage):
salary = 40 * wage
print(f"This employee worked for {weeklyHours} hours and the wage is {wage}")
class Contractor(Employee):
def determine_weekly_salary(self, weeklyHours, wage):
salary = 45 * wage
print(f"This Happy employee worked for {weeklyHours} hours and the wage is {wage}")
def get_employees():
some_perm_emp = Permanent()
some_cont_emp = Contractor()
both_emp = [some_perm_emp, some_cont_emp]
return both_emp
def main():
#employee = Employee()
# returns an exception.
hours = 50; wage = 70
employees = get_employees()
for emp in employees:
emp.determine_weekly_salary(hours, wage)
if __name__ == "__main__":
main()
|
# Write a Python program to replace last value of tuples in a list. Go to the editor
# Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
t1 = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
for i in range(len(t1[0])):
t1[i] = t1[i] + (100,)
print(t1)
|
# . Write a Python program to convert a given tuple of positive integers into an integer.
# Original tuple:
# (1, 2, 3)
# Convert the said tuple of positive integers into an integer:
# 123
t1 = (1, 2, 3)
s1 = ''
for i in t1:
s1 += str(i)
print(int(s1))
# another way
t1 = (1, 2, 3, 5, 5, 6)
t2 = str(t1)
s1 = "".join(t2).replace(", ", "")
print(s1[1:len(s1)-1])
# another way
t1 = (1, 2, 3)
print(int(''.join(map(str, t1))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.