text stringlengths 37 1.41M |
|---|
def quick_sort(list, start, end):
# repeat until sublist has one item
# because the algorithm is using in-place space, we can not use len(list) instead we use start, end for sublist
if start < end:
# get pivot using partition method
pivot = partition(list, start, end)
# recurse quick... |
""" Lab 07: Generators, Linked Lists, and Trees """
# Generators
def naturals():
"""A generator function that yields the infinite sequence of natural
numbers, starting at 1.
>>> m = naturals()
>>> type(m)
<class 'generator'>
>>> [next(m) for _ in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
... |
import numpy as np
# --Description--
# NxN Board
# Initial state is random
# Winning -> all white (ones)
class Board():
def __init__(self, size):
self.rows = size
self.cols = size
self.board = None
self.boardZeros = None
self.boardOnes = None
def getRows(self):
... |
import threading
# 이건 모듈이다.
n = 1000
offset = n//4
def thread_main(li, i):
for idx in range(offset * i, offset * (i+1)):
li[idx] *=2
li=[i+1 for i in range(1000)]
threads=[]
# 스레드를 생성
# 실행 흐름을 담당할 변수를
for i in range(4):
# Thread는 모듈에 있는 함수이다.
th=threading.Thread(
# thread_main에 들어가는 매개변수 ... |
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.
A leaf is a node with no children.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.le... |
# O(k+(n-k)lgk) time, min-heap
def findKthLargest4(self, nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
for _ in xrange(len(nums)-k):
heapq.heappop(heap)
return heapq.heappop(heap)
def findKthLargest(self, nums, k):
heap = nums[:k]
heapify(heap)
for n in ... |
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# If target is not found in the array, return [-1, -1].
# Follow up: Could you write an algorithm with O(log n) runtime complexity?
# Example 1:
# Input: nums = [5,7,7,8,8,10], target = 8
#... |
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
# DFS
class Solution:
def cloneGraph(self, node): # DFS recursively
if not node:
return node
m = {nod... |
# DFS
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
tmp_list = []
pos = 0
nums = list(range(1, n + 1))
self.get_combination(res, nums, tmp_list, k, pos)
return(res)
def get_combination(self, res, nums, tmp_list, k, pos):
... |
from collections import Counter
from itertools import cycle
def calculate(input_):
"""
Given a string with numbers separated by comma like "+1, -2"
calculate the sum of the numbers
"""
return sum([int(x.strip()) for x in input_.split(",") if x])
def find_reached_twice(input_):
"""
Given ... |
from sys import stdin, stdout
from math import sqrt
class Rectangle():
def __init__(self, x1, x2, y1, y2):
self.__x1 = x1
self.__x2 = x2
self.__y1 = y1
self.__y2 = y2
def point_in_figure(self, x, y):
return((x > min(self.__x1,self.__x2)) and (x < max(self... |
str="wecjdifhvgsjfudhscgj"
list1=list(set(str))
dict1=dict()
for i in list1:
num=str.count(i)
dict1.setdefault(i,num)
items=list(dict1.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in items:
print("{}:{}".format(i[0],i[1]))
|
class College:
college_name="Atria"
principal="Ram"
college_code="1At01"
annual_fees=10
@classmethod
def modcoll(cls):
a=int(input("enter choice 1.collname,2.pricipal,3.code"))
if a==1:
cls.college_name=input("Enter the coll name to be updated")
elif a==... |
from enum import Enum
class IntermediateType(Enum):
BOOL = 'bool'
CHAR = 'char'
STRING = 'string'
DOUBLE = 'double'
INT = 'int'
LONG = 'long'
ARRAY = 'array'
LIST = 'list'
SET = 'set'
MAP = 'map'
LINKED_LIST_NODE = 'LinkedListNode'
BINARY_TREE_NODE = 'BinaryTreeNode'
... |
class LinkedListNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
p = self
q = other
while p is not None and q is not None:
... |
from typing import List
from colors import blue, yellow
import re
def char_to_num(char: str) -> int:
"""Переводит заголовки строк (a,b,c) в числа для дальнейших операций с матрицей"""
return ord(char) - 97
def num_to_char(num: int) -> str:
"""Переводит числа в заголовки строк для вывода доски"""
ret... |
import os
print("""Choose from the options below ......
1. Create a new VG
2. View VGs
3. Exit""")
while True:
c = input("Enter your choice: ")
if int(c) == 1 :
pv = input("Enter names of the drivers: ")
vg = input("Enter the name to be allocated to the created Volume G... |
'''
READ ME:
Unfortunately, the remaining projects in this course require a library accessed only through the course
website sandbox. If you would like to play this game you can view it here: http://www.codeskulptor.org/#user47_WrxHGCVrsK_6.py
If this link has been removed in the backend, you can always play the gam... |
#Bubble Sort
l1=eval(input("Enter list here"))
count=0
for i in range(len(l1)):
for j in range(len(l1)-i-1):
if l1[j]<=l1[j+1]:
count+=1
continue
elif l1[j]>l1[j+1]:
l1[j], l1[j+1]=l1[j+1], l1[j]
count+=1
print(l1, "operations took place", count,"numbe... |
import csv
with open('Dataset.csv', newline = '') as f:
reader = csv.reader(f)
fileData = list(reader)
# Remove header while reading data
fileData.pop(0)
newData = []
### HEIGHT
# FOR I IN RANGE => for each
# len => length
for i in range(len(fileData)):
n_num = fileData[i][1]
newData.app... |
import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
# POST to API
payload = {'country': 'Italy'}
URL = 'https://api.statworx.com/covid'
response = requests.request("POST", url=URL, data=json.dumps(payload))
# Convert to data frame
df = pd.DataFrame.from_dict(json.loads(response.te... |
def prompt_input(prompt, errormsg):
"""
Prompts the user for an integer using the prompt parameter.
If an invalid input is given, an error message is shown using
the error message parameter. A valid input is returned as an
integer. Only accepts integers that are bigger than 1.
"""
is_int = F... |
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import numpy as np
### 1d example of interpolation ###
in_data_x = np.array([1., 2., 3., 4., 5., 6.])
in_data_y = np.array([1.5, 2., 2.5, 3., 3.5, 4.]) # y = .5 x - 1
f = interp1d(in_data_x, in_data_y, kind='linear')
print(f)
# f in all of the... |
a = 33
b = 200
if b > a:
print("b is greater than a")
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:... |
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft"... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
""""
Implementing a model a described in the link below would probably work well for this type of data
https://nbviewer.jupyter.org/github/srnghn/ml_example_notebooks/blob/master/Predicting%20Yacht%20Resistance%20with%2... |
from pprint import pprint
def prepare_dict(file_name: str) -> dict:
result: dict = dict()
with open(file_name, encoding='utf-8') as file:
for line in file:
name_dish = line.strip()
records_ingredients = int(file.readline())
ingridient_list = []
for ingri... |
#Zad.9 Napisz skrypt, w którym zadeklarujesz zmienne typu: string, float i szestnastkowe.
# Następnie wyświetl je wykorzystując odpowiednie formatowanie.
string = 'Hello World!'
float = float(10)
szesznastka = hex(156)
print(string)
print(float)
print(szesznastka)
|
# Zad3. Napisz skrypt, w którym stworzysz operatory przyrostkowe dla operacji: +, -, *, /, **, %
a, b, c, d, e, f = 10, 10, 10, 10, 10, 10
a += 2
print(a)
b -= 2
print(b)
c *= 2
print(c)
d /= 2
print(d)
e **= 2
print(e)
f %= 2
print(f) |
def convert_tulpe_to_str(tpl):
result = ""
if len(tpl) > 0:
for word in tpl:
result += str(word) + " "
result.rstrip()
return result |
# 猜数字游戏,1到100之间的随机数字
import random
r = random.randint(1,100)
count = 0
while True:
count = count + 1
num = int(input('请输入数字:'))
if num == r:
print('恭喜你,你猜对了')
break
elif num > r:
print('比', num, '小,再猜')
elif num < r:
print('比', num, '大,接着猜')
print('这是第', count, '... |
#NAME :PRANJAL SARODE
#DIV :D ROLL NO :9
from matplotlib import pyplot as plt # python lib for plotting graph
import numpy as np # python lib for using 2d array
import math # python lib for using mathematical aretmetics
print("Given Stress Tensor")
print( )
A = np.array([[120, -55, -75], [-55, 55, 33], [... |
def math(number):
square = number * number
third = number * number * number
print("The square of your number is {a} and to the third power is {b}.".format(a=square, b=third)
while True:
while True:
number = int(input("Tell me a number"))
math(number)
|
# # 异或
# class Solution:
# def hammingDistance(self, x: int, y: int) -> int:
# res = 0
# t = x ^ y
# while t:
# t &= (t - 1)
# # 每经过一次t &= t - 1,都会消除t对应的二进制的最右边的“1”
# res += 1
#
# return res
# 使用移位的方式,检查最右侧或最左侧的元素是否为1
class Solution:
def hamm... |
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
if n == 1 or n == 2:
return 1
# 辅助数组空间
# dp = [0] * (n + 1)
# dp[1] = 1
#
# for i in range(2, n + 1):
# dp[i] = dp... |
"""
现在有一幅扑克牌,去掉大小王52张牌。随机选出4张牌,可以任意改变扑克牌的顺序,
并填入 + - * / 四个运算符,不用考虑括号,除法按整数操作,计算过程中没有浮点数,问是否能够求值得到给定的数m。
输入描述: 一行四个数字 (JQK 分别被替换成11,12,13)单空格分割,另一行输入 m
输出描述: 可以输出1, 否则输出0
"""
def fun(nums, m):
def dfs(exp, s, i):
if i == 4:
if str(s) == m:
# print(exp[:-1])
ret... |
from typing import List
# 超时
# class Solution:
# def findAnagrams(self, s: str, p: str) -> List[int]:
# if not s or not p:
# return []
# ns, np = len(s), len(p)
# res = []
# hashp = {}
# for i in range(np):
# ch = p[i]
# hashp[ch] = hashp... |
# -*- coding:utf-8 -*-
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
# 1. 先复制普通节点,再复制随机节点
if not pHead:
return
... |
class Solution:
"""
@param A: A string
@param B: A string
@return: the length of the longest common substring.
"""
# 1.暴力解法
# def longestCommonSubstring(self, A, B):
# # write your code here
# m, n = len(A), len(B)
# maxlen = 0
#
# for i in range(m):
... |
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# 方法:排序 & 合并。时间和空间复杂度取决于排序的复杂度,即O(NlogN),空间O(logN),
# 对每个区间的左端点进行排序
intervals.sort(key=lambda x: x[0])
merged = []
for int in intervals:
# 如果列表为空,或当前区间与上一个区间... |
def insertSort(nums):
n = len(nums)
for i in range(n):
tmp = nums[i]
j = i - 1
while j >= 0 and nums[j] > tmp:
nums[j + 1] = nums[j]
j -= 1
print(nums)
nums[j + 1] = tmp
# print(nums)
return nums
numbers = [-5, 5, 11, 2, 4, -3]
inse... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 方法1。迭代法。时间复杂度为O(L1+L2),空间复杂度O(1)
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
if not l2: return l... |
class Solution:
def climbStairs(self, n: int) -> int:
# 方法:动态规划
# if n < 3: return n
# dp = [0] * (n + 1)
# dp[0], dp[1] = 1, 1
# for i in range(2, n + 1):
# dp[i] = dp[i - 1] + dp[i - 2]
# return dp[-1]
# 空间优化
if n < 3: return n
a... |
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if not numbers:
return
n = len(numbers)
arr = [0] * n
for num in numbers:
arr[num - 1] += 1
for i, a in enumerate(arr):
if a > n ... |
#-*- coding: utf-8 -*-
import threading,multiprocessing
def loop():
x = 10
while True:
x = x+1
print(x)
for i in range(multiprocessing.cpu_count()):
t = threading.Thread(target=loop)
t.start() |
#-*- coding: utf-8 -*-
#python 关于map与reduce的应用
from functools import reduce
#编写数字字典
def char2num(ch):
return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[ch]
def f(x,y):
return x*10 + y
#将字符串转换成浮点数
def str2float(s):
a = s.index('.')
s1 = s[:a]
s2 = s[a+1:]
n = len(s2)
return reduce(f,map(ch... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#python关于filter()也就是筛选函数的应用 求素数
def main():
for n in primes():
if n<1000:
print(n)
else:
break
#生成间隔为2的自然数
def _odd_iter():
n = 1
while True:
n +=2
yield n
def _not_dicisible(n):
return lambda x:x%n>0
def primes():
yield 2
it = _odd_iter
while True:... |
# -*- coding: utf-8 -*-
import hashlib
db = {
'michael': 'e10adc3949ba59abbe56e057f20f883e',
'bob': '878ef96e86145580c38c87f0410ad153',
'alice': '99b1c2188db85afee403b1536010c2c9'
}
#返回密码的md5码
def calc_md5(password):
md5 = hashlib.md5()
md5.update(password.encode('utf-8'))
return md5.hexdigest... |
# roman number to integer
nums = []
def romanToInt(roman):
sum = 0
for letter in roman:
if letter is '':
nums.append(0)
elif letter is 'I' or letter is 'i':
nums.append(1)
elif letter is 'V' or letter is 'v':
nums.append(5)
elif letter is... |
class Board:
def __init__(self, WIDTH, HEIGHT, SPACING):
"""constructor of Board object"""
self.WIDTH = WIDTH
self.HEIGHT = HEIGHT
self.SPACING = SPACING
def board_display(self):
"""draw lines of board"""
# draw the horizontal line
strokeWeight(2)
... |
from stack import Stack
stack=Stack()
stack.push("a")
stack.push("b")
stack.push("c")
temp=stack.__str__()
print(temp)
for letter in range(97,123):
print(chr(letter)) |
from dot import Dot
class Dots:
"""A collection of dots."""
def __init__(self, WIDTH, HEIGHT,
LEFT_VERT, RIGHT_VERT,
TOP_HORIZ, BOTTOM_HORIZ):
self.WIDTH = WIDTH
self.HEIGHT = HEIGHT
self.TH = TOP_HORIZ
self.BH = BOTTOM_HORIZ
self.LV =... |
import glob
import pathlib
from PIL import Image
mainfolder = input("Input folder: ")
p = pathlib.Path("{}/".format(mainfolder))
def compress(img_file):
print(img_file)
basewidth = 1920
img = Image.open(img_file)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(... |
#Lab 7 Seat Class with respective sub classes
#Logan Kilpatrick
#Implimented by lab7.py
#imported by chart class
class Seat:
'''
The Seat class has:
instance variables price and taken (a boolean).(parent class)
a constructor that initializes the taken attribute to False and ...
has a default argum... |
import math
from datetime import datetime
la1 = float(raw_input("Enter the starting latitude: "))
lo1 = float(raw_input("Enter the starting longitude: "))
la2 = float(raw_input("Enter the ending latitude: "))
lo2 = float(raw_input("Enter the ending longitude: "))
ts1 = "2016-01-15 10:00:00"
ts2 = "2016-01-15 10:30:00... |
TELEPHONES = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
NAMES = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
numero = input("Quel est le numéro?")
findIt = False
for i in range(0, 9):
if TELEPHONES[i] == numero:
print(NAMES[i])
findIt = True
if not findIt:
print("non att... |
print("entrez votre prénom et votre nom séparés d'un espace")
fullName = input()
sep = " "
nom = ""
prenom = ""
inPrenom = True
for i in range(0, len(fullName)):
if fullName[i] == sep:
inPrenom = False
elif inPrenom:
prenom = prenom + fullName[i]
else:
nom = nom + fullName[i]
print(... |
c = input('請輸入攝氏: ')
c = float(c) #溫度可能有小數點
f = (c * (9 / 5)) + 32
print('攝氏溫度', c, '的華氏溫度是', f) |
class Queue:
"""
Queue Stack provides implementation of all primary method of a queue such as enqueue, dequeue, peek
"""
def __init__(self):
self.queue = []
def show(self):
return self.queue
def enqueue(self, val):
"""
Time complexity: O(1)
... |
"""
Create a simple array class where each element must be an integer type and:
- has a .len() method which outputs the length of the array
- has a .get(i) method which outputs the value at a given index
- has a a .set(val,i) method which replaces the val at index i
"""
class Array(object):
... |
"""
Write a function that inputs a list of lists and returns if it can form a tree with the root as the first
element of the list and each other element a subtree.
"""
def isTree(l, value=True):
if len(l) == 0:
return True
if len(l) == 1:
return type(l[0]) != list
if type(l[0]) ... |
class Stack(object):
"""
class Stack provides implementation of all primary method of a stack such as push, pop, isEmpty, size, and show
"""
def __init__(self):
self.stack = []
def show(self):
"""
Time complexity: O(1)
Space complexity: O(1)
"""
... |
import unittest # import the unittest module to test the class methods
from implementation_8.binary_search_tree import BST
class TestBSTTree(unittest.TestCase):
def test_BST_insert(self):
# Set up tree
tree = BST()
self.assertEqual(tree.createBST([1, 2, 0, 4, 1.5]), "0-1-1.5-2-4... |
"""
Write a binarySearch(array, val) function that inputs a sorted array/list (ascending order)
and returns if the value is in the array using BinarySearch (should be O(logN) time)
"""
# def binary_search(l, target):
# """
# Iterative binary search algorithm
# """
# start = 0
# end = le... |
import unittest # import the unittest module to test the class methods
from implementation_10.undirected_graphs import UndirectedGraph
class TestUndirectedGraph(unittest.TestCase):
def testIsVertex(self):
graph = UndirectedGraph()
graph.insert_vertex("A")
self.assertEqual(graph.... |
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self):
self.len = 0
self.root = None
def createBST(self, l):
"""
Time Complexity: O(n*log(n))
... |
import matplotlib.pyplot as plt
#PLOTDATA Plots the data points x and y into a new figure
# PLOTDATA(x,y) plots the data points and gives the figure axes labels of
# population and profit.
def plotData(x, y):
plt.ion()
plt.figure()
plt.plot(x, y, 'x')
plt.axis([4, 24, -5, 25])
plt.xlabel... |
# a = 10
# b = 14 # 13으로 수정하면 첫 번째 조건문을 만족하지 않음
# if (a % 2 == 0) and (b % 2 == 0): # 첫 번째 조건문
# print('두 수 모두 짝수입니다.')
# if (a % 2 == 0) or (b % 2 == 0): # 두 번째 조건문
# print('두 수 중 하나 이상이 짝수입니다.')
a = 9
b = 14
if (a % 2 == 0) and (b % 2 == 0) :
print('두 수 모두 짝수')
if (a % 2 == 0) or (b % 2 == 0) :
print... |
import random
print('''
---------------------------------------
The Random Number Guessing Game Begins!
---------------------------------------
''')
scores = []
def start_game():
global scores
randomNumber = random.randint(1, 10)
attempts = 0
if scores:
print(f"\n------ The HIGHSCORE is {min... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def digitos(n):
indice=1
while n>9:
n=n/10
indice +=1
print indice
a=input("ingrese el numero ")
digitos(a) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def mayusculas (cadena):
cont = 0
for i in cadena:
if i != i.lower():
cont += 1
print "La cadena tiene "+ str(cont)+" mayusculas"
a=raw_input("ingrese una palabra ")
print mayusculas(a)
|
peso = float(input("Por favor informe seu peso: "))
altura = float(input("Por favor informe sua altura: "))
imc = float
imc = peso / (altura * altura)
if imc < 16.00:
print("seu IMC é de: {:.2f} Categoria: Baixo peso Grau III".format(imc))
elif imc <= 16.99:
print("seu IMC é de: {:.2f} Categoria: Baixo peso G... |
# import necassary packages
import random
class Product:
"""
Product class that takes name (mandatory), price (default=10),
weight (default=20), flammability (default=0.5)
"""
def __init__(self, name, price=10, weight=20, flammability=0.5):
"""
This method is to initialize the cl... |
# -*- coding: utf-8 -*-
"""
__title__ = '03 匿名函数_lambda_map_reduce_filter.py'
__author__ = 'yangyang'
__mtime__ = '2018.03.16'
"""
'''
python匿名函数:lambda
匿名函数作用:1.节省代码量。2.看着更优雅。
python: map(function,iterable,...)
Python函数编程中的map()函数是将func作用于seq中的每一个元素,并将所有的调用的结果作为一个list返回。
reduce函数:
在Python 3里,reduce()函数已经被从全局名字... |
# -*- coding: utf-8 -*-
# __title__ = '06 __repr__方法.py'
# __author__ = 'yangyang'
# __mtime__ = '2018.03.20'
#__str__与__repr__ 是在类(对象)中对类(对象)本身进行字符串处理。
# __str__ 与 __repr__ 在我看来,__repr__ 是隐形显示的给开发人员看的,__str__ 是给用户看的
class A(object):
def __str__(self):
return "__str__"
def __repr__(self):
... |
# -*- coding: utf-8 -*-
"""
__title__ = '02 属性查找与绑定方法.py'
__author__ = 'ryan'
__mtime__ = '2018/3/18'
"""
country = 'china'
class UserInfo(object):
address = 'SH'
def __init__(self,name,sex,age):
self.name = name
self.sex = sex
self.age = age
def learn(self,country):
print(" %s studying in %s"%(self.nam... |
# l = [4,7,3,1,8,5,2,6]
#
# def bubble_sort(sample_list):
# changed = True
# while changed:
# changed = False
# for i in range(len(sample_list) - 1 ):
# if sample_list[i+1] < sample_list[i]:
# temp = sample_list[i+1]
# sample_list[i+1] = sampl... |
lst = [1, 2, [3, 4, [5, 6]], 7, 8]
flat_lst = []
def remove_nesting(l):
for ele in l:
if isinstance(ele, list):
remove_nesting(ele)
else:
flat_lst.append(ele)
remove_nesting(lst)
print(flat_lst)
|
# Write a function that accepts two strings as arguments and returns True if
# either string occurs anywhere in the other, and False otherwise.
def isIn(str1, str2):
"""
Assumes str1 and str2 are strings.
Returns True if str1 is within str2 and vice versa.
"""
return str1 in str2 or str2 i... |
def triplets(numlist):
# Square and sort the list
sqrd = list(map(lambda x: x ** 2, numlist))
sqrd.sort()
# For loop beginning at last element, and goes to 1st decrementing by 1 each time
for i in range(len(sqrd)-1, 1, -1):
# Set j to first element and k to element before i
j = 0
... |
"""
File Name: utils.py
Description: This task involves writing tools for reading and processing the data, as well as defining data structures
to store the data. The other tasks import and use these tools.
Author: Himani Munshi
Date: 12/10/2017
"""
#TASK 0
from rit_lib import *
Maindata = struct_type("M... |
"""
3. Совместить валидацию email и валидацию пароля и вместо принтов райзить ошибки если пароль или
email не подходит по критериям (критерии надежности пароля можно брать с прошлого ДЗ или придумать новые).
Ошибки брать на выбор
"""
# PASSWORD AND EMAIL VALIDATOR
# ------------------------------------------
# EMA... |
from collections import Counter
"""
3. Реализовать функцию, которая принимает строку и расделитель и возвращает словарь {слово: количество повторений}
(частотный словарь)
"""
def converter(str1: str, sep1: str):
dict1 = dict(Counter(str1.split(sep1)))
return dict1
my_str = input('String ')
delimiter = i... |
"""
Создать класс воина, создать 2 или больше объектов воина с соответствующими воину атрибутами. Реализовать методы,
которые позволять добавить здоровья, сменить оружие. Реализовать возможность драки 2х воинов с потерей здоровья,
приобретения опыта.
Следует учесть:
- у воина может быть броня
- здоровье не может быть... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 27 20:38:13 2016
@author: changsongdong
To show a basic convolutional neural network built using TensorFlow
"""
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
sess = tf.InteractiveSession()
lr = ... |
"""A cli memory game board.
A representation of a memory game board and functions to interact with it.
"""
import string
from random import shuffle
class Board:
"""A memory game board."""
def __init__(self):
self.rows = 4
self.columns = 4
self.bg_board = []
s... |
import math
import os
import random
import re
import sys
def climbingLeaderboard(scores, alice):
scores = list(set(scores))
scores.sort(reverse=True)
j = len(scores)-1
ranks = []
for i in alice:
if i not in scores:
while scores[j] < i and j >= 0:
j -= 1
... |
def findRotationCount(array):
size = len(array)
for i in range(size-1):
if array[i+1]<array[i]:
return i+1
return 0
array = [7, 9, 11, 12, 5]
count = findRotationCount(array)
if count!=0:
print("Array should be rotated",count,"clockwise times to arrange it in sorted manner")
else:
print("Array is a... |
def reverseArray(arr, start, end):
while (start < end):
arr[start], arr[end] = arr[end], arr[start]
start = start + 1
end = end - 1
# Function to right rotate arr
# of size n by d
def rightRotate(arr, d, n):
reverseArray(arr, 0, n - 1)
reverseArray(arr, 0, d - 1)
reverseArray(a... |
"""
Given 2 strings A and B, and a character X. You have to insert string B into string A in such a way that after you have performed the join operation, the resulting string contains a substring that contains only character X of length len. Find the maximum possible value of len.
You are allowed to split the string ... |
# check uppercase , lowercase, digits and special character in a array
up=0
lo=0
d=0
s=0
array= input("Enter the value you want to check: ")
x=len(array)
for i in range (0,x):
if(array[i].isupper()):
print("UPPERCASE CHARACTERS : ",array[i])
up+=1
elif(array[i].islow... |
from abc import ABC, abstractmethod
class Aircraft(ABC):
@abstractmethod
def fly(self):
pass
@abstractmethod
def land(self):
pass
class Jet(Aircraft):
def fly(self):
print("My jet is flying")
def land(self):
print("My jet has landed")
jet1 = Jet()
jet1.fl... |
print("hello")
# 定义一个函数 用 def
def my_abs(x):
if x >= 0:
return x
else:
return -x
# 可以函数引用传递给一个变量 然后变量当函数用(闭包)
a = my_abs
print(a(10))
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
|
# written by Pasha Pishdad
# Student ID: 40042599
# Assignment 1
# Driver
from Assignment1Functions import *
if __name__ == "__main__":
run = True
while run:
# calling the function threshold_and_grid_size() to get the threshold and grid size
threshold_and_grid_size()
# calling the ... |
"""CSC108: Fall 2021 -- Assignment 1: Unscramble
This code is provided solely for the personal and private use of students
taking the CSC108 course at the University of Toronto. Copying for purposes
other than this use is expressly prohibited. All forms of distribution of
this code, whether as given or with any cha... |
'''
Calc 2.1 can do all the functions Calc 2 can do, but also Trig and last num equations
This part is the main script
Was other part of my OOP version of calc
'''
from Calc.CalcCore import *
while True:
... |
"""
8-1. Message:
Write a function called display_message() that prints one sentence telling
everyone what you are learning about in this chapter. Call the function, and
make sure the message displays correctly.
"""
def display_message():
"""Display what I am learning about in the current chapter, `Functions`.... |
"""
9-1. Restaurant:
Make a class called Restaurant. The __init__() method for Restaurant should
store two attributes: a restaurant_name and a cuisine_type. Make a method
called describe_restaurant() that prints these two pieces of information, and a
method called open_restaurant() that prints a message indicating ... |
"""
5-11. Ordinal Numbers:
Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most
ordinal numbers end in th, except 1, 2, and 3.
• Store the numbers 1 through 9 in a list.
• Loop through the list.
• Use an if-elif-else chain inside the loop to print the proper ordinal ending
for each number.... |
"""
7-1. Rental Car:
Write a program that asks the user what kind of rental car they would like.
Print a message about that car, such as “Let me see if I can find you a
Subaru.”
"""
car_brand = input("What kind of rental car would you like? ")
print(f"Let me see if I can find you a {car_brand}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.