text stringlengths 37 1.41M |
|---|
print 'Digite o primeiro numero'
a = input()
print 'digite o segundo numero'
b = input()
print 'Digite o terceiro numero'
c = input()
print 'Maior valor:'
if a > b and a > c:
print a
elif b > c and b > a:
print b
elif c > a and c > b:
print c
elif a == b > c or a == c > b:
print a
elif b ... |
print 'Digite a nota 1'
a=input()
print 'digite a nota 2'
b=input()
r=(a*2+b*3)/5.0
print 'Nota final: ' + str(r)
|
print 'Digite o valor de A'
A1 = input()
print 'Digite i=o valor de B'
B1 = input()
A = B1
B = A1
print 'Valor de A: ' + str(A)
print 'Valor de B: ' + str(B)
|
print 'Digite o raio da lata'
a = input()
print 'Digite a altura da lata'
b = input()
v = a * b * 3.14159
d = round(v, 2)
print 'Volume da lata: ' + str(d) |
print 'Valor do produto'
a = input()
if a < 20:
print 'Valor de venda: ' + str(a+a*45/100.0)
else:
print 'Valor de venda: ' + str(a+a*30/100.0) |
print 'Digite o valor do salario'
a = input()
print 'Digite o valor da prestacao'
b = input()
c = a - a * 70 / 100
if b <= c:
print 'O emprestimo pode ser concedido'
else:
print 'O emprestimo nao pode ser concedido' |
print 'Digite o valor de N'
n = input()
a = 0
for i in range(2, n+1):
a = a + (1.0/i)
print 'Resultado da somatoria: ',a
|
l=[]
l2=[]
for i in range (5):
print 'Digite o valor',i,'da lista'
l.append(input())
for i in range (4,-1,-1):
l2.append(l[i])
print l2
|
m1=[]
m2=[]
m3=[]
print 'Digite a quantidade de linhas e colunas da primeira matriz respectivamente'
linha=input()
coluna=input()
print 'Digite a quantidade de linhas e colunas da primeira matriz respectivamente'
linha1=input()
coluna1=input()
if coluna!=coluna1 or linha!=linha1:
print 'As duas matrizes d... |
print 'Digite o valor 1'
a=input()
print 'Digite o valor 2'
b=input()
print 'Digite o valor 3'
c=input()
if a<b+c and b<a+c and c<a+b:
if a==b and b==c and c==a:
print 'Forma um triangulo Equilatero'
if a!=b and b!=c and c!=a:
print 'Forma um triangulo Escaleno'
if a==b!=c or a==c!=b or b==c!=a:
print 'Forma u... |
l1=[]
l2=[]
l3=[]
for i in range(10):
print 'Digie o valor',i+1,'da lista 1'
l1.append(input())
print 'Digie o valor',i+1,'da lista 2'
l2.append(input())
l3.append(l1[i]+l2[i])
print 'soma das duas listas',l3
|
import random
antal_gissningar = 0
n = random.randint(1, 20)
while True:
text = input("Gissning: ")
as_number = int(text)
if as_number == n:
print(f"Korrekt! \n"
f"Antal gissningar: {antal_gissningar}")
break
if as_number < n:
print("Fel, högre!")
antal_g... |
'''
Given an array arr of distinct integers and a nonnegative integer k, write a function findPairsWithGivenDifference
that returns an array of all pairs [x,y] in arr, such that x - y = k. If no such pairs exist, return an empty array.
'''
import copy
def findPairsWithGivenDifference(arr, k):
output = []
... |
import re
from os.path import exists, isfile
pathtofile = input('Введите путь к файлу\n')
if not exists(pathtofile):
print('Файла не существует')
if not isfile(pathtofile):
print('Файл - не файл')
try:
file = open(pathtofile, 'rt')
strings = file.readlines()
except:
print('Ой, эксепшн')
finally:
file.close()
f... |
def maxProfit(nums):
"""
:param nums:
:return:
"""
profit = 0
for i in range(len(nums) - 1):
sub = max(nums[i + 1:]) - nums[i]
profit = max(sub, profit)
return profit
if __name__ == '__main__':
nums = [7, 1, 5, 3, 6, 4]
print(maxProfit(nums))
|
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
# Load the iris dataset
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
# Create a linear regression object
regr = linear_model.LinearRegression()
# Fit the linear regression to our data
regr.fit(X, y)
# Print model coeffic... |
from sys import exit
def offier():
print "If you book 5 ticket then you have 30% discount "
confirm()
def confirm():
print"How many tickets"
choice =raw_input(">")
if choice == 'one':
print" your ticket is booked"
if choice == 'four':
offier()
if choice == 'five':
print " Thank you"
def ... |
def quickSort(array):
N = len(array)
ipiv = N-1
pivot = array[ipiv]
j=0
while j<ipiv:
if pivot <= array[j]:
array[ipiv] = array[j]
array[j] = array[ipiv-1]
ipiv = ipiv-1
array[ipiv] = pivot
else:
j+=1
#Now some recursi... |
#1. buat fungsi hitung depth
#2. buat fungsi print Level Order
#23 10 65 16 45 67 19 24 30
class Node:
def __init__(self, val):
self.info = val
self.left = None
self.right = None
def insertNode(self, val):
if(val < self.info):
if(self.left == None): self.left = Node(val)
... |
from bs4 import BeautifulSoup
import requests
import re
import os
import csv
import unittest
def get_titles_from_search_results(filename):
"""
Write a function that creates a BeautifulSoup object on "search_results.htm". Parse
through the object and return a list of tuples containing book titles (as print... |
# Creating a class, init function assigns values to object properties
class Cars:
def __init__(self, model, make, year):
self.model = "Ford"
self.make = make
self.year = year
def print_model(self):
print(self.model)
def print_make_and_year(self, make, year):
print... |
import requests,json
op = 1
while(op == 1): #main
cidade = input('Entre com a cidade:')
siglaPais = input('Entre com o pais:')
uri = 'http://api.openweathermap.org/data/2.5/weather?q=%s,%s'%(cidade, siglaPais)
resposta = requests.get(uri)
informacoes = json.loads(resposta.text)
temperat... |
from typing import List
#주어진 배열에서 가능한 모든 부분집합 반환
def subsets_recursion(nums: List[int],
res: List[List[int]], sub:List[int], index) -> None:
if len(sub) > len(nums):
return
res.append(sub.copy())
# sub를 그대로 넣으면 sub의 주소값이 복사됨
for i in range(index, len(nums)):
sub.append(nums[i])
... |
from typing import List
# 배열의 회전
# 각 요소를 우측으로 k번 이동 및 회전 (k>=0)
# 각 요소를 한번씩 k번 이동 시간복잡도 N*k
def rotate(nums: List[int], k :int)->List[int]:
for l in range(k):
prev = nums[len(nums)-1]
for i in range(len(nums)):
temp = nums[i]
nums[i] = prev
prev = temp
return... |
num = int(input("Enter number: "))
print([i for i in range(1, num) if num % i == 0])
|
import os
import sys
print("proba.py")
print("Привет, программист!")
name = input("Ваше имя: ")
print(name, ", добропожаловать в мир python!")
answer = ''
while answer != 'Q':
answer = input("Давайте поработаем? (Y/N/Q?)")
if answer == 'Y':
print("1. Вывести список файлов?")
print("2. Вывести информацию о сис... |
# Practical 2
# Submitted by : Abhishek
# College: Hindu College(Section A)
# date: 07-01-2021
while True:
d = 0
print("\t\t\t\t\t\t\t\t\t\tMENU\t\t\t\t\t\n\t\t\ta) +\t\tb) -\t\tc) *\t\td) /\t\te)//\t\tf) %\n")
c= input("Enter your choice: ").lower()
n=int(input("Enter the first number: "))
... |
def strchallenge(word):
y = list(word)
cx = 0
co = 0
for x in y:
if x == 'x':
cx += 1
elif x == 'o':
co += 1
if cx == co:
print('true')
print('no of x are ', cx)
print('no of o are ', co)
else:
print('flase')
... |
from data_preparation import data_processing
from neural_network import NeuralNetwork
import numpy as np
np.random.seed(1)
#We call the data_processing() method of data_preparation.py
#and we get the training and validation sets (inputs and outputs).
x_train, y_train, x_val, y_val = data_processing()
#We set the dim... |
import re
def delete_whitespaces(line):
i=0
if line == "":
return line
clear_line = line
while clear_line[0] == ' ' or clear_line[0] == '\n':
clear_line = clear_line[1:]
if len(clear_line) == 0:
return ""
i = len(clear_line)-1
while clear_line[i] == ' ' or ... |
import string
from word import choose_word
from images import MAGES
# choose_word=['preeti','chnachal','kumkum','bhagwati','karan','rinku','vicky','sunny']
# from images import IMAGES
def get_hint(secret_word,letters_guessed):
import random
letters_not_guesses=[]
index=0
while index<len(secret_word):
... |
from OO_complex import *
from math import sqrt
class Polynomial:
'''Initialize the object'''
def __init__(self, coefficients):
self.__coefficients = coefficients
@property
def coefficients(self):
'''To view outside the class'''
return self.__coefficients
def add(se... |
def read_one_float(msg):
num = float(input(msg))
return num
def read_two_floats():
side1 = read_one_float("Enter side1: ")
side2 = read_one_float("Enter side2: ")
return side1, side2
def compute_rectangle_area(side1, side2):
return side1 * side2
def compute_rectangle_perimeter(side1, side2... |
# Sample output 1
t1 = [50, 20, 30]
t2 = [40, 25, 15.5]
# Sample output 2
# t1 = [40,40,50,15,12.5]
# t2 = [25,40,80,20,10]
print('Teacher 1:')
print(t1)
print('Teacher 2:')
print(t2)
def read_day_list():
day_received = []
while True:
day_number = int(input("Enter day number: "))
if day_numb... |
# You will learn about the import statement later;
# for now, think of import turtle as importing functions in the turtle module, containing graphic functions;
# see the document at https://docs.python.org/3/library/turtle.html
import turtle
import time
# set up pen before draw the 6 hexagons
turtle.setheading(0)
turt... |
from cell import Cell
class Board:
def __init__(self, filename):
self.__cell_list = []
self.__length = 0
self.__width = 0
self.__read_board(filename)
def __read_board(self, filename):
f = open(filename, 'r')
rows = f.read().splitlines()
self.__width = in... |
from football import *
a = FileReadFromURL()
a.read(csv_url)
while True:
action = input("(s)how summary (e)nter results (q)uit: ").lower()
if action == 'q':
print("Bye")
break
if action == 's':
a.print_list_team()
elif action == 'e':
result = input("Enter a result: ")
... |
name_list = []
def menu_text():
if name_list:
return "(N)ew (S)how (D)elete (Q)uit : "
else:
return "(N)ew (Q)uit : "
def new_item():
global name_list
name = input("Name : ")
name_list.append(name)
return f"{name} added"
def show_item():
for index,name in enumerate(name_li... |
import math
def check_unit(ans):
"""Check plural (square meter or square meters)"""
if ans > 1:
return "square meters"
else:
return "square meter"
def cal_circle(r):
"""Calculate and return area result)"""
return math.pi*r*r
def cal_triangle(b,h):
"""Calculate and return area... |
class CardDeck:
def __init__(self):
SUITS = [1, 2, 3, 4]
RANKS = [i for i in range(2,15)]
deck = []
for rank in RANKS:
for suit in SUITS:
card = str(rank) + ' ' + str(suit)
deck += [card]
self.card_deck = deck
def shuffle(s... |
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object(name=%s)'% self.name
__repr__ = __str__
s = Student('Michael')
print(s)
class Fib(object):
def __init__(self):
self.a,self.b = 0,1
def __iter__(self):
return ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
queue = []
level_queue = []
result = []
if root... |
from typing import List, Dict, Tuple
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
count = 0
result = 0
def mid(self, p, k):
if p == None:
return
... |
from typing import List, Dict, Tuple
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
return self.f(0, len(preorde... |
#!/usr/bin/env python3
# This is a cli front end to the feelings.py backend
# feelings data can be passed in as arguments when calling this script, and if
# they do not exist, the script will prompt for the appropriate information
import feelings
import sys
f = []
#if len(sys.argv) == 8:
# for r in range(1,9):
# ... |
from utils import *
def only_choice(values):
"""Finalize all values that are the only choice for a unit.
Go through all the units, and whenever there is a unit with a value
that only fits in one box, assign the value to this box.
Input: Sudoku in dictionary form.
Output: Resulting Sudoku in dict... |
#5.15, 5.16, 5.18, 5.26, 5.39.
#5.15
def vowels(sentence):
for i in range(len(sentence)):
if sentence[i] in 'aeiouAEIOU':
print(i)
#5.16
def indexes(word,alph):
acct=[]
for i in range(len(word)):
if word[i]==alph:
acct.append(i)
return acct
#5.1... |
a=int(input("Primul nr e"))
b=int(input("Al doilea nr e"))
c=int(input("Al treilea nr e"))
if (a>0) and (b>0) and (c>0):
if b>=c:
print(b)
else:
print(c)
else :
print(a+b) |
'''
哪些问题适合用递归解决
怎么用递归的方式写程序
***** 递归的三大法则
递归也是一种迭代
什么是递归?
一、递归的定义
递归是一种解决问题的方法,它把一个问题分解为越来越小的子问题,直到问题的规模
小到可以被很简单直接解决。
通常为了达到分解问题的效果,递归过程中要引入一个***调用自身的函数***
[1,2] [3,3] [6,4]
计算 [1,2,3,4,5,6,7] 的和
迭代求和
def list_sum(my_list):
the_sum = 0
for... |
"""ex38.py - Doing things to lists
Class: LearnPythonTheHardway (Py2.7)
Author: Michael Saminsky
Date: 2017-08-22
"""
import time
ten_things = "Apples Oranges Crows Telephone Hates Light"
print " Wait there are not 10 things in that list. let's fix that"
stuff = ten_things.split(' ')
more_stuff = ['day','ni... |
"""ex33.py - excercise on While loops
Class: LearnPythonTheHardway (Py2.7)
Author: Michael Saminsky
Date: 2017-08-21
"""
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i+1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The num... |
"""ex39.py - Dictionaries
Class: LearnPythonTheHardway (Py2.7)
Author: Michael Saminsky
Date: 2017-08-22
"""
# Lists have brackets around the object(s)
things = ['a','b','c','d']
print things[1]
# dicts have curly braces
stuff = {'name': 'Zed', 'age':39, 'height':6*12+2}
print stuff['name']
print stuff['heigh... |
# coding: UTF-8
# タプル ー 値の変更を許さない
t = (2, 5, 8)
print t
print len(t)
print t * 3
# t[2] = 100
l = list(t)
print l
l[2] = 100
print l
tt = tuple(l)
print tt
|
sales = [100, 200, 300, 400,20,range(3),"horihori"]
sales.sort()
#sales.reverse()
print sales
d = "2013/12/19"
print d.split("/")
a = ["a","b","c"]
print "----".join(a)
|
# coding: UTF-8
# No.1 Python Study 2015/06/11
# 数値
# 整数、少数、複素数
# 演算子 + - * / // % **
# 50
print 10*5
# 3
print 10 // 3
# 1
print 10 % 3
# 8
print 2 ** 3
# 整数と小数の演算 → 小数
# 7.0
print 5 + 2.0
# 整数同士の割り算 → 切り捨ての整数
# 3
print 10 / 3
# 3.333333...
print 10 / 3.0
# -4 OS依存で結果が変わる
print -10 / 3
# -3.33333...
print -10... |
# coding: UTF-8
# No.1 Python Study 2015/06/11
# 数値 <> 文字列
# 文字列 → 数値 int float
# 数値 → 文字列 str
# print 5 + "5" error
print 5 + int("5")
print 5 + float("5")
age = 20
print "i am " + str(age) + " years old!" |
# coding: UTF-8
# 関数を使う
# 複数の処理をまとめて定義する
# def の次に関数名() を書いて、インデントをつけて処理を記述する
def hello():
print "hello"
# 関数を呼ぶ時は 関数名() と書けばOK
hello()
# 引数を渡す場合は、()に引数を書く 初期値をつける場合は num = xとする
def kobaphone(name, num = 1):
# 関数を呼び出された時に、呼び出した際の引数を name に代入して処理を実行
print "プルプルプル %s" % name * num
def kobakaeri(name):
# 返り値としたい場... |
# coding: UTF-8
# リストに入れるのは同じ型でなくてもいい
sales = [255, 100, 353, 400]
# len + * []
print len(sales) #4が返ってくる
print sales[2] # 353
sales[2] = 100 # salesの[2]に100を置き換え
print sales[2] # 100
# inでリストに該当の値があるかどうか判定 真偽値
print 100 in sales # True
print 101 in sales # False
# rangeで連番を作ることも可能
# 0から9までの連番を作成
print range(1... |
# coding: UTF-8
# オブジェクト(変数と関数をまとめたもの)
# クラス:オブジェクトの設計図
# インスタンス:クラスを実体化したもの
class User(object):
def __init__(self, name):
self.name = name
def greet(self):
print "my name is %s!" % self.name
cuda = User("Cuda")
nash = User("Nash")
print cuda.name
cuda.greet()
nash.greet()
|
#Different python set methods
mySetNames = {"Alex", "Chloe", "Jane", "Rick", "Morty"}
mySetNames2 = mySetNames.copy()
print(mySetNames)
print(mySetNames2)
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
print(a.issubset(b))
print(b.issubset(a))
print(a.issuperset(b))
print(b.issuperset(a))
#built-in functions with set
#all
mySe... |
user = input ("Input your user name: ")
def write_username():
with open ("./user_name.txt", mode="w") as f:
f.write(user)
def read_username():
with open ("./user_name.txt", mode="r") as f:
user = f.read()
print (user)
write_username()
read_username ()
|
print("Cities I should visit")
NextDestination = ['tokyo', 'berlin', 'amsterdam', 'london', 'new york', 'istanbul']
# in, not in
cityName = 'tokyo', 'berlin', 'amsterdam', 'london', 'new york', 'istanbul'
cityName = input("Choose your first destanation: ")
if cityName in NextDestination:
print(f'{cityName} is Yo... |
import unittest
from MinMax import get_min_max
class MinMaxTest(unittest.TestCase):
def test_find_min_max(self):
minimum, maximum = get_min_max([4, 5, 3, 2, 9, 6, 7, 1, 8, 0])
self.assertEqual(0, minimum)
self.assertEqual(9, maximum)
def test_should_raise_value_error_if_array_is_emp... |
def sort_012(input_list):
if len(input_list) <= 0:
return input_list
zero_index = 0
index = 0
two_index = len(input_list) - 1
while zero_index <= two_index:
if input_list[two_index] == 2:
two_index -= 1
continue
if input_list[zero_index] == 0:
... |
import _heapq
import itertools
import time
class Scheduler:
""" Allows tasks to be scheduled for execution (or canceled).
The purpose of this class is to provide a way for tasks to be scheduled
and run in a pollable pattern. The only requirement for a Scheduler to be
used is for the thread to be call... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
An irrational decimal fraction is created by concatenating the positive
integers:
0.123456789101112131415161718192021...
It can be seen that the 12^(th) digit of the fractional part is 1.
If d_(n) represents the n^(th) digit of the fractional part, find the
value of... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
A googol (10^(100)) is a massive number: one followed by one-hundred
zeros; 100^(100) is almost unimaginably large: one followed by two-hundred
zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^(b), w... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Starting in the top left corner of a 2×2 grid, there are 6 routes
(without backtracking) to the bottom right corner.
How many routes are there through a 20×20 grid?
"""
# Since the only available directions are right and down, the number
# of routes is just the numbe... |
#!/usr/bin/env python
"""
The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + ... + 10^(2) = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^(2) = 55^(2) = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, ^(5)C_(3) = 10.
In general,
^(n)C_(r) = n! / r!(n−r)!
where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
The following iterative sequence is defined for the set of positive
integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following
sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial
of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
"""
import math
def getlimit():
"""Return the... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7. Similarly we can work from
right to left: 3797, 379, 37, and 3.
Find the sum of the ... |
"""Data Types Tree Package"""
class BinaryTreeNode(object):
"""Tree Node"""
def __init__(self, key, parent=None):
self.key = key
self.parent = parent
self.left = None
self.right = None
def find(self, key):
if self.key == key:
return self
if s... |
"""Matrix Zero-Setter Package"""
def matrix_zero(matrix):
"""Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column is set to 0."""
# O(n^2) time, O(m+n) space
m = len(matrix)
if m == 0:
return matrix
n = len(matrix[0])
rows_to_delete = set()... |
"""Find Sum Package"""
def find_sum(root, desired_sum, level=0, buffer_list=None, result=[]):
"""
You are given a binary tree in which each node contains a value
Design an algorithm to print all paths which sum up to that value
Note that it can be any path in the tree - it does not have to start at t... |
"""Data Types Package"""
class LinkedListNode(object):
"""LinkedList Node"""
def __init__(self, value):
self._value = value
self.next = None
@property
def value(self):
return self._value
class LinkedList(object):
"""LinkedList (add-to-head version)"""
def __init__... |
import pandas as pd
df = pd.read_csv('PlayTennis.csv')
print("\n Input Data Set is:\n", df)
t = df.keys()[-1]
print('Target Attribute is: ', t)
# Get the attribute names from input dataset
attribute_names = list(df.keys())
#Remove the target attribute from the attribute names list
attribute_names.remove(t)
print('Pred... |
from threading import Thread
import random
import time
class Resource:
def __init__(self):
self.value = 1
class NumberPrinter(Thread):
def __init__(self, thread_id, resource):
Thread.__init__(self)
self.thread_id = thread_id
self.resource = resource
def run(self):
... |
'''
Introducing 'while' and 'for' loops,
Demonstrating how each of them determine end state
Demonstrating how 'contiune' and 'break' affect the loop
'''
# While loop
a = 0
while a < 5:
print('a is ', a)
a = a + 1
print()
# For loop
for b in range(5):
print('b is ', b)
print()
list_of_fruits = ['apple', 'orange'... |
'''
Introducing logical operators such as '+', '-', '*', '/', 'or', 'and', etc
'''
print(2 + 3) # print the value of 1 + 2
a = 2
b = 3
print(a + b) # find the value of a and b, and then print the result of a+b
print(a - b) # minus
print(a * b) # multiplication
print(a / b) # division, this print 0, which is not we ex... |
#!/usr/bin/python3
import re
num = input().strip()
print(num)
if (bool(re.search(r'^[0-9.,]+$',num))):
matches = re.split("[,.]+",num)
print(num,matches)
if '' in matches:
matches.remove('')
print(num,matches)
if(len(matches)>0):
for i in matches:
print(i)
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
list=[]
dos= int(input())
while(dos>0):
command = input()
do = command.split()
if len(do)<=0:
continue
# com = do[0]
if do[0] == 'insert':
list.insert(int(do[1]),int(do[2]))
elif do[0] == 'append':
li... |
import random
print ('to stop anytime enter: ass')
score = 0
games = 0
while True:
# Here starts code to take input from user
games += 1
player = input('Choose and enter - Rock, Paper or Scissors: ')
if player == 'ass':
print ('Game over, see you later!')
break
if player == 'Rock':
... |
import sys
import cards
class Guide:
def __init__(self) :
self.launch()
def launch(self) :
self.introduction()
print("Press: \n0 - View Flash Cards \n1 - Add Flash Cards \n2 - Edit Flash Cards \n3 - Quit Application")
user_response = sys.stdin.readline().strip()
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
return self.buildTreeUtil(... |
import math
# fraction is tuple where:
# fraction[0] = nominator; fraction[1] = denominator
def simplify_fraction(fraction):
fraction = ensure_fraction(fraction)
gcd = math.gcd(fraction[0], fraction[1])
return (fraction[0] // gcd, fraction[1] // gcd)
def ensure_fraction(fraction):
nominator, denominator = fra... |
def closest_to (dist, gas_stations):
closest_station = 0
for station in gas_stations:
if station < dist:
closest_station = station
else:
return closest_station
return closest_station
def gas_stations(distance, tank_size, stations):
visited_stations = []
current_distance = 0
while current_distance <= ... |
# Implement deep_find_all(data, key)
# which finds the given key in the data
# and returns array of the found values.
from collections.abc import Iterable
# BFS
def deep_find_all_bfs(data, key_to_search):
queue = list(data.items())
result = []
while queue:
key, value = queue.pop(0)
if ke... |
import unittest
from song import Song
from playlist import Playlist
class TestPlaylist(unittest.TestCase):
def test_init_playlist_with_no_songs(self):
playlist = Playlist('my playlist')
self.assertEqual(playlist.get_index_of_last_played_song(), -1)
def test_add_new_song_to_playlist(self):
song1 = Song(title=... |
from bill import Bill
from batchBill import BatchBill
class CashDesk:
def __init__(self):
self.__dict = {} # bill: how many times we have it
def get_dict(self):
return self.__dict
def __add_to_dict(self, bill):
if bill in self.__dict:
self.__dict[bill] += 1
else:
self.__dict[bill] = 1
def take_mon... |
my_string= list(input ('Введите строку '))
my_string.reverse()
print('Перевернутая строка:', ''.join(my_string)) |
# 1. Написать скрипт, осуществляющий шифрование фразы, введенной пользователем,
# по методу из ДЗ-3, задание 5 (после каждой буквы исходной фразы, добавлять определенное
# число случайных символов, букв латинского алфавита. Чтобы скрыть первую букву, добавили и
# перед ней такое же количество случайных символов. Ваш... |
# написать скрипт, который предлагает пользователю ввести число,
# проверяет, если пользователь ввел символы, отличные от цифр (вспомнить подходящие методы строк) - то генерирует случайное число,
# пишет, что число сгенерировано.
# Выводит на печать число(сгенерированное или введенное) и его квадрат
import random
m... |
def ost(a):
if a % 3 == 0:
print(f'Число {a} кратно 3')
else:
print(f'Число {a} не кратно 3')
print ('До свидания!')
return None
a = int(input('Введите число:'))
ost(a)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : 17_reverse_list.py
# Author : lryong <15816537946@163.com>
# Date : 06.05.2019
# Last Modified Date: 06.05.2019
# Last Modified By : lryong <15816537946@163.com>
# 输入一个链表,反转链表后,输出新链表的表头。
# def __init__(self, x):
# ... |
# -*- coding:utf-8 -*-
# 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return ss
char_list = []
self.gen_str(ss,char_list,"")
return sorted(list(set(char_list)))
def gen_str(self,ss,cha... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : 07_fibonacci.py
# Author : lryong <15816537946@163.com>
# Date : 13.04.2019
# Last Modified Date: 13.04.2019
# Last Modified By : lryong <15816537946@163.com>
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 现在要求输入一个整数n,请你输出斐波那... |
# -*- coding:utf-8 -*-
# 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
class Solution:
def maxInW... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
class Solution:
def jumpFloorII(self, number):
if number <= 0:
return -1
else:
#return (number - 1) << 1
return pow(2, number-1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.