text stringlengths 37 1.41M |
|---|
""" Prediction of preferred songs based on song input"""
from sprs.spotify import get_features, we_recommend, add_song, track_id_for_artist_title
from sqlalchemy import create_engine
import pandas as pd
from pandas import DataFrame
import sqlite3
from sklearn.neighbors import NearestNeighbors
import json
def predict_be... |
import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.data = [float(x), float(y)]
@property
def x(self):
return self.data[0]
@property
def y(self):
return self.data[1]
def __str__(self):
return "point(%.2f, %.2f)" % (self.x, self.y)
def distanc... |
import numpy as np
def levenshtein(string1, string2):
size_x = len(string1) + 1
size_y = len(string2) + 1
matrix = np.zeros((size_x, size_y))
for x in range(size_x):
matrix[x, 0] = x
for y in range(size_y):
matrix[y, 0] = y
for x in range(1, size_x):
for y in range(1... |
def bmi(weight, height):
bmi = weight / (height/100) ** 2
return bmi
def calculator():
print("Let’s calculate your BMI (kg/m2)")
user_weight = float(input("What is your weight in kg?"))
user_height = float(input("What is your height in cm?"))
user_bmi = round(bmi(user_weight, user_height))
... |
###This code is for calulating total words, total positive words, total negative words, tweet number :: txt file
import os
def read_file_name(filename): # returning [filename, filename.root, absolute path filename, absolute path filename without root file]
f = open(filename,"r")
if(filename[0] ==... |
def createAdjMatrix(vertices_number, graph_matrix):
adjMatrix = []
# create N x N matrix filled with 0 edge weights between all vertices
for i in range(0, vertices_number):
adjMatrix.append([])
for j in range(0, vertices_number):
adjMatrix[i].append(0)
# populate adjacency matrix wit... |
import itertools
# divisible_by_three(4311)
def divisible_by_three(x):
if x % 3 == 0:
return True
else:
return False
# x = l
# n = 4
def get_combinations(x, n):
res = [y for y in itertools.permutations(x, n)]
return res
# x = (4, 1)
# input = res
def collapse_tuples(input):
outer ... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 17:07:41 2020
@author: barbora
"""
# Start with user_profily.py from the book. Build a profile of yourself by
# calling build_profile(), using your first and last names and three other
# key-value pairs that describe you.
# Function from book
def build_profile(first,... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 11:02:36 2020
@author: barbora
"""
# Print a quote and the name of its author, incl. quotation marks
author = "leslie knope"
quote = "We have to remeber what's important in life: friends waffles and work. Or waffles, friends, work."
print(f'{author.title()} once said... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 22:25:48 2020
@author: barbora
"""
# Make a list of five or more usernames, including the name 'admin'. Imagine
# you are writing code that will print a greeting to each user after they log
# into a website. Loop through the list, and print a greeting to each user:
#... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 13:45:04 2020
@author: barbora
"""
# Think of something you could store in a list. Write a program that creates a
# list comtaining these items and then uses each function introduced in this
# chapter at least once.
# Define orginal list
icecreams = ['magnum raspber... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 08:35:02 2020
@author: barbora
"""
# Think of at least three kinds of pizza. Store these pizza names in a list,
# and then use a for loop to print the name of each pizza.
# - Modify your for loop to print a sentence for eaxh pizza.
# - Add a line at the end of the pr... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 21:29:14 2020
@author: barbora
Store functions for 11-1.
"""
def return_formatted_city_country(city, country, population=''):
"""Return a string formatted as City, Country - population xxx
when population data available. Otherwise return as City, Country.
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 21:43:53 2020
@author: barbora
"""
# Make a list of your favourite fruits, and then write a series of independent
# if statements that check for certain fruits in your list.
# - Make a list of your three favourite fruits and call it favourite_fruits.
# - Write five i... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 13 20:39:56 2020
@author: barbora
"""
# Clean up the code from 6-3 using loops. When the code works, add five more
# terms to the glossary. Run the code again.
# Create glossary
glossary = {
'dictionary': 'Collection of key-value pairs',
'list': 'Collection of i... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 22:29:24 2020
@author: barbora
"""
# Add an if test to 5-8 to make sure the list of users is not empty.
# - If the list is empty, print "We need to find some users!"
# - Remove all of the usernames from your list, and make sure the correct
# message is printed.
# Lis... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 09:20:40 2020
@author: barbora
"""
# Make a list of the numbers 1 to 1 000 000, and then use a for loop to print
# the numbers.
one_mill = list(range(1,1000001))
for value in one_mill:
print(value)
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 16:24:58 2020
@author: barbora
"""
# A buffet-style restaurant offers only five basic foods. Think of five
# simple foods, and store them in a tuple.
# - Use a for loop to print each food the restaurant offers.
# - Try to modify one of the items, and make sure that P... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 6 15:08:23 2020
@author: barbora
Use a loop to see how hard it might be to win the kind of lottery modelled in
9_14. Make a list or tuple called my_ticket. Write a loop that keeps pulling
numbers until your ticket wins. Print a message reporting how many times the
loo... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 17:11:24 2020
@author: barbora
"""
# Write a function that stores information about your car in a dictionary.
# The function should always receive a manufacturer and a model name. It
# should then accept an arbitrary number of keyword arguments. Call the
# function w... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 21:18:10 2020
@author: barbora
"""
# Start with 8-7. Write a while loop that allows users to enter an album's
# artist and title. Once you have that information, call make_album() with the
# user's input and print the dictionary.
# From 8-7
def make_album(artist, tit... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 11:16:41 2020
@author: barbora
"""
# Make a list that includes at least three people you'd like to invite to
# dinner. Then use your list to print a message to each person, inviting them
# to dinner.
guests = ['alan turing', 'duncan mackay', 'taylor swift']
name =... |
import sqlite3
class Database:
DATABASE = 'personalTrainerServer/db/user.db'
con = None
cursor = None
def connect(self):
self.con = sqlite3.connect(self.DATABASE)
self.cursor = self.con.cursor()
def insert(self, table, fields=(), values=()):
# g.db is the database connec... |
import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = int(input("guess an number: "))
if guess < random_number:
print('too low')
elif guess > random_number:
print('too hight')
print('noice')
gues... |
"""
TensorFlow是采用数据流图(data flow graphs)来计算, 所以首先我们得创建一个数据流流图,
然后再将我们的数据(数据以张量(tensor)的形式存在)放在数据流图中计算. 节点(Nodes)在图
中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组, 即张量(tensor).
训练模型时tensor会不断的从数据流图中的一个节点flow到另一节点, 这就是TensorFlow名字的由来.
Tensor 张量意义
张量(Tensor):
张量有多种. 零阶张量为 纯量或标量 (scalar) 也就是一个数值. 比如 [1]
一阶张量为 向量 (vector), 比如 一维的... |
# def press_grind_beans():
# print("Grinding for 20 seconds")
# # def is for functions and () are needed afterwards
# press_grind_beans()
# # this being here makes the function work
# coffee_is_grinding = True
# def press_grind_beans():
# if coffee_is_grinding:
# print("The coffee is grinding")
# ... |
print("You are set up to zipline accross to the bank, the rope is in place. However before you start this mission you need to choose an item.")
time.sleep(3)
print("What will you pick?")
time.sleep(1)
print("A. A handrill")
time.sleep(1)
print("B. A dufflebag")
time.sleep(1)
print("C. A banana")
firstchoice = input... |
"""
+7 911 279 02 46
+7 999 210 02 46
PY itmo! вк клуб
"""
# переменная
#PEP8
is_student=True
name=input('Введите имя:')
print('hello,',name,'!')
#Что такое типы данных?
#Скалярные типы хранятся в стэке. только 1 значение в момент времени возможно
#bool- логические (True или False)
#int-целочисленные
i1=666
i2=0x5... |
# TicTacToe
import os
move_possibility = list('qweasdzxc')
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
move_info = 'Please input your move using the letters QWEASDZXC. For example Q is the left upper corner. \n'
os.system('clear')
exit_list = ['exit', 'wyjscie', "wyjście", 'quit']
player = False
def ... |
import sqlite3
from tkinter import messagebox
# Connection to DDBB for creating new table if not exists
def create_table():
try:
# Connect to Database
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
# SQL Command for creating table
sql = """CREATE TABLE IF NOT... |
#Project I: Take a Music Break
"""
Do you know a friend who works too many hours? We will write a program that schedules breaks throughout
the day -- reminding your friend to listen to his favorite music in the web browser, get up and dance to
it or just walk away from the computer if he wants to, then go back to wo... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.subplot(431) # 画的是共有四行三列,然后这是4*3这12个位置中的第三个
plt.subplot(432) # 画的是共有四行三列,然后这是4*3这12个位置中的第2个
plt.subplot(427) # 画的是共有四行2列,然后这是4*3这12个位置中的第7个
plt.show()
fig = plt.figure()
ax = fig.add_axes([0.35, 0.4, 0.3, 0.7])
line, = ax.plot([1,2,3],[... |
#comment goes here
#my first program
name = "Vahdeta Suljic"
print name[1:5]
request = "abcbd"
print request.split('b')
res = "respect"
print "-".join("respect")
print res.upper()
print name[-13]
print name[::-1]
fullname = name.split()
print fullname |
#https://projecteuler.net/problem=2
#Each new term in the Fibonacci sequence is generated
#by adding the previous two terms. By starting with 1
#and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence
#whose values do not exceed four million, fin... |
# Your code for get_companies_names goes here
def get_companies_names(companies):
new_list = []
for company in companies:
new_list.append(company["Company Name"])
return new_list
# Your code for get_countries goes here
def get_countries(companies):
new_dict = {}
for company in companies:
... |
import math
N = 9
a = 1.1231432412
print(a)
a_fxp = int(a * math.pow(2, N))
print(a_fxp)
a_float = a_fxp * 1.0 / math.pow(2, N)
print(a_float) |
import math
from abc import ABC
from abc import abstractmethod
from tkinter import Canvas
class Shape(ABC): # абстрактный класс
# Объявляем абстрактные методы, которые нужно реализовать
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def area(self):
pass
@ab... |
num =str(input())
position=1
new= 0
new2=0
odd = []
k=0
even = []
for i in num:
position+=1
p = position -1
y= int(i)
if p%2!=0:
odd.append(y)
else:
even.append(y)
if len(num)%2!=0:
for values in even :
k =str((values*2))
for numbers in k:
... |
def gameended():
global ended
ended = True
def printans():
print("")
for i in range(strength):
print (players[i]+": "+str(alllist[i])+", Banned: " + str(banlist[i]))
def round(playerno):
index = playerno-1
print("")
print(players[index]+", it is your turn.")
takefrom... |
'''
This is the first api where it is able to take email address as primary
key and name with the specified requirements.
'''
from os import name
from flask import Flask, json, request, jsonify
import sqlite3
app = Flask(__name__)
def db_connection():
conn = None
try:
conn = sqlite3.connect('users.sql... |
# one.py
#1. 编写一个程序,它以球的半径(浮点数)作为输入,
# 并且输出球体的直径,圆周长,表面积和体积
# from math import pi
# def qiu():
# r = float(input("请输入球的半径:"))
# d = 2 * r
# c = pi * d
# s = 4 * pi * r **2
# v = 4 /3 * pi * r **3
# return d,c,s,v
# print(qiu())
#2. 一个员工的总工资,等于每小时的薪水*一周的工作时间+加班费.加班费是加班总时间
# 乘以每小时工资的1.5倍.
... |
import threading
from time import sleep
s = None
e = threading.Event()
def bar():
print('bar拜山头')
global s
s = "天王盖地虎"
def foo():
print("说出口令就是自己人")
sleep(2)
if s == "天王盖地虎":
print("我是你爸爸,自己人")
else:
print("打死他")
e.set()#等foo运行之后在运行
def fun():
print("呵呵....")
... |
# class Mylist(list):
# def insert_head(self,x):
# self[0:0]=[x]
# self.insert(0,x)
# myl=Mylist(range(3,6))
# print(myl)
# myl.insert_head(2)
# print(myl)
# class Human:
# def __init__(self,n,a):
# self.name=n
# self.age=a
# def infos(self):
# print("name",self.na... |
numbers = [10086, 10000, 10010, 95588]
names = ['中国移动', '中国电信', '中国联通']
for t in zip(numbers, names):
print(t)
for No, number, name in zip(range(1, 100),
numbers,
names):
print("序号",No, name, '的客服电话是:', number)
names = ['中国移动', '中国电信', '中国联通']
for ... |
def input_student():
L=[]
while True:
d={}
x=str(input("请输入姓名:"))
if x =="":
break
try:
y=int(input("请输入年龄:"))
if 0<=y<=100:
y=y
else:
return 0
except ValueError:
return 0
... |
# x=int(input("请输入长度:"))
# y=int(input("请输入宽度:"))
# print("长方形的周长为",(x+y)*2,"厘米")
# print("长方形的面积为", x*y,"平方厘米")
# pi=3.141592653
# r=float(input("请输入半径:"))
# print("圆的周长是",pi*r*2,"CM")
# print("圆的面积是",pi*r**2,"平方CM")
# 第一题
# print(" *")
# print(" ***")
# print(" *****")
# print("*******")
#第二题
# print("中国古代的2... |
import numpy as np
class ChannelFeature:
"""
Channel Generators create characteristics from the raw data. The aim of
ChannelFeatures is to collect statistics for each supervoxel and channel.
A ChannelFeature calculates from an (n,c)-shaped array statistics
for each channel c and returns a vect... |
# input() - 두 수를 입력받아 곱하는 프로그램
x = input("첫째수 입력 : ")
n1 = int(x) # 입력받은 문자를 숫자로 변환
y = input("둘째수 입력 : ")
n2 = int(y)
gob = n1 * n2
print("두 수의 곱 :", gob)
|
import time
import threading
# 멀티스레드(실행된 프로세스가 2개 이상인 것)
def long_task():
for i in range(5):
time.sleep(1)
print("working:%s\n" % i)
print('Start')
threads = [] #[t1, t2, t3, t4, t5]
for i in range(5):
t = threading.Thread(target = long_task) # 실행할 작업 생성
threads.append(t)
for t in thread... |
import heapq
class Solution:
def jobScheduling(self, startTime, endTime, profit) -> int:
mix = []
for i in range(len(profit)):
mix.append((startTime[i], endTime[i], profit[i]))
mix.sort()
pq = []
maxVal = 0
for start, end, val in mix:
while pq ... |
word = input("Please enter a word \t")
i = 0
while i < len(word):
print(word[i] , end=" ")
i+=1
print("")
y = -1
while y >= -len(word):
print(word[y], end=" ")
y -= 1
#Write a program to access each character of string in forward and backward direction by using while loop? |
Quantity =int(input("Enter number of students: "))
rec={}
i = 1
while i <= Quantity:
name = input("Please enter a name \t")
mark = input("Please enter a mark \t")
rec[name] = mark
i = i + 1
print("Name of Student", "\t", "% of marks")
for x,t in rec.items():
print("\t", x, "\t\t\t", t) |
'''
http功能演示
将网页发送给浏览器展示
再查找一下老师的代码
'''
from socket import *
def handle(connfd):
print('Request from:',connfd.getpeername())
request = connfd.recv(4096)
#为了防止客户端断开,客户端突然关闭,request为空的。
#为什么每次运行链接了两次?
if not request:
return
#将request按行分割
request_line = request.splitlines()[0].decode(... |
"""
Income: The Income class is used for generating cash flow for users.
Income is determined by three means (as defined by various financial institutions): 1. earned, 2. passive, and 3. portfolio.
"""
class Income():
"""
Model for income (earned, passive, portfolio).
"""
def __init__(se... |
#main.py
import re
myfile = open('english.txt', 'r')
def get_dict_rank(txt):
words = re.findall(r"[\w']+", txt.read())
'''
re.findall => 匹配正则表达式并返回一个list
r"[\w']+" => 匹配英文
'''
dictionary = {}
for word in words:
if word not in dictionary:
dictionary[word] = 1
... |
'''
File description:
This file contains the implementation of an A* algorithm,
based on the Rush Hour puzzle. The goal of this algorithm is
to find the shortest path to the solution possible.
Part of the implementation is cited from:
http://www.redblobstarts.com/pathfinding/a-star/implementati... |
# Kesimpulan
# Install Python dan Pygame
# Dasar Pemrograman Python (Variable, Collections, Control Flow, Function, Classes)
# Develop Game sambil belajar mengenai Pygame
# Mengakses Library Pygame
import pygame
# Mengatur ukuran layar
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
# Memberikan Judul Game
SCREE... |
year = int(input("Enter the year: "))
if year % 12 == 0:
print("The animal is monkey.")
elif year % 12 == 1:
print("The animal is rooster.")
elif year % 12 == 2:
print("The animal is dog.")
elif year % 12 == 3:
print("The animal is pig.")
elif year % 12 == 4:
print("The animal is rat.")
e... |
length = float(input("Enter the length of the field in feet: "))
width = float(input("Enter the width of the field in feet: "))
area = length * width
new_area = area / 43560
print(f"The area of the field is {new_area} acres.")
|
from sys import argv
script, filename =argv
txt = open (filename)
print "Here is your file %r " % filename
print txt.read()
print "Type your file name again:"
file_name_again = raw_input (">")
txt_again = (file_name_again)
txt_again = open (file_name_again)
print txt_again.read()
|
#Pandigital prime
#Problem 41
#We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example,
# 2143 is a 4-digit pandigital and is also prime.
#
#What is the largest n-digit pandigital prime that exists?
import string, itertools
#pan_nums = itertools.permutati... |
#!/usr/bin/env python
#coding=utf-8
'''
Created on 2017年5月8日
@author: Administrator
'''
arr=[1,2,3,4,5,6,7]
arr1=[x for x in range(10)]
print arr1
#删除元素;
del arr[-1]
print arr
#比较两个列表
print cmp(arr1,arr)
#返回最大值
print max(arr)
#扩展列表
arr.extend(arr1)
print arr
#获取匹配值的索引
print arr.index(3)
#插入元素
... |
import random
import string
stringlen = 5
i = 0
p= 0
satisfied = 'y'
result = []
while satisfied.lower() == 'y':
def passwordgen():
rand='' .join(random.choice(string.ascii_letters) for i in range(stringlen))
return f'{first_name[:2]}{last_name[-2:]}{rand}'
first_name=inpu... |
import sqlite3
import json
from pathlib import Path
with sqlite3.connect("db.sqlite3") as conn:
command = "SELECT * FROM Movies"
# when reading from a DB the cursor move and in an iterable
cursor = conn.execute(command)
for row in cursor:
print(row)
# with fetchall we get all in o... |
"""
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Sol... |
#!/usr/bin/python3
import sys
import json
TEXT_FILE_PATH = './text.json'
messages = None
def traverse(parent, path):
node = parent[path]
if (isinstance(node, str)):
if not ask_yes_no_question('{}{}'.format(messages.get('isItA'), node)):
animal = input(messages.get('itWas'))
q... |
# chapter 07: Dimensionality Reduction with PCA
### Performing Principal Component Analysis
import numpy as np
X = [[2, 0, -1.4],
[2.2, 0.2, -1.5],
[2.4, 0.1, -1],
[1.9, 0, -1.2]]
print(np.cov(np.array(X).T))
import numpy as np
w, v = np.linalg.eig(np.array([[1, -2], [2, -3]]))
w
v
# Dimensionality ... |
guess = ""
while guess != "a":
guess = input("Guess a letter: ") |
"""Given a set of candidate numbers (C) (without duplicates) and a target number (T)"""
"""find all unique combinations in C where the candidate numbers sums to T"""
"""The same repeated number may be chosen from C unlimited number of times"""
"""All numbers (including target) will be positive integers."""
"""The s... |
"""42. Trapping Rain Water """
"""Given n non-negative integers representing an elevation map where the width of each bar is 1"""
"""compute how much water it is able to trap after raining"""
"""example: Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. """
"""Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. """
"""ergodic fro... |
import random
# This is an exercise from codementor to create a game of rock, paper, scissors where the user plays against the computer.
# It uses the random.choice() function to pick the computer's choice. The user's choice is entered as the argument in the fucntion call.
# Next step might be to keep a scoring tally.... |
class Animal(object):
def __init__(self, name):
self.name = name
self.health = 0
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.name, "has health of:"
print self... |
'''Assignment: Type List
Write a program that takes a list and prints a message for
each element in the list, based on that element's data type.
Your program input will always be a list. For each item
in the list, test its data type. If the item is a string,
concatenate it onto a new string. If it is a number,
ad... |
mensaje="Hola"
mensaje2="¿Como estas?"
resultado=mensaje+mensaje2
print(resultado)
input(".....")
|
print("Quieres hacer una operacion?")
opcion= int(input("1/2"))
while opcion==1:
print("Escoja la accion a realizar")
print("""
1.- Suma
2.-Resta
3.- Multiplicacion
4.- Division
5.- Comparar 3 numeros
6.- IVA
7.- Multiplicacion indel
8.- Salir
""... |
print("Al que madruga Dios lo ayuda\n")
nombre="Andrea"
print("Tu nombre es:",nombre)
edad=int(input("Dame tu edad:"))
print("tu edad es:",edad,"años")
print("tu proxima edad es:",edad+1)
input("Presiona cualquier tecla para continuar....")
|
print("MENU")
def menu():
print ("Selecciona una opción")
print ("Sumar dos cantidades:1")
print ("Restar dos cantidades:2")
print ("Multiplicar dos cantidades:3")
print ("Dividir:4")
print ("Comprar dos cantidades:5")
print ("Calcular IVA :6")
print ("Multiplicacion:7")
print ("Salir:8")
... |
nombre=Andrea
apellido=Caldera
cuenta=314249612
estatura=1.70
variable=femenino
lista=[nombre,apellido,cuenta,estatura,variable]
print (lista)
lista.insert(0,"andrea")
print(lista)
input("...")
|
#!/usr/bin/env python3
"""
Reads in a series of values input by the user.
Computes an alternating sum of all values entered.
For example, if your programs reads
input:
1 4 9 16 9 7 4 9 11
then, it computes 1 - 4 + 9 - 16 + 9 -7 +4 -9 + 11 = -2
"""
import sys
def calc_alt_sum(values):
"""
Calculates al... |
# Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.
def max_subarray(array):
# This is a dumb approach, dont even pursue it. n**2 time complexity
base_list = array[:]
max_ret = array[0]
for number in range(len(array... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root: return 0
countl, countr = 1, 1
leftChild, rightChild = ... |
# 좌 또는 우에서만 숫자를 가져갈 수 있다.
# 가져간 숫자로 증가 수열을 만든다.
# 최대 증가 수열의 길이와, 왼쪽에서 빼갔는지 오른쪽에서 빼갔는지를 기록한다
from collections import deque
def solution(n, arr):
arr = deque(arr)
ans = []
res = [-1]
while arr:
last = res[-1]
if last > arr[0] and last > arr[-1]:
break
elif last > arr... |
class Solution:
def balancedStringSplit(self, s: str) -> int:
R, L, count = 0, 0, 0
for i in s:
if i is "R":
R += 1
if i is "L":
L += 1
if R and R == L:
count += 1
R,L = 0,0
return count ... |
# 자연수 n이 주어지면 1부터 n까지의 원소를 갖는 집합의 부분집합을 모두 출력하는 프로그램을 작성하시오
def main(n):
ch = [0 for x in range(n+1)]
print_subsets(1,n,ch) # ...1?
def print_subsets(v,n,ch):
if v == n+1:
ans = []
for i,x in enumerate(ch):
if x == 1:
ans.append(i)
if len(ans) > 0 :... |
def pick(n, picked, to_pick):
if to_pick == 0:
print(picked)
return
smallest = 0 if len(picked) == 0 else picked[-1]+1
for i in range(smallest, n):
picked.append(i)
pick(n,picked,to_pick-1)
picked.pop()
pick(6, [], 3) |
# f: 시작점
# t: 도착점
# b: 중간점
# a에서 b로 이동하는 함수
def move(a, b):
return [a, b]
# n개를 f에서 t로 옮기는 경로 2차원 배열
def path(n, f, b, t):
if n == 1:
return [move(f, t)]
answer = path(n-1, f, t, b) + [move(f, t)] + path(n-1, b, f, t)
return answer
def solution(n):
return path(n, 1, 2, 3)
|
import time
final = 0
total = 10
print('Contagem iniciada...')
while final <= 10:
print(total)
time.sleep(2)
total -= 1
final = total
if total == -1:
print('Contagem encerrada!!!')
break
|
lista1 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 'X']
print(f'Lista original: {lista1}')
temp = lista1[0]
lista1[0] = lista1[-1]
lista1[-1] = temp
print(f'Lista final: {lista1}')
|
clientes = {'Fernando' : '991357259',
'Alberto' : '981120491'}
novo_cliente = input('Digite o nome do cliente: ')
if novo_cliente in clientes.keys():
print(f'{novo_cliente} já existe na base de dados')
novo_cliente = input('Digite o nome do cliente: ')
else:
print(f'{novo_cliente} não está cad... |
from sys import argv
script, user_name = argv
#prompt = '> '
prompt = f'{script}> '
print(f"Hi {user_name}, I`m the {script} script.")
print("I`d like to like you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
print(f"Where do you live {user_name}?")
lives = input(prompt)
print(f"how... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 14:06:13 2018
@author: sam (skh50)
"""
def main ():
#welcome message
print("Welcome to Travel Agency's Hawaiian Airline airfare calculator! Seats to Hawaii begin at $2500.")
print("There are different discounts and fees depending on... |
class User:
'''
class to create users accounts and save their informations
'''
users_list=[] # Empty users list
def __init__(self,user_name,password):
'''
Method to define the properties for each user object
'''
self.user_name=user_name
self.password=pa... |
'''
Criar Programa que peça ao usuario digitar varios VALORES
NUMERICOS e cadastre-os em uma lista. caso o número já tenha sido digitado
ele não aceitaram. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
'''
núm = list()
while True:
n = int(input('Digite um valor: '))
if n not i... |
from random import randint
from time import sleep
pc = randint(0,5) # Faz o PC escolher um nr entre 0 e 5 aleatóriamente.
print('-=-'*20)
print('Vou pensar em um número entre 0 e 5. tente Adivinhar...')
print('-=-'*20)
jogador = int(input('Em que número eu pensei? ')) # Jogador tentando adivinhar
print('processing...'... |
from datetime import date
anoatual= date.today().year
anonasc=int(input('Ano de nascimento: '))
idade = anoatual - anonasc
print('Quem nasceu em {} tem {} anos em {}.'.format(anonasc, idade, anoatual))
if idade == 18:
print('Você tem que alistar IMEDIATAMENTE!')
elif idade < 18:
saldo = 18 - idade
print('Vo... |
# int = Parte inteira de um número (Função interna não precisa de pacote externo)
x=float(input('Digite um vaor: '))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(x, int(x)))
|
'''nome = str(input('Qual é seu nome? '))
if nome == 'Gustavo'
print('Que nome lindo você tem!')
print('Bom dia {}!'.format(nome))'''
n1 = float(input('Digite a 1ª nota: '))
n2 = float(input('Digite a 2ª nota: '))
m = (n1+n2)/2
print('A sua média foi {:.1f}'.format(m))
if m >= 6.0:
print('Parabéns você foi apr... |
'''
Digitar valores enquanto o usario quiser e coloque numa lista.
Depois informe Quantos numeros foram digitrados.
A lista de calores , orednada de forma decrescente.
Se o VAlor 5 foi digitado e está ou não na lista.
'''
valores = []
while True:
valores.append(int(input('Digite um valor: ')))
resp = str(in... |
nome=str(input('Qual é o seu nome? '))
if nome == 'Daniel':
print('Que nome bonito!')
elif nome == 'Pedro' or nome =='João' or nome == 'Erick':
print('Seu nome nem é tão bonito assim!')
elif nome in 'Ana Dan Elise Pepa':
print('Belo nome estranho')
else:
print('Seu nome é bem normal.')
print('Tenha um b... |
#Listas parte 1
'''num = [2,5,9,11,4,4,14,44]
num[2] = 3
num.append(7)
num.sort(reverse=True) # sort(ordenar / reverse(ao contrário)
num.insert(2,2)
if 5 in num:
num.remove(5)
else:
print('Não achei o número 4')
print(num)
print(f'Essa Lista tem {len(num)} elementos.')'''
#Desafio: Incluir input e Flag...e so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.