text stringlengths 37 1.41M |
|---|
x = "python is the best choice"
#f포맷형식으로 문자열 출력하기
print(f'{x:!^30}')
#포맷형식으로 문자열 출력하기
print('{0:!^30}'.format(x))
#기본 함수 count
print(x.count('p'))
# |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
lca = None
def Lowest_Common_Ancestor_of_bst(self, root, val1, val2):
if root == None:
return Fa... |
"""
百分制成绩转换为等级制成绩
如果输入的成绩在90分以上(含90分)输出A;80分-90分(不含90分)输出B;70分-80分(不含80分)输出C;60分-70分(不含70分)输出D;60分以下输出E。
"""
grade = int(input("your grade is "))
if grade < 60 :
print("E")
elif grade < 70 :
print("D")
elif grade < 80 :
print("C")
elif grade < 90 :
print("B")
else :
print("A") |
#输出100以内所有的素数
for i in range(1,101) :
test = i
#test = int(input("输入一个正整数"))
#if test <= 1 :
#print("输入一个正整数")
flag=1
for i in range(2,test) :
if test % i ==0 :
flag = 0
break
"""
if flag == 0 :
print("no")
else :
print("yes")
... |
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
# https://drive.google.com/file/d/1JbdCQuVEjihRc3hV-QbY97-2hAA5VbPa/view?usp=sharing
import string
a = input('Введите первую букву: ')
b = input('Введите вторую букву: ')
first_pos = string.ascii_let... |
from cs50 import SQL
import sys
import csv
# Check numbers of arguments
if len(sys.argv) != 2:
print("Usage: python roster.py houseName")
sys.exit(1)
# Connection to the DB
db = SQL("sqlite:///students.db")
# Name of the house to look for
house = sys.argv[1]
# Query the DB
rows = db.execute("SELECT * FROM st... |
#!/usr/bin/env python2
import numpy as np
import os
import sys
'''
This function takes a list of North-East-Down (NED) coordinates from a specified file and rotates them in 2D space so that the North direction is aligned with the specified heading. The Down coordinates are unchanged by this function.
Usage:
python ... |
#!/usr/bin/env python3
"""
Show Foreign Currency/PLN pair.
It is based on Polish Central Bank (NBP) fixing exchange rate.
"""
import argparse
from exchange_rate.helpers.version import package_version
from exchange_rate.exchange_rate_to_pln import ExchangeRateToPLN
_DESCRIPTION = "Shows Foreign Currency/PLN pair based... |
'''
This is a program for a simple BlackJack game
A deck of 52 cards will be used and a single player plays against the dealer (computer)
The player may place a bet
For simplicity, only features like hit and stand are available
features like split, double, and insurance will be added in later versions
'''
imp... |
class MessageBroker(object):
"""
This class represents broker for the messages of a simulation
"""
def __init__(self, messages_to_be_transmitted = None):
"""
Constructor.
messages_to_be_transmitted -- The message that are to be transmitted
"""
self.to_be_transmi... |
i= int(input("Por favor, introduzca un número:"))
if i < 20 :
print("El número",i,"se encuentra en el rango < 20")
elif i >= 20 and i < 40:
print("El número",i,"se encuentra en el rango de 20 a 39")
elif i >= 40 and i < 60:
print("El número",i,"se encuentra en el rango de 40 a 59")
elif i >= 60:
... |
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специа... |
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
#Подсказка: попробуйте... |
"""Closed form expression, Binet's formula.
.. seealso:: https://en.wikipedia.org/wiki/Fibonacci_number
"""
import math
SQRT_5 = math.sqrt(5)
def fib(nmax, sqrt_5=SQRT_5):
"""Compute a fibonacci number, Fib(n)."""
kvar = 1 / sqrt_5
return kvar * (((1 + sqrt_5) / 2) ** nmax - ((1 - sqrt_5) / 2) ** nmax)... |
smallLetters = raw_input("Unesite bilo koju rijec pritisnite enter pa vidite sto se desava: ")
print("\n Vasa prva rijec: " + smallLetters.upper())
capitalLetters = raw_input("\n Unesite jos jednu rijec: ")
for letter in capitalLetters:
if letter != capitalLetters.lower() :
print ("\n Vasa druga rijec pr... |
msgbox = '''
*******************************************************
欢迎使用20级计院13班蜡笔3小新的的恺撒密码系统
*******************************************************
'''
print(msgbox)
def jiami():
wz = input("请输入需要加密的英文:")
k = int(input('请输入偏移值(默认为3):') or 3)
for c in wz:
if "a"<=c<="z":
pri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Dec 7, 2014
@author: Guilin
'''
import re
def getValue(s,key):
key=key+':'
list1= re.split(key, s)
for i in range(len(list1)):
if list1[i][-1]==',' or list1[i][-1]=='{':
list2=re.split(r',|}',list1[i+1])
return lis... |
# 파이썬연습 -딕셔너리
# {Key1:Value1,Key2:Value2,...}
# dic = {'name':'shin','phone':'01012348808','birth':'0312'}
a= { 1: 'hi'}
# a={'a':[1,2,3]}
# 딕셔너리 쌍 추가하기
a[2]='b'
a['name']='pey'
a[3]=[1,2,3]
print(a)
# 딕셔너리 요소 삭제하기
del a[1]
print(a)
grade ={'shin': 30, 'june': 24}
print(grade['shin'])
dic = {'name':'shin','phon... |
# 파이썬 연습 - 집합 자료형
s1 =set([1,2,3])
print(s1)
s2 = set("Hello")
print(s2)
# set의 특징 1. 중복을 허용하지 않는다. 2. 순서가 없다
l1=list(s1)
print(l1)
t1=tuple(s1)
print(t1)
# 집합 자료형 활용하는 방법
s1= set([1,2,3,4,5,6])
s2= set([3,4,5,6,7,8])
# 1. 교집합 &
print(s1&s2)
print(s1.intersection(s2))
# 2. 합집합 |
print(s1|s2)
print(s1.union(s2))
#... |
# pandas : 표, 데이터를 다루기 위한 Series 클래스
# DataFrame 클래스를 제공
# 파이썬에서 사용하는 엑셀
# 시리즈 데이터 : 데이터를 1차원 배열이나 리스트의 형식으로 표현한 것을
# 시리즈 클래스 생성자에 넣어 주면 시리즈 클래스 객체 생성
import pandas as pd
# 2017년 지역별 인구수
city = pd.Series([9857426, 1502227, 2475231, 3470635],
index=["서울","대전","대구","부산"])
# index ... |
import pandas as pd
# csv 파일 읽기
# pandas 에 read_csv() 를 사용하면 DataFrame 으로 값을 가져옴
print("----- 행 인덱스가 없는 csv 파일 읽기 ------")
csv_data1=pd.read_csv('sample1.csv', sep=",", dtype='unicode')
# 행 인덱스는 지정하지 않으면 자동으로 부여 0~정수로
print(csv_data1)
# ---------------------------------------------------------
csv_data1=pd.... |
"""
import tkinter as tk
window=tk.Tk()
def open():
pass
def exit():
window.quit()
menubar = tk.Menu(window)
filemenu=tk.Menu(menubar)
filemenu.add_command(label="열기",command=open)
filemenu.add_command(label="종료",command=exit) #quit
menubar.add_cascade(label="파일", menu=filemenu)
window.config(menu=menub... |
#!/usr/bin/env python
# coding=utf-8
# import numpy as np
# import matplotlib.pyplot as plt
# x = np.arange(0, 5, 0.1);
# y = np.sin(x)
# plt.plot(x, y)
# plt.show()
import numpy as np
import matplotlib.pyplot as mpl
from TFANN import MLPR
from sklearn.preprocessing import scale
pth = 'yahoostock.csv'
A = np.loadt... |
import re
text = "name=Milk;amount=200;unit_price=0.9\nname=Bread;amount=134;" \
"unit_price=3.48\nname=Butter;amount=58;unit_price=1.65\nname=Cheese;" \
"amount=260;unit_price=4.35"
products = re.split("\n", text)
#print(products)
sum = 0
for i in products:
product = re.split(";",i)
print(produ... |
months = {'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 'June': 30, 'July': 31,
'August': 31, 'September': 30,'October': 31, 'November': 30, 'December': 31}
#Months which have 30 days
print("Months which have 30 days")
for key in months.keys():
if months.get(key) == 30:
prin... |
print('Enter n greater than 1\n')
n = eval(input(':'))
print('Enter m greater than 1\n')
m = eval(input(':'))
def sum_values(n, m):
#sum = 0
if n == m:
return n
return n + sum_values(n+1,m)
print(str(sum_values(n,m)))
#print(str(sum_values(2,100)))
|
text = "name=Milk;amount=200;unit_price=0.9\n" \
"name=Bread;amount=134;unit_price=3.48\n" \
"name=Butter;amount=58;unit_price=1.65\n" \
"name=Cheese;amount=260;unit_price=4.35"
products=text.split("\n")
price_sum = 0
for p in products:
print(p)
product_info = p.split(";")
amount_str ... |
import turtle
import time
screen = turtle.Screen()
s=turtle.Screen()
t=turtle.Turtle()
t.hideturtle()
t.penup()
t.setx(-20)
t.sety(-120)
t.pendown()
t.pensize(3)
t.circle(100)
t.penup()
t.setx(0)
t.sety(0)
t.setx(-50)
t.setheading(150)
t.pendown()
t.circle(50, 60)
t.penup()
#Here we set coordinates for left eye
t.set... |
class Car():
def __init__(self, name, speed):
self.__name = name
if(speed >= 250):
self.__speed = 250
else:
self.__speed = speed
self.__gear = 1
def get_name(self):
return self.__name
def set_speed(self, speed):
if(speed >= 250):
... |
import math
class SquareManager:
def __init__(self, side):
self.side = side
self.area = side*side
self.perimeter = side * 4
self.diagonal = math.sqrt(2) * side
if __name__=="__main__":
sm=SquareManager(3)
print(f"The area of the square with side {sm.side} = {sm.area}")
... |
# Program to find product of numbers in a list:
def product(x):
s=1
for i in x:
s = s * i
return s
print product([1,2,3,3,4])
|
class BankAccount:
def __init__(self):
self.balance=0
def deposit(self,amount):
self.balance += amount
return self.balance
def withdraw(self,amount):
self.balance -= amount
return self.balance
a=BankAccount()
b=BankAccount()
print a.deposit(100)
print b.deposit(50)
print b.withdraw(10)
print a.withdraw(10)... |
def cumulative_product(s):
p=1
l=[]
for i in s:
p=p*i
l.append(p)
return l
print cumulative_product([4,3,2,1])
|
import re
def make_slug():
a=re.findall(r'\w+',s)
print '-'.join(a)
s=raw_input('Enter the string:\n')
make_slug()
|
def unique(x):
y=[]
for i in x:
if i.lower() not in y:
y.append(i)
return y
print unique(["python", "java", "Python", "Java"])
|
#Implement a function product to multiply 2 numbers recursively using + and - operators only.
def product(x,y):
if x<0 and y<0:
if y==0:
return 0
else:
return abs(x)+product(abs(x),abs(y)-1)
elif x<0 and y>0:
if y==0:
return 0
else:
... |
# Comment peut-on permettre à l'utilisateur de sortir de la boucle
# en modifiant les lignes de code dans la boucle while ?
continuer = "o"
while continuer == "o":
print("On continue !")
test = input("Voulez-vous continuer ? o/n ")
if (test == "o" or test == "Oui" or test == "OUI"):
break
else:... |
#!/usr/bin/env python3
#
# Use extended Euclid's algorithm to solve Diophantine equations efficiently.
#
# Given three numbers a>0, b>0, and c, the algorithm should return some x and y such that
#
# ax+by=c
#============================================================================================================
de... |
#!/usr/bin/env python3
def square(x): return x * x
def mod_exp(x, n, mod):
if n == 0: return 1
if (n % 2 == 0):
return square(mod_exp(x, n / 2, mod)) % mod
else:
return (x * mod_exp(x, n - 1, mod)) % mod
def main():
print("Raise an integer to an exponent.")
a = int(input("Enter a: ... |
# print a pyramid like this
# level = 5
# *
# * *
# * * *
# * * * *
# * * * * *
def print_pyramid(levels):
# notice the pattern itself has SPACES
# cells per row = number of pattern in last row
# 1 -> 3 -> 5 -> 7 ->....which is an A.P, nth term=a+(n-1)*d
cells_per_row = 1 + (levels - 1) * 2
... |
# --- Directions
# Given a string, return the character that is most
# commonly used in the string.
# --- Examples
# maxChar("abcccccccd") === "c"
# maxChar("apple 1231111") === "1"
import pytest
def max_char(s):
max_count, max_char = 0, None
char_counter = {}
for c in s:
if c in char_counter:
... |
class sintaxys_try:
#diferentes casos para aplicar el TRY
def suma(self, num1,num2):
try:
if num1<0:
raise Exception ('quiero este if')
except:
return 'No aplica el if'
else:
return num1+num2
def multipli(self, num1, num2):
try:
if not type(num1) is int:
raise TypeError('solo integer... |
"""Program greets user and describes what's the purpose of the program
Program asks user to enter number of kilometers.
User enters the amount of kilometers.
Program converts these kilometers into miles and prints them.
Program asks user if they'd want to do another conversion.
If yes, repeat the above process (except ... |
# https://www.youtube.com/watch?v=J4wbwvkY4lM
import sys
from Tkinter import *
import time
def tick():
time_string = time.strftime("%H:%M:%S")
clock.config(text=time_string)
clock.after(200,tick)
global time1
global time2
global time3
if time_string == time1:
time.sleep(0.9... |
'''
def IsPrime(num):
if num < 2:
return False
divisor = 2
while divisor < num:
if num % divisor == 0:
return False
else:
divisor = divisor + 1
return True
'''
import math
def IsPrime(num):
if num < 2:
return False
divisor = 2
temp = i... |
import operator
def clean(s):
word = ""
for letter in s:
if letter.isalpha():
word = word+letter
#print(word)
return word.lower()
input_file = open("a-study-in-scarlet.txt", "r")
count_dict = {}
for line in input_file:
#print(line, end="")
split_line = line.split(" ... |
zoo = ("lions", "tigers", "bears", "sheep", "zebra",
"donkey", "monkey", "snake", "turkey", "gerbil")
print(zoo)
print(zoo.index("tigers"))
animal_to_find = "gerbil"
if animal_to_find in zoo:
print("Animal found")
animal_to_find = "hampster"
if animal_to_find in zoo:
print("Animal found")
zoo1 = ("l... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
l1 = list(tuple_a) + [0, 0]
l2 = list(tuple_b) + [0, 0]
l3 = [l1[0] + l2[0]] + [l1[1] + l2[1]]
return tuple(l3)
|
#!/usr/bin/python3
def islower(c):
val = ord(c)
if val >= 97 and val <= 122:
return (True)
else:
return (False)
|
#!/usr/bin/python3
def search_replace(my_list, search, replace):
new_matrix = my_list[:]
for i in range(len(new_matrix)):
if search == new_matrix[i]:
new_matrix[i] = replace
return new_matrix
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
new_dict = dict(a_dictionary)
liste = sorted(a_dictionary.keys())
for item in liste:
new_dict[item] = a_dictionary[item] * 2
return new_dict
|
#!/usr/bin/python3
"""Class that inherits from list"""
class MyList(list):
"""Class MyList"""
# method
def print_sorted(self):
"""method print list in ascending sort"""
print(sorted(self))
|
from random import randint
import time
def selection_sort(array):
start = 0
for i in range(len(array)):
min_index = start
for j in range(start, len(array)):
if array[j] < array[min_index]:
min_index = j
array[min_index], array[i] = array[i], array[min_inde... |
def exp_sum(n,n):
if n == 1:
return 1
if start > n:
return exp_sum(n,n)
sum = 0
for i in xrange(1,start):
sum += exp_sum(n-i, i)
print sum
return sum
exp_sum(3,1)
|
#Required Code
# 1. import servo_angles #Imports Module
# 2. Servo = servo_angles.servo #Call the class variable anything you want but adapt the bellow building blocks
#'Do the Action' Code #Bellow assumes you called the class variable (Required 2.) to Servo. I... |
#匿名函数的应用
li=[[1,2],[3,33],[3,4553,6]]
li.sort(key=lambda x: x[0])
print(li)
#过滤数据
# filter()
#
# # 处理数据
# map()
#
# #识别数据类型,执行
# eval()
#执行python代码
data = """
def login():
print('1111111111')"""
exec(data)
#聚合函数
title=['a','b','c']
value=[1,2,3,4]
data=zip(title,value)
print(dict(data))
|
# _*_coding:utf-8_*_
from cal_time import cal_time
@cal_time
def linear_search(li, val):
for index, v in enumerate(li):
if v == val:
return index
return None
@cal_time
def binary_search(li, val):
left = 0
right = len(li) - 1
while left <= right:
mid = (left + right) //... |
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGH... |
import cv2
import numpy as np
img = cv2.imread('book.PNG')
#Theresholding using THRESH_BINARY on the RGB image
_, RGB_binary_threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
#Gray Scaling the RGB Image
grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Theresholding using THRESH_BINARY on the Gray Scaled ... |
import numpy as np
import sys
"""This script implements a two-class logistic regression model.
"""
class logistic_regression(object):
def __init__(self, learning_rate, max_iter):
self.learning_rate = learning_rate
self.max_iter = max_iter
def fit_GD(self, X, y):
"""Train perceptron m... |
from sklearn.model_selection import train_test_split
import data
import greedySubset as gs
import project as pr
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
def run(F):
# Load encoded data
X, y = data.load()
# Split data into Test-Train Sets
X_train, X_... |
""" playgame.py
Contains the Connect 3 game playing application.
This file forms part of the assessment for CP2410 Assignment 2
************** ENTER YOUR NAME HERE ****************************
"""
from connect3board import Connect3Board
from gametree import GameTree
def main():
print('Welcome to Connect 3 by L... |
import json
from time import sleep
import pyperclip
with open('./dictionary.json', 'r+') as dictfile:
dictionary = json.load(dictfile)
print("What do you want to convert to Qorraxish? Note that this program does not currently support plural words.\nYou can convert a Qorraxish word to a plural by adding the s... |
import numpy as np
import nnfs
from nnfs.datasets import spiral_data
import matplotlib.pyplot as plt
nnfs.init()
X, y = spiral_data(100,3)
class Layer_Dense:
def __init__(self, n_inputs, n_neurons):
self.weights = 0.1*np.random.randn(n_inputs, n_neurons) #Random Gauss ian Distributions of numbers
... |
# Jiayao Zhou
# 2021/5/21
# This is the code applies our Unary Linear Regression
import pandas as pd
import numpy as np
import pylab
def plot_data(data, b, m,datax,datay):
x = datax
y = datay
y_predict = m*x + b
print(y_predict)
data['Date']=pd.to_datetime(data['Date'])
pylab.plo... |
print('Print Character Pertama')
def digitAwal(x, y):
dasar = x
eksponen = y
pangkat = (x ** y)
strPangkat = str(pangkat) #menguhbah output "pangkat" menjadi sring
print('Character Pertamanya Adalah :', strPangkat[0])
x = int(input('Masukkan Angka : '))
y = int(input('Masukkan Angka : '))
digitAw... |
"""
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
from random import choice
from string import a... |
import nltk
paragraph = """If you observe some people then you will notice that human life is a series of tension and problems. Also, they have a variety of concerns relating to their life. Sport is something that makes us free from these troubles, concerns, and tensions.
Moreover, they are an essential part of lif... |
diccionario={
"Nombre":"luis",
"Apellido":"Gutierrez",
"Edad":16
}
for x in diccionario:
print (diccionario[x])
|
from random import randint
#Create By: ClausRB github.com/loget007
print("Bienvenido al juego Piedra, Papel o Tijera")
opciones= ['piedra', 'papel', 'tijera']
computadora = opciones[randint(0,2)]
jugador= input("Selecciona una opcion: 'Piedra', 'Papel' ó 'Tijera'\n-----> ").lower()
if jugador == computadora:
print... |
# _*_ coding: utf-8 _*_
# Find all emails in the file "datos.txt"
# Cannoical mode
# matches = re.findall(pattern, text)
# Optimized mode
# prog = re.compile(pattern)
# matches = prog.findall(pattern)
# Find all matches (non-overlapping)
# findall(text)
# Find all one-by-one
# finditer(text)
# Best simple-way
# f... |
a = [1,2,3,6,2,5,7,9,2,3,7,9,10,25,89]
b = [1,2,6,8,3,1,7,0,00,335,247,21,681,146]
a = set (a)
b = set (b)
print(a)
print(b)
temp=[]
for numbers in a:
if numbers in b:
temp.append(numbers)
print(temp)
|
#https://www.hackerrank.com/challenges/diagonal-difference/problem
def diagonalDifference(arr):
primary_diagonal = 0
for x in range(len(arr)):
primary_diagonal += arr[x][x]
secondary_diagonal = 0
reverse_index = len(arr)-1
for x in arr:
secondary_diagonal += x[reverse_index]
... |
words = str(input('Enter word'))
first = words[0]
pyg = []
for x in range(1,len(words)):
pyg.append(words[x])
pyg.insert(len(words),first)
pyg.append('ay')
words = ''.join(pyg)
print (words)
|
# https://www.algoexpert.io/questions/Reverse%20Linked%20List
def reverseLinkedList(head):
p1 = None
p2 = head
while p2 is not None:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
return p1
|
def ActualChecker(s,n,lastHalf):
firstHalf = s[:n]
lastHalfReverse = lastHalf[::-1]
b = False
if firstHalf == lastHalfReverse:
return True
else:
return False
def palChecker(s):
#preprocessing begins
filteredText = []
for x in s:
x = x.lower()
if x not in "!@#$%^&*(){}|:<>? []\',./":
if x not in " ":... |
# https://www.hackerrank.com/challenges/nested-list/problem
n = int(input())
storage = {}
for x in range(n):
name = input()
mark = str(float(input()))
if mark in storage:
names = storage[mark]
names.append(name)
storage[mark] = names
else:
names = []
names.append... |
def is_member():
lis = []
n = int(input('Enter Number of elements in list:'))
for x in range(n):
lis.append(input('Enter Members of list:'))
print('Members of the club:')
print(lis)
if input('Enter Something to check if in club or not:\n') in lis:
return ('True')
else:
return ('False')
print(is_member()... |
# https://www.algoexpert.io/questions/Nth%20Fibonacci
def getNthFib(n,counter=0, n1=0, n2=1):
response = n1
if n<counter:
return n1
counter+=1
nth_fib = n1+n2
n1 = n2
n2 = nth_fib
if n>counter:
response = getNthFib(n,counter, n1, n2)
return response
|
"""Represent a small bilingual lexicon as a Python dictionary in the following fashion
{"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"}
and use it to translate your Christmas cards from English into Swedish. That is, write a function
translate() that takes a list of English word... |
"""
"99 Bottles of Beer" is a traditional song in the United States and Canada.
It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize,
and can take a long time to sing. The song's simple lyrics are as follows:
99 bottles of beer on the wall, 99 bottles of beer.
Take one do... |
https://www.algoexpert.io/questions/Suffix%20Trie%20Construction
# Do not edit the class below except for the
# populateSuffixTrieFrom and contains methods.
# Feel free to add new properties and methods
# to the class.
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*... |
#!/bin/python3
# https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
sock_count = 0
ar... |
listPal = input("Enter word: ")
if listPal == listPal[::-1]:
print("String is palindrome")
else:
print("String is not palindrome")
|
"""Write a version of a palindrome recognizer that also accepts phrase palindromes such as
"Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis",
"Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori",
"Rise to ... |
# https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps&h_r=next-challenge&h_v=zen
#!/bin/python3
# copied from discussions. couldn't come up with solution that didn't timeout.
import math
import os
import... |
mealCost = float(input())
tipPercent = int(input())
taxPercent = int(input())
totalCost = mealCost + (mealCost*(tipPercent/100)) + (mealCost*(taxPercent/100))
totalCost = round(totalCost)
print("The total meal cost is {} dollars.".format(int(totalCost)))
|
# **************************************************************************** #
# #
# ::: :::::::: #
# Main.py :+: :+: :+: ... |
from builtins import object
#kindly borrowed from http://www.acooke.org/cute/ASCIIDispl0.html
class Tree(object):
def __init__(self, name, *children):
self.name = name
self.children = children
def __str__(self):
return '\n'.join(self.tree_lines())
def __unicode__(self):
ret... |
print('Enter any two numbers to divide')
print('Enter q to quit')
while True:
n = input('first number:')
if n == 'q':
break
m = input('second number:')
if m == 'q':
break
try:
answer = int(n)/int(m)
except ZeroDivisionError:
print('You cant divide this')
else:
print(answer)
|
import json
username = input('Enter your name ?')
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print('We\'ll remember you ' + username.title() )
|
import json
def greet_user():
'''greet the user by name'''
filename = 'username.json'
try:
with open(filename)as f_obj:
user = json.load(f_obj)
except FileNotFoundError:
username = input('Enter your name?')
with open(filename,'w')as f_obj:
json.dump(username,f_obj)
print('We\'ll remember you ' ... |
import turtle
import random
turtle.Screen()
turtle.hideturtle()
turtle.speed(1000)
turtle.penup()
class Sierpinski:
def __init__(self):
self.d1x = random.randint(-300, 300)
self.d1y = random.randint(-300, 300)
self.d2x = random.randint(-300, 300)
self.d2y = random.randint(-300, 3... |
class student:
def __init__(self,name,age,rollno,std):
self.name=name
self.age=age
self.rollno=rollno
self.std=std
s1=student('yaqoob',16,157,10)
'''print("name=",s1.name)
print("Age=",s1.age)
print("rollno=",s1.rollno)
print("Standard=",s1.std)'''
print(s1.__dict__)
|
#concatinating two string
s1=input('Enter String 1:')
s2=input('Enter String 2:')
print('Conactinating two string using + operator')
s3=s1+' '+s2
print('Concatinated String:',s3)
i,j=0,0
s4=''
while i<len(s1):
s4=s4+s1[i]
i=i+1
s4=s4+' '
while j<len(s2):
s4=s4+s2[j]
j=j+1
print('Concatinated String:',s4... |
class Engine:
a=90
def __init__(self):
self.b=30
def m1(self):
print('We are checking engine functionality')
class Car:
def __init__(self):
self.engine=Engine()
def m2(self):
print('**The Car**')
print("The Engine functionality")
print(self.engine.a)
... |
def print_formatted(number):
w = int(len(str("{0:b}".format(number))))+1
for i in range(1,number+1):
d = str("{0:d}".format(i))
o = str("{0:o}".format(i))
h = str("{0:X}".format(i))
b = str("{0:b}".format(i))
print("{:>}{:>{w}}{:>{w}}{:>{w}}".format(d,o,h,b,w=w))
print_fo... |
x = 23
x += 1
print(x) # 24
x -= 4
print(x) # 20
x *= 5
print(x) # 100
x //= 4
print(x) # 25
x /= 5
print(x) # 5.0 - note conversion from int to float
x **= 2
print(x) # 25.0 - x still represents a float
x %= 5
print(x) # 0.0 - 25 is exactly divisible by 5
greeting = ... |
from contents import recipes
# Write a function that takes a dictionary as an argument, return a deep
# copy of the dictionary.
def my_deepcopy(d: dict) -> dict:
"""Copy a dictionary, creating copies of the `list` or `dict` values.
The function will crash with an AttributeError if the values aren't... |
print("Today is a good day to learn Python")
print('Python is fun')
print("Python's strings are easy to use")
print('We can even include "quotes" in strings')
print("hello" + " world")
greeting = "Hello"
name = "Joe"
print(greeting + name)
# if we want a space, we can add that too
print(greeting + ' ' + name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.