text stringlengths 37 1.41M |
|---|
'''
PROBLEM SHERLOCK AND ANAGRAMS
Two strings are anagrams of each other if the letters of one string can be
rearranged to form the other string. Given a string, find the number of
pairs of substrings of the string that are anagrams of each other.
'''
'''
Approach is that,
First create a dictionary for each sequence ... |
'''
PROBLEM: LUCK BALANCE PROBLEM
Lena is preparing for an important coding competition that is preceded by a
number of sequential preliminary contests. She believes in "saving luck", and
wants to check her theory. Each contest is described by two integers, L[i] and T[i] :
L[i]: The amount of luck associated with a c... |
'''
PROBLEM ALTERNATING_CHARACTER
You are given a string containing characters and only. Your task is to change
it into a string such that there are no matching adjacent characters. To do this,
you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required delet... |
import pygame
class Obstacle:
def __init__(self, screen, camera, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.screen = screen
self.camera = camera
def draw(self):
pygame.draw.rect(
self.screen,
... |
for _ in range(int(input())):
n = int(input())
i = 1
if(n==0):
print('1')
elif(n==1 or n== 2):
print('2')
else:
while(2**i <=n):
i+=1
tmp = 2**(i-1)
if(tmp == n):
print(n)
elif((tmp*2 -1) == n):
print(n+1)
el... |
# Let's edit the script
def sayHello(people_name):
print("hello " + people_name)
print("How are you doing ? ")
answer = str(input(">>> "))
if answer == "I'm fine" or answer == "Fine" or answer == "Good":
print("So you have a nice day!")
elif answer == "I am not good":
print("Oh come on make a ... |
class Compagnie(object):
argent = 0
employes = 0
matiere = 0
mois = 1
def __init__(self, argent, employes, matiere, mois):
self.argent = argent
self.employes = employes
self.matiere = matiere
self.mois = mois
def achat(self, fournisseur, volume):
while v... |
# Boxplot to find outliers
import matplotlib.pyplot as plt
import numpy as np
col1 = np.array([-5, 4, 5, 3, 2.3, 4.1, 5.4, -6, 3.6, 5.6, 12, 4.3, 4, 2, 5.1, 10])
col2 = np.array([-5, 4, 5, 13, 12.3, 14.1, 15.4, -6, 13.6, 15.6, 12, 14.3, 14, 12, 15.1, 30])
age = np.array([22, 21, 23, 25, 25, 21, -5, 33, 32, 70, 21, -1,... |
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = x**2
y2 = x**3
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.4])
ax2 = fig.add_axes([0.5, 0.5, 0.4, 0.4])
ax1.set_title('SQUARE CURVE')
ax1.set_xlabel('Number')
ax1.set_ylabel('Square')
ax2.set_title('CUBE CURVE')
ax2.set_xlabel('Numbe... |
import pandas as pd
import numpy as np
student_data = {'Name': ['Suraj', 'Uttam', 'Anish', 'Rohit', 'Lalit', 'Shivam', 'Srikant', 'Aryan'],
'Roll': [101, 102, 103, 104, 105, 106, 107, 108],
'Marks': [56.5, 62.5, 68.8, 63.3, 65.5, 78.9, 80.9, 68.7],
'Age': [30, 31, 34, 28... |
# WAP to check a given is odd or even
num = eval(input("Enter a number: ")) # eval() can store int or float both as an input
if(num%2 == 0):
print(num, "is even number.")
else:
print(num,"is odd number.") |
'''
working on 'Series' one of Data Structure of pandas
'Series' is used for 1D data
'''
import pandas as pd
import numpy as np
print(pd.__version__)
arr1 = np.array([1, 2, 3, 4,5])
x1 = pd.Series(arr1) # 'S' is capital of Series data structure of pandas
print(x1)
arr2 = np.array([1, 2, 3.5, 5, 4, 5]) # ... |
import numpy as np
a = np.array([[1, 2, 3],[5, 6, 7], [10, 11, 12]])
print(a)
print(a.flatten()) # it covert in 1D array
print(a.flatten(order='F')) # it prints matrix in column bias
# order = c (print array in row bias by default)
# order = f (print array in column bias not by default)
print (a)
y = np.ravel(... |
# tuple = it is immutable can't modify tuple
x = ()
print(type(x))
y = tuple()
print(type(y))
x = (1, 2, 3)
print(x, type(x))
'''
print(x[0])
x[0]= 5
print(x)
'''
y = (1, 2, 4.5, 'iit', 'kanpur')
print(y)
x = ("patna")
print(x, type(x))
x = ("patna",)
print(x, type(x))
x = (1,2,3,5,1,3,1,5,1,7)
print(x.count(1))
p... |
print(help('for'))
print("-"*50) # line breaker for printing ------------ 50 times
print() # for one line space
a= [1,2,3,4,5]
for i in a:
print(i)
print("-"*50)
print()
b = ["Patna", "Noida", "Delhi", "Varanashi", "Kanpur"]
for i in b:
print(i)
print("-"*50)
print()
for x in "Delhi":
p... |
crr=[]
def read():
with open("test.txt") as f:
# f.readline()
for line in f:
line=line.strip()
data=line.split(" ")
brr=split(data)
print(brr)
for index in range(len(brr)):
if data[10] == brr[index]:
... |
# A simple mathematical function on which to try different testing frameworks
def square_plus_10(x):
"""
Doctest Example (Including one designed to fail)
>>> square_plus_10(2)
14
>>> square_plus_10(-2)
14
>>> square_plus_10(7)
A very surprised sperm whale
"""
return (x * x) + 10... |
from Iterator import Iterator
class BookShelfIterator(Iterator):
def __init__(self, bookshelf):
self.index = 0
self.bookShelf = bookshelf
def hasNext(self):
if self.index < self.bookShelf.get_length():
return True
else:
return False
def next(self):... |
import unittest
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if (num**(1/2)).is_integer():
return True
else:
return False
def isPerfectSquareMethod2(self, num: int) -> bool:
if num < 2:
return True
left = 2
right = num ... |
#Author: Brandon Fook Chong
#Student ID: 260989601
def get_iso_codes_by_continent(filename):
'''
(str) -> dict
Using a file containing the ISO codes of countries and their respective continents,
this function returns a dictionary with keys as the continents and associated to them
a li... |
import numpy as np
class Vector2d:
"""
Class object represents vector and allows performing basic vector operations
"""
def __init__(self, x=0., y=0.):
self.x = x
self.y = y
def rotate(self, angle):
"""
Rotates self object by the given :angle
"""
return Vector2d(
self.x*np.co... |
from functools import reduce
def product(s):
list_s = map(int, list(s))
return reduce((lambda x, y: x*y), list_s)
def largest_product(series, size):
if size == 0:
return 1
if size < 0 or size > len(series) or not series.isdigit():
raise ValueError
length = len(series)
substr... |
def abbreviate(words):
return ''.join([x[0].upper() for x in words.replace('-', ' ').split() if x[0].isalnum()]) |
"""
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
For the purposes of this kata, som... |
#!/usr/bin/env python
def fix_indents(infile, show=False, detect=False):
"""
Tries to make YAML indentation a consistent 2-spaces.
Identifies inconsistent indenation by tracking the indentation jump
Parameters
----------
infile : str
Filename to use
show : bool
If True, ... |
def convert(fahr):
return (fahr - 32)*(5/9)
def main():
while True:
fahr = input('enter fahrenheit:')
cent = convert(int(fahr))
print('%s 华氏度等于 %.2f 摄氏度' % (fahr,cent))
if __name__ == "__main__":
main()
|
#crear menu con 3 opciones
import os
def Numeros():
#ingresar n numeros donde n es numero ingresado por teclado
#mostrar cantidad de numeros positivos, negativos y iguales a 0
pos=0
neg=0
cero=0
cant=int(input("ingrese cantidad de números a ingresar: "))
for i in range(cant):
nume=int(input(str(i+1)+" Digite l... |
import adventure_game.my_utils as utils
room1_inventory = {
"knife" : 1,
}
room1_locked = {
"east" : True,
"west" : False,
"north" : False,
"south" : False
}
# # # # # # # # # # # # # # #
# This is the main room you will start in.
#
# GO: From this room you can get to Room 2 (SOUT... |
import adventure_game.my_utils as utils
# # # # #
# ROOM 10
#
# Serves as a good template for blank rooms
room10_description = '''
. . . 10th room ...
You are in a tall cave, the ceiling is shrouded in darkness and the only sound is the flutter of little,
leathery wings. There are doors leading ... |
#!/bin/python
import sys
def funnyString(s):
r = s[::-1]
for i in range(1, len(s)):
a = abs(ord(r[i]) - ord(r[i-1]))
b = abs(ord(s[i]) - ord(s[i-1]))
if a != b:
return "Not Funny"
return "Funny"
# Complete this function
q = int(raw_input().strip())
for a0 in xrange... |
#!/bin/python
import sys
def solve(year):
if year < 1918:
if year % 4 == 0:
print "12.09." + str(year)
else:
print "13.09." + str(year)
elif year == 1918 :
print "26.09.1918"
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
... |
with open ("Sonia_fav_foods.txt") as sonia_foods:
sonia_list = sonia_foods.readlines()
sonia_faves = []
for item in sonia_list:
item = item.strip()
sonia_faves.append(item)
with open ("Ally_fav_foods.txt") as ally_foods:
ally_list = ally_foods.readlines()
ally_faves = []
for ite... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#!/usr/bin/env python
"""mapper.py"""
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
# increase counters
... |
#写一个函数input_student()得到学生的姓名,年龄,年龄
# 输入一些学生信息;按照年龄从大到小排列,并输出
# 按照成绩从高到低排序后,并输出
#第一步,读取学生信息,形成字典后存入列表L中
def input_student():
L = []
while True:
name = input('请输入学生姓名:')
if not name:
break
age = int(input('请输入学生年龄:'))
score = int(input('请输入学生成绩:'))
d... |
"""
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
This module runs on your LAPTOP.
It uses MQTT to SEND information to a program running on the ROBOT.
Authors: David Mutchler, his colleagues, and Ricardo Hernandez.
"""
import tkinter
from tkinter i... |
# Class example. A class is nothing more than a way to wrap a bunch of
# variables and functions together under one 'roof'. Objects of a function
# have access to all the members (variables) of the class and can call
# the methods (functions) associated with the class. Here we have a class:
# Drawer. Drawer objects... |
import os
import re
f = open('paragraph_1.txt', 'r')
content = f.read()
words = re.split(r"[\s\.,\?]+",content)
characters = 0
#Calculate number of words
d = len(words)
#Calculate number of sentences
sentence = content.count('.')
#Calculate Average number of sentences
avg_sent_count = d/sentence
#Calculate Avera... |
import numpy as np
# 균일한 간격으로 데이터 생성
array = np.linspace(0, 10, 5)
# 0: 시작값
# 10: 끝값
# 5: 시작값과 끝값 사이에 몇개의 데이터가 있는가
print(array)
# 난수의 재연(실행마다 결과 동일)
np.random.seed(7)
print(np.random.randint(0, 10, (2, 3)))
# Numpy 배열 객체 복사
array1 = np.arange(0, 10)
array2 = array1.copy()
array2[0] = 99
print(array1... |
# 배열 형태 바꾸기
import numpy as np
array1 = np.array([1, 2, 3, 4])
# 2 * 2 행렬로 바뀜
array2 = array1.reshape((2, 2))
print(array2) |
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# 배열을 합침
array3 = np.concatenate([array1, array2])
# 배열의 크기 출력
print(array3.shape)
print(array3) |
import numpy as np
array1 = np.arange(0, 8).reshape(2, 4)
array2 = np.arange(0, 8).reshape(2, 4)
array3 = np.concatenate([array1, array2], axis=0)
array4 = np.arange(0, 4).reshape(4, 1) # (4 * 1)
print(array3 + array4) |
# -*- coding: utf-8 -*-
"""
Write a Python function, `odd`, that takes in one number and returns `True` when the number is odd and `False` otherwise.
You should use the `%` (mod) operator, not `if`.
This function takes in one number and returns a boolean.
"""
def odd(x):
return x % 2 != 0
|
# -*- coding: utf-8 -*-
"""
Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this ... |
"""
1. Convert the following into code that uses a while loop.
print '2'
prints '4'
prints '6'
prints '8'
prints '10'
prints 'Goodbye!'
"""
i = 0
while i < 10:
i += 2
print(i)
print("Goodbye!")
"""
2. Convert the following into code that uses a while loop.
prints 'Hello!'
prints '10'
prints '8'
prints '6'
pri... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertafter(self, prev, new_data):
if prev == None:
return " Error... |
#time complexity
def compress(string):
strlen = len(string)
compressL=[string[0]]
num = 1
indexc=0
for i in range(1,strlen):
if(string[i] != compressL[indexc]):
compressL.append(str(num))
compressL.append(string[i])
indexc+=2
num=1
els... |
import pandas as pd
df1 = pd.read_html('https://en.wikipedia.org/wiki/Sales_taxes_in_the_United_States')
df = df1[3].drop(df1[3].index[0]).drop([3,4,5,6,7,8], axis=1)
df.columns = ['State/territory/district' ,'Base sales tax' ,'Total with max local surtax']
#remove the % sign
df['Base sales tax']=df['Base sales tax... |
def txt_to_xml(filename):
# Open file and read the lines of the file and then close the file
file = open(filename, 'r')
lines = file.readlines()
file.close()
# Create count variable to index where the xml of the data table info begins
count = 0
for line in lines:... |
import math
"""
NIFS3 (pl. Naturalna Interpolacyjna Funkcja Sklejana 3-go stopnia)
Polynomial interpolating function using given points (x, f(x))
Spline : https://en.wikipedia.org/wiki/Spline_interpolation#Algorithm_to_find_the_interpolating_cubic_spline
"""
class Spline:
_xs = []
_ys = []
_diff_quos =... |
some_list = ['one', 'two', 'three', 'four']
#Method :1
#Conver the list to string and then remove the first and last element
method_1 = str(some_list)[1:-1]
#Method :2
#Use join to seperate elements
method_2 = ', '.join(map(str, some_list))
|
random_list = [1,2,3,3,4,5,5,6,7,7,8,8]
#Using set we can remove duplicates from a sequence
remove_duplicates = set(random_list)
convert_to_list = list(remove_duplicates)
print convert_to_list
|
def readfile(): #reads str into memory calls it f
text_file = open("file.txt","r")
f = text_file.read()
return f |
nome = input('Informe seu nome completo: ')
div = nome.split()
pn = div[0]
un = div[len(div)-1]
print('{} tem como primeiro nome {} e último nome {}.'.format(nome, pn, un))
|
cel = float(input('Informe a temperatura em ºC: '))
far = 1.8 * cel + 32
print('A temperatura de {}ºC corresponde a {}ºF.'.format(cel, far))
|
nome = input('Digite seu nome: ').strip()
print('Este é seu nome com letras maiúsculas: {}.'.format(nome.upper()))
print('Este agora com letras minúsculas: {}.'.format(nome.lower()))
div = nome.split()
joi = ''.join(div)
print('O número de letras do seu nome é: {}.'.format(len(joi))) # format(len(nome) - nome.count(' ... |
cont = 0
soma = 0
for c in range(3, 500, 3):
if c % 2 == 1:
soma += c
cont += 1
print(f'''A somatória entre todos os {cont} números ímpares
que são múltiplos de 3
no intervalo entre 1 e 500 é igual a {soma}.''')
|
from random import shuffle
print('Vamos sortear a ordem de apresentação do grupo de 4 alunos!')
a = input('Informe o nome do primeiro aluno: ')
b = input('Informe o nome do segundo aluno: ')
c = input('Diga o nome do terceiro aluno: ')
d = input('E finalmente insira o nome do quarto aluno: ')
l = [a, b, c, d]
shuffle(l... |
sal = float(input('Informe o seu salário: R$'))
aum = sal * 1.15
print('O seu salário era R${:.2f} e com o aumento de 15% ficará R${:.2f}'.format(sal, aum))
|
# greeting = "Hello"
# name = input("Please enter your name ")
# print(greeting + " " + name)
spiltString = "This string has been\nsplit over\nseveral\nlines"
print(spiltString)
tabbedString = "1\t2\t3\t4\t5"
print(tabbedString)
print (""" THis is also working """) |
from pet_goods import pet_goods
from pet_animals import pet_animals
class pet_rodents(pet_animals):
def __init__(self, name, price, kind_pet, age, rodent_breed):
pet_animals.__init__(self, name, price, kind_pet, age)
self.rodent_breed = rodent_breed
def display_rodents(self):
print(self... |
"""
Имя проекта: №27
Номер версии: 1.0
Имя файла: practicum-1(№27).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 26/11/2020
Дата последней модификации: 26/11/2020
Дано вещественное число А. Вычислить f(A), е... |
"""
Имя проекта: №54
Номер версии: 1.0
Имя файла: practicum-1(№54).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 13/12/2020
Дата последней модификации: 13/12/2020
Описание: Решение задач № 54 практикума № 1
... |
"""
Имя проекта: №91
Номер версии: 1.0
Имя файла: practicum-1(№91).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 24/05/2021
Дата последней модификации: 24/05/2021
Описание: Создать прямоугольную матрицу A, и... |
"""
Имя проекта: №38
Номер версии: 1.0
Имя файла: practicum-1(№38).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 28/11/2020
Дата последней модификации: 28/11/2020
Дан одномерный массив числовых значений, нас... |
"""
Имя проекта: №29
Номер версии: 1.0
Имя файла: practicum-1(№29).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 26/11/2020
Дата последней модификации: 26/11/2020
Известен ГОД. Определить, будет ли этот год ... |
"""
Имя проекта: №82
Номер версии: 1.0
Имя файла: practicum-1(№82).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 24/05/2021
Дата последней модификации: 24/05/2021
Описание:Создать прямоугольную матрицу A, им... |
"""
Имя проекта: №56
Номер версии: 1.0
Имя файла: practicum-1(№56).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 18/12/2020
Дата последней модификации: 18/12/2020
Описание: Решение задач № 56 практикума № 1
... |
"""
Имя проекта: №19
Номер версии: 1.0
Имя файла: practicum-1(№19).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 21/11/2020
Дата последней модификации: 21/11/2020
Даный вещественные числа: X.Y.Z. Определить,... |
"""Define the main controller."""
from typing import List
from models.deck import Deck
from models.player import Player
class Controller:
"""Main controller."""
def __init__(self, deck: Deck, view, checker_strategy):
"""Has a deck, a list of players and a view."""
# models
self.play... |
from .charclass import count_digits
def is_valid_day (val):
""" Checks whether or not a two-digit string is a valid date day.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid date day, otherwise false.
"""
if len(val) == 2 and count_digits(val) =... |
#!/usr/bin/env python
"""circle class --
fill this in so it will pass all the tests.
"""
import math
class Circle(object):
def __init__(self, x):
self._radius = x
self._diameter = x * 2
def _getradius(self):
return self._radius
def _setradius(self, value):
self._radius =... |
#!/usr/bin/env python
def count_evens(nums):
return len([x for x in nums if not x % 2])
nums = [2, 1, 2, 3, 4]
print count_evens(nums) |
from datetime import datetime
from aplication.salary import calculate_salary
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__... |
#!/usr/bin/env python
import random
import sys
print 'Print out min and max from a list of numbers'
list = random.sample(range(1, 100), 20)
print list
min = sys.maxint
max = -1
for num in list:
if num < min:
min = num
if num > max:
max = num
print 'Min: ' + str(min)
print 'Max: ' + str(max)
|
# Uses python3
import argparse
import datetime
import random
import sys
# def get_majority_element_fast(nrcall, a, left, right):
# # if array is only 2 elements long, the base case is reached
# # and a majority element is determined
# if left == right:
# print('call ' + str(nrcall) + ': ' + ... |
# Uses python3
import argparse
import random
import sys
import datetime
from collections import namedtuple
def getGreaterOrEqual(digit, maxDigit):
a = str(digit) + str(maxDigit)
b = str(maxDigit) + str(digit)
if a > b:
return digit
else:
return maxDigit
def largest_number(a):
#wr... |
# Uses python3
import argparse
import random
import sys
import datetime
import time
def partition3(a, l, r):
m1 = l
m2 = r
i = l+1
x = a[l]
while(i <= m2):
if a[i] < x:
a[m1], a[i] = a[i], a[m1]
m1 += 1
i += 1
elif a[i] > x:
... |
# Uses python3
import argparse
import random
import sys
import datetime
import string
def knapsack_dynamic_programming(capacity, bars, solutiontable=False):
n = len(bars)
# create the matrix
# rows => gold_bars, columns => weight
matrix = [[None] * (capacity+1) for i in range(n+1)]
# initialize... |
#Uses python3
import sys
#import pydot
import os
class Digraph(object):
'''
Returns a Graph-object
'''
# graph in format 'adjacency list'
adjacencyList = None
# graph in format 'edge list'
edgeList = None
# amount of vertices
count_vertices = 0
# weight
cost = None... |
import turtle
import random
x=turtle.Turtle()
colors=['red','blue','green','purple','yellow','orange','black']
x.color('red','blue')
x.width(5)
x.begin_fill()
x.circle(50)
x.end_fill()
x.penup()
x.forward(150)
x.pendown()
x.color('yellow','black')
x.begin_fill()
for y in range(4):
x.forward(100)
x.right(90)... |
#coding=utf-8
import math
x=input("请输入年纪:")
# floor函数将一个数取整为小于等于该数的最小的整数
# 与floor相对的函数是ceil,可以将给定的数值转换成为大于或者等于它的最小整数
age=int(math.floor(x))
print (u"年龄最小是%d" %age)
age2=math.ceil(x)
print (u"年龄最大是%d" %age2)
# 在确定不会导入多个同名函数(从不同模块导入)的情况下,可以使用import
# 的另外一种形式:
from math import sqrt
print sqrt(9) |
#coding=utf-8
# 列表推导式是利用其他列表创建新列表的一种方法
print [x*x for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 只打印能被3整除的平方数
print [x*x for x in range(10) if x%3==0]
# [0, 9, 36, 81]
# 也可以增加更多for语句的部分:
print [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), ... |
#coding=utf-8
string1='Hello'
# 因为字符串不能像列表一样被修改,所以有时候根据字符串创建列表会很有用。list函数可以实现这个操作
# list函数适用于所有类型的序列,而不只是字符串
list1=list(string1)
# 可以使用下面的表达式将一个由字符组成的列表转换成为字符串:
string2=''.join(list1)
print list1
print string2
|
#coding=utf-8
name=list('Perl')
print name
# 输出:['P', 'e', 'r', 'l']
name[2:]=list('ar')
print name
# 输出:['P', 'e', 'a', 'r']
# 使用分片赋值时,可以使用与原序列不等长的序列将分片替换
name2=list('Lilei')
name2[1:]=list('python2.7')
print name2
# 分片赋值语句可以不需要替换原有元素的情况下插入新的元素
numbers=[1,5]
numbers[1:1]=[2,3,4]
print numbers
# 输出:[1, 2, 3, 4, 5]
... |
#coding=utf-8
x=1
while x<=100:
print x
x += 1
name=''
# while not name:
# name=raw_input("Please enter your name:")
# print "Hello,%s!"%name
# 如果输入一个空格,程序也会接受这个名字,可以这样修改程序:
while not name or name.isspace():
name=raw_input("Please enter your name:")
print "Hello,%s!"%name
# 或者使用while not name.str... |
#coding=utf-8
# str、repr、和反引号是将Python值转换为字符串的3种方法。
# str函数会把值转换为合理形式的字符串
# 而repr会创建一个字符串,它以合法的Python表达式的形式来表示值
# 例:
print repr("Hello world!")
# 输出:'Hello world!'
print str("Hello world!")
# 输出:Hello world!
# repr(x)的功能也可以使用`x`实现(注意,`是反引号,而不是单引号)。
# 在python3.0中,已经不再使用反引号。
# 如果希望打印一个包含数字的句子,那么反引号就很有用了。比如:
temp=5
# 下面这... |
"""
A prison can be represented as a list of cells. Each cell contains exactly one prisoner.
A 1 represents an unlocked cell and a 0 represents a locked cell.
[1, 1, 0, 0, 0, 1, 0] Starting from the leftmost cell,
you are tasked with seeing how many prisoners you can set free, with a catch.
Each time you free a pri... |
"""
Mona has created a method to sort a list in ascending order.
Starting from the left of the list, she compares numbers by pairs.
If the first pair is ordered [smaller number, larger number], she moves on.
If the first pair is ordered [larger number, smaller number], she swaps the two integers
before moving on to... |
"""Create a function that removes all capital letters and punctuation in a string. Return the clean string."""
import string
def clean_string(s):
for i in s:
if i.isupper() or i in string.punctuation:
s = s.replace(i, '')
return s
print(clean_string('HELLO hello hi bye (*)^*&^(*&^(*&^AB... |
"""Make a function that encrypts a given input with these steps:
Input: "apple"
Step 1: Reverse the input: "elppa"
Step 2: Replace all vowels using the following chart:
a => 0 e => 1 o => 2 u => 3
#"1lpp0"
Step 3: Add "aca" to the end of the word: "1lpp0aca"
Output: "1lpp0aca"
Examples
encrypt("banana") ➞ "0n0n0b... |
"""Someone has attempted to censor my strings by replacing every vowel with a *, l*k* th*s. Luckily, I've been able to find the vowels that were removed.
Given a censored string and a string of the censored vowels, return the original uncensored string.
Example
uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo") ➞ "Where d... |
"""
Given a string, count all the lowercase letters.
Return a dictionary with the keys as the lowercase letters
and the values as the letters' counts respectively.
The keys should be sorted in alphabetical order.
Example:
Input:
"apple"
Output:
{'a': 1, 'e': 1, 'l': 1, 'p': 2}
"""
def dict_counter(string):
... |
from abc import ABC, abstractmethod
class Implementation(ABC):
"""
The Implementation defines the interface for all implementation classes. It
doesn't have to match the Abstraction's interface. In fact, the two
interfaces can be entirely different. Typically the Implementation
interface provides o... |
from abc import ABC, abstractmethod
from behavioral.visitor.component import ConcreteComponentA, ConcreteComponentB
class Visitor(ABC):
"""
The Visitor Interface declares a set of visiting methods that correspond to
component classes. The signature of a visiting method allows the visitor to
identify ... |
from abc import ABC, abstractmethod, abstractproperty
class Builder(ABC):
"""
The Builder interface specifies methods for creating the different parts of
the Product objects.
"""
@abstractproperty
def product(self) -> None:
pass
@abstractmethod
def produce_part_a(self) -> Non... |
from abc import abstractmethod
from typing import Any, Optional
from behavioral.chain_responsibility.handler import Handler
class AbstractHandler(Handler):
"""
The default chaining behavior can be implemented inside a base handler
class.
"""
_next_handler: Handler = None
def set_next(self, ... |
import numpy as np
import matplotlib.pyplot as plt
def step_function(x):
if x>0:
return 1
else:
return 0
def step_function2(x):
return np.array(x>0, dtype=np.int)
x = np.array([-1.0, 1.0, 2.0])
y = x > 0
y = y.astype(np.int)
print(y)
x = np.arange(-5.0, 5.0, 0.1)
y = step_function2(x)
pl... |
"""
Created by HerbertAnchovy in September 2017 as part of the 'Object-oriented Programming in Python'
FutureLearn course from the Raspberry Pi Foundation.
See https://www.futurelearn.com/courses/object-oriented-principles for details.
"""
class Item():
"""A class to create an item"""
# Constructor method used to... |
# cluster companies using their daily stock price movements
# (i.e. the dollar difference between the closing and opening prices for each trading day).
# You are given a NumPy array movements of daily price movements from 2010 to 2015 (obtained from Yahoo! Finance),
# where each row corresponds to a company, and each c... |
# -*- coding:utf-8 -*-
# Tuple
# The item in the tuple can't modify , visited only,it's data type isn't limited.
tuple = ('a string',False,2.5,34)
print tuple
print type(tuple) # print: <type 'tuple'>
print tuple[0]
print tuple[1]
print tuple[2]
print tuple[3]
#print tuple1[4] # Will throw an Index Error:tuple index o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.