text stringlengths 37 1.41M |
|---|
x=int(input())
while True:
print(int(x), end=" ")
if x==1:
break
else:
if x%2==0:
x=x/2
else:
x=x*3 +1
# HI
#bye
|
#!/usr/bin/python3
import datetime
name=input("enter your name")
age=int(input("enter age"))
x=datetime.datetime.now()
print(name + "will be of 95 year old in:" + str((95-age)+x.year))
|
import numpy as np
"""
https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.ndarray.html
ndarray:たいてい一定の大きさを持つ、同じサイズや型で構成された複数要素の多次元の容れ物である。
"""
# numpyでベクトル変算が可能
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# print(arr1 + arr2)
"""
[5 7 9]
"""
# 二次元のarrayは[[],[]]とする
arr3 = np.array([[1, 2],[3, 4],[5, ... |
#!/usr/bin/env python
"""
Reads a maf file from stdin and applies the mapping file specified by
`mapping_file` to produce a sequence of integers. Then for each possible word
of length `motif_len` in this integer alphabet print the number of times
that word occurs in the block.
usage: %prog motif_len mapping_file < m... |
from urllib2 import urlopen
from urllib2 import quote
npr_id = raw_input("Enter comma-seperated NPR IDs or leave blank.")
search_string = raw_input("Enter your search string or leave blank.")
feed_title = raw_input("What's your feed title?")
key = "API_KEY"
url = 'http://api.npr.org/query?apiKey='
url += key
url += "&n... |
## Kaprekar numbers: numbers whose square if divided into left part and right part and then if their sum equals to x then they are kaprekan numbers
## Ex:45 as 45**=2025 left part=20 and right part=25 sum of both, 20+25=45
def kaprekarNumber(x):
y=str(x**2)
z=str(x)
# Right half of the square of x should be... |
## Agorithm from https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
## Next Lexicographical permutations
#1) Select the non-increasing suffix
#2) Pivot the element prefix to the suffix
#3) Find the smallest element in the suffix
#4) replace pivot with the element
#5) reverse the whole suffix part
#6)... |
## Calendar Month Program
terminate=False
days_in_month=(31,28,31,30,31,30,31,31,30,31,30,31)
month_names=('January','Feburary','March','April','May','June','July','August','September','October','November','December')
day_name=("Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday")
print format("Prog... |
from Queue import Queue
def hotPotato(namelist, num):
sim = Queue()
for name in namelist:
sim.enqueue(name)
while sim.size()>1:
for i in range(num):
sim.enqueue(sim.dequeue())
sim.dequeue()
return sim
namelist=['Rishabh','Ayush','Ashish','Chaman','Viraj','Kunal','Ka... |
## Finding the maximum length of increasing subsequence in a sequence and the index from which it should starts the subsequence
## I have used dynamic programming to compute it.
## let's assume that you are trying to find the maximu increasing subsequence from ith element.
## in any case the choice will start from 1 an... |
# Finding median in linear time complexity O(n) for n>140 and O(1) for n=<140
import math
# Rank of x is the number of elements less than or equal to x,, so it will be in O(n)
def Rank(alist,x):
rank=0
for item in alist:
if item<=x:
rank+=1
return rank
# Finding the value that we shoul... |
# Find the length of the longest common subsequence in O(m*n)
# We will use DP to solve it
# We wil create a matrix all of all the characters of first string in rows and second string in the columns
# we will initialize the whole first column with 0 and the whole first row with 0
def LCS(string1,string2):
m=len(s... |
class Map(object):
"""Represents a map in the world.
Attributes: id, desc, size, width, height, tiles"""
def __init__(self, map_id, desc, size=(0,0), tiles= []):
self.id= map_id
self.desc= desc
self.size= size
self.width= size[0]
self.height= size[1]
sel... |
"""
Blank Separated Values
"""
import re
p_row = """(?x) "[^"]*" | '[^']*' | \S+ """
re_row = re.compile(p_row)
def rowiter(text):
for line in text.splitlines():
line = line.strip()
if not line: continue
yield re_row.findall(line)
def findall(text):
return re_row.findall(text)
def format(row,sep=' '):
def... |
x = input('Pick a number: ')
y = input('Pick a number: ')
x = int(x)
y= int(y)
product = x + y
print(product) |
import datetime
import pyearth.toolbox.date.julian as julian
def day_of_year(iYear_in, iMonth_in, iDay_in):
"""
Calculate the day in a year
Args:
iYear_in (int): The year
iMonth_in (int): The month
iDay_in (int): The day
Returns:
int: The day in a year
"""
if i... |
def convert_360_to_180(dLongitude_in):
"""
This function is modified from
http://www.idlcoyote.com/map_tips/lonconvert.html
Args:
dLongitude_in (float): The input longitude range from 0 to 360
Returns:
float: Longitude from -180 to 180
"""
a = int(dLongitude_in /18... |
#!/usr/bin/python3
"""
island perimenter
"""
def island_perimeter(grid):
"""function returns the perimeter of the island described in grid"""
max_width = 0
width = 0
heigth = 0
x = 0
if not grid:
return 0
if (len(grid[0]) + len(grid)) > 100:
return 0
for i in grid:
... |
#!/usr/bin/env python
# coding=utf-8
def merge_sort(elements):
if len(elements) == 1: return elements
mid = len(elements) // 2
left, right = merge_sort(elements[:mid]), merge_sort(elements[mid:])
sorted_result = []
while left and right:
left_head = left[0]
right_head = right[0]
... |
print("Testing on Terminal")
name = input("What's your name?\n")
print("Hello,",name)
#== lab5 ex10==
class computer:
def __init__(self,cpu,color,portability):
self.c = cpu
self.co = color
self.p = portability
def playgame(self,nameofGame):
if self.p:
print("you are playing", name... |
"""Contrived API for test purposes"""
class Square(object):
def __init__(self, length=None):
self.set_length(length)
def set_length(self, length):
self.length = length
def area(self):
return self.length * self.length
class Rectangle(object):
def __init__(self, width=N... |
"""
graphpaper.py
this program creates a graph. Input items are rows, columns and the spaces between the rows and columns
"""
import sys
def getInt(prompt):
"""
Let the user input an integer
"""
assert isinstance(prompt, str)
while True:
try:
s = input(prompt)
exc... |
import sqlite3
class songinplaylist:
def __init__(self,song,playlist):
self.song = song
self.playlist = playlist
def addToDatabase(self):
conn = sqlite3.connect('MusiclyApp.db')
conn.execute("INSERT INTO songinplaylist (song,playlist,song_playlist) VALUES ( '"+se... |
"""
7. Напишите программу, доказывающую или проверяющую, что для множества
натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2,
где n - любое натуральное число.
ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ
"""
n = 99
sum_1 = 0
for m in range(0, n + 1):
sum_1 = sum_1 + m
sum_2 = n * (n + 1) / 2
print(f'Сум... |
"""
7. По длинам трех отрезков, введенных пользователем,
определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует,
то определить, является ли он разносторонним, равнобедренным или равносторонним.
"""
try:
LE_1 = int(input("Введите длину первого отрезка: ")... |
"""
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
Подсказка:
Для извлечения цифр числа используйте арифм. операции
Пример:
Введите натуральное число: 44
В числе 44 всего 2 цифр, из которых 2 чётных и 0 ... |
"""Inneholder klassen arbritrator """
class Arbitrator:
"""Hjelpe klasse til bbcon som vekter behaviors"""
def __init__(self, BBcon):
"""Konstruktør"""
self.bbcon = BBcon
def choose_action(self):
"""Velger hvilken action som er viktigst"""
actions = self.bbcon... |
class LexicalTree:
"""
A LexicalTree stores two LexicalEntrys and a single CombinatoryRule
"""
def __init__(self, rule, a, b):
self.rule = rule
self.a = a
self.b = b
def evaluate(self):
a = self.a.evaluate() if isinstance(self.a, LexicalTree) else self.a
b =... |
#!/usr/bin/python3
"""Creating a new class"""
import cmd
import shlex
from models.base_model import BaseModel
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
import models
class ... |
import thread
import time
"""
try:
thread.start_new_thread(time_fun,("thread1",2,))
thread.start_new_thread(time_fun,("thread2",3,))
thread.start_new_thread(time_fun,("thread3",5,))
except:
print "sorry i could not create thread"
thread.start_new_thread(time_fun,("thread1",2,))
thread.start_new_thread(time_fun,(... |
def spliting(f):
words=f.split(' ')
print words
return words
def first_word(f):
print "with out sorting"
print f.pop(0)
def last_word(f):
print "with out sorting"
print f.pop(-1)
def first_word_s(f):
print "with sorting"
print f.pop(0)
def last_word_s(f):
print "with sorting"
pr... |
while True:
stringName = raw_input("Convert string to hex & ascii(type stop to quit): ")
if stringName == 'stop':
break
else:
convertedVal = stringName.encode("hex")
new_list = []
convertedVal.strip() #converts string into char
for i in convertedVal:
new_list = ord(i)
... |
import threading,time
class MyThread(threading.Thread):
def __init__(self,no,name,delay):
threading.Thread.__init__(self)
self.threadid=no
self.name=name
self.delay=delay
def run(self):
print self.name,"Thread is started"
... |
#!/usr/bin/env python3
import csv
import sys
import argparse
import os
lang_codes = []
with open('language_codes.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
lang_codes.append([row[0].split(',')[0], row[0].split(',')[1]])
def show_help()... |
def hello(name):
print('Howdy ' + name + '!')
print('Howdy ' + name + '!!!')
print('Hello there ' + name + '.')
hello('Alice')
hello('Bob')
hello('Eve')
print('Hello has ' + str(len('hello')) + ' letters in it.') |
def merge_sort(arr,start,end):
if(start<end):
mid= (start+end)//2
merge_sort(arr,start,mid)
merge_sort(arr,mid+1,end)
merge(arr,start,end)
def merge(arr,left,right):
mid = (left+right)//2
l_count=left
temp=[]
i=left
j=mid+1
while(i<=mid and j<... |
"""
This Module contains the CPU class and its functions.
Classes: CPU
Functions: move(self)
"""
import pygame
import os
import random
class CPU:
"""
A class to represent the CPU and handle its movements.
Attributes
----------
player.image : pygame.image
initializes the image
player... |
# Задание №1 - сделано
def task_1():
x = int(input('Аmount of kilometers for the first day: '))
y = int(input('Аmount of kilometers: '))
day = 1
while x < y:
x *= 1.1
day += 1
return day
print(task_1())
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if not root:
return []
... |
#task1------------------------------------------------------------
"""
Program prints squares from 1 to n
"""
n=int(input('Enter number'))
i=1
print('Squares from 1 to n:')
while i*i<=n:
print(i*i)
i+=1
#----------------------------------------------------------------
#task2----------------------------... |
# -*- coding:utf-8 -*-
# 3.2 レコード検索
# 変更: 3_1.dbの artist_basic_infoにおいて検索する
import sqlite3
dbname='../data/3_1.db'
# データベースに接続
conn= sqlite3.connect(dbname)
# SQLを実行するためのcursorオブジェクト
c=conn.cursor()
# SELECT WHERE で検索
select_sql = 'select * from artist_basic_info where sort_name=?'
search_name = ('Oasis', )
for ro... |
##Tabuada Atualizada Guanabara Curso em Vídeo
num = int(input('Digite Um Número para a tabuada : '))
for c in range(1,10):
print('{} x {:2} = {}'.format(num,c,num*c)) |
##Gerador de PA###
print('='*157)
print('Vamos calcular a Progressão aritimética de um número e mostras os 10 primeiros resultagos')
primeiro = int(input('Digite o Primeiro núimero : '))
razão = int(input('Digite a razão da PA '))
termo = primeiro
contador = 1
total = 0
mais = 0
while mais != 0:
total = ... |
velocidade = float(input('Qual é a velocidade do Carro? : '))
if velocidade > 80:
print('Você foi multado!!!! , Exedeu o limite de velocidade que é de 80Km/h')
multa = (velocidade - 80)*7
print('Voce dve pagar uma multa no valor de {:.2f}'.format(multa))
print('Tenha um Bom dia!!!!')
|
from random import randint
pc = randint(0, 10)
print('='*200)
print('='*200)
print('Olá sou seu computador vamos jogar?? ')
print('Vou pensar em um número de 0 a 10 ')
print('Tente acertar qual número eu escolhi ')
acertou = False
palpites = 0
while not acertou:
jogador = int(input('Qual é o seu palpite ?... |
a = (2,5,4)
b = (5,8,1,2)
c = a +b
print(a)
print(b)
print(a+b)# vai misturar as tuplas
print(len(c))#tamanho da tupla C
print(c.count(5)) # Quantas vezes o Num 5 aparece
print(c)
print(c.index(8)) # Qual posição do número 8
pessoa = ('Luciano' , 39, 'M' ,99.88)
#del (pessoa) Deleta a tupka
print(pessoa) |
###Aula 52 Curso em vídeo Gustavo Guanabara
###### Saber se o número é primo
print('='*200)
print("Luciano Lima jr.")
print('='*200)
num = int(input(' Digite um Nímero : '))
tot = 0
for c in range(1, num + 1):
if num % c == 0:
print('Divisivel')
tot += 1
else:
print('Não divisivel')
... |
#########Exercício 76 Curso de Python###########
produtos = ('Lapis',1.75,
'Borracha',2.00,
'Caderno',15.90,
'Estojo',25,
'Trasferidor',12.85,
'Mangá',14.90,
'Mochila',69.90,
'Caneta',1.50)
print('='*40)
print(f'{"Listagem de ... |
print('-'*50)
print('Programa de cadastro de pessoas ')
print(''*50)
tot18 = 0
toth =0
totm20 = 0
while True:
nome = str(input('Digite um nome : '))
idade = int(input('Informe a idade da pessoa : '))
sexo = 'a'
while sexo not in "FM":
sexo = str(input(' Sexo [M/F] ')).strip().upper(... |
"""
input example (beginning of William Blake poem, "The Fly")
enter a saying or poem: Little fly, Thy summer’s play My thoughtless hand Has brushed away. Am not I A fly like thee? Or art not thou A man like me?
output example
or BRUSHED thy not Little thou me? SUMMER’S thee? like THOUGHTLESS play i a not hand a my ... |
#!/usr/bin/env python3
r'''
学生管理系统入口模块
'''
from menu import *
from student_info import *
students = []
filename = '/home/tarena/kanglu/exercise/student/si.txt'
while True:
try:
show_menu()
myinput = input('请输入你的选择:')
if myinput == '1':
while True:
stu = inpu... |
# https://app.codesignal.com/interview-practice/task/rak3HBvHDAjHRkTCW
"""
Given an array of words and a length l, format the text such that each line has exactly l characters and is fully justified on both the left and the right. Words should be packed in a greedy approach; that is, pack as many words as possible in ... |
# Your code here
cache = {}
def expensive_seq(x, y, z):
# Your code here
if x <= 0:
return y + z
if (x, y, z) not in cache:
##So for here it just wants you to outright return y + z if x <= 0 so this would go above the function expression
#You can check for this explicitly as you do f... |
# def multi(x):
# print(x**2)
# return x**0.5
# value=multi(25)
# print(value)
def multi(a,b):
c=a*b
print(c)
return c
# print(multi(6,10))
value=multi(6,10)+multi(6,11)
print(value)
# multi(6,9)
# multi(6,10)
# multi(6,11)
# def accumulation(z):
# sum=0
# for x in range(1,z+1):
# ... |
from selenium import webdriver
import time
import math
from selenium.webdriver.support.ui import Select
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
link = "http://suninjuly.github.io/selects1.html"
try:
browser = webdriver.Chrome()
browser.get(link)
num1 = browser.find_element_by_css... |
import tensorflow as tf
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
def weight_variable(shape):
print("weight", shape)
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
print("bias", shape)
... |
################################################################################
#def inc(x):
# return x + 1
#f = inc
#print f(10)
#function within a function
#def h(x):
# return lambda y: x + y
#b = h(1)(3)
#print h(1)
#print h(2)
#print h(1)(3)
#print h(2)(5)
#Q3: h(1)(3) and h(2)(5) create closures.
#def... |
# -*- coding: utf-8 -*-
"""
Spyderエディタ
これは一時的なスクリプトファイルです
"""
# =============================================================================
# greeting = "Hi there "
# name = "Iqbal"
# greet = gretting + name
# print(greet)
# silly = greeting + (" "+ name)*3
# print(silly)
#
# ===============... |
# this code work for middle permutation exercise kyu4 on codewars.com
import itertools
def middle_permutation(string):
str_len = len(string)
str_sorted = sorted(string)
if str_len % 2 == 0:
start = str_sorted.pop(str_len // 2 - 1)
return start + ''.join(sorted(str_sorted, reverse=True))
... |
from turtle import Turtle
# CONSTANTS
ALIGNMENT = "center"
FONT = ("Arial", 24, "normal")
TOP = (0,270)
CENTER = (0,0)
COLOR = "red"
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.high_score = 0
self.color(COLOR)
self.p... |
import random
total_students = 30
total_teams = 6
students = range(30)
list_students = list(students)
random.shuffle(list_students)
print(list_students)
project_team = []
for i in range(6):
num_of_members = int(total_students/total_teams)
index = i * num_of_members
project_team.append(list_students[in... |
# Import all needed modules
from tkinter import *
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
import time
import os
import shutil
import Main
from Main import *
import datetime
from datetime import timedelta
# This function centers the window in the screen
def center_win... |
# This sets up a car class with a couple properties and a couple methods that take
# in info and print out results
class Car:
def __init__(self, color, top_speed):
self.color = color
self.top_speed = top_speed
def information(self):
msg = ("You\'re about to drive a {} car with a... |
def inorder(root):
result, stack, node = [], [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.val)
node = node.right
return result
|
import json
from collections import OrderedDict
class EuropeanianCities(object):
cities = []
def __init__(self, cities):
self.cities = cities;
def __str__(self):
return "Europenian cities: " + str(self.cities)
def oddLenghts(self):
oddLengthCities = [x for x in self.cities i... |
n=int(input("how many num"))
nums=[]
for i in range(n):
a=int(input("enter num: "))
nums.append(a)
differentnums={}
for x in nums:
if x not in differentnums:
differentnums[x]=1
else:
differentnums[x]+1
print("num with their freq")
maxfreq=0
mode=0
for d in differentnums... |
import random
def flip():
coin_toss= 5000
heads= 0
tails =0
count = 1
print "Initializing program..."
for elemnt in range (0, coin_toss):
random_num= random.random()
random_num= random.randint(0,101)
if (random_num >= 50):
heads+=1
print "Attempt... |
myarr= ['magical unicorns',19,'hello',98.98,'world']
sum=0
intcount=0
strcount=0
newstr= "String:"
for i in range(0, len(myarr)):
if isinstance(myarr[i], (int, float)):
sum = sum + myarr[i]
intcount= intcount + 1
elif isinstance(myarr[i], str):
newstr= newstr + " " + myarr[i]
... |
class car(object):
def __init__(self, price, speed, fuel, milage):
print "new Car"
self.price = price
self.speed = speed
self.fuel = fuel
self.milage = milage
if self.price > 10000:
self.tax= .15
else:
self.tax= .12
focus= car(5000, ... |
# Heap Sort
def heapify(a, floyd=False, bottom_up=False):
if not floyd:
for i in range(1, len(a)):
siftup(a, i)
else:
for i in range(len(a)//2 - 1, -1, -1):
siftdown(a, i, len(a), bottom_up)
return a
def siftup(a, i):
while i > 0 and a[i] > a[(i-1)//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... |
import requests
from bs4 import BeautifulSoup
def get_html_content(url):
"""Get the html from the web page
:parameter url of the webpage
:return the html content"""
html=requests.get(url)
return html.content
def parse_html_using_tag(html_content,tag):
"""To convert html format ... |
import matplotlib.pyplot as plt
from scipy.stats import uniform
import numpy as np
# Create cdf of a uniform random variable
def uniform_cdf(a, b, x):
if (x > a and x < b):
return (x-a)/(b-a)
elif (x >= b):
return 1
else:
return 0
# Create pdf of a uniform random varia... |
# Defining Function
def f(x):
return 2*x**3 - 2*x - 5
def secant(x0,x1,e,N):
print('\n\n*** SECANT METHOD IMPLEMENTATION ***')
step = 1
condition = True
while condition:
if f(x0) == f(x1):
print('Divide by zero error!')
break
x2 = x0... |
def say(arg = None):
if arg is None:
return
for name in arg:
print("Hello " + name + "!")
array = ["Takeshi", "Masashi", "Nobita"]
say(array)
|
def main():
houseCost = int(input("Enter the cost of house: "))
landSize = int(input("Enter the size of land: "))
landCost = int(input("Enter the cost of land: "))
totalLandcost = landSize * landCost
totalCost = totalLandcost + houseCost
print("The total cost is", +totalCost)
print("L... |
def getValidMoney():
money = int(input("Please enter an AUD$ amount to be converted. Whole numbers only please:\n "))
while money <= 0:
print("I'm sorry values must be greater than 0. Please try again.\n")
money = int(input("Please enter an AUD$ amount to be converted. Whole numbers only pl... |
def swapAsc(list1,length1):
for i in range(0,int(length1)):
for j in range(0,int(length1)-1):
if list1[j] > list1[j+1]:
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
print("The Ascending order is " + str(list1))
def swapDsc(list1,length1):... |
""" Provides a way to specify cronjobs which should be called at an exact time.
Example::
# A job that runs at 08:00 exactly
@App.cronjob(hour=8, minute=0, timezone='Europe/Zurich')
def cleanup_stuff(request):
pass
# A job that runs every 15 minutes
@App.cronjob(hour='*', minute='*/15', t... |
# Python script which uses OpenCV to show different types of simple thresholding in OpenCV.
# Tutorial link: https://pythonprogramming.net/thresholding-image-analysis-python-opencv-tutorial/
import cv2
import os
import numpy as np
# Importing envs
from dotenv import load_dotenv
env_path = '../.env'
# Loading envs
l... |
###24/20/2018
# Author: Rene Cortez
# How to edit list
# Creating a list of months
birthday_months = ['spril', 'may', 'november']
print(birthday_months)
# Changing an element of list
birthday_months[0] = 'april'
print(birthday_months)
# using append method
birthday_months.append('june')
print(birthday_months)
#c... |
# Working with the contents of a sale
filename = 'movies_line_by_line.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.strip())
print("\n----------------------------------\n")
popped_movie = lines.pop()
for line in lines:
print(line.strip())
print... |
# Editing & deleting values in a dictionary
# terms = {'interger' : 'Is a number that contains a decimal place.'}
#
# terms ['interger'] = 'A whole value'
#
# print(terms.get('interger'))
terms = {'interger' : 'Is a number that contains a decimal place.', 'string' : 'A sequence of characters.'}
del terms['interger']... |
# Making arguments optional
# Since the middle name is going to be optional you want to move
# that parameter to the end and assigning an empty string
def formatted_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
f... |
# Passing information to a function
def hello_world(username):
"""showing a username"""
print(" Hello " + username.title() + ".")
# We pass the argument Rene into the function
hello_world('rene')
# Positional argument
# Creating our function
def book_description(book_type, author_name):
print("\nThis Boo... |
class Demo:
def __init__(self,no1,no2):
self.no1 = no1
self.no2 = no2
def Add(self):
return self.no1+self.no2
def main():
print("Enter first number")
x = int(input())
print("Enter second number")
y = int(input())
obj = Demo(x,y)
ret =... |
class Demo:
def Add(self,no1 = None,no2 = None,no3 = None):
if no1 != None and no2!= None and no3 != None:
return no1+no2+no3
elif no1!= None and no2 != None:
return no1 + no2
elif no1!= None:
return no1
else:
return 0
... |
purchase_amt=int(input("Enter the purchase amount(in Rs.):"))
if purchase_amt<=400:
discount=0
elif purchase_amt<=5000 and purchase_amt>400:
discount=400
elif purchase_amt>5000 and purchase_amt<=10000:
discount=800
elif purchase_amt>10000 and purchase_amt<=20000:
discount=1000
else:
discou... |
# Author: John Gauthier
# Description: There is a circle of N restaurants. You can only travel from restaurant i to restaurant i+1.
# It takes some amount of energy to travel to a restaurant and you recieve some amount of energy from eating there.
# This program finds what restaurant to begin at so you can travel to al... |
'''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# Your code here
max_arr = []
# initialize window at first position
window = nums[:k]
# initialize running max with first maximum and a... |
def euclidean_division(x, y):
quotient = x // y
remainder = x % y
print(f"{quotient} remainder {remainder}")
euclidean_division(-10, 3)
euclidean_division(10, -3)
'''
Floor division always rounds away from zero for negative numbers, so -3.5 will round to -4, but towards zero for positive numbers, so 3.5 will round... |
"""
String interpolation
Question : why 0 is {file_number:03} : ans : 0 is filling the place only
suppose if you don't pass 0 the it will replace 0 with space
"""
# normal process
# number_of_files = 3
# for file_number in range(1, number_of_files + 1):
# print(f"image{file_number:03}.png")
# nested process
numbe... |
def isPrime(n):
if n == 2 or n == 3:
return True
if n % 2==0 or n < 2:
return False
for i in range(3, int(n**0.5)+1 , 2):
if n%i==0:
return False
return True
def sumDigits(n):
a = sum(int(j) for j in list(str(n)))
return a
size = int(input())
count = 0
... |
import statistics
num = int(input())
marks = [int(i) for i in input().split()]
s = statistics.mean(marks)
if sum(1 for j in marks if j > s) > num/2:
print("Winnie should take the risk")
else:
print("That's too risky") |
'''
Your program will be given an integer X. Find the smallest number larger than X consisting of the same digits as X.
Input Specification
The first line of input contains the integer X (1≤X≤999999).
The first digit in X will not be a zero.
'''
from itertools import permutations
from utils import timed
@timed
def ... |
names = ['Вася', 'Маша', 'Саша', 'Петя', 'Валера', 'Даша']
name = None
x = 0
while name != 'Валера':
name = names[x]
x += 1
if name == 'Валера':
print(f'{name} нашелся') |
dictionarie = {
"city": 'Москва',
"temperature": 20
}
print(dictionarie['city'])
dictionarie["temperature"] = dictionarie['temperature'] - 5
print(dictionarie['temperature'])
dictionarie['country'] = 'Россия'
print(dictionarie['country'])
dictionarie['date'] = '27.05.2019'
print(len(dictionarie)) |
#file handling in python
#print("writing and reading file in Python. this will write values to file and read them \n")
def inputNumbers(howMany):
list = []
for i in range(1, howMany + 1):
prompt = '{}/{} Please enter a number: '.format(i, howMany)
list.append(input(prompt))
... |
"""Programa x_x.py
Descrição:
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
p = int(0)
v = int(0)
# Entrada de dados
L = [15,7,27,39]
p = int(input("Digite o valor (p) a procurar:"))
v = int(input("Digite o outro valor (v) a procurar:"))
# Processamento
x = 0
achouP = False
achou... |
"""Programa 5_8.py
Descrição:Programa que lê 2 números e imprime a multiplicação do 1º pelo 2º número usando + ou - para achar o resultado
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
num1 = int(0)
num2 = int(0)
# Entrada de dados
num1 = int(input("Digite o primeiro número: "))
num2 = int(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.