text stringlengths 37 1.41M |
|---|
#4. Создать (не программно) текстовый файл со следующим содержимым:
#One — 1
#Two — 2
#Three — 3
#Four — 4
#Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные.
# При этом английские числительные должны заменяться на русские.
# Новый блок строк должен записываться в новый текстовый ... |
#2. Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
list_2 = input("Введите значения через ... |
#2. Реализовать функцию, принимающую несколько параметров,
# описывающих данные пользователя: имя, фамилия, год рождения,
# город проживания, email, телефон.
# Функция должна принимать параметры как именованные аргументы.
# Реализовать вывод данных о пользователе одной строкой.
def dict_func(**kwargs):
return list... |
a = int(input())
factors_a=[]
for i in range(1,a+1):
if a%i==0:
factors_a.append(i)
print(factors_a)
b = int(input())
factors_b=[]
for j in range(1,b+1):
if b%j==0:
factors_b.append(j)
print(factors_b)
x = (set(factors_a) & set(factors_b))
print(x)
largest_common_factor = max(x)
print(largest_common_factor)
|
def prime_number():
in1 = int(input("Enter start range: "))
output = []
if in1 >= 0:
in2 = int(input("Enter end range: "))
for i in range(in1,in2 + 1):
for j in range(2,i):
if (i % j) == 0:
break
... |
a=int(input('enter length:'))
b=int(input('enter breadth:'))
p=a*b
q=2*(a+b)
print('the area is' +str(p))
print('the perimeter is' +str(q)) |
x=int(input('enter one variable:'))
y=int(input('enter another variable'))
print(x**3+3*x**2*y) |
Dict={'roll no':[1,2,3,4],'name':['ram','hari','adi','elisha'],'marks':[70.0,80.0,60.0,40,0],'gender':['male','male','female','female']}
for i in range(len(Dict['roll no'])):
if Dict['gender'][i]=='male':
print(Dict['marks'][i])
print(Dict['name'][i])
print(Dict['gender'][i]) |
import pandas as pd
import numpy as np
# Read in the data
df = pd.read_csv('Amazon_Unlocked_Mobile.csv')
# Sample the data to speed up computation
# Comment out this line to match with lecture
df = df.sample(frac=0.1, random_state=10)
df.dropna(inplace=True)
# Remove any 'neutral' ratings equal to 3
df... |
"""
LeetCode 125) Valid Palindrome
Date: Jul 14, 21
"""
import timer
@timer.timer
def isPalindrome(s: str) -> bool:
s_list = []
for char in s:
if char.isalnum():
s_list.append(char.lower())
while len(s_list) > 1:
if s_list.pop(0) != s_list.pop():
print(s_list)
... |
import shapes
import color
import random
import pygame
import math
import animation
class Maze :
map = []
animatedMap = []
# retraceAnimation = animation.Animation()
# mazeAnimation = animation.Animation()
# fillAnimation = animation.Animation()
mainAnimation = animation.Animation()
def r... |
def select_features(df, features):
"""
Select features from the dataframe_.
:param df: target dataframe
:type df: pandas.DataFrame
:param features: list of features to choose
:type features: list
:return: dataframe with desired features (columns)
:rtype: pandas.DataFrame
"""
... |
# example of while loop
# take input from the user
someInput = raw_input("type 3 to continue anything else to quit")
while someInput == '3':
print("thank you for the 3, It was very kind of you")
print("type 3 to continue, anything else to quit")
someInput = raw_input()
print("How dare you, that is not a ... |
# Make a word guessing game using functions
# these are strings that I will put into a list
snow_1 = " _ "
snow_2 = " _|=|_ "
snow_3 = " ('') "
snow_4 = ">--( o )--<"
snow_5 = " ( o ) "
# this is the list of snow man strings
snow_man = [snow_1, snow_2, snow_3, snow_4, snow_5]
# defining my ... |
#!/usr/bin/env python3
import time
import string
import config
from psu import PSU
psu = PSU()
def main():
print("TTi PSU Remote Test")
print("1. Connect")
print("2. Turn On")
print("3. Turn Off")
print("4. Set Voltage to 7V")
print("5. Set Voltage1 to 13V")
print("6. Get Voltage")
pri... |
'''
A simple demo on how to perform core operation with the SQS queue.
Multiple threads are used to simulate the interaction of the different components (i.e. producer and consumer) with the queue
'''
from queue_setup import MyMessageQueue
from producer import Producer
from consumer import Consumer
fr... |
import math
import random
class line:
def __init__(self, A, B, C):
self.A = A
self.B = B
self.C = C
def dis_00(obj):
dis = C / ((A ** 2 + B ** 2) ** 0.5)
return dis
def dis_xy(obj, X, Y):
dis_x = abs(A * X + B * Y + C)
dis = dis_x / ((A ** 2 + B ** 2) ** 0.5)
return dis
def tri_area(obj):
if A... |
planet_list = ["Mercury", "Mars"]
# Use append() to add Jupiter and Saturn at the end of the list.
planet_list.append("Jupiter")
planet_list.append("Neptune")
print(planet_list)
# Use the extend() method to add another list of the last two planets in our solar system to the end of the list.
planet_list.extend(["Satur... |
import sys
import typing
def is_corrupted(line: str) -> typing.Optional[str]:
stack = []
for c in line:
if c in ['(', '{', '[', '<']:
stack.append(c)
else:
closing = stack.pop()
if (closing == '(' and c != ')') or \
(closing == '[' and c != '... |
import sys
def fuel(size: int) -> int:
return size // 3 - 2
def recursive_fuel(size: int) -> int:
f = fuel(size)
if f <= 0:
return 0
if f > 0:
return f + recursive_fuel(f)
def solve():
if sys.argv[1] == 'part1':
return sum([fuel(int(s.strip())) for s in sys.stdin])
... |
import sys
def parse_digits_sequence(sequence: str):
return sequence.strip().split(" ")
def parse_input_line(input_line: str):
(input_sequence, output_sequence) = input_line.split("|")
return parse_digits_sequence(input_sequence), parse_digits_sequence(output_sequence)
def solve():
io_pairs = []
... |
import sys
from collections import Counter
from typing import Tuple, List
def check_trees_for_slow(tree_map: List[str], slope: Tuple[int, int]) -> int:
current_column = slope[1]
trees = 0
for row_index in range(slope[0], len(tree_map), slope[0]):
row = tree_map[row_index]
trees += int(row[... |
import sys
from typing import Tuple
def find_marker(s: str, distance: int) -> Tuple[int, str]:
for i in range(len(s) - 3):
chars = set(list(s[i:i+distance]))
if len(chars) == distance:
return i + distance, s[i:i+distance]
def solve():
if sys.argv[1] == 'part1':
return fin... |
import sys
from typing import Tuple, List, Set, Dict
Point = Tuple[int, int]
def manhattan_distance(point1: Point, point2: Point) -> int:
return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])
def walk(steps: List[str]) -> Set[Point]:
points = set()
current_step = (0, 0)
for step in steps:
... |
name = input("Enter your name: ")
age = int(input("Enter your age: "))
bday = 2120 - age
print("You will be 100 yr in " + str(bday)) |
# Partner 1 Name: Jane Chen
# Partner 2 Name: Daisy Chen
############################
# Assignment Name: GitHub Practice - 2/25/20 - 10 points
import random
def getNRandom(n):
numbers = []
for i in range(n):
number = random.randint(1, 10)
numbers.append(number)
return numbers
def multiplyR... |
"""
CS051P Lab Assignments: Final Project
Author: Hannah Mandell & Kirsten Housen
Date: 12 - 13 - 19
This program displays control over csv file usage, matplotlib, and function creation to better understand numerical
data within large data files. More specifically, this program analyzes Chicago c... |
from __future__ import print_function
from __future__ import division
import numpy
import itertools
import math
def prime_generator():
n = 2
primes_set = set()
while True:
for prime in primes_set:
if n % prime== 0:
break
else:
primes_set.add(n)
... |
# Convolutional Neural Network
# Installing Keras
# Enter the following command in a terminal (or anaconda prompt for Windows users): conda install -c conda-forge keras
# Part 1 - Building the CNN
import keras
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Co... |
# assume X_train is the data where each column is an example (e.g. 3073 x 50,000)
# assume Y_train are the labels (e.g. 10 array of 50,000)
# assume the function L evaluates the loss function
bestloss = float("inf") # Python assgins the highest possible float value
for num in xrange(1000):
W = np.random.randn(10, 30... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Paul Sladen, 2016-03-08, Hereby placed in the Public Domain
"""Pure-python parsing of UIC rolling stock numbers and checksums
Examples:
Test-suite examples from command-line
`$ ./rollingstocknumber.py`
Explicit tests passed on the commandline:
`$ ./rollingstocknumb... |
import cv2
import numpy as np
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def gray_scale(img):
#display the gray scale imag
np.dot(img[...,:3], [0.299, 0.587, 0.114])
cv2.imshow(img)
return img
def main():
#Open the image
img = mpimg.imread(sys.... |
#!/usr/bin/env python
def generate_pin(input):
pinpad = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 1 2 3
# 4 5 6
# 7 8 9
# ULL
# xCoord, yCoord [0, 2]
xCoord = 1
yCoord = 1
pin = ""
for line in input:
for d in line.strip():
print("Read direction: {}".format(d)... |
'''
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime... |
somme = 0
for x in range(1,1000):
if x%3==0 or x%5==0:
somme+=x;
print(somme); |
# Ejercicio 1
# Adivina un número entre 1 y 100
import random
r = random.randint(1,100)
print("Mini-juego de adivinar un número entre 1 y 100")
find = False
for i in range(10):
n = int (input ("Introduzca un número del 1 al 100: "))
if n > 100 or n < 1:
print ("El número tiene que estar en el rango... |
"""Naive Bayes."""
import math
from abc import ABC, abstractmethod
from collections import Counter
from collections import defaultdict
import numpy as np
class NaiveBayes(ABC):
"""Abstract Naive Bayes class."""
@abstractmethod
def predict(self, sample: list):
"""
Compute probability and... |
# filter() is a higher-order built-in function that takes a function and iterable as inputs and
# returns an iterator with the elements from the iterable for which the function returns True.
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]
def is_short(name):
return len(n... |
# integer and float
x = int(4.7) # x = 4
y = float(4) # y = 4.0
print(x)
print(y)
# boolean data type with comparison operators
age = 14
is_teen = age > 12 and age < 20
not_teen = not (age > 12 and age < 20)
print(is_teen)
print(not_teen)
# strings - which are immutable order series of characters
welcome_msg = "He... |
# CONTINUE terminates one iteration of a for() or while loop
# example - 1
fruit = ["oranges", "strawberry", "apple"]
foods = ["apple", "apple", "hummus", "toast"]
fruit_count = 0
for food in foods:
if food not in fruit:
print("not a fruit")
continue
fruit_count += 1
print("Found a fruit!"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Klass:
__x = 10
def __init__(self, value):
self.member1 = value
self._member2 = value
self.__member3 = value
instance = Klass("ahaha")
print("member1=",instance.member1)
print("member2=",instance._member2)
print("member3=",instan... |
import random
high_score = 0
def dice_game():
global high_score
choice = "1"
while choice == "1":
print("Current High Score:", high_score,
" \n1) Roll Dice \n2) Leave Game")
choice = input("Enter your choice: ")
if choice == "1":
ro... |
filename = 'guest_book.txt'
x = ''
with open(filename, 'a') as file_object:
while True:
x = input("Podaj swoje imię: ")
if x == 'q':
break
else:
print("Witaj " + x + "!")
file_object.write("\n")
file_object.write(x)
|
# This import statement imports the Card class from HW4_1
from HW4_1 import Card
# A deck is a list of cards
### NEEDS IMPLEMENTATION!
# The deck is a list of cards. You should remove the _first_ card
# from the deck and return that card. Return None if the deck is empty
# Hint: look at the list.pop() function:
# h... |
"""
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
"""
def longest_k(s, k):
res = s[:k]
l_res = k
cur = res
letters = set(cur)
num_letters... |
"""
A Singleton Sound Manager class
Author: Liz Matthews, 9/20/2019
Provides on-demand loading of sounds for a pygame program.
"""
import pygame
import os
class SoundManager(object):
"""A singleton factory class to create and store sounds on demand."""
# The singleton instance variable
... |
# print("This line will be printed.")
# x = 1;
# if x == 1:
# print('x is 1.')
# zach = 'me'
# print(zach);
# myFloat = 7.0
# print(myFloat)
# anothaFloat = float(9)
# print(anothaFloat)
# one = 1
# two = 2
# three = one + two
# print(three)
# hello = "hello"
# world = "world"
# helloworld = hello + " " + world
#... |
#Problem 1:
i = 1
for i in range(100):
print("forat")
i = i + 1
#Problem 2:
#Part 1
number1 = 5
print(number1)
#part2
number2 = number1 * 0.5
print(number2)
#Problem 3:
#Part 1:
list1 = [5,8,9]
i = 0
for i in range(3):
print(list1[i])
i = i + 1
#Part 2:
for i in range(3):
print((list... |
from helpers import alphabet_position, rotate_character
from sys import argv, exit
def encrypt(text, key):
startingIndex = 0
encrypted = []
for letter in text:
if letter.isalpha() == True:
rotation = alphabet_position(key[startingIndex % len(key)])
encrypted.append(rotate_... |
var = {"key1": "value1", "key2": "value2", "key3": "value3"}
print('key1' in var)
print('hello' in var)
|
var0 = 'I am' + ' 박정태'
print(var0)
var1 = "I am {name}".format(name="박정태")
print(var1)
var2 = "I am {0}".format("박정태")
print(var2)
var3 = "I am {0} I am {name}".format("박정태", name="정보 문화사")
print(var3)
|
def recursive_sum(items):
result = 0
for item in items:
if type(item) is list:
result += recursive_sum(item)
else:
result += item
return result
def main():
test_lists = [
[1, [1], [1, 1], [1, 1, 1], [1, 1, 1, 1]],
[[1], [1], [1], [1], [1], [1], [... |
def str_to_dict(some_str):
"""
:param some_str: str
:return: dict
"""
# YOUR CODE HERE
count_dict = dict()
for letter in some_str:
if not (letter in count_dict.keys()):
count_dict[letter] = some_str.count(letter)
return count_dict
# print('Str to dict:', str_to_di... |
def sum(a, b) -> float:
if a != 0:
return 1 + sum(a - 1, b)
elif b != 0:
return 1 + sum(a, b - 1)
else:
return 0
def main() -> None:
a = int(input())
b = int(input())
print(sum(a, b))
main()
|
def decideIfSymmetric(_number: str):
for i in range(4):
if not _number[i] == _number[3 - i]:
return -1
return 1
def mainFunc():
number = input()
if len(number) == 3:
number = '0' + number
return decideIfSymmetric(number)
print(mainFunc())
|
num = int(input())
maximum = num
while num != 0:
num = int(input())
if num != 0 and num > maximum:
maximum = num
print(maximum)
|
"""
This module provides only the Researcher class
"""
__author__ = 'F. Bidu'
class Researcher(object):
"""
This class holds the data of a researcher
"""
name = ""
articles = []
articlesByKeywords = {}
def __init__(self, name, articles=None):
articles = articles or []
self... |
#!/usr/bin/env python2.7
"""
Created on Fri Jan 22 11:02:51 2016
@author: yanj
"""
def helpFunc():
print '''
processfasta.py: reads a FASTA file and builds a dictionary with all sequences
bigger than a given length
processfasta.py [-h] [-l <length>] <filename>
-h print this message
-l <lengt... |
# Crypto Analysis: Frequency Analysis
#
# To analyze encrypted messages, to find out information about the possible
# algorithm or even language of the clear text message, one could perform
# frequency analysis. This process could be described as simply counting
# the number of times a certain symbol occurs in the give... |
# -*- coding: utf-8 -*-
from listiterator import List, NoSuchElementException
import time
def print_with_iterator (l):
"""
Print elements of a list using an iterator.
:param l: The list to be printed
:type l: dict
"""
iterator = List.ListIterator(l)
fin = False
res =''
while n... |
""":mod:`` module : HashFunctions implements multiple hashing for characters.
:author: `FIL - Univ. Lille <http://portail.fil.univ-lille1.fr>`_
:date: 2021
"""
import random
class HashFunctions:
def __init__(self, nb):
'''
Build hash functions for 128 characters
:param nb: Number of has... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 23:12:55 2020
@author: parthrajauria
"""
# Ans1
#import random
#
#for i in range(10):
# x = random.random()
# print(x)
""" Ans 2 """
#def print_lyrics():
# print("I'm a lumberjack, and I'm okay. ")
#
#def repeat_lyrics():
# print_... |
#! python3
"""
Module for Autonomous code
"""
import time
def init( robot ):
"""
This function is run once each time the robot enters autonomous mode.
"""
# Save real-world timestamp when auto starts.
# All other auto events below are relative to this start time
robot.auto_start_time = time.time( )
def peri... |
"""
测试numpy特性的临时文件
"""
import numpy as np
def test_int():
"""
测试int类型超过最大值的行为
:return:
"""
n = np.zeros(5, dtype=np.uint8)
n[0] = 254
for i in range(3):
print(n[0])
n[0] += 1
class C1:
def __init__(self):
self.num = 100
def say(self):
print(se... |
def sum_array(arr):
dict = {}
sum=0
res = []
for i in range (len(arr)):
dict[i] = arr[i]
sum+= arr[i]
for i in range (len(arr)):
res.append(sum-dict[i])
return res
arr = [3,6,4,8,9]
print(sum_array(arr))
|
def removeduplicates(nums):
if len(nums)<=0:
return 0
j=0
for i in range(1, len(nums)):
if(nums[i] != nums[j]):
j= j + 1
nums[j] = nums[i]
return j+1
a = [1,1,2]
res = removeduplicates(a)
print(res)
ans =[]
for i in range(0,re... |
import heapq
def even(sentence):
#print(sentence)
a =[]
max=0
count =0
currWord = []
s = sentence.split(' ')
for word in s:
if len(word) %2 == 0:
#print(word)
count = len(word)
if count >= max:
#print('here')
if le... |
from BST import BST
def bfs(root):
if root is None:
return
queue = []
queue.append(root)
while len(queue) > 0:
print(queue[0].val)
node = queue.pop(0)
if node.leftChild is not None:
queue.append(node.leftChild)
if node.rightChild is not None:
... |
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = []
stack.append(root)
while stack:
node = stack.pop(-1)
if node:
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right... |
'''
Created on Nov 9, 2017
@author: eliotkaplan
'''
from multiprocessing.pool import ThreadPool
import sys, os, time, datetime
# Disable
def block_print():
sys.stdout = open(os.devnull, 'w')
# Restore
def enable_print():
sys.stdout = sys.__stdout__
class isola_game(object):
def __init__(self, p1, ... |
"""
Liam Duncan
24/01/17, last changed 24/01/17
Course notes compiler
-takes sporatic notes with a given course identifier and writes them
into a new file from the complete 'notes' file
"""
#user cmdline input: new filename and paragraph identifier
newFileName = input('Enter desired filename: ')
textMarker ... |
print('Program removes punctuation from the line you enter', end='')
print(' and tells if it fails to resolve Google\'s URL')
import socket
# define punctuation
punctuations = '''()-[]{};:'"\,<>./?!@#$%^&*_~'''
def remove_punctuation(my_str):
# define punctuation
punctuations = '''!-[]{}();:'"\,<>./?@#$%^&*_~'''
... |
#!/usr/bin/python
# encoding=utf8
# The Goal:
# The program will first prompt the user for a series of inputs a la Mad Libs. For example, a singular noun, an adjective, etc.
# Then, once all the information has been inputted, the program will take that data and place them into a premade story template.
# You’ll need p... |
#!/usr/bin/env python
# coding: utf-8
# In[134]:
# modules we will use
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# read in all our data
nfl_data = pd.read_csv("NFL-merged.csv", skiprows = 0)
# set seed for reproducibility
np.random.seed(0)
# In[135]:
# number of rows and columns
n... |
#! /usr/bin/python
# 面向对象 OOP
# This part takes Warcraft as example.
# Unit, base class of all
class ArmorType:
Unarmored = 0
Light = 1
Medium = 2
Heavy = 3
Hero = 4
Fortified = 10
class AttackType:
Normal = 0
Piercing = 1
Siege = 2
Chaos = 3
MagicDamage = 4
Hero = 5
... |
#time complexity : O(mnlog(n)) . I understood m is for traversing but I didn't understand why nlog(n)? can you please explain?
#space complexity is o(n)
#Approach : First sorting each string in a list and then storing each key and it's values in a hashmap.
# Yes it passed all thetest cases in leet code
class Solution(... |
#!/usr/bin/env python
import sys
import os.path
import argparse
import re
# ----- command line parsing -----
parser = argparse.ArgumentParser(
description="Prints fasta containing only the given set of sequences.")
parser.add_argument("fasta_file", type=str, help="FASTA file.")
parser.add_argument("prefix", type=... |
'''
'''
from validate_email import validate_email
'''
Created Sept 17, 2021
@author Luke Schlueter
'''
class Contact():
# constructs the contact object's fields
def __init__(self):
self.information = {
"first_name": input("What is your first name?\n"),
"last_name": input("Wh... |
class State:
def __init__(self,n, parent):
self.n = n
self.parent = parent
def initialState():
return State(1, None)
def queueIsEmpty():
return len(queue) == 0
def showState(s):
print(s.n)
def expand(s):
if s.n >= 4:
return []
ret = []
ret.append(State(1,s))
r... |
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = '''
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
test
'''
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
"""
Extra Credit 1:
Search online to see what other esc... |
'''
Project: leetcode_python
Author: jinfanglin
Date: 2020-11-15
'''
def validPalindrome(s):
i = 0
j = len(s)-1
while i<j:
if s[i] != s[j]:
return isPalindrome(s,i,j-1) or isPalindrome(s,i+1,j)
else:
i+=1
j-=1
def isPalindrome(s,i,j):
while i<j:
... |
# Recursive sum using divide and conquer approach
def sum(array):
if len(array) == 0:
return 0
return array[0] + sum(array[1:])
print(sum([1, 2, 3, 5, 6, 7, 8]))
|
# Desafio 47 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
cabecalho(47,"Números pares entre 1 e um número positivo qualquer!")
try:
numeroLimite = int(input("Digite um número positivo inteiro: "))
except ValueE... |
# Desafio 31 Curso em Video Python
# Este programa calcula o preço de viagem cujo valor depende da distâcia a ser percorrida.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 31')
print('Este programa calcula o preço de viagem cujo valor depende da distâcia a ser percor... |
# Desafio 46 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
from emoji import emojize as em
def fireworks():
system('clear')
cabecalho(46,"Contagem Regressiva!")
print(em(':balloon::balloon::balloon:'))
... |
# Desafio 3 Curso em Video Python
# Fazer a soma e diferença de valores informados pelo usuário, convertendo a entrada para números!
#By Rafabr
'''O detalhe do exercício e saber como converter caractere de entrada
em uma variável do tipo float para poder realizar a soma dos números'''
import os
os.system('clear')
... |
# Desafio 11 Curso em Video Python
# Calcula a área de uma parede a apartir da largura e altura informadas, e quantos litros de tinta são necessários para pintá-la.
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 11'.center(80))
print('Este pro... |
# Desafio 12 Curso em Video Python
# Recebe o preço de um produto e cálcula uma desconto de 5% eno preço.
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 12'.center(80))
print('Este programa recebe o preço de um produto e calcula uma desconto d... |
# Desafio 6 Curso em Video Python
# Receber um número da usuário e informar o seu dobro, triplo e a raiz quadrada
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 6'.center(80))
print('Este programa mostra o dobro, o triplo e a raiz quadrada de ... |
# Desafio 43 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(43,"Cálculo e Avaliação de IMC")
try:
peso = float(input("Informe o seu peso(Em Kg - Ex.: 80) : ").replace(',','.'))
altura = float(input('Informe sua altura(Em metros - Ex.: 1,73): ')... |
import ps0
#0 - even or odd
#DONE
print("The number 7 is even: {} ".format(ps0.even_or_odd(7)))
print("The number 8 is even: {} ".format(ps0.even_or_odd(8)))
print("The number 0 is even: {} ".format(ps0.even_or_odd(0)))
#1 - number of digits
#DONE
print("0 has {} digits".format(ps0.number_digits(0)))
print("3 has {} ... |
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
self.items.remove(self.items[0])
def peek(self):
return self.items[len(self.items)-1]
def ... |
""" Module with players points logicon. """
import const as con
import game
def punktuj():
""" Initializing the board with points. """
left_of_middle = con.SIZE/2-2
right_of_middle = con.SIZE/2+1
for x_coord in range(con.SIZE):
for y_coord in range(con.SIZE):
#PUNKTOWANIE ZA OKRAG
... |
# 6.0001 Problem Set 3
#
# The 6.0001 Word Game
# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
#
# Name : Ömer Coşkun
# Collaborators : <your collaborators>
# Time spent : <total time>
import math
import random
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
wdlis... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 27 12:07:51 2021
@author: vyaso
"""
#setting up the environment
# load packages
import requests
from bs4 import BeautifulSoup
#definig the URL of site i.e., url of rotten tomatoes
url = "https://editorial.rottentomatoes.com/guide/140-essential-action-movie... |
import time
import random
weapon = ["steel sword", "silver sword"]
enemy = ["dragon", "pirate", 'wizard']
item = ""
enemy_chosed =""
def print_pause(message):
print(message)
time.sleep(1)
def field():
print_pause("You find yourself standing in an open field,filled with "
"... |
# 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 2*1000?
def problem():
num = 2**1000
str_num = str(num)
list_num = list(map(int, list(str_num)))
return sum(list_num)
if __name__ == "__main__":
print(problem())
|
def problem():
sum_num = 0
sum_sqnum = 0
for y in range(1,101):
sum_sqnum += y**2
sum_num += y
return sum_num**2-sum_sqnum
if __name__ == "__main__":
# Load_MREPOS()
problem()
|
import eulertools as et
from eulertools import timeit
"""
0 = 1,1 - 1
1 = 2,3 - 3 5 7 9
2 = 4,5 - 13 17 21 25
3 = 6,7 - 31 37 43 49
"""
def corner_values(n):
if n == 0:
return [1]
last_corner = ((n * 2) + 1)**2
corner_count = [3, 2, 1, 0]
return list(last_corner - (n * 2) * x for x in corner... |
import eulertools as et
from eulertools import timeit
"""
0 = 1,1 - 1
1 = 2,3 - 3 5 7 9
2 = 4,5 - 13 17 21 25
3 = 6,7 - 31 37 43 49
"""
def encrypt(array, key):
e = []
for i in range(0, len(array)):
e.append(chr(array[i] ^ int(key[i % len(key)])))
return e
def cipher():
with open(r'C:\Code\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.