text stringlengths 37 1.41M |
|---|
'''
Count-combination features in Pandas.
Intended for use on Amazon access data.
'''
import pandas as pd
import itertools as it
def get_counts(df, fields):
'''
Create value-count features for combinations of fields in a data frame.
Counts are taken over combinations of the values in fields.
Args:
... |
import time
import secrets
# Helper Functions:
# This function parses a string into an array of bytes
def toBytes(s:str):
return s.encode("utf-8")
# This function converts an array of bytes back to a String
def toString(b):
return b.decode("utf-8")
# These functions take care of user input and prompt user f... |
# 1.3 URLify
# Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the 'true' length of the string. (Note: if implementing in Java, please use a character array so that you can perform this ... |
import matplotlib.pyplot as plt
class FenetreCourbe(object):
"à partir de listes de valeurs (les tailles des populations relevées à intervalles réguliers) affiche des courbes d'évolution de ces population en fonction du temps"
def __init__(self,donnees=[24,58,65,69,32,14,78,25,3,8]): ## Cette liste ne sert qu'à i... |
def foo(x, y, result):
if result is None:
return (y + 1) ^ x ^ 1337
elif x is None:
return result ^ (y + 1) ^ 1337
elif y is None:
return (result ^ x ^ 1337) - 1
def bar(x, y, z, result):
if result is None:
return (z + 1) * y + x
elif x is None:
return result... |
list=["maria", "pepe", "Marta", "Antonio"]
print(list[:])
print(list[3])
print(list[-2])
#cuando utilizamos el - empieza desde atras y el primer elemento es -1; en lugar 0
print(list[0:3])
#porciones, incluye el primer elemento y omite el ultimo indicado en el print
print(list[2:])
#ejecuta desde el v... |
#Continue, Pass y else
#Continue: indica a donde continuar la intruccion y bucle. Salta a la sig interaccion de bucle
#Pass se usa para definir clases (ej: nulas) y casos concretos. Devuelve "null" como si no ejecutara
#Pass cuando quieres desarrollar algo despues y usas este pass para continuar trabajando
for le... |
#Generate hashes of string data using 3 Algorithms from hashlib
import hashlib
str1="Ambar Mittal"
#Using sha1 Algorithm
Hashed_1=hashlib.sha1(str1.encode()).hexdigest()
print("Hashed Password using sha1:",Hashed_1)
#Using blake2b Algorithm
Hashed_2=hashlib.blake2b(str1.encode()).hexdigest()
print("Hashed... |
### Project Description ###
# The project will be a Kinect-supported game called "Shape-Matching Game".
# A shape formed by connecting multiple circles will be displayed on the screen,
# and the player gains points by touch all circles simultaneously with their
# hands, feet, and/or head. The game will also support m... |
''' REPLACING ALL SPECIAL CHARACTERS'''
STR1 = input()
STR2 = " "
for i in STR1:
if i in "!@#$%^&*":
STR1 = ""
else:
STR2 += i
print(STR2)
|
'''GIVEN A NUMBER, FIND THE PRODUCT OF THE DIGITS'''
NUM = int(input())
COUNT = 0
PROD = 1
COUNT2 = 0
if NUM == 1:
print(1)
if NUM == 2:
print(2)
if NUM == 3:
print(3)
if NUM == 4:
print(4)
if NUM == 5:
print(5)
if NUM == 6:
print(6)
if NUM == 7:
print(7)
if NUM == 8:
print(8)
if NUM == ... |
import json
import urllib.request as jur
j_url = input("Enter location: ")
data = jur.urlopen(j_url).read().decode()
print('Retrieving', j_url)
print('Retrieved', len(data), 'characters')
info = json.loads(data)
print('User count:', len(info))
sum=0
total=0
for comment in info["comments"]:
sum = sum + int... |
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
--
>>> line.lower()
'have a nice day'
>>> line.lower().startswith('h')
True
print('Hi There'.lowe())
>>>hi there
---
**************
stuff = "Hello World"
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'f... |
import re
x = "My 2 favorite numbers are 19 and 42"
y = re.findall("[0-9]+",x)
print(y)
o<<<['2', '19', '42']
|
"""
File: slotmachine.py
Author: David
Python Final Project (9/23/19)
Create a Slot Machine GUI-based application
This application should be GUI-based and contain the following features:
- A label that serves as the title of your app
- A command button that will run the application
- Fields and labels for the... |
import re
def testPasswordStrength(password):
eightCharsLongRegex = re.compile(r'[\w\d\s\W\D\S]{8,}')
upperCaseRegex = re.compile(r'[A-Z]+')
lowerCaseRegex = re.compile(r'[a-z]+')
oneOrMoreDigitRegex = re.compile(r'\d+')
if not eightCharsLongRegex.search(password):
return False
elif n... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 12:41:33 2019
@author: Gabriel Silva, 100451
Vertex cover algorithm:
Initialize all possible solutions
while there are solutions
Check if current solution is valid:
if valid:
count the number of vertices use... |
"""
Translate a RNA into peptides
Calculate a peptides could be translated from in total how many RNAs
"""
codon_table_file =open('RNA_codon_table.txt')
CODON_TABLE = {}
REVERSE_CODON_TABLE ={}
for line in codon_table_file.readlines():
# Construct CONDON TABLE dict
entry = line.split()
if len(entry) > 1:
... |
"""
Calulates simple equations for use in basic electrical engineering
"""
def main():
print "Welcome!"
print ""
print "--------------------"
print "1: Calculate using Ohm's Law"
print "2: Calculate a resistor's value"
print "--------------------"
print ""
choice = int(raw_input("Enter ... |
删除排序链表中的重复元素
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
h = head
if h == None:
return []
while h.next:
... |
生命游戏
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
q = copy.deepcopy(board)
hang = len(board)
lie = len(board[0])
for i in range(hang):
... |
下降路径最小和
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
row = len(A[0])
res = [[1000 for i in range(row)] for j in range(len(A))]
for i in range(row):
res[0][i] = A[0][i]
for i in range(1,len(A)):
for j in range(row):
... |
两个数组的交集 II
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
list1 = []
for i in nums1:
if i in nums2:
list1.append(i)
nums2.pop(nu... |
子域名访问计数
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
dict = {}
for i in range(len(cpdomains)):
left,right = cpdomains[i].split(" ")
list = []
list = right.spli... |
打家劫舍 III
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
def dp(root):
if not root:
return [0,0]
... |
二叉搜索树的最小绝对差
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
res = []
def dp(root):
if root... |
斐波那契数
class Solution:
def fib(self, N: int) -> int:
if N == 0:
return 0
if N == 1:
return 1
list1 = [0,1]
for i in range(2,N+1):
list1.append(list1[i-1] + list1[i-2])
return list1[-1]
|
两数之和 II - 输入有序数组
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
len1 = len(numbers)
import bisect
s = set()
for i in range(0,len1):
if numbers[i] in s:
continue
for j in range(i+1,len1):
... |
比特位计数
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
list1 = [0 for i in range(num+1)]
for i in range(1,num+1):
n = i
cont = 0
if list1[i] == 0:
while n:
... |
4的幂
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
j = 1
for i in range(32):
if j == num:
return True
elif j > num:
return False
j = j * 4... |
递增子序列
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res = set()
len1 = len(nums)
def dfs(nums,a):
if len(a) >=2:
res.add(tuple(a[::]))
for j in range(len(nums)):
if nums[j] >= a[-1]:
... |
字符串中的第一个唯一字符
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
q = list(set(s))
lis = []
for i in range(len(q)):
if s.count(q[i]) == 1:
lis.append(s.index(q[i]))
if lis:
re... |
反转链表 II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
sum1 = 0
x = head
flag = ListNode(0)
... |
print("DISCLAIMER: Only merge sort works with string arrays.")
#import statements
import time
from generate import gen
from importing import importlist
from msort import mergesort
from bubble import bubblesort
from insertion import insertionsort
from linearsearch import linearsearch
from binarysearchtree import btsear... |
'''
uzatılmış öklidi fonksiyonu ile d hesalıyoruz
Bir sayı hangi sayı ile çarpılırsa totient fonk değerinin modu 1 olur
d*e=1modT
'''
def u_oklid(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = u_oklid(b % a, a)
return (g, x - (b // a) * y, y)
'''
en büyük ortak bölen
'''
def obeb(... |
#List comprehensions
squares = [x**2 for x in range(10)]
print(squares)
print([(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y])
#Create a list with values doubled
vec = [-4, -2, 0, 2,4]
print([x*2 for x in vec])
#Filter the -ve numbers from list
print([x for x in vec if x >= 0])
# Call a method on e... |
#car pooling question asked in VArious commapnies
# GOOGLE , AMAZON , UBER , Microsoft
class Solution:
def carPooling(self, trips,capacity):
timestamp = [0] * 1001
for trip in trips:
timestamp[trip[1]] += trip[0]
timestamp[trip[2]] -= trip[0]
used_capacity = 0
... |
# This Question is asked by uber for sde Role
#Pig Latin
# If string contain aeiou add ma to end
# if constrant remove frist element and add to the end with ma
# add a for every element
class Solution():
def toGoatLatin(self,S):
temp = S.split(" ")
counter = 1
result = []
vowels = (... |
#You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
#Merge all the linked-lists into one sorted linked-list and return it.
#Example 1
#Input: lists = [[1,4,5],[1,3,4],[2,6]]
#Output: [1,1,2,3,4,4,5,6]
#Explanation: The linked-lists are:
#[
# 1->4->5,
# 1->3->4,
# 2->6
#]... |
# Task: check if Linked List is a Palindrome
class Node(object):
"""Node in a linked list."""
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
"""Linked List using head and tail."""
def __init__(self):
self.head = None
self.tail ... |
print("Determina o mdc de dois números n > 0 e m > 0\n")
# leia o valor de n
n = int(input("Digite o valor de n (n > 0): "))
# leia o valor de m
m = int(input("Digite o valor de m (m > 0): "))
# aqui começa o algoritmo de Euclides
anterior = n
atual = m
resto = anterior % atual
while resto != 0:
anterior ... |
# Узнайте у пользователя число n.
# Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
num = (input("Введите число: "))
n_1 = int(num)
n_2 = int(num + num)
n_3 = int(num + num + num)
rez = n_1 + n_2 + n_3
print(rez)
|
from tkinter import *
import tkinter
from tkinter import ttk
#frame raising function
def raise_frame(frame):
frame.tkraise()
window = Tk()
f1 = Frame(window,bg='#05386B')
f2 = Frame(window,bg='#05386B')
f3 = Frame(window,bg='#05386B')
window.rowconfigure(0,weight=1)
window.columnconfigure(0,weight=1)... |
# Циклический сдвиг влево
# Пример 1
# 1 2 3 4 5
# 2 3 4 5 1
import random as r
n = int(input())
a = [r.randint(-10, 10) for i in range(n)]
print(*a)
t = a[0]
for i in range(n - 1):
a[i] = a[i + 1]
a[-1] = t
print(*a) |
from control import Control
import tkinter as tk
import time
# port = "COM5"
# cont = Control(port)
# These functions use the control class to send data through the com port
def forward(event):
cont.send("1")
def back(event):
cont.send("0")
def leftu(event):
cont.send("3")
def leftd(event):
con... |
#!user/bin/env python
import string
import keyword
alphas = string.letters + '_'
nums = string.digits
kwlist = keyword.kwlist
print 'Welcome to the Identifier Checker v1.0'
myInput = raw_input('Identifier to test?')
if myInput[0] not in alphas:
print '''invalid:first symbol must be alphabetic'''
else:
for ot... |
#-*-coding:UTF-8 -*-
class Employee:
'ԱĻ'
empCount = 0
def __ini__(self,name,salary):
self.name = name
self.salary =salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" %Employee.empCount
def displayEmploy(self):
print "Name: " ,self.name,",Salary: ",self.salary
print "... |
class Stack:
def __init__(self):
self.stack = []
def push(self, item): # положить элемент в стек
self.stack.append(item)
def isEmpty(self): # вернуть True, если стек пуст, иначе вернуть False
if self.stack == []:
return True
return False
def pop(... |
# Módulo criado para o exercício 107.
def aumentar(valor, taxa):
'''
=> Função que calcula um valor com aumento.
:param valor: Valor informado pelo usuário.
:param taxa: Taxa de aumento (Ex.: Para calcular um aumento de 10%, digitar 10.
:return: Retorna o valor acrescido do aumento.
'''
au... |
# Faça um programa que leia o peso de cinco pessoas. No final, mostre qual
# foi o maior e o menor peso lidos.
maior = 0
menor = 0
for pessoa in range(1, 6):
peso = float(input(f"Digite o peso da {pessoa}ª pessoa (kg): "))
if pessoa == 1:
maior = peso
menor = peso
else:
if peso > ma... |
# Crie um programa que leia dois valores e mostre um menu na tela:
# [ 1 ] somar
# [ 2 ] multiplicar
# [ 3 ] maior
# [ 4 ] novos números
# [ 5 ] sair do programa
# Seu programa deverá realizar a operação solicitada em cada caso.
from time import sleep
num_01 = int(input("Digite o primeiro número: "))
num_02 = int(inp... |
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
m = float(input("Digite o valor em metros: "))
dm = m * 10
cm = m * 100
mm = m * 1000
dam = m / 10
hm = m / 100
km = m / 1000
print(f"{m} m equivale a:\n{dm} dm\n{cm} cm\n{mm} mm\n{dam} dam\n{hm} hm\n{km} km")
|
# Escreva um programa em Python que leia um número inteiro qualquer e peça
# para o usuário escolher qual será a base de conversão: 1 para binário, 2
# para octal e 3 para hexadecimal.
print("\033[7mBem vindo ao conversor de bases numéricas!\033[m")
num = int(input("Digite um número: "))
print('''Escolha uma opção:
1 ... |
# Faça um programa que tenha uma função chamada contador(), que receba
# três parâmetros: início, fim e passo. Seu programa tem que realizar
# três contagens através da função criada:
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
from time import sleep
def contador(inicio, f... |
# Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar
# mais alguns termos. O programa encerrará quando ele disser que quer
# mostrar 0 termos.
primeiro = int(input("\033[1mDigite o primeiro termo da PA: \033[m"))
razao = int(input("\033[1mDigite o valor da razão: \033[m"))
termo_init = 1
while ter... |
# Aprimore o desafio 93 para que ele funcione com vários jogadores,
# incluindo um sistema de visualização de detalhes do aproveitamento
# de cada jogador.
from time import sleep
time = list()
while True:
i = 0
gols = []
jogador = {"nome": str(input("\nNome do jogador: ")).strip().upper(),
... |
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas.
# No final do programa, mostre: a média de idade do grupo, qual é o nome
# do homem mais velho e quantas mulheres têm menos de 20 anos.
soma_idades = 0
velho = 0
novo = 0
menos_20 = 0
nome_velho = ""
nome_novo = ""
for pessoa in range(1, 5):
p... |
# Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora a
# possibilidade da digitação de um número de tipo inválido. Aproveite e crie
# também uma função leiaFloat() com a mesma funcionalidade.
def leiaInt(valor):
while True:
try:
inteiro = int(input(valor))
except:... |
# 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 = 0
while True:
dados.append(... |
# Faça um programa que mostre na tela uma contagem regressiva para o estouro
# de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
from time import sleep
for cont in range (10, 0, -1):
print(cont)
sleep(1)
print("Feliz Ano Novo!") |
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela
# o nome do escolhido.
from random import choice
print("Digite o nome dos alunos:")
aluno01 = str(input("Aluno 1: "))
aluno02 = str(input("Aluno 2: "))
aluno03 = st... |
# Escreva um programa que pergunte a quantidade de Km percorridos por um carro
# alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a
# pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
print("Vamos calcular o preço do aluguel do veículo.")
km = float(input("Digite a quan... |
from typing import Dict, List
def get_student_marks() -> List[float]:
n = int(input())
student_marks: Dict[str, List[float]] = {}
for _ in range(n):
name, *line = input().split()
student_marks[name] = list(map(float, line))
query_name: str = input().strip()
return student_marks[q... |
# -*- coding: UTF-8 –*-
# 上面这一行是python头文件的声明
# 缺省情况下程序需要用ascii码书写,但如果其中写中文的话,python解释器会报错
from scipy.misc import imread, imresize
import imageio
from PIL import Image
import numpy
'''
直接使用pip安装misc会报错 ImportError:cannot import name 'imread' from 'scipy.misc'
原因在于包的版本问题,新版本的scipy.misc没有这一个方法
为了对照文档,我们卸载并重新安装:pip3 inst... |
import socket
s = socket.socket()
s.connect(("localhost", 9999))
validacion=False
# comprueba si el email es valido
def comprobarEmail(email):
comprobacion=False
if "@" in email:
nuevo_email=email.split('@')
resto=nuevo_email[1]
if "." in resto:
comprobacion=True
re... |
import random
def strong():
a = random.randint(20, 40)
s = ''
print(a)
for i in range(1, a):
aa = random.randint(0, 2)
aaa = random.randint(1, 100)
c = random.choice("aertuiopqsdfghjklmcvbn")
c2 = random.choice("aertuizyxopqsdfghjklmcvbn")
if aa == 0:
... |
from decimal import DivisionByZero
from sys import exc_info
from traceback import print_exc, print_exception
def main():
print("Learning Exceptions")
'''
Try can be with catch and multi catch
'''
try:
x = 5/0
# x = int("potato")
'''
If I purposefully raise an... |
def add(num1: float = 1, num2: float = 0):
# A function's doc string will always be inside it rather than on top of it
'''
This function will add the two numbers passed to it
'''
return num1 + num2
def subtract(num1: float = 1, num2: float = 0):
return num1 - num2
def multiply(num1: float ... |
class ShippingOperator:
def __init__(self, shipping_network_data):
# basic data structures
self.shipping_time = dict() # (<port-a>, <port-b>) -> <number-of-traveling-days>
self.shipping_graph = dict() # <port-a> -> <port-b>
for route in shipping_network_data:
self.shippin... |
# key value pair
# keyword - dict
dict1 = { 'name' : 'ad', 'age' :2}
print('dictionary dict1 -',dict1)
#get specific value from dict
print('get the value of the name key from dict1 -',dict1['name'])
# create new item in dictionary
dict1['address'] = 'address1'
print('updated dictionary dict1 -',dict1)
#get list... |
#从视频零基础学习爬虫写的
#用的是 suop获取的图片地址
import requests,urllib.request
from bs4 import BeautifulSoup
url = 'http://tieba.baidu.com/p/5149504613?pn=1'
url2 = 'http://desk.zol.com.cn/bizhi/7244_89635_2.html'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.... |
# 함수 functions : 코드를 간략하고 쉽게 짜기 위한 툴
# 입력값 parameters, 반환값 return <반환값이 있어야 변수에 담을 수 있다
# def > 데피니션
def hello_friends(nam):
print("hello, {}".format(nam))
name1 = "강윤"
name2 = "은혜"
name3 = "맥스"
name4 = "크림"
hello_friends(name1)
hello_friends(name2)
hello_friends(name3)
hello_friends(name4)
# 입력값 있고, 반환값 있고
de... |
alpha = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеєжзиіїйклмнопрстуфхцчшщьюяАБВГДЕЄЖЗИІЇКЛМНОПРСТУФХЦЧШЩЬЮЯ0123456789'
step = 2
step1 = 1
text = input("Please write your text ").strip()
res = ''
digit=''
for c in text:
if c.isalpha():
if digit:
res += str(int(digit)+int(step1))
... |
#배열 arr가 주어집니다.
# 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다.
# 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다.
# 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. 예를 들면,
# arr = [1, 1, 3, 3, 0, 1, 1] 이면 [1, 3, 0, 1] 을 return 합니다.
# arr = [4, 4, 4, 3, 3] 이면 [4, 3] 을 return 합니다.
# 배열 arr에서 연속적으로 나타나는 숫자는 제거하고 남은 수들을 return 하... |
class Cone():
def __init__(self, Radius, Height):
self.radius = Radius
self.height = Height
def Volume(self):
r = self.radius
h = self.height
V = int((3.14 * (r*r)*h) / 3)
print("Volume is ", V)
def Surface_area(self):
r = self.... |
str = "hey this is sai, I am in mumbai,...."
ls =[]
print(str)
#function
def strcap(String):
lst = list(str.split())
for i in lst:
a = i.capitalize()
ls.append(a)
for i in ls:
print(i, end=" ")
strcap(str)
|
from AlertCreators.alert_creator import AlertCreator
from datetime import datetime, time
import re
class NosyNeighbor(AlertCreator):
"""
It's an AlertCreator
It has a constructor __init__(name, bed_time, wake_up_time) . I believe the name is self-explenatory, and the rest of the properties are explained... |
import MapReduce
import sys
"""
Asymmetric Friends in the Simple Python MapReduce Framework
Given an input record as a 2-element list [personA, personB], returns the
list of all one-way friendships, i.e. personA is friends with personB, but
personB is not friends with personA
"""
mr = MapReduce.MapReduce()
# ======... |
#Paulo = Necessário assistir a aula para colocar em ordem
from random import randint
from operator import itemgetter
dados = dict()
maior = 0
for c in range(1, 5):
dados[f'Jogador {c}'] = randint(1, 6,)
print(f'O jogador 1 tirou {dados["Jogador 1"]}\n'
f'O jogador 2 tirou {dados["Jogador 2"]}\n'
f'O jog... |
#PAULO - OK
'''contidade = conthomem = contmulher20 = 0
while True:
idade = int(input('Digite sua idade: '))
sexo = str(input('Digite seu sexo [M/F]: ')).upper().strip()
continua = str(input('Quer continuar [S/N]? ')).upper().strip()
if idade >= 18:
contidade += 1
if sexo == 'M':
con... |
#Não consegui fazer sozinho, necessário estudar esse tipo de exercício!
valor = int(input('Qual valor deseja sacar: R$ '))
cédula = 100
total = valor
contcéd = 0
while True:
if total >= cédula:
total -= cédula
contcéd += 1
else:
if contcéd > 0:
print(f'Toatal de \033[1;34m{co... |
#Paulo
def área(a, b):
cálculo = a * b
print(f'A área de um terreno {a}x{b} é de {cálculo}m²')
print(' Controle de terrenos')
print('-'*30)
largura = float(input('Digite a LARGURA (m): '))
comprimento = float(input('Digite o COMPRIMENTO (m): '))
área(largura, comprimento)
#Guanabara
'''def área(larg, com... |
#Paulo
'''n = 0
cont = 0
s = 0
while n != 999:
n = int(input('digite um número e digite 999 para parar: '))
s = s + n
cont = cont + 1
print(f'Você digitou {cont-1} e a soma dos números é de {s-999}')'''
|
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
#Code starts here
# Data Loading
data=pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'},inplace=True)
print(data.head(10))
# Summer or Winter
... |
n, d = int(input()), {}
for i in range(n):
x = int(input())
if not x in d:
d[x] = f(x)
print(d[x])
''' Решение со Степика
a=[int(input()) for i in range(int(input()))]
b={x:f(x) for x in set(a)}
for i in a:
print(b[i])
''' |
my_list = [
{
'a' : [1,2,3],
'b' : 2,
'c' : 'Hello',
'd' : True
},
{
'a' : [4,5,6],
'b' : 'hello',
'c' : False
}
]
print(my_list[0]['a'][1]) #2
my_dict = {
123 : [1,2,3],
True : 'Hello'
}
... |
from claseProyecto import Proyecto
class ManejadorProyectos:
__proyectos=None
def __init__(self):
self.__proyectos = []
def agregarProyecto(self, proyecto):
'''recibe un objeto proyecto a agregar a la colección'''
if type(proyecto) == Proyecto:
self.__proyectos.... |
class IntervalTree:
def __init__(self, intervals):
# sort the full list of intervals by begin and build the tree
self.root = self.split_intervals(sort_by_begin(intervals))
# build the interval tree by recursively splitting the intervals into:
# - intervals overlapping with the node cente... |
import string
file = 'AlicesAdventuresinWonderland_text.txt'
text = open(file, 'r')
word_counts = {}
for line in text:
data = line.strip().split(' ')
for value in data:
key = value.translate(str.maketrans('','',string.punctuation)).lower()
if key in word_counts.keys():
word_count... |
i = 0 #Verify variable 'i'
for i in range(0, 10):#Repeat under code from 'i'=0 until 'i'=7.
'''
Calculator.py 참조
'''
cal = input("계산하고 싶은 숫자 2개를 입력해주세요.\n")
fir = int(cal.split(' ')[0])
sec = int(cal.split(' ')[1])
f = cal.split(' ')[0]
s = cal.split(' ')[1]
oper = input("연산자를 입력해주세... |
# Strings
print("String", 'Another String '
'He\'s Right ' # Escaping characters with the backspace (\)
""" He's Right"""
)
long_string = """Here's a new line:
...
... It's right there!"""
print(long_string)
# You can add strings together with plus sign
print(
"string1 " + "string2"
)
# You c... |
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
tree = node("g... |
"""
Environment File
"""
import os
import json
from pathlib import Path
def get_variable(variable_name, default=None, required=False):
"""
Loads an environment variable.
Falls back to check in the user's home directory for an env file.
It will load the variable from that file if it exists.
"""
... |
import time
file_loc = ".\\notes.txt"
def take_note():
note = raw_input('Enter Note --->')
note_file = open(file_loc, 'a')
note_file.write('---' + time.strftime(' %c: ') + note + '\n')
note_file.close()
def view_notes():
note_file = open(file_loc, 'r')
print("Your Notes:")
print(note_fil... |
year=int(input("please enter the year number you wish:"))
if((year %400==0)or(year %4==0) and (year %100!=0)):
print("%d is a leap year"%year)
else:
print("%d is not the leap year"%year)
|
# Varun Shourie, CIS345, Tuesday/Thursday, 12:00PM-1:15PM, A6
from tkinter import *
import math
def add_number(button):
"""When the user presses a numerical button, this function will check if the button pressed is a number or decimal
point. If a decimal, the function will check to see another decimal... |
def generator():
x = 0
while True:
y = yield x
if y is None:
x = x + 1
else:
x = y
g= generator()
print(next(g))
print('cos innego')
print(next(g))
print(next(g))
print('cos innego')
print(next(g))
print(g.send(12))
print(next(g)) |
x = input("podaj x:")
y = input("podaj y:")
print('x =', x)
print('y =', y)
print('Wynik dodawania:',int(x) + int(y))
print('Wynik odejmowania:', int(x) - int(y))
print('Wynik mnożenia:', int(x) * int(y))
print('wynik dzielenia:', int(x) / int(y))
print('wynik dzielenia całkowitego:', int(x) // int(y))
print('... |
"""--- Part Two ---
Out of curiosity, the debugger would also like to know the size of the loop:
starting from a state that has already been seen, how many block redistribution
cycles must be performed before that same state is seen again?
In the example above, 2 4 1 2 is seen again after four cycles, and so the answ... |
"""--- Part Two ---
There are more programs than just the ones in the group containing program ID 0.
The rest of them have no way of reaching that group, and still might have no
way of reaching each other.
A group is a collection of programs that can all communicate via pipes either
directly or indirectly. The progra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.