text stringlengths 37 1.41M |
|---|
"""This is a simple expamle for crawling the forbeschina website."""
from bs4 import BeautifulSoup
import requests
import csv
def get_data(url):
req = requests.get(url)
bf = BeautifulSoup(req.text)
return bf.find_all('tr')
def save_data(items):
results = []
results.append([i.te... |
import multiprocessing as mp
def job (x):
return x*x# pool can use return
def multicore():
pool=mp.Pool(processes=2)
res= pool.map(job,range(10))
print(res)
res=pool.apply_async(job,(2,))
print(res.get())
multi_res=[pool.apply_async(job,(i,)) for i in range (10)]
print([res.get() for r... |
"""(Incomplete) Tests for BookCollection class."""
from bookcollection import BookCollection
from book import Book
def run_tests():
"""Test BookCollection class."""
# Test empty BookCollection (defaults)
print("Test empty BookCollection:")
book_collection = BookCollection()
print(book_collection)... |
class classroom:
funciones= 30
segura= "si"
clasificacion= "educativa"
nombre="classroom"
usuarios=("Millones de usuarios")
seguro="si"
def online(self):
print("online")
def app(self):
print("aplicacion")
def enviodearchivos(self):
print("Permite enviar archivos")
def __init__(self):
... |
class vacaciones:
dias= 30
costo= 7000
vacacionistas= 4
totaldeequipaje= 6
mujeres= 2
hombres= 2
lugaresporvisitar= 7
niños= 1
adultos= 3
def descanso(self):
print("Descanso")
def relajarse(self):
print("Relajarse")
def __init__(self):
pass
clas... |
'''
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
tmp_x = abs(x)
string_x = str(tmp_x)
lst = []
for each in string_x:
... |
class Queue: # linkedList-based Queue
class Node:
def __init__(self, data= None):
self.data = data
self.next = None
def __init__(self):
self.front = None
self.rear = self.front
self.size = 0
def enqueue(self, data):
node = Queue.Node(data)
... |
# Hey everyone and welcome back to another text tutorial!
# In this script we will use Maths to work with Python
# Watch the video here: https://youtu.be/RpBskLBshoc
# As you know we already have did basic math, today we will do some more complex calculations
# Not too complex, that is for another video because it's t... |
# -*- coding: utf-8 *-*
import string
baseUrl = 'http://www.pythonchallenge.com/pc/def/map.html'
upperLimit = ord('z') + 1
lowerLimit = ord('a')
def challenge2():
# K => M = 2
# 0 => Q = 2
# E => G = 2
scrambledString = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl... |
# Check the versions of libraries
import random, os, time
import numpy as np
import pickle
from os import system
from time import sleep
import network
training_data=[None]*15
to_learn =0;
print("To Load the Lesson already Learnt Type 0, ELSE To Teach Counting Type 1")
to_learn=int(input())
if to_lear... |
names = ['Iron Man', 'Hulk', 'Thor', 'Black Widow', 'Ultron', 'Thanos']
print(names[:])
# Find largest number in list
numbers = [1,5,20,3,300,10000,34]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) |
numbers = [5,3,2,3,4,5]
numbers2 = numbers.copy()
numbers.append(20)
numbers.insert(0, 22)
numbers.remove(3)
numbers.pop() #remove last item in list
print(numbers.index(2))
print(3 in numbers)
print(numbers.count(3))
numbers.sort()
print(numbers)
print(numbers2)
# Write a program to remove the duplicates in a lis... |
import random as rand
import time
import argparse
import math
def no_neighbors(amt,options,bounds,iter,cur):
file = open('fractaldata.csv', 'a')
file.write('x,y')
file.write('\n')
try:
while iter < int(amt):
if iter == 0:
file.write(str(cu... |
nr_inmat=[]
print("\nIntroduceti 3 numere de inmatriculare pentru verificare:")
nr=input()
while nr:
nr_inmat.append(nr)
nr=input()
jud=['AB', 'AR', 'AG', 'B', 'BC', 'BH', 'BN', 'BT', 'BV', 'BR', 'BZ', 'CS', 'CL', 'CJ', 'CT', 'CV', 'DB', 'DJ', 'GL', 'GR', 'GJ', 'HR', 'HD', 'IL', 'IS', 'IF', 'MM', 'MH', 'MS... |
# Udacity Full Stack Web Developer nanodegree
# Programming Fundamentals
# Use Classes
# Movie class design
# 2017-06-12 Robert Buckley
import webbrowser
class Movie():
"""
This class provides a way to store movie related information
Attributes:
title (str): the movie's title
storyline (str): a bri... |
from timeit import timeit
# Returns list of adjacent nodes
def adjacent_nodes(n, grid_size=3):
adj = []
n0 = n[0]
n1 = n[1]
if 0 < n0:
adj.append((n0 - 1, n1))
if n0 < grid_size:
adj.append((n0 + 1, n1))
if 0 < n1:
adj.append((n0, n1 - 1))
if n1 < grid_s... |
class Solution:
"""
@param nums: an array of integers
@return: the number of unique integers
"""
def deduplication(self, nums):
# write your code here
if not nums:
return 0
if len(nums) == 1:
return 1
i, values_dic =0, {}... |
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
# write your code here
s = ''.join([el.lower() for el in s if el and el.isalnum()])
start, end = 0, len(s)-1
while start<end:
if s[start... |
n = int(input())
result = ''
a = 1
for a in range(1, n+1):
for b in range(1, n+1):
for c in range(1, n+1):
for d in range(1, n+1):
for e in range(1, n+1):
for f in range(1, n+1):
if a*b*c*d*e*f == n:
result ... |
n = float(input()) # страна на квадрат
w = float(input()) # едната страна на плочка
l = float(input()) # другата страна на плочка
m = float(input()) # широчина на пейката
o = float(input()) # дължина на пейката
lice_square = n**2
lice_peika = m * o
area_with_tiles = lice_square-lice_peika
area_tiles = w*l
ar... |
print("回回回回回回回回回回回回回回回回")
print("回 回")
print("回 Javeciales 回")
print("回 回")
print("回回回回回回回回回回回回回回回回")
print()
Nota1 = float(input("Digite la nota del primer parcial: "))
Nota2 = float(input("Digite la nota del segundo parcial: "))
Nota3 = float(input("... |
'''
Write a Python script to merge two Python dictionaries.
'''
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={}
for i in (dic1,dic2):
dic3.update(i)
print(dic3) |
def main():
mass = float(input("Kütleniz: "))
height = float(input("Boyunuz (m): "))
value = mass / (height ** 2)
value = round(value, 3)
print(f"Boy kütle indeksiniz: {value}")
if value <= 18.4:
print("Zayıfsınız")
elif value > 18.4 and value <= 24.9:
print("Normal Kilolus... |
import turtle
import math
class Dog:
def __init__(self):
self.turtle = turtle.Turtle()
self.turtle.shape('turtle')
self.rotation = 0
self.speed = 0.1
self.turtle.speed(100)
def rotate(self, degrees):
self.rotation += degrees
self.turtle.left(degrees)
... |
from math import sqrt
def F(y):
return 1 / (2 * y)
def eulers(steps):
y = 1
h = 1 / steps
for i in range(steps):
y = y + h * F(y)
return y
def newtons(steps):
if steps == 0:
return 1
return 0.5 * (newtons(steps - 1) + (2 / newtons(steps - 1)))
print("Euler's 100:", eulers... |
import datetime
class Date():
def __init__(self):
self.today = datetime.datetime.today()
self.year = int(self.today.strftime('%y')) + 2000
self.month = int(self.today.strftime('%m'))
self.day = int(self.today.strftime('%d'))
def format_date(self):
try:
date ... |
from turtle import Screen
from paddle import Paddle
from ball import Ball
from score import Scoreboard
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("My Pong Game")
screen.tracer(0)
l_paddle = Paddle((-350,0))
r_paddle = Paddle((350,0))
ball = Ball()
scoreboard = Scoreboar... |
import random
import math
import string
import hangman_art
import hangman_words
# DAY 5: PYTHON LOOPS
def height_calculator():
print("Welcome to the Average Height Calculator!")
height_list = input("Enter a list of heights (ie: 180 124 165 etc)\n").split(" ")
sum = 0
student_count = 0
for i in heig... |
"""
Input format:
script_dict : dictionary obtained from the json for a movie script
scene : any entry from script_dict (ex. script_dict[0] for the first scene)
char_name : string for character name (ex. 'TYLER')
"""
import json
def get_description_for_scene(scene):
scene_desc = " ".join(desc[1] for desc in scene... |
from threading import *
from time import sleep
from BehaviorEngine import *
import signal
class Behavior:
""" Base class for behaviors. """
def __init__(self, engine):
self._should_stop = False;
self._engine = engine
def engine(self):
""" Returns the hosting behavior engine... |
"""
The purpose of this script is to demonstrate the functionality of MachUpX for modelling
a small swarm of drones. Run this script using:
$ python swarm_example.py
The input file is also written such that the same analyses will be performed if run using
the `python -m` command. This is done using:
$ python -m mach... |
import numpy as np
import matplotlib.pyplot as plot
# Get x values of the sine wave
time = np.arange(0, 1, 0.008);
# Amplitude of the sine wave is sine of a variable like time
amplitude = np.sin(377*time)
# Plot a sine wave using time and amplitude obtained for the sine wave
plot.plot(time, amplitude)
# Give a... |
import pandas as pd
import codecs
filename = "popular-names.txt"
df = pd.read_table(filename,header=None,names=["name","sex","count","year"])
print(*df["name"],sep="\n",file=codecs.open('col1.txt', 'w', 'utf-8'))
print(*df["sex"],sep="\n",file=codecs.open('col2.txt', 'w', 'utf-8'))
# cut -f 1 popular-names.txt > col... |
PALAVRAS_PROIBIDAS = ('futebol', 'religião', 'política')
textos = [
'João gosta de futebol e política',
'A praia foi divertida',
]
for texto in textos:
for palavra in texto.lower().split():
if palavra in PALAVRAS_PROIBIDAS:
print('Texto possui pelo menos uma palavra proibida', ... |
"""Data preparation for inference on a convolutional neural network.
Expects png images of faces with N * D dimensions, and converts
this into a tensor of N * N matrices of the right input size (ex. 96x96) for
the neural network. Configured to use with cropped pngs of MTCNN.
Author: Boaz Vetter, 2020
"""
import os
i... |
import random
#The Monty Hall problem.
numExperiments = 1000000
firstGuessExperiments = 0
secondGuessExperiments = 0
winFirstGuess = 0
winSecondGuess = 0
#win counters
for experimentNum in range(numExperiments):
#picking the 1 is a win, picking a 0 is a loss.
doors = [1,0,0]
random.shuffle(doors)
#rando... |
import string
wordList = ['girl.','icecream','--sdafojieea']
index = 0
for word in wordList:
wordList[index] = word.strip(string.punctuation)
print(word)
index += 1;
print(wordList)
|
import pygame
import random
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
class Star:
def __init__(self, x, y):
self.x = x
self.y = y
self.slower = 0
direction = random.choice([-1, 1])
self.x_speed = random.randint(2, 4) * direction
self.y_speed = random.randint(2, 4) *... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##### Written by Hadrien Gourlé. Feel free to use and modify #####
Description="Script that gives you the reverse complement of a sequence."
import argparse
parser=argparse.ArgumentParser(description=Description)
parser.add_argument("filetype",choices=["s","f"],
help="Fil... |
'''
x1,y1,x2,y2,x3,y3=eval(raw_input('x1,y1,x2,y2,x3,y3'))
c=math.sqrt(pow(x1-x2,2)+(y1-y2,2))
a=math.sqrt(pow(x2-x3,2)+(y2-y3,2))
b=math.sqrt(pow(x3-x1,2)+(y3-y1,2))
'''
'''
a=float(raw_input('>>'))
if int(a%2)==0:
print('yes')
else:
print('no')
'''
'''
a=raw_input('shuaibushuai')
if a == y
b=raw_input... |
'''
#1
def getPentagonalNumber(n):
for i in range(1,101):
for x in range(i):
a=x*(3*x-1)/2
print(a,end = '')
print(i*(3*i-1)/2)
'''
'''
#2
def sumDigits(n):
s=0
while n!=0:
s=s+n%10
n=n/10
return s
a=eval(raw_input('>>>'))
print(sunDigits(a))
... |
"""playCheckers.py
============================================
The secondary file which contains the main function to run the game versus the AI opponent
"""
from classes import *
from termcolor import colored
import webbrowser
import time
def get_coord(coord):
"""Converts the user input into the program bas... |
'''Python tiene un tipado dinamico, lo que quiere decir que una variable puede cambiar de tipo indistintamente, ademas de
que en python no se declara el tipo de variable al inicializarse esta'''
var = 5
print(var)
var ="hello"
print(var)
print("------------------------")
'''Ahora veremos la sintaxis de los bucles ... |
print('The quick brown fox', 'jumps over', 'the lazy dog')
name = input('please enter your name:')
print('hello,', name)
|
"""
Project: PolySolvy Version X
Math 351 - Numerical Analysis
Under the instruction of Professor Eric Merchant
Team: Nathan, Jaeger, Ronnie
File Description:
bivariate.py takes a vector of coeffs generated by vmond.py for
a bivariate interpolating polynomial. It implements a naive function Bivariate() whi... |
# File: button.py
"""
This file defines the GButton class, which implements a simple onscreen
button.
"""
from pgl import GCompound, GRect, GLabel, GWindow
# Class: GButton
class GButton(GCompound):
"""
This class implements a simple onscreen button consisting of a
GCompound with a GRect and a GLabel. ... |
import random
from random import choice
import time
random.seed(time.time)
dict = {
"Kaiserschmarrn": {
"Kalorien": 500,
"Art": 'vegetarisch'
},
"Chilli": {
"Kalorien": 480,
"Art": 'fleisch'},
"Toast": {
"Kalorien": 600,
"Art": 'vegetarisch'
... |
class HTMLElement:
indent_size = 2 # +1 point here, we used spacebar in non class approach
def __init__(self, name="", text=""): # Name is the name of the element and text it the actual text
self.name = name
self.text = text
self.elements = [] # Why is this used? Lets find out - > elem... |
class User:
def __init__(self, name):
self.name = name
def show_name(self):
print("Hi There, what's happening {}". format(self.name))
if __name__ == "__main__":
user = User(name = "Shaan")
user.show_name()
print("*" * 10) |
# Definition:
# The Decorator Pattern attaches additional
# responsibilities to an object dynamically.
# Decorators provide a flexible alternative to
# subclassing for extending functionality.
from abc import ABC, abstractmethod
# A normal bevrage, it can be coffee, it... |
# Permutation means to find the "NO OF WAYS" to arrange a given set/num/str
# here the order does matter and is consider a unique permutation... ABC, BCA, ACB are all acceptable
# Example -- You do a permutation when you want to crack a password
# COMBINATION is to combine
# That means we order doesn't matter and ABC... |
#output format
s = 'ABC'
print str(s)
print repr(s)
print str(0.1)
print repr(0.1)
a = '1'
b = 1
print a == b
print a == repr(b)
print '10'.rjust(10)
print '10'.ljust(10) ,'|'
print '10'.zfill(10)
print '-10'.zfill(10)
print '10.001'.zfill(2)
print int(a) == b
|
#!usr/bin/python
# -*- coding=Utf-8 -*-
import math
class Vecteur:
"""Classe représentant un vecteur de dimension finie n"""
def __init__(self, *coords):
"""Constructeur de la classe"""
self.coords = coords
def __repr__(self):
"""Affiche le vecteur proprement"""
r... |
from copy import deepcopy
from enum import Enum
class Game:
board = None
is_finished = False
def __init__(self, board):
self.board = board
def select_move(self, selection):
"""
Select a particular move to execute.
Returns:
bool: Whether or not the move w... |
import re
from .replace_numbers import replace_basic_numbers, decimal_regex
from .utils import combine_words_for_sentence
dollar_sign_regex = '\$(?:\s?)'
modifier_regex = '(\s(?=\w))?(?P<modifier>\w*)'
dollar_regex = re.compile(r'' + dollar_sign_regex +
'(?P<amount>\d+)' + decimal_regex +
... |
import os
import pygame
from game_state import Action, FPS
from pygame.locals import *
def load_images():
"""Load all images required by the game and return a dict of them.
The returned dict has the following keys:
background: The game's background image.
bird-wingup: An image of the bird with its w... |
#This file will contain some functions to solve a quadratic equation
#Note that some functions will start with an underscore _
#These functions are considered private,
#i.e. when we import this file in some other file,
#we won't be able to use the functions that start with an underscore in that other file...
#IIRC same... |
from random import randint
print('------ Jogo da Adivinhação ------ ')
jogador = int(input('Escolha um número entre 0 e 5 e tente adivinhar em qual numero eu pensei: '))
computador = randint(1, 10)
contador = 1
while computador != jogador:
if computador > jogador:
jogador = int(input('\033[31mMais... ... |
velocidade = float(input('Digite a sua velocidade em km: '))
multa = (velocidade - 80) * 7.0
if velocidade > 80:
print('Você excedeu o limite de velocidade! \nO valor total da sua multa é {}R$'.format(multa))
else:
print('Muito bem! Continue dirigindo com segurança!') |
altura = float(input('Digite a altura em metros:'))
largura = float(input('Digite o largura em metros:'))
area = altura*largura
tinta = area/2
print('A dimensão é {}x{} e sua área é {:.2f}m²'.format(altura, largura, area))
print('A quantidade de tinta necessária é de {:.2f} Litros'.format(tinta))
|
num = int(input('Digite um numero: '))
c = num
f = 1
print('O fatorial do numéro {} é:'.format(num))
for c in range(num, 0, -1):
print(' {} '.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print(' {} '.format(f)) |
nome = str(input('Digite seu nome completo: '))
print('O seu nome em maísculo: ',nome.upper())
print('O seu nome em minúsculas: ', nome.lower())
# ==== algoritmo para contar a quantidade de letras sem os espaços ======
divisao = nome.split() # divide a string em forma de lista;
uniao = ''.join(divisao) #... |
cont = 0
total = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont = cont + 1
total = total + c
print('todos os {} valores do intervalo de 1 a 500 tem uma soma de {}'.format(cont, total))
|
cidade = str(input('Qual cidade você nasceu? ')).strip()
cidade1 = cidade.upper().lower().split()
print('santo'in cidade1)
|
r1 = float(input('Digite o primeiro segmento de reta: '))
r2 = float(input('Digite o segundo segmento de reta: '))
r3 = float(input('Digite o terceiro segmento de reta: '))
if abs(r1-r2) < r3 < r1 + r2:
print('Esses segmentos podem formar um triângulo')
else:
print('Esses segmentos NÃO podem formar u... |
menor = maior = cont = soma = n = 0
continuar = 's' or 'n'
while continuar == 's':
n = int(input('Digite um valor: '))
continuar = str(input('Você deseja continuar [S / N]? ')).strip().lower()
cont += 1
soma += n
media = soma / cont
if cont == 1:
maior = menor = n
else:
... |
def countApplesAndOranges(s, t, a, b, apples, oranges):
#s start house
#t end house
#a apple point tree
#b orange point tree
totalApples = 0
totalOranges = 0
for apple in apples:
apple_in_the_house = apple + a
if apple_in_the_house >= s and apple_in_the_house <= t:
... |
#!/usr/bin/env python3
# CS765 and CS465 at Johns Hopkins University.
# Module for integerizing Python objects.
# Author: Jason Eisner <jason@cs.jhu.edu>, Spring 2018, Fall 2020, Fall 2021
# The Integerizer class makes it easy to map between objects and
# integers. The objects are assigned consecutive integers start... |
def planets(x):
for i in range (0,8):
if number[i] == x:
return i + 1
return x + " is not a planet"
number= ["mercury", "venus", "earth", "mars", "jupiter", "saurnn", "uranus", "neptune"]
print (planets("comet"))
|
num = int(input("Enter the number:\n"))
for i in range(num):
if num%2==0:
num = num-1;
res = 2*i +1
print(res)
"""Output: (examples)
1) if a = 1, then output : 1
2) if a = 2, then output : 1
3) if a = 3, then output : 1, 3, 5
4) if a = 4, then output : 1, 3, 5
5) if a = 5, then output :... |
import csv
import os
import pandas as pd
import pandas_datareader
from pandas import DataFrame
import datetime
from pandas_datareader import data, wb
TIME_TRIAL_DISTANCE = 3.0
SLOWEST_PACE = 99
# Working through https://automatetheboringstuff.com/chapter12/#calibre_link-64
# 10 July 2015 branched to follow newcoder.... |
# 1,2,3
# 4,5,6
# 7,8,9
# ir de 1->9
# 1 ->2
# 1 ->4
# 1 ->5
# sucesores de 1 es 2, 4 y 5
# asi con 2 y los demas
# se mete 2, 4 y 5
# 2 no es 9 se pasa a 4 y 4 no es 9 y se pasa a 5 y 5 no es 9
# genera los sucesores de 2 que es el primero y asi se va...
def sucesores(nodo_actual):
if nodo_actual == 1:
... |
num = 1
while(num<10):
print(' '*(10-num), '*'*num )
num += 1 |
class llnode:
def __init__(self,value=None):
self.value= value
self.next= None
def getdata(self):
return self.value
def getnext(self):
return self.next
def __str__(self):
return str(self.value)
def setnext(self,newvalue):
self.next = newvalue
class li... |
import unittest
def bin_search(arr,ele):
# Base Case!
if len(arr) == 0:
return False
# Recursive Case
else:
mid = len(arr)/2
# If match found
if arr[mid]==ele:
return True
else:
# Call again on second half
if ele<arr[mid]... |
def is_palindrome(string):
i = 0
j = len(string)-1
for x in range(len(string)//2):
if string[i] != string[j]:
return False
i+= 1
j-= 1
x+= 1
print("done")
return True
string = "nitin"
print(is_palindrome(string))
|
#!/usr/bin/python3
# coding: utf-8
# IL 30.10.2017
"""
ProjectEuler Problem 10
"""
__author__ = 'ilya_il'
import time
def get_prime_numbers(upper_bound):
prime_numbers = [2, ]
n = 3
while n < upper_bound:
for pn in prime_numbers:
if n % pn == 0:
break
e... |
#!/usr/bin/python3
# coding: utf-8
# IL 30.10.2017
"""
ProjectEuler Problem 12
triangle num - 76576500
num pos - 12376
number of factors - 576
--- 2302.319999933243 seconds ---
"""
__author__ = 'ilya_il'
import time
def get_factors(num):
fact = list()
for i in range(1, int(num/2) + 1):... |
#!/usr/bin/python3
# coding: utf-8
# IL 30.10.2017
"""
ProjectEuler Problem 41
"""
__author__ = 'ilya_il'
def check_pandigital_number(s):
if len(s) == 9 and len(set(s)) == 9 and s.find('0') == -1:
return True
else:
return False
def get_prime_numbers2(upper_bound):
# get prime numbe... |
#!/usr/bin/python3
# coding: utf-8
# IL 30.10.2017
"""
ProjectEuler Problem 26
really cool doc - http://kvant.mccme.ru/pdf/2000/02/kv0200semenova.pdf
"""
__author__ = 'ilya_il'
def get_fraction(n):
"""Get fraction 1/n"""
res = ''
d = 1
# 100 - fraction len
for i in range(1, 10000):
... |
#!/usr/bin/python3
# coding: utf-8
# IL 30.10.2017
"""
ProjectEuler Problem 58
"""
__author__ = 'ilya_il'
def check_prime(n, pn_list):
"""
Check if number is prime by dividing it by real prime numbers in cycle (see problem 3)
:param n: number to check
:param pn_list: list of prime numbers
:r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 09:26:01 2018
@author: longzhan
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
torch.manual_seed(1)
word_to_ix = {"hello":0, "world":1}
embeds = nn.Embeddi... |
items = int(input("Enter number of items: "))
if items == 1:
print("$ 10.95")
else:
total = 2.95 * (items - 1) + 10.95
print("${0: 0.2f}".format(total))
|
import random as rnd
import copy
def play_randomly(board):
value = board.three_in_a_row()
counter = 0
while value == 0:
moves = board.list_moves()
# print("moves = ", moves)
if moves ==[]: return 0
random_nr = rnd.randint(0, len(moves)-1)
random_move = moves... |
# Author: Geoffrey Ranson
# SN# G11002201
# Date: mm/dd/2013
# File: Homework_chap_2.py
# Description: Brief description of what this program does
"""
ALGORITHM: The pseudocode description for how the program performs its tasks.
Write as many lines as necessary in this space to describe the
method selected t... |
# Author: Geoffrey Ranson
# S# G11002201
# Date: 06/03/2013
# File: template.py
# Description: Brief description of what this program does
"""
ALGORITHM: The pseudocode description for how the program performs its tasks.
Write as many lines as necessary in this space to describe the
method selected to solve ... |
"""
A module to define and store a movie class with his properties.
Usage : entertainment_center.py
"""
class Movie:
"""
Creating Movie class with it's properties:
movie_title, poster_image_url, trailer_youtube_id
"""
def __init__(self, movie_title, movie_imdb_link, movie_storyline, poster_image_u... |
linha = 1
coluna = 1
while linha <= 10:
print('')
while coluna <= 10:
print('{} x {} = {}'.format(linha, coluna, linha * coluna))
coluna += 1
linha += 1
coluna = 1 |
"""Code for managing game state."""
from typing import Tuple
import pygame
from game_object import GameObject
class Game(object):
"""Class for managing game objects."""
def __init__(self, screen):
"""Instantiate game."""
self.screen = screen
self.game_objects = {}
self.bg_col... |
#!/usr/bin/env python3
PLUS = '+'
MULT = '*'
# evaluate modes enum
VALUE = 0
OP = 1
SKIPPING = 2
def evaluate(ex):
total = 0
op = PLUS
currVal = ''
mode = VALUE
bracketsClosed = 0
for i, char in enumerate(ex):
if ex[:i].count(')') < bracketsClosed:
continue
if mode == SKIPPING:
mode ... |
#!/usr/bin/env python3
PREAMBLE_LENGTH = 5
#INVALID = 127
#INVALID_INDEX = 14
INVALID = 14144619
INVALID_INDEX = 504
numbers = [int(x.strip()) for x in open('input.txt')]
def part1():
for i, n in enumerate(numbers):
if i < PREAMBLE_LENGTH:
continue # makes future maths easier to just continue past prea... |
ip=input()
mylist=ip.split()
newlist=[]
for i in range(0,len(mylist)):
if mylist[i] in newlist:
continue
else:
newlist.append(mylist[i])
print(" ".join(newlist))
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", dest="file", help="input housing data file")
args = parser.parse_args()
file = args.file
data=open(file)
my_file = data.read()
my_file_lines = my_file.split('\n')
print(my_file)
for line in my_file_lines:
if line != '':
... |
import random
rand_num =0
theList=[]
while rand_num!=5:
rand_num =random.randrange(19)
theList.append(rand_num)
print(theList) |
""" Author:
Student ID : 500187737
Student Name : Anand Veerarahavan
"""
#Break statements
dig = 10
while dig > 0:
print ('The current value is:', dig)
dig = dig -1
if dig == 5:
break
print ("Completed!")
#Continue statements
dig = 11
while dig > 0:
dig -= 1
if dig == 7:
... |
import random
print ("returns a random number from range(100) : ",random.choice(range(100)))
print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1, 5, 3, 5, 9, 'll']))
print ("returns random character from string 'Hello World' : ", random.choice('Hello World'))
print (random.random())
pri... |
string, letter = input("Enter").split()
for c in string:
if letter == c:
print("Yes", string.index(c))
break
else: print("no")
|
#coding:utf-8
"""
@file: kmp
@author: IsolationWyn
@contact: genius_wz@aliyun.com
@python: 3.5.2
@editor: PyCharm
@create: 2017/7/22 0:58
@description:
--
"""
def kmp_match(text, pattern):
def init_prefix_table(word):
prefix_count = 0
prefix_table = [0]*len(word)
... |
#swapcase of characters
def swap_case(s):
word=''
for i in range(len(s)):
if s[i].isupper():
word+=s[i].lower()
elif s[i].islower():
word+=(s[i]).upper()
else:
word+=s[i]
return word
print(swap_case('HackerRank.com presents "Pythonist 2".'))
#spl... |
#open streams
f = open('ext_index.csv', 'r')
fr = open('out.csv', 'w')
##Number of colums on source file.
print("Enter number of colums:")
input(colum_num)
counter = 0
## Interates through the input file.
for str in f.read():
if str.isspace():
fr.write(",") ##writes comma to output
counter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.