text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
"""
QUESTION:
Given a string, determine if it is a palindrome, considering only
alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
EXAMPLES:
Input: "A man, a plan, a canal: Panama"
Output: true
Input: "race a car"
Ou... |
#!/usr/bin/env python3
"""
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and ... |
#!/usr/bin/env python3
"""
Given a 2d grid map of '1's (land) and '0's (water), count the
number of islands. An island is surrounded by water and is formed
by connecting adjacent lands horizontally or vertically. You may
assume all four edges of the grid are all surrounded by water.
EXAMPLES:
Input:
11110
1... |
#!/usr/bin/env python3
"""
Given a string S and a string T, find the minimum window in S which will contain
all the characters in T in complexity O(n).
EXAMPLES:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Input: S = "AA", T = "AA"
Output: "AA"
NOTE:
- T may have duplicated letters.
- If there i... |
#!/usr/bin/env python3
#
# Heap Sort.
#
# Method:
# 1. Create a max heap.
# 2. Move the head (largest element) to the bottom.
# Reduce the heap size by 1 (thus excluding the largest element at the bottom).
# 3. Re-heapify the heap from the top.
# 4. Repeat steps 2, 3 until the heap is empty.
#
# Ref: https://www.g... |
"""
Creates a conceptual grid-based maze
The actual maze is a graph of Cells.
Author: Ashley Beckers
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, List
import random
@dataclass()
class Maze:
"""
The actual maze
grid: list of cells
width: the wid... |
class ListNode:
def __init__(self, value, next=None):
self.val = value
self.next = next
class LinkedList:
def __init__(self, arr=None):
self.head = None
self.tail = None
self.appendList(arr)
def append(self, newNode):
if not self.head:
self.head... |
"""First Star"""
total_orbit_count = 0
def indirect_orbit_check(check_orbitee, orbit_map):
global total_orbit_count
for orbitee, orbiter_list in orbit_map:
if check_orbitee in orbiter_list:
total_orbit_count += 1
indirect_orbit_check(orbitee, orbit_map)
break
def... |
a = int(input("Введите число"))
sum = 0
while a > 0:
sum = sum + a % 10
a = a // 10
print(f"Сумма цифр {sum}")
|
###solution to problem 67 from ben stephenson's "the python workbook".
###i make things simpler by assuming zoo visitors are at most 1000 years old.
def get_age():
print("Enter the age of the visitor:")
result = input()
if result != '':
return float(result)
else:
return -1
age = get_age()
costs_by_ag... |
import secrets
def sel_chars(length):
# CODE THAT ASKS IF USER WANTS TO USE NUMBERS, LETTERS OR SYMBOLS
print("Alright, your password will have",length,"symbols\n")
print("Do you want to use Numbers, Letters or Special characters? Maybe all of the above?")
print("----------------------")
pri... |
import os
annee=input("Enter a year : ")
annee=int(annee)
if annee%400 == 0 or (annee%4 == 0 and annee%100 !=0):
print("The year", annee,"is a leap year")
else:
print("The year", annee,"isn't a leap year")
os.system("pause")
|
import sys
import os
import numpy as np
#these three functions implement a collision check of a given edge with a given obstacle
#the collision check is based on Jeffrey Thompson's effort (http://www.jeffreythompson.org/collision-detection/line-circle.php)
#as parameters of the main function **collision_check** the ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 15:55:45 2021
@author: Patricia
"""
print="Hello, World!"
a=7
b=5
c=a<b
if a>b:
print("*** a maior que b***")
else:
print("a menor que b")
|
#Отже, ми можемо взяти будь-яку частину коду, дати їй ім’я і винести з основного потоку програми.
#Наприклад, програма, яка шукає на відрізку від 0 до 99 всі числа, записані однаковими цифрами,
#може бути записана так:
print("#1")
n=100
for x in range(n):
is_cool = x<10 or (int(x/10)==x%10)
print(x,is_coo... |
## ========================================================================== ##
##
## Programa: 2_Patrones_ArMoon_Interfaz.py
## Autores : Arburola León, Samantha P.
## Rojas Alfaro, Luis A.
## Fecha : 07.05.2014
##
## Dibujar Patrones ArMoon con una tortuga en una ventana. Con fun-
## cionalida... |
#***********************************
#
# Mi primer programa
#
#***********************************
base= int (input( "base:"))
altura= int( input( "altura:"))
area= (base*altura) /2
print ( "el area es de :", area)
|
##--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.-##
##
## Programa: Menú_ArMoon.py
## Autores : Arburola León, Samantha
## Rojas Alfaro, Luis
## Fecha : 02.04.2014
##
## Los Patrones Armoon son representaciones mediante figuras
## especiales de números en binario ... |
#Encapsulamiento
class Fecha():
def __init__(self):
self.__dia = 1
def getDia(self):
return self.__dia #revisa el ejemplo de encapsulamiento
def setDia(self, dia):
if dia > 0 and dia < 31:
self.__dia = dia
self.__printfecha()#Metodo estatico
else:
... |
zoo=('python','elephant','penguin')
print('Number of animals in the zoo is: ',len(zoo))
new_zoo='monkey','camel',zoo
print('Number of cages in the zoo is: ',len(new_zoo))
print('all amimals in the new_zoo is: ',new_zoo)
print('Animals brought from old zoo is',new_zoo[2][2])
print('number of animals in the new zoo is: ... |
# the for loop
for i in range(1,5):# can specify the three parameter end it's become in count
print(i)# No include the second number
else:
print('the for loop is over')
# it's similar to write 'for(int i=1;i<5;i++' in Java,c
|
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.preprocessing as sk_preprocessing
import sklearn.linear_model as sk_linear_models
muscle_mass_df = pd.read_csv("data/muscle_mass.csv")
muscle_mass_df.sort_values(by="training_time", inplace=True)
X = muscle_mass_df[["training_time"]]
y = muscle_mass_d... |
# https://www.codewars.com/kata/5508249a98b3234f420000fb
from math import ceil
from string import ascii_letters, ascii_lowercase, ascii_uppercase
def moving_shift(s, shift, reverse=False):
caesar_string = ''
increment = 1 if reverse is False else -1
for letter in s:
if letter in ascii_letter... |
strA = "phong tran"
strB = strA[None:None:-1]
print(strB)
print(strA.count('n'))
print(strA.capitalize()) #in hoa chữ cái đầu
print(strA.upper())
print(strA.lower)
print(strA.title())
print(strA.ljust(20, '-'))
print(strA.center(20, '-'))
strC = "Tan tai abcd"
print(strC.find('a'))
print(strC.index('a')) ##không tì... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 18:57:05 2017
@author: Joe
"""
def get(string,numtype,bounds):
try:
value = float(input(string))
except ValueError:
return get(string,numtype,bounds)
if value in bounds:
return value
else:
return get(string,numtype,bou... |
# -*- coding: utf-8 -*-
print "I will now count my chickens:" # here we are printing some shit
print "Hens", 25.00 + 30.00 / 6.00 # some shit and calculations
print "Roosters", 100.00 - 25.00 * 3.00 % 4.00 # same here
print "Now I will count the eggs:" # prepearing to calculate some shit
print 3.0 + 2.0 + 1.0 - 5.0 +... |
# Write a function, that, given a zero-indexed array A consisting of
# N integers, returns the number of distinct values in array A.
class Distinct(object):
def solution(self, numericarray):
if len(numericarray) == 0:
return 0
return len(list(set(numericarray))) |
# Write a function that, given a non-empty zero-indexed array A,
# returns the value of the maximal product of any triplet
class MaxProductOfThree(object):
def solution(self, numericArray):
# Defensive!
if len(numericArray) == 0:
return 0
# Get the values in order Hi... |
# Step 3
def place_marker(board, marker, position):
board[position] = marker
# Step 4
def win_check(board, mark):
return(# ROWS:
(board[1] == mark and board[2] == mark and board[3] == mark) or
(board[4] == mark and board[5] == mark and board[6] == mark) or
(board[7] == mark and board[8] ... |
'''
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is di... |
'''
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string.
Consider two strings "aabcdefg" and "fbd". How many characters do we have to remove from the first string to get the second string? Although not the only way to solve this, we could create a Hash of c... |
'''
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (... |
'''
Debug celsius converter
Your friend is traveling abroad to the United States so he wrote a program to convert fahrenheit to celsius. Unfortunately his code has some bugs.
Find the errors in the code to get the celsius converter working properly.
To convert fahrenheit to celsius:
celsius = (fahrenheit - 32) * (5/... |
'''
Consider a sequence u where u is defined as follows:
The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
There are no other numbers in u.
Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13... |
'''
Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input: 21445 Output: 54421
Input: 145263 Output: 654321
Input: 1254859723 Output: 9875543221
'... |
'''
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]
Note: k... |
'''
You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:
next_bigger(12)==21
next_bigger(513)==531
next_bigger(2017)==2071
If no bigger number can be composed using those digits, return -1:
next_bigger(9)==-1
next_bigger(111)==-1
next_bigger(... |
'''
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money?
Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean.
If bonus is true, the salary should be multiplied by 10. If bonus is false, ... |
'''
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.
This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for th... |
# THis is a string object #
name = 'Ankit'
if name.startswith('Ank'):
print('Yes, the string starts with Ank')
if 'n' in name:
print('Yes, the contains the string "n"')
if name.find('kit') != -1:
print('Yes, it contains the string "kit"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']... |
class CircularQueue:
def __init__(self, maxQueueSize):
self.queueSize = maxQueueSize
self.objectList = [None] * maxQueueSize
self.head = 0
self.tail = 0
def dequeue(self):
firstPosition = self.objectList[self.head]
self.objectList[self.head] = None
if not... |
# i=1
# j=1
# while i<5:
# k=1
# while k<6:
# print(j,end=" ")
# j=j+1
# k=k+1
# print()
# i=i+1 |
#Nama:Teng Tzi Yap
#Tingkatan:3 RED
#Tahun:2021
import tkinter
from tkinter import *
from tkinter.ttk import*
from tkinter.scrolledtext import ScrolledText
from time import*
window = Tk()
window.geometry("850x430")
window.maxsize(850,430)
window.title("💰HOME LOAN CALCULATOR💸")
icon=PhotoImage(file... |
board = ['_', '_', '_',
'_', '_', '_',
'_', '_', '_']
def display_board():
print('|' + board[0] + '|' + board[1] + '|' + board[2] + '|')
print('|' + board[3] + '|' + board[4] + '|' + board[5] + '|')
print('|' + board[6] + '|' + board[7] + '|' + board[8] + '|')
winner = None
game_on = True
... |
# compares adjacent elements and sorts them
def bsort(a):
for i in range(len(a) - 1, 0, -1):
for j in range(i):
if a[j] > a[j + 1]:
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
a = [2, 54, 23, 76, 9]
bsort(a)
print(a)
|
from optparse import OptionParser
parser = OptionParser()
# set short tag "-c" and long tag "--color"
# "color" is the name of the variable where input is stored
# "red" is the default value if no input is given
parser.add_option("-c", "--color", dest="color", default="red",
help="select which color ... |
for coords in [(1, 2), (2, 5), (7, 12), (8, 2)]:
x = coords[0]
y = coords[1]
print(f"Мы на клетке [{x}, {y}]")
for coords in [(1, 2), (2, 5), (7, 12), (8, 2)]:
x, y = coords
print(f"Мы на клетке [{x}, {y}]")
for x, y in [(1, 2), (2, 5), (7, 12), (8, 2)]:
print(f"Мы на клетке [{x}, {y}]")
for ... |
from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
CLIENT_ID = "_SPOTIFY_CLIENT_ID_" # input your own
CLIENT_SECRET = "_SPOTIFY_CLIENT_SECRET_" # input your own
# spotipy auth and token generation
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope="p... |
def find_GCD(A, B):
max = A
if B > A:
max = B
B = A
A = max
while B != 0:
M = B
B = A % M
A = M
return A
def find_LCM(A, B, GCD):
LCM = (A * B) / GCD
return LCM
inp = open('test.txt', 'r')
N = int(inp.readline())
for i in range(N):
AandB = ... |
__author__ = 'Vince'
from math import sqrt
# -B +- sqrt(B ^ 2 - 4AC) / 2A
inp = open('test.txt')
out = open('result.txt', 'r+')
N = int(inp.readline())
def find_root(a, b , c):
# first check if complex number
rtarg = b ** 2.0 - 4.0 * a * c
if rtarg < 0.0:
# Complex root
rtarg *= -1.0
... |
#splits a file into list that contains a list of strings in a line.
def splitlist():
mylist = []
for line in open('test.txt', 'r'):
mylist.append(line.strip().split('\n'))
return mylist
mylist = splitlist()
Nlist = mylist[0]
N = int(Nlist[0])
for i in range(1, N + 1):
points = mylist[i]
npoints = points[0].s... |
"""
Card Names
Find the suit and rank of a card given its number in the deck.
"""
__author__ = 'Vince'
def find_card_name(card_val):
"""
Given the card number in a 52 card deck, returns the ranks
and suit of a card.
:param card_val:
:return card_suit:
:return card_rank:
"""
suits = ['... |
__author__ = 'Vince'
def rand_int_to_dice(rando, die_sides=6):
"""Converts a random number to it's associated die value."""
die_value = rando % die_sides + 1
return die_value
inp = open('test.txt')
N = int(inp.readline())
for dummy_i in range(N):
dice = inp.readline().split()
print rand_int_to_di... |
def triangle_type(side_list):
hyp = max(side_list)
hyp_square = hyp ** 2
side_sum = 0
for side in side_list:
if side != hyp:
side_sum += side ** 2
if side_sum == hyp_square:
return 'R'
elif side_sum < hyp_square:
return 'O'
else:
return 'A'
... |
def findlist(numlist, k):
numbers = numlist[k]
str_list = numbers[0].split()
int_list = []
for num in range(len(str_list)):
int_list.append(int(str_list[num]))
return int_list
#splits a file into list that contains a list of strings in a line.
def splitlist():
mylist = []
for line in open('test.txt', 'r'):
... |
infile = open('test.txt')
str = infile.read()
list = str.split()
print list
#convert list to floating point numbers
def floating_list(list):
float_list = []
for num in range(len(list)):
floatnum = float(list[num])
float_list.append(floatnum)
return float_list
#Rounds numbers in a floating point list and conve... |
import utils
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def caesar_enc(letter, key):
if letter < 'A' or letter > 'Z':
print("Invalid letter")
return
else:
return alphabet[(ord(letter) - ord('A') + key) % len(alphabet)]
def caesar_enc_string(plaintext, key):
ciphertext = ''
key =... |
def duplicate_count(text):
'''
Returns count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string.
>>> duplicate_count('abcde')
0
>>> duplicate_count('abcdea')
1
>>> duplicate_count('indivisibility')
1
>>> duplicate_count... |
# Being given a list of binary trees print all nodes that have the same position and the same value in all trees:
#
# Signature array printEqualNodes(array [ Node nodes ]) {
# Input the array of root nodes
# Output the values which exist in all trees in the same position.
#
# Example
# Input:
#
# First tree
# 10 <-... |
def process_hand(hand):
# Jack == 11, Queen == 12, etc.
face_card_dict = {'T': '10', 'J': '11', 'Q': '12', 'K': '13', 'A': '14'}
# assign number values for face cards
new_hand = []
for card in hand:
if card[0].isalpha():
new_hand.append(face_card_dict[card[0]] + card[1:])
else:
new_hand.app... |
# class sravani:
# def __init__(self,me,nithin):
# self.me=me
# self.nithin = nithin
#
# def myfunc(self):
# print("my name is " +self.me)
#
# obj1 = sravani("sravani","nithin")
# obj1.myfunc()
#
#
# class test:
# y = 10
#
# obj2 = test()
#
# print(obj2.y)
#
# class selftesting:
# def... |
'''
# python_scuola
Python3 5Finf. - AS 2019/2020
'''
import math
scelta=0
while scelta<=0 or scelta>2:
scelta=input("Effettua una scelta:\n1) Calcolo del quadrato;\n2) Calcolo della radice quadrata.\n\t\t")
scelta=int(scelta)
if scelta<=0 or scelta>2:
print("ERRORE! Scelta non valida! Valori accettabili 1... |
import re
def to_url_name(s):
"""
Convert a string to match the conventions for URL names and titles. E.g.
all lowercase, only alphanumeric characters, separated by hyphens.
"""
if type(s) == str:
raise ValueError("Need to be called with a unicode string!")
# Transliterate accented uni... |
#Proyecto: Quiz Harry Potter
#Aurot: Alexander Tzoc Guarchaj
#Carnet: 2262015
#Autor: Alvaro Abraham Lemus Santizo
#Carnet: 1631320
#Este programa le pedirá al usuario que responda un Quiz
#Llamar todas las dunciones que se necesitan
from random import randint
from time import sleep
from screen import ... |
def hello():
return("Hello, World!");
# I'm a moron.
# class Hello:
# def hello(self):
# return("Hello, World!")
# hello_world = Hello()
# print(hello_world.hello())
# class Hello:
# def hello(self):
# print('Hello, World!');
# hello_world = Hello();
# hello_world.hello();
# def hello_... |
def is_pangram(sentence):
sentence = sentence.replace(" ", "").lower()
dict = {}
for char in sentence:
if (ord(char) > 96 and ord(char) < 123):
dict[char] = 1
if (len(dict) == 26):
return True
return False
|
class Garden(object):
def __init__(self, diagram, students = None):
self._plant_codes = {
'G': 'Grass',
'C': 'Clover',
'R': 'Radishes',
'V': 'Violets'
}
if students == None:
self._students = [
'Alice',
... |
import random
def main():
continuing = True
instructions()
while continuing == True:
rolls = []
rolls_string = ''
input_string = input("What do you want to roll?: ")
if input_string == 'quit' or input_string == 'Quit':
continuing = False
else:
... |
# Method 1
# Using the infinite series 1/(1)^5 - 1/(3)^5 + 1/(5)^5 - 1/(7)^5 + ... = ((pi)^5)*(5/1536)
from functions import *
from math import factorial
def operation(n):
result = ((factorial(n))**2)*(2**n)/(factorial(2*n + 1))
return result
def operation_to_pi(n):
result = 2 * n
return result
prin... |
from SegmentWord import Segment
segment = Segment()
word_list = ['కృష్ణదేవరాయలు', 'చంద్రగుప్త మౌర్య', 'రాముడు మంచి బాలుడు','కుంతి', 'కాండౌన్']
for word in word_list:
ExtractedWord = segment.extract(word,1)
print (ExtractedWord) |
from languages import html, py, java, c, cpp
import tkinter.filedialog as f
from datetime import datetime
import os
timeCreated = datetime.today().strftime('%d-%m-%Y')
langs = ['html', 'py', 'java', 'c', 'cpp']
inputName = input('Name: ')
print('')
incorrectProjectType = True
while incorrectProjectType:
inputP... |
class Solution:
def singleNumber(self, nums):
# requires additional memory
seen = set()
for num in nums:
if num in seen:
seen.remove(num)
else:
seen.add(num)
return seen.pop()
s = Solution()
print(s.singleNumber([2,2,1]))
p... |
class Memory:
def __init__(self):
self.dict = {}
def has_key(self, name):
return name in self.dict.keys()
def get(self, name):
return self.dict.get(name, None)
def put(self, name, value):
self.dict.update({name: value})
class MemoryStack:
... |
'''https://github.com/mikesmales/Udacity-ML-Capstone/blob/master/Notebooks/2%20Data%20Preprocessing%20and%20Data%20Splitting.ipynb'''
'''https://medium.com/x8-the-ai-community/audio-classification-using-cnn-coding-example-f9cbd272269e'''
import keras
import pandas as pd
import numpy as np
from sklearn.preprocessing im... |
#Please use python3 to check the code
import re
n=int(input())
for i in range(n):
cardnumbers = input()
check1 = re.search(r"^[456]",cardnumbers) #Validate whether value starts with 4,5,6
check2 = re.match(r"(-?\d{4}){4}$",cardnumbers) #Validate that value has only digits, seperated by -
check3 = re.se... |
teams=15*int(input("How many teams?"))
if (teams%48)>=20:
print("Hire ", teams // 48+1, "Big buses and", 0, "small buses")
print("cost=$", (teams // 48+1)*200.0)
else:
print("Hire ", teams // 48, "Big buses and", (teams % 48 // 10)+1, "small buses")
print("cost=$", ((teams // 48) * 200.0)+((teams % 48 ... |
class Gocard:
def __init__(self, bal):
self.balance = bal
self.transaction = [('Initial balance', bal)]
def topup(self, amount):
amount = float(amount)
if amount > 0:
self.balance += amount
self.transaction.append(('Top up', amount))
def ride(self, ... |
hours = int(input("Hours: "))
bonus = int(input("Sale: "))
wage = (hours * 30.25)
if hours <= 37:
ow = 0
print("Wage: $", wage)
else:
hours > 37
ow = (hours - 37) * 45.375
print("Wage: $", (37 * 30.25) + ow)
wage = (37 * 30.25 + ow)
if bonus <= 3000:
b = 0
print("Sorry you didn't sel... |
def printCommand(vars, val):
if val.isalpha():
if val in vars:
print(val, 'equals', vars[val])
else:
print(val, 'is undefined.')
elif val.isdigit():
print(val)
else:
print("Syntax error.")
def inputCommand(vars, var):
if not var.isalpha():
... |
#Bus Passengers
T = 15
B = 38
S = 10
b = int(input("How many big busses? "))
s = int(input("How many small busses? "))
print("Number of teams =", (B * b + S * s) // T) |
#file: members.py
#This module defines the members of the university.
from person import *
class Member(Person):
#A Member is a Person with an ID that letters can be written to.
def __init__(self, name, address, id):
#Makes a Member.
#name is a Name.
#address is an Address.
#i... |
numbersList = []
while True:
enterNumber = input("Enter a number: ")
if enterNumber == "":
break
numbersList.append(enterNumber)
numbersList = sorted(numbersList)
median = 0
if len(numbersList)%2.0 == 0:
middle1 = int(len(numbersList)/2.0+0.5)
middle2 = int(len(numbersList)/2.0-0.5)
... |
#-*- coding: utf-8 -*-
level_count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] #階層ごとの括弧の個数を保存しておく配列(level:階層、count:番号)、グローバル変数
def readNumber(line, index):
number = 0
while index < len(line) and line[index].isdigit():
number = number * 10 + int(line[index])
index += 1
if index < len(line) and line[in... |
import re
import bs4
import urllib.parse
import requests
import pandas as pd
import numpy as np
from itertools import chain
def get_request(url):
'''
Open a connection to the specified URL and if successful
read the data.
Inputs:
url: an absolute URL
Outputs:
request object... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 18:08:08 2020
@author: s1778490
"""
def square(x):
# calculate the square of the value of x
return x*x |
import os
import sys
import csv
def import_csv(file_path):
file = open(file_path, 'r')
csvreader = csv.reader(file, delimiter=',')
prediction_data = PredictionData()
for line in csvreader:
prediction_data.append(line)
return prediction_data
def predictions_0(data):
""" Model ... |
# The purpose is to create files in a directory
# with a defined frequence.
# the title of the will be log+currentdate
# Python version is 3.
import time
import os
import csv
from datetime import date
def create_file_name():
return 'LogFiles-'+str(date.today())
#def record_data_into_csv():
# file = /Data/tem... |
#!/usr/bin/env python
"""
Ros node to make to the turtle draw a circle
"""
import rospy
from turtlesim.msg import Pose
from geometry_msgs.msg import Twist
import math
class TurtleController(object):
"""
Controls the turtle to draw a circle
"""
def __init__(self):
# turtle current position
... |
import json
import codecs
import csv
from datetime import datetime
import hashlib
from collections import defaultdict
input("Welcome! Press enter to start the conversion. This will take files from airports.dat and routes.dat and build a JSON 'database' out of them")
database = {}
# Open list of airports and extract ... |
#!/usr/bin/env python3
# Copied from tutorial on youtube by TigerHawkT3
import tkinter as tk
from idlelib.ToolTip import ToolTip as Tip
class Gear:
def __init__(self, name, description, tip, cost, quantity=0, per_second=0, limit=0):
self.name = name
self.description = description
self.tip ... |
print("I am thinking of a number between 1 and 100.");
print("Make a guess and I will tell you if you")
print("are too high, too low, or got it right. ")
print("You've got 10 attempts.")
import random
attempts = 1
x = random.randint(1,100)
guess = int(input("Enter your Number: "))
while x != guess and... |
"""
import turtle
turtle.shape("turtle")
finn = turtle.clone()
finn.shape("square")
finn.penup()
finn.goto(50,0)
finn.pendown()
finn.goto(150,0)
finn.stamp()
finn.goto(150,100)
finn.stamp()
finn.goto(50,100)
finn.stamp()
finn.goto(50,0)
finn.stamp()
charlie = turtle.clone()
charlie.shape("triangle")
charlie.penup()
cha... |
width = input("how wide?")
height = input("how tall?")
print "Here is a rectangle:"
for x in range (0,height):
print width * "*"
|
"""
EKV 2019
- made portable
Single python file
Only builtin libraries
Smartly manage unit conversions, that are configurable, and comprehensible to the human brain
There are other libraries to do similar things but they either:
- require numpy
- come with a lot more features than I want
- are intended for scientific... |
#%%
def tax(subtotal):
return subtotal * 0.08875
#%%
def set_a():
a = 10
print('the value of a:', a)
a = 20
print('Initially the value of a', a)
set_a()
print('finally the value of a', a)
#%%
l = [4, 7, 2, 6]
for num in l:
print(num*2)
#%%
x = 'hello'
type(x)
'hello'+'world'
#%%
len('hello wor... |
import random
# storing words for the mad lib
# variable has to be defined within interpreter for it to understand
verbs = ["run","skip","frolic","hide","duck","swim"]
nouns = ["The cat","An orange"]
print(verbs)
#%%
print(random.choice(nouns) + " decided to " + random.choice(verbs))
#%%
|
# Even though there are multiple objects, we still only need one class.
# No matter how many cookies we make, only one cookie cutter is needed.
class Car(object):
# The Constructor is defined with arguments.
def __init__(self, c, xpos, ypos, xspeed):
self.c = c - 100
self.xpos = xpos
self.y... |
# This script plots multiple graphs into a single plot.
# The i-th series is contained in the file data/datai.csv
# The structure of the file is (x,y): first column is x, second column is y
import matplotlib.pyplot as plt
import numpy as np
num_files = 2 # Set the number of files manually
plt.xlabel('x label')
plt.y... |
def no_duplicates(str_):
""" Determine if str_ has all unique characters """
print(set(str_))
return len(str_) == len(set(str_))
print(no_duplicates('abccdefg')) |
# Open the file mbox-short.txt and read it line by line.
# When you find a line that starts with 'From ' like the following line:
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line using split() and print out the second word
# in the line (i.e. the entire address of the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.