text stringlengths 37 1.41M |
|---|
def fizzbuzz(n):
"""
>>> result = fizzbuzz(16)
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
>>> result is None
True
"""
current = 1
while current <= n:
if (current % 3 == 0) and (current % 5) == 0:
print("fizzbuzz")
elif current % 3 == 0:
print("fizz")
elif current % 5... |
statement="The quick brown fox jumped over the lazy dogs"
for letter in statement:
if(letter=='q' or letter=='e'):
continue
print("current letter",letter)
|
grade=45
if(grade>=90):
Grade='A'
elif(grade>=80):
Grade='B'
elif(grade>=70):
Grade='C'
elif(grade>=60):
Grade='D'
else:
Grade='E'
print(Grade)
|
name="Python for beginners"
age=42
x=12.5
instructor="Mark Lassoff"
con='a'
print(name)
print(age)
print(instructor)
print(con)
print(age*x)
print(name,sep="\n",age,"\t",con,"\r")
print(name,"\n",age,"\t",con,"\r")
|
import math
class Vector:
# TODO Use operator overloading(http://blog.teamtreehouse.com/operator-overloading-python)
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
r... |
import graphvisual as G
from typing import List
class TreeNode:
def __init__(self, parent, id: int, value, children):
self.id = id
self.value = value
self.parent = parent
self.children = children
def set_children(self, children):
self.children = children
class Tree:
... |
n = int(input())
count = n
for i in range(n):
word = input()
for j in range(len(word)-1):
if word[j] == word[j+1]:
pass
elif word[j] in word[j+1:]:
count -= 1
break
print(count) |
class Deque():
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self,item):
self.items.insert(0,item)
def removeFront(self):
self.items.pop(0)
def addRear(self,item):
self.items.append(item)
def removeRear(self):
self.items.pop()
def size(self):
ret... |
from random import randrange
a = randrange(1000)
while True:
b = int(input())
if a == b:
print(" you're a winner!")
break
print('Smaller' if (a < b) else 'Bigger')
|
def pkl_exists(name, folder=False):
"""This scripts checks if a certain pkl-file already exists.
Args:
name: Name of pkl file (<name>.pkl)
folder: Folder containing pkl file
"""
if (not name.endswith('.pkl')): name = name+'.pkl'
from os.path import exists, join
# if folder is n... |
def pkl_save(obj, name, folder='.pc', ascii=True):
"""This scripts saves any kind of object as a pkl file in folder.
Args:
obj: object you want to save in an pkl file
name: name of pkl file, '.pkl' will be added automatically if missing
ascii: if you dont want to save pkl file in ascii set this... |
"""Manages pygame images"""
import collections
import os
from typing import List, Optional, Tuple
import pygame
class Animator(object):
"""Animates a sequence of images."""
def __init__(self, owner: Optional[pygame.sprite.Sprite]=None):
"""Creates an image animator.
Args:
owner: Owner of this anima... |
import turtle
from math import sqrt
t = turtle.Turtle()
def main():
t.speed(50)
t.color('red')
for i in range(40):
tr(150+i)
t.left(10)
def tr(a):
t.penup()
t.forward(a*sqrt(3)/3)
t.pendown()
t.left(150)
for i in range(3):
t.forward(a)
t.left(120)
... |
##2.1.2. DICTIONARY
##Python Dictionary is an unordered sequence of data of key-value pair form.
##It is similar to the hash table type. Dictionaries are written within curly braces in the form key:value.
##It is very useful to retrieve data in an optimized way among a large amount of data.
##Keys in a dictionary... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 18:12:36 2020
@author: Johnier Sanchez
"""
import EjercicioUno
def nombreUsuario(nombreIngresado):
# Se calcular la longitud del nomre de usuario.
long=len(nombreIngresado)
# Se calcula que la cadena contenga valores alfanuméricos.
... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
def FM(seq):
s = "ACDEFGHIKLMNPQRSTVWYX"
fm_vec = []
seq_length = len(seq)-1
for i in s:
num = seq.count(i)
if i == 'K':
num = num - 1
freq = num / seq_length
fm_vec.append(freq)
return fm_vec
... |
import json,difflib
f = open('resources/data.json')
dictionary = json.load(f)
word = input("please enter the word : ")
word = word.lower()
def checkSimilarity(word):
"""Founding the close matching words of a word
Args:
word (string): Word for which close mnatches to be found
Returns:
... |
a = {'key':'value', 'cow':'mooh'}
print(a['cow'])
#will print "mooh" on the screen# Dictionary is nothing but key value pairs
d1 = {}
print(type(d1))
# I mean by this is that Python provides us with a long list of already defined methods for dictionaries that can
# help us to do our work in a shorter span of time with ... |
from Crypto.Cipher import AES
import string
import base64
import time
import os
#crypto method
PADDING = '{'
BLOCK_SIZE = 32
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
#encryption and decryption variables
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decry... |
def test_is_palindrome():
assert is_palindrome(45) == False
assert is_palindrome(555) == True
assert is_palindrome(4554) == True
assert is_palindrome(1221) == True
def is_palindrome(n):
'''
varifica daca numarule este palindrom
:param n: natural
:return: True sau False
'''
oglin... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
2+5
# In[2]:
4-1
# In[3]:
5*7
# In[4]:
4**7
# In[8]:
4***3
# In[9]:
1.0+4.5
# In[10]:
x = 2.8
y = 4.2
z = x+y
print(z)
# In[11]:
type(z)
# In[12]:
x = 2.5
y = 4.5
z = x+y
# In[15]:
print(z)
# In[14]:
type(z)
# In[16]:
x = 3... |
#!/usr/bin/python
#-- coding: UTF-8 --
#通过%2判断是否能为2整除,能整处为偶数
i = 0
while i < 101:
if i%2 == 0:#假如i是偶数
print(i)
else:
pass
i = i + 1
#输出1-100之间的奇数
#!/usr/bin/python
#-- coding: UTF-8 --
i = 0
while i < 101:
if i%2 != 0:#假如i是奇数
print(i)
else:
pass
i = i + 1
|
# Utility methods
import sys
import time
# 0.05 is nice for effect
sleepInterval = 0.00
def WhatDoYouDo(prompt, suggestions, suggestionsOn, inventory):
p(prompt, 2)
keepAsking = True
a = suggestions
while keepAsking:
keepAsking = False
p('\nWhat do you do?')
if suggestionsOn... |
########
#
# Welcome to sticks.py
#
# This program draws sticks
#
########
# Keep this line: It gives you the plotting library
import matplotlib.pyplot as plt
# Keep this line: It gives you mathematical functions like sine and cosine
import numpy as np
# Keep this line: It assigns the value of pi (3.1415...) to t... |
import sys
import time
import items
import enemies
# Global state variables
printSuggestions = False
foyerSpiderAsleep = False
inventory = ['torch', 'sword', 'biscuit', 'match']
sleepInterval = 0.05
# methods
# rooms
def Entrance():
stuckEntrance = True
while stuckEntrance:
p('You are outside an o... |
chores = ['feed Maia', 'clean room', 'stow dishes']
print chores
print len(chores)
chores.append('chop wood')
print chores
print len(chores)
happy = False
thisChore = 0
while not happy:
print 'i am not happy because my chores are not done.'
print ' now i am doing this:', chores[thisChore]
th... |
# Knight Tour
#
# An 8 x 8 chess board is empty save for a lone knight on one corner. Can the knight make
# 63 moves and visit each remaining square of the board once?
#
# The answer is yes and writing code to solve the problem is an interesting two-stage
# exercise (the way I approach it). I have solved this pr... |
# coding=utf-8
# 作者 : MinsonHuang
# 创建时间 : 2020/12/15-16:40
# 测试仅可以传递位置参数的函数形参定义
def func_1(a, b, /):
print("a:", a)
print("b:", b)
def test_only_postion_param():
func_1(1, 2)
func_1(1, b=2) # TypeError: func_1() got some positional-only arguments passed as keyword arguments: 'b'
# 测试仅可以传递关键... |
start_day = int(input("Ranging from 0 to 6 days with 0 representing Sunday, from 0-6 what day is it? "))
days_to_wait = int(input("And what is the length of your stay? "))
end_day = (start_day + days_to_wait) % 7
print(end_day)
#While your program works but it doesn't return the weekday name.
#This one wasn't one of ... |
import numpy as np
import numpy.random as rng
def discrete_sample(p, n_samples=1):
"""
Samples from a discrete distribution.
:param p: a distribution with N elements
:param n_samples: number of samples
:return: vector of samples
"""
# check distribution
#assert isdistribution(p), 'Prob... |
#El Hola Mundo es muy conocido en Python, por eso decidi cambiar la frase
#Aunque no altera en nada lo que queremos decir ya que como quiera le estoy dando la orden de que lo imprima
#Asi hubiera puesto otra frase diferente seria igual
#El def lo utilizamos para definir una funcion y al terminar el cogigo tenemos que... |
while True:
dan=int(input('multiple:'))
if dan==0:
print('{}. exit'.format(dan))
break
if dan<2 or dan>9:
print('{} is not. Please rewrite'.format(dan))
continue
print('{} output'.format(dan))
i=1
while i<=9:
print('{}*{}={:2d}'.format(dan,i,dan*i))
i=i+1
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 27 13:10:20 2021
@judul : praktikum 2, Operasi Aritmatika pada Python
@hari tanggal : 27-09-2021
@NIM : 065002100002
@Nama : Nabilah Putri
"""
print("penghitugan aritmatika dalam python")
a=float(input("masukan nilai umur kamu:"))
b=float(input("masukan nilai... |
import sys
def init_board(r,c):
board = [' ']*r
for i in range(r):
board[i] = [' ']*c
r=int(r)
x=int(r/2)
board[x-1][x-1]='X'
board[x][x]='X'
board[x][x-1]='O'
board[x-1][x]='O'
r=str(r)
return board
def print_board(board, c):
#print first row of dashes
for ... |
def get_num_names():
num_names=int(input("How many names would you like to enter?"))
return num_names
def get_names(name_list, num_names):
for x in range(num_names):
name=input("Name "+str(x)+":").lower()
name_list[x]=name
count(name_list, num_names)
def count(name_list, num_names):
... |
######################################################################
def isPositive(s):
#checks if a string is a positive integer
for i in range(len(s)):
if s[i] < chr(48) and s[i] > chr(57):
return False
if s[0]=='-':
return False
return True
###########... |
# Write your code here
path = "flowers.txt"
#def create_flower(filename):
flower_dict = {}
# HINT: create a dictionary from flowers.txt
with open(path) as flo:
for name in flo:
(key,val) = name.split(": ")
flower_dict[str(key)] = val
#return flower_dict
#print(flower_dict)
# HINT: create a function... |
h = int(input('Height: '))
for i in range(h):
print(" "*(h-i)+"#"*(i+1));
|
#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-11-15
@author: ymy
'''
##如果要读入很多数据处理的话会占用较大内存,用生成器一个个读取数据会节约内存开销
def func():
a = 1
while a < 10:
yield a
a += 1
print 'here'
a = 1
while a < 10:
yield a
a += 1
def main():
for i in func():
print... |
#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-11-15
@author: ymy
'''
def func2(f):
def func3(x, y):
print 'x is %d, y is %d' % (x, y)
r = f(x, y)
print 'result is %d' %r
return r
#@func2
def add(x, y):
return x + y
print add(5, 7)
# def main():
# test = add(5, 6)
... |
#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-10-25
@author: ymy
'''
class A:
a = 10
def mmx(self, b):
print self.name, b
class D(A):
name = 'd'
a = A()
a.b = 20
a.name = 'bob'
d = D()
print A, A.a
print a, a.b, a.name
print d
a.mmx(20)
d.mmx(20) |
#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-11-22
@author: ymy
'''
import random
def main():
start = 1
end = 1000
c = 0
number = random.randint(start, end+1)
#print number
while True:
in_number = raw_input("input (%d - %d) " %(start, end))
print number
if in_numbe... |
#!/usr/bin/python
#coding=utf-8
'''
Created on 2017年11月15日
@author:ymy
Copyright ymyjohnny@gmail.com
'''
import sys
try:
textfile1 = sys.argv[1]
textfile2 = sys.argv[2]
except:
print 'please enter 20171115_idfa_chonghe.py text1 text2'
sys.exit()
def readline(filename):
f = open(filename,'r')
... |
#!/usr/bin/python
#coding=utf-8
'''
Created on 2015-10-25
@author: ymy
'''
#from chardet.test import result
import os
s = os.popen('cat /home/ymy/python/uplooking/少年pi的奇幻漂流\ 中文版.txt').read().decode('utf-8')
#f = open('/home/ymy/python/uplooking/少年pi的奇幻漂流\ 中文版.txt')
#s = f.read().decode('utf-8')
def split_and_extend(se... |
from Cliente import*
class Cuenta:
"""Nuestro constructor tendrá dos atributos que seran tomados en cuenta como variables de tipo booleano de tal modo que estas variables
notifiquen al estado de la cuenta en el caso de que se haya hecho un retiro o deposito"""
def __init__(self,balance):
s... |
import numpy as np
import _gsvd
def gsvd(A, B, full_matrices=False, extras='uv'):
'''Compute the generalized singular value decomposition of
a pair of matrices ``A`` of shape ``(m, n)`` and ``B`` of
shape ``(p, n)``
The GSVD is defined as a joint decomposition, as follows.
A = U*C*X.T... |
from abc import ABC, abstractmethod
# 1. Create a class hierarchy of animals with at least 5 animals that have additional methods each,
# create an instance for each of the animal and call the unique method for it.
# Determine if each of the animal is an instance of the Animals class
class Animal:
"""
Parent... |
name=raw_input ("enter your name\t")
print name
age=int(input ("your age\t"))
print age
mark=float(input ("your mark\t"))
print mark
|
class person:
name="riyas"
age=10
mark=67
student = person()
print (student.name)
print (student.age)
print (student.mark)
|
"""
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
Also: responds to Beacon button-presses by beeping, speaking.
This module runs on the ROBOT.
It uses MQTT to RECEIVE information from a program running on the LAPTOP.
Authors: David Mutchler, his co... |
def fac(i):
if i is 1:
return 1
else:
return i * fac(i-1)
def fib(n):
if n is 1:
return 1
elif n is 2:
return 1
else:
return fib(n-1) + fib(n-2)
print(fac(10))
print(fib(5))
print(fib(27)) |
people = 30
cars = 40
trucks = 15
if cars>people:
print "We should take cars"
elif cars<people:
print "We shold not take cars"
else:
print "We cant decide"
if trucks >cars:
print "thats too many trucks"
elif trucks<cars:
print "Maybe we could take the trucks"
else:
print "still cant decide... |
class Solution(object):
@staticmethod
def longest_palindromic(s: str):
# Square Matrix - length = length of the string [False]
matrix = [[False for i in range(len(s))] for i in range(len(s))]
for i in range(len(s)):
# major diagonal elements = True
matrix[i... |
#Building the CNN
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#Initialising the CNN
classifier=Sequential()
#Step-1 Convolution
classifier.add(Convolution2D(32,3,3,input_shape=(64,64,3)... |
names = ['Janek', 'Arek', 'Adam', 'Ola', 'Kasia', 'Zenek']
name = str(input('Podaj imie ')).capitalize()
names = names + [name]
print(list(names))
for name in names:
print('Cześć', name)
a = input('Podaj nazwe: ')
for x in a.split():
print(x) |
# -*- coding: utf-8 -*-
colours = ['red', 'blue', 'yellow', 'yellow', 'green', 'black', 'white']
plurals = ['sky', 'water', 'sea', 'T-shirt']
actors = ['Angelina Jolie', 'Jeniffer Lopez', 'Pamela Anderson', 'Megan Fox']
colours.pop(0)
print('Nr indeksu:', colours.index('white'))
print('lista:', colours)
print(... |
def calc_tax(amount):
print("消費税は{0}円です".format(int(amount * 0.08)))
calc_tax(100)
def calc_price_including_tax(amount):
return int(amount * 1.08)
amount = 100
price_including_tax = calc_price_including_tax(amount)
print("100円の税込み金額は{0}円です。".format(price_including_tax)) |
# class名の頭文字は大文字
class Lang:
pass
# こういう書き方もできるらしい
java = Lang()
java.name = "Java"
java.type = "Static"
print(java.name + "は" + java.type)
python = Lang()
python.name = "Python"
python.type = "Dynamic"
python.since = 1991
print("{0}は{1}で{2}年からある".format(python.name, python.type, python.since))
# コンストラクタ
class... |
# %% [markdown]
# ### DS7337 NLP - HW 4
# #### Neil Benson
# %% [markdown]
# # Homework4
#
# <u>**HW 4:**</u>
#
# [book link](http://www.nltk.org/book/)
#
# 1. Run one of the part-of-speech (POS) taggers available in Python.
# - a. Find the longest sentence you can, longer than 10 words, that the POS tagger tags co... |
#!/usr/bin/env python3
"""
Parse all FASTA records from stdin and print id and sequence
"""
import sys
class FASTAReader(object):
def __init__(self, file):
self.last_id = None
self.file = file
self.eof = False
def __iter__(self):
return self
def __next__(self):
... |
def validate(tic, r,c):
res = False
if ((r<3 and r>-1 and c<3 and c>-1)):
if(tic[r][c] == ' '):
res=True
return res
def checkForWinner(tic, char):
result=False;
#horizontal
for line in tic:
if(line[0]==char and line[1] == char and line[2] == char):
re... |
import timeit
from datetime import datetime
start = 0
stop = 0
def get_start_time():
# Get the start time
start = timeit.default_timer()
start_time = datetime.now()
print('Execution started at {}'.format(start_time))
def get_stop_time():
# Get the stop time
stop = timeit.default_timer()
stop_time = datetime.... |
import unittest
from classes.song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self.song1 = Song("You! Me! Dancing!", "Los Campesinos!")
self.song2 = Song("Song 2", "Blur")
self.song3 = Song("Total Eclipse of the Heart", "Toni Braxton")
self.song4 = Song("Fresh Pr... |
from matplotlib import pyplot as plt
from die import Die
# 模拟投掷两个骰子
die1 = Die()
die2 = Die()
results = []
for roll_num in range(1000):
result = die1.roll() * die2.roll()
results.append(result)
# 分析结果
max_result = die1.num_sides ** 2
frequencies = []
numbers = [m * n for m in range(1, die1.num_sides + 1)
... |
def make_album(singer, singer_album_name):
album_info = {"singer": singer, "album_name": singer_album_name}
return album_info
while True:
print("\nPlease tell me your favorite singer and album:")
print("(enter 'q' at any time to exit)")
singer_name = input("Singer:")
if singer_name == "q":
... |
def show_magicians(magician_names):
for name in magician_names:
print(name.title())
magician_names = ['Eisenheim', 'Sophie', 'Inspector Uhl',
'Crown Prince Leopold', 'Young Father', 'Josef Fischer']
show_magicians(magician_names)
|
import matplotlib.pyplot as plt
plt.title("Square Numbers")
plt.xlabel("Value")
plt.ylabel("Square of Value")
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors="none")
plt.savefig("squares_plot.png", bbox_inches="tight")
|
def f(x):
return x * x
result = map(f, range(1, 10))
print(list(result))
str_list = list(map(str, range(1, 11)))
print(str_list)
|
# while True:
# prompt = '请输入观众的年龄:'
# age_str = input(prompt)
# age = int(age_str)
# if age < 3:
# print('免费')
# elif 3 <= age <= 12:
# print('10¥')
# else:
# print('15¥')
# prompt = '请输入观众的年龄:'
# message = ''
# while message != 'quit':
# message = input(prompt)
# ... |
#main module used to run the code
#importing codes from other modules
import input_
import convert
import sum_
run=True
while run:
input_.inputnum() #calling inputnum() function from input module
"""converting input num1 from input module to binary with
convert_to_binary() function from con... |
from collections import defaultdict
from pprint import pprint
from collections import deque
# Graph implementation using adjacency list,
# Used python dictionary of sets to build adjacency list
class Graph(object):
def __init__(self, connections, vertices, directed = False):
self.graph = defaultdict(set) # adjace... |
#understanding the concepts of module
# This is a global variable that stores the name of the module, if not specified,
# it is the same as the file name.
#__name__ = 'fibonacci'
def fib(n):
a, b = 0, 1
count = 0
while count < n:
print(a, end = ' ')
next = a + b
a = b
b = next
count+=1
if __name__... |
#!/usr/bin/python
# coding=utf-8
import argparse
import math
import sys
v = 'Square 2.1'
def disc(i, j, k):
d = math.pow(j, 2) - 4 * i * k
return d
def is_zero(z):
if z == 0:
return True
else:
return False
def solve(qc, lc, co):
r = []
d = disc(qc, lc, co)
if is_zero(... |
import math
import matplotlib.pyplot as plt
import numpy as np
import random
import statistics
class Road:
"""has length, type, chance of random slowing down, Tracks where cars are
Road looks like this:
| | | | | | | | | | | | | | | | | | | | | ... | <= end
0 1 2 3 4... |
# input consists on lowercase and uppercase letters
vowels = "aoyeui"
word = input()
# delete all the vowels
# insert "." before each consonant
# convert the word to lowercase
word = word.lower()
# delete all the vowels and insert "." while adding to new string
temp = ""
for char in word:
if char not in vowels:
t... |
target = int(input())
if target % 5 == 0:
print(target // 5)
else:
print(target // 5 + 1)
|
import sqlite3
import csv
import os
class SudokuDB(object):
"""Class for handling all database commands for a single sql puzzle
Args:
object (string): name of the sudoku puzzle in csv format, ie "puzzle.csv"
"""
def __init__(self, file_name="easy01.csv"):
# Static properties
s... |
#In the previous code we sent a simple text mail, here I have added the code part for adding a subject and also
#how to add the HTML code to customize your text message.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
host = "smtp.gmail.com"
port = 587
use... |
#coding=utf-8
__author__ = 'zhulixin'
# 用逗号隔开print语句的内容,打印出以空格分隔的字符串
print 'Age: ', 42
print 1,2,3
print (1,2,3)
name = 'Gumby'
salutation = 'Mr.'
greeting = 'Hello,'
print greeting, salutation,name
# import as
import math as foobar
print foobar.sqrt(4)
from math import sqrt as bar
print bar(4)
# 先令value=(1,2,3),然后令x... |
# 1.8
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
# min_price — (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price — (612.78, 'AAPL')
prices_and_names = zip(prices.values(), prices.keys())
print... |
import sys
def remove_zeros(number: str) -> int:
return int(number.rstrip('0'))
def add_zeros(number: int, original_length: int) -> str:
return str(number).ljust(original_length, '0')
def main():
number_of_lines = int(sys.stdin.readline())
for n in range(number_of_lines):
str_number = sys.stdin.readline(... |
###########################################################################
# Simple program to convert .rtf text files in the Documents directory to
# plain text format.
###########################################################################
import glob
from striprtf.striprtf import rtf_to_text
if __name__ == '_... |
import unittest
import solution
class TestWc(unittest.TestCase):
def setUp(self):
self.text = ('lqlqlq lq \n' + 'lqlq\n' + ' lq.')
with open('text_file.txt', 'w') as file:
file.write(self.text)
def test_with_chars_command(self):
self.assertEqual(solution.wc('chars', 'tex... |
import unittest
from solution import is_int_palindrome
class IsIntPalindromeTest(unittest.TestCase):
def testing_is_palindrome_one_digit_int(self):
self.assertTrue(is_int_palindrome(100001))
def testing_is_palindrome_two_digit_int(self):
self.assertFalse(is_int_palindrome(42))
def testin... |
def int_to_list(n):
result= []
while(n != 0):
result.append(n % 10)
n=n // 10
return result
def is_number_balanced(n):
l = int_to_list(n)
if len(l)==1:
return True
elif len(l)%2 !=0:
return sum(l[:len(l)//2]) == sum(l[len(l)//2 + 1 :])
else:
ret... |
# 1.3 保留最后N个元素
# 问题
# 在迭代操作或者其他操作的时候,怎样只保留最后有限的几个元素的历史记录
# 解决方案
# 保留有限历史记录正是collections.deque大显身手
from collections import deque
def search(lines,pattern,history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line,previous_lines
pass
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def fact(n):
if n==1: return 1
return n*fact(n-1)
m = float(input())
x = int(input())
prob = (m**x)*(math.exp(-m))/fact(x)
print(round(prob,3)) |
"""
Classification in Spark
The intent of this blog is to demonstrate binary
classification in pySpark. The various steps involved in
developing a classification model in pySpark are as follows:
1) Initialize a Spark session
2) Download and read the the dataset
3) Developing initial understanding about the data
4... |
import random
lst = random.sample(range(1, 100), 10)
print(lst)
def split(lst, start, end):
i = start - 1
splitter = lst[end]
for j in range(start, end):
if lst[j] >= splitter:
i = i + 1
lst[i], lst[j] = lst[j], lst[i]
lst[i+1], lst[end] = lst[end], lst[i+1]
return ... |
def multiplicar1(x, y):
print(x * y)
multiplicar1(2, 3)
def multiplicar2(*numeros):
for i in numeros:
print(i)
multiplicar2(2, 3, 4)
def multiplicar3(*numeros):
total = 1
for i in numeros:
total *= i
return total
print(multiplicar3(2, 3, 4))
def ver(**data):
print(... |
letras = ["a", "b", "c", "d", "e"]
varios = [6] * 3
numeros = list(range(20))
caracteres = list("lorem impsum")
print(len(letras))
print(letras[2])
letras[2] = "f"
print(letras[:3])
print(numeros)
print(numeros[::2])
print(numeros[::-1])
data = [1, 2, 3, 4, 5, 6]
uno, dos, *otros = data
print(otros) |
class Rectangulo:
def __init__(self, x, y):
self.x = x
self.y = y
def dibuar(self):
print(f"base {self.x}, altura {self.y}")
rectangulo = Rectangulo(2, 3)
rectangulo.dibuar()
|
# Python Snap Math Application for Stanford University's Code In Place 2021 final project
# Developer: Crislana R. Date: May 25, 2021
# A tool to help students practice and master basic math skills with the help of Snap Math App's mascot, Sam the Sea Otter
from tkinter import *
from tkinter import messagebox
from PIL... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 17:04:07 2020
Возвращает k самых частых чисел в списке
Наверное, надо придумать алгоритм. но есть же most common ^^
easy
https://leetcode.com/problems/top-k-frequent-elements/
@author: Arh
"""
from collections import Counter
class Solution:
def topKFrequent(self, ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 16:04:01 2020
Перемешивает список. опять легкая хрень :/
medium?
https://leetcode.com/problems/shuffle-an-array/
"""
from random import shuffle
class Solution:
def __init__(self, nums):
self.nums = nums
def reset(self):
return self.nums
... |
#!/bin/python
#Specify an empty list. We will append user input into this list
st = []
#check how big our range will be
num_list = int(input("How many numbers are you going to list?: "))
#Run the for loop until the number entered for num_list is reached
for n in range (num_list):
numbers = int(input... |
from sys import argv
script, filename = argv
#open file filename
txt = open(filename)
print "Here's your file %r: " % filename
# read file and display the content on screen
print txt.read()
txt.close()
print "Type the filename again:"
# request file name
file_again = raw_input("> ")
#open file
text_again = open(fi... |
"""
Various useful array utilities. Provided for use on the homework in this unit.
@author GCCIS Faculty
"""
import arrays
import random
def range_array(start, stop, step=1):
a_range = range(start, stop, step)
length = len(a_range)
an_array = arrays.Array(length, 0)
for index in range(length):
... |
def solution(n):
'''
Args:
n: number of floors
Returns:
for example if n = 4
print out like below
#
##
###
####
'''
for i in range(n):
num = i+1
print(" "*(n-num) + "#"*num) |
"""
Does it work on files where no error checking is needed on the fields
>>> sumRows("rows1.csv") == {'tim': 36.0, 'bob': 11.0, 'anna': 54.0}
True
Does it ignore headers if requested?
>>> sumRows("rows1.csv", header=True) == {'tim': 36.0, 'anna': 54.0}
True
Is it returning the right type of result?
>>> type(sumRow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.