text stringlengths 37 1.41M |
|---|
# Read Method
# with open("data_memory.txt") as file:
# contents = file.read()
# print(contents)
# Write Method with write mode:
# with open("data_memory.txt",mode="w") as file:
#file.write("New text")
# Write Method with adding written mode:
# with open("data_memory.txt",mode="a") as file:
#file.writ... |
# Example 5-6. Sum of integers up to 99 performed with reduce and sum
from functools import reduce
from operator import add
s = reduce(add, range(100))
print(s)
print(sum(range(100)))
|
# By default int constructor return "0".
print(int())
# We can express integer value in binary, octal, hexadecimal format.
print(0b1011, 0o52, 0x7f)
# converts floating point to int.
print(int(1.34))
# valid string produces integral value that string represent, base 10.
valid_string = '121'
print(int(valid_string))
... |
# Example 8-5. t1 and t2 initially compare equal, but changing a mutable item inside tuple
# t1 makes it different
t1 = (1, 2, [30, 40])
t2 = (1, 2, [30, 40])
print(t1 == t2)
print(t1 is t2)
print("id of t1[-1] : ", id(t1[-1]))
print("id of t2[-1] : ", id(t2[-1]))
t1[-1].append(99)
print("after modification id of t... |
# Example 8-2. Variables are assigned to objects only after the objects are created
class Gizmo:
def __init__(self):
print('Gizmo id : %d', id(self))
x = Gizmo()
try:
y = Gizmo() * 10
except TypeError as e:
print(e)
|
# Example 8-3. charles and lewis refer to the same object
charles = {'name': 'Charles L. Dodgson', 'born': 1832}
lewis = charles
print(lewis is charles)
print("charles id : ", id(charles), " ", "lewis id : ", id(lewis) ) |
# Banking Account Inheritance
class Account:
def __init__(self, title=None, balance=None):
self.title = title
self.balance = balance
def getBalance(self):
return self.balance
def deposite(self, amount):
self.balance += amount
def withdrawl(self, amount):
self... |
# Example 5-2. Use function through a different name, and pass function as argument
def factorial(n):
""" returns n!"""
return 1 if n < 2 else n * factorial(n - 1)
fact = factorial
print(type(fact))
m = map(fact, range(10))
print(m)
print(list(m))
|
# Example 5-25. Demo of methodcaller: second test shows the binding of extra arguments
from operator import methodcaller
s = 'The time has come'
upcase = methodcaller('upper')
print(upcase(s))
hiphenate = methodcaller('replace', ' ', '-')
print(hiphenate(s)) |
# By default it returns "False"
bool_return_value = bool()
print(bool_return_value)
# returns "True"
bool_return_value = bool(True)
print(bool_return_value)
# Numbers evaluate to "False" if zero, and "True" if nonzero.
zero = 0
print(bool(zero))
non_zero = 5
print(bool(non_zero))
# Sequences and other container ty... |
x = 10
a = lambda y: x + y
x = 20
b = lambda y: x + y
# the value of x used in the lambda expression is a free variable that gets bound at runtime, not definition time.
print(a(10), b(10))
# include the value as a default value, If you want an anonymous function to capture a value at the point of definition
x = 10
c ... |
r = range(0, 101, 2)
print(type(r)) # returns range class
print(r[10]) # supports indexing
print(len(r)) # returns length
class Range:
def __init__(self, start, stop=None, step=1):
if step == 0:
raise ValueError("step size cant be 0")
if stop is None:
start, stop = 0, s... |
# Basic container types, such as list, tuple, and set, qualify as iterable types.
from collections.abc import Iterable
data = [1, 2, 3, 4]
iterable_object = iter(data)
print(type(iterable_object), iterable_object)
for i in iterable_object:
print(i)
iterable_object2 = iter(data)
try:
print(next(iterable_obje... |
# first-class objects are instances of a type that can be assigned to an identifier, passed as a parameter,
# or returned by a function.
scream = print # assign name ’scream’ to the function denoted as ’print’
scream("hello world") # call that function
from math import pi, sqrt
print(vars())
# pseudo random numbe... |
from abc import ABC, abstractmethod
class Shape(ABC):
pass
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return (self.length * self.le... |
class MaxHeap:
def __init__(self, *args):
self.heap = []
self.heap_size = 0
for i in args:
self.heap.append(i)
self.heap_size += 1
self.sift_up(self.heap_size - 1)
def sift_down(self, i):
while 2 * i + 1 < self.heap_size:
left = 2... |
english= "hello world"
italian = "ciao mondo"
esperanto = "saluton mondo"
response1 = input("choose a language")
print("the translation to hello world in " + response1 + " is ")
#word english
if (response1 == "english") :
print(english)
else print("restart the program please")
my_name = input("what's your nam... |
import matplotlib.pyplot as plt
import matplotlib_venn as v
a=v.venn2(subsets=[set([1,2]),set([2,3,4,5])],set_labels=('A','B'))
plt.title("Venn diagram")
plt.show()
a=v.venn3(subsets=(1,1,0,1,0,0,0),set_labels=('A','B','C'))
a.get_label_by_id('100').set_text('First')
#부분집합
v.venn2(subsets=[set([2,3]),set([2,3,4,5])]... |
#Loop that runs forever until
# a positive integer is entered#
n = float(input("Please enter a postiive number"))
if n <= 0:
while n <= 0:
print("Please try again")
n = float(input("Please enter a positive number"))
else:
print(f"Yay! {n} is Positive Number") |
# Fib Series using recurssion
fib_series = []
# Prints the nth term
def fib(x):
"""assumes x an int >= 0
returns Fibonacci of x"""
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
# Calls the function
x = int(input("Please enter a number \n"))
fib(x)
# Prints a... |
# The formal parameter needs to initialize before calling a function)
# A funtion can also be without any parameter
def g():
n = int(input("Please enter a number \n"))
t= n*"$"
s = "$" + " "*(n-2) + "$ \n"
r= s*(n-2)
print(f"{t}\n{r}{t}")
z = g()
def f():
'''n = no. of rows of stars y... |
'''Retrieve and Print words form A URL
Usage:
Python withs.py <URL>
'''
from urllib.request import urlopen
import sys
def fetch_words(url):
'''Fetch a list of words form URL
Args:
url: The Url of UTF-8 text document
Returns:
A list of list containing words in a
line of the document
'''
with urlopen(ur... |
import os
import unittest
def analyze_text(filename):
with open(filename, 'r') as f:
return sum_tuple((1, len(line)) for line in f)
def sum_tuple(iter):
sumx = (0, 0)
for x in iter:
sumx = x[0] + sumx[0], sumx[1] + x[1]
return sumx
class TextAnalysisTests(unittest.TestCase):
""""T... |
# this example makes use of fermat's theorem, thus it's much harder to detect the deadcode
# fermat's theorem states that there are no three positive integers a, b, c such that a^n + b^n = c^n for n > 2
# this was only proven in 1994
def f(a, b, c):
if a > 0 and b > 0 and c > 0:
if a*a*a + b*b*b == c*c*c:... |
# Brandon Roberts
# Space trivia
print ("Welcome to the epitome of space trivia!")
name = input("Enter your name: ")
print ("Hello", name, "I hope you are ready to begin!")
print ("The following is a series of questions to help you determine just how much you may know about space.")
print (2-2)
print ("Hello")
### Fig... |
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
def fun1(a):
for i in range(len(a)):
a[i]*=a[i]
print(a)
a=[1,2,3]
fun1(a)
print(a)
|
#!/usr/bin/python3
#-*-coding:UTF-8-*-
greeting='hello'
if greeting=='hello':
student={'小萌':'1001','小智':'1002','小强':'1005','小张':'1006'}
print('字典元素个数为: %d个'%len(student))
student.clear()
print('字典删除后元素个数为:%d个'%len(student))
|
import math
import random
# 15
# 5 10
# 20
class Heap:
def __init__(self):
self.storage = []
self.size = 0
def insert(self, value):
self.storage.append(value)
self.size += 1
# if only single element return
# ! single element is a heap
... |
# __str__()
# 如果类定义了__str__方法,就会打印从这个方法中的return数据,没有定义这个方法,打印这个对象的内存地址.
class Animal():
def __init__(self,sleeptime):
self.sleeptime = sleeptime
def __str__(self):
return '返回动物睡眠时间'
cat = Animal('10小时')
print(cat) #返回动物睡眠时间 |
# 上下文管理器
# 一个类只要实现了__enter__()和__exit__()这两个方法,通过该类创建的对象我们就称之为上下文管理器
# with语句是由上下文管理器支撑,也就是说使用open函数创建的文件对象就是一个上下文管理器对象
# 示例代码
# 自定义上下文管理器类
class File(object):
def __init__(self, fileName, fileMode):
self.fileName = fileName
self.fileMode = fileMode
# 上文方法,负责返回操作对象资源,比如文件对象、数据库连接对象
... |
# 烤地瓜
# 需求主线:
# 1. 被烤时间对应地瓜状态
# 0-3分钟 生的
# 3-5分钟 半生不熟
# 5-8分钟 熟的
# 超过8分钟 糊了
# 2. 添加调料
# 用户按照自己的意愿添加调料
# 步骤分析
# 需求涉及一个事物:地瓜,故案例涉及一个类:地瓜类
# 地瓜的属性
# 被烤的时间
# 地瓜的状态
# 添加的调料
# 地瓜的方法
# 被烤
# 用户根据意愿设定每次烤地瓜的时间
# 判断地瓜被烤总时间在哪个区间,修改地瓜状态
#... |
# 自定义异常
# 在python中,抛出自定义异常的语法为raise异常类对象
# 需求:密码长度不够,则报异常(用户输入密码,如果输入长度不足6位,则报错,即抛出自定义异常,并捕获该异常)
# 自定义异常类,继承Exception
class ShortPswError(Exception):
def __init__(self,length,minlen):
# 用户输入的密码长度
self.length = length
# 系统要求最低密码长度
self.minlen = minlen
# 设置抛出异常描述信息
def __st... |
# 私有权限
# 获取修改私有属性值
# 在python中,一般在类里面定义函数名getXX来获取私有属性,定义setXX用来修改私有属性值
# 1. 师傅类
class Master(object):
def __init__(self):
self.kongfu = '[古法煎饼果子]'
def makeCake(self):
print(f'使用{self.kongfu}制作煎饼果子')
# 2. 学校类
class School(object):
def __init__(self):
self.kongfu = '[黑马古法煎饼果子]'
... |
# 多继承
# 一个类同时继承了多个父类
# 当一个类有多个父类的时候,默认使用第一个父类的同名属性和方法
# 1. 师傅类
class Master(object):
def __init__(self):
self.kongfu = '[古法煎饼果子]'
def makeCake(self):
print(f'使用{self.kongfu}制作煎饼果子')
# 2. 学校类
class School(object):
def __init__(self):
self.kongfu = ['黑马古法煎饼果子']
def selfinfo(sel... |
# 斐波拉契数列的生成
# num 表示生成斐波那契数列个数
def fibonacci(num):
# 初始化前两值
a = 0
b = 1
# 记录每次生成个数的索引
curindex = 0
# 循环判断条件是否成立
while curindex < num:
rlt = a
# 条件成立交换连个变量的值
a, b = b, a+b
curindex += 1
yield rlt
# 创建生成器
f = fibonacci(5)
for i in f:
print(i)
|
import numpy as np
class MyClass:
"""A simple example class"""
i = 12345
def __init__(self,name=''):
self.name = name
def f(self):
if self.name == '':
return 'hello world'
else:
print('hello ', self.name)
x= MyClass()
|
#!/usr/bin/env python3
"""
BFV2 Theme 05 - Genomics - Sequencing Project
Simple template for parsing BED data.
Deliverable 1
-------------
Make changes to the 'parse_bed_data' function, following the instructions
preceded with double '##' symbols.
usage:
python3 deliverable1.py
"""
# METADATA VARIABLES... |
from collections import defaultdict
strings = ['сон', 'нос', 'сорт', 'трос', 'торт', 'рост']
def group_anagrams(strings):
m = defaultdict(list)
for s in strings:
m[tuple(sorted(s))].append(s)
return list(m.values())
print(group_anagrams(strings)) |
def trouverNb():
import random
continuer=True
while continuer==True:
nbBase = random.randint(1,1000)
print(nbBase)
n=int(input("Le nombre que vous devez trouver est entre 1 et 1000. "))
gagne=False
while gagne==False:
if n!=nbBase:
... |
import os
#ex1
def double(n):
res=n*2
return res
print(res)
n=int(input("entrer entier : "))
print("le double de ",n, "est ",double(n)) #appel de la fonction
#ex4
def max3(x1,x2,x3):
if x1>=x2 and x1>=x3:
return x1
elif x2>=x3 and x2>=x3:
return x2
else:
... |
n=1
continuer = True
while continuer == True:
######################################################################################################################################################################
pieces_accepte = [10, 5, 2, 1, 0.5]
tarif_heure = 2
hA = float(input("ticket n°... |
class Employee:
def __init__(self, id, name, phone, age):
self.id = id
self.name = name
self.phone = phone
self.age = age
def dict_employee(self):
# Turning the employee instance into a dictionary
employee = {
'id': self.id,
'name': self.... |
def print_number(my_number):
print(my_number)
print_number(55)
print_number(25)
print_number(8)
def add_numbers(a, b):
print(a + b)
add_numbers(11, 7)
def sum_two_numbers(a, b):
result = a + b
return result
# Capture the function's result into a variable
# by puttin g"my_result =" in front of it.... |
class Mahasiswa(object):
"""Class Manusia yang dibangun dari class manusia"""
def __init__(self,nama,NIM,kota,us):
"""Metode inisiasi ini menutupi metode inisiasi di class Manusia"""
self.nama = nama
self.NIM = NIM
self.kotaTinggal = kota
self.uangSaku = us
class MhsTIF ... |
from algoritms.BubleSort import BubleSort
from algoritms.InsertionSort import InsertionSort
from algoritms.QuickSort import QuickSort
import random
import time
class Run:
bublesort = BubleSort()
insertionsort = InsertionSort()
quicksort = QuickSort()
def __init__(self):
pass
def ini... |
# -*- coding: utf-8 -*-
__author__ = 'Dan'
__email__ = 'daz040@eng.ucsd.edu'
from assignment2 import Player, Action
class HumanPlayer(Player):
def move(self, state):
"""Reads the next move from the console.
The move should be entered as two numbers separated by a space, like '3 3'.
Args... |
''' 1. Elabore um JOGO de FORCA:
Crie uma lista de palavras e sorteie uma randomicamente uma a cada execução. Pesquise como usar números aleatórios (randômicos)
O programa mostra a forca com os espaços correspondentes às letras da palavra escolhida:
Ex: PERNAMBUCO.
O usuário digita a letra, e se ela fizer parte da pal... |
import random
import art
def blackJack():
print(art.logo)
#define card deck
cards=["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10]
#define new card
def newCard():
return random.choice(cards)
#set get score function
def getScore(x):
#set black jack condition
if len(x)==2 and "A" in x and 10 in x:
... |
#!/usr/bin/env python3
'''
Author: Spencer Norris
Date: 09/26/17
Description: Let's get some angles.
'''
import matplotlib.pyplot as plt
import numpy as np
import random
import math
import sys
def main(d):
def __get_norm(x):
'''
Returns the L2 norm of the input vector x.
'''
return math.sqrt(sum(map(lambda... |
def multiply(c, constant):
result = []
for i in range(len(c)):
result.append(constant * c[i])
return result
# r1 must be a column while r2 must be a row, bigger matrices not yet supported
# and for the purpose of this project it is not needed yet
def matrixmultiplication(A, B):
res... |
# Checks if a matrix is a list of numbers and nothing else
def Check_is_1D_Matrix(M):
# Check if the entered thing is a list
if not isinstance(M, list):
return False
# Check if the list has integers or floats in its entries (Elements of the matrix)
for i in range(len(M)):
if not (... |
import unittest
from example import *
class TestAverageCsv(unittest.TestCase):
def test_path_error(self):
with self.assertRaises(Exception):
get_file_list(path='')
def zero_value(self):
self.assertEqual(csv_average_reader(), {'close': 0.0, 'high': 0.0, 'low': 0.0, 'open': 0.0})
... |
import pygame, random
pygame.init()
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 255, 255)
# Set the width and height of the screen [width, height]
size = (900, 450)
frame = 0
screen = pygame.display.set_mode(size)
pygame.display.set_c... |
# -*- coding: utf-8 -*-
'''
A dump of some conjugation functions I've been pondering
'''
def ichidan_pot_pas(word):
'''
Takes ichidan verbs and conjugates to the passive/potential form
'''
stem = word.decode('utf-8')[:-1].encode('utf-8')
return '{}{}'.format(stem, 'られる')
def ichidan_causitive(wor... |
class Animal():
def __init__(self):
print('Animal Created')
def who_am_i(self):
print('I am an animal')
def eat(self):
print('I am eating')
class Dog(Animal):
'''
Animals and Dogs have overlapping attributes, so I want
Dog to inherit from the Animal class
'''
def __init__(self):
Animal.__init__(se... |
'''
OrderedDict remembers the order that things were added to the dictionary
'''
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
d['f'] = 6
for k,v in d.items():
print(k,v)
#will print the dictionary, but not necessarily in order bc dicitonaries don't store in order
from collections import Order... |
import random
'''
This is a blackjack game in the command line
'''
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9... |
class Line:
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
return ((self.coor2[0]-self.coor1[0])**2 + (self.coor2[1]-self.coor1[1])**2)**.5
def slope(self):
return (self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0])
coordinate1 = (3,2)
coordinate2 ... |
with open('data.txt', 'r') as f:
paths = f.read()
data = paths.split('\n')
tree = "#"
def trees_encounter(left_moves, down_moves):
trees_count, index, list_len = 0, 0, len(data)
for i in range(0, list_len, down_moves):
p = data[i]
while True:
try:
tree_or_s... |
#!/usr/bin/env python
Name: Jerinca Vreugdenhil
Student number: 12405965
Analyzis about mean modus median and standard deviation:
When we look at the analyzis the first thing we see is that the standard deviation is way too high.
There for we will analyze the histogram first and make a new analyzes after we maybe drop... |
list1=input('enter the element of list1')
list2=input('enter the elememt of list2')
list3=[]
list4=[]
list5=[]
for m in list1:
if m in list2:
list3.append(m)
elif m not in list2:
list4.append(m)
for n in list2:
if n in list1:
list5.append(n)
else:
list4.append(n)
print('C... |
a=0
b=1
max_count= int(input('enter the number'))
for X in range (0,max_count):
c=a+b
print(c)
a=b
b=c
|
a_list = [5,6,2,3,1]
def shaker_sort(a_list):
n = len(a_list)
for i in range(n-1,0,-1):
for j in range(n-1,0,-1):
if a_list[j] < a_list[j-1]:
swap(a_list,j,j-1)
return a_list
def swap(the_list,i,j):
the_list[i],the_list[j] = the_list[j], the_list[i]
pr... |
List_size = "Enter size of list:"
size = int(input(List_size))
List = [0]*size
Value = "Enter temperature:"
i = 0
while i < size:
List[i] = int(input(Value))
i = i + 1
def minimum1(List, size1):
j = 0
minimum = List[0]
while j < size1:
if List[j] < minimum:
minimum = List[j]
... |
# A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
#
# Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
#
#
#
# Example 1:
#
# Input: [[4,3,8,4],
#... |
# Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
#
# Example:
#
# Input: [1,2,3,4]
# Output: [24,12,8,6]
# Note: Please solve it without division and in O(n).
class Solution(object):
... |
import requests
from json import dump
from json import loads
def run_query(json, headers): # A simple function to use requests.post to make the API call.
request = requests.post('https://api.github.com/graphql', json=json, headers=headers)
if request.status_code == 200:
return request.json()
else... |
class Environment:
def __init__(self, parent=None):
# :string: => :Primitives: if environment
# :string: => :Node: if func_env
self.symbols = {}
self.parent = parent # :Environment:
"""
Will refer to the symbol in the most current
environment. If it doesn't exist, return None.
"""
def get(self, var_name)... |
with open("input.txt") as f:
input_ = f.read().split('\n')
def naughty_or_nice(text):
vowels = 0
double = False
previous_letter = text[0]
nots = ['ab', 'cd', 'pq', 'xy']
if text[0] in 'aeiou':
vowels += 1
for letter in range(1, len(text)):
if text[letter... |
import re
class Reindeer(object):
def __init__(self, name, speed, stam, rest):
self.name = name
self.speed = int(speed)
self.stam = int(stam)
self.rest = int(rest)
self.cycle_distance = int(stam) + int(rest)
self.points = 0
self.current_step = 1
... |
# Write a function that takes a two-dimensional list (list of lists) of numbers
# as argument and returns a list which includes the sum of each column. Assume
# that the number of columns in each row is the same.
def _sum_of_columns_sample_(sample_list):
# Solution type 1:
# return [max(col) for col ... |
# Write a function that accepts a number x and evaluates the following polynomial expression:
# y=x4−12x3+13x2+11 and returns the value of y
def equation(x):
y=x**4-12*x**3+13*x**2+11
return y
print(equation(4))
|
#Write a function that accepts a list of integers and returns the average.
#Assume that the input list contains only numbers.
def list_avg(mylist):
sum=0
for item in mylist:
sum=sum+int(item)
result=(sum/len(mylist))
return result
|
# Write a function which accepts an input string and returns a reverse of the
# input string while the case for every single character is reversed. The input
# string for this function would be a sentence (words separated by spaces)
# consisting of alphabetic characters.
def string_reversed_case_swapped(input_strin... |
# Write a program that asks the user for an input 'n'(assume that the user enters a positive integer)
# and prints a sequence of powers of 10 from 10^0 to 10^n in separate lines.
# For example if 'n' is equal to 4 then the output should look like the following
#1
#10
#100
#1000
#10000
user_num=int(input("enter... |
# paper_doll('Hello') --> 'HHHeeellllllooo'
# paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
def paper_doll(text):
newtxt=''
for item in text:
newtxt=newtxt+item*3
print(newtxt)
paper_doll('Hello') |
# Write a function named items_price that accepts two lists as parameters.
# The first list contains the quantities of n different items, the second list
# contains the prices that correspond to those n items respectively. Now,
# calculate the total amount of money required to
# purchase those items. Assume that bo... |
# Write a function that accepts a positive integer n as function parameter
# and returns True if n is a prime number, False otherwise.
def prime_number(n):
if n>1:
for item in range(2,n+1):
if n%item==0:
return False
else
|
# Write a function that accepts a list as input and returns a new list which includes every
# other element in the original list. Keep the first element, i.e. input_list[0].
def _every_other_element_sample_(sample_list):
output = []
length = len(sample_list)
output.append(sample_list[0])
for eleme... |
# Write a function that a accepts a positive number 'r' as the radius of a circle
# and calculates and returns the area of the circle. Use the value of pi as 3.14
def circle_area(r):
area=(r*r)*3.14
perimeter=(r*2)*3.14
return area
return perimeter
print(circle_area(1.45))
|
# Write a function that accepts a 2-dimensional list of integers,
# and sorts (descending order) all the elements inside each row and
# returns the sorted 2-dimensional list.
def _2d_rows_sorted_sample_(_2d_list):
for rows in _2d_list:
rows.sort(reverse=True)
return _2d_list
p... |
#Using a for loop, write a program which asks the user to type an integer, n,
#and then prints the sum of all numbers from 1 to n (including both 1 and n
user_num=int(input("Enter your number "))
num=0
total=0
for num in range(1,user_num+1):
total=total+num
print(total) |
# Write a function that accepts a list and return a new list which contains all but the first and last elements of the original list.
def list_exe6(mylist):
newlist=mylist[1:-1]
return newlist
|
# Write a function that accepts a number as input argument
# and adds 5 to it and returns the resulting number.
def add_return(x):
result=x+5
print(result)
num=int(input("Enter your number "))
add_return(num)
|
# Write a function which returns the total number of vowels in an input string
# which consists of alphabetic characters. Note that capitalization does not
# matter here i.e. a lower case character should be considered the same as an
# upper case character. For this problem, the vowels are considered to
# be A, E, ... |
import unittest
from app.models import Source
class SourceTest(unittest.TestCase):
"""
SourceTest class to test the behaviour of the Source class
"""
def setUp(self):
"""
Method that runs before each other test runs
"""
self.new_source = Source('abc-news', 'ABC news', ... |
# calculate tip
def calculateTax(cost, percentageTax):
return (cost * (percentageTax / 100))
def calculateCost(cost, percentageTip):
return (cost * (percentageTip / 100))
# Ask user for the cost
cost = float(input("Enter cost of bill(Exclude $ sign) \n"))
# Ask user for tax percentage
percentageTax = int(... |
# put your code here.
#import test.txt
#import twain.txt
words = {}
def word_count(file):
file = open(file).read()
file = file.lower()
file.strip('?' '.')
print(file)
file = file.split()
for word in file:
words[word] = words.get(word, 0) + 1
return words
print(word_count('test.t... |
# 6 - Largest and Smallest in a List
# Source: https://adriann.github.io/programming_problems.html
# Write a function that returns the largest and smallest elements in a list.
numbers = []
i = 0
print("Please enter 5 numbers.")
while i < 5:
try:
listItem = float(input(str(i + 1) + ": ")) # Get input from... |
# 10 - Reverse String
# Write a function to reverse a string.
word = input("Enter a word: ")
# Easy Way
print("Original: " + str(word))
print("Easy Reverse: " + str(word)[::-1])
# Function
def reverse(word):
reversedWord = []
currentPos = len(word) - 1 # Start at the last letter (5 letters = 0 - 4)
endAt... |
def insertion_sort(A, asc=True):
"""
Insertion sorting algorithm for sequence of n numbers.
Parameters
------
A : array-like of shape (n,)
Array to be sorted.
asc : boolean
If True sorts sequence in increasing order.
Returns
-------
A : array-like of shape (n,)
... |
from dataclasses import dataclass
from pprint import pprint
from lessons.lesson_8.MyException import MyException
from lessons.lesson_8.Ship import Ship
@dataclass
class Motorboat(Ship):
mast_height: int = 0 # Высота мачты
sail_area: int = 0 # Площадь полотна паруса
def make_sound(self):
pprint(... |
#module that will allow us to use json format for our dictionaries.
import json
#module that will allow us to connect to the API.
import requests
#module that allow us to work with dates and perform the
# functionalities that will aid us in completing this challenge.
from datetime import datetime, timedelta
#module th... |
from decimal import *
import random
def keySearch(L, k):
for elem in L:
if elem[0] == k: return elem[1]
return None
EtoF = {'bread': 'du pain', 'wine': 'du vin',\
'eats': 'mange', 'drinks': 'bois',\
'likes': 'aime', 1: 'un',\
'6.00':'6.00'}
def translateWord(word, dictionary):
... |
from caesar import rotate_string
def alphabet_position(letter):
alphabet = string.ascii_lowercase
return alphabet.find(letter.lower())
def rotate_character(char, rot):
letters = string.ascii_letters
if str(char) not in letters:
return char
charPosition = alphabet_position(char)
alpha... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Quantas PAs
quantas_pa = 0
n = 0
razao = int(raw_input())
while True:
seq = raw_input()
seqs = seq.split()
if seq == 'fim':
break
for d in range(len(seqs) -1):
if int(seqs[d +1]) - int(seqs[d]) == razao:
n += 1
if n == len(seqs) -... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Produto de dois somatórios
numero = raw_input()
soma_par = 0
soma_impar = 0
for c in range(len(numero)):
if c == 2 or c == 4 or c == 0:
soma_par += int(numero[c])
else:
soma_impar += int(numero[c])
produto = soma_par * soma_impar
i... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Custo Empregado
salario = float(raw_input())
dias = int(raw_input())
custo_transporte_diario = float(raw_input())
# custo empregador
inss_empregador = salario * 0.08
fgts_empregador = salario * 0.12
custo_transporte = dias * custo_transport... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Falta um
def encontra_rotulo_perdido(l1,l2):
for i in range(len(l2)):
for d in range(len(l1)-1,-1,-1):
if l1[d] == l2[i]:
l1.pop(d)
for i in l1:
return i
|
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Inserção ordenada do ultimo elemento de uma lista
def insere_ordenado_ultimo(dados):
for d in range(len(dados)):
troca = False
for i in range(0,len(dados) -1):
if dados[i] > dados[-1]:
dados[i],dados[i+1] = dados[i+1], dados[i]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.