text stringlengths 37 1.41M |
|---|
# Draw Image Example with custom color palette
#
# This example shows off how to draw images in the frame buffer with a custom generated color palette.
import sensor
import image
import time
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE) # or GRAYSCALE...
sensor.set_framesize(sensor.QQVGA) # or QQVGA...
sens... |
## Dictionaries and Loops ##
# Counting Words in Text / Counting Pattern #
# The general pattern to count the words in a line of text is to split the line into words,
# then loop through the wordsand use a dictionary to track the count of each word independently.
counts = dict()
print('Enter a line of text: ')
line =... |
f = open("input", "r")
def calc(n):
tot = 0
while True:
n = n//3 - 2
if n <= 0:
return tot
tot += n
tot = 0
for l in f:
tot += calc(int(l))
print(tot)
|
#!/usr/bin/env python3
import sys
from comp import Comp
from collections import deque
if len(sys.argv) == 1:
print("Usage: python3 both.py <program>")
exit(1)
program = [int(x) for x in open(sys.argv[1], "r").readline().split(',')]
def next_p(p, i):
x, y = p
if i == 1: y -= 1
if i == 2: y += 1
... |
import random
secret = random.randint(1,9)
temp=input("what i mean:")
if isinstance(temp,int):
guess=int(temp)
qaz=1
if guess==secret:
print("我去,你是我肚子里的蛔虫吗")
else:
if guess>secret:
print("猜错了,大了")
else:
print("猜错了,小了")
while guess!=secret and qaz<3... |
bingo = "5"
answer = input("请输入世界上最美妙的数字:")
while True:
if answer == bingo:
break
answer = input("很遗憾,你错了,请再输入一遍(答案正确才能退出游戏):")
print("同道中人啊")
print("game over")
|
import os
import csv
total_votes = 0
candidates = {'Seth': 0, 'Torres': 0, 'Cordin': 0, 'Vestal': 0}
with open('election_data_1.csv') as csv_voting:
csv_votes = csv.reader(csv_voting)
next(csv_votes)
for row in csv_votes:
total_votes +=1
candidates[row[2]]+=1
print(candidate... |
Physics = 80
Chemistry = 100
Maths = 100
Total = Physics+Chemistry+Maths
Per=Total*100/450
print ("Physics:",Physics)
print("Chemistry:",Chemistry)
print("Maths:",Maths)
print("__________________")
print("Total Marks:",Total)
print("Percantage:",Per)
print("__________________")
|
#bulletPointAdder.py - Adds wikipedia bullet points to the start
#of each line of the text on the clipboard
import pyperclip
text = pyperclip.paste()
#Separate lines and add stars
lines = text.split('\n')
#loop through all indexes in the "lines" list
for i in range(len(lines)):
#add star to each string in "lines" li... |
'''
Write a function named printTable() that takes a
list of lists of strings and displays it in a well-
organized table with each column right-justified.
Assume that all the inner lists will contain the
same number of strings.
'''
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol'... |
###############################RK4 method########################################
import numpy as np
def dydx(x, y):
return (x-y**2)
def rungeKutta(x0, y0, x, h):
n = (int)((x - x0)/h)
# Iterate for number of iterations
y = y0
for i in range(1, n + 1):
"Apply Runge Kutta Formulas to f... |
import re
def clean_string(user_input):
"""Remove all punctuation and white space from input string"""
return re.sub(r'[^A-Za-z]', '', user_input.lower())
def palindrome_iterative(user_input):
"""Check if input matches forwards and backwards"""
return user_input == user_input[::-1]
def palindrome_... |
from datetime import datetime
import pandas as pd
def to_datetime(year, month):
year = int(year[:-1])
month = int(month[:-1])
if year >= 63:
year += 1900
else:
year += 2000
return datetime(year, month, 1)
df = pd.read_excel('lt01-a10.xls', skiprows=[0,1,2,3,4,6,7,8,9], skip_foo... |
# Assigning Values to Variables here
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name) |
# def merge_sort(li):
# if len(li) < 2: return li
# m = len(li) / 2
# return merge(merge_sort(li[:m]), merge_sort(li[m:]))
# def merge(l, r):
# result = []
# i = j = 0
# while i < len(l) and j < len(r):
# if l[i] < r[j]:
# result.append(l[i])
# i += 1
# e... |
'''
main.py
Created by Jo Hyuk Jun on 2020
Copyright © 2020 Jo Hyuk Jun. All rights reserved.
'''
def solution(arr, divisor):
answer = []
for i in range(len(arr)):
if (arr[i] % divisor == 0 and arr[i] // divisor > 0):
answer.append(arr[i])
if (len(answer) == 0)... |
'''
main.py
Created by Jo Hyuk Jun on 2020
Copyright © 2020 Jo Hyuk Jun. All rights reserved.
'''
import sys
year = int(sys.stdin.readline())
if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)):
print(1)
else:
print(0) |
'''
main.py
Created by Jo Hyuk Jun on 2020
Copyright © 2020 Jo Hyuk Jun. All rights reserved.
'''
import sys
score_sum = 0
for _ in range(5):
score = int(sys.stdin.readline())
if score < 40:
score = 40
score_sum += score
print(score_sum // 5) |
'''
main.py
Created by JO HYUK JUN on 2022
Copyright © 2022 JO HYUK JUN. All rights reserved.
'''
def solution(numbers, k):
return numbers[(3 + (k - 2) * 2) % len(numbers) - 1] |
#!/usr/bin/python
import numpy as np
import cv2
import imutils
class ColourDescriptor:
def __init__(self,bins):
self.bins=bins #the number of bins for our histogram
def describe(self,image):
image=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
features=[]
(h,w)=image.shape[:2] #th... |
# David Li
# August 17,2015
print('This program will compute the sum of the first n integers')
n=int(input('Enter the number of integers: '))
sumN = n*(n+1)/2
print(sumN)
|
# David Li
# August 31, 2015
# AllSubLists.py
# This program will generate all sublists
def allSublists(data):
sublists= []
#Generate all of the sublists of data from length 1 to len(data)
for length in range(1, len(data) + 1 ):
#Generate the sublists starting at each index
for i in range(... |
# David Li
# August 18, 2015
# This program will find the distance bewteen two points
import math
class point(object):
def __init__(self, x,y):
#define x and y variables
self.X= x
self.Y = y
def __str__(self):
return ("Point(%s,%s)"%(self.X, self.Y))
print("This program will ... |
''' to find the area of circle'''
r=eval(input("enter the radius of circle"))
a=2*3.14*r
print("area of circle",a)
|
from shapely.geometry import Point, Polygon, LineString
def createPointGeom(x_coord, y_coord):
"""
Function should create a shapely Point geometry object and
return that. Demonstrate the usage of the function by
creating Point -objects with the function.
:param x_coord:
:param y_coord:
:r... |
'''
This outline will help solidify concepts from the Variables lesson.
Fill in this outline as the instructor goes through the lesson.
'''
#1)
#Make an example variable of each of the types of variables (int, float,
#string, boolean and list):
#int
a = 8
#float
a = 1.16
#string
a = "hello"
#boolean
a = True
a =... |
"""
Created on Feb 4 2019 08:05 AM
@author : S C V S L S RAVI KIRAN
"""
'''
Split the input - Python
Question : https://practice.geeksforgeeks.org/problems/split-the-input-python/1/?track=fork-python
'''
"""
{
def main():
testcases=int(input()) #testcases
while(testcases>0):
inPutS() #the function tha... |
"""
Created on Feb 4 2019 02:38 PM
@author : S C V S L S RAVI KIRAN
"""
'''
Mark Even and Odd - Python
Question : https://practice.geeksforgeeks.org/problems/mark-even-and-odd/1/?track=python-module-2
'''
"""
{
#Initial Template for Python 3
//Position this line where user code will be pasted.
# Driver Code
def main()... |
"""
Created on Feb 24 2019 06:46 PM
@author : S C V S L S RAVI KIRAN
"""
'''
Jumping through While - Python
Question : https://practice.geeksforgeeks.org/problems/jumping-through-while-python/1/?track=python-module-2
'''
"""
{
#Initial Template for Python 3
//Position this line where user code will be pasted.
# Driver... |
def type_analysis(year):
"""
Takes a valid year and outputs its type (Leap, later, middle, previous ou anomalous).
:param year: the year to analyze.
:return: binary list with the year type (string) and its list index (0-4).
"""
types = ['Leap', 'Later', 'Middle', 'Previous', 'Anomalous']
... |
"""
The goal: to build the biggest token dictionary in Brazilian Portuguese, and the most important,
garanting quality.
"""
from node_tree import NodeTree
class CrawlerTree(NodeTree):
"""
We aim to build a beautiful Tree of text's documents from the internet.
So, expect each node to be a d... |
import hashlib
import os
# Verify a password against a hash and salt
def verify_password(password, hashstring):
salt = bytes.fromhex(hashstring.split("$")[0])
hash = bytes.fromhex(hashstring.split("$")[1])
hash2 = hashlib.scrypt(bytes(password, 'utf-8'), salt=salt, n=16384, r=8, p=1)
if hash == hash2:
... |
'''
def is_odd(x):
return x % 2 == 1
L = [1,2,3,4,5,6,7,8,9]
print(list(filter(is_odd,L)))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty, ['a', '', 'c'])))
'''
def is_palindrome(x):
s = 0
source = x
while x > 0.1:
temp = x % 10
x = int(x / 10)
s = s ... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
a1=0
o1=0
app1=0
org1=0
for i in range(0,len(apples),1):
a1=a+apples[i]
if a1>=s and a1<=t:
... |
import math
import matplotlib.pyplot as plt
import numpy as np
# 資料輸入
CurrentPrice = float(input('Please enter the current price: '))
ParValue = float(input('Please enter par value: '))
Period = int(input('Please enter total period: '))
# 宣告 Forward Table
ForwardTable = [[0 for _ in range(Period+1)] for _ i... |
#Clinton Caldwell Lab 3
#Python Sorting Algorithms
def printPreSortList(sortType, a):
print("Pre-",sortType,"Sort:\n",a,)
def printPostSortList(sortType, a):
print("Post-",sortType,"Sort:\n",a,)
print("----------\n")
#Insertion Sort ----------------------------------
def insertionSort(a):
printPre... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word, count=0):
# Look at the first and second letters... |
#
# #Creating a variable
#
# x = 10 #Type of integer
#
# print("hello world")
#
# y = 3.6 #float
# name = "Sparta" #String
#
# print(x)
#
# print(y)
# print(x + y)
#
# print(type(name))
#
# print(x + name) #You can't run a integer with a string.
# print(str(x) + name) #This is a way to fix that. Casting the integer val... |
class Dog:
animal_kind = "canine" #Class variable
def __init__(self, name, colour): #initialisation
self.name = name
self.colour = colour
def bark(self):
return "woof woof"
def sleep(self):
return "snooring"
def breath(self):
return "breathing"
def ru... |
def please_conform_one_pass(caps):
if len(caps) == 0:
print('There is no persons')
else:
caps += [caps[0]]
for i in range(1, len(caps)):
if caps[i] != caps[i-1]:
if caps[i] != caps[0]:
if caps[i] == caps[i+1]:
a = 0
... |
from util import entropy, information_gain, partition_classes
import numpy as np
import ast
class DecisionTree(object):
def __init__(self):
# Initializing the tree as an empty dictionary or list, as preferred
#self.tree = []
self.tree = {}
pass
def learn(self, X, y):
# TODO: Train the decision tree... |
# Workout Tracker - Marshall Ferguson - 7/2020
# Imports
import csv
import matplotlib.pyplot as plt
# TODO - take input from the command line
# TODO - ask the user the name of exercise, sets, reps, and weight
# TODO - calculate the volume lifted, the total sets, and total reps
print("Welcome to the Workout... |
from abc import abstractmethod, ABC
from typing import List, Optional
from kivy import Logger
from kivy.app import App
from ds.Purchase import Purchase
class ShoppingCartListener(ABC):
@abstractmethod
def on_change(self):
pass
class ShoppingCart:
#
# empty constructor
#
def __init... |
import pandas as pd
import numpy as np
import math
import json
import matplotlib.pyplot as plt
import seaborn as sns
def id_mapper(df,id_column):
'''
This function is for mapping user's id to int.
--------
Input:
df: the pandas dataframe which contain user id column.
id_column: title(str)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# challenge 157 easy
input1 = """
O
O-X
-XX
O--
"""
input2 = """
X
XO-
OO-
---
"""
input3 = """
O
OXOX
OOXX
--O-
----
"""
def build_board(input):
raw = input.strip().split('\n')
next_move = raw.pop(0)
board = [[i for i in row] for row in raw]
return (board, ... |
"""
Leetcode
209. Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the minimal length
of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than
or equal to target. If there is no such subarray, return 0 instead.
... |
"""
Leetcode
1004. Max Consecutive Ones III
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,... |
"""
Leetcode:
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:... |
"""
Leetcode
643. Maximum Average Subarray I
Given an array consisting of n integers, find the contiguous subarray
of given length k that has the maximum average value. And you need to
output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
... |
import os
import csv
#create a path to the csv
path = os.path.join("Resources", "budget_data.csv")
outfile = os.path.join("Analysis", "PyBank.txt")
#generate empty lists
total_months = []
profit_loss = []
monthly_change = []
#read csvs and append data to the empty lists
with open(path, "r") as file:
csv_reader... |
# import libraries
from bs4 import BeautifulSoup
import requests
# accept the city name
city = input('Enter the city name to know its weather: ')
city = f"Temperature in {city}"
# search the city on web
url = f'https://www.google.com/search?&q={city}'
# get the data for the provided city
r = requests.get(u... |
s = "you are awesome!"
print(s)
a = """ you
are amazing ! """
print(a)
#get 2nd item
print(s[2])
#print string 2 times
print(s * 2)
print(len(s)) |
'''
BMI Calculator with Python
The body mass index is calculated by dividing an individual’s weight in kilograms by their height in meters,
then dividing the answer again by their height. Now let’s see how to create a BMI calculator with Python:
'''
#take user inputs
height = float(input(' Enter your height in centim... |
값 =int(input("수를 입력하시오"))
int = 1
sum=0
for i in range(1, 값 +1 , 1) :
sum=sum+i
print(sum)
|
#!/usr/bin/env python
'''
This script loads a textfile in csv format generated by bag2csv script.
The csv file should have the first element of each row the time and represents two things:
a) if no rows are given --> it generates the plot of all the rows against the time
b) if a list of rows are... |
"""Ejercicio 1:
Vamos a crear un Cliente. Sus atributos son: nombre, edad y DNI.
*Construir los siguientes métodos para la clase:
*Un constructor, donde los datos pueden estar vacíos.
-Muestra los datos de la persona.
-Devuelve un valor lógico indicando si es mayor de edad."""
class Persona:
def __init__(s... |
# -*- coding: utf-8 -*-
"""
Utility functions.
"""
import crcmod.predefined
"""
Computes the CRC-16 check-sum of a string.
"""
crc16 = crcmod.predefined.mkCrcFun('crc-16')
def unpad_integer(integer, bits=7):
"""
Decodes a bit-padded integer such as the one used for ID3v2 tag sizes.
@param bytearray integer
... |
# Contents:
# Compare Closely!
# Compare... Closelier!
# How the Tables Have Turned
# And
# Or
# Not
# This and That (or This, But Not That!)
# Mix 'n' Match
# Conditional Statement Syntax
# Else Problems, I Feel Bad for You, Son...
# I Got 99 Problems, But a Switch Ain't One
# The Big If
print("### Compare Closely! #... |
# Contents:
# Introduction to Lists
# Access by Index
# New Neighbors
# Late Arrivals & List Length
# List Slicing
# Slicing Lists and Strings
# Maintaining Order
# For One and All
# More with 'for'
# This Next Part is Key
# New Entries
# Changing Your Mind
# Remove a Few Things
# It's Dangerous to Go Alone! Take This
... |
#Connor Crowe
#Tic Tac Toe
#11/11/19
X = "X"
O = "O"
NUM_SQUARS = 10
TIE = "TIE"
EMPTY = " "
def instructions():
"""Display Game Instructions"""
print(
"""
Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
This will be a showdown between your human brain and my silicon processor.
Y... |
def getTalk(type="shout"):
# We define functions on the fly
def shout(word="yes"):
return word.capitalize()+"!"
def whisper(word="yes") :
return word.lower()+"...";
# Then we return one of them
if type == "shout":
# We don't use "()", we are not calling the function,
... |
# Autor David Yair Fernández Salas
# Este programa te dice cual boletos quieres y te dice el costo.
"""Escribe la función calcularPago que recibe como parámetros el número de boletos que quiere comprar para cada zona y regresa el
total a pagar."""
def CalcularPago(boletosA, boletosB, boletosC):
TotalBoleto... |
from collections import namedtuple
players = {0: 'X', 1: 'O'} # X is Player, O is CPU
'''
help command
'''
def help(game):
print("Supported Commands: ")
for command in commands:
print(command, commands[command])
'''
undo command
'''
def undo(game):
game.undo() #In place
'''
reset command
'''
def... |
# Created by : James Lee
# Created on : June 2019
# Deck class
# The deck class holds all the cards
# It can return a card via its drawCard method
import random
class deck:
#Constructor
def __init__(self):
self.__deckOfCards = []
self.__runningCount = 0
# Shuffles deck
def shuffle(self):
rando... |
#!/usr/bin/env python2.7
# -*- encoding: utf-8 -*-
from random import randint
class GeneticAlgorithm( object ):
'''
Classe de implementação do algoritmo genético
'''
# Attributes
populationAmount = 0
genesAmount = 0
generations = 0
crossingRate = 0
mutationRate = 0
adjacencyMatrix = None
colors = []
po... |
# Link to the problem: https://www.codechef.com/MARCH18B/problems/BIGSALE
def main():
T = int(input())
while T:
total_loss = float(0)
T -= 1
N = int(input())
while N:
N -= 1
pqd = []
pqd = list(map(int, input().split()))
inc_price... |
# Link to the problem: https://www.codechef.com/COUT2018/problems/ADI
def main():
N = int(input())
ans = []
while N:
N -= 1
string = input()
if "a" in string and "e" in string and "i" in string and "o" in string and "u" in string:
ans.append(string)
if ans:
... |
"""
This module provides classes for representing defender strategy
"""
from enum import Enum
from model.ActionType import ActionType
from base_strategy import BaseStrategy
from point import Point
from vector import Vector
__all__ = ['DefenceStrategy']
class StrategyState(Enum):
undefined = 1
move_to_defe... |
#!/usr/bin/python
class Train:
def __init__(self, WheelCount, speed):
self.WheelCount = WheelCount
self.speed = speed
def go(self):
print "running at "+str(self.speed)+" KM per hour"
def stop(self):
print " engaging brakes on "+str(self.WheelCount)+ "wheel"
Train1 = Train(8, 280)
... |
#Π17041-Python 3.6.4
import random
def triplet_sum(array,req_sum):
triplets = []
if len(array) < 3:
return None
for mid in range(1, len(array)):
low = 0
high = len(array) - 1
while low < mid and high > mid:
if array[low] + array[mid] + arra... |
# Car_Purchase_Amount
import streamlit as st
import pandas as pd
import numpy as np
def main() :
st.title('자동차 구매 가격 예측')
menu = ['Dataset', 'X_data, y_data'] # 메뉴 카테고리
choice = st.sidebar.selectbox('메뉴', menu) # 메뉴를 표시해라
print(choice) # 사람이 볼수있게 디버깅함
df = pd.read_csv('data/Car_Purch... |
'''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.
No final mostre:
A) QUANTAS VEZES APARECEU O VALOR 9
B) EM QUE POSICAO FOI DIGITADO O PRIMEIRO VALOR 3
C) QUAIS FORAM OS NUMEROS PARES'''
num = (int(input("Digite um número: ")),
int(input("Digite um número: ")),
int(input("Digit... |
'''Crieum programa que gerencie o aproveitamento de um jogador de futebol.
O programa vai ler o nome do jogador e quantas partidas ele jogou.
Depois vai ler a quantidade de gols feitos em cada partida.
No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.'''
jogado... |
'''Crie um programa que tenha uma função chamada maior(),que receba varios parametros
com valores inteiros.
Seu programa tem que analisar todos os valores e dizer qual deles é maior.'''
from time import sleep
def maior(*num):
count = 0
maior = 0
print("-=" * 35)
print("Analisando os valores passados .... |
'''Faça um programa que leia nome e peso de várias pessoas guardando tudo em uma lista. No final mostre:
A)QUANTAS PESSOAS FORAM CADASTRADAS
B) UMA LISTAGEM COM AS PESSOAS MAIS PESADAS
C) UMA LISTAGEM COM AS PESSOAS MAIS LEVES.'''
pessoas = list()
dados = list()
maior = menor = count = 0
pessoaMais = " "
pessoaMenos... |
#!/usr/bin/env python3
"""
Kattis: Last Factorial Digit
August 12, 2019
Description: For each value of n, print the last digit of n!
"""
import sys, math
num_test_cases = int(sys.stdin.readline().strip())
for i in range(num_test_cases):
num = int(sys.stdin.readline().strip())
num_fac = math.factorial(num)
... |
#!/usr/bin/env python3
"""
Kattis: ABC
July 9, 2019
Input: The first line contains the three positive
integers A, B and C, not necessarily in that order.
The three numbers will be less than or equal to 100.
The second line contains three uppercase letters ’A’,
’B’ and ’C’ (with no spaces between them) representing... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import random
#defining a base class
class Rectangle:
#the _init_() function
def __init__(self,width,length):
self.width = width#define width
self.length = length#define length
#define the area of a rectangle
def area(self):
area... |
"""
A set of functions to deal with knights tour problems
"""
import operator
import math
def allowed_pos(pos, board):
moves = [(i,j) for i in [-1,1,-2,2] for j in [-1,1,-2,2] if
abs(j)!= abs(i)]
allowed_pos = [tuple(map(operator.add,pos,move)) for move in moves]
allowed_pos = [x for x in allo... |
# -*- coding: utf-8 -*-
"""
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
"""
from typing import List
class Solution:
def plusOne(self, digits: List[int]) -> Lis... |
#!/usr/bin/python3
# https://stackoverflow.com/questions/35402609/point-on-circle-base-on-given-angle
import sys
from math import cos, sin, pi
def point_on_circle(center, angle, radius):
'''
Finding the x,y coordinates on circle, based on given angle
'''
#center of circle, angle in degree and rad... |
class Employee:
employee_count = 0
employee_salary = 0
def __init__(self, n, f, s, d):
self.name = n
self.family = f
self.salary = s
self.department = d
Employee.employee_count = Employee.employee_count + 1
Employee.employee_salary = Employee.employee_salary ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 00:05:33 2018
@author: justin
"""
from LinkedList import LinkedList, Node
def intersect(l1, l2):
h1 = l1.head
h2 = l2.head
len1 = l1.size()
len2 = l2.size()
if len1 < len2:
shorter = h1
longer = h2
else:
shorter = h2
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 20 23:45:00 2018
@author: justin
"""
from LinkedList import LinkedList, Node
def sumList(l1, l2):
h1 = l1.head
h2 = l2.head
ret = LinkedList()
carry = 0
while h1 != None or h2 != None:
total = 0 + carry
if h1 != None:
... |
"""3D CNN network implementation"""
from torch import nn
import torch
from collections import OrderedDict
class MLPConv(nn.Module):
"""MLP Conv layer as described in Section 4.2 / Fig. 3 of https://arxiv.org/pdf/1604.03265.pdf"""
def __init__(self, in_channels, out_channels, kernel_size, stride):
"""
... |
num=int(input("Ingrese un número: "))
while num>0:
print(num, end=", ")
num-=1 |
class Employee():
ID = 0
def __init__(self, name, surname, age, gender):
self.id = Employee.getID()
self.name = name.split(" ")[0]
self.names = name.split(" ")[1:]
self.surname = surname
self.age = age
self.gender = gender
def get_fullna... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 12:29:59 2020
@author: mh iyer
Linear Regression with Two variables
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# get cost given parameter and ground truth values
# hypothesis = candidate*x
# cost = sum_over(square_of(h(... |
cont = 0
total = 0
totmil = 0
menor = 0
barato = ''
while True:
produto = str(input('Nome do Produto: '))
preço = float(input('Preço: R$'))
cont = cont + 1 # assim que ele ler o preço,vai começar a contar mais um.
total +=preço
if preço > 1000:
totmil += 1
if cont == 1: # isso é,se for... |
'''from random import randint
from time import sleep
computador=randint(0,5)#Vai pensar num numero de zero até cinco
print('=-=' * 20)
print('Vou pensar num numero de 0 a 5. Tente adivinhar....')
print('=-=' *20)
jogador=int(input('Em que número eu pensei? '))
print('PROCESSANDO....')
sleep(2)
if jogador == computador:... |
d=float(input('Quanto de dinheiro você tem na carteira:R$ '))
dolar=d/5.52
e=d/6.00
print('Com {:.2f} você pode comprar US${:.2f}.'.format(d,dolar))
print('Com {:.2f} você pode comprar EURO {:.2f}.'.format(d,e))
#Estamos passando por um vírus invisível,por isso está tão alto.Xô#Coronaaa
|
lista=[] #conjunto vazio
for c in range(0,5):
n=int(input(f'Digite um valor: '))
if c==0 or n>lista[-1]:#se ele é o primeiro ou maior que o ultimo
lista.append(n)
print('Adicionando ao final da lista...')
else:
pos=0
while pos <len(lista):#vai da posição zero até a última
... |
from time import sleep
print('\033[1;33m =-=\033[m' * 20)
print('\033[1;31m ANALIZANDO O TRIÂNGULO....\033[m')
print('\033[4;36m =-=\033[m' * 20)
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo Segmento: '))
r3 = float(input('Terceiro Segmento: '))
sleep(3)
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < ... |
estados=list()
resp=''
while True:
estados.append(str(input('Digite o Estado: ')).strip().upper())
if resp in estados:
print(f' O Estado {estados[0]} tem bastante gente com covid')
|
n=0
s=0
nome=''
while True:
n=str(input('Digite algum nome:'))
if n == 'José':
break
nome+=n
'''print('A será {}'.format(n,s))
IREMOS aprender daqui adiante com F string,uma nova pep que o
python faz,não precida por format mais,colocamos f depois aspas.'''
print('Seu nome é {}'.format(n))
|
from datetime import date
atual= date.today().year
totmaior=0
tomenor=0
for pess in range(1,8):
nasc=int(input('Em que ano a {}ª pessoa nasceu: '.format(pess)))
idade=atual-nasc
if idade >=21:
totmaior=totmaior+1
else:
tomenor=tomenor+1
print('\033[31mAo todo tivemos {} pessoas maiores\0... |
from datetime import date
from time import sleep
nome=input('Qual seu nome? ').upper()
idade=int(input('Qual sua idade? '))
time=input('Qual seu time: ').upper()
atual=date.today().year
anos_time=int(input('Em que anos seu time foi fundado: '))
resultado_anos=atual - anos_time
print(f'Seu nome é {nome}, tem {idade} ano... |
n1=int(input('Digite um número: '))
s=n1+1
a=n1-1
print('Analizando o valor {},seu sucessor é {} e o antecessor é {}'.format(n1,s,a))
|
somaidade=0
mediaidade=0
maioridadehomem=0
nomevelho=''
totmulher=0
for p in range(1,5):
print('------{}ªpessoa------'.format(p))
nome=str(input('Nome: ')).strip().upper()
idade=int(input('Idade: '))
sexo=str(input('M/F: '))
somaidade=somaidade+idade
if p == 1 and sexo in 'Mm':
maioridad... |
n=int(input("Enter range:"))
l=[]
for i in range(0,n):
x=int(input("Enter:"))
l.append(x)
temp=l[0]
l[0]=l[n-1]
l[n-1]=temp
print(l)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.