text stringlengths 37 1.41M |
|---|
# Given a roman numeral, convert it to an integer.
# Input is guaranteed to be within the range from 1 to 3999.
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
mapping = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sum =... |
# Given a sorted array, remove the duplicates in-place such that
# each element appear only once and return the new length.
# Do not allocate extra space for another array, you must do
# this by modifying the input array in-place with O(1) extra memory.
class Solution:
def removeDuplicates(self, nums):
"""... |
# Given a non-empty, singly linked list with head node head, return a middle node of linked list.
# If there are two middle nodes, return the second middle node.
# Example 1:
# Input: [1,2,3,4,5]
# Output: Node 3 from this list (Serialization: [3,4,5])
# The returned node has value 3. (The judge's serialization of... |
# You have a total of n coins that you want to form in a staircase shape,
# where every k-th row must have exactly k coins.
#
# Given n, find the total number of full staircase rows that can be formed.
#
# n is a non-negative integer and fits within the range of a 32-bit signed integer.
#
# Example 1:
#
# n = 5
#
# Th... |
# In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.
# Return the element repeated N times.
# Example 1:
# Input: [1,2,3,3]
# Output: 3
# Example 2:
# Input: [2,1,2,5,3,2]
# Output: 2
# Example 3:
# Input: [5,1,5,2,5,3,5,4]
# Output: 5
from collections i... |
# Implement the following operations of a stack using queues.
#
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.
# empty() -- Return whether the stack is empty.
# Notes:
# You must use only standard operations of a queue -- which means only push... |
a = int(input("enter 3 digit number : \n"))
b = a // 100
c = a % 100
d = c // 10
e = c % 10
f = (b ** 3) + (d ** 3) + (e ** 3)
if a==f:
print('It IS Armstrong Number')
else:
print('It Is Not Armstrong Number')
|
a=str(input("Enter Your String : "))
a=a.split(" ")
d1 = dict()
for i in range(0,len(a) ) :
c=a[i]
x=a.count(c)
i+=1
key=c
value=x
d1[key]=value
print(d1)
|
class Queue:
def __init__(self):
self.rear = -1
self.front = 0
self.arr = []
self.max = 5
def insert(self, x):
if self.rear == self.max - 1:
print("Queue is full")
else:
self.rear += 1
self.arr.insert(self.rear, x)
... |
che=input("Enter Your Char : ").lower()
vo=('a','e','i','o','u')
if che in vo:
print(" It Is A vowel")
else:
print("It is A consonants") |
import random
choises = ["Rock", "Paper", "Sesior"]
computer = random.choice(choises)
player = False
player_score = 0
cpu_score = 0
while True:
player = input("Rock, Paper or Sesior ?").capitalize()
if player == computer:
print("Tie !!")
elif player == "Rock":
if computer == "Paper":
... |
import random
import termcolor
from termcolor import colored
num_digit=3
max_guess=10
def getSecretNum(num_digit):
#returns a string of random digits which is num_digit long(3)
numbers=list(range(10))
random.shuffle(numbers)
secretnum =""
for i in range(num_digit):
secretnum += str(numbers... |
import math
def kl_dist(h1,h2,size):
sum1=0
sum2=0
for i in range(size):
sum1+=h1[i]*math.log(h1[i]/h2[i],10)
sum2+=h2[i]*math.log(h2[i]/h1[i],10)
return sum1,sum2
def bh_dist(h1,h2,size):
sum=0
for i in range(size):
sum+=math.sqrt(h1[i]*h2[i])
return (-1*math.log(s... |
__author__ = 'Stanislav Ushakov'
import random
import math
class NotSupportedOperationError(Exception): pass
class Operation:
"""
Class represents single operation.
It isn't supposed to create instances of Operation class in code.
Operations.{OPERATION} must be used instead.
is_unary - True, if o... |
from random import choice
ines = choice(["piedra", "papel", "tiejera"])
juan = choice(["piedra", "papel", "tiejera"])
print(f"ines ha sacado {ines}")
print(f"juan ha sacado {juan}")
if ines == juan:
print("Empate")
elif ines == "piedra" and juan == "tiejera":
print("gana ines")
elif ines == "papel" and juan ... |
def rotate(word):
temp=word[0]
df=[]
for i in range(len(word)-1):
df+=word[i+1]
df+=temp
return "".join(df)
f=rotate("abcd")
g=rotate(f)
h=rotate(g)
print(h)
def leftRotate(arri):
temp=arri[0]
for i in range(0,(len(arri)-1)):
arri[i]=arri[i+1]
arri[-1]=temp
return... |
# coding: utf-8
# # Week 1: Mean/Covariance of a data set and effect of linear transformation
#
# In this week, we are going to investigate how the mean and (co)variance of a dataset changes
# when we apply affine transformation to the dataset.
# ## Learning objectives
# 1. Get Farmiliar with basic programming usin... |
from math import floor
def check_prime(n):
if n == 2:
return True
for i in range(2, floor(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input()) # n will always be an integer
result = check_prime(n)
if(result == True):
print("Yes it is a prime")
else:
print("No it's not a prime") |
import operator
#from the longest prefix search
#reorder each list according to price
#input as a .text file
def Routing(number):
if number=="":
return None
OperatorNames,Lists=ConvertInputText()
#reorder each list by lowest price
Sorted_Lists=list()
for each in Lists:
sorted_e=sorted(each.items(),key=oper... |
from random import randint
class Cube:
def __init__(self, size, color):
'''
:param size: integer
:param color: integer
'''
self.__size = size
self.__color = color
def getSize(self):
return self.__size
def getColor(self):
return self.__color
... |
import random
# Read in all the words in one go
with open("input.txt") as f:
words = f.read()
splitWords = words.split()
# TODO: analyze which words can follow other words
# Your code here
# TODO: construct 5 random sentences
# Your code here
mark_storage = dict()
startWords = list()
endWords = list()
capi... |
def inssort(A):
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
A = input('Enter the list values to be stored: ').split()
inssort(A)
print(A)
|
def mergeSort(A):
if len(A) > 1:
mid = len(A) // 2
L = A[:mid]
R = A[mid:]
# Recursive call on each half
mergeSort(L)
mergeSort(R)
# Two iterators for traversing the two halves
i = 0
j = 0
# Iterator for the mai... |
import math
def main():
print("This program calculates your BMI.")
weight = eval(input("Enter your weight in pounds: "))
height = eval(input("Enter your height in inches: "))
bmi = (weight * 720) / height**2
if bmi >= 19 and bmi <= 25:
print("Your BMI is {0:0.2f}, within the health... |
def main():
print("This program calculates if a year is leap.")
year = eval(input("Enter a year in your digits: "))
if year % 400 == 0:
print("The year {0} is a year leap.".format(year))
else:
print("The year {0} is not a year leap.".format(year))
main()
|
def main():
print("This program calculates how much you will take two double an investment.")
inv = eval(input("Enter the initial capital: "))
rate = eval(input("Enter the anualized rate: "))
year = 0
gain = inv *(1+rate)
while gain < (2*inv):
year = year + 1
gain = inv *(ye... |
def main():
first_name, last_name = get_name()
print("First Name:",first_name)
print("Last Name:",last_name)
last, first = reverse_names(first_name, last_name)
print("My name in reverse order is ",last, first)
def get_name():
first = input("Enter first name: ")
last = input("Enter last name... |
my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
print('Original order:',my_list)
my_list.sort()
print('Sorted order:',my_list)
|
# This program calls the split method, using the
# '/' character as a separator.
def main():
# Create a string with a date.
date_string = '11/26/2020'
# Split the date.
date_list = date_string.split('/')
# Display each piece of the date.
print(f'Month: {date_list[0]}')
print(f'Day: {date_... |
text = 'Four score and seven years ago'
search_string = 'eight'
if search_string not in text:
print(f'The string {search_string} was not found.')
else:
print(f'The string {search_string} not found.')
|
city = 'Boston'
index = 0
while index < len(city):
print(city[index])
index+=1
|
# Create two variables: top-speed and distance.
top_speed = 160
distance = 300
# Display the values referenced by the variables.
print('The top speed is')
print(top_speed*2)
print('The distance traveled is ')
print(distance*2)
|
# This program demonstrates a function that accepts
# two arguments.
def main():
# print('The sum of 12 and 45 is')
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the secomd number: "))
show_sum(num1, num2)
# The show_sum function accepts two arguments
# and displays their sum.
... |
sales = float(input("Enter the value of sales made: "))
if sales > 50000:
bonus = 500.0
print("You have a bonus of",bonus)
print('Our business is changing lives')
|
# A program to print the multiplication table
# Get the rows and columns input
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
# Print the header
for c in range(cols):
print('-------',end='')
print()
for c in range(1, cols+1):
if c == 1:
print(f' {... |
# A program to print 1 - 10 using the while loop
init = 1
while (init <= 10):
print(init, end=" ")
init = init + 1
|
""" Transfer file from source to destination """
from pathlib import Path
from shutil import copyfile
import filecmp
def transfer_data(filename: Path, src_dir: Path, dst_dir: Path):
""" Copy file
:param
filename: Path
Name of file to copy
src_dir: Path
Directory ... |
class Node :
def __init__(self,data=None):
self.data=data
self.next=None
def getNext(self):
return self.next
def setData(self,data):
self.data=data
def getData(self):
return self.data
def setNext(self,newNext):
self.next=newNext
class lList:
def __init__(self):
self.head=None
def i... |
# a= input()
# b= input()
# c= input()
# d= input()
# if (( int(a) > 10 or int(b) > 10) or (int(c) > 10 or int(d) > 10)):
# print("too high")
# elif (a==b and c==d):
# print("correct")
# elif (a==b or b==c):
# print("half")
"""this writes a program thats takes input from the user less than 10, and compares... |
def main():
string1, string2, penalties = read_input("sequence01.txt")
min_penalty, alignment1, alignment2 = solve(string1, string2, penalties)
write_output(None, min_penalty, alignment1, alignment2)
def read_input(filename):
with open(filename, "r") as input_file:
string1 = input_file.readlin... |
def main():
capacity, items = read_input("knapsack01.txt")
max_value = solve(capacity, items)
write_output(None, max_value)
def read_input(filename):
with open(filename, "r") as input_file:
capacity = int(input_file.readline())
items = [KnapsackItem(value=int(value_str), weigh... |
import sys
def main():
input_filename = "sigkey.in" if len(sys.argv) == 1 else sys.argv[1]
output_filename = "sigkey.out" if len(sys.argv) == 1 else sys.argv[2]
keys = read_input(input_filename)
key_pair_count = solve(keys)
write_output(output_filename, key_pair_count)
def read_input(filename):... |
import threading
def writer(x, event_for_wait, event_for_set):
for i in xrange(10):
event_for_wait.wait()
event_for_wait.clear()
print "I`m {} thread".format(x)
event_for_set.set()
def main():
e1 = threading.Event()
e2 = threading.Event()
thread1 = threading.Thread(targ... |
class Interval:
def __init__(self, min: int, max: int) -> None:
if max < min:
raise ValueError("max must be higher than min")
self._min = min
self._max = max
def min(self) -> int:
"""
Return the current min of the interval
:return: The min of the in... |
"""Quick sort
>>> quicksort([9,8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> quicksort([4,-2,0,1,-1,0])
[-2, -1, 0, 0, 1, 4]
"""
import random
def quicksort(lst):
def partition(lst, low, high):
pivot = lst[random.randint(low, high)]
while True:
while lst[low] < pivot:
... |
import os
import csv
#Set variables
totalMonths = 0
netTotal = 0
avgChange = 0
previousChange = 0
changeList = []
monthOfChange = []
greatestIncreaseProfit = ["", 0]
greatestDecreaseLoss = ["", 0]
totalAvgChange = 0
#Path to collect data from folder
PyBankCSV = os.path.join( "budget_data.csv")
# Read in the CSV file... |
# This is a document about the sliding Window. May be used in array and Linked List.
# Question 1
# Given an array, find the average of all contiguous subarrays of size ‘K’ in it.
def find_averages_of_subarrays(K, arr):
res = []
window_start, windom_sum = 0, 0
for window_end in range(len(arr)):
wi... |
from numpy import *
def ReLU(x):
# activation function
return x*(x>0)
def dReLU(x):
# defivative of the activation function
return (x>0)*1.0
def Softmax(x):
# softmax
e_x = exp(x - max(x))
return e_x / e_x.sum(axis=0)
def NN_FeedForward(X,W,B,k):
# feed forward nueral network
l ... |
# 投入する金額を受け取る
insert_price = input('insert: ')
# 商品の金額を受け取る
product_price = input('product: ')
# 型を変換しておつりを計算
change = int(insert_price) - int(product_price)
print(change)
|
data = [6,15,4,2,8,5,11,9,7,13]
def quick_sort(data):
if len(data) <= 1:
return data
pivot = data[0] #ピボットとしてリストの先頭を使用
# ピボットより小さいものでリストを作る
left = [i for i in data[1:] if i <= pivot]
# ピボットより大きいものでリストを作る
right = [i for i in data[1:] if i > pivot]
left = quick_sort(left) #左側をソート
... |
import heapq
def heap_sort(array):
h = array.copy()
heapq.heapify(h)
return [heapq.heappop(h) for _ in range(len(array))]
data = [6,15,4,2,8,5,11,9,7,3]
print(heap_sort(data))
|
M, N = 6, 5
route = [[0 for i in range(N+1)] for j in range(M+1)]
# 横方向の最初の1行をセット
for i in range(M+1):
route[i][0] = 1
for i in range(1, N+1):
# 縦方向の最初の1列をセット
route[0][i] = 1
for j in range(1, M+1):
# 左と下から加算する
route[j][i] = route[j - 1][i] + route[j][i - 1]
print(route[M][N])
|
text = list('SHOEISHA SESSHOP') #テキストをリストに変換
pattern = list('SHA') #パターンをリストに変換
for i in range(len(text)):
match = True #一致しているものとして探索開始
for j in range(len(pattern)):
if text[i + j] != pattern[j]:
match = False #一致しなかった
break
if match: #全ての文字が一致していれば出力
print(i)
... |
import sys
import getopt
import os
import traceback
import utils
"""
------------------------------------------------------------------------------------------------------
SOURCE FILE: client.py - client application
PROGRAM: Tcp File Transfer Client Server
DATE: Oct 1, 2020
DESIGNER: Junyin Xia
PROGRAMMER: Junyin ... |
#from collections import deque
#stack = deque()
#stack.append('a')
#stack.append('b')
#print(stack.pop())
#print(stack.pop())
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()
def... |
#from collections import deque
#stack = deque()
#stack.append('a')
#stack.append('b')
#print(stack.pop())
#print(stack.pop())
class SetOfStacks:
def __init__(self):
self.stack = [[]]
def pop(self):
if len(self.stack[0]) < 1:
return None
elif len(self.stack[len... |
# 5
SPEED = 70 # constant
print("Distance for 6h = ", SPEED * 6)
print("Distance for 10h = ", SPEED * 10)
print("Distance for 15h = ", SPEED * 15)
|
# task 7
# subtotal = 5
# total = subtotal * 0.15
# task 8
# a = 5
# b = 2
# c = 3
# result = a + b * c
# print(result)
# task 9
# num = 99
# num = 5
# print(num)
# task 10
# sales = 10.19999
# print(round(sales, 2))
# task 11
# number = 1234567.456
# print(format(number, ',.1f'))
# task 12
# print('Джордж', 'Джон... |
# 1. При помощи цикла for вывести на экран нечетные числа
# от 1 до 99.
def print_even_by_range(start,stop):
# i = 1
# while i < 99:
# i += 2
# print(i)
# for i in range(1, 100):
# if i % 2 !=0:
# print(i)
#
# recommended
for i in range(start,stop,2):
print(i)
# test comment 111111232... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = K... |
# Andrzej Kocielski, 03-05-2019
# Classes
# ===
class Rectangle:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
r1 = Rectangle(1, 3, 5, 6)
r1 = Rectangle(3, 2, 7, 4)
print(r1.x1, r1.y1, r1.x2, r1.y2)
|
# Andrzej Kocielski, 15-05-2019
# What character appears most in the sentence
# =====
sentence = "This is a common interview question."
# letters = [sentence]
# Salution taken and adapted from: https://codewithmosh.com/courses/417695/lectures/6781694
char_frequency = {} # empty Dictionary
for char in sentence: # i... |
# Monster Fight Game
# Author: Andrzej Kocielski
# Created: 02-08-2020
# Based on tutorial by Manuel Lorenz: https://www.youtube.com/watch?v=kDdTgxv2Vv0
# ------------------------------
# -----
# importing libraries
from random import randint
# -----
# game main code block
def main():
game_running = True
#... |
def recursive_insertion_sort(seq):
isort(seq,len(seq))
def isort(seq,k):
if k>1:
isort(seq,k-1)
insert(seq,k-1)
def insert(seq,k):
pos = k
while pos > 0 and seq[pos] < seq[pos-1]:
(seq[pos], seq[pos-1]) = (seq[pos-1], seq[pos])
pos -= 1
def main():
seq = list(map(int,input("Enter some no. : ").split())... |
def factorial(n):
if n==0:
return(1)
else:
return(n * factorial(n-1))
def multiply(m,n):
if n==1:
return(m)
else:
return(m + multiply(m,n-1))
def length(l):
if l == []:
return(0)
else:
return(1 + length(l[1:]))
def sumlist(l):
if l == []:
return(0)
else:
return(l[0] + sumlist(l[1:]) )
|
def gcd(m,n):
if m<n:
(m,n)=(n,m)
if m%n is 0:
return n
else:
diff = m-n
return gcd(max(n,diff),min(n,diff))
m,n = map(int, raw_input("Enter two 2 nos.:").split())
print gcd(m,n)
|
import random
from typing import List
class Ship():
def __init__(self, size: int = 2, vector: str = 'h'):
'''
set default ship size to 2
set vector to h for horizontal(default) or v for vertical
set default position to 0, 0
'''
self.size = size
self.ve... |
#!/usr/bin/python3
"""Changes case in numerous ways"""
name = "ada lovelace"
print("Original Name: {}".format(name))
print("Name using title function: {}".format(name.title()))
print("-----")
print("Original Name: {}".format(name))
print("Name using upper: {}".format(name.upper()))
print("Name using lower: {}".format... |
from tkinter import *
root = Tk()
root.title('Hola Mundo!')
r = IntVar()
r.set('2')
ESTADOS = [
('Feliz','Feliz'),
('Triste','Triste'),
('Amargado','Amargado'),
('Enojado','Enojado')
]
varestado = StringVar()
varestado.set('Enojado')
for text, estado in ESTADOS:
Radiobutton(root, text... |
from tkinter import *
root = Tk()
root.title('Hola Mundo')
root.geometry('550x350')
# para definir un input se llama a Entru() y este recibe los argumentos de:
# 1ro donde se va a renderizar el input, 2do cuanto va a ser el ancho el input
e = Entry(root, width=40)
# utilizo pack para mostrar el widget
e.pack()
# Most... |
class SimpleKalmanFilter(object):
"""Simple kalman filter with constant value"""
def __init__(self):
"""set up the initial values"""
# Kalman fixed values for simple model~
self.A = 1
self.H = 1
self.Q = 0
self.R = 4
#computation of estimate
sel... |
# -*- coding: utf-8 -*-
def puzzle():
mypuzzle = []
mylist =[]
row = input('Enter the values for row 1: ')
for num in row:
mylist.append(int(num))
mypuzzle.append(mylist)
mylist = []
for i in range(2,len(row)+1):
row = input(f'Enter t... |
''' Write a program wget.py to download a given URL. The program should
accept a URL as argument , download it and save the basename of the URL.
If URL ends with a /, consider the basename as index.html '''
import urllib
import os
def wget(url):
res = urllib.urlopen(url)
base_name = os.path.basename(url)
if base_n... |
''' Implement a fn product to multiply 2 numbers recursively using + and
- operators only. '''
def product(x,n):
if n == 0:
return 0
else :
return x + product(x, n - 1)
p = product(2,3)
print "%d * %d = " % (2,3),
print p
|
''' Write a f. 'factorial' to compute factorial of a number. Can you use the
'product' fn defined in the previous example to compute factorial '''
def product(x):
prdct = 1
for element in x:
prdct = prdct * element
return prdct
def factorial(n):
x = range(1,n+1)
fact = product(x)
return fact
n = input('Give... |
#implenting usage of a method- Upper
x = "hello"
print x
f = x.upper
print "Result after using Upper fn."
print f()
|
''' Write a program to list all files in the given directory '''
import os
def get_files(cwd):
print "All files in the DIrectory "
for files in os.listdir(cwd):
print files
cwd = os.getcwd()
print "Current Directory : "
print cwd
get_files(cwd)
|
''' Write a python fn parse_csv to parse csv (comma separated values) files
'''
fp = open('2.csv', 'w')
fp.write('a,b,c \n 1,2,3 \n 2,3,4 \n 3,4,5')
fp.close()
def parse_csv(filename):
import csv
res = []
f = open(filename)
csv_f = csv.reader(f)
res = [row for row in csv_f]
#for row in csv_f:
# res.append(row)... |
def reverse(x):
l = len(x)
res = range(1,l + 1)
l = len(res)
for element in x:
res[l - 1] = element
l = l - 1
print "Reversed : "
print res
x = [1,2,3,4]
print "List : "
print x
reverse(x)
|
import sys
import re
number = int(sys.argv[1])
palindromes = []
i=number
j=number
for i in range(number,1,-1):
for j in range(i,1,-1):
palindrome = repr(i*j)
if palindrome == palindrome[::-1]:
palindromes.append(palindrome)
print(sorted(palindromes,key=int,reverse=True)[0]) |
# How do you find the missing number in a given integer
# array of 1 to 100?
def missing_number(Arr):
for i in range(1, 101):
if i in Arr:
pass
else:
return i
Array = [j for j in range(1, 100)]
print(missing_number(Array)) |
class Sort:
def merge(self, arr1, arr2):
"""
Merges the two sorted lists
"""
arr3 = []
while len(arr1) != 0 and len(arr2) != 0:
if arr1[0] < arr2[0]:
arr3.append(arr1[0])
arr1.remove(arr1[0])
else:
... |
from __future__ import division, print_function
from random import randint,random
#1
def has_duplicates(a):
for x in a:
if a.count(x) > 1:
return True
return False
#print has_duplicates([1,2,3,4,4])
#2
def rand_birthdays(size):
lst = []
for i in range(0,size):
lst.append(randint(1,365))... |
import art
print(art.logo)
num_a = float(input("What's the first number?: "))
print("+")
print("-")
print("*")
print("/")
operator = input("Pick an operation: ")
num_b = float(input("What's the second number?: "))
def add(num_a, num_b):
return num_a + num_b
def sub(num_a, num_b):
return num_a - num_b
d... |
s = input()
vowels = "AEIOUY"
flag = False
for _ in range(len(s)):
if (int(s[0])+int(s[1]))%2==0 and (int(s[3])+int(s[4]))%2==0 and (int(s[4])+int(s[5]))%2==0 and (int(s[-1])+int(s[-2]))%2==0:
flag = True
ans = 'valid' if (flag and s[2] not in vowels) else 'invalid'
print(ans)
|
b = []
for _ in range(5):
r = [int(x) for x in input().split()]
b.append(r)
# print(b) # simple array
for i in range(5):
for j in range(5):
if b[i][j] == 1:
r,c = i,j
# print('row: ',r)
# print('col: ',c)
# print('Step to make beautiful matrix is: ',( abs(2-r) + abs(2-c)))
print(( abs(2... |
# 二叉树的操作
class BinaryTreeNode:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = BinaryTreeNode
# 二叉树的递归遍历
# 递归前序遍历
def preOrderRecursive(self, root)... |
for i in range(1, 8):
print("N == " + str(i) + " : if(n) period_r := period_r - (period_r >> " + str(i) + ");")
print(" else period_r := period_r + (period_r >> " + str(i) + ");")
|
import numpy as np
def fdweights(m, x0, x, dtype='float_'):
'''
Calculate finite difference weights.
Returns the finite difference weights for derivatives 1, 2, ..m at the
location x0 for the stencil defined in the array of points x.
Parameters
----------
m : int
maximu... |
import random
# test cases: testing for partial match, no matches, complete match, and incorrect order (no matches)
a = ['ab', 'cd', 'efc', 'ab']
b = ['af', 'ee', 'efc', 'ba']
# generate the number of additional elements in a and b, max lowered to 10 to reduce runtime
elems = random.randint(1, 10)
# generate the len... |
poll = {}
while True:
name = input("(leave blank to end the program) What's your name:")
if name == '':
break
place = input("Where'd you want to go: ")
poll[name] = place
for name,place in poll.items():
print(f"{name.title()} would want to go to {place}") |
pizzas = ["cheese", "meat", "shrimp","seafood","chicken"]
print("the first three items are:")
print(pizzas[:3])
print("")
print("the middle three items are")
print(pizzas[1:4])
print("")
print("the last three items are")
print(pizzas[-3:])
|
print("Hello world!")
def sum(x, y):
return x + y
#end
x = 5
y = 3
print("sum {} + {} = {}".format(x, y, sum(x, y)))
|
from copy import deepcopy
t=(1,[],"Hello",True)
print(t)
tuple=deepcopy(t)
print(tuple)
tuple[1].append(60)
print(tuple)
|
# Write a Python function that takes a list of words and returns the length of the longest one.
def longest_word(word_list):
word_len=[]
for i in word_list:
word_len.append((len(i),i))
word_len.sort()
return word_len[-1][1]
print(longest_word(["California","Switzerland","Huwaii","Germany"]))
|
#Write a Python programming to create a pie chart of the popularity of programming Languages.
#Sample data:
#Programming languages: Java, Python, PHP, JavaScript, C#, C++
#Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
import matplotlib.pyplot as plt
languages=['Java', 'Python', 'PHP', 'JavaScript','C#','C++']
popularity... |
# Write a Python program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2.
#Expected Output:
#Array1: [ 0 10 20 40 60 80]
#Array2: [10, 30, 40, 50, 70, 90]
#Set difference between two arrays:
#[ 0 20 60 80]
import numpy as np
array1=n... |
#. Write a Python program to get the powers of an array values element-wise.
#Note: First array elements raised to powers from second array
#Expected Output:
#Original array
#[0 1 2 3 4 5 6]
#First array elements raised to powers from second array, element-wise:
#[ 0 1 8 27 64 125 216]
import pandas as pd
import nump... |
#Write a Python program to create a null vector of size 10 and update sixth value to 11.
#[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#Update sixth value to 11
#[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]
import numpy as np
x=np.zeros(10)
print(x)
x[6]=11
print(x)
|
# Build a machine learning model to predict salary based on position for a given dataset
#https://drive.google.com/open?id=1jKfNxQkybZKprVpCkoL16mTjmSSnCol3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import St... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.