text stringlengths 37 1.41M |
|---|
import unittest
from temp_converter import convert_celsius_to_fahrenheit
class TempConverterTest(unittest.TestCase):
# convert temperature from celsius to F
# test data type input
def test_celsius_is_converted_to_fahrenheit(self):
"""
F = C * 9/5 +32
"""
actual = conver... |
from Prac08.taxi import Taxi, UnreliableCar, SilverServiceTaxi
def main():
# Prius = Taxi("Prius", 100)
# print(Prius)
# Prius.drive(40)
# Prius.current_fare_distance = 100
# print(Prius)
#
# dodge = UnreliableCar('dodge', 100)
# print(dodge)
# if dodge.drive(130):
# print... |
import turtle
t = turtle.Turtle()
# screen
s = turtle.Screen()
s.bgcolor("black")
t.pencolor("white")
t.speed(0)
for n in range(73):
for i in range(4):
t.forward(80)
t.left(90)
t.left(5)
t.hideturtle()
turtle.done()
|
initial_money = 2000
initial_price = 100
age = 20
hungry = (age / 100) * 100
price = initial_price
while hungry < (85/100) * 100:
print("Buy an ice cream")
print("Ice price:", price)
print ("Hungry is:", hungry)
price = price * (1 + 20/100)
hungry = hungry + age
print("Actual hungry:", hungry)
if hungry >= (85/... |
def aptitude():
age = int(input("How old are you?: "))
experience = int(input("How long were you at your previous job, in months?: "))
score = int(input("What did you score in the competency test?: "))
competence = (age + experience) * score
if competence > 200:
print("Candidate is competen... |
"""
修改图片后缀名
"""
import os
base_path = "G:\\FaceImg\image\\{}"
filename = "G:\\FaceImg\\"
file = os.listdir(filename)
count = 0
for i in file:
count +=1
names = str(count) + '.jpg'
filenames = base_path.format(names)
filenamess = "G:\\FaceImg\\{}".format(i)
print(filenamess)
with open(filename... |
import itertools
# %% Manually Consuming an Iterator
items = [1, 2, 3]
it = iter(items) # Invokes items.__iter__()
while True:
n = next(it, None) # Invokes items.__next__()
if n == None:
break
print(n)
# %% Iterating in Reverse
a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[a for a in reversed(a)] # In... |
"""This class represents the game state of a 2048 game in progress, intentionally made as general as
possible to accomodate variations on the game."""
from copy import deepcopy
from random import choice
import numpy as np
import make_move
class Board:
"""A 2048 game board with tiles on it."""
UP = 0
... |
"""This file has a class that allows someone to play a complete 2048 game with full game history."""
import os
from random import choice
import numpy as np
from board import Board
from verboseprint import *
class Game:
"""A game of 2048."""
def __init__(self, width=4, height=4, board=None, board_obj=None, ... |
class Animals:
'''Животные'''
interaction = "не кормить"
weight = 0 # кг
weight_max = 0 # кг
voice = "!"
emp_count = 0
weight_sum = 0
def __init__(self, name, weight):
self.name = name
self.weight += weight
Animals.emp_count += 1
Animals.weight_sum += w... |
b=[1,2,3,4,5]
print(b)
for i in range(5):
print('i is now:',i)
|
# n = raw_input("ENTER STRING\n")
n = "CAMMAC"
length = len(n)
for i in range(0, int(length/2 + 1)):
if n[i] is not n[-i - 1]: #change logic here.
break
if i < (length / 2):
print("not")
else:
print("yes") |
def interface():
while True:
print("#############################")
list=("1. KMP\n2. Modulo42\n3. AliceNBob\n4. CupsNBall\nEnter 'Q' to quit\n")
select=input(list+"Enter a program to run :").upper()
import Programs.KMP as a
import Programs.Modulo42 as b
import Pro... |
import sqlite3
class Database(object):
""" the Silent Disco database. """
def __init__(self):
self.conn = sqlite3.connect('database.db', check_same_thread=False)
self.users_cursor = self.conn.cursor()
self.users_cursor.execute(
""" CREATE TABLE IF NOT EXISTS user... |
# Python内置了字典:dict的支持,dict全称dictionary
# 在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
# 这个通过key计算位置的算法称为哈希算法(Hash)。
# []:list
# ():tuple
# {}: dict
# 学生成绩
score = {"Nicolo":100,"Tom":99,"Jerry":99}
print("打印Nicolo的成绩:",score["Nicolo"])
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
score["Nicolo"] = 101
print("打印Nicolo的成绩:",score[... |
print("tuple一旦初始化就不能修改,比如同样是列出同学的名字")
classmates = ('Michael', 'Bob', 'Tracy')
print(classmates)
# 现在,classmates这个tuple不能变了,它也没有append(),insert()这样的方法。
# 其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。
# 不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。 |
# InheANDPoly 继承和多态
# 编写了一个名为Animal的class,有一个run()方法可以直接打印:
class Animal(object):
def run(self):
print('Animal is running...')
def eat(self):
print('Eating meat...')
# 当我们需要编写Dog和Cat类时,就可以直接从Animal类继承:
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self)... |
print("hello")
print("这样","可以","连接","起来吗?",",自动识别为空格")
print("试试"+"加好可以连接吗?","事实证明是可以的")
print("100+200 =",100+200)
print(len("abc")) |
import PyPDF2
file1=raw_input("Enter name of first file: ")
file2=raw_input("Enter name of second file: ")
#Access and open the files to merge
pdfFile_1=open("%s" %file1 + '.pdf','rb')
pdfFile_2=open("%s" %file2 + '.pdf','rb')
#Read the two files
pdfRead_1=PyPDF2.PdfFileReader(pdfFile_1)
pdfRead_2=PyPDF2.PdfFileReader... |
"""
Small anonymous functions can be created with the lambda keyword.
This function returns the sum of its two arguments: lambda a, b: a+b.
* Lambda functions can used wherever function objects are required.
* They are syntactically restricted to a single expression.
* Semantically, they are just syntactic sugar for a ... |
"""
Shortest unique prefix.
Given a list of words, for each word find the shortest unique prefix.
You can assume a word will not be a substring of another word
(i.e. 'play' and 'playing' won't be in the same words list)
Example:
input: ['joma', 'jack', 'john', 'teodore']
poutput: ['jom', 'ja', 'joh', 't']
... |
inputfile = open('{NAME_OF_FILE_HERE}')
emails = inputfile.readlines()
myfuckingset = set()
counter = 0
linecounter = 0
print("Duplicates:")
for line in emails:
linecounter = linecounter + 1
if line not in myfuckingset:
myfuckingset.add(line)
else:
print(line)
counter = counter + 1
print("Number of duplicates:... |
#!/usr/bin/python
from collections import defaultdict
import string
import os
import sys
from heapq import heappush as push, heappop as pop, heappushpop as pushpop
# Initialization
print "Executing word_count_running_median.py...\n"
max_heap = []
min_heap = []
N = 0
file_names = []
word_count = defaultdict(int)
# O... |
from time import sleep
#app number call list
# add number call
def addPhone(val, lists):
k = 0
adTrue = False
ref = {0: True, 1: False}
while k < len(lists):
if val == lists[k]:
adTrue = ref[0]
k += 1
if adTrue == True:
print("\n", val, "Ya se encuentra agregado.\n\n")
else:
print("agregando..")
... |
class Person(object):
pass
x = Person()
print(type(x)) # module __main__.Person in Py3 , but instance in Py2!!! to make it compatible use Person(object)
# new-style of classes!
# py2 doesn't inherit! https://www.python.org/doc/newstyle/
# use in py2/py3 (object)!!!
print(dir(x))
x.neco = 123 # new attribute wi... |
class Person:
Person_id = 1
def __init__(self, name, age):
self.name = name
self.age = age
self.cid = Person.Person_id
Person.Person_id += 1
def printall(self):
print ("Name : %s, age : %d, id : %d" % (self.name, self.age, self.cid))
bob = Person("Bob", 20)
alice... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 11:10:12 2021
@author: frank
"""
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
max = 0
for upper_key in animals:
tem_total = 0
for inne... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 10:02:02 2017
@author: kashen
"""
import numpy as np
import math
def get_curves(points=1000, radius=2, noise=None, original=False, *args, **kwargs):
"""
Generates syntethic data in the shape of two quarter circles, as in
the example from the paper by Mika... |
#!/user/bin/env python
def quick_sort(arr):
sort_all(arr, 0, len(arr)-1)
return arr
def sort_all(arr, start_index, end_index):
if end_index <= start_index:
return
pivot_index = sort_a_little_bit(arr, start_index, end_index)
sort_all(arr, start_index, pivot_index-1)
sort_all(arr, pivot_index+1, end... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
'''
The solve of question:
1- I will creat... |
#!/usr/bin/env python
def count_inversion(ls): #--> Time Complixty O(n)
#-->basic vriables
inversion = 0
#--> get middle
midd = len(ls) //2
#--> divied array to left and right
left = ls[:midd]
right = ls[midd:]
#-->sort left array and right array
left, inv_l = buble_sort(left, inversion)
right, i... |
'''
Exercise 4. Hamming Distance
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Calculate the Hamming distace for the following test cases.
'''
def hamming_distance(str1, str2):
"""
Calculate the ha... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or rece... |
#!/usr/bin/env python
'''
Problem Statement
You have been given an array containg numbers. Find and return the largest sum in a contiguous subarray within the input array.
'''
def max_sum_subarray(arr):
current_sum = arr[0] # `current_sum` denotes the sum of a subarray
max_sum = arr[0] # `max_sum` de... |
import sys
sys.argv.append("..")
from utils import constants
import numpy as np
from typing import Union
class Berry:
"""
Berries are to be eaten by the baby and are randomly spawned
in the environment. They roll around randomly in one of the
four compass directions.
"""
def __init__(
... |
def RiemanSum(f, a, b, Increment = 0.0001):
"""One dimensional function that returns the riemansum between two points; This implies that the function has the property of Rieman integrability."""
if not callable(f):
raise TypeError("[Rieman.py]: Function RiemanSum needs the input function f to be callab... |
# # 确定中间数 以中间数为基准左右删除
# num_strarr = input().split(' ')
# num_arr = []
# for i in num_strarr:
# num_arr.append(int(i))
#
# index_arr = []
# # 先找出中间数
# for i in range(0,len(num_arr)):
# if i == 0:
# if num_arr[i] >= num_arr[i+1]:
# index_arr.append(i)
# elif i == len(num_arr) - 1:
# ... |
def swap(arr,i,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def printArr(arr):
s = ""
for i in range(len(arr)):
s+= str(arr[i])
if(i<len(arr)-1):
s+=" "
print(s)
T = int(input())
i=0
arr_big = list()
while i<T:
i+=1
size = int(input())
arr = list(map(i... |
# Assignment 13.1
import xml.etree.ElementTree as ET
import urllib.request, urllib.error, urllib.parse
from urllib.request import urlopen
url = input("Enter location:")
print("Retrieving:", url)
datastring = urlopen(url).read()
stuff = ET.fromstring(datastring)
lst = stuff.findall('comments/comment')
Tot = 0
for num... |
def isAlt(s):
vowels = 'aeiou'
rule = lambda x,y : x in vowels and y not in vowels or x not in vowels and y in vowels
return all(rule(s[i], s[i+1]) for i in range(len(s) - 1)) |
def is_prime(n):
if n == 0 or n == 1: return False
res = True
for i in range(2, int(n**.5)+1):
if n % i == 0:
res = False
break
return res
def generate_primes(x):
return (n for n in range(x+1) if is_prime(n)) |
def one_two_three():
n = 2*one_two() + one_two() - 2
while n not in [1,2,3]:
n = 2*one_two() + one_two() - 2
return n |
from collections import Counter
def first_non_repeating_letter(string):
c = Counter(string)
nonrepetitive = [k for k, v in c.items() if v == 1]
nonrepetitive = [k for k in nonrepetitive if not k.isalpha()] + \
[k for k in nonrepetitive if k.swapcase() not in string]
if nonrepetitive... |
def yes_no(arr):
res = []
l = arr[:]
i = 0
while len(res) < len(arr):
try:
res.append(l[i])
l.append(l[i+1])
i += 2
except IndexError:
pass
return res
|
def convert_to_mixed_numeral(parm):
n, d = [int(i) for i in parm.split('/')]
if abs(n) < d:
return parm
else:
a, b = divmod(abs(n), d)
if b == 0: return "-" * (n < 0) + "%d" % a
return "-" * (n < 0) + "%d %d/%d" % (a, b, d)
|
def capitalize(s):
return [
"".join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s)),
"".join(c.upper() if i % 2 != 0 else c for i, c in enumerate(s))
] |
def palindrome(num):
if not isinstance(num, int):
return "Not valid"
elif num < 0:
return "Not valid"
else:
num = str(num)
for i in range(len(num) - 1):
for j in range(i+1, len(num)):
if num[i] == num[j]:
p = num[i:j+1]
... |
import re
def parse_example(example):
expression, variable = example.split(" = ")
return variable, "(" + expression + ")"
def only_one_variable_in_expression(expression):
return len(set(select_variables(expression))) == 1
def select_variables(expression):
return re.findall(r"[a-z]+", expression, ... |
import re
def triple_double(num1, num2):
tripleMatch = re.search(r"(\d)\1{2}", str(num1))
if tripleMatch is None:
return False
else:
tripleNum = tripleMatch.group(1)
return bool(re.search(r"([%s])\1" % tripleNum, str(num2)))
|
def stairs(n):
w = 2*n + 2*n-1
return '\n'.join((' '.join(str(num%10) for num in range(1, i+1)) + ' ' + ' '.join(str(num%10) for num in range(i, 0, -1))).rjust(w) for i in range(1, n+1))
|
import re
def trump_detector(trump_speech):
duplicates_regex = re.compile(r"([aeiou])\1+", re.IGNORECASE)
duplicates = []
normal_speech = re.sub(duplicates_regex, lambda x: duplicates.append(x.group()) or x.group()[0], trump_speech)
extra_vowels = sum(len(d)-1 for d in duplicates)
total_vowels = su... |
def order_word(s):
return "Invalid String!" if not s else ''.join(sorted(s)) |
from string import ascii_lowercase as alphabet
def sort_string(s):
nonEnglishIndex = [i for i in range(len(s)) if s[i].lower() not in alphabet]
nonEnglishChars = ''.join(s[i] for i in nonEnglishIndex)
s2 = "".join(sorted(s, key=lambda x: x.lower())).strip(nonEnglishChars)
for idx in nonEnglishIndex:
... |
def reverse(n):
power = len(str(n))-1
if n < 10:
return n
else:
return (n%10)*10**power + reverse(n//10) |
from math import sqrt
def find_divs(n):
divs = []
for i in range(1,int(sqrt(n))+1):
if n % i == 0 : divs.append(i)
return sorted(divs + [n/j for j in divs if j != sqrt(n)])
def oddity(n):
return 'even' if len(find_divs(n)) % 2 == 0 else 'odd' |
def is_increasing(n):
res = True
n0 = str(n)[0]
for d in str(n)[1:]:
if d < n0:
res = False
break
else:
n0 = d
return res
def is_decreasing(n):
res = True
n0 = str(n)[0]
for d in str(n)[1:]:
if d > n0:
res = False
... |
def unique_in_order(iterable):
if len(iterable) < 2:
return list(iterable)
res = []
for i in range(len(iterable) - 1):
if iterable[i] != iterable[i+1]:
res.append(iterable[i])
return res + [iterable[-1]]
|
def solution(digits):
largest = 0
for i in range(len(digits) - 4):
current_val = int(digits[i: i+5])
if current_val > largest:
largest = current_val
return largest |
def remove_smallest(numbers):
if not numbers:
return []
else:
min = numbers[0]
for number in numbers[1:]:
if number < min:
min = number
numbers.remove(min)
return numbers
|
def fibo(n) :
a = 0
b = 1
for i in range(n-1) :
c = a + b
c = c % 10
a = b
b = c
return b
n = int(input())
sol = 1
if n > 2 :
sol = fibo(n)
sol = str(sol)
print(sol[-1])
|
# Uses python3
import sys
def get_change(n):
#write your code here
#print("hi",n)
c=0
while n>0 :
if n == 0:
break
if n > 10 :
c=c+1
n=n-10
elif n>=5 and n<=9:
c=c+1
n=n-5
else:
# print("hi")
... |
import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a v... |
class Student:
def __init__(self, name, carrera, nivel):
self.nombre = name
self.carrera = carrera
self.nivel = nivel
self.calificaciones = []
self.promedio = 0.0
def capturar_calificaciones(self, unidad, calificacion):
self.calificaciones.insert(unidad, califica... |
from math import ceil
#import networkx as nx
import shortest_path as sp
import graph
def path_weight(Graph,path):
weight = 0
for i in range(0,len(path)-1):
#print('path_weight edges ',Graph.edges(data=True))
#print('path weight indeces ',path[i],path[i+1])
#weight += Graph.get_edge_data(path[i],pat... |
# # 身份验证
# username=input("username:")
# password=input("password:")
# if username== "admin" and password=="12345":
# print("pass")
# else:
# print("failed")
# 分段函数求值
# x=float(input("请输入x的值:"))
# # if x>1:
# # print(3*x-5)
# # elif -1<=x<=1:
# # print(x+2)
# # else:
# # print(5*x+3)
# if x>1:
... |
# Importação das biliotecas
import streamlit as st
import pandas as pd
import base64
import geopy
import folium
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
csv = df.to_csv(index=False,float_fo... |
from abc import ABC, abstractmethod
import pygame
# Klasa pod koniec wyłączona z użycia, zastąpiona Spritem
class MovingObjects(ABC, ):
def __init__(self, x, y):
self.speed = 0
self._position = [x, y]
self.direction = []
@abstractmethod
def get_event(self):
pass
@ab... |
# -*- coding: utf-8 -*-
sayi1 = int(input("Sayı Giriniz (1.)"))
sayi2 = int(input("Sayı Giriniz (2.)"))
sayi3 = int(input("Sayı Giriniz (3.)"))
if (sayi1>=sayi2) and (sayi1>=sayi3):
enBuyuk = sayi1
elif (sayi2>=sayi1) and (sayi2>=sayi3):
enBuyuk = sayi2
else:
enBuyuk = sayi3
print("En Büyük ... |
def compare(user_number, random_number):
if int(user_number) == random_number:
return 'You win'
elif int(user_number) > random_number:
return 'Вваше число Больше'
elif int(user_number) < random_number:
return 'Вваше число Меньше'
|
"""
Суть задачи:
юзер пришел в казино, сел за автомат, начал игру и у него начали выпадать рандомно величины из представленных выше.
Нужно написать впрограмму, которая за каждым вводом "Играть" (на Ваше усмотрение) - делал вывод полученых очков в комбинации и количество очков
юзера за всю игру. Если юзре ввел "Выйти" ... |
"""
Input: Feb 12 2019 2:41PM
Output: 2019-02-12 14:41:00
Функция принимает строку (пример - Input) и возвращает строку (пример - Output)
"""
from datetime import datetime
date_input = "Feb 12 2019 2:41PM"
date_output = str(datetime.strptime(date_input, "%b %d %Y %I:%M%p"))
print(date_output)
"""
Напишите функция is... |
# Given s, starting location, and n, # of steps to take
# Output all possibilities in sequential order
# s = 1, n = 1 --> [
# [1, 2],
# [1, 4],
# [1, 5]
# ]
# s = 1, n = 2 --> [
# [1, 2, 1], [1, 2, 3], [1, 2, 4], [1, 2, 5], [1, ... |
import numpy as np
import matplotlib.pyplot as plt
import scipy as sci
import scipy.io as sio
from warmUpExercise import warmUpExercise
from computeCost import computeCost
from gradientDescent import gradientDescent
## Machine Learning Online Class - Exercise 1: Linear Regression
# Instructions
# ------------
#
# ... |
#Reverse Integer - easy
# Given a signed 32-bit integer x, return x with its digits reversed. If reversing
# x causes the value to go outside the signed 32-bit integer
# range [-231, 231 - 1], then return 0.
# Assume the environment does not allow you to store 64-bit integers
# (signed or unsigned).
def reverse_i... |
import unittest
import passwordGenerator
import itertools
import collections
class TestPasswordGenerator(unittest.TestCase):
def setUp(self):
pass
def test_length(self):
password = passwordGenerator.generatePassword()
self.assertTrue( len(password) > 12)
def test_upper... |
'''
###TODO:
plot on map
compare with regular passport rankings
make it not read any file
find to taiwan
'''
def logger(text):
if logHuh == True:
print(text)
def workWithLog(argz):
logHuh=False
nArgz=[]
if len(argz) > 1 and argz[1]=='log' :
logHuh=True
logger('###log: logging')
nArgz.append(argz[0])
fo... |
def missed_cans( num_1, num_2 ):
sum = num_1 + num_2 - 1
return sum - num_1, sum - num_2
cans_num_1 = int( input( 'the number of cans the first man : ' ) )
cans_num_2 = int( input( 'the number of cans the second man : ' ) )
missed1, missed2 = missed_cans(cans_num_1, cans_num_2)
print(missed1)
print(missed2)
|
st = 'Print only the words that start with s in this sentence'
my_st = st.split(" ")
print(my_st)
for words in my_st:
if words.startswith('s') == True:
print(words)
print(list(range(0,11,2)))
for num in range(0,50):
if num % 3 == 0:
print(num)
st_2 = 'Print every word in this sentence that h... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 19:32:16 2017
@author: rjr
Covering the implementation of a while loop
"""
# Setting variables
i = 0
numbers = []
while i<6:
print(f"At the top i is {i}")
numbers.append(i)
i += 1
print("Numbers now:", numbers)
print(f"At the bottom i is... |
def funcion_par(num):
res = num % 2
if res == 0:
print(f"EL NUMERO {num} ES PAR ")
else:
print(f"EL NUMERO {num} ES IMPAR ")
def main():
num = int(input("DIGITE UN NUMERO: "))
funcion_par(num)
if __name__ == "__main__":
main() |
#######################################################
#
# MiniBurger.py
# Python implementation of the Class MiniBurger
# Generated by Enterprise Architect
# Created on: 19-6��-2021 18:39:45
# Original author: 70748
#
#######################################################
from .Hamburg import Hamburg
class Mi... |
# def get_words(sentence):
# return list(filter((lambda x: len(str(x)) > 0), str(sentence).split(sep=' ')))
#
#
# def get_word_count(sentence):
# return get_words(sentence).count()
def get_word_freq_in_sentences(word, sentences):
"""
:param word: the word which frequency we calculate
:para... |
import sqlite3
conn = sqlite3.connect('test.db')
print("Opened database successfully")
# conn.execute('''CREATE TABLE USER_NAME
# (USER_ID INTEGER PRIMARY KEY AUTOINCREMENT,
# UNAME CHAR(64) NOT NULL,
# PASSWORD CHAR(128) NOT NULL,
# TYPE_OF_US... |
base=float(input("Digite a largura do terreno: . . ."))
altura=float(input("Digite o comprimento do terreno: . . ."))
area=base*altura
perimetro=(2*base)+(2*altura)
print("A area do terreno é:",area)
print("O perimetro do terreno é:",perimetro) |
qntkm = float(input("Digite o kilometro percorrido: "))
qntdias = float(input("Digite a quantidade de dias que ele foi alugado: "))
dias=qntdias*60
km=qntkm*0.15
print("O preço a pagar é a quantidade de {} dias mais {} quantidade de km rodados, totalizando em R$:{:.2f}".format(qntdias,qntkm,dias+km))
|
reais = float(input("Digite o valor a ser convertido: "))
dinheiro=reais/5.40
print("O valor R$:{:.2f} são US:{:.2f}".format(reais,dinheiro)) |
nome = input ('Qual é o seu nome? . . .')
print ("olá ",nome,"!, prazer em conhecelo!") |
"""
Desarrolle un programa que grafique los largos de las secuencias de Collatz
de los números enteros positivos menores que el ingresado por el usuario
"""
def Cantidad_Collatz(n):
if n == 1:
return 1
if n%2==0:
return 1 + Cantidad_Collatz(n//2)
else:
return 1+ Cantidad_Collatz(n*3+1)
n=int(input())
str_c... |
####Ejercicio Numero 2, Busqueda de un entero en un arreglo
def Busqueda(lista, numero):
return numero in lista
lista = []
consulta = input("Ingrese una Lista seguido del Número a Buscar: ")
numero="";
end = False
for c in consulta :
if end :
if c == ',' or c == ' ':
pass
else :
numero +=c
elif c == '... |
# unit test
import unittest
class sample(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("calls once before any tests in class")
@classmethod
def tearDownClass(cls):
print("calls once after all tests in class")
def setUp(self):
... |
score = int(input("คะแนนที่ได้ : "))
while score != -1:
score = int(input("คะแนนที่ได้ : "))
print(score) |
from random import randint
from random import seed
seed(135)
class Reverser:
def reverse(self, num):
def to_bits(num):
def binary_sum(num1, num2):
a = []
b = []
c = []
dim = 13
for i in range(dim):
a.append(randint(-2**31, 2**31))
r = Reverser()
for i in range(dim):
b.append(r.reverse(a[i]))
for ... |
import random
from random import randint
from random import seed
seed(1941706)
i = []
for s in range(19601):
i.append(randint(1,35))
x = 0
def while_1():
while x < 5:
print(x + 1)
def while_2():
while x < 5:
if x == 4:
x = 0
print(x)
x += 1
def while_3():
... |
from random import randint
from random import choice
from random import seed
seed(135)
class P:
def __init__(self, lista = []):
self.lista = lista
def __getitem__(self, index):
decision = choice((-1, 1))
idx = (index + decision)
def __setitem__(self, index ,value):
self... |
from random import seed
from random import choice
from random import randint
from string import ascii_letters
seed(1850201)
t = []
def random_string_generator():
f = ""
my_str = ""
for z in range(0,3):
my_str += choice(ascii_letters).lower()
for s in range(randint(1,20)):
idx = randint... |
# Шукуров Фотех Фуркатович
# группа № 181-362
import random
mas = ["КИРИЛЛ", "МЕФОДИЙ"]
random.shuffle(mas)
name = input("Назовите одного из двух братьев, создателей старославянской азбуки: ")
nameUpper = name.upper()
if mas[0] == nameUpper:
print("Ты выиграл!")
else:
print("Я загадывал не это имя.\nПравильный... |
# -*- coding: utf-8 -*-
from math import *
import math
try:
x = int(input("Введите значние X: \n"))
if x <=-2.5: y = -6/7*x-36/7
elif -2.5<x and x<2: y = x**3 + 1.5*x**2-2.5*x-3
elif 2<=x: y = -2*x + 10
print("X={0:.2f} Y={1:.2f}".format(x,y))
except:
print('Ошибка ввода.')
print("\n__________... |
import random
from Num_Racionales import *
class Matriz:
def __init__(self, nombre, filas, columnas):
self.nombre = nombre
self.filas = filas
self.columnas = columnas
self.elementos = []
def elem_Random(self):
elementos = []
for i in range(self.filas):
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def checkio(words: str) -> bool:
'''
tmp = []
for word in words.split(' '):
if word.isalpha():
tmp.append(word)
if len(tmp) == 3:
return True
else:
tmp = []
return False
'''
count_wo... |
import base64, urllib2
from PIL import Image
"""
This iteration uses list slicing to get the values at the even and odd pairs.
Once you get this the operation is similar to that in level11.py.
"""
username = 'huge'
password = 'file'
base64string = base64.b64encode('%s:%s' % (username, password))
link = urllib2.Requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.