text stringlengths 37 1.41M |
|---|
import ctypes
class Queue():
def __init__(self, capacity=1):
self._size = 0
self._queue_front = 0
if capacity <= 0:
capacity = 1
self._capacity = capacity
self._storage = self._make_array(self._capacity)
def is_empty(self):
return self._size == ... |
class Employee(object):
"""description of class"""
def __init__(self, ID = '', Name = '', Manager = None, Hourly_Rate = 0.0):
self.ID = ID
self.Name = Name
self.Manager = Manager
self.Hourly_Rate = Hourly_Rate
def GetSalary(self):
return 40 * self.Hourly_Rate
|
from Rectangle import Rectangle
class Square(Rectangle):
"""description of class"""
def __init__(self, name, number_of_sides, length):
super().__init__(name, number_of_sides, length, length)
|
from Tree import *
class BinaryTree(Tree):
def right(self, p):
#return Tree to the right of the current position
raise NotImplementedError
def left(self, p):
# return Tree to the left of the current position
raise NotImplementedError
def sibling(self, p):
# parent... |
class QueensPuzzle:
QUEEN = 'Q'
SPACE = ' '
def __init__(self, number_of_queens):
self.number_of_queens_on_board = 0
self.board = []
self.total_number_of_solutions = 0
self.total_queens = number_of_queens
for row in range(number_of_queens):
self.board.appe... |
"""
This module provides access to color schemes for
- qualitative (or categorical) data: :func:`qualitative_colors`
- sequential data: :func:`sequential_colors`
- diverging data: :func:`diverging_colors`
as explained at https://personal.sron.nl/~pault/
Color schemes are provided through three functions, all accepti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random, math
def random_up(limits) :
"""a position in upper screen"""
return (random.randint(0, limits[0]), random.randint(-limits[1]/6, 0))
def pol2cart(radius, angle) :
x = radius * math.cos(angle)
y = radius * math.sin(angle)
return x, y
cla... |
def flatten(NestedArray):
if NestedArray == []:
return NestedArray
if isinstance(NestedArray[0], list):
return flatten(NestedArray[0]) + flatten(NestedArray[1:])
return NestedArray[:1] + flatten(NestedArray[1:])
def findSpread(index, wordLength, se, sandwich):
endStart = len(san... |
'''(04) 피보나치 순열
문제 설명
인자로 0 또는 양의 정수인 x 가 주어질 때, Fibonacci 순열의 해당 값을 구하여 반환하는 함수 solution() 을 완성하세요.
Fibonacci 순열은 아래와 같이 정의됩니다.
F0 = 0
F1 = 1
Fn = Fn - 1 + Fn - 2, n >= 2
재귀함수 작성 연습을 의도한 것이므로, 재귀적 방법으로도 프로그래밍해 보고, 반복적 방법으로도 프로그래밍해 보시기 바랍니다
'''
''''#iterative
def solution(x):
if x < 2:
return x
else:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A tool to convert file between utf8 and gb18030 """
import argparse
import os
import sys
import chardet
import logging
import six
import subprocess
def check_file_encoding(file_path):
""" check file encoding """
with open(file_path, 'rb') as fd:
encode_... |
#!usr/bin/python
############### Expected behaviour of code ##################################
# The code expects three types of input
# ---- directory name .. directory name which contains all the input files converted to text.
#----- stopwords filename ... Filename containing stopwords.
#----- Output directory ........ |
from const import *
import random
from enum import Enum
random.seed(SEED)
class CurrentRule(Enum):
PIECE= 0
EMERGENCY = 1
class CurrentState(Enum):
SAFE = 0
DANGER = 1
class Task:
def __init__(self,generation_num=0):
self.generation_num = generation_num
def get_current_rule(self):
... |
"""
Project Euler's Problem 012
Barisan bilangan segitiga dibuat dengan menjumlahkan bilangan asli. Maka bilangan segitiga ke-7
adalah 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Sepuluh bilangan segitiga pertama adalah:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Jika kita membuat daftar faktor dari tujuh bilangan segit... |
# Hello World program in Python
#http://www.tutorialspoint.com/python/python_date_time.htm
import time
import calendar
import support
import Phone
print "Hello World!\n"
dict = {}
dict['one'] = "valor de clave1"
dict[2] = "valor de clave2"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dic... |
def check_non_negative(index):
def validator(f):
def wrap(*args):
if args[index] < 0:
raise ValueError(
'Argument {} must be non-negative.'.format(index))
return f(*args)
return wrap
return validator
# the below example decorator is a... |
# You have two numbers represented by a linked list, where each node contains a single digit
# The digits are stored in reverse order, such that the 1's digit is at the head of the list
# write a function that adds the two numbers and returns the sum as a linked list
# FOLLOW UPS
# Suppose the digits are stored in forw... |
# Implement an algorithm to determine if a string has all unique characters.
# What if you can't use additional data structure
def isUnique(string):
for index, char in enumerate(string):
for j in xrange(index + 1, len(string)):
if char == string[j]:
return True
return False... |
# assume you have a method isSubstring which checks if one word is a
# substring of another. Given two string, s1 and s2, write code to check if s2
# is a rotation of s1 using only one call to isSubstring (e.g. waterbottle is a rotation of erbottlewat)
waterbottle + waterbottle = waterbottlewaterbottle
then check if... |
import csv
with open("words.csv", "r") as fp:
csvreader = csv.reader(fp.readlines())
masterlist = []
for row in csvreader:
for item in row:
masterlist.append(item)
#print(masterlist)
COLS = 3
REMAINDER = len(masterlist) % COLS
REGULAR_ROWS = int(len(masterlist) / COLS)
print("Words:", len(masterlist))
pri... |
# For python files relating to index (/) page.
import csv
# Opens and appends to code_list the list of healthboards and their relevant code
with open('app/static/codes_healthboard.csv') as codes:
readCSV = csv.reader(codes, delimiter=',')
code_list = []
for row in readCSV:
hbc = {"code": row[0], "... |
# verifica sequencialmente quantos números impares existem, por exemplo os cinco primeiros números ímpares
n=int(input("Digite uma quantidade numeros impares desejados: "))
i=0 # inicializando somador
while n>=1: # enquanto a quantidade de números for maior ou igual a 1
i=i+1 #soma 1 para verificar se é impar
i... |
ano=int(input("Digite o ano a ser verificado se é bissexto:"))
if ano%4==0 or ano%400==0 and ano%100!=0:
print("O ano é bissexto")
else:
print("O ano não é biseexto") |
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
#Sem Recursão
while n2 != 0:
n1, n2 = n2, n1 % n2
#Python <3
print ("Sem Recursão - MDC =", n1)
#Com Recursão
def mdc(x, y):
if y == 0:
return x
else:
return mdc(y, x % y)
print ("Com Recursão - MDC =", mdc(n1, n2)) |
#main
#number game
#guessing_number_game_functions
#number game
import random
# 4536 total possibilites
possibilities = []
for a in range (1,10):
for b in range (0,10):
for c in range (0,10):
for d in range (0,10):
if a != b and a!=c and a!=d and b != c and b!=d and c != d:... |
#!/usr/bin/python
from read_grid_parameters import width, height
for x in xrange(width):
for y in xrange(height):
if x != width-1:
print("(%i,%i) X (%i,%i) X" % (x,y,(x+1)%width,y))
if y != height-1:
print("(%i,%i) Z (%i,%i) Z" % (x,y,x,(y+1)%height))
if x != width-... |
import turtle
import time
import random
import pygame
pygame.init()
speed = 9
#score
score = 0
high_score = 0
score_rate = 1
#set up the screen
window=turtle.Screen()
window.title("小精靈")
window.bgcolor("#000000")
window.setup(width=600,height=600)
window.tracer(0)#turn off the screen updates
#sn... |
#!/usr/bin/env python
import collections
import fileinput
from math import sqrt
import sys
def dist(a, b):
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
def process(line):
(name, classs, mag, x, y, z) = line.split()
return name, float(x), float(y), float(z)
def journey(l... |
#!/usr/bin/env python
#CodeWars 2016
#
#Input
#The first line of input indicates the number of word triplets the program must read. Each line after contains three words, and we use that term loosely, separated by one or more spaces. Don't assume there will only be one space between words.
#3
#TEST MEANT TIME
#KINDERGA... |
#!/usr/bin/env python
#CodeWars 2016
#
#Input
#The first line of input indicates the number of word triplets the program must read. Each line after contains three words, and we use that term loosely, separated by one or more spaces. Don't assume there will only be one space between words.
#3
#TEST MEANT TIME
#KINDERGA... |
#!/usr/bin/env python
#CodeWars 2014
#
#Clock Power
#
# The clock uses four seven-segment LEDs to display the hours and
# the minutes. Lighting a single segment of an LED requires 15 milliamps.
# There is also a divider between the hours and the minutes.
# Lighting the divider requires 20 milliamps.
# The first L... |
import sys
from fractions import Fraction
def word_hash(text):
return sum(ord(x)-ord('a')+1 for x in text)
def main():
cases = int(sys.stdin.readline().rstrip())
for caseNum in range(cases):
names = sys.stdin.readline().rstrip().split()
dates = list(map(int,sys.stdin.rea... |
#!/usr/bin/env python
#CodeWars 2014
#
#Pangram
# A sentence that uses every letter of the alphabet is called a pangram.
# A "perfect" pangram only uses each letter once.
# Write a program to determine if a sentence is a pangram or a perfect pangram.
# Input
#
# Each line of input is a sentence that ends with a pe... |
import re
from collections import defaultdict
diph = ["aI", "aU", "OY"]
vowels = ["a", "A", "a~", "e", "E", "I", "i", "O", "o", "U", "u", "Y", "y", "9", "2", "@" , "6", "a:", "a~:", "e:", "E:", "i:", "o:", "u:", "y:", "2:"]
consonants = ["z", "S", "Z", "C", "x", "N", "b", "d", "f", "g", "h", "j", "k", "l", "m", "n", "... |
import re
short_vowels = ["a", "e", "E", "I", "i", "O", "o", "U", "u", "Y", "y", "9", "2"]
# Sets the context of search at file level and finds the right word number
# Returns the type of stress that falls on the given vowel of the given file of the given word
# none (unstressed), s_stress (secondary), p_stress (pri... |
import collections
def BFS(s, adj):
visited=[]
queue=[]
visited.append(s)
queue.append(s)
while queue:
s=queue.pop(0)
print(s, end=" ")
for v in adj[s]:
if v not in visited:
visited.append(v)
queue.append(v)
pri... |
import random
import sys
width = int(sys.argv[1])
height = int(sys.argv[2])
bomb = int(sys.argv[3])
board = []
board = [[0]*(width) for x in range(height)]
for x in range(bomb):
try:
h = random.randint(0, height-1)
l = random.randint(0, width-1)
board[h][l] = "*"
if l!=0:
if h!=0:
board[h-1][l-1] += ... |
"""
Mitchell Yu
9/24/2018
Text-Game - Black Jack
I tried to create a very stripped down version of Black Jack. I didn't include any sort of spliting or anything fancy, just the basic rules. You may see a few places where I violated the DRY coding policy, but I decided that it was more important for the game to be compl... |
number = int(input("Input number of discs"))
def moves(n, left):
if n == 0:
return
moves(n-1, not left)
if left:
print(str(n)+'left')
else:
print(str(n)+'right')
moves(n-1, not left)
moves(number, True)
"""
The number next to each move is directly related to the size. All of the even numbered discs move on... |
"""
Random Atom Factory
===================
"""
import random
import itertools as it
from .atom_factory import AtomFactory
__all__ = ('RandomAtomFactory', )
class RandomAtomFactory(AtomFactory):
"""
Creates a random collection of atoms.
Parameters
----------
atoms : :class:`tuple` of :class:`... |
numtest = int(input())
s = []
for _ in range(numtest):
s.append(input())
for userstring in s:
# normal string
# get length
length = len(userstring)
even = []
odd = []
for n in range(length):
if n % 2 == 0: #even
even.append(userstring[n])
else: # odd
... |
import redis
class Datastore(object):
'''Abstract wrapper for a key-value store.'''
def __init__(self):
'''Constructor.'''
self._conn = redis.Redis()
self._prefix = u''
def _key(self, key):
'''Returns 'key' with the prefix prepended, if any.'''
if self._prefix == '':
return key
re... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from var_dump import var_dump
# 匿名函数 map会根据提供的函数对指定序列做映射
# 匿名函数不用return值,返回值就是表达式的结果,另外匿名函数没有名称,无需担心名称冲突
L = list(map(lambda x: x * x, range(1, 10)))
print(L)
# 以上匿名函数lambda x: x * x
def f(x):
return x * x
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from var_dump import var_dump
# 列表生成式,python内置的创建list的生成式
nums = list(range(1, 11))
print(nums)
# 生成1-10的平方值
L = []
for x in range(1, 11):
L.append(x * x)
print(L)
# 也可以直接调用循环值,还可以跟上筛选条件
LL = [x * x for x in range(1, 11) if x % 2 == 0]
print(LL)
# 还可以组成全排... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from var_dump import var_dump
# 排序算法 内置sorted()函数
L = [36, 24, 48, 78, 2, 90, 8]
print(sorted(L))
# sorted()也是高阶函数,允许接收一个key函数来实现自定义排序
L1 = [-1, 5, 25, -87, -56, 34]
# noinspection PyTypeChecker
print(sorted(L1), sorted(L1, key=abs))
# 反向排序时,可以传入第三个参数,reverse=True
prin... |
import matplotlib.pyplot as plt
# draw a simple line chart showing population growth over the last 115 years
years =[1900, 1960, 1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015]
pops = [1.6, 2.5, 2.6, 3.0, 3.3, 3.6, 4.2, 4.4, 4.8, 5.3, 5.7, 6.1, 6.5, 6.9, 7.3]
# ploy our chat with data a... |
def ArmN(x): #define function
sum=0
t=x
while (t>0): #starts while loop
d=t%10 #extracts last digit
sum+=d**3 #cube of extracted digit
t=t//10 #gives quotent of the input
if sum==x: ... |
import os
import sqlite3
dir_path = os.path.dirname(os.path.realpath(__file__))
db_path = dir_path + '/database.db'
def get_lecturer_by_id(username):
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT * FROM Lecturer WHERE username = ?;", [username])
lecturer = {}
for row in c:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 30 00:13:07 2019
@author: k3sekido
"""
n=input()
slst=map(int, input.split())
r=0
f=True
for odd in slst:
if (odd % 2<>0):
f=False
|
"""
Determine if a string is a permutation of another.
"""
def is_permutation(str1, str2):
"""
Runtime: O(n).
"""
chars1 = _string_chars_freq(str1)
chars2 = _string_chars_freq(str2)
for key, val in chars1.items():
if not key in chars2:
return False
if chars2[key] !=... |
"""
Determine if a string has all unique characters.
"""
def is_unique(val):
"""
With additional data structures.
"""
chars = {}
for char in val:
if char in chars and chars[char]:
return False
chars[char] = True
return True
def is_unique_no_data_structs(val):
"... |
import timeit
def timer(function):
def new_function():
start_time = timeit.default_timer()
function()
elapsed = timeit.default_timer() - start_time
print(f'"{function.__name__}" took {elapsed} seconds')
return new_function
MOD = 10**9 + 7
""" mod combを用いるとテストケースで失敗する!! """
def mod_cmb(n, a, mod... |
X=int(input())
def sieve():
n = 10**6
is_prime = [True for _ in range(n+1)]
is_prime[0] = False
for i in range(2, n+1):
if is_prime[i-1]:
j = 2 * i
while j <= n:
is_prime[j-1] = False
j += i # iの倍数は自動的に素数ではないから
for i in range(1, n+1)... |
S=input()
R={'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
x = [R[c] for c in reversed(S)]
print(''.join(x))
|
import math
P = float(input())
def f(x):
return x + P*(2**(-x/1.5))
def is_ok(x):
# x + P*(2**(-x/1.5)) を微分すると
# 1 + P * 2**(-x/1.5) * log 2 * (-1/1.5)
if 1 + P * 2**(-x/1.5) * math.log(2) * (-1/1.5) > 0:
return True
return False
def meguru_bisect(ng, ok):
while (abs(ok - ng) > 0... |
b_size = {}
for b in range(1, int(input())+1):
if b%2 == 0:
continue
size = len([by for by in range(1, b+1) if b%by == 0 and by%2 == 1])
if size == 8:
b_size[b] = size
print(len(b_size))
|
# define class in python
class Vehicle:
# define constructor (__init__)
# always executed when the class is being initiated
def __init__(self, type, plates, year):
# create public property
self.type = type
self.year = year
# create private property
# (added a double underscore at the beginni... |
# Program to calculate grade on basis of the Percentage
percentage = float(input("Enter your percentage: "))
if(percentage >= 90.0):
print("Your grade is A")
elif(percentage >= 80.0 & percentage < 90.0):
print("Your grade is B")
elif(percentage >= 70.0 & percentage < 80.0):
print("Your grade is C")
e... |
"""Convert string of input into pig latin.
best practice by: dykchui, alpharam, pomps, enfrightened, Wild_Pointer
def pig_it(text):
lst = text.split()
return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha()
else word for word in lst])
"""
def pig_it(text):
"""Convert string to pig latin."""
... |
# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
# Return the array in the form [x1,y1,x2,y2,...,xn,yn].
# Example 1:
# Input: nums = [2,5,1,3,4,7], n = 3
# Output: [2,3,5,4,1,7]
# Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
# Runti... |
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
def average(num1, num2, num3):
return (num1 + num2 + num3) / 3
print("The average is: ")
average(num1, num2, num3)
|
print("Este programa pide dos numeros y evalua cual es mayor")
num1 = int(input("Ingresa el primer numero a evaluar: "))
num2 = int(input("Ingresa el segundo numero a evaluar: "))
def DevuelveMax(num1, num2):
if num1 < num2:
print(num2)
elif num2 < num1:
print(num1)
else:
print(... |
#!/usr/bin/env python3
from random import choice
import argparse
# colors for strings
def bold(bold): return f"\033[1;0m{bold}\033[0m"
def red(red): return f"\033[1;31m{red}\033[0m"
def green(green): return f"\033[1;32m{green}\033[0m"
# Main function for replace some normal characters with special characters
def nor... |
import matplotlib.pyplot as plt
from compound import compound_yearly_value_with_interest
# future value
# interest
present_value = 1000
rate = 0.1
time = 30
# x-values - time
xTime = list(range(0, time+1))
result = compound_yearly_value_with_interest(present_value, rate, time)
unzipped = list(zip(*result))
# y-va... |
file = open("users.txt", "r")
def login(inusername, inpassword):
for line in file:
if line.split(' ')[0] == inusername:
if line.split(' ')[1] == inpassword:
return True
else:
print("Incorrect Password")
return False
else:
... |
# This program accepts a chess piece and the square it sits on
# and returns all possible squares that piece could move to
# assuming that there are no other pieces on the chess board
#
# It accepts 2 parameters:
# -p PIECE
# where PIECE is a 2 letter sequence
# The first letter signifies the piece's color, ... |
import sys
script, input_encoding, error = sys.argv
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
print(next_lang, " : ", raw_bytes, "<===>", cooked_string)
def main(l... |
"""
Exploratory Data Analysis Plot for Bank Note dataset - 2
Produces a plot for all the features
Prints description of the dataset to the console
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("Datasets\\BankNote.txt",header=None)
print(data.describe())
print("Labe... |
# encoding: utf-8
import inspect # 判断是否是某类对象 如:inspect.isfunction(fun1)
class Dog(object):
c = 2
def __init__(self, age):
print('__init__ 自动输出')
self.age = age
# 重写__getattribute__。需要注意的是重写的方法中不能
# 使用对象的点运算符访问属性,否则使用点运算符访问属性时,
# 会再次调用__getattribute__。这样就会陷入无限递归。
# 可以使用super()方... |
def main():
#This is a List of song names to be selected at random. They are in script form because this is just a placeholder.
sadSongs = ["Tahalamot - Tinariwen ", "Toumast anlet - Tamikrest ", "Nanuflay - Tinariwen "]
madSongs = [ "Karambani - Terakraft ", "Kamelemba - Oumou Sangare ", "Tahigren - Bombino "]
... |
class Solution:
def __init__(self):
self.row=0
self.col=0
def check(self, board, i,j,word):
if len(word)==0:
return True
if i<0 or i==self.row or j<0 or j==self.col or board[i][j]!=word[0]:
return False
res=False
board[i][j]="#"
for... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def helper(self, root):
if root:
if root.left is None and... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @param B : root node of tree
# @return the root node in the tree
def solve(self, A, B):
... |
# Python XML DOM Tree
# xml.dom.minidom Minimal DOM implementation.
# xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages.
# It is intended to be simpler than the full DOM and also significantly smaller. Users who are not already profici... |
#!/usr/bin/python3
"""
对象的域(实例变量)代表了对象的状态,修改变量,就修改了实例的状态。当把
一个对象作为参数传给其他函数时,其他函数可能会错误的修改实例变量,需要控
制访问(封装)--数据隐藏
以双下划线"__" 开头的变量是私有变量,类外部不能直接访问
以下划线“_" 开头的变量是保护变量,子类可以访问,但是非子类的类外部不能直接访问
以双下划线开头和结尾的变量是系统变量
"""
class People:
def __init__(self, n="", g="x"):
self.__name = n
self.__gender = g
d... |
def reverse(num):
reverse = 0
remainder = 0
while num > 0:
remainder = num % 10
reverse = reverse * 10 + remainder
num = num // 10
return reverse
if __name__ == '__main__':
print(reverse(5634))
|
Lol = input('Введите текст: ').split(' ')
print(' '.join([n.upper() if n == n.title() else n for n in Lol])) |
'''
Vantage point trees are data structures that, among other things, make it easy to
search for strings that are similar to a given input string.
For this example, we'll index dozens of different spellings of Pacific Gas & Electric
Co., a large and politically active utility based in California, as they were reported... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import sys
def main():
# 『人間失格』のテキストデータを取得
with open("ningen.txt", "r") as f:
text = f.read()
# 単語を分かち書き
wordlist = wakati(text)
print(wordlist)
# 『人間失格』バイグラムを作成
bigram = make_bigram(wordlist)
txt = ""
... |
from project import Solution
class Day(Solution):
def __init__(self, day, year):
super().__init__(day, year)
self.input = [int(x) for x in self.puzzle_input.split('\n')]
def part_1(self):
return sum([self.fuel_requirement(m) for m in self.input])
def part_2(self):
return ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# a= pd.Series([4, 7, -5, 3])
#
# print(a)
#
# print(list(a))
#
# print(a[[0,1,2]])
#
# print(7 in a.values)
# sdata = {'Texas': 10, 'Ohio': 20, 'Oregon': 15, 'Utah': 18} # Dictionary
# states = ['Texas', 'Ohio', 'Oregon', 'Iowa']
# obj4 = pd.Series... |
import time
''' Bubble sort base template taken from https://github.com/vptuan/COMP1819ADS/tree/main/Lab_05'''
data = {}
indivset = []
def WriteSorted2FIle():
file = input("input file name")
with open((file + "_Sorted" + ".txt"), 'w') as f:
for i in indivset:
f.write("%s\n" %... |
# A palindromic number reads the same
# both ways. The largest palindrome made
# from the product of two 2-digit numbers
# is 9009 = 91 × 99.
# Find the largest palindrome made from
# the product of two 3-digit numbers.
def isPalin(x) :
s = str(x)
count = 0
while count < int(len(s) / 2) :
if s[coun... |
A = int(input(">"))
B = int(input(">"))
C = float(input(">"))
print("NUMBER =", A)
print("SALARY = %.2f"% (B*C))
|
Valor = float(input(">"))
L1 = [100, 50, 20, 10, 5, 2]
L2 = [1, 0.50, 0.25, 0.10, 0.05, 0.01]
print("NOTAS:")
for nota in L1:
qtd = int(Valor // nota)
print("{} nota(s) de R$ {}.00".format(qtd, nota))
Valor -= qtd * nota
print("MOEDAS:")
for moeda in L2:
qtd = int(Valor // moeda)
print("{} moeda... |
import math
from decimal import Decimal, getcontext
from typing import Iterable
class Vector:
"""class Vector(iterable).
Iterable must be a sequence, a container that supports iteration or an iterator object.
The Vector class uses decimal floating point arithmetic, provided by Python's
module 'decima... |
str = "nama saya Stefany Caesarya Permatasari"
#fungsi capitalize
a = str.capitalize()
print(a)
#fungsi center
a = str.center(50,"=")
print(a)
#fungsi count
print(str.count("a"))
#fungsi len
print(len(str))
#fungsi replace
print(str.replace("saya", "aku"))
#fungsi upper dan lower
print(str.upper())
print(str.lowe... |
class CoffeeMachine:
state = 'choosing an action' # default state
def user_input(self, choice):
if self.state == 'choosing an action':
if choice == 'buy':
self.state = 'buying a coffee'
self.user_input(choice=input('\nWhat do you want to buy? 1 - espresso, 2... |
# Exemplo basico socket (lado passivo)
import socket
from collections import Counter
HOST = '' # '' possibilita acessar qualquer endereco alcancavel da maquina local
PORTA = 5000 # porta onde chegarao as mensagens para essa aplicacao
# cria um socket para comunicacao
sock = socket.socket() # valores default: soc... |
# Rúbrica:
# Petición y validación de variables (5 ptos)
# Ingreso de frase y llave. (1 pto)
frase = input("Ingrese mensaje a encriptar: ")
# Minúsculas y cadena limpia a los lados.
# Puede ser mayúscula, pero letras del alfabeto deben ser también mayúsculas
frase = frase.lower().strip() # (1 pto)
# Validar ... |
''''You can walk a directory tree and add files to compressed ZIP archives in
several other programs. For example, you can write programs that do the
following:
Walk a directory tree and archive just files with certain extensions, such
as .txt or .py, and nothing else
Walk a directory tree and archive every file except... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow
# In[2]:
#這是單行註解
'''
這是多行註解
'''
a=3
b=8
print(a+b)
# In[3]:
a=3
b=8
a,b=b,a
print(a)
print(b)
# In[1]:
x,y,z=3,4,5
print(x)
print(y)
print(z)
# In[3]:
x,y,z=3,4,5
x += 1
y *= 2
z **= 3
print(x,y,z)
# In[4]:
#變數的應用
#Q:邊長為3,4,5的三角形,其面... |
#!/usr/bin/env python
# coding: utf-8
# # numpy套件
# In[1]:
a_list=[1,2,3,4,5]
print(a_list*3)
# In[3]:
#numpy套件ndrray型態,提供element-wise的操作
import numpy as np
a_ndarray=np.array([1,2,3,4,5])
print(a_ndarray*3)
# In[4]:
print(type(a_ndarray))
print(a_ndarray.ndim) #ndarray的維度
print(a_ndarray.shape) #ndarray的sh... |
def mysplit(string):
if not ' ' in string:
return []
lst = []
curstring = string.strip()
while ' ' in curstring and len(curstring):
lst.append(curstring[:curstring.index(' ')])
curstring = curstring[curstring.index(' ') +1:]
if ' ' not in curstring and len(curstring) != 0:
... |
n = int(input("Ingrese un número para comenzar: \n"))
print()
for i in range(0, n+1, 2):
print(i) |
import random
def print_line():
print("\n")
def introduction():
name = "Johanna Sjöstrand "
date = "27/4/2020"
print (name + date)
print_line()
def choose_amount_of_die():
#Will ask user for input on amount of die, if text or wrong amount the loop will continue until answer is within the v... |
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Hide Company Tags LinkedIn Google Uber Airbnb Facebook Twitter Amazon Microsoft
Hide Tags Divide and Conquer Linked List Heap
Hide Similar Problems (E) Merge Two Sorted Lists (M) Ugly Number II
'''
# Definition for s... |
'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
... |
'''
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?... |
'''
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of tim... |
#!/usr/bin/python
'''
Count inversion
Given 2 lists, have same element in different orders:
1 2 3 4 5 6
l1: a b d e c f
l2: b a c f d e
Goal:
Count pairs of items that in different orders in two lists
Hint:
Only need one list for index:
For this example, your input should look like:
2 1 5 6 3 4
'''
count = 0
def mer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.