text
stringlengths
37
1.41M
def last_room(route): result = 1 + 6 * (route - 1) * route / 2 return int(result) n = int(input()) route = 1 while last_room(route) < n: route += 1 print(route)
# 미해결 (시간초과) class Queue(): def __init__(self): self.position = [] self.time = [] def put(self, pos, t): self.position.append(pos) self.time.append(t) def get(self): return (self.position.pop(0), self.time.pop(0)) def is_empty(self): if len(self.positi...
# stack implementation practice class Stack(object): def __init__(self): self.size = 0 self.data = [] def push(self, value): self.data.append(value) self.size += 1 def pop(self): if self.is_empty(): print("the stack is empty") else: ...
def space_to_20(str): output_arr = [] for start in range(len(str)): if str[start] != ' ': break for end in range(len(str)-1, -1, -1): if str[end] != ' ': break for i in range(start,end+1): ch = str[i] if ch == ' ': ch = '%20' ...
for _ in range (10): n = int(input()) if n == -1: break result = 0 c = 0 for _ in range(n): a, b = input().split() a = int(a) b = int(b) result += (a * (b-c)) c = b print(result, "miles")
# Analysis # # If the network is initialized to zero weights, the activations of the hidden # layers are always set to zero, whatever the value of the inputs. The gradient # is always zero for all training samples and no learning can happen with any # gradient-based optimizer (SGD, Adam...): the loss stays constant. # ...
# -*- coding: utf-8 -*- """ 时间:2019-05-06 作者:哥哥 题号:0067 题目: 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 """ class Solution(object): """ :type a: str :type b: str :rtype: str """ # 方法1 使用python特性 def addBinary1(self, a, b): return bin(int(a,2)+int(b,2))[2:] def ad...
# -*- coding: utf-8 -*- """ Created on Thu May 9 10:22:26 2019 @author: liusi """ class Solution(object): def searchInsert(self, nums, target): if target in nums: return nums.index(target) else: for i in range(len(nums)): if nums[i] > target: #target is no...
# -*- coding: utf-8 -*- """ 时间:2019-04-28 作者:哥哥 题号:0021 题目: 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(obje...
# -*- coding: utf-8 -*- '简化路径' # Given an absolute path for a file (Unix-style), simplify it. # For example, # path = "/home/", => "/home" # path = "/a/./b/../../c/", => "/c" def simplify_path(path): path_lst = [item for item in path.split('/') if item not in ('.', '')] stack = [] for item in path_lst: ...
# -*- coding: utf-8 -*- '蛇形打印二叉树结构' class Node(object): '二叉树节点定义' def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def get_tree_list(root): stack = [] stack.append(root) results = [] while stack: node = stack....
# my first python program # print prints a blank line print # remove the # to print the line # this prints Hello World! #print "Hello World!" # this prints Hello again #print "Hello again" # this prints I like typing this #print "I like typing this." # this prints This is fun. #print "This is fun." # this prints Ya...
"""Each ListNode holds a reference to its previous node as well as its next node in the List.""" class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next """Wrap the given value in a ListNode and insert it after this node. Note that this no...
No= int(input("Enter a number: ")) def DivNumber(No): if(No % 5==0): print("True") else: print("False") if __name__ == '__main__': DivNumber(No)
import itertools num_nodes = 0 # record number of nodes the algorithm traverse visited = {} # store the baord the algorithm has already traversed max_depth = 100 # maximum search depth def iddfs_queue(root_node): print("="*10+"IDDFS (QUEUE)"+"="*10) global num_nodes num_nodes = 0 for depth in itertools.count()...
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.ace = Card('Hearts', 1) self.two = Card('Diamonds', 2) self.card_game = CardGame() self.cards = [self.ace, self.two] def test_check_for_is_...
aa=input() aa=aa.split() a=int(aa[0]) b=int(aa[1]) c=int(aa[2]) if a>b: if a>c: print (a) elif b>c: print (b) else: print (c)
# Medium """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ # perfect binary tree : # 1. all leaves are on same level # 2....
class Solution: # returns subtrees last node previous = None inorder_successor_node = None def iter(self, node: TreeNode, p: TreeNode): if not node: return self.iter(node.left, p) if self.previous == p and not self.inorder_successor_node: self.inorder_su...
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: now = head length = 0 while now: length += 1 now = now.next now = head # addition = 0 if length % 2 else 1 # len is odd: 0, even: 1 addition = 0 for ...
from queue import Queue class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: # rooms: key that is placed in room # enter from room 0, can you open all the rooms? s = [False] * len(rooms) q = Queue() q.put(0) while q.qsize() > 0: e...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: def iter(fst, sn...
#!/usr/bin/env python # coding: utf-8 # In[15]: """NUI Galway CT5132/CT5148 Programming and Tools for AI (James McDermott) Skeleton/solution for Assignment 1: Numerical Integration By writing my name below and submitting this file, I/we declare that all additions to the provided skeleton file are my/our own work, ...
# -*- coding: utf-8 -*- # ################### # input : one file that contains the names in the format(other things can be present) # # f <first name> # # m <second name> # # l <last name> # one file that contains only emails in the format # #e <email> # with a blank line separating 2 papers # output: on...
# = равно # == соответствует # >= больше равно # <= меньше равно # != неравно if 1: print ("True") print ("All is ok") # При значении 0, проверка функции не произойдет и значение не выведутся. if 0: print ("False") print ("Error. Check log file") print("All is cool!") num = input ("Введите ваше имя: "...
import time import random print "Welcome to Russian Roulette!!" time.sleep(2) number = raw_input('Enter a number from 1 to 6 ') print ('you entered %s !' % number) q = raw_input ('ARE you ready ?! y or n ' ) if q == 'y': x = random.randrange(1,6) for i in range(20): print "BE READY !!" time.sl...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-27 08:44:15 LastEditors: yangyuxiang LastEditTime: 2021-05-27 08:57:16 FilePath: /leetcode/145.二叉树的后序遍历.py ''' # # @lc app=leetcode.cn id=145 lang=python # # [145] 二叉树的后序遍历 # # @lc code=start # Definition for a binary tree node....
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-06 22:12:18 LastEditors: yangyuxiang LastEditTime: 2021-06-19 09:32:47 FilePath: /leetcode/二分插入.py ''' def insert(nums, val): left = 0 right = len(nums) while left < right: mid = left + (right - left) // 2 ...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-15 09:31:13 LastEditors: yangyuxiang LastEditTime: 2021-06-23 22:25:59 FilePath: /leetcode/15.三数之和.py ''' # # @lc app=leetcode.cn id=15 lang=python # # [15] 三数之和 # # @lc code=start class Solution(object): def threeSum0(self, n...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-09-04 21:54:45 LastEditors: Yuxiang Yang LastEditTime: 2021-09-04 23:24:41 FilePath: /leetcode/剑指 Offer II 101. 分割等和子串.py Description: 给定一个非空的正整数数组 nums ,请判断能否将这些数字分成元素和相等的两部分。 输入:nums = [1,5,11,5] 输出:true 解释:nums 可以分割成 [1, 5, 5] 和 [11] 。 ''' cla...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-12 10:28:49 LastEditors: yangyuxiang LastEditTime: 2021-05-12 10:36:07 FilePath: /leetcode/77.组合.py ''' # # @lc app=leetcode.cn id=77 lang=python # # [77] 组合 # # @lc code=start class Solution(object): def __init__(self): ...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-24 07:51:33 LastEditors: yangyuxiang LastEditTime: 2021-05-24 07:58:19 FilePath: /leetcode/20.有效的括号.py ''' # # @lc app=leetcode.cn id=20 lang=python # # [20] 有效的括号 # # @lc code=start class Solution(object): def isValid(self,...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-13 14:21:21 LastEditors: Yuxiang Yang LastEditTime: 2021-08-13 15:16:57 FilePath: /leetcode/剑指 Offer 28. 对称的二叉树.py Description: 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 ''' # Definition for a binary tree node. # class TreeNode(object): ...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-20 08:37:41 LastEditors: yangyuxiang LastEditTime: 2021-05-20 09:01:58 FilePath: /leetcode/1011.在-d-天内送达包裹的能力.py ''' # # @lc app=leetcode.cn id=1011 lang=python # # [1011] 在 D 天内送达包裹的能力 # # @lc code=start class Solution(object): ...
#!/usr/bin/env python # coding=utf-8 ''' Description: leetcode Author: yangyuxiang Date: 2021-05-13 10:23:48 LastEditors: yangyuxiang LastEditTime: 2021-06-28 06:54:02 FilePath: /leetcode/22.括号生成.py ''' # # @lc app=leetcode.cn id=22 lang=python # # [22] 括号生成 # # @lc code=start class Solution(object): def __init...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-24 10:35:31 LastEditors: Yuxiang Yang LastEditTime: 2021-08-24 10:38:53 FilePath: /leetcode/剑指 Offer II 083. 没有重复元素集合的全排列.py Description: 给定一个不含重复数字的整数数组 nums ,返回其 所有可能的全排列 。可以 按任意顺序 返回答案。 输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-12 21:40:45 LastEditors: Yuxiang Yang LastEditTime: 2021-08-12 22:14:24 FilePath: /leetcode/剑指 Offer 13. 机器人的运动范围.py Description: 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。 一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-23 22:11:07 LastEditors: yangyuxiang LastEditTime: 2021-07-06 08:55:13 FilePath: /leetcode/45.跳跃游戏-ii.py ''' # # @lc app=leetcode.cn id=45 lang=python # # [45] 跳跃游戏 II # # @lc code=start class Solution(object): def jump(self...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-23 22:58:40 LastEditors: Yuxiang Yang LastEditTime: 2021-08-23 23:22:04 FilePath: /leetcode/剑指 Offer 46. 把数字翻译成字符串.py Description: 给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。 一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-23 16:02:22 LastEditors: yangyuxiang LastEditTime: 2021-05-23 17:20:56 FilePath: /leetcode/82.删除排序链表中的重复元素-ii.py ''' # # @lc app=leetcode.cn id=82 lang=python # # [82] 删除排序链表中的重复元素 II # # @lc code=start # Definition for singly-l...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-04-20 16:24:47 LastEditors: yangyuxiang LastEditTime: 2021-04-20 16:32:33 FilePath: /leetcode/509.斐波那契数.py ''' # # @lc app=leetcode.cn id=509 lang=python # # [509] 斐波那契数 # # @lc code=start class Solution(object): def __init__(sel...
# # @lc app=leetcode.cn id=150 lang=python # # [150] 逆波兰表达式求值 # # @lc code=start class Solution(object): def calc(self, x, y, f): if f == "+": return y + x elif f == "-": return y - x elif f == "*": return y * x else: return int(float(...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-15 08:50:35 LastEditors: yangyuxiang LastEditTime: 2021-05-15 09:30:15 FilePath: /leetcode/653.两数之和-iv-输入-bst.py ''' # # @lc app=leetcode.cn id=653 lang=python # # [653] 两数之和 IV - 输入 BST # # @lc code=start # Definition for a binar...
# # @lc app=leetcode.cn id=112 lang=python # # [112] 路径总和 # # @lc code=start # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def hasPathSum1(self, ...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-04-22 23:07:22 LastEditors: yangyuxiang LastEditTime: 2021-06-17 23:07:28 FilePath: /leetcode/76.最小覆盖子串.py ''' # # @lc app=leetcode.cn id=76 lang=python # # [76] 最小覆盖子串 # # @lc code=start class Solution(object): def minWindow(sel...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-24 08:33:13 LastEditors: yangyuxiang LastEditTime: 2021-05-24 08:58:11 FilePath: /leetcode/56.合并区间.py ''' # # @lc app=leetcode.cn id=56 lang=python # # [56] 合并区间 # # @lc code=start class Solution(object): def merge(self, int...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-26 11:18:54 LastEditors: Yuxiang Yang LastEditTime: 2021-08-26 11:22:13 FilePath: /leetcode/剑指 Offer II 012. 左右两边子数组的和相等.py Description: 给你一个整数数组 nums ,请计算数组的 中心下标 。 数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。 如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧...
# # @lc app=leetcode.cn id=912 lang=python # # [912] 排序数组 # # @lc code=start class Solution(object): def sortArray(self, nums): def merge_sort(nums, l, r): """ :type nums: List[int] :rtype: List[int] 归并排序, inplace """ if l >= r: ...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-30 22:00:20 LastEditors: Yuxiang Yang LastEditTime: 2021-08-30 23:06:31 FilePath: /leetcode/剑指 Offer II 029. 排序的循环链表.py Description: ''' """ # Definition for a Node. class Node(object): def __init__(self, val=None, next=None): self...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-09-03 07:52:34 LastEditors: Yuxiang Yang LastEditTime: 2021-09-03 08:24:17 FilePath: /leetcode/剑指 Offer II 048. 序列化与反序列化二叉树.py Description: ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.v...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-19 22:31:32 LastEditors: Yuxiang Yang LastEditTime: 2021-08-19 23:36:18 FilePath: /leetcode/剑指 Offer 53 - I. 在排序数组中查找数字 I.py Description: 统计一个数字在排序数组中出现的次数。 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 ''' class Solution(object): def search...
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-05-11 10:07:35 LastEditors: yangyuxiang LastEditTime: 2021-05-11 11:26:08 FilePath: /leetcode/234.回文链表.py ''' # # @lc app=leetcode.cn id=234 lang=python # # [234] 回文链表 # # @lc code=start # Definition for singly-linked list. # class L...
# 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 """ size1 = si...
# # @lc app=leetcode.cn id=88 lang=python # # [88] 合并两个有序数组 # # @lc code=start class Solution(object): def find_position(self, nums, m, target): if not nums: return left, right = 0, m while left < right: mid = left + (right - left) // 2 if nums[mid] == t...
#!/usr/bin/env python # coding=utf-8 ''' Author: Yuxiang Yang Date: 2021-08-30 08:42:32 LastEditors: Yuxiang Yang LastEditTime: 2021-08-30 08:51:26 FilePath: /leetcode/剑指 Offer II 025. 链表中的两数相加.py Description: 给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。 可以假设除了数字 0 之外,这两个数字都不会以零开头。 ''' # De...
"""Convert integer to roman numerals Riza Marjadi""" def integer_to_roman(num): values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] symbol = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", ...
"""Coin changes Riza Marjadi""" print("This program will return numbers of quarters, dimes, nickels, and pennies for a dollar value") more='y' while more=='y': while True: try: regularPrice=float(input("\nEnter the regular retail price: $")) break except ValueError: ...
import data_processing import numpy as np from sklearn.linear_model import Ridge from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline from matplotlib import pyplot as plt x, y = data_processing.load_car_price('car_price2.csv') x_train = x[:120] y_train = y[:120] X = np.expa...
# --*-- encoding:utf-8 --*-- #! usr/bin/env python3 students = ['小明', '小红', '小兰'] for student in students: print('%s%s' %(student, '吃了一个苹果!')) students = ['小明', '小红', '小兰'] for student in students: if student == '小红': continue print('%s%s' %(student, '吃了一个苹果!'))
#!/usr/bin/env python3 import math def dectobin(number): li = [] while number > 0: li.append(number % 2) number = math.floor(number / 2) return li[::-1] def main(): a = 156 print(dectobin(a)) #####################################################################...
#!/usr/bin/env python3 def spiral(length): mainli = [[None] * length for j in range(length)] pos_x = 0 pos_y = 0 incr_x = 1 incr_y = 0 for i in range(1, length*length + 1): mainli[pos_x][pos_y] = i temp_x = pos_x + incr_x temp_y = pos_y + incr_y if ...
#!/usr/bin/env python3 # encoding: utf-8 def main(): s = """Cbcq Dgyk! Dmeybh kce cew yrwyg hmrylyaqmr: rylsjb kce y Nwrfml npmepykmxyqg lwcjtcr! Aqmimjjyi: Ynyb""" s1 = """""" i = 0 while i < len(s): if s[i].isalpha(): if s[i] == 'y': s1 += ...
''' 1000-digit Fibonacci number - Problem 25 INPUT: The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci s...
''' Counting Sundays - Problem 19 INPUT: Information: - 01/12/1900 was a Monday. - April, June, September and November - 30 days - All the rest have - 31 days - February - 28 days Leap year - February - 29 days - Leap year if % 4 == 0 - ХХ00 if % 400 == 0 PROBLEM: How many Sundays fell on the first of the month durin...
''' Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' num_1 = 1000 num_2 = 1000 palindome = [] while num_1 >= 100: ...
import RPi.GPIO as IO #calling header file which helps us use GPIO’s of PI import time #calling time to provide delays in program IO.setwarnings(False) #do not show any warnings IO.setmode (IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN35 as ‘GPIO19’)...
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0} money = float(input("Введите количество денег ")) v = list(per_cent.values()) v = list(map(lambda x: x* money*0.01, v)) print(v) print(max(v))
import random class Monty(object): def __init__(self, numIterations, switch): self.choices = ["0", "1", "2"] self.wins = 0 self.losses = 0 self.iterations = numIterations self.isSwitch = switch random.seed() def RunGame(self): for i in range(self.iterations): # randomize the choices ...
# polynomial (linear) regression by 2blam # import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # import dataset dataset = pd.read_csv("Position_Salaries.csv") X = dataset.iloc[:, 1].values # Level column y = dataset.iloc[:, 2].values # Salary column # prefer usi...
def sapa(name): print(f"Hello, {name}") sapa("Luke Skywalker") def tanya(nama, hal): print(f"Hello, {nama}, anda sedang berada di halaman {hal}") tanya("Luke","user admin") def printNegative(index, length): if index == "" and length == "": return while index < length: if index %2 == 1: p...
#创建coachdata.sqlite数据库 import sqlite3 connection=sqlite3.connect('coachdata.sqllite') cursor=connection.cursor() cursor.execute("""CREATE TABLE athletes( id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name TEXT NOT NULL, dob DATE NOT NULL)""") cursor.execute("""CREATE TABLE timing_data( athlete_id INTERGER NO...
import pickle from athletelist import AthleteList from athletelist import get_coach_data def put_to_store(files_list): all_athletes={} for each_file in files_list: ath=get_coach_data(each_file) #将各个文件转换为AthleteList对象实例 all_athletes[ath.name]=ath #把对象实例存储到字典中,对象实例的键名与实例的name属性相同;对象实例是值 # print(all_athletes[ath...
import tkinter as tk window = tk.Tk() window.geometry("306x245") window.minsize(306, 245) window.title('calculator') window.configure(bg='gray20') expression = '' input_text = tk.StringVar() def btn_click(item): """function continuously updates the input field whenever you enters a number""" global expressi...
#!/usr/bin/env python # coding: utf-8 # In[3]: #In order to check if a string contain specific suffix like car print('user_car'.endswith('car')) # In[4]: # check from index 4 to end of string print('user_car'.endswith('car', 4)) # In[5]: #To check from index 5 to 7 print('user_car'.endswith('car', 5, 8)) ...
import math print(math.exp(3)) #Esta funcion es mucho mas precisa print(math.e**3) #Que invocar la variable e y exponer print(math.pow(math.e,3)) #Que invocar la variable e y exponer print(math.log(12)) #Si no le especificas toma logaritmo base e print(math.log(12,2)) print(math.log2(32)) print(math.log10(...
#!/usr/bin/env python # coding: utf-8 # In[1]: x = [1,2,3,4,5,6,7,8,9,10] print(1 in set(x), 15 in set(x),20 in set(x)) # In[2]: numbers = [1,2,5,6,12,15,20] num_set = set(numbers) print(num_set) # In[3]: my_colors = {"red","yellow","orange","green","blue"} print("yellow" in my_colors) # In[4]: print(my_...
#!/usr/bin/env python # coding: utf-8 # In[ ]: user_name_and_car_color = {'David':'red','John':'green','Sara':'yellow'} # In[ ]: user_name_and_car_color['Kate'] = 'black' print(user_name_and_car_color) # In[ ]: #In order to remove the item with key = “Kate” and print dictionary: del user_name_and_car_color[...
from enum import Enum def convert_to_enum(item, enum, prefix='', to_upper=False): if isinstance(item, Enum): return item elif isinstance(item, (int, float)): try: return enum(item) except ValueError: raise ValueError('Cannon convert int/float to enum') elif ...
# Import Mods import os import csv #set path for file csvpath = os.path.join("Resources" , "PyBank_budget_data.csv") # Open the CSV file with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # ignore first row - header csvheader = next(csvfile) # print(f"header:{header}") ...
a = list('hello') print(f'Made list from string hello, {a}') a.append(100) print(f'Can append integer (100) to list of strings, {a}') a.extend((1, 2, 3)) print(f'Can be extended using tuples, {a}') a.extend('...') print(f'Extended by a string (...), {a}')
"""Provides corresponding single or plural values """ plurals = { 'Opportunities':'Opportunity', 'CPQ Quotes':'CPQ Quote' } def get_single_or_plural(name): """Return corresponding to ``name`` single or plural value form global ``plurals`` dictionary """ print(name) for k, v in pl...
import csv import glob import os from pathlib import Path #get name of csv file in same path as script targetfile = os.path.dirname(os.path.abspath(__file__))+"\*.csv" filename = glob.glob(targetfile)[0] fields = [] rows = [] results = [] nopattern = [] #read csv file with open (filename, 'r') as csvfile: csvrea...
# Алгоритм вычисления значения функции F(n), где n – натуральное число, задан следующими соотношениями: # F(n) = n + 15, при n ≤ 5 # F(n) = F(n//2) + n*n*n - 1, при чётных n > 5 # F(n) = F(n-1) + 2*n*n + 1, при нечётных n > 5 # Здесь // обозначает деление нацело. Определите количество натуральных значений n из отрезка ...
''' Argument: Argument is input that you feed to the program or command to respond. Parsing: When you hit ls -l the OS parses it in a certain way under the hood. Reference Link: https://www.datacamp.com/community/tutorials/argument-parsing-in-python ''' # arg_demo.py import argparse def get_args(): """""" p...
## APPROACH : LINKED LISTS ## ## LOGIC : GREEDY ## class ListNode: def __init__(self, x): self.val = x self.next = None self.prev = None class BrowserHistory: def __init__(self, homepage: str): self.root = ListNode(homepage) def visit(self, url: str) -> None: nod...
''' You are given a string that represents time in the format hh:mm. Some of the digits are blank (represented by ?). Fill in ? such that the time represented by this string is the maximum possible. Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid. Example1: Input: "?4:5?" Out...
''' Given an Array A, find the minimum amplitude you can get after changing up to 3 elements. Amplitude is the range of the array (basically difference between largest and smallest element). Example1: Input: [-1, 3, -1, 8, 5 4] Output: 2 Explanation: we can change -1, -1, 8 to 3, 4 or 5 Example2: Input: [10, 10, 3, 4,...
''' Method: Recursive BFS TC: O(N) SC: O(N) ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: ...
''' ChainMap: A ChainMap is a class that provides the ability to link multiple mappings together such that they end up being a single unit. ''' import argparse import os from collections import ChainMap def main(): app_defaults = {'username':'admin', 'password':'admin'} parser = argparse.ArgumentParser() ...
''' collections: Container datatypes namedtuple():factory function for creating tuple subclasses with named fields deque: list-like container with fast appends and pops on either end ChainMap: dict-like class for creating a single view of multiple mappings Counter: dict subclass for counting hashable ob...
''' Time complexity # Since, at the most, all the projects will be pushed to both the heaps once, the time complexity of our algorithm is O(NlogN+KlogN), where ‘N’ is the total number of projects and ‘K’ is the number of projects we are selecting. Space complexity # The space complexity will be O(N) because we will be...
''' A struct is basically a complex data type that groups a list of variables under one name. namedtuple which you can use to replace Python’s tuple. ''' from collections import namedtuple Parts = namedtuple('Parts', 'id_num desc cost amount') auto_parts = Parts(id_num='1234', desc='Ford Engine', cost=1...
<<<<<<< HEAD # from collections import defaultdict # import math # def digitAnagrams(a): # count = 0 # dict = defaultdict(list) # for i in range(len(a)): # s="".join(sorted(str(a[i]))) # dict[s].append(a[i]) # # for k in dict: # n = len(dict[k]) # if n>= 2: # ...
''' Question: Given a list of video clips with start and end positions, write a program to find out the missing video segments in a given interval Each video clip comes with two elements start and end which is an integer that indeces into position of clip. Clips are not ordered.They can overlap. example of input: [s...
''' employee_info { "id": "10" "first_name":"Marie_inn" "last_name":"" "email":"" "gender":"" "age":"" "salary":"" "job_title":""} ''' import pandas as pd from csv import DictReader employee_info = [] with open("employee.csv", newline="") as f: reader = DictReader() for row in re...
"""Question1: Minimum Path in Unix""" class Solution: def simplifyPath(self, path: str) -> str: if not str: return str s = [] for i in path.split('/'): if i == '.' or not i: continue elif i == '..': if s: ...
''' Method: Brute Force Time Complexity: O(n^3) Space Complexity: O(min(n,m)) ''' class Solution: def allUnique(self, s, start, end): set_list = {} set_list = defaultdict(lambda: 0, set_list) for i in range(start, end): ch = s[i] set_list[ch] += 1 if set...
#!/usr/bin/env python class NullDecl (object): def __init__ (self, func): print self.__class__.__name__, "__init__" self.func = func ##for n in set(dir(func)) - set(dir(self)): ## setattr(self, n, getattr(func, n)) def __call__ (self, * args): print self.__class__.__...
import pandas as pd import matplotlib.pyplot as plt import streamlit as st from sklearn.model_selection import train_test_split from sklearn.svm import SVC # Loading the dataset. df=pd.read_csv("iris-species.csv") # Adding a column in the Iris DataFrame to resemble the non-numeric 'Species' column as numeric usi...
class Stack: """ Stack: Class implementation """ def __init__(stack): """ Initializes new stack """ stack.elements = [] def push(stack, elem): """ Pushes 'elem' to stack 'stack' """ stack.elements.append(elem) def pop(stack): """ Removes head of stack 'stack'...