text stringlengths 37 1.41M |
|---|
def items(x,y):
return x*y
print(items('gg',5))
first_list = [21,234,13,345,56,234,6,34,12]
second_list = [234,13,235,123,56,23,1,6,12,56,123]
def same_values(x,y):
rezult = [] # local value
for key in x:
if key in y:
rezult.append(key)
rezult.sort()
return(rezult)
print(same_values(firs... |
import re
my_text = 'This is my text, created by kindix'
# find with
match = re.match('This is my text, created by (.*)', my_text)
#print(match.group(1))
my_list = [[1,2,3], [4,5,6], [7,8,9]]
my_list.append(2)
#print(my_list)
#col2 = []
#for row in my_list:
# col2 = row[1]
#print(col2)
diag = []... |
import curses
from curses.textpad import Textbox, rectangle
#make an input box for user to prompt when options are too long for command line
#this uses the curses library that is only inclueded in linux so windows users will need to use alternatives
#such as Cygwin
class TextInput(object):
@classmethod
def ... |
import requests
from bs4 import BeautifulSoup
a = '#' * 80
planet_url = "http://0.0.0.0/planets.html"
html = requests.get(planet_url)
soup = BeautifulSoup(html.text, "lxml")
#print the html as string
print(str(soup)[:100])
print(a)
#navigate to the div element
print(str(soup.html.body.div.table)[:100])
# retreive ... |
a = int(input("Give me a number 1"))
b = int(input("Give me a number 2"))
c = int(input("Give me a number 3"))
if a+b > c and a+c > b and b+c > a:
if a==b==c:
print("This traingle is equilateral")
elif a==b or a==c or b==c:
print("This traingle is isosceles")
else:
print("This is... |
class TV():
def __init__(self, inch, hz, fhd ):
self.inch = inch
self.hz = hz
self.fhd = fhd
def __str__(self):
if self.fhd == True:
return f"Your Tv has {self.inch}', {self.hz}Hz and is FullHd"
else:
return f"Your Tv has {self.inch}', {self.hz}Hz... |
# ZADANKO 1
var = input("Give me 9 characters o or x")
# sprawdzamy piony
if var[0] == var[3] == var[6] or var[2] == var[5] == var[8]:
print("WIN!!!!")
# sprawdzam rzฤ
d
elif var[0:3] =="xxx" or var[0:3] =="ooo" or var[3:6] =="xxx" or var[3:6] =="ooo" or var[6:9]=="xxx" or var[6:9]=="ooo":
print("WIN!!!")
#spra... |
#Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
name = input("Give me your name")
age = int(input("Give me your age"))
lack = 100 - age
year_when_user_100yearold = 2019 + (100 - age)
print(f"{nam... |
# This program print the change from available coins:
# available_coins: 5,2,1,0.5, 0.2, 0.1
change = float(input("How many change you have"))
available_coins = [0.05, 5, 2, 1, 0.5, 0.2, 0.1]
available_coins.sort(reverse=True)
change_in_coins = []
while (change > 0.1):
for coin in available_coins:
if coi... |
"""
โโโโโโโโโโโ โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโ
โโโ โโโโโโ โโโ โโโ โโโ
โโโโโโโโโโโโโโโโ โโโ โโโ ... |
#!/usr/bin/env python3
"""
Author : Johan Runesson <info@johanrunesson.se>
Date : 2020-08-03
Purpose: Jump the Five
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Jump the Five... |
# Creating star pyramid
print("Star pyramid\n")
limit = int(input("Enter pyramid hight limit\n"))
x = 0
y = 0
while x < limit:
z = x
while z < limit:
print(" ", end="")
z = z + 1
y = x
while y >= 0:
print("* ", end="")
y = y - 1
print("\n")
x = x + 1
|
# Here look for how to add unlimited arguments in python
print("Unlimited Argument function in python")
def names(*values):
print("first value = " + values[0] + "\nSecond Value = " + str(values[1]) + "\nThird value = " + values[2])
names("Muhammed Ajmal y", 25, "Android Developer")
x = 1
def jf():
print... |
from collections import deque
def bfs(node):
queue = deque()
visited = []
queue += node
while len(queue) != 0:
node = queue.popleft()
if node not in visited:
visited.append(node)
queue += graph[node]
print(node, "-")
if __name__ == '__main__':
... |
class Matrix:
"""
A class used to represent a Matrix
...
Attributes
----------
matrix_string : str
string with embedded newlines like:
"9 8 7\n5 3 2\n6 6 7"
Methods
-------
row(index)
returns the number "index" row as a list of integers
column(index)
... |
class Animal:
def __init__(self, name):
self.name = name
# ABSTRACT METHOD
def speak(self):
raise NotImplementedError("Subclass must will implement this abstract method")
class Dog(Animal):
# ABSTRACT METHOD IS OVERRIDDEN HERE
def speak(self):
return self.name + " says woo... |
import sqlite3
import sys
#checking for wrong usage
if len(sys.argv) != 2:
print("Wrong usage")
sys.exit()
#getting the house name provided
house = sys.argv[1]
#connecting to our database
db = sqlite3.connect("students.db")
#the db.execute (as opposed to some documentation I read, returns a list of tuples)
... |
# A RouteTrie will store our routes and their associated handlers
# A RouteTrieNode will be similar to our autocomplete TrieNode... with one additional element, a handler.
import os
class RouteTrieNode:
def __init__(self, handler):
# Initialize the node with children as before, plus a handler
sel... |
#https://www.youtube.com/watch?v=eSOJ3ARN5FM&t=842s
#https://en.wikipedia.org/wiki/A*_search_algorithm
import numpy as np
class Vertex(object):
def __init__(self, origin=None, position=None):
self.origin = origin
self.position = position
self.f = 0
self.g = 0
sel... |
print('This program turns a sentance into camel case')
userInputSentance = input("Enter a sentance to convert:")
#x = 0
#while x < len(userInputSentance):
#if userInputSentance[x] == ' ':
#takes the string and capitalizes each word using title function
userInputSentance = userInputSentance.title()
#joining the... |
# Day 2 100 days of code
# Variables
# You do not have to specify a variable type
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print("Variable z is ", z)
|
#get information
ask_user = float(input("Please give me a number"))
#do calculation
#give output
print(ask_user+2) |
#Write a program that prints out the first n triangular numbers.
n=int(input("Pick a number"))
count=0
for i in range(1,n+1):
print(i, "\t", i+count )
count+=i
|
a=float(input("Length of the first shorter side"))
b=float(input("Length of the second shorter side"))
y=float(input("Length of the longest side"))
x=(a**2+b**2)**0.5
threshold = 1e-7
if abs(x-y) < threshold:
print("TRUE")
else:
print("FALSE")
|
import string
def remove_punctuation(phrase,):
phrase_sans_punct = ""
for letter in phrase:
if letter not in string.punctuation:
phrase_sans_punct += letter
x=len(phrase_sans_punct.split())
count=0
for word in phrase_sans_punct.split():
if "e" in word:
count ... |
# Take user input of a string
user_input = input('Give me a word. ')
# Make a dictionary
dictionary = {}
# dictionary contains how many times each letter was used in word
# work through each character in input, count how many times it exists in string,
# then counts how many each appears, then adds them to dictionary
f... |
def function1(x): # here im defining the function and making x the var.
convert = (x * 1.6) #converting miles to kilometers
print ('km :')
print (convert)
function1(11) #doing the function over and over with different inputs
function1(22) #22 miles
function1(45) #45 miles
# this function converts mi... |
"""
@param: A: An integer array
@return: A list of integers includes the index of the first number and the index of the last number
"""
def FindMaxArray(A, st, ed):
if st==ed:
return (A[st], st, ed)
if st>ed:
return (-1000, st, ed)
mid = int((st + ed)/2)
# print("call", (st, ... |
#!/usr/bin/env python3
# state
memory = []
pc = 0
opcode = 0
modes = []
halt = False
# read program into memory as integers
with open("input.txt") as F:
for line in F:
for i in line.strip().split(','):
memory.append(int(i))
def opcode0102():
# opcode01 = add
# opcode02 = multiply
... |
n = int(input("How many apples are there with Harry: "))
mn = int(input("Minimum numbers of students: "))
mx = int(input("Maximum numbers of students: "))
if mn > mx:
print("This is not a range. Minimum is greater than Maximum")
if mn == mx:
print("This is not a range. Minimum and Maximum are same")
else:
... |
import heapq
import math
pqueue=[]
grafico={
"A":{"B":5,"C":1},
"B":{"A":5,"C":2,"D":1},
"C":{"A":1,"B":2,"C":4,"D":8},
"D":{"B":1,"C":4,"E":3,"F":6},
"E":{"C":8,"D":3},
"F":{"D":6}}
def iniciaDis(graph):
distancia={"A":0}
for vertex in grafico:
if vertex !=... |
dict={}
multatotal = 0
class Motorista:
empCount = 0
multa=0
def __init__(self, numero, multa):
self.numero= numero
self.multa = multa
def adicionarmulta(multa):
multa=multa+multa
while True:
str=input('digite registrar ou exibir :')
if str=='exibir':
break
... |
import time
class BlockChain:
""" a block chain implementaion in python
used for learning purpose and translated from
javascript code of
"""
def __init__(self):
self.chain = []
self.pending_transactions= []
def create_block(self, nonce, previous_block_hash, current_block_hash):
new_block = {
'index... |
"""
The meteo module contains all functions related to meteorological
variables. All meteorological functions can be calculated on a daily
or instantaneous basis. Base functions are available also. The daily
functions have a 'daily' extension, instantaneous functions have a 'inst'
extension
"""
fro... |
from vector import Vector
class Rigidbody:
gravity = 9.8 / 120
def __init__(self, obj, mass, collider):
self.mass = mass
self.velocity = Vector(0, 0)
self.acceleration = Vector(0, self.gravity)
self.rotationalVelocity = 0
self.rotationAcceleration = 0
self.maxR... |
import sqlite3
import sys
conn = sqlite3.connect('food.sqlite')
curs = conn.cursor()
query = 'SELECT * FROM Food WHERE ' + sys.argv[1]
print(query)
curs.execute(query)
print(curs.description)
names = [f[0] for f in curs.description]
for row in curs.fetchall():
print(row)
for pair in zip(names, row):
... |
name = input("Enter your name pls : ")
print(f"Welcome : " + name)
#OR
print(f"Welcome : {name}") |
# ์ด๊ฑด ์๊ฐ์ด๊ณผ,,,,
# def Oct_to_binary(n):
# if n <= 1:
# return str(n)
# answer = ''
# while True:
# if n % 2 == 0:
# answer += '0'
# else:
# answer += '1'
# n //= 2
#
# if n == 1:
# answer += '1'
# return answer[::-1]
#
#
#... |
a = [15,26,78,54,69]
print("Maximum element in the list is :", max(a), "\nMinimum element in the list is :", min(a))
a = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
a.append(numbers)
print("Maximum element in the list is :", max(a), "\nMinimum element... |
"""
Implements the transition model.
"""
import dataclasses as py_dataclasses
import random
from typing import AbstractSet, Any
import pomdp_py
from ..action import Action
from ..state import ALL_CARDS, Card, CardValue, State, Suit, lowest_club
from ..utils import agent_won_trick
class TransitionModel(pomdp_py.Tr... |
# Finding the right amount to save away
def final_savings(starting_salary, portion_saved, semi_annual_raise = .07, r = .04, months = 36):
"""Return the amounts of money saved over a specified period."""
annual_salary = starting_salary
current_savings = 0
for month in range(months):
... |
# merge all overlapping intervals
def mer (intervals):
intervals=sorted([intervals])
new_list=[]
start=intervals[0][0][0]
end =intervals[0][0][1]
print(start,end )
for i in intervals[0][1:]:
print(i)
if i[0]>=start and i[0]<=end :
if i[1]>= start and i[1]<=e... |
months = ['jan', 'feb', 'march', 'april', 'may']
# Sort list in alphabetical order
months.sort()
print(months)
# Sort list in reversed alphabetical order
months.sort(reverse=True)
print(months)
# Sort list temporarily
months = ['jan', 'feb', 'march', 'april', 'may']
print(sorted(months))
print(months)
# Reverse a l... |
# Retrieve value from dictionary
user = {
'name': 'derrick',
'email': 'derrick@gmail.com'
}
print(user.get('name'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def f(n):
"""
Calculate the next step in the collatz sequence.
Parameters
----------
n : int
Returns
-------
int
"""
if n % 2 == 0:
return n / 2
else:
return 3*n + 1
if __name__ == "__main__":
import argpa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Solves https://code.google.com/codejam/contest/4304486/dashboard#s=p1."""
def solve(lists, n):
"""
Get the missing list.
Parameters
----------
lists : list of lists
2*n - 1 lists with integers
n : int
Returns
-------
stric... |
#!/usr/bin/env python
"""Generate datasets."""
# core modules
import math
# 3rd party modules
import matplotlib.pyplot as plt
import numpy as np
def spiral(radius, step, resolution=.1, angle=0.0, start=0.0, direction=-1):
"""
Generate points on a spiral.
Original source:
https://gist.github.com/el... |
#!/usr/bin/env python
"""Example for learning a regression."""
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
import numpy
def plot(xs, ys_truth, ys_pred):
"""
Plot the true values and the predicted values.
Parameters
----------
xs : list
Numeri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate a testset for range minimum queries."""
from random import randint, seed
def generate_numbers(n, filename, minimum, maximum):
"""
Generate n numbers in the range [minimum, maximum] and store them in
filename.
Parameters
----------
n ... |
name = input()
name2 = input()
print('Hello {} {}! You just delved into python.'.format(name , name2)) |
n = int(input())
list1=[]
for p in range(n):
a = input()
b = a.split(" ")
if(b[0] == 'insert'):
i = int(b[1])
j = int(b[2])
list1.insert(i,j)
elif(b[0] == 'remove' ):
k = int(b[1])
list1.remove(k)
elif(b[0] == 'append'):
l = int(b[1])
list1.append(l)
elif(b[0] == 'sort'):
list1.sort()
el... |
'''
HEllO!!!!
Install These all Modules Before running the code :)
'''
import requests # it sends HTTP request with python
from bs4 import BeautifulSoup #Beautiful soup library is used for extracting data from website HTMl content
import pprint # it prettify's the syntax of result
import json
res = requests.get('h... |
# ***** Building a Trie in Python *****#
# ***** PROBLEM DESCRIPTION ********#
#Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete ... |
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def ... |
country_1 = input('่ซ่ผธๅ
ฅๅๅฎถ(ไธญๆ): ')
age_1 = input('่ซ่ผธๅ
ฅๅนด้ฝก: ')
age_1 = float(age_1)
if country_1 == 'ๅฐ็ฃ':
if age_1 >= 18:
print('ไฝ ๅฏไปฅ้่ป')
else:
print('ไฝ ้็กๆณ้่ป')
elif country_1 == '็พๅ':
if age_1 >= 16:
print('ไฝ ๅฏไปฅ้่ป')
else:
print('ไฝ ้็กๆณ้่ป')
else:
print('ไฝ ๅช่ฝ่ผธๅ
ฅ็พๅๆๅฐ็ฃ')
country_2 = input('่ซๅๆฌก่ผธๅ
ฅๅๅฎถ(ไธญๆ): ')
age_2 = input(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 22:02:34 2019
@author: tcm410
"""
values = []
values.append(1)
values.append(3)
values.append(5)
print('first time:', values)
values=values[1:3] #slice function
print('second time:', values)
print('string to list:', list('tin'))
print('list ... |
# Generate a basic quiver plot (vectors) inside a sphere
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.quiver([0,0,0],[0,0,0],[0,0,0],[0,0,1],[0,1,0],[1,0,0], normalize=True, color=... |
from collections import namedtuple
Point = namedtuple('Point', ('x', 'y'))
def sign (p1, p2, p3):
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
while True:
try:
x = list(map(float, input().split()))
p1 = Point(x[0], x[1])
p2 = Point(x[2], x[3])
p3 = Point(x[4], x[5])
... |
import tkinter as tk
root = tk.Tk()
canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()
def hello():
label1 = tk.Label(root, text='Hello World!', fg='green',
font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 200, window=label1)
button1 = tk.Button(text='Click Me'... |
# Logger. ะกัะฟะตะผ ะดะตะนััะฒะธั ะฒ ะปะพะณ.
# ะ ะตะบะพะผะตะฝะดัะตััั ะธัะฟะพะปัะทะพะฒะฐัั ัะพะปัะบะพ ััะฝะบัะธั write_to_log.
class Logger:
def __init__(self):
self.logfile = "log.log"
self.logfile_inst = None
def open_file_for_write(self):
self.logfile_inst = open(self.logfile,'a')
def write_to_log(self, text):
self.open_file_for... |
import random
number = random.randint(1, 100)
while (True):
user_guess = int(raw_input("pick a number between 1 and 100:")) #think about what type the input is.
print(number)
if user_guess > number:
print("Lower\n")
elif user_guess < number:
print("Higher\n")
else:
... |
import numpy as np
import pandas as pd
gp = pd.DataFrame([[30133, 2419.76], [28000,2172.90],[22286, 1350.11], [21500, 1137.52], [19530, 1562.45], [18595, 3016.3], [17000, 1375.00], [13400, 1591.76]], index=["shanghai", "beijing", "shenzhen", "guangzhou", "chongqing",... |
# create array
from numpy import array
# create array
list1 = [1.0, 2.0, 3.0]
a = array(list1)
# display array
print(a)
# display array shape
print(a.shape)
# display array data type
print(a.dtype)
# create empty array
from numpy import empty
b = empty([3,3])
print(b)
#The values or conte... |
import csv
import json
#We need to create a list of users whose passwords have been compromised.
compromised_users=[]
with open("passwords.csv") as password_file:
password_csv=csv.DictReader(password_file)
for password_row in password_csv:
#print(password_row['Username'])
compromised_users.append(password_... |
# https://www.hackerrank.com/challenges/nested-list/problem
if __name__ == '__main__':
result = {}
min_2 = 101.0
min_1 = 101.0
for _ in range(int(input())):
name = input()
score = float(input())
if score in result:
result[score].append(name)
else:
... |
x = int(input())
for i in range(1, x+1):
if(x%i == 0):
print(i, end = ' ') |
counties = ["Arapahoe", "Denver", "Jefferson"]
# if counties[1] == 'Denver':
# print(counties[1])
# if "El Paso" in counties:
# print("El Paso is in the list of counties")
# else:
# print("El Paso is not in the list of counties")
# if "Arapahoe" in counties and "El Paso" in counties:
# print("Arapaho... |
#!/usr/local/bin/python3
# -*- coding:UTF-8 -*-
"""
@desc: ๆ่ฟฐ
@Time: 2019/9/26 10:46 ไธๅ
@Author: lvxh
"""
import sys
import doctest
# ๆๆณข้ฃๅฅ(fibonacci)ๆฐๅๆจกๅ
def fib(n): # ๅฎไนๅฐ n ็ๆๆณข้ฃๅฅๆฐๅ
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a + b
print()
def fib2(n): # ่ฟๅๅฐ n ็ๆๆณข้ฃๅฅๆฐๅ
res... |
#!/usr/local/bin/python3
# -*- coding:UTF-8 -*-
"""
@desc: ้ๆฉๆๅบ
@Time: 2019/10/11 3:57 ไธๅ
@Author: lvxh
"""
import random
a = {}
num = 10
for i in range(num):
a[i] = random.randint(1, 100)
print(a)
# del a[2]
# print(a)
def chose_sort(arr):
a = []
while len(arr) > 0:
min = None
min_k ... |
#coding:utf8
#desc: ้ๅฝ่พๅบๅฝๅ็ฎๅฝไธ็ๅญ็ฎๅฝๅๆไปถ
#author: me
import os
import time
def dirlist(pathname,level=1):
if level == 1:
print "%s" % pathname
for d in os.listdir(pathname):
time.sleep(1)
print('%s|-- %s' %('| '* (level-1),d)) #่ฟไธ่กๆงๅถๆ ๅฝข็ๆ ผๅผ๏ผlevel ๆงๅถ่พๅ
ฅ | ็ๆฐ้๏ผๅฝๅๅฑ็บงๅ1
if os.path.isdi... |
#!/usr/bin/env python
#coding:utf8
def shout(word="yes"):
""""
this is shout function documents:
demoe : shout(paramsStr)
print ParamsStr
"""
return word.capitalize()+"!"
help(shout)
times = 10
print times
print times
print times
print 1.1
import decimal
print decimal.Decimal(1.1) |
import tkinter
window = tkinter.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
window.config(padx=200, pady=200)
#Label
my_label = tkinter.Label(text="I am a label", font=("Arial", 24, "bold"))
my_label.grid(column=0, row=0)
my_label["text"] = "New Text"
my_label.config(text="New T... |
import tkinter
from tkinter import messagebox
import string
from random import choice, randint
import pyperclip
import json
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate_password():
characters = string.ascii_letters + string.digits + string.punctuation
passwo... |
seq = ["nestor", "hugo", "gomez", "franco", 45, 22, False, "Python"]
# Show items and indexes from sequence using the range function
for i in range(len(seq)):
print("index", i, seq[i])
# Show items and indexes from sequence using a wrap class
class Indexed:
def __init__(self, seq):
self... |
#!/usr/bin/env python
# coding: utf-8
# # AMOGH G. LONARE
# # TASK 1 : Prediction using Supervised ML
# Predict the percentage of an student based on the no. of study hours.
# # IMPORTING LIBRARIES
# In[34]:
import numpy as np
# In[35]:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as ... |
# Necessary for the program
import json
import zipfile
import sys
# Just used for file selection gui
from tkinter.filedialog import askopenfilename
from tkinter import Tk
Tk().withdraw()
history = askopenfilename(title = "Select Zip file for analysis",filetypes = (("zip files","*.zip"),("all files","*.*")))
... |
import os
class Filelo(object):
filename = None
def __init__(self,filename):
self.filename = filename
def ReadFile(self):
try:
f = open(self.filename, "r")
text = f.read()
print(text)
f.close()
except IOError:
print(self... |
#Numeros Random
import random
print(random.randrange(1, 10))
print('\n')
#ciclos
for x in "banana":
print(x)
a = "Hello, World!"
print('\n')
print(len(a))
#Busca la palabra en el txt
txt = "The best things in life are free!"
print("free" in txt)
#Condicional if
if "free" in txt:
print("... |
# prime.py
from math import sqrt
def is_prime(x):
if x < 2:
return False
for i in range(2, int(sqrt(x))+1):
if x % i == 0:
return False
return True
def nth_prime(n):
count = -1
num = 0
while True:
if is_prime(num):
count += 1
if count... |
# Control Structures
# Exercises
# 1. Conditional Basics
# a. prompt the user for a day of the week, print out whether the day is Monday or not
print('Please enter a day of the week: ')
day = input()
if day.lower() == 'monday':
print(f'Your day is {day}!')
else:
print('Not Monday.')
# b. prompt the user for... |
def encrypt1(plaintext: str, k: int) -> str:
"""
Basic implementation of caesar cipher
"""
cipher = ''
for p in plaintext:
z = chr(((ord(p) - ord('a') + k) % 26) + ord('a'))
cipher += z
return cipher
def encrypt2(plaintext: str, k: int, alphabet: str = "abcdefghijklmnopqrstuv... |
import sqlite3
with sqlite3.connect('db.sqlite3') as connection:
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)')
cursor.execute('INSERT OR IGNORE INTO users VALUES (1, "alice", "1234")')
cursor.execute('INSERT OR IGN... |
a = 2
if a == 1:
print("a == 1")
elif a == 2:
print("a == 2")
else:
print("other")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 00:51:00 2018
@author: jia_qu
"""
import requests
def exchange(base,other):
#base="USD"
#other="GBP"
resp=requests.get("https://api.exchangeratesapi.io/latest?",params={"base":base,"symbols":other})
#resp=requests.get("https://d... |
class QElement:
def __init__(self, value, priority):
self.value = value
self.priority = priority
def __str__(self):
return 'Value: %d, Prioirty: %d' % (self.value, self.priority)
class PriorityQueue:
def __init__(self):
self.data = []
def enqueue(self, value, priority):
qElement = QElement(value, prior... |
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def __str__(self):
return 'Node value: %d, Left node: %s, Right node: %s' % (self.value, self.left.value if self.left != None else 'None', self.right.value if self.right != None else 'None')
def isLeaf(self):
ret... |
class HashTable:
def __init__(self, size):
self.data = [None] * size
self.size = size
self.keyList = []
def _hash(self, key):
hash = 0
for i in range(len(key)):
hash = (hash + ord(key[i]) * i) % self.size
return hash
def set(self, key, value):
index = self._hash(key)
if self.data[index] == None... |
# Problem
# Given a array and a integer, whether there is a pair in the array that their sum is the same to given integer or not.
# Sample
# [1,2,4,9], 8 - False
# [1,2,4,4], 8 - True
# [6,4,3,2,1,7], 9 - True
# Brute-force solution
def isPairWithSum1(arr, target):
for i in range(len(arr)-1):
for j in range(i+1, l... |
#!/usr/bin/python3
from string import punctuation
import os
def text_analyzer(s="", *argv):
"""\nThis function counts the number of upper characters, \
lower characters, punctuation and spaces in a given text."""
if len(argv) > 0:
print("ERROR")
quit()
print("SSS ", s)
if s == "":
... |
#!/usr/bin/python3
import sys
cookbook = {
"sandwich": {
"ingredients": ["ham", "bread", "cheese", "tomatoes"],
"type": "lunch",
"prep_time": 10,
},
"cake": {
"ingredients": ["flour", "sugar", "eggs"],
"type": "dessert",
"prep_time": 60,
},
"salad": ... |
#!/usr/bin/python3
import numpy as np
def cost_elem_(y, y_hat):
if len(y) != len(y_hat):
return None
J_elem = (1 / (2 * len(y))) * (y_hat - y)**2
return np.asarray(J_elem)
def cost_(y, y_hat):
if len(y) != len(y_hat):
return None
J_value = 0.0
J_elem = cost_elem_(y, y_hat)
for i in J_elem:
J_value += i
... |
import numpy as np
import os
import math
from decimal import Decimal
from fractions import Fraction
import time
print(len(str(0.45)))
def factorising(a,b,c):
### Todo Add support for coefficients
roots = solvefact(a,b,c)
print("(x + {0})(x + {1}) | Currently only works with coeffficient of 1".format(roots... |
# This calculates the number of days and years needed to save a certain amount of money.
#
Savings = int(input("input savings wanted"))
Balance = [1]
Cents = (Savings * 100)
Day = 0
while (Balance[Day] < Cents):
Balance.append(Balance[Day] + Day)
Day = Day + 1
print ("The number of days needed to save is"... |
"""
9. Write a Python program to add a border (filled with 0's) around an existing array.
Expected Output:
Original array:
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
1 on the border and 0 inside in the array
[[ 0. 0. 0. 0. 0.]
[ 0. 1. 1. 1. 0.]
[ 0. 1. 1. 1. 0.]
[ 0. 1. 1. 1. 0.]
[ 0. 0. 0. 0. 0.]]
"""
import numpy as np
... |
"""
18. Write a Python program to change the name 'James' to 'Suresh' in name column of the DataFrame.
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, ... |
import math
import statistics
from functools import reduce
area = lambda radius: math.pi * (radius ** 2)
# from Celius to F
c_to_f = lambda data: (data[0], (9/5)*data[1]+32)
radii = [2, 5, 7.1, 0.5, 10]
output_areas = list(map(area, radii))
print(radii)
print(output_areas)
temps = [("Berlin", 29), (... |
def pythagorean_triplet_checker(triplet_array):
arr_len = len(triplet_array)
for i in range(arr_len):
triplet_array[i] = triplet_array[i] ** 2
triplet_array.sort()
for val in range(arr_len-1, 1, -1):
j = 0
k = val - 1
while (j < k):
if (triplet_array[j] + t... |
from functools import reduce
def add_subtract(x):
def add_subtract_recursive(x, add_subtract_func):
def curried_add_subtract(y):
return add_subtract_func(x, y)
return curried_add_subtract
def add_subtract_func(x, y):
def add_subtract_iterate(acc, item):
if acc ... |
def find_bridges(graph, num_vertices):
# Initialize a list to store the bridges
bridges = []
# Initialize a counter to assign discovery times to the vertices
disc_time = [0] * (num_vertices + 1)
# Initialize an array to store the lowest discovery time reachable from a given vertex
low = [0] * ... |
def is_toeplitz(matrix):
# Iterate through each element of the matrix, starting from the second row and second column
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
# Check if the current element is equal to the element above and to the left of it
if matrix[i]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.