text stringlengths 37 1.41M |
|---|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
dummyA, dummyB = h... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.depth = 0
def dfs(root, de... |
class RomanToInt(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict = {"M": 1000, "CM": 900, "D": 500,
"CD": 400, "C": 100, "XC": 90,
"L": 50, "XL": 40, "X": 10, "IX": 9,
"V": 5, "IV": 4, "I": 1}
i, ... |
class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if not num:
return 0
res = num % 9
if not res: return 9
else: return res |
def else_example(item_list):
for item in item_list:
if item == 'banana':
return 'Banana found'
else:
print(ValueError('No banana flavor found!'))
my_list_1 = ['apple', 'banana', 'peach']
my_list_2 = ['apple', 'peach', 'blueberry']
print('my_list_1:')
print(else_example(my_list_1))... |
from collections import namedtuple
Result = namedtuple('Result', 'count average')
# the subgenerator:
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield
if term is None:
break
total += term
count += 1
average = total/count... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 1 15:55:08 2018
@author: RickyLi
"""
import numpy as np
def factors( n ):
fs = []
n = int(n)
for i in range(2,n):
if n % i == 0.0:
fs.append(i)
#print(i)
return fs
def fraction( n ):
n_str = str( n )
d... |
import numpy as np
import time
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
# You may use this function as you like.
error = lambda y, yh... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 12 20:09:59 2018
@author: RickyLi
"""
import numpy as np
def mc_pi(n):
xy = np.random.random((n,2))*2-1
d = (xy[:,0]**2 + xy[:,1]**2)**0.5 - 1
d = np.maximum(d,0)
return d
print(mc_pi(10)) |
from Classes.Conta import Conta
import json
response = requests.get("http://jsonplaceholder.typicode.com/comments")
print(response.status_code)
class Pessoa():
def __init__(self, nome, altura, idade):
self.conta = Conta()
self.__nome = nome
self.__altura = altura
self.__idade = ida... |
#!/usr/bin/env python3
# -*- coding: utf -8-*-
import sys
def reverse_iterative(sequence, left, right):
""" Funkcja iteratywnie odwraca sekwencję sequence od liczby o indeksie left do right wlacznie
>>> reverse_iterative([1,2,3,4,5,6], 1, 4)
[1, 5, 4, 3, 2, 6]
>>> reverse_iterative([10,9,8,7,6,5,4,3,2,... |
#!usr/bin/env python3
# -*- coding: utf -8-*-
import sys
N = 100000
class Node:
"""Klasa reprezentująca węzeł listy dwukierunkowej."""
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def __str__(self):
return str(self... |
#!/usr/bin/env python3
# -*- coding: utf -8-*-
import sys
def flatten(sequence):
""" Funkcja zwraca splaszczoa liste wszystkich elementow z sekwencji
>>> flatten([1, [2, [3]]])
[1, 2, 3]
>>> flatten([1,(2,3),[],[4,(5,6,7)],8,[9]])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
out = []
for item in sequ... |
#asking for user input
string = input("Please Enter your own single word: ")
#what is that below? it's slicing and when you write it this way
#it starts from the end towards the first, using index values
if(string == string[:: -1]):
print("True")
else:
print("False") |
import random
# the question/answer dictionary.
my_dict = {
"What is my first name:": "Gift",
"Where do I live(county):": "Mombasa",
"Which HighSchool do I go to": "Makueni Boys",
"How old am I:": "18",
"Which form am I": "4",
"What do I love the most in this world": "Computers",
... |
import ctypes
class Array:
"""
Class that represents low-level array data structure
"""
def __init__(self, size):
"""
Initializes an array with size
:param size: int
"""
if size <= 0:
raise ValueError
self._size = size
py_array_type ... |
STACK = False
def main(args):
args = map(lambda arg: arg if arg[-1:] == '"' and arg[0] == '"' else 'str({0})'.format(arg),
args)
return '"".join([{0}])'.format(','.join(args))
|
data_A = []
data_B = []
count = 0
while True:
add_data_A = int(input('Enter numbers between 0 - 100 : '))
add_data_B = int(input('Enter numbers between 0 - 100 : '))
count += 1
if add_data_A < 0 or add_data_A > 100:
del add_data_A[count]
print('Invalid input.')
count -= 1
elif add_data_B < 0 or add_data_B... |
from Car import Cars
class Trucks(Cars):
def __init__(self):
super().__init__()
self.type = 'Truck'
self.weight = 0
def in_information(self, line):
self.weight = line[1]
self.engine_power = line[2]
self.fuel_consumption = line[3]
self.global_weight = l... |
# In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
def DNA_strand(dna):
comp = ''... |
Pandas series data structure
======================================================================================================================================
- one dimensional labeled array object (No column headers)
>>> c = pd.Series([1,2,3])
>>>
>>> c
0 1
1 2
2 3
dtype: int64
>>>
>>> c
0 1
1 2
2 ... |
Python Regex
=======================================================================================================================================
import re
1) findall => returns a list of all the matches
================================================
>>> re.findall('Tame', 'Tame is in tame')
['Tame']
>>> re.comp... |
# Shallow Copy and Deep Copy
# When you use "=" to create a copy of an object, It only creates a new variable that shares the reference of the original object.
a = [1,2,3,4]
b = a
a.append(5)
a[2] = 100
print(a,b)
=> [1, 2, 100, 4, 5] [1, 2, 100, 4, 5]
-- Shallow copy creates a copy of t
import copy
a = [1,2,3,4]
... |
#!/usr/bin/python
import subprocess
import re
# Function that prompts users for yes or no response
def yes_no(answer):
# Expected 'yes' formats
yes = set(['yes', 'y'])
# Expected 'no' formats
no = set(['no', 'n'])
# Prompt user for input until they answer either 'yes' or 'no'
while True:
... |
#!/usr/bin/env python
#
# Show credentials if any
file=open('.credentials')
user = ""
passwd = ""
for line in file:
if line.startswith('username'):
user = line.split()[-1]
if line.startswith('password'):
passwd = line.split()[-1]
if user and passwd:
print "User:", user, "has password:", passwd
|
"""
A small `pdoc` example using Mermaid diagrams.
The relationship for Pet and Dog follows the UML diagram:
```mermaid
classDiagram
class Dog~Pet~{
-__init__(str name) None
+bark(bool loud) None
}
Dog <|-- Pet
Pet : +str name
Pet : +List[Pet] friends
```
"""
class Pet:
name:... |
import random
import math
Upper = int(input("introduzca rango superior: "))
Lower = int(input("introduzca rango inferior: "))
Num_a_adivinar = random.randint(Lower,Upper)
intentos = int(input("cuantas oportunidades de adivinar necesitas?: "))
count = 0
while count < intentos:
count += 1
... |
"""Search for an email address given a fragment of a job description."""
# TODO: Add the required import for the csv module to support the
# parsing of the contact database stored in the provided file
def search_for_email_given_job(job_description: str, contacts: str):
"""Search for and return job(s) given an em... |
"""
Implementation of address-related features.
"""
from ipaddress import ip_address
import zmq
from .common import unique_identifier
def address_to_host_port(addr):
"""
Try to convert an address to a (host, port) tuple.
Parameters
----------
addr : str, SocketAddress
Returns
-------
... |
import numpy as np
class MLP:
"""The class is the implementation of multi layer perception (or neural network)."""
def __init__(self, hidden_layer_sizes=(5,), activation=np.tanh, learning_rate=0.1, max_iter=2000, tol=0.05,
momentum=0.9, random_seed=1985):
"""
Args:
... |
from array import *
def runRecursive(array):
return runRecursiveHelper(array, 0)
def runRecursiveHelper(array, index):
# base case
if not array:
return []
elif (len(array) == 1):
return sorted(array[0])
elif (len(array) == 2):
return sorted(array[0])
# normal case
elif (index < len(array)-2):
ne... |
def slices(source, length):
if source == "":
raise ValueError("Source series cannot be blank.")
elif length < 0:
raise ValueError("Length of slices cannot be less than 1.")
elif length > len(source):
raise ValueError("Source length needs to be longer than your requested slice.")
... |
class Person:
def __init__(self, _name: str, _age: int, _gender: str, _money: float):
self.name: str = _name
self.age: int = _age
self.gender: str = _gender
self.money: float = _money
def get_name(self) -> str: return self.name
def get_age(self) -> int: return self.age
... |
'''
Created on Feb 22, 2016
@author: MADHUSUDAN
'''
def gcd(m,n):
while m%n!=0:
old_m=m
old_n=n
m=old_n
n=old_m%old_n
return n
class Fraction(object):
'''
classdocs This is a simple class program that defines about abstract datatypes here we ... |
from __future__ import division
# Newtons method to find root
def sqtr_n(n):
root= n/2
for _ in range(20):
root=1/2 *((root)+ (n/root))
return root
print sqtr_n(4) |
#This file contains all conversion functions we will need for this project
#Summary: This function converts a decimal value to binary format
#Precondition: Pass in a decimal value
#Postcondition: Returns binary string of decimal value passed in
def convertToBinary(dVal):
binNum = "{0:b}".format(dVal)
return binNum
... |
def binery_search(kumpulan, target) :
kiri = 0
kanan = len(kumpulan) - 1
while kiri <= kanan :
tengah = (kiri + kanan) // 2
if kumpulan[tengah] == target :
return tengah
elif kumpulan[tengah] < target :
kiri = tengah + 1
else :
... |
def towerofhanoi(n,a,b,c):
if n==1: # base case
print(a, c)
return
towerofhanoi(n-1,a,c,b)
print(a, c)
towerofhanoi(n-1,b,a,c)
n=int(input())
towerofhanoi(n, 'a', 'b', 'c') |
## Tricky question:output as follows
## 1
## 212
## 32123
## 4321234
n = int(input())
i = 1
while(i<=n):
space = n - i
while (space > 0):
print(end=" ")
space = space - 1
j=i
#increasing sequence
while(j>0):
print... |
n = int(input())
for i in range(1,n+1,1):
for j in range(1, i, 1):
print(' ',end="")
for l in range(i, n+1, 1):
print(l,end="")
print()
for i in range(1,n,1):
for j in range(n-i, 1, -1):
print(' ',end="")
for l in range(n-i, n+1, 1):
print(l,end="")
... |
#simple example:
i=1
while i<10:
print(i)
i=i+1
else:
print("this will be printeed at the end only once")
#complex example with Break as well:
i=1
while i<10:
if i == 5:
break
print(i)
i=i+1
else:
print("i has reached 5 !!") ## this time it will not be... |
def sort(array):
i=0
while i < 3:
low = i
j=0
while j< len(array):
if array[j] == low:
print(low,end=" ")
j+=1
i+=1
N = int(input())
if N<=1:
print()
else:
arr = [int(x) for x in input().split()]
sort(arr) |
# output:
# 1
# 232
# 34543
# 4567654
n = int(input())
for i in range(1,n+1,1):
for space in range(1,(n+1)-i,1):
print(' ',end="")
for j in range(i,i*2,1):
print(j,end="")
for j in range(2*i-2,i-1,-1):
print(j,end="")
print()
|
#_____________________________# Array intersection !!
def unique_arr(list_1,list_2):
i = 0
while i<N1:
count = 0
j = 0
while j<N2:
if list_1[i] == list_2[j]:
list_2[j] = 9999999999
count = count + 1
break
... |
def countDuplicate(string):
newstr = ""
string += ' '
l = len(string)
count = 1
for i in range(l-1):
if string[i] == string[i+1]:
count += 1
else:
print(string[i],end="")
if count > 1:
print(count, end="")
co... |
#_____________________________________________________# introduction:
li = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print(li[2][3])
#_________________________________________________# storing data in 2D lists :
li = [[1,2,3,4],[5,6,7,8]]
print(li[0])
type(li[0])
li[0][1] = 4
print(li[0])... |
# Ability to take multiple forms { METHOD OVERIDING }
# order of print in python : 1.=> lowest class 2.=> parent class => .....=> parent's parent's parent's.......class !
class Vehicle:
def __init__(self,color,maxSpeed):
self.color = color
self._maxSpeed = maxSpeed
@classmethod
def getMaxSpeed(cls... |
def linear_search(list,element):
for i in range(len(list)):
if list[i]==element:
return i
break
else:
return -1
li = [1,2,3,4,5]
index = linear_search(li,3) # using function linear search
print("index =",index) |
#________________________________________________________# new list method !#_______________________________________________________________________________________#
# given a list : check if sorted :
#Base case : list of size 0 or 1 (is by default sorted!) : should return TRUE (induction hypothesis)
# check ... |
#_______________________________________________________________#square of elements :
li = [1,2,3,4]
#_____________________________# long way :
li_new=[]
for ele in li:
li_new.append(ele**2)
print(li_new)
#_______________________________________________________________# using comprehension now :
li_ne... |
n = int(input()) # no of elements
li = [int(x) for x in input().split()] # elements in the list
print(li)
ele = int(input()) # element to be searched
isFound = False
for i in range(len(li)): # searches elements in the list
if li[i] == ele:
pri... |
#_____________________________________________________________# Sum of 1st n natural numbers !_________________________________________________________________________
#concept : E(n) = n + E(n-1) ______where n is the base case and rest is the follow.
def sum_n(n):
if n == 0:
return 0
smallout... |
n = int(input())
i=1
x=2
print(1)
while(i<n):
j=1
print(1,end="")
while(j<i):
print(x,end="")
j=j+1
print(1,end="")
print()
i=i+1 |
#______________________________________________# SWAPPING !!
def reverse(list):
n = len(list)
for i in range(0,n//2,1):
li[n-i-1],list[i] = li[i],list[n-i-1] ## this is the syntax
li = [1,2,3,4,5,6,7]
reverse(li)
print(li)
# output : [7, 6, 5, 4, 3, 2, 1]
#___... |
# Two main concepts in OOPS:
# 1. classes
# 2. Objects
# way to create a class : and a function inside it :
class student:
def __init__(self,name,age):
self.name = name
self.age = age
s1 = student("abc",16)
s2 = student("def",17)
# display s1 and s2 address:
print(s1,s2)
# ... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
#if len(s) < 1 or len(s) > 10^4 or any(c not in '()[]{}' for c in s):
#print('False')
temp = []
for para in s:
if para == "(" or para == "[" or pa... |
# -*- coding:utf-8 -*-
from collections import namedtuple
# 问题描述:
student = ('Jim', 16, 'male', 'jim8721@mail.com')
NAME, AGE, SEX, MAIL = range(4)
# NAME = 0
# AGE = 1
# SEX = 2
# EMAIL = 3
# name
print(student[NAME])
# age
if student[1] >= 18:
print(student[AGE])
# sex
if student[2] == 'male':
print(stu... |
'''
如何实现可迭代对象和迭代器对象
问题:如果一次抓取所有信息,第一有延时,另外浪费存储空间
方案:使用“用时访问”策略,能够把问题封装到一个对象中,然后进行迭代
解决:
1. 实现可迭代对象 next 方法每次返回一个城市气温
2. 实现可迭代对象 __iter__ 方法 返回一个迭代器对象
'''
from collections import Iterable, Iterator
import requests
class WeatherIterator(Iterator):
def __init__(self, cities):
... |
'''
问题:如何解析简单的xml文档?
实际案例
xml是一种十分常用的标记性语言,可提供统一的方法来描述应用程序的结构化数据:
<?xml version="1.0" ?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name=... |
###################################_STACK_USING_OOPS###################################################################
class Stack():
def __init__(self):
self.list = []
def empty(self):
return self.list ==[]
def push (self,item):
self.list.append(item)
def pop(self):
return self.list.pop()
... |
import pandas
import json
'''
Boyer Moore String Search implementation in Python
__author__: Pawda
Date: 2016-04-04
'''
# method bad character to find the shift bit. len(ref) == len(read)
def bad_cha(ref,read):
for i in range(1, len(read)+1):
if not read[-i] == ref[-i]:
for j in range(1,len... |
# Advent of Code 2017
# https://adventofcode.com/2017
# Day 2
# https://adventofcode.com/2017/day/2
"""
As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be
idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'... |
import requests
from os import path
from pprint import pprint
from collections import Counter
def getPythonSite():
r = requests.get('https://www.python.org')
# print(r.content)
# Count # of spans in r.content
s = f'span count: {str(r.content).count("span")}'
print(s)
f = open('newFile.txt', 'w')
f.write(s)
f... |
def spiral(n,a): # passed all pubic cases and passed all private cases
r=0 #row start
c=0 #col start
m=n #col end
n=n#row end
while(r<n and c<m):
for i in range(r,n):#first col
if(r==n-1 and c==m-1):
print(a[i][c],end="")
else:
print(a[i][c],end=" ")
c += 1
fo... |
import random
n = int(input())
arr = []
for i in range(0,n):
ele = int(input())
arr.append(ele)
def isSorted(arr):
flag = 1
for i in range(0,len(arr)):
if(i<len(arr)-1 and arr[i]>arr[i+1]):
flag = 0
return flag
def swap(arr,i,j):
arr[i],arr[j] = arr[j],arr[i]
return arr
list1 ... |
n = 1
sum = 0
while(n<6):
sum = sum + int(input())
n = n + 1
average = sum/5
print(average , end="")
|
count = int(input('how many numbers are there in your code? '))
codelist = []
def mainloop():
count = int(input('how many numbers are there in your code? '))
codelist = []
while len(codelist) > 0:
codelist.pop((len(codelist)))
entercode(count)
decode(count)
finaldecode()
def entercode... |
# Equal Sum Partition
# PS: Given an arrays "nums", return whether or not the array can be broken into 2 subsets such that the sum of both the partitions is equal
# eg:
# nums = [1,5,11,5]
# o/p = True
# because [1,5,5] = 11 and [11] = 11
# *********************NOTE**********************
# If the sum of the elements... |
# Using recursion
# Reference: https://youtu.be/kvyShbFVaY8
def knapsack(wts, val, W, length):
# Base Condition:
# Smallest valid weight = 0 kg
# Smallest possible capacity value = 0
if length==0 or W==0: # When either knapsack is full when no elements remain in the wts array
return 0
... |
# Basic linked list implementation using functions
# Both insertion and deletion
class LinkedList:
def __init__(self):
self.head= None
# Printing the linked list
def printll(self):
temp = self.head
while (temp):
print(temp.data, end = " ")
... |
# Subset Sum Problem reference https://youtu.be/_gPcYovP7wc
# Problem Statement: Given an integer array "nums" and an integer "sums", output where any subset of nums can sum upto to "sum"
# Output: Boolean (True/False)
# eg1:
# nums = [2,3,7,8,10]
# sum = 11
# output: True
#First Step, Let's make the DP Matrix
# t[l... |
# -*- coding: utf-8 -*-
__author__ = "Patrick Lehmann"
from itertools import permutations
persons = set()
happiness = dict()
def main():
global persons, happiness
biggest_happiness = 0
seat_placement = "None"
with open('../../input/day13.txt', 'r', encoding='utf-8') as f:
data = f.read()
... |
__author__ = "Patrick Lehmann"
import heapq
def main():
"""
Entry point of the program
"""
with open('../../input/day02.txt') as f:
data = f.read()
parse_input(data)
def parse_input(data):
total_wrapping_paper = 0
total_ribbon = 0
for line in data.splitlines():
dime... |
__author__ = "Patrick Lehmann"
def main():
"""
Entry point of the program
"""
with open('../../input/day01.txt') as f:
data = f.read()
print("Part 1: ")
print(answer_part1(data))
print("Part 2: ")
print(answer_part2(data))
def answer_part1(data):
counter = 0
for c in... |
# make sure to run previous codes
# Summarize all numeric columns
print(df.describe())
# Summarize all columns
print(df.describe(include='all'))
print(df.describe(include=['object'])) # limit to one or more types
# statistics per group (groupby)
print(df.groupby("job").mean())
print(df.groupby(... |
import math
class Shape2D:
def area(self):
raise NotImplementedError()
# __init__ is a special method called the constructor
# Inheritance + Encapsulation
class Square(Shape2D):
def __init__(self, width):
self.width = width
def area(self):
return self.width ... |
# Missing data
# Missing values are often just excluded
df = users.copy()
df.describe(include='all') # exclude missing values
# find missing values in a series
df.height.isnull() # True if NaN, False otherwise
df.height.notnull() # False if NaN, True otherwise
df... |
import pymongo
###Connection
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"] # Db
mycol = mydb["customers"] #table
list1 = mycol.find().sort("name") # ascending
list = mycol.find().sort("name", -1) # Descending
for x in list:
print(x)
|
class Student:
def __init__(self): #Called when class called(similar to constructor of java)
self.name = "Rolf"
self.grades = (88, 91, 78, 98, 95)
def __init__(self, name, grades): #Called when class called(similar to constructor of java)
self.name = name
self.grades = grades
def average(self)... |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Tis is title")
# showinfo, showwarning, showerror, askyesno, askquestion
def popup():
response = messagebox.askyesno("This is title","Here is messagebox")
if response==1:
Label(root,text="You clicked yes").pack()
... |
"""
简单选择排序
基本思想:在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;
然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和
第n个元素(最后一个数)比较为止。
时间复杂度:O(n*n)
"""
def simple_select_sort(array):
for i in range(len(array)):
min_index = i
for j in range(i, len(array)):
if array[j] < array[min_index]:
... |
# -*- coding: utf-8 -*-
import math
import csv
import copy
from collections import OrderedDict
from fractions import Fraction
AGE_GRANULARITY = 10
def reidentify_patient(record_hospital):
gender = record_hospital['gender']
age = record_hospital['age']
zipcode = record_hospital['zipcode']
success = F... |
"""
Simulation of fast-food restaurant
system description should be added
Outputs : 1-mean time for customer being in the system
2-mean customer's waiting time in receiving food
3-mean and maximum of queue length in serving food part
4-mean performance of the servers in ordering and ... |
def reverseInteger(x:int):
num = str(x)
temp = str()
if num[0] == '-':
temp += '-'
for i in range(len(num)-1, -1, -1):
if num[i] == '-':
pass
else:
temp += num[i]
return int(temp)
print(reverseInteger(-123)) |
# coding: utf-8
# <div align="right">Python 2.7 Jupyter Notebook</div>
#
# # Living labs
# <br>
# <div class="alert alert-warning">
# <b>This notebook should be opened and completed by students completing both the technical and non-technical tracks of this course.</b>
# </div>
#
# ### Your completion of the noteboo... |
#!/usr/bin/env python3
from rearrange import rearrange_name
import unittest
class TestRearrange(unittest.TestCase):
def test_basic(self):
testcase = 'Guenon, Rene'
expected = 'Rene Guenon'
self.assertEqual(rearrange_name(testcase),expected)
def test_null(self):
testcase = ""
expected = ""
self.assertEqu... |
#!/usr/bin/env python3
import re
def rearrange_name(name):
# full words use of: \b....\b
result = re.search(r"^([\w .]*), ([\w .]*)$", name)
#print(result.groups())
if result == None:
return name
return "{} {}".format(result[2],result[1])
|
# Author: Christopher LeMoss
# Date: 1-30-2021
# Description:
# Homework 3 for CS362 Software Engineering II at Oregon State University.
# Determines whether or not the given year is a leap year.
# Lacks error handling.
year = int(input("Enter year: "))
is_leap_year = False
if year % 4 == 0:
if year % 100... |
class TicTacToe:
def __init__(self):
self._board = [['','',''],['','',''],['','','']]
self._current_state = "UNFINISHED"
self._num = 0
def horizontal_win(self, row, player):
if row>2 or row<0:
return False
if self._board[row] != "":
retur... |
import mysql.connector
mydb = mysql.connector.connect(host='localhost', user='root', password='', database='salon')
mycursor = mydb.cursor()
mycursor.execute('select flight_id FROM passengers GROUP BY flight_id HAVING COUNT(*) > 1')
myresult = mycursor.fetchall()
if myresult:
print('COUNT Have Records:')
... |
cpf = input("Entre com o seu CPF ")
cpflist = []
cpflist = list(cpf)
for digito in cpflist:
if not digito.isnumeric():
cpflist.remove(digito)
digito1 = []
for i in range(10, 1, -1):
digito1 += [i]
digito2 = []
for i in range(11, 1, -1):
digito2 += [i]
var = 0
for i in range(9):
var += int(digito... |
dinheiro = [100, 50, 25, 10, 5, 2, 1, 0.5, 0.25, 0.10, 0.05, 0.01]
newvalue = float(input('Qual valor você deseja sacar em reais? '))
print("Você irá sacar:")
for i in dinheiro:
x = int(newvalue//i)
if i > 1 and x != 0:
print(f'{x} nota(s) de R$ {i:.2f}')
elif i <= 1 and x != 0:
... |
'''
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that... |
'''
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640... |
'''
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
'''
import numpy as np
def lattice_paths(width, height):
grid = np.zeros((width + 1, height + 1), dtyp... |
'''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
factorials = {'0': 1}
f = 1
for i in range(1, 10):
f *= i
factorials[str(i)] = f
resu... |
'''
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
'''
def is_bin_Palindrome(n):
b = str(bin(n... |
# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# TO-DO
# merged_arr = sorted(elements)
merged_arr = sorted(arrA + arrB)
return merged_arr
# test_array_one = [1, 2, 3]
# test_array_two = [4... |
#this program is meant for creating quizes with random order and random wrong answers
#this is for making each exam completely differente from one another
import random
import json
import os
import time
def createquiz(quiznum):
now = list(time.localtime()) #setting the current date
foldername = 'quize... |
##Check a given number/word, whether its a palindrome or not
##Use recursion to do the task
def is_palindrome(num): #argument alays takes int.
n= str(num) #input ('Enter number or word') #input alays takes string.
if len(n) <= 1:
return True
elif n[0] == n[-1] and is_palindrome(n[1:-1]):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.