text stringlengths 37 1.41M |
|---|
p = collections.Counter(x)
print (p)
count_of_sum = sum(p.values())
for k,v in p.items():
print("The frequency of number" + str(k) + "is" + str(float(v)/count_of_sum))
plt.hist(testlist, histtype="bar")
plt.show()
plt.boxplot(testlist)
plt.show()
plt.figure()
x = np.random.normal(size=1000)
graph1 = stats.probp... |
# 最小公倍数
def lcm(x, y):
# 获取较大的数
if x > y:
bigger = x
else:
bigger = y
while (True):
if (bigger % x == 0) and (bigger % y == 0):
result = bigger
break
else:
bigger += 1
return result
if __name__ == '__main__':
print(lcm(6, 8... |
# 替换列表中所有的 3 为 3a
if __name__ == '__main__':
nums = ['harden', 'lampard', 3, 34, 45, 56, 76, 3, 3, 876, 999]
for i in range(nums.count(3)):
ele_index = nums.index(3)
nums[ele_index] = '3a'
print(nums)
|
class Hand():
def __init__(self):
self._cards = []
self.__index = 0
@property
def cards(self):
return self._cards
@cards.setter
def cards(self, value):
self._cards = value
@property
def count(self):
return len(self.cards)
def add_card(self, c... |
from .UnitConversion import UnitConversion
# Above from "." = current directory
try:
user_feet = float(input("Please enter the number of feet (0 or greater)"))
user_inches = float(input("Please enter the number of inches (0 or greater)"))
# This could ask for both and split on a space but with a console be... |
#算法思想
#将待插入元素与其前一个元素进行比较,若小于,
# 则将前一个元素后移一位,在将带插入元素与前前一位进行比较,
# 若小于,则将前前一位往后移,如此操作直到遇到小于待插入元素的位置,
# 插入到该位后一位(此位已经在上一步后移了)
def Insert_Sort(arr):
for i in range(1,len(arr)):
key = arr[i]
a = i#使用一个变量a来记录数组下标
while key<arr[a-1]:#这时的第一次循环key是之前排好序的数组新加入的一个未排序的数,
#先将key与他前面的元素arr[a-1]... |
from typing import *
from abc import *
from decimal import *
import functools, itertools
class Product:
def __init__(self, name: 'str', price: 'Decimal' = Decimal("0.00")) -> 'None':
self.__name = name
self.__price = price
@property
def name(self) -> 'str':
return self.__name
... |
def age_checker(age):
classifications = ["U", "PG", "12a", "15", "18"]
if age > 17:
print("These are the movies you can watch:", classifications)
elif 14 < age < 18:
print("These are the movies you can watch:", classifications[0:4])
elif 11 < age < 15:
print("These are the movie... |
student_record = {"name": "Ibrahim",
"DOB": "01/01/1996",
"Country of Birth": "Saudi Arabia",
"Employee ID": "12345",
"Comment": "He likes football"}
def record_printer():
for keys in student_record:
print(keys, ":", student_record.get(... |
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor ("grey")
abcd = turtle. Turtle()
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
turtle.color ("blac... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 20:32:26 2021
Program to demonstrate Encapsulation (Private Member)
@author: Lokesh
"""
class Person:
def __init__(self):
self.name = 'Manjula'
self.__lastname = 'Dube'
def PrintName(self):
return self.name +' ' + self.__lastname
... |
d = { 'a': 1, 'b': 2, 'c': 3 }
print d.items()
print [(v, k) for k, v in d.iteritems()] |
num = input("Please give the Integer : ")
numbr = num
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 2:
result = str(num%2) + result
num = num/2
if num <= 2:
result = str(num/2)+ str(num%2) + result
if isNeg:
result = '-' + r... |
import math
X = 2.4
print math.ceil(X)
#Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
Y= -1
print math.copysign(X,Y)
#Return x with the sign of y. On a platform that supports signed zeros, copysign(1.0, -0.0) returns -1.0.
x = -2.5999999999999
print math.fabs(x)
#Return t... |
from random import choice
from math import sqrt
# Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
a = 0
b = 1
c = []
# like a dynamic prog
for __ in range(m):
a, b = b, a + b
c.append... |
# Vigenere Cipher
import pyperclip
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main():
# myMsg = 'Alan Mathison Turing was a British mathematician, logician, cryptanalyst, and computer scientist.'
myMsg = str(input("Enter your message:\n"))
myKey = str(input("Enter the string key: "))
myMode = str(inp... |
# Testing Transposition Cipher
import sys, random, TranspositionEncryption, TranspositionDecryption
def main():
ask = int(input("How many times to run the code? "))
random.seed(42) # Set the random "seed" to a static value
for i in range(ask):
# Generate random message to test
# The message wil... |
## SJS 5/22/14. Feel free to email stephanie.spielman@gmail.com with questions!
# Script to introduce the biopython module and regular expression usage.
# import the sequence input-ouput functionality from the Biopython module
from Bio import SeqIO
# import the regular expression python module
import re
# This file... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math as m
import matplotlib.pyplot as plt
def rotate_points_2D(points, angle):
"""Rotate points using complex numbers"""
# Encode the rotation operation
z = complex(m.cos(angle), m.sin(angle))
points_rot = []
for point in points:
p_... |
class Spawner(object):
'''
Abstract base class for classes that can spawn and communicate between `MachineController` instances.
Each subclass should define a way to create and track `MachineController` instances, and to communicate
with them once they have started running.
'''
@property
def dz_time(self... |
# Copyright © 2019 Adobe, Inc.
# Author: Miguel Sousa
"""
Generates a simple text file for testing emoji characters.
"""
import argparse
import os
import sys
from generate_test_html import (
append_to_file,
parse_emoji_test_file,
CHANGES_INPUT_PATH,
TEST_DIR,
TEST_INPUT_PATH,
)
TEST_OUTPUT_FILENAM... |
import tkinter
import winsound
import time
import math
def countdown(count):
seconds = math.floor(count % 60)
minutes = math.floor((count / 60) % 60)
hours = math.floor((count / 3600))
label['text'] = "Hours: " + str(hours) + " Minutes: " + str(minutes) + " Seconds: " + str(seconds)
... |
#Pertemuan pertama sintax dasar python
#penulisan variable
# di php => $
# vasriable di js => let, var, const
# java const
# python => nama_variable
# variable
# - type data
# - int => angka
# - string => input " " biasanya berupa huruf,
# karakter angka
# - bool => False or True
# - array => di... |
cafeMenu=['wings', 'cookies', 'spring rolls', 'salmon', 'steak', 'meat tornado', 'a literal garden', 'ice Cream', 'cake', 'pie', 'coffee', 'tea', 'unicorn tears']
print(
"""
**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To quit at any time... |
import numpy as np
x = np.array(range(1, 101))
y = np.array(range(1, 101))
x_train =x[:60]
x_val = x[60:80]
x_test = x[:80] #[:80] = 시작부터 80까지 [80:] =80부터 마지막까지
y_train = y[:60]
y_val = y[60:80]
y_test = y[80:]
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
# model.add(Dens... |
#1. 데이터 2개가 들어가서 하나로 나오는 것.
import numpy as np
x1 = np.array([range(1, 101), range(311,411), range(100)])
x2 = np.array([range(711,811), range(711,811), range(511,611)])
y1 = np.array([range(101,201), range(411,511), range(100)])
#print(x1.shape) # 열우선, 행무시
x1 = np.transpose(x1) #100행 3열.
y1 = np.transpo... |
#2. 튜플
#리스트와 거의 같으나 삭제, 수정이 안된다.
a = (1, 2, 3)
b = 1, 2, 3
print(type(a))
print(type(b))
print(a + b)
print(a * 3) #리스트와는 똑같다. 하지만 객체안은 수정이 안된다. |
import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS supermarket(Itemno INTEGER, Category TEXT,
FoodName TEXT, Company TEXT, Price INTEGER)""")
sql = "DELETE FROM supermarket"
cursor.execute(sql)
# 데이터 넣기
sql = "INSERT into supermarket... |
from fractions import Fraction
x=int(input("numaratorul fractiei 1 este: "))
y=int(input("numitorul fractiei 1 este: "))
z=int(input("numaratorul fractiei 2 este: "))
w=int(input("numitorul fractiei 2 este: "))
print("suma este:",Fraction(x,y)+Fraction(z,w))
print("produsul este",Fraction(x,y)*Fraction(z,w)) |
for i in range(1,100):
print (i)
if (i % 3 == 0) and (i % 5 == 0):
print(f'{i} FizzBuzz')
elif (i % 3 == 0):
print(f'{i} Fizz')
elif (i % 5 == 0):
print(f'{i} Buzz')
|
Repaint Rectangular Grid
There is a rectangular grid of length L and breadth B. The rectangular
grid is already painted with the colors Red, Green and Blue. A painter
wants the repaint the rectangular grid with the color C based on the
following conditions.
- He can repaint a cel l with the color C only if one of ... |
Water Tanks in Staircases
There are R*C water tanks arranged as a matrix. The water tanks are
connected diagonally from top-left to bottom-right like staircases
(i.e., If a water tank overflows, then the water will flow into the tank at
its bottom-right). The maximum capacity and the amount of water in
each water ... |
Decreasing Order - Interlace
The program must accept two integers N1 and N2 as the input. The
program must find the absolute difference Dbetween N1 and N2.
Then the program must form a series S1 of integers using the previous
D integers of the largest integer(inclusive) between N1 and N2. Then
the program must... |
Find Case Sensitive Pattern
The program must accept two string values S and P containing only
alphabets as the input. The program must print all possible substrings
of S that match the pattern P. If a substring matches the pattern P, then
the case of each alphabet in the pattern P matches with the
corresponding al... |
Filling Holes with Wooden Sticks
The program must accept a character matrix of size R*C representing a
wood as the input. The character asterisk (*) represents the hole. The
character hash symbol (#) represents the wooden part. There
are N wooden sticks of different heights used to fill the holes. The
depth of a h... |
from visual import *
from visual.graph import *
#graphs the taylor series function for cos(x)
def taylor(N):
#initializes a window for display
gd = gdisplay(width=600,height=600,xmax=N,xmin=-N,
ymax=5,ymin=-5)
series = ""
s = 0
#adds the number of terms to the equation
for n ... |
from math import *
import pyfits
#pulls boxes of pixel values of out of an image or fit file
def photometry():
#allows the user to input a file to read
fileName = raw_input("Enter the file name: ")
image = pyfits.getdata(fileName)
print image
#asks the user to input details of the star or asteroi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 15:55:19 2018
@author: ConorGL
The aim of this project is to look in to Reddit comments and to use them to make our own.
This will form part 1 of a larger project which will be to generate our own Floria Man stories.
"""
import nltk
import csv
import itertools
from da... |
import unittest
class Stack:
"""Simple Stack implementation - First In Last Out"""
def __init__(self):
self.__data = []
def push(self, text):
"""Push an item to a stack
Arguments:
text {string} -- Element that will be put on stack
"""
self.__data.inse... |
class Vector:
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
def getX(self):
return self.__x
def getY(self):
return self.__y
def abs(self):
return (self.__x ** 2 + self.__y ** 2) ** 0.5
def unitVec(self):
abs = self.abs()
... |
import random
#Finding the minimum of random numbers
randNum = []
for x in range(10):
randNum.append(random.randint(0,100))
print(min(randNum))
test = "Sample string"
num = int(input("Enter a number: "))
print("You entered {} test {} ".format(num,test))
list = [random.randint(0,10) for x in range(3)]
print(list... |
class Movie:
def __init__(self, name, genre, watched):
self.name = name
self.genre = genre
self.director = "Default Director"
self.watched = watched
def __repr__(self):
return "<Movie: {}>".format(self.name)
def json(self):
return {
'name':self.n... |
'''
8.4 Open the file romeo.txt and read it line by line.
For each line, split the line into a list of words using the split() method.
The program should build a list of words.
For each word on each line check to see if the word is already in the list
and if not append it to the list. When the program completes, s... |
from typing import TypeVar, Generic, List
T = TypeVar("T")
class Pilha(Generic[T]):
def __init__(self) -> None:
self._container: List[T] = []
def coloca(self, item: T) -> None:
self._container.append(item)
def retira(self) -> T:
return self._container.pop()
#__repr__ é basic... |
# import ...
# -----------------------------------------------------------------------------
# Exercise (Easy): Quick and Efficient Fibonacci
# This problem is fairly easy by itself, so an
# additional requirement is to run the function
# in O(n) time and O(1) space complexity.
# Ex) Input: 3 Output: 2
... |
import pandas as pd
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_linear_regression
import numpy as np
import seaborn as sns
#Step 1: Readding dataset
df = pd.read_csv('dataset.csv')
#sns.set_theme(color_codes=True)
#Step 2: Parameter Initilization
theta = [1,2]
x = df['x']
y = df['y']
#print(x... |
def word_count(s):
# Your code here
"""
This function takes a single string as an argument.
Ex. Hello, my cat. And my cat doesn't say "hello" back.
It returns a dictionary of words and their counts:
Ex. {'hello': 2, 'my': 2, 'cat': 2, 'and': 1, "doesn't": 1, 'say': 1, 'back': 1}
Case sho... |
d = {
"foo": 12,
"bar": 17,
"qux": 2
}
items = list(d.items())
# for t in d.items():
# print(t)
print(items)
items.sort() #> sorts tuples in order by key (alphabetically)
print(items)
# Sort by value
# def fun1(e):
# return e[1]
# items.sort(key=fun1)
items.sort(key=lambda e: e[1])
print(ite... |
from copy import deepcopy
import math
AXES = [0,1,2]
CUBE_MAP = [2,1,1,2,1,2,1,1,2,2,1,1,1,2,2,2,2]
def walk(steps, axis, sign, path, map_index):
# Copy args
steps = deepcopy(steps)
axis = deepcopy(axis)
sign = deepcopy(sign)
path = deepcopy(path)
map_index = deepcopy(map_index)
... |
# Should perform merge sort on the given list
ul = [4,2,9,20,292,4,37,8,273,49]
def merge(l1, l2):
i, j = 0, 0
new_list = []
while i<len(l1) and j<len(l2):
#print l1[i], l2[j]
if l1[i] <= l2[j]:
new_list.append(l1[i])
i += 1
else:
new_list.append... |
n=input()
m=input()
if sorted(n)==sorted(m):
print('anagram')
else:
print('Not anagram')
|
x = (1, 'two', 3.0, 4, False)
y = (1, 'two', 3.0, 4, False)
print('x is {}'.format(x))
# x and y are both tuple
# each element has it's own type
print(type(x))
print(type(x[4]))
print(type(y))
# unique id's'
print(id(x))
print(id(y))
# use is:instance(x, type)
if isinstance(x, tuple()):
print('x is tuple'.format(x... |
# 1. (a)
### Write down the result of running the following Python code. Justify your answers. (5 marks)
### i) print(len('9yth0\\\n'))
### ii) print('3\'4')
### iii) len("4-1") = 3
### iv) print(3*"ab"*2)
### v) print("He said, 'No!'")
# print(len('9yth0\\\n')) # 7
# print('3\'4') # 3'4
# len("4-1") = 3 # error
# pri... |
# oscar stanley
#6-10-2014
# range 21 to 29
number = int(input("please enter a number: "))
if number >= 21 and number <= 29:
print(" you number is in the range")
else:
print("your number must be in the rage of 21-29")
|
"""
¿A qué velocidad se ejecuta?
¿Necesitamos que sea tan rápido?
https://nerdparadise.com/programming/pygame/part1
"""
clock = pygame.time.Clock()
while not done:
pygame.display.flip()
# will block execution until 1/60 seconds have passed
# since the previous time clock.tick was called.
clock.tick(... |
array = []
array_size = raw_input("Please enter the size of the array")
for number in range(0,int(float(array_size))):
user_input = raw_input("Please enter the %number of the array")
array.append(user_input)
def Counting(array,search_term):
count = 0
for x in array:
if x == search_term:
count = coun... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def isPrime(n):
if n==1:
return 0
for i in range(2,int(pow(n,0.5))+1):
if n%i==0 and i!=n:
return 0
return 1
if __name__=="__main__":
n=int(input())
while n>0:
if isPrime(int(input())... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def count_days(a, b):
# actual-return,expected-returned
if a[2] > b[2]:
return 10000
elif a[2] == b[2]:
if a[1] == b[1] and a[0] > b[0]:
return 15 * (a[0] - b[0])
elif a[1] > b[1]:
... |
class Vivienda(object):
"""
Clase Vivienda
"""
code = None
link = None
address = None
barrio = None
distrito = None
ciudad = None
lat = None
lon = None
price = None
area = None
has_elevator = None
floor = None
exterior = None
rooms = None
anuncio... |
#!/usr/bin/env python3
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
clas... |
__author__ = 'Matthew'
n = input('what number would you like to choose? ')
a = int(str(n))
def prime(a):
a = abs(int(a))
if a < 2: #2 is the lowest prime number
return False
if a == 2: #also the only even one
return True
if not a & 1: #this is to say that any odd numbers are prime
... |
#!/usr/bin/env python2
import os
import sys
import platform
import datetime
def creation_date(path_to_file):
"""
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
i... |
from ascii_table import Table
from aqa_assembly_simulator.error.VirtualMachineError import VirtualMachineError
class Memory:
def __init__(self, capacity):
"""
Memory constructor.
Constructs _memory using a list comprehension.
:param capacity: number of addressable memory units (... |
#Binary Decoder
#Katie Hay
#Version 2.7.15
from sys import stdin
def decode(binary, n):
text = ""
i = 0
while (i < len(binary)):
byte = binary[i:i+n]
byte = int(byte, 2)
#if backspace, remove last character of string
if(byte == 8):
text = text[:-1]
... |
tab = [2, 5, 4, 1, 8, 7, 4, 0, 9]
def reverse(tab):
tab2=[]
i=len(tab)-1
j=0
while i>=0:
tab2.append(tab[i])
j+=1
i-=1
print("",tab,"\n",tab2)
reverse(tab)
|
n=int(input('Podaj liczbę w systemie dziesiątkowym: '))
x=n
k=[]
while (n>0):
a=int(float(n%2))
k.append(a)
n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
string=string+str(j)
print('Liczba ',n,"w systemie binarnym wynosi: ",string) |
n = int(input("Podaj liczbe n: "))
x = int(input("Podaj początek zakresu: "))
y = int(input("Podaj koniec zakresu: "))
def sprawdzanie(n,x,y):
if n>x and n<y:
print("Liczba mieści sie w zakresie")
else:
print("Liczba nie mieści się w zakresie")
sprawdzanie(n,x,y) |
x = int(input("Podaj liczbę: "))
if x%2==0:
print("Liczba jest parzysta")
else:
print("Liczba jest nie parzysta") |
from ascii_art import print_hello
print_hello("making your own game board")
a=' ---'
b='| '
c="|"
size=input("How big do you want your game board? Use commas to tell x and y apart (x,y): ")
size2=size.split(',')
x=int(size2[0])
y=int(size2[1])
with open('gameboard.txt','w') as file:
for i in range(y):
fil... |
a=[]
b=[]
l=[]
print('Digit the elements of the 1st list one by one. Press "." when you are done: ')
while True:
c=input()
if c!=".":
a.append(c)
elif c==".":
break
print('Digit the elements of the 2nd list one by one. Press "." when you are done: ')
while True:
d=input()
if d!=".":
... |
from datetime import datetime, time, timedelta
import sys
import pytube
def is_time_between(begin_time, end_time, check_time=None):
# If check time is not given, default to current UTC time
check_time = check_time or datetime.utcnow().time()
if begin_time < end_time:
return check_time >= begin_tim... |
import time,random
import numpy as np
from math import factorial
import matplotlib.pylab as plt
def dise(trials,N,p):
histogram = np.zeros(N+1 , int)
sum = 0.0
j=0
r=0
while j < trials :
sum = 0
for i in range(N):
rd=random.random()
if(rd<p):
... |
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
xs = [3... |
class Personne:
"""docstring for Personne."""
def __init__(self, nom, prenom):
self.nom = nom
self.prenom = prenom
self.compte_bancaire = None
def creer_compte_bancaire(self):
self.compte_bancaire = CompteBancaire(self.nom)
def depot(self, somme):
self.compte_b... |
# Даны два целых числа A и В. Выведите все числа от A до B включительно, в порядке возрастания, если A < B,
# или в порядке убывания в противном случае.
a = int(input())
b = int(input())
s = 0
p = 0
if a < b:
s = 0
for s in range(a, b + 1):
print(s)
else:
for s in range(a, b - 1, -1):
print... |
print('Даны три целых числа. Определите, сколько среди них совпадающих. Программа должна вывести одно из чисел: 3 (если все совпадают), 2 (если два совпадает) или 0 (если все числа различны).')
a = int(input())
b = int(input())
c = int(input())
x = 0
if a == b:
x += 2
if b == c:
x += 2
if c == a:
x += 2
if... |
# Последовательность Фибоначчи определяется так:
# φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
# По данному числу n определите n-е число Фибоначчи φn.
# Эту задачу можно решать и циклом for.
n = int(input())
x, y, z = 0, 1, 1
if n == 0:
z = 0
else:
i = 1
for i in range(1, n):
z = x + y
x, y = y, z
... |
# Последовательность состоит из натуральных чисел и завершается числом 0.
# Определите значение наибольшего элемента последовательности.
s, d, f = 0, 0, 0
while True:
s = input()
if s == '0':
break
if int(s) > int(d):
d = s
print(d)
|
# Дана строка. Замените в этой строке все появления буквы h на букву H, кроме первого и последнего вхождения.
s = input()
a = s.find('h')
b = s.rfind('h')
print(s[:a+1] + s[a+1:b].replace('h', 'H') + s[b:]) |
from math import ceil
a = int(input())#рубли
b = int(input())#копейки
n = int(input())#кол-во пирожков
x = n*(a*100 + b)
print(int(x//100), (x%100)) |
# Дано натуральное число A. Определите, каким по счету числом Фибоначчи оно является, то есть выведите такое число n,
# что φn = A. Если А не является числом Фибоначчи, выведите число -1.
a = int(input())
x, y, z = 0, 1, 1
i = 1
while a > z:
z = x + y
x, y = y, z
i += 1
if a == z:
print(i)
... |
# Задача «Количество элементов, которые больше предыдущего»
s, d, i = 0, 0, 0
d = input()
while True:
s = input()
if s == '0':
break
if int(s) > int(d):
i += 1
d = s
print(i) |
# Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в
# строку и выведите получившуюся строку.
# При решении этой задачи не стоит пользоваться циклами и инструкцией if.
s = input()
x = int(s.find(' '))
print(s[x+1:], s[:x])
|
def OneDollarGame():
p = int(input("Enter # of pennies: "))
n = int(input("Enter # of nickels: "))
d = int(input("Enter # of dimes: "))
q = int(input("Enter # of quarters: "))
total = p + 5 * n + 10 * d + 25 * q
if total == 100:
print ("Congrats, you won 'One Dollar... |
myInput = (2, 123.4567, 10000)
print("file_00{} , floatr2: ,{:.2f}, center15,{:>15.2e}".format(myInput[0], myInput[1], myInput[2]))
for x in range(1):
myTuple = (float(input("what is age")),str(input("what is your name")),float(input("what was your age last year")))
print("the first 3 numbers are: {:$< 8.2f}... |
# Week 7 - Lab #1: HTML Renderer Exercise
# Date: Friday, February 19, 2016
# Student: Chi Kin Ho
# !/usr/bin/env python
"""
Python class example.
"""
# The start of it all:
# Fill it all in here.
class Element(object):
tag = 'html' # class attribute
level = 1 # indentation level
def __init__(self, c... |
# this is a re-do of the slicing lab to make sure I did it
'''
return a sequence with the first and last items exchanged.
return a sequence with every other item removed
return a sequence with the first and last 4 items removed, and every other item in between
return a sequence reversed (just with slicing)
return a s... |
def size_func(fib, lfib):
if fib % 2 == 0:
size = 'medium'
else:
if lfib % 2 == 0:
size = 'large'
else:
size = 'small'
return size
def list_pop(fib_list, size_list):
list_len = len(fib_list)
for i in range(3):
indx = i + list_len
fib_... |
"""mailroom.py
Deana Holmer
Practice with Dictionaries, User Input and Strings"""
# one way to populate tuple-like dictionary with initial values
donors = \
{ 'Chuck': [100,200,300],
'Mary': [50],
'Todd': [50,100],
'Janet': [200,300],
'Bob': [10,20,30]
}
# alternate meth... |
#!/usr/bin/python3.4
'''
#########################################################################
SECTION 1 OF LIST LAB
#########################################################################
#1 Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”
#2 Display the list
#3 Ask the user for anot... |
#!/usr/bin/python
#Author:kbindhu
#Date:1/27/2016
#ROT13 encryption
"""Below program takes any amount of text and returns the text with each letter replaced
by letter 13 away from it."""
"""Algorithm is to convert each letter in the input text to ascii code with ord function.
Then for alphabets a-m and A-M add 13 to as... |
#!/usr/bin/python3
#Open the students file
language_dict = {}
with open("students.txt", "r") as f:
for line in f:
# Split on full name (given by ':')
name = line.split(":")[0]
languages = line.split(":")[1]
# Convert the languages into a list
languages = languages.split(... |
# return sequence with last and first items changed
seq1 = [4,5,6,7,8,9]
temp = seq1[0]
length = len(seq1)
temp1 = seq1[length-1]
print("original sequence",seq1)
seq1.pop(0)
seq1.pop(length-2)
print("sequence with first and last element removed",seq1)
seq1.append(temp)
seq1.insert(0,temp1)
print("sequence with the ... |
def enterACoin (coinName):
numberOfCoins = input("Enter the number of "+coinName+":")
try:
int(numberOfCoins)
return int(numberOfCoins)
except:
print("Please enter an integer")
return enterACoin(coinName)
def isADollar(pennies, nickels, dimes, quarters):
value = pennies*.01+nickels*.05+dimes*.1+quar... |
#define trapez function
"""Compute the area under the curve defined by
y = fun(x), for x between a and b
:param fun: the function to evaluate
:type fun: a function that takes a single parameter
:param a: the start point for teh integration
:type a: a numeric value
:param b: the end point for the integration
:type b... |
# Write a program that prints the numbers from 1 to 100 inclusive.
# for multiples of three print “Fizz” instead of number
# For multiples of five print “Buzz”.
# multiples of both three and five print “FizzBuzz”
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
... |
def trapz(fun, a, b, num_steps, **kwargs):
"""
Compute the area under the curve defined by
y = fun(x), for x between a and b
:param fun: the function to evaluate
:type fun: a function that takes a single parameter
:param a: the start point for the integration
:type a: a numeric value
... |
# print out the numbers from 1 to n, but replace numbers divisible by 3 with "Fizz",
# numbers divisible by 5 with "Buzz". Numbers divisible by both factors should display "FizzBuzz.
# The function should be named FizzBuzz and be able to accept a natural number as argument
def FizzBuzz(n):
for i in range(n): #si... |
import math
class Circle(object):
@classmethod
def from_diameter(cls, diameter):
return cls(diameter/2)
def __init__(self, radius):
self.r = radius
@property
def radius(self):
return self.r
@radius.setter
def radius(self, val):
self.r = val
@prope... |
#!/usr/bin/env python3
total = 0
print("Please input the number of...")
pennies = int(input(" " * 4 + "pennies: "))
total += pennies
nickels = int(input(" " * 4 + "nickels: "))
total += nickels * 5
dimes = int(input(" " * 4 + "dimes: "))
total += dimes * 10
quarters = int(input(" " * 4 + "quarters: "))
total += q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.