text stringlengths 37 1.41M |
|---|
# The Riddler Classic 2020-03-20: SET
# https://fivethirtyeight.com/features/how-many-sets-of-cards-can-you-find/
# Monte-Carlo simulation
import random
import itertools
class card:
def __init__(self, number, shape, color, shading):
self.number = number
self.shape = shape
self.color = co... |
#The Riddler Express 2018-11-02: Rigged Coin Flip
#Monte-Carlo simulation
import random
Nsim = 1000000 #number of simulations
#----------------------------------------------------
#Methods for coin flips and comparing flip results
def coin_flip():
#Outputs the result of a single coin flip
return bool(random... |
#The Riddler Classic 2018-10-26: Organisational Obsession
#Monte-Carlo simulation
import random
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def draw(n, deck):
#This function returns a random hand of size n drawn from a deck
return random.sample(dec... |
#The Riddler Classic 2016-11-18: The Lonesome King
#analytical computation and monte carlo simulation
import random
import math
#function returning the binomial coefficient, ie. n choose k
def binomcoeff(n, k):
return int(math.factorial(n)/math.factorial(k)/math.factorial(n - k))
#=================================... |
# The Riddler Classic 2020-09-18: Guess My Word
# https://fivethirtyeight.com/features/can-you-break-a-very-expensive-centrifuge/
# Monte-Carlo simulation and comparison with theoretical expectations
import math
import random
def expected_guesses(n):
#recursive function for expected number of guesses
if (n =... |
"""
Authors: Sasha Friedrich
Amelia Sheppard
Date: 4/1/18
Description:
"""
import numpy as np
import csv
from util import * # data extraction functions
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
def lineplot(x, y, label):
"""
Make a line plot.
Parameters
... |
# In this lecture we'll cover the usage of the with statement.
# The with statement allows to close a file without using the close method.
# The with statement defines a block, which will close the file once left.
# In the block defined the variable file can be used
with open("18_Text_File.txt", 'a') as file:
fil... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
变量可以指向函数,函数名其实就是指向函数的变量
'''
# print abs(-111)
'''
高阶函数:能够接收函数作为参数的函数
demo:接收abs函数作为参数,定义一个函数,接收x,y,f三个参数,其中x.y是普通的数,f是函数
'''
def add(x,y,f):
return f(x)+f(y)
print add(-1,-22,abs) |
age = int(input('enter your age\n'))
if age <=0:
print("invalid input for age.")
elif age <=1:
print("you are an infant.")
elif age <=12:
print("you're just a kid.")
elif age <=19:
print("you're a teenager.")
elif age <=45:
print("you are adult now.")
elif age <=59:
print("you're middle-aged.")
elif age <=120:
p... |
names = ['john Doe','jane Doe','johny truk']
#change the first name in the last
names[0] = 'foo bar'
print ( 'names now :', names)
#Append some more names
names.append('Molly Mormon')
names.append('Joe bloggs')
print('Names finally:', names)
print('last names in the list: %s' % names[-1])
#you can join lists using str... |
"""
https://www.hackerrank.com/challenges/grading/problem
"""
import math
def is_grade_enough(grade):
if rounded(grade) < 40:
return(False)
return(True)
def rounded(grade):
if next_multiple_of_five(grade) - grade < 3:
return(next_multiple_of_five(grade))
return(grade)
def next_mul... |
import sys
class board:
def __init__(self, pieces):
self.pieces = pieces
def add_piece(self, piece):
self.pieces.append(piece)
def get_piece_on_coordinate(self, x, y):
"""
:param x: x value of coordinate
:param y: y value of coordinate
:return: piece on coo... |
power = eval(input('Enter power : '))
number = 2**power
lastDigits = number%100
print('Power =',power)
print('Number =',number)
print('Last Two Digits =',lastDigits)
|
weightInKilograms = eval(input('Enter weight : '))
weightInPounds = weightInKilograms*2.2
print('There are',weightInPounds,'pounds in',weightInKilograms,'kilograms.')
|
fib1 = 1
fib2 = 1
fib = fib1+fib2
numberOfFib = eval(input('Enter Number of Elements In The Sequence : '))
print(fib1,fib2,fib,sep=',',end='')
for i in range(numberOfFib-3):
fib1 = fib2
fib2 = fib
fib = fib1+fib2
print(',',fib,sep='',end='')
# What is a user enters a number less than 3?
|
# Imagine we wanted to to display a --- a^n, where n is an real numbers.
# Ofcouse a*a*a*a*a*...*a would be tedious and combusome.
import math
for i in range(1,21):
print(i, pow(i,2),sep=' --- ')
|
exponent = eval(input('Enter power : '))
answer = pow(2,exponent)
digit = answer%10
print('Power =',exponent)
print('Number =',answer)
print('Last Digit =',digit)
|
def rozciagniecie(plansza, x, y):
list_of_x = range(-1,2)
list_of_y = range(-1,2)
for row in list_of_y:
for col in list_of_x:
ix = col
iy = row
while plansza[y][x] == ".":
x += ix
y += iy
return x, y |
#Number game - Guess a number between 0 to 10
print("Guess a number between 0 to 10")
guess=0
high = 10
low =0
while(high >low):
guess +=1
guess = (high+low)/2
print("Is the number",guess)
while True:
answer = input("If the answer is right enter \n"
"Y for Yes\n"
... |
import string
START = 32
END = 126
def palindrome(input):
input = str(input)
input = input.lower()
input = input.replace(' ','')
if input == input[::-1]:
exclude = set(string.punctuation)
return ''.join(c for c in input if c not in exclude)
return None
def main():
DATA = ('Mur... |
#!/usr/bin/env python
print("***** Cuanto sera este numero en minutos y hora *****")
num = int(input("Ingrese el numero:"))
print ("Horas:%d - Minutos:%d" % (num/60,num%60)) |
#!/usr/bin/env python
print("***** Una imagen vale mas que mil palabras *****")
word = input("Ingrese la palabra:")
print("Mil Veces: ")
print("%s "%(word) * 1000) |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return f"{self.data}"
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_val(self, x):
'''Append value x at the end ... |
# ## 1. Load MNIST Database
from keras.datasets import mnist
( x_train, y_train),( x_test, y_test ) = mnist.load_data()
# ## 2. Normalize the data
# rescale [ 0, 255] -> [ 0, 1 ]
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# 3. Encode categorical integer labels using a one-... |
def pisano_numbers(n, m):
previous, current = 0, 1
pisano_numbers = [previous, current]
for i in range(6 * m):
previous, current = current, (previous + current) % m
pisano_numbers.append(current)
if previous == 0 and current == 1:
pisano_numbers = pisano_numbers[0:-2... |
# Spencer Nettles
# CS246
# Calculator program will take exations and solve them
import math
# Finds Magnitude of Vector
def magVector():
Vx = float(input("Vx = "))
Vy = float(input("Vy = "))
mag = math.sqrt((Vx * Vx) + (Vy * Vy))
print("Magnitude of the vector = ", mag)
# Finds the angle the vector i... |
'''
密碼重設程式
password = 'a123456'
讓使用者重複輸入密碼
最多輸入3次
如果正確,就印出 "登入成功!"
如果不正確,就印出 "密碼錯誤! 還有__次機會!"
'''
password = 'a123456'
number = 0
left_chance = 3-number #剩於機會
while left_chance > 0:
user_pwd = input('請輸入密碼(最多3次): ')
number += 1
left_chance = 3 - number
if user_pwd == password:
print('登入成功')
... |
https://www.hackerrank.com/challenges/find-angle/problem
Find Angle MBC
from math import *
ab, bc = [int(input()) for _ in range(2)]
print(str(int(degrees(atan2(ab,bc)) + 0.5))+'°')
|
ERROR: type should be string, got "https://www.hackerrank.com/challenges/write-a-function/problem\nWrite a function\n\ndef is_leap(year):\n leap = False\n \ndef is_leap(y):\n return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)\n \n return leap\n \n" |
https://www.hackerrank.com/challenges/merge-the-tools/problem
Merge the Tools!
def merge_the_tools(string, k):
for i in range(0, len(string), k):
output = ''
unique_letters = set()
for letter in string[i:i + k]:
if letter not in unique_letters:
output += letter
... |
ERROR: type should be string, got "https://www.hackerrank.com/challenges/swap-nodes-algo/problem\nSwap Nodes [Algo]\n\nimport os\nimport sys\nsys.setrecursionlimit(15000)\n\ntree = []\n\nclass Node:\n\n def __init__(self, value=None):\n self.value = value\n self.right = None\n self.left = None\n\n def __repr__(self):\n return \"Node:- {} Right - {} Left {}\".format(self.value, self.right, self.left)\n\ndef swap(root, l, q):\n if l % q == 0:\n root.left, root.right = root.right, root.left\n if root.left:\n swap(root.left, l + 1, q)\n if root.right:\n swap(root.right, l + 1, q)\n\n\ndef inorder(roots, inter_result):\n if roots:\n inorder(roots.left, inter_result)\n inter_result.append(roots.value)\n inorder(roots.right, inter_result)\n\n#\n# Complete the swapNodes function below.\n#\n\ndef swapNodes(indexes, queries):\n initial_root = Node(1)\n tree = [initial_root]\n for i in range(0, len(indexes)):\n root = tree.pop(0)\n left = indexes[i][0]\n right = indexes[i][1]\n if left != -1:\n root.left = Node(left)\n tree.append(root.left)\n\n if right != -1:\n root.right = Node(right)\n tree.append(root.right)\n result = []\n for query in queries:\n inter_result = []\n swap(initial_root, 1, query)\n inorder(initial_root, inter_result)\n result.append(inter_result)\n return result\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n indexes = []\n\n for _ in range(n):\n indexes.append(list(map(int, input().rstrip().split())))\n\n queries_count = int(input())\n\n queries = []\n\n for _ in range(queries_count):\n queries_item = int(input())\n queries.append(queries_item)\n\n result = swapNodes(indexes, queries)\n\n fptr.write('\\n'.join([' '.join(map(str, x)) for x in result]))\n fptr.write('\\n')\n\n fptr.close()\n \n" |
https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem
Binary Search Tree : Lowest Common Ancestor
# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
def __init__(self,info):
self.info = info
self.left = None
s... |
https://www.hackerrank.com/challenges/any-or-all/problem
Any or All
n, l = int(input()), input().split()
a, b = [int(x) > 0 for x in l], [x == x[::-1] for x in l]
print(all(a) and any(b))
|
https://www.hackerrank.com/challenges/py-set-difference-operation/problem
Set .difference() Operation
n = int(input())
e_set = set(map(int, input().split()))
m = int(input())
f_set = set(map(int, input().split()))
print(len(e_set.difference(f_set)))
|
https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem
Insert a node at a specific position in a linked list
# Complete the insertNodeAtPosition function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def insert... |
https://www.hackerrank.com/challenges/find-a-string/problem
Find a string
def count_substring(string, sub_string):
return (sum([1
for i in range(0, len(string) - len(sub_string) + 1)
if (string[i:(len(sub_string)+i)] == sub_string)]))
|
# task_1 - leap year and list of all leap years from 0 to 2018 and count their amount
def is_leap(year):
if year%4==0 and year%100!=0 or year%400==0:
return True
return False
years = [n for n in range(2019)]
leap_years_list = []
for year in years:
if is_leap(year):
print( year, 'is leap')
... |
# -- coding: utf-8 --
def add(a, b):
print "ADDING %d + %d" %(a, b)
return a + b
def substract(a, b):
print "SUBSTRACTING %d + %d" %(a, b)
return a - b
print "Let's do some math with just fuctions!"
age = add(30, 5)
height = substract(78, 4)
print "Age : %d, Height : %d" % (age, height)
|
#coding: gbk
#===========================================Core Function===========================================
#SelectionSort
def SelectionSort(A):
for i in range(0 , len(A) - 1): #For all A element
min = i #Record the minimum's cursor.Init by i self
... |
raio = float(input("Digite o raio em cm: "))
area = 3.14 * (raio**2)
print("A área do círculo de raio " + str(raio) + "cm vale: " + str(area) + "cm2") |
nA = int(input("A: "))
nB = int(input("B: "))
print("Resultado: " + str(nA + nB)) |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("300x400+0+0")
root.resizable(0,0)
root.title("TIC TAC TOE")
#################################################################
i=1
data = StringVar()
data.set("Player 1")
x=0
p1=0
p2=0
p3=0
p4=0
p5=0
p6=0
p7=0
p... |
#!/usr/bin/env python
# coding: latin-1
# Autor: kevin
# Date: 20160331
# Version: 1.0
#Thanks for origin Autor's Ingmar Stape
# This module is designed to control two motors with a L298N H-Bridge
# Use this module by creating an instance of the class. To do so call the Init function, then command as des... |
"""
Author : Gurpreet Singh
Date : 17 jan 2020
Purpose : To understand how to access the varible of one process to another using "Queue"
######################
Queue : FIFO (First in First out)
Two Method :
put : enqueue
get : dequeue
###############
Create Queue varible :
q = muliiprocessing.Queue()
"""
import ti... |
"""
Author : Gurpreet singh
Date 20 jan 2020
############# Basic cmd
[np.fxn : generic fxn]
1. check the type of numpy dimension : ndim
ex. a.ndim
2. itemsize : tell about the size of each elements
ex. a.itemsize
3. a.dtype : Tells about the type of datatype/ or used to initialize array with specific datatype
ex. ... |
#骰子
from random import randint
class Die():
'''扔骰子的简单尝试'''
def __init__(self, sides):
self.sides = sides
def roll_die(self, times):
i = 0
while i < times:
print(randint(1, self.sides))
i += 1
num_one = Die(6)
num_one.roll_die(8)
|
# computes the gcd. taken from snappea
from functools import total_ordering
import re
def gcd(a, b):
a = abs(a)
b = abs(b)
if a == 0:
if b == 0: raise ValueError("gcd(0,0) undefined.")
else: return b
while 1:
b = b % a
if (b == 0): return a
a = a % b
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 22:29
@annotation = ''
"""
import numpy as np
import pandas as pd
"""
自定义函数 有点像map
"""
s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
def add3(x):
return x + 3
if False:
print s1.apply(add3)
"""
applymap()
pand... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/6/18 14:27
@annotation = ''
"""
"""
文字信息 转化为数字
"""
"""
Dealing with categorical features in Python
● scikit-learn: OneHotEncoder()
● pandas: get_dummies()
"""
"""
In [3]: df_origin = pd.get_dummies(df)
In [4]: print(df_origin.head())
mpg d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 21:54
@annotation = ''
"""
import numpy as np
# Subway ridership for 5 stations on 10 different days
ridership = np.array([
[0, 0, 2, 5, 0],
[1478, 3877, 3674, 2328, 2539],
[1613, 4088, 3991, 6461, 2691],
[1560, 3392, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2017/1/24 20:55
@annotation = ''
"""
import pandas as pd
a = pd.Series([1, 2, 3, 4])
# Accessing elements and slicing
if False:
for country_life_expectancy in a:
print 'Examining life expectancy {}'.format(country_life_expectancy) ... |
"""
OOP implementation
"""
import reprlib
import itertools
import typing as typ
from treasure_hunt.utils import list_to_str
class SearchForTreasurePath:
"""
Object-oriented implementation of treasure search
"""
__slots__ = ('_treasure_map', '_curr_row', '_curr_col')
def __init__(self, treasure... |
def factorial(n):
if n < 0:
print("Factorials do not exist below zero")
return -1
elif (n == 0) or (n == 1):
return 1
elif n > 1:
product=1
for x in range(2, n+1):
product=product*x
return product
|
'''Faça um programa que leia algo pelo teclado e mostre
na tela o seu tipo primitivo e todas as informações
possíveis sobre ele.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO04\033[m iniciado.')
print('=' * 50)
info = input('Digite \033[4malgo\033[m: ')
print(info.isalnum())
print(info.isalp... |
'''Faça um programa que leia um número inteiro e diga
se ele é ou não um número primo.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO52\033[m iniciado.')
print('=' * 50)
num = int(input('Digite um número: '))
aux = 0
for cont in range(1, (num + 1)):
# num % cont
if (num % cont == 0):
... |
'''Refaça o DESAFIO09, mostrando a tabuada de um número
que o usuário escolher, só que agora utilizando um
laço for.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO49\033[m iniciado.')
print('=' * 50)
num = int(input('Digite um número: '))
print('_' * 50)
print(f'\033[1mTabuada do {num}\033[... |
'''Faça um programa que leia a largura e a altura de uma parede
em metros, calcule a sua área e a quantidade de tinta
necessária para pintá-la, sabendo que cada litro de tinta
pinta uma área de 2m².'''
print('=' * 50)
print(('' * 10), 'Programa \033[1;4mDESAFIO11\033[m iniciado.')
print('=' * 50)
largura = flo... |
'''Faça um programa que mostre a tabuada de vários
números, um de cada vez, para cada valor digitado pelo
usuário. O programa será interrompido quando o número
solicitado for negativo.'''
print('=' * 50)
print('Programa \033[4mDESAFIO67\033[m iniciado. Digite um \033[31mnúmero negativo\033[m para \033[31msair\033[... |
'''
Crie um programa que leia nome e duas notas de vários
alunos e guarde tudo em uma lista composta. No final,
mostre um boletim contendo a média de cada um e permita
que o usuário possa mostrar as notas de cada aluno
individualmente.
'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO89\033[m ini... |
'''Crie um programa que tenha uma tupla única com nomes
de produtos e seus respectivos preços na sequência. No
final, mostre uma listagem de preços, organizando os
dados em forma tabular.'''
print('=' * 50)
print(' ' * 10, 'Programa \033[1;4mDESAFIO76\033[m iniciado.')
print('=' * 50)
print('Lista de itens:')
... |
'''Faça um programa que leia uma frase pelo teclado e mostre:
- Quantas vezes aparece a letra "A"
- Em que posição ela aparece a primeira vez
- Em que posição ela aparece a última vez'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO26\033[m iniciado.')
print('=' * 50)
frase = str(input('Digite u... |
'''
Faça um programa que leia o 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
'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO84\033[m inicia... |
'''Faça um programa que leia o peso de cinco pessoas.
No final, mostre qual foi o maior e o menor peso lidos.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO55\033[m iniciado.')
print('=' * 50)
print('Digite o peso de 5 pessoas:')
for cont in range(1, 6):
peso = float(input('Peso da pessoa ... |
'''Escreva um programa que pergunte o salário de um funcionário
e calcule o valor do seu aumento.
Para salários superiores a R$ 1.250,00, calcule um aumento
de 10%.
Para os inferiores ou iguais, o aumento é de 15%.'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO34\033[m iniciado.')
print('=' * 50... |
'''Escreva um programa que leia dois números inteiros e
compare-os, mostrando na tela alguma destas mensagens:
- O primeiro valor é maior
- O segundo valor é maior
- Não existe valor maior, os dois são iguais'''
print('=' * 50)
print((' ' * 10), 'Programa \033[1;4mDESAFIO38\033[m iniciado.')
print('=' * 50)
p... |
# Exercise 1.
# Using a while loop create a program that prints the values of your favorite movie stars.
# have a number in front of the printed name.
movie_stars = ["Eddie Murphy", "Ryan Reynolds", "Julia Robers"]
i = 0
while i < len(movie_stars):
print(f"{i+1}. {movie_stars[i]}")
i += 1
#################... |
# *
# ***
# *****
# *******
for x in range(0, 4):
for y in range(0, 6-x):
print(" ", end="")
for k in range(0, 2 * x + 1):
print("*", end="")
print("")
|
coins = 0
print(f"You have currently have {coins} coins.")
more_coins = input("Do you want another?\n")
while more_coins == "yes":
coins +=1
print(f"You have {coins} coins.")
more_coins = input("Do you want another?")
else:
print("Bye!")
|
day = int(input("Day (0-6)?"))
if day == 0:
print("It is Sunday")
elif day == 1:
print("It is Monday")
elif day == 2:
print("It is Tuesday")
elif day == 3:
print("It is Wednesday")
elif day == 4:
print("It is Thursday")
elif day == 4:
print("It is Friday")
else:
print("I don't know wh... |
"""
Problem: 238. Product of Array Except Self
Url: https://leetcode.com/problems/product-of-array-except-self/
Author: David Wang
Date: 12/31/2020
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
m_profit = 0
if not prices:
return 0
... |
"""
Problem: 63. Unique Paths II
Url: https://leetcode.com/problems/unique-paths-ii/
Author: David Wang
Date: 06/23/2020
"""
from typing import List
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if len(obstacleGrid) == 0:
return 0
if len(obstacleGrid[0]) =... |
# Miller-Rabin algorithm
def fast_int_mod_power(base, exponent, n):
inbase2 = list()
basepowers = list()
while(exponent > 0):
exponent, r = divmod(exponent, 2)
inbase2.append(r)
basepowers.append(base)
base = base * base % n
result = 1
for i in range(len(inbase2)):
... |
class Operaciones:
def __init__(self,num1,num2):
self.numero1=num1
self.numero2=num2
def suma(self):
suma=self.numero1 + self.numero2
return suma
def resta(self):
return self.numero1 - self.numero2
def multiplicacion(self):
return self.numero1 * self.n... |
from collections import namedtuple
NIVEL = int(input("Ingrese el nivel de dificultad deseado - 1 a 5-")) # El usuario debe ingresar el nivel que quiere jugar
while NIVEL > 5 or NIVEL < 1: # Hasta que el usuario no ingrese un nivel dentro del rango estipulado, el programa se lo sigue solicitando
NIVEL = ((int(inp... |
#!/usr/bin/env python3
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=no-else-return
# pylint: disable=consider-using-enumerate
"""
Trie datastruktur
"""
from node import Node
class Trie:
"""
Trie datastruktur
"""
def __init__(self):
"""init"""
... |
#!/usr/bin/env python3
"""
Unittest file for Phone
"""
import unittest
from hand import Hand
from deck import Deck
from card import Card
class Testwar(unittest.TestCase):
"""Submodule for unittests, derives from unittest.TestCase"""
def setUp(self):
""" Create object for all tests """
self.h... |
# Pandas Getting Started
# Import Pandas
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
print()
# Pandas as pd
import pandas as pd
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pd.DataFr... |
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
def f3(x):
"""discus function"""
sum = 0.0
sum += (x[0]**2)*(10**6)
for i in range(2, len(x)+1):
sum += x[i-1]**2
return sum
#Function 3
X = np.linspace(-100, ... |
print ("Citlali Gonzalez")
def superpower(a,b):
m=0
for m in range(b):
m= m+1
s= pow(a,m)
return s
a = int(input("Give me the number: "))
b = int(input("Give me the power: "))
sp = superpower(a,b)
print(sp)
|
##Nama: Gilang Anggi Wisnu Brata
##Kelas: A
##NIM:L200170011
#####=====No.1==============######
class Pesan(object):
"""hai"""
def __init__(self,sebuahString):
self.teks= sebuahString
def cetakIni(self):
print(self.teks)
def cetakPakaiHurufKapital(self):
print(str.up... |
import json
with open('country_list.json') as json_file:
data = json.load(json_file)
def display(dc):
print(dc['country'])
print("Total number of registered cases: ", end = "")
print(dc['cases'])
print("Total number of deaths: ", end = "")
print(dc['deaths'])
def query_by_country_name(name):... |
"""
This module is used to provide data structures that describe the possible
outcomes of a test execution.
"""
from typing import Optional
import datetime
class TestOutcome(object):
"""
Describes the outcome of a test execution.
"""
def __init__(self,
passed: bool,
d... |
def solve(n,char_str):
checked = []
checking = char_str[0]
for i in char_str:
if i != checking:
if i in checked:
return 'NO'
checked.append(checking)
checking = i
return 'YES'
t = int(input())
for i in range(t):
n = ... |
def find_max_len(arr):
max_flag = 0 ##Result to return at last
flag = 0 ##To track the number of increasing nature
for i in range(len(arr)-1): ##Going throu the arr
if arr[i] < arr[i+1]: ##Checking if increasing
flag += 1
else:
... |
def watermelon_prob(noOfwatermelon):
if noOfwatermelon%2 == 0 and noOfwatermelon != 2:
print("Yes")
else:
print("No")
num = int(input())
watermelon_prob(num)
|
import socket
# Takes address as input
addr = input("Enter IP address >>> ")
# Loops over all the ports
for port in range(65536):
# Creates socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
# Connects to socket
result = sock.connect_ex((addr, port))
if re... |
import random
from random import choice
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
num_caract = int(input("Número de caracteres: "))
Ler_Arquivo = input('Você deseja ver a senha?')
arquivo = open('key.txt', 'w')
def password():
if (num_caract < 0):
return "Erro: número ... |
"""Implement 1D and 2D Peak Finding as described in
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/
in the first lecture.
Usage:
p = Problem([a, b, c, ....], dims=(x,y) or None for 1D)
p.findPeak() -> (value, position)
"""
import numpy as np
impo... |
from Maze import maze
import random
from Maze import bcolors
import time
def game_result(height,width,board):
game = Mazeboards(height,width,board)
game.board_initializer()
while game.exit():
game.next_turn()
return (game.move,game.move_pattern)
class Mazeboards:
# 0 = nothing
# 1 = wa... |
# A Pulsator is a Black_Hole; it updates as a Black_Hole
# does, but also by growing/shrinking depending on
# whether or not it eats Prey (and removing itself from
# the simulation if its dimension becomes 0), and displays
# as a Black_Hole but with varying dimensions
from prey import Prey
from blackhole impor... |
print("Welcome to the Haiku generator!")
print("Provide the first line of your haiku:")
a = str(raw_input())
print("Provide the second line of your haiku:")
b = str(raw_input())
print("Provide the third line of your haiku:")
c = str(raw_input())
print("What file would you like to write your haiku to?")
myFile = str(raw... |
import random
import numpy as np
random.seed(1234)
print(random.random())
print(random.uniform(25,50))
#Uniform
unifNumbers = [random.uniform(0,1) for _ in range(1000)]
print(unifNumbers)
#Normal
mu = 0
sigma = 1
print(random.normalvariate(mu, sigma))
mu = 0
sigma = 1
[random.normalvariate(mu, sigma) for _ in rang... |
# define functions for poptok here
def num_div35(num):
if num % 3 == 0 and num % 5 == 0:
return True
else:
return False
def num_div3(num):
if num % 3 == 0:
return True
else:
return False
def num_div5(num):
if num % 5 == 0:
return True
else:
r... |
def change_string(string, operation):
if operation == "uppercase":
print(string.upper())
elif operation == "lowercase":
print(string.lower())
elif operation == "join":
string = string.split(" ")
print("".join(string))
else:
print("Operation not poss... |
if __name__ == "__main__":
print("---- Guess the Capital ---")
print("10 Questions to test your geography knowledige.")
import random
import json
with open("capitals.json", "r") as f:
capitals = json.load(f)
f.close()
used = []
questions = 10
question = 0
nu... |
#!/usr/bin/python3
""" JSON Module
"""
import json
def from_json_string(my_str):
"""
Args:
my_str (object): The first parameter.
Returns:
string: JSON string
"""
return json.loads(my_str)
|
#!/usr/bin/python3
"""Same Class Module
"""
def is_same_class(obj, a_class):
"""
Args:
obj (object): The first parameter.
a_class (object): The second parameter.
Returns:
bool: True or False
"""
if type(obj) is a_class:
return True
else:
return F... |
#!/usr/bin/env python
# coding: utf-8
# # Handling Missing Data
#
# In this section, we will study ways to identify and treat missing data. We will:
# - Identify missing data in dataframes
# - Treat (delete or impute) missing values
#
# There are various reasons for missing data, such as, human-errors during data-en... |
# Python Regular Expression
# re.search() is used to find the first match for the pattern in the string.
# Syntax: re.search(pattern, string, flags[optional])
import re
s = "my number is 123"
match = re.search(r'\d\d\d', s)
print (match)
print (match.group())
s1 = "python tuts"
match = re.match(r'py', s1)
if match... |
N = int(input())
#student_marks = list(input().split() for _ in range(N))
#student_marks.sort(key = value)
student_marks = []
for i in range(N):
name, score = input().split()
a = []
a.append(name)
a.append(score)
student_marks.append(a)
#print(student_marks)
def takeSecond(elem):
return elem[1]
student_marks... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.