text stringlengths 37 1.41M |
|---|
# --- python is strongly typed
# lets verify that every object has a definite type
for obj in [1, True, 2.5, "hello", [1, 2, 3], {1: "one", 2: "two"}]:
# hints:
# 1. print is your buddy
# 2. https://docs.python.org/3/library/functions.html#type
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
... |
# given a dict 'd', return a new dict with all duplicated values removed. keep the smallest key of duplications.
# for example, for the dict {1: 'a', 2: 'a', 3: 'b'} return {1: 'a', 3: 'b'}
from pprint import pprint
def remove_duplicates(d):
raise NotImplementedError("YOUR IMPLEMENTATION HERE")
pprint(remove_du... |
# print 10 literal in decimal base
print(10)
# print 10 literal in binary base
print(0b10)
# print 10 literal in hexadecimal base
print(0x10)
# convert to int
f = 1.5
print(int(f))
# convert to int
s = "121"
print(int(s))
# fill in objects_as_bool with the truth value of objects in 'objects'
objects = [0, 12, 0.0,... |
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
#import numpy as np
import pandas as pd
st.title('My first app')
st.write("well hello there")
df = pd.DataFrame({
'first column': ['pink', 'white', 'blue', 'black']
})
option = st.selectbox(
... |
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
button1 = 16
button2 = 12
LED1 = 11
LED2 = 13
GPIO.setup(button1, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(button2, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(LED1, GPIO.OUT)
GPIO.setup(LED2, GPIO.OUT)
BS1 = False
BS2 = False
while(1):... |
from tkinter import *
def newFile():
pass
def openFile():
pass
def SaveFile():
pass
def quitApp():
pass
def cut():
pass
def copy():
pass
def paste():
pass
def about():
pass
if __name__ == '__main__':
#Basic tkinter setup
root=Tk()
root.title("Untitled-Notepad")
root.geome... |
#a new new library for you, just like turtle or math, it is a standard python library
#it is used for pretty print, in this case we use it to print a multi-level dict
import pprint
def daily_earning_spening_dictionary(file_path):
transaction_file = open(file_path, "r")
#initialize the dict
daily_summary = ... |
import sqlite3
import json
conn = sqlite3.connect("mycontacts.db")
cur = conn.cursor()
with open("./data/fake_data/dataNov-7-2020.json", "r") as fh:
data = json.load(fh)
for contact in data:
address = f"{contact['street']}, {contact['city']}, " \
f"{contact['country']}, {contact['zipcode']}"
... |
# Approach #1 Using Recursion
# Time Limited Exceed
class Solution_Rec(object):
def PredictTheWinner(self,nums):
return self.helper(nums,0,len(nums)-1,1)>=0
def helper(self,nums,s,e,turn):
if s==e:
return turn*nums[s]
a =turn*nums[s]+self.helper(nums,s+1,e,-1*turn)
... |
'''
O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um
conjunto indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas
informadas, bem como a média das temperaturas.
'''
num = int(input("Informe quantas temperaturas são:"))
print("")
temperatura ... |
'''
Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade
de turmas e a quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos.
'''
turma = int(input("Digite a quantidade de turmas: "))
print("")
soma = 0
for a in range(1, turma +1):
alunos = int(inpu... |
'''
Os números primos possuem várias aplicações dentro da Computação, por exemplo na Criptografia. Um
número primo é aquele que é divisível apenas por um e por ele mesmo. Faça um programa que peça um
número inteiro e determine se ele é ou não um número primo.
'''
num = int(input("Digite um número inteiro: "))
x = 2
a... |
import random
import numpy as np
import pandas as pd
def convert_to_zodiac(day, month):
if (month == 3 and day > 20) or (month == 4 and day < 21):
return "Aries"
elif (month == 4 and day > 20) or (month == 5 and day < 21):
return "Taurus"
elif (month == 5 and day > 20) or (month == 6 and d... |
import numpy as np
def gradient_descent(x, y):
m_curr = b_curr = 0
iterations = 1105
n = len(x)
learning_rate = 0.0670032 # tweak as you go to make cost better
# m 2.000000000006345, b 2.9999999999770908, cost 1.0000080525120793e-22, iteration 1104
for i in range(iterations):
y_predi... |
__author__ = 'Brad'
class Flight():
"""
Stores the flight information such as origin, destination, departure and arrival times, duration, and stops
"""
def __init__(self, origin, dest, depart, arrive, duration, stops):
self.origin = origin
self.dest = dest
self.depart = depart
... |
# monopoly is responsible for:
# running the game
# turn-by-turn mechanics
# asking the player for input
# check to see if legal move
# ask player for strat (returns TRUE or FALSE)
# if player says yes, ask player to do thing (player doesn't check anything)
# state variable
import json
import rando... |
from monopoly.player import Player
class GreedyPlayer(Player):
# buy all the houses/hotels as possible
def do_strat_buy_from_bank(self, bldgs):
if bldgs:
self.explain("Building " + bldgs[0].name + " up -- as well as any other building -- as soon as possible")
return bldgs[0]
... |
"""Expresiones Booleanas."""
def es_vocal_if(letra: str) -> bool:
"""Toma un string y devuelve un booleano en base a si letra es una vocal o
no.
Restricción: Utilizar un if para cada posibilidad con la función lower().
Referencia: https://docs.python.org/3/library/stdtypes.html#string-methods
"""... |
# Coded by Stephanie Callejas
# Last Edit: 12 Nov 2018
# CS2302 Lab 4 B Project
# Instructors: Diego Aguirre and Saha, Manoj Pravakar
# Goal: Determine if a given anagram is a valid word in the english language using hash tables
# f is used to populate the tree with the words
f = open("words.txt")
word_list = f.readli... |
tupla = 1, 2, 3, 4,'Hola',3.2
print (tupla[3])
#la tupla no puede cambiar sus valores asignados
diccionario = {'nombre': 'Juan','apellido': 'López'}
usuario = {'nombre':'Pedro', 'apellido': 'Sanchez'}
lista = [diccionario, usuario]
print(diccionario['nombre'])
print (lista[1:2])
#crear llave nueva
usuario ['correo']... |
class priorityQueue(object):
def __init__(self):
self.list = []
self.size = 0
def getSize(self):
return self.size
def placeToInsert(elem, list):
mid = len(list)//2
if list[mid] == elem :
return mid
... |
import chess
def move():
turn = 0
board = chess.Board('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1')#initialize the board
print(board)
while board.legal_moves != 0:# the game will end if there's no legal move for one player
turn = turn +1
print('{} round'.format(turn)... |
import sqlite3
from tkinter import *
def insert_into_db(name,email,password):
conn = sqlite3.connect('quiz.db')
c = conn.cursor()
c.execute('create table if not exists users (user_id integer primary key autoincrement, username text, email text, password text)')
query = """INSERT INTO users (userna... |
"""
Given a word w and a string s, find all indices in s which are the starting locations of anagrams of w. For example, given w is "ab" and s is "abxaba", return [0, 3, 4]
"""
w = input()
s = input()
len_s = len(s)
len_w = len(w)
res = []
def is_anagram(first, second, n):
first_array = [0] * 26
second_array ... |
import sys # de system, para hablar con el intérprete, que en este caso es python
argumentos = sys.argv
# aquí van a estar las palabras despues de python
# nos va a dar una array (lista) con unas serie de argumentos posicionales,
# de tal manera que después de python de tal manera que:
# python cambiapalabra.py fich... |
#PYTHON
#Hecho por: Angela Quintana
#Fecha: 7 marzo 2017
try:
puntuacion_raw = raw_input("Por favor ingrese la puntuacion: ")
puntuacion = float(puntuacion_raw)
if (puntuacion <= 1.0 and puntuacion >= 0.0):
if (puntuacion >= 0.9):
print "Sobresaliente"
if (puntuacion < 0.9 and puntuacion >= 0.8):
... |
# -*- coding:utf-8 -*-
class Solution:
# return 2-dim list
def printMatrix(self, matrix):
# write code here
if not matrix:
return []
start = 0
rows = len(matrix)
columns = len(matrix[0])
result = []
while(rows>start*2 and columns>start*2):
... |
# -*- coding:utf-8 -*-
class Solution:
# solution 1
def Power_1(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
elif exponent == 1:
return base
result = 1
for i in range(abs(exponent))... |
def q_sort(l1):
if len(l1)<=1:
return l1
pivot = l1[0]
left_list, right_list = [], []
for le in l1[1:]:
if le<pivot:
left_list.append(le)
else:
right_list.append(le)
return q_sort(left_list) + [pivot] + q_sort(right_list)
n = int(input())
nums = [int(... |
print 'Welcome to the Pig Latin Translator!'
# variavel que faz parte do jogo
pyg = 'ay'
# entrada do usuário
original = raw_input("Enter a word: ")
# passando a palavra para letras minusculas
word = original.lower()
# take first letter
first = word[0]
# make word len() => retorna o tamanho de uma variavel
new_wor... |
# somar unidades de um numero inteiro
def digit_sum(x):
v = str(x)
result = 0
for un in v:
x = int(un)
result += x
return result
print digit_sum(434)
# fatorial ######
def factorial(x):
result = 1
for i in range(x):
#print i + 1
result *= (i + 1)
#prin... |
import numpy as np
a = np.arange(10)
print(a)
print(a[5]) #get 5th indexed or 6th element
print(a[2:6]) #get from 2nd to 6th element
print(a[:8:3]) #get from start to index 8, exclusive, get every 3rd element
print(a[-1]) #get last element
print(a[-3:-1]) #get 3rd positioned eleme... |
import cvc
import pvp
import pvc
import sys
def choose_game_type():
print("Hello, please choose the type of game you wish to play.")
while True:
game_type = input("Please enter PvP for player vs player, PvC for player vs computer, "
"or CvC to watch the computer battle it out.... |
# Author: Jaime O Salas
# Data Structures & Algorithms
# TA: Anithdita Nath
# Instructor: Olac Fuentes
# Last Modification: 2/8/19
# Purpose of program: The purpose of this lab is to be
# able to draw figures/fractals recursively
import matplotlib.pyplot as plt
import numpy as np
import math
import time
# method f... |
import pygame
from pygame.locals import *
import sys
import random
fps = 144
width = 600
height = 400
linethickness = 10
paddlesize = 50
paddleoffset = 20
black = (0, 0, 0)
white = (255, 255, 255)
class Ball:
def __init__(self, x=width / 2 - linethickness / 2, y=height / 2 - linethickness / 2,
... |
######################################
####### 카카오톡 코딩테스트 #############
######################################
## 십진수값을 이진수값으로 치환, 이진수 값 리스트를 문자열화
print("함수 테스트입니다.")
def binary(num):
lst = []
while num != 0:
lst.append(num % 2)
num //= 2
# print(lst, num)
if num == 1:
lst... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addNode(self, value):
temp = Node(value)
if self.head == None:
self.head = temp
else:
runner = self... |
import unittest
import tictactoe
def board(cells): return tictactoe.Board(cells)
class TicTacToeTest(unittest.TestCase):
def test_isWon(self):
_ = tictactoe.EMPTY
X = tictactoe.CROSS
O = tictactoe.NOUGHT
self.assertEqual(_, board([_,_,_,
_,_,_,
_,_,_]).isWon(... |
from random import randint
from time import sleep
from termcolor import colored
while True:
temp=randint(1,6)
if temp==6:
print('%i . lets Dice again!' %(temp))
sleep(2)
else:
playagain=input('%i .wanna play again?(y/n) ' %(temp))
if playagain=='n':
bre... |
weight=float(input('weight(kg): '))
height=float(input('height(meter): '))
bmi=weight/height**2
if bmi<18.5:
print('under weight')
elif bmi<25:
print('normal')
elif bmi<30:
print('over weight')
elif bmi<35:
print('obese')
else:
print('extremly obese')
|
def readFile():
try:
myFile = open('translate.txt', 'r')
wordList = myFile.read().split('\n')
for i in range(len(wordList)):
if i%2==0:
tempDic={}
tempDic['english']=wordList[i]
else:
tempDic['persian']=wordList... |
"""Wilsons-Algorithm.py: A python demonstration of Wilson's algorithm for generating a random spanning tree."""
__author__ = "Nathan Helgeson"
import networkx as nx
import matplotlib.pyplot as plt
from random import random
n = 100 # number of nodes for G
m = 200 # number of edges for G
G = nx.gnm_random_graph(n,... |
class Deck(object):
def __init__(self):
self.deck = []
def createDeck(self):
suits = ["Heart","Diamond","Club","Spade"]
values = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
for suit in suits:
for val in values:
card = Card(suit,... |
#create a variable with any name you like and assign it any value.
name = "Jimmy"
name = "Bob"
print 4 + 5
print "Jimmy" + name
print name + str(100)
print name + "100"
|
# Assignment: Stars
# Part I:
# Create a function called draw_stars() that takes a list of numbers and prints out *.
#
# For example:
# x = [4, 6, 1, 3, 5, 7, 25]
# draw_stars(x)should print the following in when invoked:
# ****
# ******
# *
# ***
# *****
# *******
# *************************
draw_stars([4,6,1,3,5,7,... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of tex... |
from datetime import datetime
people_dict = {} # name_input: [Persons]
def get_first_name(name_input):
first_name = ""
for char in name_input:
if char == " ":
break
else:
first_name += char
return first_name
def get_chart_block(output, num): # returns 30char + "|"
... |
from parent_class_Spooky_Workshops import *
from child_class_Student_Monster import *
# Ask for information
# evaluate information
# say which option you chose
# I should be able to create a monster
# List all workshops
# Add student to spooky workshop
# I should be able to see students grade
# print full information... |
"""Classes for workers and tasks for use with WorkerMapper."""
from multiprocessing import Process
import multiprocessing as mp
import time
import logging
class Worker(Process):
"""Worker process.
This is a subclass of process with an overriden `__init__`
constructor that will automatically generate the ... |
def func(num):
p = 2 ** num
q = 2 **(-1*num)
return p,q
print("n=2")
print(func(2))
print("n=4")
print(func(4))
print("n=6")
print(func(6))
print("n=8")
print(func(8))
print("n=10")
print(func(10))
print("n=12")
print(func(12))
print("n=13")
print(func(13))
print("n=14")
print(func(14))
print(... |
an_array = [1, 2, 3, 4, 5, 6, 7 , 8, 9, 0]
# This adds all the values in the list
print reduce(lambda x, y: x + y, an_array)
# This runs whatever command you structure out for it
print map(lambda x: x * 1 + 10, an_array)
# This gives you the value that can fully divide the number you ask it to.
print filter... |
# Numbers Range For Prime Check
numbers = range(1, 101)
# Numbers List To Be Checked For Finding Prime
numbers_check = range(2, 10)
# Check Prime Function
def prime(number):
# Check If Number Does Not Exist In Numbers List
if number not in numbers:
# Return Number Not In Range Error
... |
# Part 1
with open("Advent of Code/input_day_1.txt", "r+") as file:
numbers = file.readlines()
list_of_numbers = [int(number) for number in numbers]
for number_1 in list_of_numbers:
for number_2 in list_of_numbers:
if number_1 + number_2 == 2020:
print(f'First number is {... |
marks = []
num = 0
print("Enter your marks to get them in descending order, -1 to stop: ")
while num != -1:
num = int(input())
marks.append(num)
marks.pop()
print("Entered marks: ", marks)
marks.sort()
print("Marks in ascending order: ", marks)
marks.reverse()
print("Marks in descending order: ", marks)
|
# String can be either in single quotes or double quotes
print('Hello')
print("Hello")
# It is dynamically typed language!
# Even we get type of var, if we don't assign datatype
a = 10
print(a)
print(type(a))
a = "Python"
print(type(a))
# We get TypeError for below statement, must be str! not int as it is str!!
# a + ... |
import csv
class HardwareManager:
def __init__(self, hardware, purchaseYear, user, location):
self.hardware = hardware
self.purchaseYear = purchaseYear
self.user = user
self.location = location
print("Hardware Manager")
records = []
starter = True
while starter:
print()
... |
nums = [10, 11, 20, 21, 30, 31, 40, 41]
def iseven(n):
return n % 2 == 0
enums = filter(iseven, nums)
for n in enums:
print(n)
# using lambda
onums = filter(lambda n: n % 2 == 1, nums)
for n in onums:
print(n)
|
def add(n1, n2):
"""Adds two numbers and returns the result.
Args:
n1(int) : first number.
n2(int) : second number.
Returns:
int : Sum of the given two numbers.
"""
return n1 + n2
help(add)
print()
print(add.__doc__)
|
# class
class Product_private_members:
# initializer or special method or can be call it as constructor
def __init__(self, name, price=None):
# instance variables
# if we assigin __ before instance var then it'll become private!
# if _ then it'll become protected
# if no _ then i... |
fruits = ['orange', 'apple', 'grape', 'mango', 'apple']
print(fruits)
print(fruits.count('apple'))
fruits.append('banana')
print(fruits)
fruits.sort()
print(fruits)
print(fruits.index('apple'))
fruits.insert(1, 'mango')
print(fruits)
fruits.pop()
print(fruits)
# it can be iterable
new_fruits = []
for fruit in f... |
def getPrimes(n):
i = 2
while i < n:
prime = True
for a in range(2, i):
if i % a == 0:
prime = False
break
if prime == True:
yield i
i += 1
for i in getPrimes(100):
print(i)
|
class InsufficientBalance(Exception):
def __init__(self, balance, w_amount):
self.message = "Insufficient Balance %d, withdraw amount is %d" % (balance, w_amount)
def __str__(self):
return self.message
class Account:
minbal = 1000
def __init__(self, acno, customer, balance=0):
... |
import re
r = re.search(r"\d+", "59 abc 78")
print(r)
r = re.search(r"\d+", "abc def xyz")
print(r)
r = re.search(r"\d+", "abc 8787 def")
print(r)
|
# To be frank python doesn't support method overloading like other languages,
# but it can do like that by overriding old method
class Test:
def fun(self, x):
print("First fun!")
def fun(self, y):
print("Second fun!")
def fun(self, z):
print("Third fun!")
v = Test()
# only Third ... |
# Øving 7 - Oppgave 5a
# Håkon Ødegård Løvdal
def main():
n = int(input('Skriv inn tall: '))
print(is_prime(n))
def is_prime(tall):
if tall <= 1:
return False
elif tall > 1 and tall <= 3:
return True
else:
for x in range(2, tall):
if tall % x == 0:
return False
else:
return True
# for 0 ... |
import math
import random
import copy
# The transfer function of neurons, g(x)
def log_func(x):
return 1.0 / (1.0 + math.exp(-x))
# The derivative of the transfer function, g'(x)
def log_func_derivative(x):
return math.exp(-x) / (pow(math.exp(-x) + 1, 2))
def random_float(low, high):
r... |
# last element pivot
import random
import time
#end is included index
def quick_sort(array, start, end):
if end > start:
wall = partition(array, start, end)
quick_sort(array, start, wall-1)
quick_sort(array, wall+1, end)
# pivot is the end
def partition(array, start, end):
... |
"""
Class that represents an attempt made by students.
"""
class Node:
START_COLOR_CODE = "#9cffed"
GAVE_UP_COLOR_CODE = "#f58787"
CORRECT_COLOR_CODE = "#b3ffb0"
CORRECT_ARROW_COLOR_CODE = "#08d100"
MINIMUM_TO_BE_ANNOTATED = 10
DEGENERATE_CODE = "No completions"
DECIMAL_PRECISION = 2
S... |
"""
https://practice.geeksforgeeks.org/problems/minimum-platforms-1587115620/1#
sort both arr and dep
then move with two pointer approch
"""
class Solution:
#Function to find the minimum number of platforms required at the
#railway station such that no train waits.
def minimumPlatform(self,n,arr,... |
"""
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
Example 1:
Input:
n = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after ... |
"""
https://leetcode.com/problems/longest-consecutive-sequence/
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive e... |
"""
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums... |
"""
Execution: python cycle.py filename.txt
Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt
https://algs4.cs.princeton.edu/41graph/mediumG.txt
https://algs4.cs.princeton.edu/41graph/largeG.txt
Identifies a cycle.
Runs in O(E + V) time.
% python cycle... |
"""
Execution: python RedBlackBST.py < input.txt
Data files: https://algs4.cs.princeton.edu/33balanced/tinyST.txt
A symbol table implemented using a left-leaning red-black BST.
This is the 2-3 version.
% more tinyST.txt
S E A R C H E X A M P L E
% python RedBlackBST.py < tinyST.txt
A 8
... |
"""
Execution: python separate_chaining_hash_st.py < input.txt
Data files: https://algs4.cs.princeton.edu/33balanced/tinyST.txt
A symbol table implemented using a separate chaining hash.
This is the 2-3 version.
% more tinyST.txt
S E A R C H E X A M P L E
% python separate_chaining_hash_st... |
"""
Sorts a sequence of strings from standard input using quick 3-way sort.
% more tiny.txt
S O R T E X A M P L E
% python quick_3way.py < tiny.txt
A E E L M O P R S T X [ one string per line ]
% more words3.txt
bed bug dad yes zoo ... all bad yet
% python quick_3way.py < words3.txt
all b... |
#!./anaconda/bin/python
import random
SIZE=3
SYMBOLS=['X','O']
def print_grid(grid):
print(f' {grid[0][0]} | {grid[0][1]} | {grid[0][2]} ')
print('-----------')
print(f' {grid[1][0]} | {grid[1][1]} | {grid[1][2]} ')
print('-----------')
print(f' {grid[2][0]} | {grid[2][1]} | {grid[2][2]} ')
def c... |
#!/usr/bin/env python
# What is this ^ for?
# The line above the previous one says where in your environment to find the python executable.
def main(options):
# reading in the output file
output_file = options.output_file
#print(type(output_file))
# reading in the gtf file
gtf_file = options... |
# if statements
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
price = 1000000
has_good_credit = True
if has_good_credit:
... |
import sqlite3
#conn = sqlite3.connect('sqlitetest.db')
sqlite_file = 'C:\sqlite\db\sqlitetestdb.sqlite'
table_name = 'memberTable1'
col_fName = 'firstName'
col_sType = 'TEXT'
col_iType = 'INTEGER'
# Connecting to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# Creating a new SQLite table ... |
# comparison operators
temperature = 35
if temperature > 30:
print("It's a hot day.")
else:
print("It's not a hot day.")
# exercise - If name is less than 3 characters long
# name must be at least 3 characters
# otherwise if it's more than 50 characters long
# name can be maximum of 50 characters
# other... |
my_number = raw_input('Please Enter a Number: \n')
Please Enter a Number:
1337
print(my_number)
1337
# In Python 2 input(x) is just eval(raw_input(x)). eval() will just evaluate a generic string as if it were a Python expression.
my_raw_input = raw_input('Please Enter a Number: \n')
Please Enter a Number:
123 + 1... |
import unittest
import re
my_txt = "An investment in knowledge pays the best interest."
def LetterCompiler(txt):
result = re.findall(r'([a-c]).', txt)
return result
print(LetterCompiler(my_txt))
class TestCompiler(unittest.TestCase):
def test_basic(self):
testcase = "The best preparation for... |
import math as mymath
import unittest
# THIS CODE NEEDS TO BE FIXED, add function not available...
# i modified mymath module as math module from original code.. mymath is old module it seems , study more
class TestAdd(unittest.TestCase):
"""
Test the add function from the mymath library
"""
def test_a... |
"""
* Assignment: Type Float Altitude
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Plane altitude is 10.000 ft
2. Data uses imperial (US) system
3. Convert to metric (SI) system
4. Result round to one decimal place
5. Compare result with "Tests" section (see below)
Polish:... |
"""
* Assignment: Type Int Bits
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min
English:
1. Calculate altitude in kilometers:
a. Kármán Line Earth: 100_000 m
b. Kármán Line Mars: 80_000 m
c. Kármán Line Venus: 250_000 m
2. In Calculations use floordiv (`//`)
3. Compare res... |
"""
* Assignment: Type Int Bandwidth
* Complexity: easy
* Lines of code: 10 lines
* Time: 3 min
English:
1. Having internet connection with speed 100 Mb/s
2. How long will take to download 100 MB?
3. To calculate time divide file size by speed
3. Note, that all values must be `int` (type cast if needed... |
def anagramSolution2(s1,s2):
alist1 = list(s1)
alist2 = list(s2)
alist1.sort()
alist2.sort()
pos = 0
matches = True
while pos < len(s1) and matches:
if alist1[pos]==alist2[pos]:
pos = pos + 1
else:
matches = False
return matches
f = open("lati... |
"""
This code searches through a text file and prints out all alphabetic characters
"""
f = open('chall2.txt','r')
myli = []
while True:
c = f.read(1)
if not c:
print "End of File"
break
if c.isalpha():
myli.append(c)
print "".join(myli)
|
#To sort the given sentence's words in ascending order
inputString=input("Enter the input String : ")
print("Sorting the input string words in ascending order :")
wordList=list(inputString.split(" "))
wordList.sort()
print(wordList)
|
Symbol="*"
def main():
password=input("Enter the password:")
while not valid_password(password):
print("Invalid password")
password=input("Enter the password:")
def valid_password(password):
if len(password)<=0:
return False
password_count=0
for char in password:
if c... |
class Elevador:
"""Um elevador pro InfinityElevator8000.
Atributos:
andar: em qual andar ele está.
direção: se está parado, subindo ou descendo.
funcionando: True a menos que esteja quebrado.
chamados: lista de andares por visitar.
Métodos:
chamar(andar): adiciona o... |
"""
File: fire.py
---------------------------------
This file contains a method called
highlight_fires which detects the
pixels that are recognized as fire
and highlights them for better observation.
"""
from simpleimage import SimpleImage
# Constants
HURDLE_FACTOR = 1.05 # Controls the threshold of detecting green ... |
def write_scores(filename, scores):
"""This is a utility function to save scores from a simulation
:param filename: Filename to save scores under
:param scores: List of scores to save to file
:return: Void, writes to files stored in saved_scores
"""
f = open(f"C:\Dev\Python\RL\Policy-Based-Meth... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Qian.Wu
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""
对比列表和字典的包含操作的效率
"""
import timeit
import random
'''比较list 和 dict之间的时间差'''
for i in range(10000, 1000001, 20000):
t = timeit.Timer("ra... |
"""
CHECKS IF THE EQUATIONS ARE EQUALS OR NOT
EQ FROM: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/assignments/MIT6_042JF10_assn01.pdf
"""
F = False
T = True
p = F
q = F
r = F
equation1 = not (p or (q and r))
equation2 = (not p) and (not... |
# -*- coding: utf-8 -*-
"""
About the data:
Let’s consider a Company dataset with around 10 variables and 400 records.
The attributes are as follows:
Sales -- Unit sales (in thousands) at each location
Competitor Price -- Price charged by competitor at each location
Income -- Community income level (in ... |
# TheAntsGoMarchingLyric.py
# This program print the lyrics of The Ants Go Marching
# Writen by: Ali Arefi
def marchinglLyric(quantity, disturb):
print("The ants go marching {0} by {0}, hurrah, hurrah\n\
The ants go marching {0} by {0}, hurrah, hurrah\n\
The ants go marching {0} by {0},\n\
The... |
#!/usr/bin/python
# https://www.hackerrank.com/challenges/py-introduction-to-sets
# Enter your code here. Read input from STDIN. Print output to STDOUT
inputVal=int(input().strip());
inputArr=input().strip().split(" ");
tmpSet=set()
for n in range(inputVal):
tmpSet.add(int(inputArr[n]))
print(sum(tmpSet)/len(tm... |
#Sudoku generator for printi.me/mango
#13 September 2019, Python 3.7;2
#Adjust difficulty: line 26
#If Inconsolata Regular not installed or using non-Windows OS, change: line 48
#Change printi: line 60
from random import sample
from PIL import Image, ImageDraw, ImageFont
import printipigeon as pp
import os
print(' SU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.