text stringlengths 37 1.41M |
|---|
# Memanggil library math
# Rujukan: https://docs.python.org/3/library/math.html
import math
jari_jari = float(input("Masukkan radius: ")) # Menampilkan text kemudian menunggu input nilai radius
sisi = jari_jari * 2 # Menghitung panjang sisi dengan 2x nilai dari jari ja... |
import random
def main():
file = open("silly.txt", 'r')
read_file = file.readlines()
random_line = random.choice(read_file)
print(random_line)
def reverser():
rev_file = open("reversable.txt", 'r')
read_rev_file = rev_file.readlines()
to_insert = read_rev_file[1]
print(f"welcom... |
from string_database import StringDatabase
from game import Game
import random
class Guess:
"""
This is the driver file for the game. It starts the game and has various
options for user to select, based on the option selected by user, it chooses
the appropriate action and moves the game forward or ends it.
"""
... |
#coding=utf-8
'''
max item of a array
'''
def max_item(nums):
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(nums[0], max_item(nums[1:]))
if __name__ == '__main__':
n = range(10)
assert max_item(n) == 9
n = range(10)[::-1]
assert max_item(n) == 9
|
from ps3a import *
import time
from perm import *
#
#
# Problem #6A: Computer chooses a word
#
#
def comp_choose_word(hand, word_list, start_size = HAND_SIZE, debug = False):
"""
Given a hand and a word_dict, find the word that gives the maximum value score, and return it.
This word should be calculated by c... |
def merge(x, y):
r = []
iter1 = 0
iter2 = 0
while iter1 != len(x) and iter2 != len(y):
if x[iter1] < y[iter2]:
r.append(x[iter1])
iter1 += 1
else:
r.append(y[iter2])
iter2 += 1
while iter1 != len(x):
r.append(x[iter1])
iter1 += 1
while iter2 != len(y):
r.append(y[iter2])
iter2 += 1
re... |
# coding=utf-8
import csv
from urllib.request import urlopen
import json
# Not sure this is necessary any longer
import unicodedata
import re
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(un... |
# Person类定义
class Person:
# 初始化方法
def __init__(self, name):
# 将外部传来的name赋值给Person类的__name属性,__开头的属性是私有的
self.__name = name
# 定义人洗衣服的方法
def wash_cloth(self, cloth_number, washer):
print("%s打开洗衣机盖子,放进%d件衣服" % (self.__name, cloth_number))
print("%s放进洗衣液" % self.__name)
... |
import unittest
import dictionary
class DictionaryTests(unittest.TestCase):
def setUp(self):
self.dictionary = dictionary.Dictionary()
def test_word_morphing(self):
word = 'marek'
expected = ['_arek', 'm_rek', 'ma_ek', 'mar_k', 'mare_']
morphed_words = dictionary.Dictionary... |
# Bilal Sayed C950 HashTable.py
# class to make hash table data structure
class HashTable:
index = 0
def __init__(self, length):
self.array = [None] * length
def __setitem__(self, key, value):
self.add(key, value)
def __getitem__(self, key):
return self.get(key... |
testcases = int(raw_input());
for y in range(1,testcases+1):
number_of_stations = int(raw_input());
stations ={};
for x in range(number_of_stations*2):
stations[raw_input()] = raw_input()
for x in stations.keys():
if x not in stations.values():
source = x ;
break;
print "Case #%s:"%(y),
while stations.h... |
# Author: Taimur Khan
# Purpose: Renaming files in the order of which they were modified
# Date: 22 December 2019
import os
from os import path
# Get the working directory
working_dir = os.getcwd()
# Newest to oldest or oldest to newest can be set using this boolean
newest_to_oldest = False
# Init the dictionary of... |
"""
Challenge
Create an application that mimics a simplistic debit card system. For our purposes, account
information is stored in memory only, and will be lost when the application exits.
One feature of these accounts is special support for restaurants. After a customer provides their
credit card to pay for a mea... |
"""
File: weather_master.py
Name: Johnson
-----------------------
This program should implement a console program
that asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
EXIT = -1
... |
"""
File: hailstone.py
Name: Johnson
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
print('This pr... |
from random import randint
import World
class Main:
def game(self):
world = World.World()
number_tries = 10
tries = 0
while number_tries > tries:
x = randint(1, 1000)
y = randint(1, 1000)
print(world.generate_tile(x, y))
tries = trie... |
def one_chicken(needed, provided):
if needed > provided:
if needed == provided + 1:
plural = ''
else:
plural = 's'
return f"Dr. Chaz needs {needed - provided} more piece{plural} of chicken!"
else:
if provided == needed + 1:
plural = ''
... |
set_counter = 0
keep_going = True
number_of_strings = int(input())
while keep_going:
set_counter += 1
strings = []
for string in range(number_of_strings):
strings.append(input())
print(f"SET {set_counter}")
for index in range(number_of_strings):
if index < number_of_strings / 2:
... |
N = int(input())
cups = {}
for cup in range(N):
first, second = input().split()
if str.isdecimal(first):
cups[int(first) / 2] = second
else:
cups[int(second)] = first
for radius in sorted(cups.keys()):
print(cups[radius])
|
numbers = list(map(int, input().split(' ')))
if numbers[0] + numbers[1] == numbers[2]:
print('correct!')
else:
print('wrong!') |
# https://open.kattis.com/problems/synchronizinglists
def synclist(list_1, list_2):
sorted_1 = sorted(list_1)
sorted_2 = sorted(list_2)
return [sorted_2[sorted_1.index(v)] for v in list_1]
def test_1():
assert synclist([10, 67, 68, 28, ], [55, 73, 10, 6]) == [6, 55, 73, 10]
def test_2():
assert... |
from typing import Sequence
def anotherbrick(height: int, width: int, bricks: Sequence[int]) -> bool:
for layer in range(height):
tot_width = 0
while tot_width < width:
tot_width += bricks.pop(0)
if tot_width > width:
return False
return True
def test_1():
... |
from typing import Tuple, Sequence
def cake_length(width: int, pieces: Sequence[Tuple[int, int]]) -> int:
total_area = sum([p[0]*p[1] for p in pieces])
return total_area // width
assert cake_length(width=4,
pieces=[(2,3),(1,4),(1,2),(1,2),(2,2),(2,2),(2,1)]) == 6
width = int(input())
num_pieces = int(in... |
# https://open.kattis.com/problems/internationaldates
def solution(us_eu: str) -> str:
a, b, _ = list(map(int, us_eu.split('/')))
if a > 12:
return 'EU'
elif b > 12:
return 'US'
else:
return 'either'
def test_1():
assert solution('25/03/2023') == 'EU'
assert solution('0... |
def abc(numbers, letters):
numbers.sort()
output = [numbers[ord(letter) - ord('A')] for letter in letters]
return output
assert abc([1,5,3], 'ABC') == [1,3,5]
numbers = list(map(int, input().split()))
letters = input()
print(' '.join(map(str, abc(numbers, letters))))
# from 369.3 rank 1029 to 371.1 rank ... |
# original authors: https://www.geeksforgeeks.org/python-program-for-rabin-karp-algorithm-for-pattern-searching/
import sys
import re
from typing import List, Tuple
def solution(pat: str, txt: str) -> str:
d = 256
locations = []
q = 101
M = len(pat)
N = len(txt)
i = 0
j = 0
p = 0 # has... |
from typing import Tuple
import sys, math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
... |
from typing import Tuple
def temperature(x: int, y: int) -> Tuple[str, float]:
if y == 1:
if x == 0:
return ('ALL GOOD', 0.0)
else:
return ('IMPOSSIBLE', 0.0)
return ('normal', x / (1 - y))
def test_1():
assert temperature(32, 2) == ('normal', -32)
assert tem... |
name = input()
lastchar = ''
for char in name:
if char != lastchar:
print(char, end='')
lastchar = char
print |
def rotate(c, amount):
return chr(ord('A') + (26 + (ord(c) - ord('A')) + amount) % 26)
def decrypt(cipher_text, key):
plain_text = []
for ndx, c in enumerate(cipher_text):
amount = ord(key[ndx]) - ord('A')
if ndx % 2 == 0: # decrypt, so even is shift back, odd is forward
amount ... |
# https://open.kattis.com/problems/freefood
from collections import defaultdict
def freefood(events):
food_days = defaultdict(int)
for event in events:
start, end = event
for day in range(start, end + 1):
food_days[day] += 1
return len(food_days)
def test_freefood():
asse... |
left, right = list(map(int, input().split()))
if left == right and left > 0:
print(f"Even {left * 2}")
elif left == right == 0:
print("Not a moose")
else:
print(f"Odd {max(left, right) * 2}") |
# https://open.kattis.com/problems/insert
import math
from itertools import count
_ids = count(1)
class Node():
def __init__(self, value):
self.id = next(_ids)
self.value = value
self.left = None
self.right = None
def __repr__(self):
tot = []
tot.append(f"{sel... |
import math
from typing import List
def solution(g: List[int]) -> float:
x,y, x1, y1, x2, y2 = g
if x <= x1:
dx = x1-x
if y <= y1:
dy = y1-y
return(math.sqrt(dx*dx + dy*dy))
elif y >= y2:
dy = y-y2
return(math.sqrt(dx*dx + dy*dy))
... |
Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(key, msg):
result = ''
Inset = Alphabet
Outset = key
for ch in msg:
if ch.upper() in Inset:
idx = Inset.find(ch.upper())
if ch.isupper():
result = result + Outset[idx].upper()
else:
... |
def minmax(data):
small = big = data[0] # assuming nonempty
for val in data:
if val < small:
small = val
if val > big:
big = val
return small,big
|
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10])
print("Intial Set: ")
print(set1)
# Removing elements from Set
# using Remove() method
set1.remove(5)
print("\nSet after Removal of 5: ")
print(set1)
# Removing elements from Set
# using Discard() method
set1.discard(8)
print("... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 11:29:34 2019
@author: tiagocabo
"""
# need to create an virtualenvironment
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
app = Flask(__name__) # create app variable
app.conf... |
data = '''Vixen can fly 8 km/s for 8 seconds, but then must rest for 53 seconds.
Blitzen can fly 13 km/s for 4 seconds, but then must rest for 49 seconds.
Rudolph can fly 20 km/s for 7 seconds, but then must rest for 132 seconds.
Cupid can fly 12 km/s for 4 seconds, but then must rest for 43 seconds.
Donner can fly 9 k... |
import queue
def neighbors(point):
return {(point[0] - 1, point[1]), (point[0], point[1] - 1), (point[0] + 1, point[1]), (point[0], point[1] + 1)}
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def wall(point):
x, y = point
number = x*x + 3*x + 2*x*y + y + y*y + 1352
return bin(nu... |
#from itertools import cycle
from string import ascii_lowercase as abc
current = 'cqjxjnds'
def straight(password):
for pos in range(len(password) - 2):
sub = password[pos:pos+3]
if sub in abc:
return True
return False
def unambiguous(password):
return set(password).isdisjoint... |
passcode = 'bwnlcvfs'
from hashlib import md5
from queue import PriorityQueue
def point_add(a, b):
return (a[0] + b[0], a[1] + b[1])
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def open_doors(path):
hash = md5(f'{passcode}{path}'.encode()).hexdigest()
return {door for char, door i... |
#implementing binary search
def binary_search(array, element, start, end):
if start > end:
return -1
mid = (start + end) // 2
if element == array[mid]:
return mid
if element < array[mid]:
return binary_search(array, element, start, mid-1)
else:
return bi... |
#doubly linked list add certain nodes
class Node(object):
# Doubly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
se... |
#five arithmetic operations
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
power = num1 ** num2
#printing the values
print('Sum is :',add)
print('Difference is :',dif)
print('Product is :',mul)
... |
"""
Given n number of requests
s(i) start time
f(i) finish time
s(i) < f(i)
Two requests are compatible if they don't overlap
i.e. f(i) <= s(j) or f(j) <= s(i)
Goal: Select a compatible subset of requests of maximum size
"""
def greedy_interval_scheduling(input_list):
"""
@params
inpu... |
import os
from PIL import Image
# where are the images?
old_folder = "C:\\Users\\sopsla\\Desktop\\session2a-image\\raw" # path here
# make a new folder
new_folder = "C:\\Users\\sopsla\\Desktop\\test" # path here
os.mkdir(new_folder)
# list all images in the old folder
img_list = os.listdir(old_folder)
# let's see... |
x = str(input())
for ch in x:
if(ch=='a'):
print('ka',end='')
elif(ch=='e'):
print('ke',end='')
elif (ch == 'i'):
print('ki', end='')
elif (ch == 'o'):
print('ko', end='')
elif (ch == 'u'):
print('ku', end='')
elif (ch == 'y'):
print('ky', end='... |
"""
This file creates a pipeline to input image files, do transformations and output image files with
Lane imposed in the images.
"""
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import os
# ==========================================================... |
x = int(input("Type a number: "))
def addSix (x):
return (x + 6)
print (addSix(x))
|
"""
This module is for writing the formal structure or the block world in different formats. This is
done by defining abstract base classes for Writers, which can then be implemented by Writers for
specific formats.
If you want to support additional formats, you can use the ``tarski.writers`` entry point in your
``set... |
from bs4 import BeautifulSoup # подключение библиотеки для поиска по html
import requests # подключение библиотеки для отправки и получения запросов
from openpyxl import load_workbook # подключение библиотеки для работы с excel
import re # подключение библиотеки для работы с текстом
from urllib import request
def... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 开发人员 :Davis Niu
# 开发时间 :5/18/2020 08:23 PM
# 文件名称 :2020_05_18.py
def comp(array1, array2):
"""
Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same mul... |
import re
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __iter__(self):
for word in self.words:
yield word
return
s = Sentence('niu hai bao')
for word in s:
print... |
__author__ = 'sajith'
from datetime import datetime
from datetime import timedelta
def get_floor_time(date):
if (hasattr(date, "time")):
return date.replace(hour=0, minute=0, second=0, microsecond=0)
else:
return datetime.combine(date, datetime.time(0, 0, 0, 0))
def get_time_as_str( date):
... |
# Tea types for Tea timer app
# Jonathan Clede 2016
# Designed for Python 3
class Tea(object):
"""Class for specific types of tea."""
def __init__(self, name, brew_dur, temp=None, qty=None ):
self.name = name
self.brew_dur = brew_dur
self.temp = temp
self.qty = qty
# A set... |
import itertools
def gen_triangle():
for n in itertools.count(1):
v = n * (n + 1) // 2
yield v
def gen_pentagonal():
for n in itertools.count(1):
v = n * (3 * n - 1) // 2
yield v
def gen_hexagonal():
for n in itertools.count(1):
v = n * (2 * n - 1)
yield v
... |
import sqlite3
conn = sqlite3.connect('sqltest.db')
c = conn.cursor()
#c.execute("CREATE TABLE IF NOT EXISTS books(bookid integer NOT NULL,bookname varchar(20) not null,bookquantity integer not null)")
'''
c.execute("INSERT INTO books values(1,'maths',40)")
c.execute("INSERT INTO books values(2,'science',50)")
c.execu... |
import random
N_PIECES = 100
AGING_TIME = 1000
WIDTH = 20
PROBS = {
'red': 0.2,
'yellow': 0.3,
'green': 0.4,
'gray': 0.1
}
BREAK_PROBS = {
'red': 0.3,
'yellow': 0.2,
'green': 0.1,
'gray': 0
}
GRAY_CHANGE_PROB = 0.2
class Game():
def __init__(self):
self.board = Board()
... |
class user:
def __init__(self, name):
self.name = name
self.account_balance = 1000
def account_withdrawal(self, amount):
self.account_balance -= amount
def account_deposit(self, amount):
self.account_balance += amount
blake = user("blake gifford")
john = user("john john")
jo... |
#1
# prints 5 because value return.
def a():
return 5
print(a())
#2
#prints 10 because both returned values are numbers
def a():
return 5
print(a()+a())
#3
#prints 5 because function ends at return.
def a():
return 5
return 10
print(a())
#5
#prints 5 at x definition because x = a() runs function.
#p... |
class User:
counter = 0
def __init__(self, name, email):
User.counter+=1
self.name = name
self.email = email
self.account = BankAccount()
#Made "realistic" account ID
#self.id = str(round(random.random()*8999+1000)+User.counter)
self.id = User.counter
... |
def mymax(a):
"""
Function that determines the highest number in a list and returns that number only accepts lists
of numbers and throws an AssertionError for incorrect paramater types, incorrect types in list and empty lists
Parameters
----------
a : list
list of numbers
Return
... |
class TrieNode:
"""
Class that functions as a node for a Trie tree.
Attributes
---------
letter: char
Letter on the Trie tree.
lst_next_letters: list
List containing all the letters that fall under this node.
n: int
Count of occurence of this node in the Trie.
... |
import mystack as ms
def haakjesprobleem(string):
"""
This function returns whether a string "string" follows the rules of "haakjesprobleem" correctly, using the
"mystack" class which functions as a stack. It evaluates if for every opening bracket there is an appropriate
closing bracket.
Paramete... |
from random import sample, random #used to select spies
from mission import Mission
from GameState import GameState
#from KellyAIs import dullMuteDeaf as playerBot # dullMuteDeaf is a bad AI
class ResistanceGame():
def setPlanList(self):
# missionList returns the default list of missions for the game
... |
import random
class Die :
def __init__(self, dieSides = 6) :
self.dieNum = 0
def __str__ ( self ) :
return dieNum
def random ( self ) :
dieNum = random.randint(1,6)
class Testing :
def __init__(self)
dieFirst = Die() #First die
dieSecond = Die() #Second die
player... |
a=3
o=0
print('you have: ',a,'oranges and',o,'apples')
buy_a=4
buy_o=6
print('you buy: ',buy_a,'apples and',buy_o,'oranges')
a=a+buy_a
o=o+buy_o
print('you now have:',a,'apples and',o,'oranges')
|
# Desafío - Ventas
# Patricio Cortés
# G18
# 14-09-2021
# datos de entrada argv
import sys
# diccionario ventas
ventas = {
"Enero" : 15000 ,
"Febrero" : 22000 ,
"Marzo" : 12000 ,
"Abril" : 17000 ,
"Mayo" : 81000 ,
"Junio" : 13000 ,
"Julio" : 21000 ,
"Agosto" : 41200 ,
"Septiembre" : 25000 ,
"Octubre" : 21500 ,
"Novie... |
"""Basic text read, organize by column, create pickle."""
import csv
import pickle
csv_name = 'Test_01.csv'
pickle_name = 'Test_01.pickle'
# create empty arrays to append elements later
state_ide = []
state_dur = []
# read & display csv
file = open(csv_name)
data = csv.DictReader(file)
# instead of... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 20:56:06 2021
@author: ctorti
"""
""" Functions that relate to matrices. """
import numpy as np
from general_tools.general import are_items_equal_to_within_eps
def matrix_sum_of_squares(matrix):
"""
Compute the root-sum-of-squares of a matrix.
Para... |
def sqaures(x):
return x*x
def mapper(this_func,myArgs):
result = []
for i in range(myArgs):
result.append(this_func(i))
return result
Square_result = mapper(square,[2,3,4,5,6])
print(Square_result)
|
#Greg Phillips
#9/13/17
#gradeCalculator.py - calculates the letter grade to their percentage grade
gradePercent = float(input("Enter your percent grade here: "))
if(gradePercent<60):
print("You earned an incomplete")
elif(gradePercent>=60 and gradePercent<70):
print("You earned a D")
elif(gradePercent>=70 and... |
#https://leetcode.com/problems/implement-strstr/
def find_sub_string(user_input, query):
if query in user_input:
print(user_input.index(query))
else:
print("-1")
user_input = "hello"
query = "ll"
user_input1 = "aaaaa"
query1 = "bba"
find_sub_string(user_input, query)
find_sub_string(user_input... |
# https://www.hackerrank.com/challenges/python-loops/problem
def square_the_number():
new_list=[]
user_input=int(input("enter the limit of the number to be square "))
for i in range(0,user_input):
new_list.append(i*i)
print(new_list)
square_the_number()
|
#https://leetcode.com/problems/search-insert-position/
def search_insert_position():
value_to_insert=4
user_input=[1,2,3,5]
if value_to_insert in user_input:
index_of_the_value=user_input.index(value_to_insert)
print(index_of_the_value)
else:
user_input.append(value_to_insert)
... |
#https://leetcode.com/problems/baseball-game/
def baseball_game(user_score):
operations = []
for score in user_score:
if score == "C":
operations.pop()
elif score == 'D':
operations.append(operations[-1] * 2)
elif score == '+':
operations.append(operat... |
# https://www.hackerrank.com/challenges/electronics-shop/problem?h_r=internal-search
def electronic_shop(amount, keyboard, usb):
array = [-1]
for i in range(0, len(keyboard)):
for j in range(0, len(usb)):
if keyboard[i] + usb[j] < amount:
array.append(keyboard[i] + usb[j])
... |
from nltk.tokenize import sent_tokenize
def listAppend(a, b, c):
"""Iterate over two files (strings) and place similar parts in a new list """
c = []
for item in a:
if item in b:
if item not in c:
c.append(item)
return c
def buildSubstringList(x, n):
"""Build ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "MENU Registros/n/n1)-Nuevo/n2)-Mostrar/n3" - "Eliminar Registros"
opcion = raw_input("Elige una opcion")
if opcion =="1":
print "Nuevo Registro/n"
archivo = open("progra.csv","a")
pais = raw_input (u"Ingrese el nombre del país: ")
capital = raw_input (u"Ingres... |
'''
Bradley White
Programming 1: Multi-Processor Management
CSCI-460: Operating Systems
September 26, 2017
'''
# Interpreter: Python 3.5.1
# k = 1876 % 3 + 2 = 3 processors
# $pip install simpy
import simpy
import statistics
import random
jobs = [(4, 9), (15, 2), (18, 16), (20, 3), (26, 29), (29, 198), (35, 7), (45,... |
# -*- coding: utf-8 -*-
"""Ransom note solver using hash-maps."""
# Created: 2019-03-06 Devansh Jani <devansh.jani@mysinglesource.io>
# Challenge Link https://www.hackerrank.com/challenges/ctci-ransom-note
__author__ = 'Devansh Jani <devanshjani@gmail.com>'
from collections import Counter
from typing import List
""... |
def bitStrings(n):
if n == 0: return []
if n == 1: return ["0", "1"]
return [digit+bitstring for digit in bitStrings(1) for bitstring in bitStrings(n-1)]
print(bitStrings(2))
|
class DoublyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def setHead(self,node):
pass
def setTail(self,node):
pass
def insertBefore(self,node,nodeToInsert):
pass
def insertAfter(self,node,nodeToInsert):
pass
d... |
#!env python3
message = "Hello how are you?"
for word in message.split():
print(word)
|
#!/usr/bin/env python3
"""circle_area version 1.3
Python 3.7.2"""
import math
def find_area():
"""Find the area of a user defined circle."""
while True:
radius = input('Enter the radius of the circle. ')
result = math.pi * int(radius)**2
try:
number = int(radius)
... |
#!/usr/bin/env python3
"""weird version 1
Python 3.7.2"""
def weird():
'''weird'''
while True:
pick_number = int(input('Pick a number: '))
if pick_number % 2 == 0:
print('Not Weird!')
else:
print('Weird!')
weird()
|
'''
This class serves a first cleansing of the data.
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Store training and tests sets
testSet = pd.read_csv("C:\\Users\\r.lazcano.pello\\Desktop\\Documentos no relacionados con el proyecto\\Python\\Titanico\\data\\test.csv")
trainingSet = pd.re... |
INTEGER, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, EOF = ('INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', 'LPAREN', 'RPAREN', 'EOF')
class Token():
def __init__(self,type,value):
self.type = type
self.value = value
def __str__(self):
return f'Token({self.type},{repr(self.value)})'
def ... |
# Jackson J.
# 11/13/19
# I will create the basis for a project I have had on my mind for a while
class Person:
def __init__(self, name, age, height, weight, strength):
self.name = name
self.age = int(age)
self.height = int(height)
self.weight = int(weight)
self.strength = ... |
import numpy as np
array = np.arange(20)
print(array)
r1 = np.mean(array)
print("\nMean: ", r1)
r2 = np.std(array)
print("\nstd: ", r2)
r3 = np.var(array)
print("\nvariance: ", r3)
#CHALLENGE 2
import numpy as np
import matplotlib.pyplot as plt
nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1])
bins = np.array([0... |
number_of_tests = int(input())
for i in range(number_of_tests):
args = input().split()
try:
divisible = int(args[0])
divisor = int(args[1])
print("{0}".format(divisible//divisor))
except BaseException as e:
print("Error Code:",e)
|
def greater_less(n):
if n >= 2 and n <=5 and n % 2 == 0:
print("Not Weird")
elif n >= 6 and n <=20 and n % 2 == 0:
print("Weird")
elif n > 20 and n % 2 == 0:
print("Not Weird")
else:
print("Weird")
n = int(input())
greater_less(n)
|
import math
class Point(object):
def __init__(self, x, y=None, z=None):
if type(x) is list:
self.x = x[0]
self.y = x[1]
self.z = x[2]
else:
self.x = x
self.y = y
self.z = z
def __sub__(self, other):
return Point(se... |
#Space Invaders
import turtle
import math
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Space Invaders")
running = True
points = 0
pointBox = turtle.Turtle()
pointBox.speed(0)
pointBox.color("white")
pointBox.penup()
pointBox.setposition(-290, 260)
pointString = "Points: %s" %points
pointBox.writ... |
class TrieNode:
def __init__(self, children, isWord):
self.children = children
self.isWord = isWord
class Solution:
def __init__(self):
self.trie = None
def build(self, words):
self.trie = TrieNode({},False)
for word in words:
current = self.trie
... |
from node import *
class Search:
def __init__(self, maze):
self.frontier = []
self.explored = []
self.found = False
self.node = None
self.maze = maze
def add_start_to_frontier(self):
n = Node(cell = self.maze.start, parent = None, path_cost = 0)
self.fro... |
def saludo ():
nombre ="Esli"
print ("hola")
print ("tu nombre es ", nombre)
return ## esta es la estructura basica de una funcion
print ("empezamos en un momento")
saludo()
print ("termina el programa")
input(">>>>>>>>>>>>>><<<<")
|
a=int(input("dame el valor del numero A: "))
b=int(input("dame el valor de B: "))
c=int(input("dame el valor de C: "))
print ("se procede a evealuar los numeros")
if a==b and b==c:
print ("son iguales")
elif a>b and a>c:
print ("A es mayor")
elif b>a and b>c:
print ("B es mayor")
elif c>a and c>... |
def ejemplo ():
a =10""local
print (a)
return
a=5 ## global
ejemplo();
print (a)
input(">>>>>>>")
## uso de variables locales y globales
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.