text stringlengths 37 1.41M |
|---|
from Player import *
from Enemy import *
from Level import *
import random
import pygame
#Sets up a game between the AI and non-AI
class Game():
def __init__(self, screen, player=None):
""" Creates a game that contains two players and a level """
self.screen = screen
if player != None:
self.player = player
else:
self.player = None
self.enemy = None
self.level = None
self.entities = []
self.intiializeGame() #set up each game
#Update the health of both
def updateAllHealth(self):
self.player.updateHealth()
self.enemy.updateHealth()
#Add the players to the environment
def intiializeGame(self):
#Add the AI
if self.player == None:
self.player = Player(self.screen, (0,450))
self.player.rect.x = 0 # x-position
self.player.rect.y = 450 # y-position
self.level = Level_01(self.player,self.screen)
self.player.level = self.level
#Add the enemy
self.enemy = Enemy(self.screen, (800,450))
self.enemy.rect.x = 800 # x-position
self.enemy.rect.y = 450 # y-position
self.enemy.level = self.level
#Add the players to the player list for the game
self.level.player_list.add(self.player)
self.level.enemy_list.add(self.enemy)
self.entities.append(self.player)
self.entities.append(self.enemy)
self.player.setEnemy(self.enemy)
self.enemy.setEnemy(self.player)
|
from argparse import ArgumentParser
from itertools import product
import numpy as np
import points as pts
def build_parser():
parser = ArgumentParser()
parser.add_argument('--data-path', type=str, required=True)
parser.add_argument('--max-distance', type=int, default=10000)
return parser
def main():
args = build_parser().parse_args()
with open(args.data_path) as file:
data = file.read().splitlines()
points = pts.get_points(data)
minx, miny, maxx, maxy = pts.get_point_bounds(points)
max_distance = args.max_distance
area = 0
for x, y in product(range(minx, maxx + 1), range(miny, maxy + 1)):
distance = sum(
pts.manhattan_distance([x, y], point)
for point in points
)
if distance < max_distance:
area += 1
print(area)
if __name__ == '__main__':
main()
|
from argparse import ArgumentParser
def build_parser():
parser = ArgumentParser()
parser.add_argument('--data-path', type=str, required=True)
return parser
def main():
args = build_parser().parse_args()
with open(args.data_path) as file:
data = file.read().splitlines()
frequency = sum(map(int, data))
print(frequency)
if __name__ == '__main__':
main()
|
"""The Passenger class tracks who has entered the plane, at which row they are
currently, and to which row they need to get before sitting down.
Usage:
from airplane import Seat
from passenger import PassengerQueue
seat = Seat(row=10, seat=0, window_middle_aisle='window')
passenger = Passenger(seat=seat)
"""
from airplane import Seat
class Passenger(object):
def __init__(self, seat: Seat) -> None:
"""Passengers board the plane.
Args:
seat (Seat)
"""
self._seat = seat
self.current_row = None
def __lt__(self, other):
"""Passengers are ordered by their seat"""
return self._seat < other._seat
def __gt__(self, other):
"""Passengers are ordered by their seat"""
return self._seat > other._seat
@property
def row(self):
return self._seat.row
@property
def seat(self):
return self._seat.seat
@property
def arrived_at_row(self) -> bool:
return self.current_row == self.row
def board(self) -> None:
"""Sets the row counter to -1 so that the next row is row 0."""
self.current_row = -1
def move(self) -> None:
"""Moves forward 1 row."""
try:
self.current_row += 1
except TypeError:
# The passenger has not yet boarded. Skip.
pass
|
import numpy
import itertools
def queens_check(list):
result = 0 # đếm số lời giải
# kiểm tra lời giải
for k in list:
fitness = 0 # đếm số vị trí không phù hợp
for i in range(len(k) - 1):
for j in range(i + 1, len(k)):
if (k[j] == k[i]) or (k[j] == k[i] + (j - i)) or (k[j] == k[i] - (j - i)):
fitness += 1
break
if fitness != 0: break
# nếu tất cả phù hợp thì in kết quả
if fitness == 0:
result += 1
for f1 in range(len(k)):
for f2 in range(len(k)):
if f2 == k[f1]:
print('Q', end=' ')
else: print('.', end=' ')
print('')
print('---------------')
if result == 0:
print('Bài toán không có lời giải')
else:
print('Có tổng số lời giải là {0} (bao gồm đối xứng)'.format(result))
def Queen(N):
# tạo bàn cờ
# 1 0 0 0
# 0 1 0 0
# 0 0 1 0
# 0 0 0 1
# board = [0,1,2,3]
board = numpy.arange(0,N)
# hoán vị các vị trí quân trên bàn cờ
l = list(itertools.permutations(board))
# kiểm tra và in kết quả
queens_check(l)
def main():
N = int(input('Nhập số quân hậu: '))
Queen(N)
if __name__ == "__main__": main() |
# matplotlib_intro.py
"""Python Essentials: Intro to Matplotlib.
<Name> Elaine Swanson
<Class> MTH 420
<Date> 1/29/2021"""
import numpy as np
from matplotlib import pyplot as plt
# Problem 1
def var_of_means(n):
"""Construct a random matrix A with values drawn from the standard normal
distribution. Calculate the mean value of each row, then calculate the
variance of these means. Return the variance.
Parameters:
n (int): The number of rows and columns in the matrix A.
Returns:
(float) The variance of the means of each row."""
A = np.random.normal(size=(n,n))
y = np.mean(A, axis=1)
return np.var(y)
print(var_of_means(3))
print('\n')
def prob1():
"""Create an array of the results of var_of_means() with inputs
n = 100, 200, ..., 1000. Plot and show the resulting array."""
Q = np.linspace(100, 1000, 10)
V = [1]*len(Q)
for j in range(len(Q)):
V[j] = var_of_means(int(Q[j]))
plt.plot(Q, V)
return plt.show()
print(prob1())
print('\n')
# Problem 2
def prob2():
"""Plot the functions sin(x), cos(x), and arctan(x) on the domain
[-2pi, 2pi]. Make sure the domain is refined enough to produce a figure
with good resolution."""
x = np.linspace(-2*np.pi, 2*np.pi, 3000)
plt.plot(x, np.sin(x), x, np.cos(x), x, np.arctan(x))
return plt.show()
print(prob2())
print('\n')
# Problem 3
def prob3():
"""Plot the curve f(x) = 1/(x-1) on the domain [-2,6].
1. Split the domain so that the curve looks discontinuous.
2. Plot both curves with a thick, dashed magenta line.
3. Set the range of the x-axis to [-2,6] and the range of the
y-axis to [-6,6]."""
x1 = np.linspace(-2, 1, 200, endpoint = False)
x2 = np.linspace(1, 6, 200)
x2 = x2[1:]
y1 = 1/(x1-1)
y2 = 1/(x2-1)
plt.plot(x1, y1, 'm--', linewidth=4)
plt.plot(x2, y2, 'm--', linewidth=4)
plt.xlim(-2, 6)
plt.ylim(-6, 6)
return plt.show()
print(prob3())
print('\n')
# Problem 4
def prob4():
"""Plot the functions sin(x), sin(2x), 2sin(x), and 2sin(2x) on the
domain [0, 2pi].
1. Arrange the plots in a square grid of four subplots.
2. Set the limits of each subplot to [0, 2pi]x[-2, 2].
3. Give each subplot an appropriate title.
4. Give the overall figure a title.
5. Use the following line colors and styles.
sin(x): green solid line.
sin(2x): red dashed line.
2sin(x): blue dashed line.
2sin(2x): magenta dotted line."""
x = np.linspace(0, 2*np.pi, 3000)
y = np.sin(x)
z = np.sin(2*x)
ax1 = plt.subplot(221)
ax1.plot(x, y, 'g-')
ax1.set_title("ax1")
ax1.set(xlim=(0, 2*np.pi), ylim=(-2, 2))
ax2 = plt.subplot(222)
ax2.plot(x, z, 'r--')
ax2.set_title("ax2")
ax2.set(xlim=(0, 2*np.pi), ylim=(-2, 2))
ax3 = plt.subplot(223)
ax3.plot(x, 2*y, 'b--')
ax3.set_title("ax3")
ax3.set(xlim=(0, 2*np.pi), ylim=(-2, 2))
ax4 = plt.subplot(224)
ax4.plot(x, 2*z, 'm:')
ax4.set_title("ax4")
ax4.set(xlim=(0, 2*np.pi), ylim=(-2, 2))
plt.suptitle('All Subplots')
return plt.show()
print(prob4())
print('\n')
# Problem 6
def prob6():
"""Plot the function f(x,y) = sin(x)sin(y)/xy on the domain
[-2pi, 2pi]x[-2pi, 2pi].
1. Create 2 subplots: one with a heat map of f, and one with a contour
map of f. Choose an appropriate number of level curves, or specify
the curves yourself.
2. Set the limits of each subplot to [-2pi, 2pi]x[-2pi, 2pi].
3. Choose a non-default color scheme.
4. Add a colorbar to each subplot."""
x = np.linspace(-2*np.pi, 2*np.pi, 1000)
y = np.linspace(-2*np.pi, 2*np.pi, 1000)
X, Y = np.meshgrid(x, y)
g = (np.sin(X)*np.sin(Y))/(X*Y)
plt.subplot(121)
plt.pcolormesh(X, Y, g, cmap ='cool', shading='auto')
plt.colorbar()
plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-2*np.pi, 2*np.pi)
plt.subplot(122)
plt.contour(X, Y, g, 7, cmap ='ocean')
plt.colorbar()
plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-2*np.pi, 2*np.pi)
plt.suptitle('Heat map and Contour')
return plt.show()
print(prob6())
print('\n')
if __name__ == "__main__":
print("Lab 4 complete.") |
# This defines the base object that all classes inherit from
class RDObject(object):
def __init__(self, elevation_bottom = 0):
self.elevation_bottom = elevation_bottom
@property
def start_stage(self):
return self.elevation_bottom
@property
def start_stage_elevation(self):
return self.start_stage
class RDCircle(RDObject):
'''
This objects contains the methods typical for circular objects
'''
def __init__(self, elevation_bottom = 0, diameter_in = None, diameter_ft = None ):
super().__init__(elevation_bottom = elevation_bottom)
if diameter_ft:
self.set_diameter(feet = diameter_ft)
elif diameter_in:
self.set_diameter(inches = diameter_in)
def set_diameter(self, inches = None, feet = None):
if inches:
self._diameter_inches = inches
self._diameter_feet = inches / 12
return True
elif feet:
self._diameter_feet = feet
self._diameter_inches = feet * 12
return True
return False
@property
def diameter_feet(self):
return self._diameter_feet
@property
def radius_feet(self):
return self._diameter_feet / 2
|
# Module 1 Required Coding Activity
# Introduction to Python (Unit 2) Fundamentals
# This Activity is intended to be completed in the jupyter notebook, Required_Code_MOD1_IntroPy.ipynb, and then pasted into the assessment page that follows.
# The link to the .ipynb Jupyter Notebook files are in the last lesson of section 0 of module 1
# This is an activity from the Jupyter Notebook Practice_MOD01_IntroPy.ipynb which you may have already completed.
# Important Assignment Requirements
# NOTE: This program requires print output and using code syntax used in module 1 such as keywords for/in (iteration), input, if, else, .isalpha() method, .lower() or .upper() method
# Program: Words after "G"/"g"
# Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
#Sample input:
# enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with all your heart
# Sample output:
# WHERESOEVER
# YOU
# WITH
# YOUR
# HEART
# split the words by building a placeholder variable: word
# loop each character in the input string
# check if character is a letter
# add a letter to word each loop until a non-alpha char is encountered
# if character is alpha
# add character to word
# non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
# else
# check if word is greater than "g" alphabetically
# print word
# set word = empty string
# or else
# set word = empty string and build the next word
# Hint: use .lower()
# Consider how you will print the last word if it doesn't end with a non-alpha character like a space or punctuation?
# [] create words after "G"
# sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)//
quote = input("enter a 1 sentence quote, non-alpha separate words")
word = ''
for ltr in quote:
if ltr.isalpha():
word = word+ltr
else:
if word.lower()>='h':
print(word.upper())
word = ''
else:
word = ''
|
# -*- coding:utf-8 -*-
# python2.7.9
"""
ʵһһַеĿո滻ɡ%20磬ַΪWe Are Happy.滻ַ֮ΪWe%20Are%20Happy
"""
class Solution:
# s Դַ
def replaceSpace(self, s):
# write code here
words = s.split(' ')
g = lambda x:'%20' if x == ' 'else x
return '%20'.join([g(i) for i in words])
if __name__ == '__main__':
s = Solution()
print s.replaceSpace('hello world')
|
from datetime import datetime
# Función para devolver columna de fecha y hora
def fecha_hora(df):
'''
Separa la indormacion de fecha y hora que en todos los df estan juntas como string
Argumentos
----------
df: el dataframe de cada año de recorridos de bicis
'''
# Se splitea la columna en dos: fecha y hora que en todos los df estan juntas como str
fecha_hora = df['bici_Fecha_hora_retiro'].str.split(' ', expand=True)
# Se almacena en un nuevo df
fecha_hora.columns = ['Fecha','Hora']
return fecha_hora
# Función para devolver dia de la semana
def obtener_dia_semana(fecha):
'''
Devuelve el dia de la semana a partir de la fecha
Argumentos
----------
fecha: columna del df, para usarla hay que mapearla porque strptime no toma series
'''
return datetime.strptime(fecha,'%Y-%m-%d').weekday()
# Reemplaza numero de dia por nombre. Se le pasa cualquier de los dataframes
def nombre_dia(df):
dia = df.replace({0:'lunes', 1:'martes', 2:'miercoles', 3:'jueves', 4:'viernes', 5:'sabado', 6:'domingo'})
return dia |
#creating 5*5 matrix with initial value 0
def create_matrix(row,column,initial_value):
#matrix=[[initial_value]*column]*row
matrix=[[initial_value for i in range(5)] for j in range(5)]
return matrix
#returns the index of given element
def find_index(matrix,letter):
for i in range(5):
for j in range(5):
if matrix[i][j]==letter:
return i,j
#encrpyting plaintext
def encryption(matrix,plainText):
cipherText=[]
#while paring if same pair has same element adding x between them
for i in range(0,len(plainText),2):
if(i<len(plainText)-1):
if plainText[i]==plainText[i+1]:
plainText=plainText[:i+1]+'x' +plainText[i+1:]
#adding x if odd no of element
if len(plainText)%2!=0:
plainText=plainText[:]+'x'
#replacing j with i
if 'j' in plainText:
plainText=plainText.replace('j','i')
#finding row and column
for s in range(0,len(plainText),2):
row1,column1=find_index(matrix,plainText[s])
row2,column2=find_index(matrix,plainText[s+1])
if row1==row2:
cipherText.append(matrix[row1][(column1+1)%5])
cipherText.append(matrix[row2][(column2+1)%5])
elif column1==column2:
cipherText.append(matrix[(row1+1)%5][column1])
cipherText.append(matrix[(row2+1)%5][column2])
else:
cipherText.append(matrix[row1][column2])
cipherText.append(matrix[row2][column1])
print("\nCipher Text: "+''.join(cipherText))
#decrypting cipherText
def decryption(matrix,cipherText):
plainText=[]
#finding row and column
for s in range(0,len(cipherText),2):
row1,column1=find_index(matrix,cipherText[s])
row2,column2=find_index(matrix,cipherText[s+1])
if row1==row2:
plainText.append(matrix[row1][(column1-1)%5])
plainText.append(matrix[row2][(column2-1)%5])
elif column1==column2:
plainText.append(matrix[(row1-1)%5][column1])
plainText.append(matrix[(row2-1)%5][column2])
else:
plainText.append(matrix[row1][column2])
plainText.append(matrix[row2][column1])
print("\nPlain Text: "+''.join(plainText))
key=input("\nEnter your key: ")
result=[]
# checking if key has repeated alphabet
for i in key:
if i in result:
if i=='j':
result.append(i)
else:
result.append(i)
alphabets='abcdefghijklmnopqrstuvwxyz'
alphabets=list(alphabets)
# adding remaing alphabets
for i in alphabets:
if i in result:
pass
else:
if i=='j':
pass
else:
result.append(i)
matrix=create_matrix(5,5,0)
#changing result to 5*5 matrix
k=0
for i in range(0,5):
for j in range(0,5):
matrix[i][j]=result[k]
k=k+1
print(matrix)
choice = int(input("\nEnter your choice:\n1. Encrypt\n2. Decrypt\n3. Exit\n"))
if choice == 1:
plainText=input("\nEnter plain text: ")
encryption(matrix,plainText)
elif choice == 2:
cipherText=input("\nEnter cipher text: ")
decryption(matrix,cipherText)
elif choice == 3:
exit()
else:
print("Is that a MISCLICK? Choose a correct Number.")
|
import argparse
import re
from typing import List
parser = argparse.ArgumentParser(description='Run an Advent of Code program')
parser.add_argument(
'input_file', type=str, help='the file containing input data'
)
args = parser.parse_args()
input_data: List = []
with open(args.input_file) as f:
for line in f.readlines():
m = re.match(r"([0-9]+)-([0-9]+) ([a-zA-Z]): ([a-zA-Z]+)", line)
input_data.append(
(
int(m.group(1)), # type: ignore
int(m.group(2)), # type: ignore
m.group(3), # type: ignore
m.group(4), # type: ignore
)
)
# Part 1
good_passwords = 0
for (lower_bound, upper_bound, letter, password) in input_data:
occurrences = password.count(letter)
if int(lower_bound) <= occurrences <= int(upper_bound):
good_passwords += 1
print(f'Part 1 - Good Passwords: {good_passwords}')
# Part 2
good_passwords = 0
for (lower_index, upper_index, letter, password) in input_data:
# Use XOR (`^`) to get one and only one
if (password[lower_index - 1] == letter) ^ (
password[upper_index - 1] == letter
):
good_passwords += 1
print(f'Part 2 - Good Passwords: {good_passwords}')
|
import argparse
from typing import List, Set
parser = argparse.ArgumentParser(description='Run an Advent of Code program')
parser.add_argument(
'input_file', type=str, help='the file containing input data'
)
args = parser.parse_args()
input_data: List = []
with open(args.input_file) as f:
input_data = [line for line in f.read().splitlines()]
letters: Set[str] = set()
groups_of_letters = []
for line in input_data:
# New record?
if line == '' and letters:
groups_of_letters.append(letters)
letters = set()
for letter in line:
letters.add(letter)
groups_of_letters.append(letters)
letter_count = sum([len(x) for x in groups_of_letters])
print(f'Part 1: {letter_count}')
letters = set()
groups_of_people = []
people: List[Set[str]] = []
for line in input_data:
# New record?
if line == '' and people:
groups_of_people.append(people)
letters = set()
people = []
continue
people.append(set([letter for letter in line]))
groups_of_people.append(people)
letter_count = sum(
[len(x) for x in [set.intersection(*group) for group in groups_of_people]]
)
print(f'Part 2: {letter_count}')
|
#FUNÇÕES (FUNCTION)
#EXEMPLO SEM O USO DE FUNÇÃO :(
rappers_choice = ["L7NNON", "KB", "Trip Lee", "Travis Scott", ["Lecrae", "Projota", "Tupac"], "Don Omar"]
rappers_country = {"BR":["Hungria", "Kamau", "Projota", "Mano Brown", "Luo", "L7NNON"],
"US":["Tupac", "Drake", "Eminem", "KB", "Kanye West", "Lecrae", "Travis Scott", "Trip Lee"]}
for rp in rappers_choice:
if isinstance(rp, list):
for rp_one in rp:
if rp_one in rappers_country["BR"]:
print(f"Rapper BR: {rp_one}")
elif rp_one in rappers_country["US"]:
print(f"Rapper US: {rp_one}")
else:
print(f"Rapper not found in lists: {rp_one}")
else:
if rp in rappers_country["BR"]:
print(f"Rapper BR: {rp}")
elif rp in rappers_country["US"]:
print(f"Rapper US: {rp}")
else:
print(f"Rapper not found in lists: {rp}") |
# Scrabble: Freeform project using dictionaries
# credit: Codecademy (Python 3)
# The focus of this project is to process data from a game of scrabble, using dictionaries to organize players, words, and points.
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
# Update the letters list to contain lowercase letters
letters += [letter.lower() for letter in letters]
points *= 2
# Using list comprehension, create a dictionary that has key value pairs of letters and points.
# Make sure to add the infamous blank scrabble tile.
letter_to_points = {key:value for key, value in zip(letters, points)}
letter_to_points[" "] = 0
print(letter_to_points)
# Create a function that will take in a word and return the point value of that word.
# If the letter is not in the dictionary, add 0 to the point total.
def score_word(word):
point_total = 0
for letter in word:
point_total += letter_to_points.get(letter,0)
return(point_total)
# Test the function.
brownie_points = score_word("BROWNIE")
print(brownie_points)
# Create a dictionary that maps scrabble players to a list of words they have played.
player_to_words = {
"player1": ["BLUE", "TENNIS", "EXIT"],
"wordNerd": ["EARTH", "EYES", "MACHINE"],
"Lexi Con": ["ERASER", "BELLY", "HUSKY"],
"Prof Reader": ["ZAP", "COMA", "PERIOD"]
}
# Create an empty dictionary to track the points for each player.
player_to_points = {}
# Iterate through the player_to_words dictionary and assign each player to player and each list of words to words.
# Create another loop that calculates the value of each player's words and adds it to a points variable.
def update_point_totals():
for player, words in player_to_words.items():
player_points = 0
for word in words:
player_points += score_word(word)
player_to_points[player] = player_points
update_point_totals()
# Create a function that takes in a player and word and adds it to the player_to_words dictionary
def play_word(player, word):
player_to_words[player].append(word)
print(player_to_words)
# Turn nested loops into a function that can be called any time a new word is played - addition line 43
|
from random import randint
choices=["rock", "paper", "scissors"]
player_lives = 5
computer_lives = 5
computer=choices[randint(0,2)]
player = False
def winorlose(status):
print("called win or lose function", status, "\n")
print("You", status, "! Would you like to play again?")
choice = input("Y / N? ")
if choice == "Y" or choice == "y":
global player_lives
global computer_lives
global player
global computer
player_lives = 5
computer_lives = 5
player = False
computer = choices[randint(0, 2)]
elif choice == "N" or choice == "n":
print("You chose to quit. Better luck next time!")
exit()
else:
print("Make a valid choice. Yes or no!")
while player is False:
print("========================================")
print("Computer Lives:", computer_lives, "/5")
print("Player Lives:", player_lives, "/5")
print("========================================")
print("Choose your weapon!\n")
player=input("choose rock, paper or scissors: \n")
if player == computer:
print("tie, no one wins! try again")
elif player == "quit":
print("you chose to quit, quitter.")
exit()
elif player == "rock":
if computer == "paper":
print("You lose!", computer, "covers", player, "\n")
player_lives = player_lives -1
else:
print("You won!", player, "smashes", computer, "\n")
computer_lives = computer_lives -1
elif player == "paper":
if computer == "scissors":
print("You lose!", computer, "cuts", player, "\n")
player_lives = player_lives -1
else:
print("You won!", player, "covers", computer, "\n")
computer_lives = computer_lives -1
elif player == "scissors":
if computer == "rock":
print("You lose!", computer, "smashes", player, "\n")
player_lives = player_lives -1
else:
print("You won!", player, "cuts", computer, "\n")
computer_lives = computer_lives -1
if player_lives is 0:
winorlose("lost")
elif computer_lives is 0:
winorlose("won")
else:
player = False
computer=choices[randint(0,2)]
|
# https://leetcode.com/problems/sliding-window-median/description/
import bisect
class Solution(object):
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
window = sorted(nums[:k])
res = [(window[k / 2] + window[(k - 1) / 2]) / 2.0]
for i in range(k, len(nums)):
del window[bisect.bisect_left(window, nums[i - k])]
bisect.insort(window, nums[i])
res.append((window[k / 2] + window[(k - 1) / 2]) / 2.0)
return res
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
fast, slow, entr = head, head, head
while (fast.next and fast.next.next and slow.next):
fast = fast.next.next
slow = slow.next
if fast == slow:
while(slow != entr):
slow = slow.next
entr = entr.next
return entr
return None
|
"""
01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0
for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
"""
from collections import deque
import sys
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
queue = deque()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
queue.append((i, j))
else:
matrix[i][j] = sys.maxsize
while queue:
i, j = queue.popleft()
# 设置临近点
for dx, dy in zip((1, -1, 0, 0), (0, 0, 1, -1)):
ny = i + dy
nx = j + dx
if ny < 0 or ny >= m or nx < 0 or nx >= n:
continue
value = matrix[ny][nx]
if value <= matrix[i][j] + 1: # 更新过, 且更小(近)
continue
# 加入队列继续处理
queue.append((ny, nx))
# 更新, 临近点 + 1
matrix[ny][nx] = matrix[i][j] + 1
return matrix
# matrix = [
# [0],
# [0],
# [0],
# [0],
# [0]
# ]
matrix = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 1]
]
s = Solution()
list = s.updateMatrix(matrix)
print(list)
|
# The n-queens puzzle is the problem of placing n queens
# on an n×n chessboard such that no two queens attack each other.
# Given an integer n, return all distinct solutions to the n-queens puzzle.
# Each solution contains a distinct board configuration of the n-queens' placement,
# where 'Q' and '.' both indicate a queen and an empty space respectively.
# For example,
# There exist two distinct solutions to the 4-queens puzzle:
# [
# [".Q..", // Solution 1
# "...Q",
# "Q...",
# "..Q."],
# ["..Q.", // Solution 2
# "Q...",
# "...Q",
# ".Q.."]
# ]
class Solution(object):
def __init__(self):
self.check_set = set() # 0: col, 1: dig(minus), 2:dig(plus)
self.res = []
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
self.dfs(n, 0, [])
return [[ '.'*i + 'Q' + '.'*(n-i-1) for i in r] for r in self.res]
def dfs(self, n, row, cur_res):
if row >= n:
self.res.append(cur_res)
return
for i in range(n):
if (0, i) in self.check_set or (1, row - i) in self.check_set or (2, row + i) in self.check_set:
continue
self.check_set.add((0, i))
self.check_set.add((1, row-i))
self.check_set.add((2, row+i))
self.dfs(n, row + 1, cur_res + [i])
self.check_set.remove((0, i))
self.check_set.remove((1, row-i))
self.check_set.remove((2, row+i))
# class Solution(object):
# def solveNQueens(self, n):
# """
# :type n: int
# :rtype: List[List[str]]
# """
# mask = (1 << n) - 1
# st = {1 << i : '.' * (n - i - 1) + 'Q' + '.' * i for i in range(n)}
# s = [0 for _ in xrange(n)] # selection
# p = [0 for _ in xrange(n)] # not tried
# x = [0 for _ in xrange(n)] # sum (s[i]), up to down
# y = [0 for _ in xrange(n)] # sum (s[i] << n + ~i), right up to left down
# z = [0 for _ in xrange(n)] # sum (s[i] << i), left up to right down
# res = []
# i = 0
# p[i] = mask
# while i >= 0:
# s[i] = p[i] & -p[i]
# if s[i] == 0:
# i -= 1
# else:
# p[i] &= ~s[i]
# if i == n - 1:
# res.append(map(lambda x: st[x], s))
# else:
# x[i + 1] = x[i] | s[i]
# y[i + 1] = y[i] | s[i] << n + ~i
# z[i + 1] = z[i] | s[i] << i
# i += 1
# p[i] = mask & ~(x[i] | y[i] >> n + ~i | z[i] >> i)
# return res
if __name__ == '__main__':
print(Solution().solveNQueens(4))
|
"""
Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
count = len(nums)
if count == 1:
return nums[0]
currentMax = minProduct = maxProduct = nums[0]
for i in range(1, count):
number = nums[i]
if number < 0:
minProduct, maxProduct = maxProduct, minProduct
maxProduct = max(number, maxProduct * number)
minProduct = min(number, minProduct * number)
currentMax = max(maxProduct, currentMax)
return currentMax
# class Solution(object):
# def maxProduct(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# if not nums:
# return 0
#
# count = len(nums)
# if count == 1:
# return nums[0]
#
# currentMax = minProduct = maxProduct = preMin = preMax= nums[0]
# for number in nums[1:]:
# maxProduct = max(number, max(preMin * number, preMax * number))
# minProduct = min(number, min(preMin * number, preMax * number))
# currentMax = max(maxProduct, currentMax)
# preMin, preMax = minProduct, maxProduct
# return currentMax
nums = [2, 3, -5, 0, 4, 6, -8, 3, -1]
s = Solution()
maxProduct = s.maxProduct(nums)
print(maxProduct)
|
import csv
import math
file = open('election_data.csv', mode='r')
#convert to dictionary with csv reader library
#csvdat = csv.DictReader(dat)
csvdat = csv.reader(file)
rowcount = 0
total = 0.0
votes = {}
#no clue why this takes a user programmed loop
for row in csvdat:
if row[0] == "Voter ID":
continue
r1 = int(row[0])
total = total + r1
if row[2] in votes:
votes[row[2]] = votes[row[2]] + 1
else:
votes[row[2]] = 1
rowcount += 1
winner = ["", 0]
f = open("results.txt", mode='w')
print("=========================Election Results=============================")
f.write("=========================Election Results=============================\n")
print("Totes Votes: " + str(rowcount))
f.write("Totes Votes: " + str(rowcount)+"\n")
print("-----------------------------------------------------------------------")
f.write("-----------------------------------------------------------------------\n")
for cand in votes:
print(cand + ": " + str(round((votes[cand] /rowcount)*100, 2)) + "% ("+ str(votes[cand])+ ")")
f.write(cand + ": " + str(round((votes[cand] /rowcount)*100, 2)) + "% ("+ str(votes[cand])+ ")\n")
#print(votes)
print("------------------------------------------------------------------------")
f.write("------------------------------------------------------------------------\n")
for cand in votes:
if votes[cand] > winner[1]:
winner[0] = cand
winner[1] = votes[cand]
print("Winner: " + winner[0])
f.write("Winner: " + winner[0]+"\n")
print("------------------------------------------------------------------------")
f.write("------------------------------------------------------------------------\n")
|
class Movie():
def info(self):
print("moive name:",self.name)
print("hero is:",self.hero)
print("director is",self.director)
print("rating is:",self.rating)
m=Movie()
m.name="ls"
m.hero="nc"
m.director="sk"
m.rating=100
m.info() |
#setters and getters
class Student:
def setName(self,name):
self.name=name
def setMarks(self,marks):
self.marks=marks
def getName(self):
return self.name
def getMarks(self):
return self.marks
n = int(input("enter number of students: "))
for i in range(n):
s=Student()
name=input("Enter the name: ")
marks=input("Enter the marks: ")
s.setName(name)
s.setMarks(marks)
print("Name of the student",s.getName())
print("Marks of ",s.getName(),"is" ,s.getMarks())
|
import mariadb
con=mariadb.connect(
user="root",
password="password",
host="127.0.0.1",
port=3306,
autocommit=True,
database='schools'
)
cursor=con.cursor()
"""cursor.execute("SELECT * FROM COMPUTERS WHERE FACULTY_NAME='ANIL'")"""
'''cursor.execute("select * from computers where depart_id =1 ")
cursor.execute("SELECT * FROM COMPUTERS WHERE FACULTY_NAME LIKE '%ac'")'''
cursor.execute("SELECT * FROM COMPUTERS WHERE FACULTY_NAME LIKE '_a_%'")
'''cursor.execute("SELECT * FROM COMPUTERS ORDER BY YEAR DESC LIMIT 2 OFFSET 1")''' # DEFAULT IS ASCENDING ORDER
SELECT * FROM students;
SELECT s_id,s_name FROM students ORDER BY s_id;
SELECT s_year,COUNT(*) FROM students GROUP BY s_year DESC ;
SELECT * FROM students HAVING s_year=3;
a=cursor.fetchall()
print(a)
|
## unziping
from zipfile import *
f=ZipFile("file1.zip","r",ZIP_STORED)
# if you the file name
f1=open("names.txt","r")
data=f1.read()
print(data)
# if you don't know the file names
names=f.namelist()
for i in names:
print("file name: ",i)
print("content of file is ")
f1=open(i,"r")
data=f1.read()
print(data) |
class Book:
def __init__(self,pages):
self.pages=pages
def __add__(self,other):
print("magic add method is calling")
total= self.pages+other.pages
return Book(total)
def __str__(self):
print("Str method is calling ")
return str(self.pages)
b=Book(200)
b1=Book(300)
b2=Book(400)
b3=Book(500)
print(b+b1+b2+b3)
# number of times magic method called is equal to number of number of opertator symbols
# like (+,-,*) |
# static variable is same to all the obbjects
class Team():
# 1:
game="cricket"
def __init__(self,name,team,country):
self.name=name
self.team=team
self.country=country
Test.
def about(self):
print("player_name:",self.name)
print("team",self.team)
print("country:",self.country)
#accessing with in the class so we need to use self
print("game",self.game)
t=Team("virat","rcb","india")
t.about()
##accessing using object reference
print(t.game)
##accessing using class
print(Team.game)
print(t.__dict__) |
import os
fname=input("enter the file name: ")
a=os.path.isfile(fname)
if a==True:
f=open(fname,"r+")
list=f.readlines()
lcount=0
wcount=0
ccount=0
for i in list:
lcount=lcount+len(list)
ccount=ccount+len(i)
words=i.split()
wcount=wcount+len(words)
print("number of lines",lcount)
print("number of words",wcount)
print("number of char",ccount)
else:
print("sorry")
f.close() |
#f=open("file.md","r")
try:
fname=input("enter the name of the file you want to open: ")
mode=input("enter the mode in which you want to open the file")
f=open(fname,mode)
n=int(input("enter the number of line you want to print: "))
except ValueError as msg:
print("enter the integers only ",msg)
except BaseException as msg:
print("The number should be in limit: ",msg)
else:
print("thanks for entering correct number")
for i in range(n):
data=f.readline()
print(i,data)
finally:
f.close()
|
a=10
b=2
print(a+b," addition")
print(a-b,"substraction")
print(a/b,"division")
print(a%b,"modulo division")
print(a**b,"power or exponential")
print(a//b,"floor division")
|
## composition or HAS-A-RELATION
class Engine:
a=10
def __init__(self):
b=100
print("Engine function")
def test(self):
print("successfully tried")
class car:
def __init__(self):
self.engine=Engine()
self.m2()
def m2(self):
print(Engine.a)
print(self.engine.test())
c=car()
|
def checking(a):
if a%2==0:
print(a,"is a even number")
else:
print(a,"is a odd number")
checking(8647)
checking(7) |
#with multithreading
from threading import *
import time
def double(numbers):
for i in numbers:
print("double: ",2*i)
def square(numbers):
for i in numbers:
print("square: ",i**i)
numbers=[1,2,3,4,5,6]
begintime=time.time()
t1=Thread(target=double,args=(numbers,))
t2=Thread(target=double,args=(numbers,))
t1.start()
t2.start()
t1.join()
t2.join()
endtime=time.time()
print("total time: ",endtime-begintime) |
class X:
a=10
def __init__(self):
self.b=100
def m1(self):
print("this is m1 from class X")
class Y:
c=20
def __init__(self):
self.d=200
def m2(self):
x=X()
print(x.a)
print(x.b)
x.m1()
print(self.c)
print(self.d)
print("this is m2 from class y")
y=Y()
y.m2() |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 18 20:19:20 2016
@author: Rahul Patni
"""
import random
class Node():
def __init__(self, x, y):
self.next = None
self.x = x
self.y = y
self.hit = 0
self.visited = 0
self.next = None
def checkOver(self):
if self.x >= 8 or self.y < 0 or self.x < 0 or self.y >= 8:
return True
return False
class Stack():
def __init__(self):
self.head = None
self.total = 0
def push(self, node):
if self.total == 0:
self.head = node
self.total += 1
return
node.next = self.head
self.head = node
self.total += 1
def pop(self):
if self.total == 0:
print "cannot remove from empty stack"
return
toRet = self.head
self.head = self.head.next
toRet.next = None
self.total -= 1
return toRet
def main():
s = Stack()
for i in range(20):
x = random.randint(0, 7)
y = random.randint(0, 7)
print x, y
n = Node(x, y)
s.push(n)
print s.total
print "remooving"
while s.total != 0:
curr = s.pop()
if curr != None:
print curr.x, curr.y
main()
|
def fibonacci(n):
'''input: from distinct_list import distinct_list
out: fibonaccis sequence'''
try:
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
except exception as e:
raise ValueError()
|
class Math:
@staticmethod
def min(first, last):
if first > last:
return last
return first
@staticmethod
def max(first, last):
if first > last:
return first
return last
class Employee:
annual_raise = 1000
def __init__(self, imie, nazwisko):
self.imie = imie
self.nazwisko = nazwisko
def __str__(self):
return 'Imie: {}, nazwisko: {}, roczna podwyzka: {}'.format(self.imie, self.nazwisko, self.annual_raise)
def __add__(self, other):
emp = Employee(self.imie + other.imie, self.nazwisko+other.nazwisko)
return emp
@classmethod
def change_annual_raise(cls, new_raise):
cls.annual_raise = new_raise
@staticmethod
def nakrzycz():
print('Jestes guuupi!!!!!!!')
@classmethod
def initialise_with_raise(cls, imie, nazwisko, new_raise):
# alternatywny konstruktor
employee = cls(imie, nazwisko)
employee.annual_raise = new_raise
return employee
print(max(12, 10))
# Employee.nazwisko = 'Rutka'
wiktor = Employee('wiktor', 'rutka')
print(wiktor)
#alternatywny konstruktor
konrad = Employee.initialise_with_raise('konrad', 'zajac', 4000)
print(konrad)
anna = Employee.initialise_with_raise('anna', 'hawryluk', 12000)
print(anna)
klaudia = Employee('klaudia', 'schiffer')
print(klaudia)
Employee.nakrzycz()
|
class Animal:
legs = None
head = None
eyes = 2
_max_speed = 12
def __init__(self, legs: list = None):
print('init invoked')
self.legs = []
if legs:
self.legs = legs
self.speed = 0
self.eyes = 3
def run(self):
self.speed = 10
def faster(self, increment: int = 1):
if not self.speed >= self._max_speed:
self.speed += increment
return
self.speed = self._max_speed
def slower(self):
self.speed -= 1
def stop(self):
self.speed = 0
print(Animal.eyes)
dog = Animal()
dog.legs.append('left')
dog.legs.append('right')
dog.run()
dog.faster(increment=2)
# dog.faster()
# dog.speed = 17
# dog.faster()
dog.legs.append('tylna lewa')
print(dog.speed)
cat = Animal(legs = ['przednia prawa', 'przednia lewa', 'tylna prawa'])
print(cat.legs)
Animal.legs
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#########################################################################
# File Name: testiterator.py
# Author: Wang Biwen
# mail: wangbiwen88@126.com
# Created Time: 2016.03.14
#########################################################################
class TestIterator(object):
value = 0
def next(self):
self.value += 1
if self.value > 10:
raise StopIteration
return self.value
def __iter__(self):
return self
if __name__ == '__main__':
ti = TestIterator()
print list(ti)
|
# Program : Movie Search App
# Author : David Velez
# Date : 07/18/18
# Description: Movie Searching App running against movie_service.talkpython.fm
# that returns a list of movies based upon user search input
# Learned from Michael Kennedy's Python Jump Start Training Videos
# Imports
import movie_svc
import requests.exceptions
# Main Function
def main():
print_header()
search_event_loop()
# Print the Header
def print_header():
print("------------------------")
print(" Movie Search App")
print("------------------------")
print()
# Search Logic
def search_event_loop():
search = "ONCE_THROUGH_LOOP"
while search != "x":
try:
search = input("Movie search text (x to exit): ")
if search != "x":
results = movie_svc.find_movies(search)
print("Found {} results.".format(len(results)))
for r in results:
print("{} -- {}".format(
r.year, r.title
))
print()
except ValueError:
print("Error: Search text is required")
except Exception as requests.exceptions.ConnectionError as ce:
print("Error: Your network is down.")
except Exception as x:
print("Unexpected error. Details: {}".format(x))
print("exiting...")
# Main
if __name__ == "__main__":
main()
|
input_string = "abcd"
purmutations_set = set()
def list_to_str(string):
permutation = ''
for s in string:
permutation = permutation + s
return permutation
def permute(j, input_string, length):
for i in range(j, length):
string = list(input_string)
string[j], string[i] = input_string[i], input_string[j]
purmutations_set.add(list_to_str(string))
permute(j+1, list_to_str(string), length)
permute(0, input_string, len(input_string))
import math
print(math.factorial(len(input_string)))
permutations_list = []
for permutation in purmutations_set:
permutations_list.append(permutation)
permutations_list.sort()
for i in range(len(permutations_list)):
print(f'{i+1} {permutations_list[i]}')
|
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
1964 : "ferrari",
}
'''
for item in thisdict:
print(item, end='\t')
print(thisdict[item])
'''
item = 1964
if 1964 in thisdict:
print(thisdict[item])
my_dict = {k:k**k for k in range(10)}
for item in my_dict:
print(item, end='\t')
print(my_dict[item]) |
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return self.first + '.' + self.last + '@email.com'
@property
def fullname(self):
return f'{self.first} {self.last}'
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
@fullname.deleter
def fullname(self):
self.first = None
self.last = None
emp_1 = Employee('John', 'Smith')
emp_1.fullname = 'Jill Don'
print(emp_1.fullname)
print(emp_1.email)
print()
emp_1.first = 'Jack'
emp_1.last = 'Barber'
print(emp_1.fullname)
print(emp_1.email)
print()
del emp_1.fullname
print(emp_1.first) # None
print(emp_1.last) # None |
def square(x):
return x * x
def my_map(func, arg_list):
results = []
for arg in arg_list:
results.append(func(arg))
return results
squares = my_map(square, [1,2,3,4,5])
for square in squares:
print(square) |
from typing import List
from itertools import permutations
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = nums.copy()
temp.sort()
perm = permutations(temp, len(nums))
perm_list = list(perm)
print(set(perm_list))
length = len(perm_list)
i = 0
while i < length:
are_equal = True
permutation = list(perm_list[i])
#print(permutation)
#print(nums)
for j in range(len(nums)):
if permutation[j] != nums[j]:
are_equal = False
break
if are_equal:
break
i += 1
#print(i)
index_to_copy = i + 1
if index_to_copy == length:
index_to_copy = 0
result_list = perm_list[index_to_copy]
#print(result_list)
index = 0
for i in result_list:
nums[index] = i
index += 1
print(nums)
ob = Solution()
nums = [1,5,1]
ob.nextPermutation(nums)
#print(nums) |
str_to_float = ['2.1', '2.3', '7,5', '$12.12', '8.9', '5%', '33.1', '33#1']
floats = []
for s in str_to_float:
try:
floats.append(float(s))
except:
floats.append(None)
print('exception')
print (floats)
def adder(x, y):
try:
z = x+y
except TypeError as target:
return ('cannot add these types together')
else:
return ('result is:', z)
print (adder(5,7))
print (adder(5,"7"))
def no_four(number):
if number == 4:
raise ValueError('No fours allowed!!')
else:
print('Number:', number)
no_four(2)
print ("===========Knowledge Check===========")
def compare(a, b):
try:
a_greater = (a > b)
except:
a_greater = None
b_greater = None
else:
b_greater = (b > a)
finally:
print(a_greater, b_greater)
compare(10,11)
print ("===========Knowledge Check===========")
def positive_only(a, b):
output = a + b
if output >= 0:
return output
else:
# Your code here. to throw an valueError
raise ValueError
#positive_only(10,-25)
print ("===========Knowledge Check===========")
def int_checker(a, b):
try:
if isinstance(a, int) and isinstance(b, int):
print('both integers')
else:
raise ValueError
except:
print('error occurred')
else:
print('no error occurred!')
finally:
print('function completed')
int_checker(5,6)
int_checker('5',6)
print ("===========Knowledge Check===========")
def divider(a, b):
try:
c = a/b
# else:
# print('divided:', c)
except:
print('could not divide numbers')
divider(10, 2)
|
# 1_5
print("chaotic function")
x = eval(input("Number between 0 and 1: "))
n = eval(input("how often? "))
for i in range(n):
x = 3.9 * x * (1-x)
print(x)
|
def merge_sort0(a: list, b: list):
""""Сортировка слиянием 2-х массивов(списков)"""
c = [0]*(len(a)+len(b))
i = k = n = 0 # инициализируем 3 счетчика
while i < len(a) and k < len(b):
if a[i] <= b[k]:
c[n] = a[i]
i += 1
n += 1
else:
c[n] = b[k]
k += 1
n += 1
"Если один из массивов опустел"
while i < len(a):
c[n] = a[i]
i += 1
n += 1
while k < len(b):
c[n] = b[k]
k += 1
n += 1
print (c)
#Рекурсивная функция
def merge_sort1(a):
"""сортировка списка а методом слияния"""
if len(a) <= 1:
return
middle = len(a)//2
left = [a[i] for i in range(0, middle)]
right = [a[i] for i in range(middle, len(a))]
merge_sort1(left)
merge_sort1(right)
c = merge_sort0(left, right)
a = c[:]
print(a)
def test_merge_sort0(sort_algorithm):
print("testcase#1: ", end=" ")
a = [1, 9, 12]
b = [3, 11]
c_sorted = [1, 3, 9, 11, 12]
sort_algorithm(a, b)
print("Ok" if c_sorted == merge_sort1(a, b) else "Fail")
def test_merge_sort1(sort_algorithm):
print("testcase#0 : ", end=" ")
a = [1, 9, 12, 3, 11]
c_sorted = [1, 3, 9, 11, 12]
sort_algorithm(a)
print("Ok" if c_sorted == merge_sort0(a) else "Fail")
if __name__ == '__main__':
test_merge_sort0(merge_sort0)
test_merge_sort1(merge_sort1)
|
#возвращает рекурсивно число фиббоначи
def fib(n: int):
assert n >= 0
if n <= 1:
return n
else:
return (fib(n-1) + fib(n-2))
return fib[n]
# вычисляется число фиббоначи динамический
def fib2(n: int):
assert n >= 0
fib = [None]*(n+1)
fib[:2] = [0,1]
for k in range(2, n+1):
fib[k] = fib[k-1]+fib[k-2]
return fib[n]
def test_fib(algorithm):
print("testcase#0 : ", end=" ")
n = 9
number = 34
algorithm(n)
print("Ok" if number == n else "Fail")
if __name__ == '__main__':
test_fib(fib) |
def find_factors(number):
"Нахождение простых множителей"
factors=[]
i=2
while i < number:
#Проверяем делимость на i.
while number%i==0:
#i является множителем. Добавляем его в список.
factors.append(i)
#Делим число на i.
number = number / i
#Проверяем следующий возможный множитель.
i += 1
#Если от числа что-то осталось, остаток — тоже множитель.
if number > 1:
factors.append(number)
return (factors)
def find_factors_mod(number):
"""Нахождение простых множителей
-Не стоит проверять, делится ли число на любое четное, кроме 2, поскольку
четные числа уже сами по себе кратны двум. Это означает, что нужно рассмотреть
лишь делимость на 2 и на нечетные числа, вместо того, чтобы перебирать все
возможные множители. В таком случае время работы сократится вдвое.
-Следует проверять множители только до квадратного корня числа. Если n == p*q,
то p или q должно быть меньше либо равно sqrt (n). (Если p и q боль-ше sqrt (n),
их произведение превысит n.) Проверив возможные множители до sqrt (n),
вы найдете наименьший среди них, а, поделив n на такой множитель, определите еще один.
Это сократит время работы до O(sqrt (n)).
-Всякий раз при делении числа на множитель вы можете обновить максимальное
количество потенциальных множителей, которые необходимо проверить."""
import math
factors=[]
#Проверяем делимость на 2.
while number%2==0:
factors.append(2)
number = number / 2
#Ищем нечетные множители.
i=3
max_factor = math.sqrt(number)
while i>max_factor:
#Проверяем делимость на i.
while number%i==0:
# i является множителем. Добавляем его в список.
factors.append(i)
# Делим число на i.
number = number / i
# Устанавливаем новую верхнюю границу.
max_factor = math.sqrt(number)
# Проверяем следующий возможный нечетный множитель.
i += 2
if number > 1:
factors.append(number)
return (factors)
|
'''
Add two numbers represented by linked lists | Set 2
Given two numbers represented by two linked lists, write a function that returns sum list.
The sum list is linked list representation of addition of two input numbers. It is not allowed
to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
'''
import PrintNode as pn
from ListNode import ListNode
def addNumRecur(n1, n2, n1Leng, n2Leng):
if n1.next == None and n2.next != None:
needAddOne, isn1Longer = addNumRecur(n1, n2.next, n1Leng, n2Leng+1)
if needAddOne:
val = n2.val + 1
n2.val = val%10
return (val>=10, isn1Longer)
else:
return (n2.val>=10, isn1Longer)
elif n1.next != None and n2.next == None:
needAddOne, isn1Longer = addNumRecur(n1.next, n2, n1Leng+1, n2Leng)
if needAddOne:
val = n1.val + 1
n1.val = val%10
return (val>=10, isn1Longer)
elif n1.next != None and n2.next != None:
needAddOne, isn1Longer = addNumRecur(n1.next, n2.next, n1Leng+1, n2Leng+1)
if isn1Longer and needAddOne:
val = n1.val + 1
n1.val = val%10
return (val>=10, isn1Longer)
elif not isn1Longer and needAddOne:
val = n2.val + 1
n2.val = val%10
return (val>=10, isn1Longer)
else:
return (False, isn1Longer)
else:
if n1Leng >= n2Leng:
n1.val = (n1.val+n2.val)%10
else:
n2.val = (n1.val+n2.val)%10
return (n1.val+n2.val >=10, n1Leng >= n2Leng)
def addNumbers(h1, h2):
if h1 == None and h2 == None:
return
elif h1 == None:
return h2
elif h2 == None:
return h1
else:
(needAddOne, isn1Longer) = addNumRecur(h1, h2, 1, 1)
if needAddOne:
newh = LinkNode(1)
newh.next = (h1 if isn1Longer else h2)
return newh
else:
return (h1 if isn1Longer else h2)
n1, n2, n3 = ListNode(5), ListNode(6), ListNode(3)
n1.next = n2
n2.next = n3
N1, N2, N3 = ListNode(8), ListNode(4), ListNode(2)
N1.next = N2
N2.next = N3
pn.printNode(addNumbers(n1, N1))
|
'''
Partition a set into two subsets such that the difference of subset sums is minimum
Given a set of integers, the task is to divide it into two sets S1 and S2 such that
the absolute difference between their sums is minimum.
If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2
must have n-m elements and the value of abs(sum(Subset1) - sum(Subset2)) should be minimum.
Example:
Input: arr[] = {1, 6, 11, 5}
Output: 1
Explanation:
Subset1 = {1, 5, 6}, sum of Subset1 = 12
Subset2 = {11}, sum of Subset2 = 11
'''
import sys
def printT(t):
print [i for i in xrange(len(t[0]))]
for elm in t:
print elm
#Important. DP method to find different sums from all possible subsetsg
def findTable(nums):
total = sum(nums)
t = [ [False] * (total+1) for _ in xrange(len(nums))]
for i in xrange(len(t)):
t[i][0] = True
for i in xrange(len(nums)):
num = nums[i]
t[i][num] = True
for i in xrange(1,len(t)):
for j in xrange(1,len(t[0])):
if nums[i] == j:
continue
elif nums[i] > j:
t[i][j] = t[i-1][j]
else:
t[i][j] = t[i-1][j-nums[i]]
return t
def minDiffPartition(nums):
total = sum(nums)
table = findTable(nums)
minDiff, bestPart = sys.maxint, None
for j in xrange(len(table[-1])/2):
if table[-1][j] and minDiff > total - j*2:
minDiff = total - j*2
bestPart = j
return bestPart, total-bestPart
arr = [1, 6, 11, 5]
print minDiffPartition(arr)
arr = [3, 1, 4, 2, 2, 1]
print minDiffPartition(arr) |
'''
Maximum Path Sum in a Binary Tree
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
Example:
Input: Root of below tree
1
/ \
2 3
Output: 6
'''
import sys
class Node(object):
def __init__(self, num):
self.val = num
self.left = None
self.right = None
def addLeft(self, node):
self.left = node
def addRight(self, node):
self.right = node
class Solution(object):
def __init__(self):
self.maxSum = -sys.maxint-1
def maxPathSumUtil(self, root):
if root == None:
return -sys.maxint-1
if root.left == None and root.right == None:
return root.val
l_sum = self.maxPathSumUtil(root.left)
r_sum = self.maxPathSumUtil(root.right)
sum_sigle = max(root.val, root.val + max(l_sum, r_sum))
sum_top = max(root.val, l_sum + r_sum + root.val, sum_sigle)
self.maxSum = max(self.maxSum, sum_top)
return sum_sigle
def maxPathSum(self, root):
self.maxPathSumUtil(root)
return self.maxSum
n1, n2, n3, n4, n5, n6, n7, n8 = Node(10), Node(2), Node(10), Node(20), Node(1), Node(-25), Node(3), Node(4)
n1.addLeft(n2)
n1.addRight(n3)
n2.addLeft(n4)
n2.addRight(n5)
n3.addRight(n6)
n6.addLeft(n7)
n6.addRight(n8)
sol = Solution()
print sol.maxPathSum(n1) |
'''
Compare two strings represented as linked lists
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s->b
Output: -1
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
'''
from ListNode import ListNode
def compareString(h1, h2):
p1, p2 = h1, h2
if p1 == None or p2 == None:
return -1
while p1 != None and p2 != None:
if p1.val != p2.val:
return -1
p1 = p1.next
p2 = p2.next
return (0 if p1==None and p2==None else 1)
n1, n2, n3, n4, n5, n6 = ListNode("g"), ListNode("e"), ListNode("e"), ListNode("k"), ListNode("s"), ListNode("a")
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
N1, N2, N3, N4, N5, N6 = ListNode("g"), ListNode("e"), ListNode("e"), ListNode("k"), ListNode("s"), ListNode("b")
N1.next = N2
N2.next = N3
N3.next = N4
N4.next = N5
# N5.next = N6
print compareString(n1, N1) |
'''
Given a string, print all possible palindromic partitions
example:
input:
nitin
output:
n i t i i n
n iti n
nitin
input:
geeks
output:
g e e k s
g ee k s
'''
def isPalidrom(string):
return "".join(string[::-1]) == string
def allPossiblePalUtil(string, start, end, collection, res):
if start > end:
res += [collection]
return
for i in xrange(start+1, len(string)+1):
if isPalidrom(string[start:i]):
copy = collection[:]
allPossiblePalUtil(string, i, end, copy+["".join(string[start:i])], res)
def allPossiblePal(string):
res = []
allPossiblePalUtil(string, 0, len(string)-1, [], res)
return res
string = "nitin"
print allPossiblePal(string)
string = "geeks"
print allPossiblePal(string) |
'''
Length of the largest subarray with contiguous elements | Set 1
Input: arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3
Input: arr[] = {14, 12, 11, 20};
Output: Length of the longest contiguous subarray is 2
Input: arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45};
Output: Length of the longest contiguous subarray is 5
'''
import sys
def findLeng(arr):
maxLen = -sys.maxint-1
for i in xrange(len(arr)-1):
maxElm, minElm = arr[i], arr[i]
for j in xrange(i+1, len(arr)):
maxElm = max(maxElm, arr[j])
minElm = min(minElm, arr[j])
if j-i+1 == maxElm-minElm+1:
maxLen = max(maxLen, maxElm-minElm+1)
return maxLen
arr = [10,12,11]
print findLeng(arr)
arr = [14,12,11,20]
print findLeng(arr)
arr = [1,56,58,57,90,92,94,93,91,45]
print findLeng(arr)
|
'''
Dynamic Programming | Set 18 (Partition problem)
Partition problem is to determine whether a given set can be partitioned into
two subsets such that the sum of elements in both subsets is same.
'''
def partitionToSameSum(arr):
total = sum(arr)
if total%2 == 1:
return False
target = total/2
t = [ [False] * (target+1) for _ in xrange(len(arr))]
print "target:", target
t[0][0], t[0][arr[0]] = True, True
for i in xrange(1,len(arr)):
for j in xrange(len(t[0])):
if arr[i] < j:
t[i][j] = t[i-1][j-arr[i]]
elif arr[i] == j:
t[i][j] = True
else:
t[i][j] = t[i-1][j]
return sum([ t[i][-1] for i in xrange(len(arr))]) # there exist a subset that can form target
arr = [3,1,5,9,12]
print partitionToSameSum(arr)
|
from flask import Flask, request
"""Extensão Flask"""
def init_app(app: Flask):
@app.route('/')
def index():
print(request.args)
return "Hello Codeshow"
@app.route('/contato')
def contato():
return "<form><input type='text'></input></form>"
def page_other(app: Flask):
@app.route('/lista')
def tabela():
return """<ul><li>Teste1</li>
<li>Teste2</li>
<li>Teste3</li></ul>""" |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Simple Sudoku CLI Application.
Example usage:
sudoku COMMAND INPUT_GRID
sudoku show INPUT_GRID
sudoku solve INPUT_GRID
sudoku validate INPUT_GRID
Format of INPUT_GRID: nine nine-digit numbers separated by commas
530070000,600195000,098000060,800060003,400803001,700020006,060000280,000419005,000080079
"""
import fire
from sudoku.base import Sudoku, SudokuGridError
class SudokuCLI(object):
"""Simple Sudoku CLI Application."""
@staticmethod
def _parse_input_grid(input_grid):
grid = []
if ',' in input_grid:
if input_grid.count(',') != 8:
raise SudokuGridError("Invalid input grid format.")
else:
raise SudokuGridError("Invalid input grid format.")
for i in input_grid.split(','):
grid.append([int(j) for j in list(i)])
return grid
def show(self, input_grid):
"""Prints Sudoku grid in nice format."""
grid = self._parse_input_grid(input_grid)
Sudoku.show(grid)
def solve(self, input_grid):
"""Solves Sudoku puzzle."""
grid = self._parse_input_grid(input_grid)
sudoku = Sudoku(grid)
sudoku.solve_puzzle()
def validate(self, input_grid):
"""Validates correctness of the grid."""
grid = self._parse_input_grid(input_grid)
sudoku = Sudoku(grid)
if sudoku.validate_grid():
print("Valid grid")
else:
print("Invalid grid")
def main():
fire.Fire(SudokuCLI, name='sudoku')
|
name=input("请输入姓名:")
print("{}同学,学好python,前途无量".format(name))
print("{}大侠,学好pathon,大展拳脚".format(name[0]))
print("{}哥哥,学好pathon,人见人爱".format(name[-2]))
|
strcount=0
intcount=0
spacecount=0
othercount=0
try:
x=input('请输入一行字符:')
y=eval(x)
except (Namerror,SyntaxError):
for i in x:
if ord(i) in range(68,91) or ord(i) in rang(97,123):
strcount+=1
elif ord(i) in range(48,58):
intcount+=1
elif i =="":
spacecount+=1
else:
othercount+=1
finally:
print("英文字母、数字、空格和其他字符的个数分别是:{}、{}、{}、{}".format(strcount,intcount,spacecount,othercount))
|
def moon_weight(start_weight, increase_weight,year):
weight_every_year = []
for year in range(year):
weight = start_weight*0.165+ increase_weight*year*0.165
weight_every_year.append(weight)
print(weight_every_year)
input1 = float(input('Please enter your current Earth weight>',))
input2 = float(input('Please ebter the amount your weight might increase each year>',))
input3 = int(input('Please enter the number of years',))
moon_weight(input1,input2,input3)
|
radius=25
area=radius*radius*3.1415926
print(area)
print({".2f"}.format(area))
|
import sys
inputs = sys.argv
inputs.pop(0)
for entry in inputs:
integer = int(entry)
print_string = ""
if integer % 3 == 0:
print_string = print_string + "fizz"
if integer % 5 == 0:
print_string = print_string + "buzz"
if print_string == "":
print(integer)
else:
print(print_string) |
#!/usr/bin/env python
# coding: utf-8
# In[24]:
Dictionary = {"hello": [1, 2, 3], "hi": "1,2,3"}
print(Dictionary["hello"])
print(Dictionary.get('age')) # get.[] it is used to avoid error when we search a key which is not present in a dictionary.
print("hello" in Dictionary.keys())
print('1,2,3' in Dictionary.values())
print(Dictionary.items())
print("hello" in Dictionary.items())
Dictionary1 = {"hello": [1, 2, 3], "hi": "1,2,3"}
Dictionary1.clear() #to make a dictionary empty.
print(Dictionary1)
print(len(Dictionary))
print(Dictionary.update({'hiii': '55'})) #used to modify a Dictionary
print(Dictionary)
# In[34]:
my_list = [1, 2, 3, 4, 5]
my_list[3] = 6
print(my_list)
my_list2 = [3, 5, 1, 99, 10, 100, 1, 2, 5, 20, 90]
my_list2.sort()
print(my_list2)
length = len(my_list2)
print(length)
mid = length//2
print(mid)
# In[39]:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
new_tuple = my_tuple[:]
print(new_tuple)
print(new_tuple.count(3))
print(new_tuple.index(3))
# In[14]:
#SETS importand part
my_set = {1, 2, 3, 4}
my_set.add(5)
print(my_set)
# In[23]:
#removing the repeating elements present in a list using SETs method.
list1 = [1, 1, 3, 2, 5, 1, 9, 8, 7, 6, 5, 1, 9]
list1.sort()
print(list1)
my_set1 = set(list1[:])
print(my_set1)
print(list(my_set1))
# In[31]:
my_set3 = {1, 2, 3, 4, 5}
your_set = {4, 5, 6, 7, 8, 9, 10}
print(my_set.union(your_set)) # .union() is used to join two sets
print(my_set.difference(your_set)) # .differenece() prints the difference between set1 and set2.
print(my_set.intersection(your_set)) # .intersection() or "&" is used to find the intersection elements.
print(my_set & your_set)
print(my_set.isdisjoint(your_set)) # used to find whether there the both sets are joint or not
print(my_set | your_set) # | or .union() is used to union the set
print(my_set.difference_update(your_set))
print(my_set) #it is used to remove the common elements present in set1 or in set2.
# In[30]:
set1 = {4, 5}
set2 = {4, 5, 6, 7}
print(set1.issubset(set2)) # .issubset() is used to check whether the set1 is a subset of set2.
print(set2.superset(set1) # set2 contains all the elements of set1, so ,superset() is used to check whether the set2 is a superset.
# In[ ]:
|
#!/usr/bin/env python
try:
import requests
except ImportError:
print("\nA package called requests is required to run this script.")
print("Install it by : sudo apt-get install python-requests\n")
quit()
try:
from bs4 import BeautifulSoup
except ImportError:
print("\nA package called Beautiful Soup is required to run this script.")
print("Install it by : sudo apt-get install python-bs4\n")
quit()
import os
ch='y'
while ch=='y':
os.system('clear')
keyword = raw_input('\nEnter a word :') #Takes input
url = "http://www.dictionaryapi.com/api/v1/references/learners/xml/"+keyword+"?key=f46c56a3-000f-4057-bd99-90dc09fa4156" #sanyam.jain@iiitb.org API key for learners
print("\nConnecting to the internet...") #Fetches the XML Document
r = requests.get(url)
while r.status_code is not 200:
r = requests.get(url)
print("Connected.")
soup = BeautifulSoup(r.text,"xml")
if soup.select("dt")==[] :
print("\nThe word you have entered is not in the dictionary.\n")
else:
label = soup.fl.string #Finds the label
examples=[] #Fetches 3 examples usage of the words
for link in soup.find_all('vi'):
examples.append(link.text)
link.decompose()
if len(examples)==3:
break
for tag in soup.dt.findAll(True): #Deletes other tags
tag.decompose()
meaning=soup.dt.text #Finds the meaning of the word
print("")
print("Label\t:"+label)
print("Meaning "+meaning.strip())
for example in examples[0:3]:
print("Example :" +example)
print("\n")
ch = raw_input("You you want to search more ? y/n\n") #Takes input
print("\nBye.")
print(' _________\n / \\\n | /\\ /\\ |\n | - |\n | \\___/ |\n \\_________/');
print("")
|
"""Program to count the number of words in a file using pyspark."""
from pyspark.sql import SparkSession
import constants as constants
from operator import add
from typing import List
class SparkEnv:
def __init__(self):
self.spark_session = SparkSession\
.builder\
.appName("PysparkWordCounter")\
.getOrCreate()
def get_spark_session(self):
return self.spark_session
class WordCounter:
""" Utility class, counts the number of words in a file"""
def txt_filereader(self,spark:SparkSession,path: str) -> str:
lines = spark.read.text(path).rdd.map(lambda r: r[0])
return lines
def word_counter(self,lines):
count = lines.flatMap(lambda x: x.split(' ')) \
.map(lambda x: (x,1)) \
.reduceByKey(add)
return_value = count.collect()
return return_value
if __name__ == '__main__':
obj = WordCounter()
spark_obj = SparkEnv()
read_file = obj.txt_filereader(spark_obj.spark_session,constants.WORD_COUNT_FILE_PATH)
if read_file.count() == 0:
print("File is empty",file = sys.stderr)
sys.exit(1)
else:
word_counts = obj.word_counter(read_file)
for key,value in word_counts:
print("{} - {}".format(key,value))
|
import random
user_input = input('Enter a single digit number:\t')
guess = random.randrange(0, 9)
if int(user_input) == int(guess):
print('Congratulations, You have won the lottery!!')
else:
print('Sorry, please try again!')
|
# 2. Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560,
# в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
n = (input('Введите число: '))
even_num = 0
uneven_num = 0
for i in range(len(n)):
num_int = int(n[i])
if num_int % 2 != 0:
uneven_num += 1
else:
even_num += 1
print('В числе {0}: {1} четных цифр и {2} нечетных цифр'.format(n, even_num, uneven_num))
|
# 2. Написать два алгоритма нахождения i-го по счёту простого числа.
# Функция нахождения простого числа должна принимать на вход
# натуральное и возвращать соответствующее простое число.
# Проанализировать скорость и сложность алгоритмов.
import cProfile
# Первый — с помощью алгоритма «Решето Эратосфена».
def first_erat(index):
sieve = [i for i in range(index + 1)]
sieve[1] = 0
for el in range(2, index + 1):
if sieve[el] != 0:
elem = el * 2
while elem <= index:
sieve[elem] = 0
elem += el
nums = [el for el in sieve if el != 0]
return nums[-1]
# print('Простое число: '.format(nums[-1]))
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.first_erat(10)"
# 1000 loops, best of 5: 8.59 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.first_erat(20)"
# 1000 loops, best of 5: 10 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.first_erat(100)"
# 1000 loops, best of 5: 28.7 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.first_erat(1000)"
# 1000 loops, best of 5: 375 usec per loop
# cProfile.run('first_erat(1000)')
# Для 10: 1 0.000 0.000 0.000 0.000 hw4_2.py:9(first_erat)
# Для 100: 1 0.000 0.000 0.000 0.000 hw4_2.py:9(first_erat)
# Для 1000: 1 0.001 0.001 0.001 0.001 hw4_2.py:9(first_erat)
# Сложность алгоритма O(n).
# Второй — без использования «Решета Эратосфена».
def second_my(index):
i = 1
number = 1
nums = [2]
if index == 1:
return 2
while i != index:
number += 2
for num in nums:
if number % num == 0:
break
else:
i += 1
nums.append(number)
return number
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.second_my(10)"
# 1000 loops, best of 5: 7.32 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.second_my(20)"
# 1000 loops, best of 5: 17.9 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.second_my(100)"
# 1000 loops, best of 5: 331 usec per loop
# python -m timeit -n 1000 -s "import hw4_2" "hw4_2.second_my(1000)"
# 1000 loops, best of 5: 31 msec per loop
# cProfile.run('second_my(1000)')
# Для 10: 1 0.000 0.000 0.000 0.000 hw4_2.py:38(second_my)
# Для 100: 1 0.001 0.001 0.001 0.001 hw4_2.py:38(second_my)
# Для 1000: 1 0.077 0.077 0.077 0.077 hw4_2.py:38(second_my)
# Сложность алгоритма O(n).
# Вывод: с увеличением объема данных алгоритм «Решето Эратосфена» работает быстрее второго.
|
numbers= [1, 6, 8, 1, 2, 1, 5, 6]
n= int(input("Enter number: "))
count=0
i=0
while i < len(numbers):
c=numbers[i]
i+=1
if n==c:
count += 1
print(n, "appears", count, "times in my list")
|
n=int(input("Nhap so cot"))
m=int(input("Nhap so dong"))
for i in range (m):
print("\n")
for i in range (1,n+1,2):
print("* o ", end='')
|
prices={
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock={
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
fruits = list(prices.keys())
for i in fruits:
print(i)
i ==prices.get(i,0)
i ==stock.get(i,0)
print("price: ",prices.get(i,0))
print("stock: ",stock.get(i,0))
print()
total = 0
total_fruits = 0
for i in fruits:
i ==prices.get(i,0)
i ==stock.get(i,0)
total=prices.get(i,0)*stock.get(i,0)
print("Total",i,": ", total)
total_fruits = total_fruits + prices.get(i,0)*stock.get(i,0)
print("Total fruits: ",total_fruits)
|
print("Welcome to our shop, what do you want?")
print("Our items:")
items = ["T-Shirt", "Sweater"]
print(*items, sep=', ')
new_item=input("Enter new item:")
items.append(new_item)
print(*items, sep=', ')
n= int(input("Update position:"))
items.pop(n-1)
m=input("New item?")
items.insert(n-1,m)
print(*items, sep=', ')
l=int(input("Delete position:"))
del(items[l])
print(*items, sep=', ')
|
n=int(input("Nhap so:"))
result = 1
for i in range (1,n+1):
result = result * i
print (result)
|
print ("Hello Chung")
n=input("What's your name?")
print("Hi",n)
|
def print_max(a,b):
if a > b:
print(a," is maximum")
elif a == b:
print(a, " is equal to " , b)
else:
print(b, "is maximum")
if __name__ == '__main__':
pass
#print_max(3, 4) # directly pass literal values
x = 5
y = 7 # pass variables as arguments
print_max(x, y)
|
def compress( _str ):
comp_str = []
count = 1
comp_str.append(_str[0])
for i in xrange(1, len(_str)):
if _str[i] == _str[i-1]:
count += 1
else:
if count != 1:
comp_str.append(str(count))
comp_str.append(_str[i])
count = 1
else:
comp_str.append(_str[i])
if count != 1:
comp_str.append(str(count))
return "".join(comp_str)
print compress(raw_input()) |
from wip_list import build_list as build
from lexicon import word_list as lex
#print(lex)
def find_example_word(wip):
example = ""
wip_len = len(wip)
if wip in lex:
example = wip
else:
for word in lex:
print("++++\nWORD: ", word, "\n++++\n")
#assume the word is a valid example for this wip, then look for counter-examples by:
#1) checks that each letter is in the would-be example word
#2) checks that any letters that appear BEFORE a given "letter" in the "wip" also appear AT LEAST ONCE before that same "letter" in the "word"
#3) repeat #2, checking letters that appear AFTER a given "letter" in the "wip"
valid = True
for index in range(0, wip_len):
letter = wip[index]
pre = wip[:index]
post = wip[index+1:]
print(" ====")
print(" wip: ", wip, "\n pre: ", pre, "\n letter: ", letter, "\n post: ", post)
print(" valid: ", valid)
print(" ====")
#if the letter isn't in the word at all, word is not valid example for this wip
if letter not in word:
valid = False
break
#if any other letters exist BEFORE this "letter"
if len(pre) > 0:
for other_letter in pre:
#if the FIRST occurance of "other_letter" is not until AFTER "letter" in "word"
if word.find(other_letter) > index or other_letter not in word:
valid = False
break
#if any other letters exist AFTER this "letter"
if len(post) > 0:
for other_letter in post:
#if the LAST occurance of "other_letter" is BEFORE "letter" in "word"
if word.rfind(other_letter) < index or other_letter not in word:
valid = False
break
print(" ----")
print(" still_valid: ", valid)
print(" ----")
#if still valid at this point, then "word" is proven to be a valid example for "wip"
if valid:
example = word
else:
break
#once example word is no longer empty string, we don't need to keep looping through "word"(s) in "lex"
if example != "":
break
return example
(find_example_word("noth"))
|
def main():
import sys
#write this command to run:
#python practice.py < [file].txt > [file].html
#the txt file is known, you are creating the html file
writeToFile (sys.stdin, sys.stdout)
def writeToFile(query, w):
import MySQLdb
temp = query.readline()
query = query.read()
conn = MySQLdb.connect('localhost', 'root', 'database', 'test')
c = conn.cursor()
c.execute(query)
results = c.fetchall()
w.write("<head>\n")
w.write("<h3>"+temp+"</h3>\n\n")
w.write("\n<table border=1>")
for row in results:
w.write("<tr>")
for i in row:
w.write("<td>"+str(i)+"</td>")
w.write("</tr>")
w.write("</table>\n</head>")
main()
|
def is_palindrome(fname):
with open(fname) as f:
lines = f.readlines()
for line in lines:
input_string = (" ".join(line.split()))
reverse_string = input_string[::-1]
if reverse_string == input_string:
print (input_string)
fname = "/home/pavkata/test/test.txt"
is_palindrome(fname) |
'''
def sum(a, b, c, d):
result=(a+b+c+d)
print ("The result on sum is "+ str(result))
def multiply(a, b, c, d):
result=(a*b*c*d)
print ("The result of multiply is "+ str(result))
a = input("Please enter a number: ")
b= input("Please enter a number: ")
c= input("Please enter a number: ")
d= input("Please enter a number: ")
sum(a, b, c, d)
multiply(a, b, c, d)
'''
def sum(input_numbers):
result = 0
#input_numbers.replace(" ", "")
for i in input_numbers:
result =result+int(i)
return result
input_numbers= raw_input("Please enter numbers: ")
print (sum(input_numbers.replace(" ", "")))
|
import re
def make_ing_form(verb):
vowels = ["a", "e", "i", "o", "u"]
consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" ]
suffix1 = ("e")
suffix2 = ("ie")
if verb in ["be", "see", "flee", "knee"]:
return "".join((verb, "ing"))
elif verb.endswith(suffix1):
return re.sub('e$','ing ',verb)
elif verb.endswith(suffix2):
return "".join((verb, "es"))
else:
return "".join((verb, "ing"))
verbs = "lie", "see", "move", "hug", "be"
for verb in verbs:
print (make_ing_form(verb))
|
from tkinter import *
root = Tk()
top_frame = Frame(root)
top_frame.pack()
bottom_frame = Frame(root)
bottom_frame.pack(side=BOTTOM)# параметр side позволяет задать положение
button1 = Button(top_frame, text='кнопка1', fg='red', bg='orange')
button2 = Button(top_frame, text='кнопка2', fg='blue', bg='orange')
button3 = Button(top_frame, text='кнопка3', fg='green', bg='orange')
button4 = Button(bottom_frame, text='кнопка4', fg='gray', bg='orange')
button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack(side=BOTTOM)
root.mainloop()
|
from tkinter import *
root = Tk()
one = Label(root, text='one', bg='red', fg='yellow')
one.pack()
two = Label(root, text='two', bg='blue', fg='orange')
two.pack(fill=X)# будет растягиваться в соответствии с размером окна по оси Х
three = Label(root, text='three', bg='black', fg='white')
three.pack(side=LEFT, fill=Y)# будет растягиваться в соответствии с размером окна по оси Y
root.mainloop()
|
from card import *
class Hand(object):
def __init__(self, contents = None):
self._contents = contents if contents else []
# if contents is nont None:
# self._contents = contents
# else:
# self._contents = []
def __repr__(self):
return "Hand({})".format(self._contents)
def __str__(self):
return str([str(card) for card in self._contents])
def insert(self, card):
self._contents.append(card)
def deal(self):
return self._contents.pop(0)
def __len__(self):
return len(self._contents)
def contents(self):
return self._contents.copy()
def __add__(self, other):
if type(other) is Card:
return Hand(self._contents + [other])
else:
return Hand(self._contents + other.contents())
|
colors = set(['White', 'Black', 'Blue', 'Red', 'Yellow'])
N = int(raw_input())
for _ in range(N):
color = raw_input()
if color in colors:
colors.remove(color)
print colors.pop()
|
import random
print("rock paper or scissor game")
player1 = input("Enter your option: ")
choice = ["rock", "paper", "scissor" ]
player2 = random.choice(choice)
def game(p1, p2):
if p1 == p2:
print("Its a tie")
elif p1 =="rock":
if p2 == "scissor":
print("Rock Wins")
else:
print("Paper Wins")
elif p1 == "scissor":
if p2 == "paper":
print("Scissor Wins")
else:
print("Rock Wins")
elif p1 == "paper":
if p2 == "rock":
print("Paper Wins")
else:
print("Scissor Wins")
game(player1, player2) |
#list with numbers with new list with numbers less than a number
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b =[]
for each in a:
if each<5:
b.append(each) |
class productos:
def __init__(self,nombre,elaboracion):
self.nombre=nombre
self.elaboracion=elaboracion
class nodo:
def __init__(self,producto =None,siguiente=None):
self.producto=producto
self.siguiente=siguiente
class lista_productos:
def __init__(self):
self.primero = None
def insertar(self, producto):
if self.primero is None:
self.primero = nodo(producto=producto)
return
actual = self.primero
while actual.siguiente:
actual = actual.siguiente
actual.siguiente = nodo(producto=producto)
def recorrer(self):
actual= self.primero
while actual != None:
#print("nombre: ", actual.producto.nombre,"elaboracion: ", actual.producto.elaboracion.recorrer())
print("nombre: ", actual.producto.nombre,"elaboracion: ", actual.producto.elaboracion)
actual = actual.siguiente
def clean(self):
actual= self.primero
while actual != None:
actual.producto.elaboracion.Limpiar()
#print("nombre: ", actual.producto.nombre,"elaboracion: ", actual.producto.elaboracion)
actual = actual.siguiente
def eliminar(self,nombre):
actual = self.primero
anterior = None
while actual and actual.producto.nombre != nombre:
anterior = actual
actual = actual.siguiente
if anterior is None:
self.primero = actual.siguiente
elif actual:
anterior.siguiente = actual.siguiente
actual.siguiente = None
def buscar(self,nombre):
actual = self.primero
anterior = None
while actual and actual.producto.nombre != nombre:
anterior = actual
actual = actual.siguiente
if actual is None:
print("No se encontro la persona con el no:", nombre)
break
if actual is not None:
if actual.producto.nombre == nombre:
#print("nombre: ", actual.producto.nombre)
#print("Lista: ", actual.producto.elaboracion)
#actual.producto.elaboracion.recorrer()
return actual.producto
def ListadoProductoss(self):
lista = []
actual= self.primero
while actual != None:
lista.append(actual.producto.nombre)
actual = actual.siguiente
return lista
"""
if __name__ == "__main__":
e1 = productos(1,1)
e2 = productos(2,2)
e3 = productos(3,3)
lista_e = lista_productos()
lista_e.insertar(e1)
lista_e.insertar(e2)
lista_e.insertar(e3)
lista_e.recorrer()
""" |
import time
import math
start = time.time()
#time: 1.92652 seconds
def prime_array():
#array of prime numbers
array = [2,3]
step = 0
i = 5
comp = 0
count = 1
count2 = 2
while len(array) < 10001:
# this loop get the next 6n+/-1 number and checks whether it be divided by each prime number in the array, if not it is added to the array
while step < int(math.sqrt(array[len(array)-1])):
if i%array[step] == 0 and i != array[step]:
comp += 1
step = array[len(array)-1]
else:
step += 1
if comp == 0:
array.append(i)
comp = 0
step = 0
#prime number can be either 6n +/- 1. Eg 6*1-1=5, 6*1+1=7, 6*2-1=11
if count2 % 2 != 0:
i = 6 * count - 1
else:
i = 6 * count + 1
count += 1
count2 += 1
print("Answer to the question:", array[len(array)-1])
prime_array()
elapsed = time.time() - start
print("Time: {:.5f} seconds".format(elapsed))
|
# Reading and Writing files and directories
# Read the Docs: https://docs.python.org/3/library/os.path.html
# os.path.join() allows us to build paths that will work on any OS
import os
os.path.join('usr', 'bin', 'spam')
# returns: 'usr\\bin\\spam'
# on linux or OS X it would have returned usr/bin/spam
# the following example joins names from a list of filenames to the end of a folder’s name:
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join('C:\\Users\\t1337', filename))
# C:\Users\t1337\accounts.txt
# C:\Users\t1337\details.csv
# C:\Users\t1337\invite.docx
# current working directory and change directory as strings
import os
os.getcwd()
# 'C:\\Users\\t1337\\Documents\\automation'
os.chdir('C:\\Windows\\System32')
os.getcwd()
# 'C:\\Windows\\System32'
# you get an error if you try to change to a dir that doesn't exist
os.chdir('C:\\ThisFolderDoesNotExist')
# FileNotFoundError: [WinError 2] The system cannot find the file specified:
# Create new folders with os.makedirs()
import os
os.makedirs('C:\\delicious\\walnut\\waffles')
# os.makedirs() will create any intermediate folders so that the full path exists
# convert a relative path to an absolute one with
os.path.abspath(path)
# the following will return True if the argument is an absolute path and False if it's relative
os.path.isabs(path)
# to return a string of a relative path from the start path to path. Default start is pwd
os.path.relpath(path, start)
# examples
os.path.abspath('.')
'C:\\Python34'
os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
os.path.isabs('.')
False
os.path.isabs(os.path.abspath('.'))
True
# relative path examples
os.path.relpath('C:\\Windows', 'C:\\')
'Windows'
os.path.relpath('C:\\Windows', 'C:\\spam\\eggs')
'..\\..\\Windows'
os.getcwd()
'C:\\Python34'
# Dir name and Base name
# C:\Windows\System32\calc.exe The Dir name is C:\Windows\System32 and the Base name is calc.exe
path = 'C:\\Windows\\System32\\calc.exe'
os.path.basename(path)
'calc.exe'
os.path.dirname(path)
'C:\\Windows\\System32'
# to split the path's dir name and base name together use os.path.split() to get a tuple value with both strings
calcFilePath = 'C:\\Windows\\System32\\calc.exe'
os.path.split(calcFilePath)
('C:\\Windows\\System32', 'calc.exe')
# the following does the same thing, but os.path.split() is a greate shortcut if you need both values
(os.path.dirname(calcFilePath), os.path.basename(calcFilePath))
('C:\\Windows\\System32', 'calc.exe')
# to split the file path into a list of strings of each folder use os.path.sep
calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']
# on OS X and Linux there will be a blank string at the start of the returned list:
'/usr/bin'.split(os.path.sep)
['', 'usr', 'bin']
# Finding folder and file sizes
os.path.getsize(path) # this returns the size in bytes of the file
os.listdir(path) # this returns a list of filename strings for each file in the path argument
os.path.getsize('C:\\Windows\\System32\\calc.exe')
776192
os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
# to find the total size of files in this directory use the following..
totalSize = 0
for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
print(totalSize)
1117846456
# when I call os.path.getsize(), I use os.path.join() to join the folder name with the current filename
# Checking Path Validity
# the following will return True or False depending on whether the file of folder exists
os.path.exists(path)
# the following will return True of False depending on whether it exists and is a file
os.path.isfile(path)
# the following will return True of False depending on whether it exists and is a folder
os.path.isdir(path)
>>> os.path.exists('C:\\Windows')
True
>>> os.path.exists('C:\\some_made_up_folder')
False
>>> os.path.isdir('C:\\Windows\\System32')
True
>>> os.path.isfile('C:\\Windows\\System32')
False
>>> os.path.isdir('C:\\Windows\\System32\\calc.exe')
False
>>> os.path.isfile('C:\\Windows\\System32\\calc.exe')
True
'''
You can determine whether there is a DVD or flash drive currently attached to the computer by checking
for it with the os.path.exists() function. For instance, if I wanted to check for a flash drive with the
volume named D:\ on my Windows computer, I could do that with the following:
'''
os.path.exists('D:\\')
True
# Reading/Writing Process with .txt files
# Binary files are all other file types, like word documents, PDFs, images, spreadsheets, and .exe's
'''
There are three steps to reading or writing files in Python.
Call the open() function to return a File object.
Call the read() or write() method on the File object.
Close the file by calling the close() method on the File object.'''
# open() function
helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
# in OS X use
helloFile = open('/Users/your_home_folder/hello.txt')
# Reading the Contents of Files
helloContent = helloFile.read()
helloContent
'Hello World!'
# use the readlines() method to get a list of string values from the file, one string for each line of text
sonnetFile = open('sonnet29.txt')
sonnetFile.readlines()
#[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my
# outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And
# look upon myself and curse my fate,']
# Writing To Files.. write mode will overwrite the existing file and start from scratch
'''
Write mode will overwrite the existing file and start from scratch, just like when you overwrite a
variable’s value with a new value. Pass 'w' as the second argument to open() to open the file in write
mode. Append mode, on the other hand, will append text to the end of the existing file. You can think
of this as appending to a list in a variable, rather than overwriting the variable altogether.
Pass 'a' as the second argument to open() to open the file in append mode.
If the filename passed to open() does not exist, both write and append mode will create a new, blank
file. After reading or writing a file, call the close() method before opening the file again.
'''
baconFile = open('bacon.txt', 'w')
baconFile.write('Hello world!\n')
13
baconFile.close()
baconFile = open('bacon.txt', 'a')
baconFile.write('Bacon is not a vegetable.')
25
baconFile.close()
baconFile = open('bacon.txt')
content = baconFile.read()
baconFile.close()
print(content)
'Hello world!'
'Bacon is not a vegetable.'
# Saving Variables with the shelve Module
# The shelve module will let you add Save and Open features to your program. For example, if you ran a
# program and entered some configuration settings, you could save those settings to a shelf file and then
# have the program load them the next time it is run.
import shelve
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Simon']
shelfFile['cats'] = cats
shelfFile.close()
# 3 new files are created: mydata.bak, mydata.dat, and mydata.dir (on OS X mydata.db is created)
# This frees you from worrying about how to store your program's data to a file
# use shelve module to later reopen the data from these files.
# we can open them up and check to make sure the data was properly store by doing the following
shelfFile = shelve.open('mydata')
type(shelfFile)
<class 'shelve.DbfilenameShelf'>
shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
shelfFile.close()
# just like dictionaries, shelf values have keys() and values() methods that return list like values
# to get them to the list for use the list() function
shelfFile = shelve.open('mydata')
list(shelfFile.keys())
['cats'] # the output we get
list(shelfFile.values())
[['Zophie', 'Pooka', 'Simon']] # the output
shelfFile.close()
# Plaintext is useful for creating files that you’ll read in a text editor such as Notepad or TextEdit,
# but if you want to save data from your Python programs, use the shelve module.
# Saving Variables with the pprint.pformat() Function
'''
remember that pprint.pprint() pretty prints contents of a list or dictionary, while the
pprint.pformat() function will return this same text as a string instead of printint it
Not only is this string formatted to be easy to read, but it is also syntactically correct
Python code. Say you have a dictionary stored in a variable and you want to save this variable
and its contents for future use. Using pprint.pformat() will give you a string that you can
write to .py file. This file will be your very own module that you can import whenever you want
to use the variable stored in it.
'''
import pprint
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
fileObj = open('myCats.py', 'w')
fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
83
fileObj.close()
'''
The modules that an import statement imports are themselves just Python scripts. When the string from
pprint.pformat() is saved to a .py file, the file is a module that can be imported just like any other.
And since Python scripts are themselves just text files with the .py file extension, your Python
programs can even generate other Python programs. You can then import these files into scripts.
'''
import myCats
myCats.cats
[{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
myCats.cats[0]
{'name': 'Zophie', 'desc': 'chubby'}
myCats.cats[0]['name']
'Zophie'
|
#firstchallenge
#List down all the error types
#1.)NameError
#2.)ModuleNotFoundError
#3.)IndexError
#4.)ZeroDivisionError
#5.)ValueError
try:
raise NameError('Aeroplane')
except NameError:
print("The exception demolished")
#ModuleNotFoundError
try:
import numpy
print("Module found")
except:
print("module not found")
#Indexerror
L=list(range(0,10))
try:
print(L[30])
except:
print("Error handled")
#ZeroDivisionError
try:
c=9/0
print(c)
except:
print("Cannot divide by zero")
#ValueError
try:
x=int(input("Enter the number"))
except:
print("It is not a number")
#Excercise_2_Design a simple calculator app with try and except for all use cas-es
a=int(input("Enter the first integer"))
b=int(input("Enter the second integer"))
print("Choose the arithmetic function you want to do")
print("1.Addition")
print("2.Subraction")
print("3.Multiplication")
print("4.Division")
ch=int(input("Enter your choice"))
try:
if (ch == 1):
c = a + b
print("The added value is: ",c)
except:
print("Invalid input")
try:
if(ch==2):
c=a-b
print("The subtracted value is: ",c)
except:
print("Invalid input")
try:
if(ch==3):
c=a*b
print("The multiplied value is: ",c)
except:
print("Invalid input")
try:
if(ch==4):
c=a/b
print("The divided value is: ",c)
except:
print("Invalid input")
finally:
print("End of program")
#Excercise_3_print one message if the try block raises a NameError and another for other errors
try:
raise NameError("Apple")
except NameError:
print("The Exception is handled")
#Excercise_4_When try-except scenario is not required
#Answer:Whwenever there is no need for error to be handled or we can let the program to display the error,try-except scenario is not required.
#Excercise_5_Try getting an input inside the try catch block
while True:
try:
t=int(input("Enter the integer"))
print("The integer you have entered is",t)
break
except:
print("Invalid integer")
print("Yeah!!,Successfully you have entered integer") |
# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
#
# 示例:
#
# Trie trie = new Trie();
#
# trie.insert("apple");
# trie.search("apple"); // 返回 true
# trie.search("app"); // 返回 false
# trie.startsWith("app"); // 返回 true
# trie.insert("app");
# trie.search("app"); // 返回 true
# 说明:
#
# 你可以假设所有的输入都是由小写字母 a-z 构成的。
# 保证所有输入均为非空字符串。
class Trie:
def __init__(self):
self.val = ''
self.left = None
self.right = None
"""
Initialize your data structure here.
"""
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
if self.val=='':
self.val = word
else:
cur = self
while cur.val!='':
if word<cur.val:
if cur.left == None:
cur.left = Trie()
cur.left.val = word
break
else:
cur = cur.left
if word>=cur.val:
if cur.right==None:
cur.right = Trie()
cur.right.val = word
break
else:
cur = cur.right
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
if self.val == word:
return True
elif word<self.val:
if self.left==None:
return False
return self.left.search(word)
else:
if self.right==None:
return False
return self.right.search(word)
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
if self.val[:len(prefix)] == prefix:
return True
elif prefix<self.val:
if self.left==None:
return False
return self.left.startsWith(prefix)
else:
if self.right==None:
return False
return self.right.startsWith(prefix)
# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('word')
obj.insert('apple')
print(obj.search('word'))
print(obj.startsWith('ap'))
print(obj.search('apple')) |
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
max_length = [1 for _ in nums]
for i in range(1, len(nums)):
max_num = 0
for j in range(i):
if max_length[j] > max_num and nums[j] < nums[i]:
max_num = max_length[j]
max_length[i] = max_num + 1
return max(max_length)
a = Solution().lengthOfLIS([0,1,0,3,2,3])
print(a) |
def quicksort(nums):
res = []
for i in nums:
has_found = False
for j in range(len(res)):
if res[j] >= i:
has_found = True
res.insert(j, i)
break
if not has_found:
res.append(i)
return res
if __name__ == '__main__':
nums = [2,4,1,6,3,7,4]
res = quicksort(nums)
print(res)
# dp[0] = 1
# dp[1] = 2
# dp[i] = dp[i-1] + dp[i-2]
# return dp[n-1]
|
name = input("What is your name?")
starter = input("What is your favourite starter?")
main_course = input("What is your favourite main course?")
dessert = input("What is your favourite dessert?")
drink = input("What is your favourite drink?")
print ("Hello " + name + "! Your favorite meal is " + starter +","+ main_course + " and " + dessert + " with a glass of" + drink)
|
##suma de filas y de columnas
import numpy as np
def numero_filas_columnas (filas, columnas):
return np.random.randint(0, 11, (filas, columnas))
matriz = numero_filas_columnas(5, 5)
print(matriz)
v1 = np.array([])
w1 = np.array([])
vt = np.array([])
for v in range(0, 5):
suma_filas = 0
cuadrado = 0
suma_columnas = 0
cubo = 0
for w in range(0, 5):
suma_filas += (matriz[v][w]) ** 2
cuadrado = suma_filas ** 0.5
suma_columnas += (matriz[w][v]) ** 3
cubo = suma_columnas ** 0.33333
print("suma de fila", str(v + 0), "es = ", suma_filas)
print(cuadrado)
print("suma de columna", str(v + 0), "es = ", suma_columnas)
print(cubo)
v1 = np.insert(v1, v, cuadrado)
w1 = np.insert(w1, v, cubo)
vt = np.transpose(v1)
print(v1)
print(w1)
vt = np.array([v1])
#multipliacion de matrices
import numpy as np
def matriz1(filas, columnas):
return np.random.randint(0, 11, (filas, columnas))
matrizaa = matriz1(4, 4)
print(matrizaa)
def matriz2(fila, columna):
return np.random.randint(0, 11, (fila, columna))
matrizbb = matriz2(4, 4)
matrizc = np.zeros((4, 4))
print(matrizbb)
for i in range(len(matrizaa)):
for j in range(len(matrizaa[i])):
matrizc[i, j] = matrizaa[i, j] * matrizbb[i, j]
print(matrizc)
print(matrizaa * matrizbb)
#decimal a binario
numero = int(input(" leer el valor a convertir a binario: "))
lista = []
while numero >= 1:
lista.append(str(numero % 2))
numero //= 2
print("".join(lista[::-1]))
#Realizar un algoritmo que calcule el valor aproximada de pi, basa en el método Euler:Realizar un algoritmo que calcule el valor aproximada de pi, basa en el método Euler:
e = int(input(" leer el valor: "))
resultado = 0
f1 = 1
f2 = 1
n1 = 0
n2 = 0
for m in range(0, e):
e = m
n1 = e
n2 = (2 * e) + 1
for i in range(1, n1 + 1):
f1 *= i
for j in range(1, n2 + 1):
f2 *= j
resultado += (2 ** e) * (f1 ** 2) / f2
f1 = 1
f2 = 1
print(resultado)
#numero base_exponente
base = int(input(" leer la base: "))
exponente = int(input(" leer el exponente: "))
resultado = base
t = 0
for i in range(1, exponente):
for j in range(1, base + 1):
t += resultado
resultado = t
t = 0
print(resultado)
|
for i in range(20, 0, -1):
print(" informes del año: ", i)
#factorial de un numero
factorial = int(input(" poner el valor a factorial: "))
for i in range(1, factorial, 1):
factorial *= i
print(" factorial es igual: ", factorial)
#cuadrado de un número
n = int(input(" leer valor: "))
respuesta = 0
for i in range(1, 2 * n, 2):
respuesta += i
print(" cuadrado del número es:", respuesta) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.