text stringlengths 5 121k |
|---|
'''
By: Manas Bundele
Project Constraints:
The goal is to train a CNN to recognize images of digits from the MNIST dataset. This dataset consists of
gray level images of size 28x28. There is a standard partitioning of the dataset into training and testing.
The training has 60,000 examples and the testing has 10,000 ... |
"""Generate "data.csv", which is used as classifier training data.
The CSV file is formatted like:
value1,value2,positive
-3.12,4.23,True
-5,5,False
-4,-4.1,False
...
"""
import random
with open('data.csv', 'w') as f:
f.write('value1,value2,positive\n')
for _ in range(1000000):
value1 = random.unif... |
from exceptions import MyException
from utility.my_date import MyDate
from utility.my_time import MyTime
class Note(object):
"""класс описывает заметку(задание)"""
def __init__(self, start: MyTime = None, end: MyTime = None, date: MyDate = None, title: str = None, description: str = None, important: int = Non... |
import psycopg2
dbname = 'wbtaflae'
user = 'wbtaflae'
password = 'PrFRj3SJLlpPBhmG8I0SY3ogazL6bmGz'
host = 'salt.db.elephantsql.com'
rpg_conn = psycopg2.connect( dbname =dbname, user=user, password=password, host=host)
print(rpg_conn)
rpg_curs = rpg_conn.cursor()
rpg_curs.execute('SELECT * FROM t... |
'''
python implement of search algorithms.
'''
def binary_search(data, find):
'''
binary search of a sorted list.
'''
start = 0
stop = len(data)-1
while(stop>=start):
mid = int((start + stop)/2)
if(find == data[mid]):
print('the index is {}'.format(mid))
... |
import requests
cus_session = requests.session()
url = 'https://passport.jiayuan.com/dologin.php?pre_url=http://www.jiayuan.com/usercp/'
formdata = {
'name': '18518753265',
'password': 'ljh123456',
'remem_pass': 'on',
'_s_x_id': '7a106b00170857e594da431080ae0761',
'ljg_login': '1',
'm_p_l': '1... |
__author__ = 'Gio'
import sys
import math
def isPrime(ashton):
p = True
for j in range(2, int(math.sqrt(ashton))):
if (ashton % j == 0):
p = False
break
return(p)
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
a = ""
b = ""
c = 0
total = 0
temp = test.split(',')
for i in temp:
if c ==... |
x = float (input ("Enter 1st Number = "))
y = int (input ("Enter 2nd Number = "))
ch = input ('Enter a Char = ') [0]
result = eval(input('Enter An Expression = '))
print(type(x))
print(type(y))
print(type(ch))
print (type(result))
z = x+y
print (z)
print(ch)
print (result)
|
import math
x = int(input('Enter First Number of your choice = '))
y = int(input('Enter Second Number of your choice = '))
z = int(input('Enter Third Number of your choice = '))
if (x > y) and (x >z) :
print('X is Greatest')
elif (y > x) and (y >z):
print('Y is Greatest')
else:
print ('Z is Greatest')
|
from numpy import *
from array import *
arr1 = array('i',[1,10,3,24,5])
arr2 = array('i',[1,2,3,4,5])
arr3 = array('i',[])
for e in range(0, len(arr1)):
arr3.append (arr1[e] + arr2[e])
print(arr3)
max = 0
for i in range(0,len(arr1)):
if max > arr1[i]:
continue
else:
max = arr1[i]
print ... |
import threading
import time
class myThread(threading.Thread):
"""
Thread count down
"""
def __init__(self, threadId, name, count):
threading.Thread.__init__(self)
self._threadId = threadId
self._name = name
self._count = count
def run(self):
print('Starting... |
from board import board
def solve(bo):
print_board(board)
print('='*25)
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo):
return T... |
from typing import Tuple, List
import pygame
def make_font(fonts: list, size: int) -> pygame.font.Font:
"""
Method responsible for making font of certain size. You can specify name of font, then it will
be searched in system fonts. If None then default font will be returned
:param fonts: list of font... |
import sys
sys.path.append('../linked_list')
from linked_list import LinkedList
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def enqueue(self, item):
self.storage.add_to_tail(item)
self.size += 1
def dequeue(self):
if self.size > 0:
self.size -= 1
r... |
prices =[10, 20, 20]
total = 0
for item in prices:
total += item
print("total {}".format(total))
|
name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
|
def pyramid(number):
pyr_result = "a" * number
return pyr_result
def illuminati(number):
x = 0
space = 0
while x <= number:
space = int((number - x) / 2)
space_result = " " * space
print(space_result, pyramid(x))
x += 2
def main():
illuminati(14)
m... |
animals = ('bear', 'bunny', 'swordfish', 'cat')
for pet in animals:
print(pet)
for pet in range(5):
print(pet) |
import smtplib
import pandas
import datetime as dt
import random
now = dt.datetime.now()
day = now.day
month = now.month
today = (month, day)
birthday = pandas.read_csv("birthdays.csv")
MY_EMAIL = "rhlywyyys@gmail.com"
MY_PASSWORD= "RACHELI200"
birthday_dict = {(data_row.month, data_row.day): data_row for (index, da... |
"""
Russian Translator
Written in Python 3.8.1
requires words.txt document
"""
import io
import sys
import time
import os as system
def examples():
print("\n \n \n")
print('=' *25)
print("\n")
with open("words.txt", "... |
num = 11
while True:
num_str = str(num)
bin_str = format(num, 'b')
oct_str = format(num, 'o')
if num_str == num_str[::-1]\
and bin_str == bin_str[::-1]\
and oct_str == oct_str[::-1]:
print(num)
break
else:
num += 2
|
"""
Authors: Orlando Coyoy, Ya'Kuana Davis, Roger Trejo
Course Name: CSCI 3725
Assignment Name: PQ1
Date: September 25, 2020
Description: This file includes a collection of functions that will either assist or cause mutations on given recipe objects
"""
import random
from classes import Recipe, Ingredient
def ingr... |
def fib(n):
assert n >= 0
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fibs = []
for i in range(1, 10):
fibs.append(fib(i))
print(fibs)
[fib(i) for i in range(1, 10)]
{i: fib(i) for i in range(1, 10)}
{fib(i) for i in range(1, 10)}
data = [fib(i) for i in range(1, 10)]
[x for x i... |
import sys
import math
print ("Enter number of tests to be run for T: ")
Not1= int(sys.stdin.readline())
print (Not1)
if Not1 < 1 or Not1> 1000:
print("ERROR: Incorrect NumberOfTests : ", Not1)
def isSubSequence(str1,str2):
m = len(str1)
n = len(str2)
p=len(str3)
j =... |
class TreeNode:
def __init__(self, data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
return "data {}".format(self.data)
def levelOrderPrint(root):
results = []
level = 0
list = [root]
results=list
... |
import numpy as np
N=8
board = np.zeros((N, N))
board[0,2]=1
board[1,2]=1
board[6,3]=1
board[4,4]=1
board[7,0]=1
print(board)
current_path = []
def is_free(x, y):
return board[x, y] == 0
def get_path(x, y):
p = (x, y)
current_path.append(p)
if (x == 0 and y == 0):
return True
success = F... |
'''
1.1 Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
'''
def isUniqueChars(s):
appears = [False]*256
for c in s:
idx = ord(c)
if appears[idx]:
return False
else:
appears[idx]=True
... |
class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def deque(self):
if len(self.s2)==0 and len(self.s1)==0:
return None
else:
if len(self.s2)==0:
while(len(self.s1)!=0):
self.s2.append(self.s1.pop())
... |
from tkinter import *
import tkinter as tk
class FoodOpt:
def __init__(self, item, side, servingI, servingS):
self.item = item
self.side = side
self.servingI = servingI
self.servingS = servingS
foodList = {
"Chicken": 335,
"Rice": 205,
"Pizz... |
name = raw_input("Enter your name : ")
while 1:
try:
age = input("Enter your age : ")
except :
print("enter a valid age : ")
continue
else :
break
x = 100 - age
if ( age > 100):
print ( " You are more than 100 years old")
else :
print (" Your will turn 100 in %d years") %(x)
|
from urllib.request import urlopen
from urllib.error import URLError
from urllib.error import HTTPError
from bs4 import BeautifulSoup
'''
02: Write a Python program to download and display the contens of robots.txt for https://en.wikipedia.org
'''
class Scraper:
'''
Loads any webpage and returns an exit code ... |
from pypoly import X
import numpy as np
def lagrange(datos):
"""
Entrada: Un conjunto de datos (ti, yi)
Salida: Polinomio interpolante del conjunto de datos con metodo de Lagrange
"""
n, pol = len(datos), 0
for j in range(n):
y = datos[j][1]
prod1, prod2 = 1, 1
for k in ... |
number_of_seats = int(input("How many seats do you want to reserve? "))
if number_of_seats <= 8:
print (f"No problem. We have a table for {number_of_seats} seats ready for you.")
else:
print ("Sorry, you will have to wait.")
|
vowel_list = ["a", "e", "i", "o", "u"]
vowel_count = 0
vowel_count_found = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
user_input = str.lower(input("Please enter a string: "))
for i in range(len(user_input)):
if user_input[i] in vowel_list:
if user_input[i] == "a":
vowe... |
from datetime import date, timedelta
class DateRangeIterable:
"""An iterable that contains its own iterator object."""
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
self._present_day = start_date
def __iter__(self):
retur... |
def ft_count_char_in_str(a, b):
c = 0
for i in a:
if i == b:
c += 1
return c
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.table import Table
from .maze import Enviroment
class ValueLearner(object):
"""Value learner for a 2D grid world.
Parameters
----------
maze : Enviroment
Maze enviroment to work with.
discount : float
Discount fa... |
"""
Created on Fri Sep 28 16:59:28 2018
@author: Melina
"""
import numpy as np
class Perceptron:
def __init__(self,eta=0.01,iter=10):
self.eta=eta
self.iter=iter
def fit(self,x,y):
self.w=np.zeros(1+x.shape[1])
self.errors=[]
for i in range(self.iter):
... |
import numpy as np
def magnitude(chirp, radar_data_type):
"""
Calculate magnitude of a chirp
:param chirp: radar data of one chirp (w x h x 2) or (2 x w x h)
:param radar_data_type: current available types include 'RI', 'RISEP', 'AP', 'APSEP'
:return: magnitude map for the input chirp (w x h)
... |
import datetime
import os
import time
list1=[1,3,6,3,21,56,8]
list2=[3,52,62,2,7,8]
set1=set(list1).union(set(list2))
set1.pop()
print(set1)
list1=list(set1)
list1.sort()
print(list1)
|
from math import *
def math_program():
f_val = 2.1
print(f"Square root {sqrt(f_val)}")
print(f"Square {pow(f_val, 2)}")
print(f"Floor {floor(f_val)}")
print(f"Ceil {ceil(f_val)}")
print(f"Round {round(f_val)}")
print(pi)
f1 = 1.0 - 0.7 - 0.3
f2 = 1.0 - 0.6 - 0.4... |
def methods_basics_program():
print(add(1, 3) == 4)
print(f2c(32) == 0)
print(abs(-12) == 12)
print(pow(2, 8) == 256)
print(is_even(6))
name = get_name()
welcome(name)
def add(a, b):
return a + b
def f2c(fahrenheit):
... |
def primitive_variables_program():
a: int = 0
b: int = 5
print(a)
print(b)
a = 6
b = a
print(b)
b += 1
print(b)
b -= 1
print(b)
a = a + 1
print(a)
b = b + 2
print(b) ... |
from random import random
def rps_program():
max_rounds = 5
human = 0
computer = 0
result = 0
this_round = 0
total: int = 0
print("Welcome to Rock, Paper and Scissors")
print("Game over!")
if tota... |
def median_kth_smallest_program():
list1 = [9, 3, 0, 1, 3, -2]
print(list1 == [-2, 0, 1, 3, 3, 9])
list2 = [5, 4, 2, 1, 7, 0, -1, -4, 12]
list3 = [2, 3, 0, 1]
list4 = [2, 3, 0, 1, 5, 4]
list5 = [5, 4, 2, 2, 1, 7, 4, 0, -1, -4, 0, 0, 12]
if __... |
def when_is_easter_sunday_program():
year = int(input("Input a year (1900-2099) > "))
a = year % 19
b = year % 4
c = year % 7
s = 19 * a + 24
d = s % 30
t = 2 * b + 4 * c + 6 * d + 5
e = t % 7
date = 22 + d + e
... |
"""
Created on Sun Sep 15 06:32:28 2019
@author: llwu
"""
import math
num_str = input("请输入整数:");
num = int(num_str)
num_n = math.sqrt(num)
n = math.floor(num_n)
left_min = n*n
mid_value = n*n + n+1
right_max = (n+1)*(n+1)
def getLeftRightSteps(input_num):
letf_right_steps = math.ceil(input_num/2)-... |
class edge:
def __init__(self, u, v, w):
self.u = u
self.v = v
self.w = w
def either(self, ):
return self.u
def other(self, p):
if self.u == p:
return self.v
else:
return self.u
def __lt__(self, other):
return... |
"""
Created on Thu May 23 07:13:26 2019
@author: chaninlaohaphan
"""
from player import MachinePlayer
import random
class RandomBot(MachinePlayer):
def make_move(self, board):
x = random.randrange(3)
y = random.randrange(3)
while board[x][y] != ' ':
x = ra... |
import folium
import pandas
data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elevation = list(data["ELEV"])
def marker_color(elevation):
if elevation < 1000:
return 'green'
elif 1000 <= elevation < 3000:
return 'orange'
else:
return 'red'
... |
import socket
import threading
from queue import Queue
open_ports = []
queue = Queue()
target = ''
def portscan(port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target, port))
return True
except:
return False
def fill_queue(port... |
import numpy as np
def h(x: np.ndarray, theta: np.ndarray):
"""
Linear regression hypothesis function.
:param x: Features. N*M matrix. N-instances, M-features
:param theta: Bias + Weights; M*1 column vector
:return: Prediction (y_hat). N*1 column vector
"""
return np.array(x @ theta, dtype... |
"""
426. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example
Given "25525511135", return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
"""
class Solution:
"""
@param s: the IP string
@return: All possi... |
"""
Supreme Court
A program that requests the name of a president as input and then
displays the names and years of the justices appointed by that president.
"""
import pickle
def main():
dicLst = createDictFromBinaryFile("JusticesDict.dat")
president = input("Enter a president: ")
getJustice(dicLst, ... |
"""
Min Function
A function that returns the minimum value in a list of numbers.
"""
def main():
min_number = min()
print("Your minimum number is:", min_number)
def min():
count = int(input("How many numbers in your list?: "))
numbers = []
for number in range(count):
number = int(input("Enter... |
"""
US Presidents
Takes the names, sorts the order by first name, then by last name.
From there, the last name is placed in front of the first name, then printed
"""
def main():
names = [("Lyndon, Johnson"), ("John, Kennedy"), ("Andrew, Johnson")]
names.sort(key=lambda name: name.split()[0])
names.sor... |
"""
Academy Awards
A program that displays the different film genres,
requests a genre as input, and then diplays the Oscar-winning films
of that genre.
Use Oscars.txt
"""
def main():
oscars = getData("Oscars.txt")
print()
genre = input("Enter a genre: ")
genre = genre.lower()
winners(os... |
def showStars(row):
for i in range(1, row + 1):
stars = '*' * i
print(stars)
showStars(5)
|
def sum_of_divisors(n):
sum=0
for div in range(1,n+1):
if(n%div==0):
sum+=div
return sum
def main():
print(sum_of_divisors(8))
print(sum_of_divisors(7))
print(sum_of_divisors(1))
print(sum_of_divisors(1000))
if __name__ == '__main__':
main() |
def column(matrix, i):
return [row[i] for row in matrix]
def row(matrix,i):
return matrix[i]
def take_submatrix_3x3(matrix,p,q):
return [matrix[i][j] for i in range(p,p+3) for j in range(q,q+3)]
def is_array_solved(arr):
unique_numbers=set(arr)
restricted_numbers=[x for x in unique_numbers if x in range(1,10)]
... |
from itertools import dropwhile, takewhile
def prime_factorization(n):
divs=[]
while(n>1):
for div in range(2,n+1):
if(n%div==0):
divs.append(div)
n//=div
break
result=[]
while(divs != []):
countOfDiv=list(takewhile(lambda x: x==divs[0], divs))
result.append((countOfDiv[0],len(countOfDiv)))
d... |
def contains_digits(number, digits):
digitsOfNumber=[]
while number!=0:
digitsOfNumber.append(number%10)
number//=10
for digit in digits:
if(not digit in digitsOfNumber):
return False
return True
def main():
print(contains_digits(402123, [0, 3, 4]))
print(contains_digits(666, [6,4]))
print(contains_di... |
def sum_of_min_and_max(arr):
maxElem=max(arr)
minElem=min(arr)
return maxElem+minElem
def main():
print(sum_of_min_and_max([1,2,3,4,5,6,8,9]))
print(sum_of_min_and_max([-10,5,10,100]))
print(sum_of_min_and_max([1]))
if __name__ == '__main__':
main() |
def sevens_in_a_row(arr, n):
if( len([x for x in arr if x==7]) >= n):
return True
return False
def main():
print(sevens_in_a_row([10,8,7,6,7,7,7,20,-7], 3))
print(sevens_in_a_row([1,7,1,7,7], 4))
print(sevens_in_a_row([7,7,7,1,1,1,7,7,7,7], 3))
print(sevens_in_a_row([7,2,1,6,2], 1))
if __name__ == '__main__'... |
pdw_id = 19
title = "The confusingly named setdefault"
pub_date = (2010, 12, 28, 11, 42)
author = "Kurt"
tags = ("dict", "setdefault", "collections", "defaultdict")
"""
dict.setdefault(key[, default]) returns the key's value if the key is in the dict.
If it's not, it inserts the default and returns that val... |
followers_list = twitterBot("username","password").get_followers()
following_list = twitterBot("username","password").get_following()
unfollower_list = twitterBot("username","password").get_unfollowers()
all_list = twitterBot("username","password").get_all()
import pandas as pd
writer = pd.ExcelWriter(... |
""" Multilayer Perceptron.
A Multilayer Perceptron (Neural Network) implementation example using
TensorFlow library. This example is using the MNIST database of handwritten
digits (http://yann.lecun.com/exdb/mnist/).
Links:
[MNIST Dataset](http://yann.lecun.com/exdb/mnist/).
Project: https://github.com/aymericdamie... |
age = int(input())
washing_machine_price = float(input())
single_toy_price = int(input())
toys_number = 0
money_as_a_gift_each_birthday = 0
money_collected_as_gift = 0
money_total = 0
for i in range(1, age + 1):
if i % 2 == 0:
money_as_a_gift_each_birthday += 10
money_collected_as_gift... |
import re
x = "Why should you learn to write programs? 7746 12 1929 8827 Writing programs (or programming) is a very creative \
7 and rewarding activity. You can write programs for many reasons, ranging from making your living to solving \
8837 a difficult data analysis problem to having fun to helping 128s... |
def sumarry():
array = [17, 1, 12, 54, 23, 9, 21]
sumarray = []
for i in array:
if i >= 3 and i <= 20:
sumarray.append(i)
print(sum(sumarray))
sumarry()
def sumval():
val1 = 0
val2 = 0
integ = []
while True:
num = int(input("Enter a Number: "))
in... |
def print_hi(N):
for i in range(1, N):
j = i
if i % 3 == 0:
j = "Frontend"
if i % 5 == 0:
j = "Backend"
if i % 5 == 0 and i % 3 == 0:
j = "Frontend Backend"
print(j, ",", end="")
if __name__ == '__main__':
print_hi(50)
|
import random
coords_list = []
y = 0
x = 0
for a in range(81):
coords_list.append((x,y))
x += 1
x %= 9
if len(coords_list) > 8 and x == 0:
y+=1
coords_list = {a:[b for b in range(1,10)] for a in coords_list}
block0 = [(0,0),(1,0),(2,0),
(0,1),(1,1),(2,1),
(0,2),(1,2)... |
"""
"""
import json
def load_from_file(file):
"""
Args:
file ():
Returns:
(Dictionary): the data from the file
"""
with open(file) as json_data:
return json.load(json_data)
def save_to_file(data, file, pretty_print=False):
"""
Args:
data (Dictiona... |
from itertools import count
class Namespace(object):
""" Namespace that provide easy nesting and collision avoidance.
String can be retrieved by means of a standard `str` built-in.
"""
def __init__(self, name='', parent=None):
self._name = name
self._parent = parent
self._chi... |
"""
Created on Sat Jan 14 19:56:09 2017
@author: aa
"""
from math import *
import matplotlib.pyplot as plt
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
p1=Point(0,0)
def arrow(f,p,angle):
A=Point(p.x+0.5*cos(pi+angle),p.y+0.5*sin(pi+angle))
B=Point(p.x+0.5*cos(angle),p.y+0.5*sin... |
a = []
a.append("Hello")
a.append("Geeks")
a.append("For")
a.append("Geeks")
print("The length of list is: ", len(a)) |
lst = []
num = int(input('Enter how many items in list: '))
for n in range(num):
numbers = int(input('Enter cost of item '))
lst.append(numbers)
print("Sum of elements in given list is :", sum(lst)) |
def one_away(first,second):
if abs(len(first) - len(second)) > 1:
return False
m = len(first)
n = len(second)
if m > n:
return one_away(second, first)
diff = n - m
i = 0
while i < m and first[i] == second[i]:
i += 1
if i... |
n = input("Enter n: ")
multiples = []
for i in range(int(n)):
if i%3 == 0 or i%5 == 0:
multiples.append(i)
print("Multiples of 3 or 5 or both are ",multiples)
print("Sum of Multiples of ",n," Numbers is ",sum(multiples)) |
import numpy as np
from activation import activation
act = activation()
def init_network():
network = {}
network['w1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
network['b1'] = np.array([0.1, 0.2, 0.3])
network['w2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
network['b2'] = n... |
import pandas as pd
'''
It is true that, very quickly, we can write some Python code to parse this CSV
and output the maximum value from the integer column without even
knowing what types are in the data:
'''
cols = [
'integercolumn',
'stringcolumn'
]
data = pd.read_csv('myfile.csv', names=cols)
print(da... |
import random
import sudoku_class
def randomize_position():
random_x = random.randint(0, 8)
random_y = random.randint(0, 8)
return random_x, random_y
def randomize_first_box():
"""used to break most easy patterns in the first box"""
random_x = random.randint(0, 3)
random_y = random.randint(0... |
from tkinter import *
def resize(ev=None):
label.config(font='Helvetica -%d bold'%scale.get())
top=Tk()
top.geometry('250x150')
label=Label(top,text='Hello World',font='Helvetica -12 bold')
label.pack(fill=Y,expand=1)
scale=Scale(top,from_=10,to=40,
orient=HORIZONTAL,command=resize)
scale.set(12)
scal... |
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(low,high):
if(i%2==0):
print(i,end=" ")
print("")
for i in range(low,high):
if(i%2!=0):
print(i,end=" ")
low=int(input("Enter the lower limit: "))
high=int(input("ENter the ... |
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) |
monthconversion={
"Jan":"January",
"Feb":"February",
"Mar":"March",
"Apr":"April",
"May":"May",
6:"June",
"Jul":"July",
"Aug":"August",
"Sep":"September",
"Oct":"October",
"Nov":"November",
"Dec":"December"
}
print(monthconversion.get("Mar"))
print(monthconversion["Jul"])
print(monthconversion[6])
prin... |
for i in range(10):
for j in range(10):
print(j,end="")
print("")
print(i)
number_grid=[
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[1][2])
for row in number_grid:
print (row)
for coloumn in row:
print(coloumn)
|
def HCF(x,y):
if x%y==0:
return y
else:
return HCF(y,x%y)
x=int(input(""))
y=int(input(""))
hcf=HCF(x,y)
lcm=(x*y)/hcf
print("The HCF is",hcf,". The LCM is",lcm) |
print(2**3)
def exponents(base,power):
i=1
for index in range(power):
i=i*base
return i
a=int(input(""))
b=int(input(""))
print(a, "raised to the power of" ,b,"would give us", exponents(a,b))
|
string=input("")
j='a'
lower=0
upper=0
space=0
for i in string:
for j in range(65,92):
if chr(j) in i:
upper=upper+1
elif j==" ":
space=space+1
for j in range(97,123):
if chr(j) in i:
lower=lower+1
print("There are",lower-sp... |
import sqlite3
import sys
def task5_sql(cursor):
print("Task 5 SQLite")
if len(sys.argv) > 1:
neighbourhood = str(sys.argv[1])
else:
neighbourhood = input("Please enter a neighbourhood: ")
try:
sql = ''' SELECT avg(price) as average_rental
FROM listings
WHERE ... |
import numpy as np
class PCA:
'''
Refactored submission for the PCA Course by the Imperial College of London on Coursera.
Many thanks to the fellow students who completed this course and provided useful tips
and guidance on the forums. None of this would have been possible without you.
... |
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if not endWord or not wordList or endWord not in wordList:
return 0
L = len(endWord)
newWordList = collections.defaultdict(list)
for word in wordList:
... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
maps = {}
for i in range(len(s)):
if s[i] in maps and maps[s[i]] != t[i]:
return False
elif s[i] not in maps:
if t[i] in maps.values():
return False
... |
class Human:
company = "Python"
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
human1 = Human("홍길동", "23", "M")
human2 = Human("장희빈", "21", "F")
human3 = Human("임꺽정", "32", "M")
print(human2.name)
print(human3.sex)
class Colleague(Human):
... |
num1 = int(input("1st number "))
num2 = int(input("2nd number "))
sign = input("which sign(+,-,/,x or *)")
if sign == "+":
print(num1+num2)
elif sign == "-":
print(num1-num2)
elif sign == "/":
print(num1/num2)
elif sign == "x" or sign == "X":
print(num1*num2)
else:
print("wrong input please try aga... |
nama = 'Waviq Subhi';
print(nama[0])
print(nama[3])
print(nama[-1])
print(nama[0:5:2])
number = "1, 2, 3, 4, 5, 6"
print(number[0::3])
print("Waviq "*2)
print("Waviq "*(3+2))
today = "sunday"
print("day" in today)
print("un" in today)
print("waviq" in "waviq")
print("sk" in "waviq") |
'''
Ternary operator
'''
if 4>5:
print('Yes')
else:
print('No')
|
'''
Reference URLs:
https://sqlite.org/cli.html
'''
import sqlite3
import argparse
from os.path import exists, join
from os import makedirs
import pandas as pd
def showSQLite3TblToCSV(inputDFPath, outputDirPath):
conn = sqlite3.connect(inputDFPath)
cursor = conn.cursor()
print(cursor)
... |
def multiples(n,k):
multiples = []
i = 1
while i < n:
if k*i < n:
multiples.append(k*i)
i += 1
else:
return multiples
m3 = multiples(10,3)
m5 = multiples(10,5)
mults = m3 + m5
answer = sum(set(mults))
assert answer == 23, "Test case failed, I got {0}".format(answer)
m3 = multiples(1000,3)
m5 = m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.