text
stringlengths
37
1.41M
class Solution: def rotate(self, nums, k): copy_nums = nums.copy() for i in range(len(nums)): nums[(i + k) % len(nums)] = copy_nums[i] class Solution: def rotate(self, nums, k): n = len(nums) k %= n # reverse all numbers for i in range(n // 2): ...
# Approach 1 using sorting # Time-complexity: O(N log N) class Solution: def carPooling(self, trips, capacity): timestamp = [] for trip in trips: timestamp.append([trip[1], -trip[0]]) timestamp.append([trip[2], trip[0]]) timestamp.sort(key=lambda x: (x[0], -x[1])) ...
# 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: first = TreeNode() second = TreeNode() prev = TreeNode(-(2**31)) def recoverTree(self, root: TreeNode) ...
from typing import List # 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: sorted_no...
# Brute-Force: O(N ^ 3) where N - length of s class Solution: def longestNiceSubstring(self, s: str) -> str: n = len(s) max_length = 0 ans = "" for i in range(n - 1): for j in range(i + 1, n): good = True substring = s[i:j + 1] ...
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: largest_sum = -float("inf") curr_sum = 0 for num in nums: curr_sum += num largest_sum = max(largest_sum, curr_sum) curr_sum = max(0, curr_sum) return largest_s...
from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: n = len(board) m = len(board[0]) rows, cols, squares = {}, {}, {} for i in range(9): rows[i] = set() cols[i] = set() for i in range(3): for j...
# Recursive class Solution: def postorderTraversal(self, root): ans = [] self.helper(root, ans) return ans def helper(self, root, ans): if root: self.helper(root.left, ans) self.helper(root.right, ans) ans.append(root.val) # Iterative 1 # T...
# Recursive class Solution: def inorderTraversal(self, root): ans = [] self.solve(root, ans) return ans def solve(self, root, ans): if root: self.solve(root.left, ans) ans.append(root.val) self.solve(root.right, ans) return ans # Ite...
from typing import List class Solution: def findDuplicate(self, paths: List[str]) -> List[List[str]]: duplicates = {} for path in paths: directory, *files = path.split(" ") for file in files: idx = file.index('(') content = file[idx + 1: -1] ...
# 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 from collections import deque class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head): if not head: return if head.next: h = head.next else: return head ...
# 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 insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val)...
def hIndex(citations): if len(citations) == 0 or (len(citations) == 1 and citations[0] == 0): return 0 l = 0 r = len(citations) - 1 ans = 0 while l <= r: mid = l + (r - l) // 2 if citations[mid] == len(citations) - mid: return citations[mid] elif citations...
from typing import List class Solution: def pivotIndex(self, nums: List[int]) -> int: nums_sum = sum(nums) n = len(nums) left_sum, right_sum = 0, nums_sum for i in range(n): right_sum -= nums[i] if left_sum == right_sum: return i ...
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for row in matrix: start = 0 end = n - 1 while start < end: ...
def validIPAddress(ip): number = 0 word = 0 ok = 1 zero = 0 if ip.count(':') == 7 and len(ip) <= 39: for ch in ip: if ('a' <= ch <= 'f') or ('A' <= ch <= 'F') or ch.isdecimal(): word += 1 elif ch == ':': if word > 4 or word == 0: ...
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() merged_start, merged_end = intervals[0] merged_intervals = [] for start, end in intervals: if start <= merged_end: merged_end = max(m...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: add = 0 dummy = l3 = ListNode(0) while l1 and l2: sum_...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def partition(self, head: ListNode, x: int) -> ListNode: first_greater = prev = None curr = head while curr: changed_cu...
# Approach 1 using hashing # Time-complexity: O(N) class Solution: def findJudge(self, N, trust): people = [0] * N for pair in trust: people[pair[1]-1] += 1 trust_judge = max(people) if trust_judge == N - 1: judge = people.index(trust_judge) for pa...
def rangeBitwiseAnd(x, y): while x < y: y -= (y & -y) return y print(rangeBitwiseAnd(12, 15))
def trace(matrix): r = 0 trace = 0 index = 0 for row in matrix: if len(row) != len(set(row)): r += 1 trace += row[index] index += 1 return [r, trace] t = int(input()) for i in range(1, t + 1): n = int(input()) matrix = [] matrix_reversed = [] for ...
from collections import deque from typing import List class Solution: def generateParenthesis(self, n: int) -> List[str]: dq = deque() dq.append(["(", 1, 0]) ans = [] while dq: combination, left, right = dq.popleft() if left == n and right == n: ...
from typing import Optional # 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 rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: s...
# Approach 1 (BRUTE-FORCE) # TC: O(2^N) class Solution: def fib(self, n: int) -> int: if n < 2: return n return self.fib(n-1)+self.fib(n-2) # Approach 2 (MEMOIZATION) # TC: O(N) class Solution: def fib(self, n: int) -> int: cache = {0: 0, 1: 1} def recur_fib(n): ...
from math import sqrt t = int(input()) for test in range(1, t + 1): z = int(input()) target = int(sqrt(z)) first = second = third = -1 for i in range(target, target - 565, -1): prime = True for d in range(2, int(sqrt(i) + 1)): if i % d == 0: prime = False ...
#!/usr/bin/env python3 # Created by Marlon Poddalgoda # Created on December 2020 # This program calculates the square of all positive integers # between 0 and a user input def main(): # this function will calculate the square of all positive # integers between 0 and a user input print("This p...
'''The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True. The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of ...
_MAX_SPLITS_ALLOWED = 1 class Hand(object): """A representation of a blackjack hand.""" def __init__(self, split=False, split_card=None, split_count=0): """Deals a new blackjack hand and stores it as a tuple. Args: shoe: A blackjack shoe interface. split: A boolean in...
import bankroll class PlayerInput(object): """Container for player input functions.""" def __init__(self, time): """Creates a new player input container. Args: time: A time interface. """ self._time = time def welcome_and_get_buyin(self, input_func=raw_input)...
def find_swap(next, sorted_tail): """ return negative int index in sorted tail of thing to swap """ if len(sorted_tail) == 1: return -1 i = -2 while abs(i) <= len(sorted_tail): if next > sorted_tail[i]: return i+1 i -= 1 def do_swap(head, sorted_tail, swap_...
def is_even(num): if num % 2 == 0: return True else: return False def only_evens(lst): new_lst = [] for n in lst: if is_even(n): new_lst.append(n) return new_lst print(only_evens([11, 20, 42, 97, 23, 10]))
# --------------------------------------------------------------------------------------------- # Name: main.py # Purpose: Uses the Nearest Neighbour class and read_write_TSP to find the tour and plots # the tour using GraphWorld # Programmers: Ishwar Agarwal(Driver) & Xhafer Rama(Navigator) # Ackno...
class Entries: """Class for creating an entries dictonary""" # Class initializer. It has 5 custom parameters, with the # special `self` parameter that every method on a class # needs as the first parameter. def __init__(self, id, time, concept, entry, mood_id): self.id = id self.tim...
''' Title: 819. Most Common Word (Easy) https://leetcode.com/problems/most-common-word/ Runtime: 52 ms, faster than 8.96% of Python online submissions for Most Common Word. Memory Usage: 11.9 MB, less than 5.05% of Python online submissions for Most Common Word. Description: Given a paragraph and a list of ba...
''' Title: 496. Next Greater Element I (Easy) https://leetcode.com/problems/next-greater-element-i/ Runtime: 80 ms, faster than 21.69% of Python online submissions for Next Greater Element I. Memory Usage: 11.7 MB, less than 5.94% of Python online submissions for Next Greater Element I. Description: You are g...
''' Title: 292. Nim Game (Easy) https://leetcode.com/problems/nim-game/ Runtime: 20 ms, faster than 69.91% of Python online submissions for Nim Game. Memory Usage: 11.7 MB, less than 5.36% of Python online submissions for Nim Game. Description: You are playing the following Nim Game with your friend: There is...
''' Title: 35. Search Insert Position (Easy) https://leetcode.com/problems/search-insert-position/ Runtime: 36 ms, faster than 93.09% of Python3 online submissions for Search Insert Position. Memory Usage: 13.6 MB, less than 5.11% of Python3 online submissions for Search Insert Position. Description: Given...
''' Title: 905. Sort Array By Parity (Easy) https://leetcode.com/problems/sort-array-by-parity/ Runtime: 68 ms, faster than 49.45% of Python online submissions for Sort Array By Parity. Memory Usage: 12.5 MB, less than 5.22% of Python online submissions for Sort Array By Parity. Description: Given an array A ...
''' Title: 104. Maximum Depth of Binary Tree (Easy) https://leetcode.com/problems/maximum-depth-of-binary-tree/ Runtime: 48 ms, faster than 87.33% of Python3 online submissions for Maximum Depth of Binary Tree. Memory Usage: 14.5 MB, less than 82.20% of Python3 online submissions for Maximum Depth of Binary Tree. Des...
''' Title: 7. Reverse Integer (Easy) https://leetcode.com/problems/reverse-integer/ Runtime: 40 ms, faster than 99.91% of Python3 online submissions for Reverse Integer. Memory Usage: 13.1 MB, less than 5.71% of Python3 online submissions for Reverse Integer. Description: Given a 32-bit signed integer, reve...
''' Title: 217. Contains Duplicate (Easy) https://leetcode.com/problems/contains-duplicate/ Runtime: 108 ms, faster than 42.07% of Python online submissions for Contains Duplicate. Memory Usage: 17.1 MB, less than 5.24% of Python online submissions for Contains Duplicate. Description: Given an array of integers, ...
''' Title: 283. Move Zeroes (Easy) https://leetcode.com/problems/move-zeroes/ Runtime: 40 ms, faster than 56.79% of Python online submissions for Move Zeroes. Memory Usage: 12.8 MB, less than 5.06% of Python online submissions for Move Zeroes. Description: Given an array nums, write a function to move all 0's...
''' Title: 671. Second Minimum Node In a Binary Tree (Easy) https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ Runtime: 20 ms, faster than 74.81% of Python online submissions for Second Minimum Node In a Binary Tree. Memory Usage: 11.5 MB, less than 6.06% of Python online submissions for Second Minimu...
''' Title: 509. Fibonacci Number (Easy) https://leetcode.com/problems/fibonacci-number/ Runtime: 20 ms, faster than 78.99% of Python online submissions for Fibonacci Number. Memory Usage: 11.8 MB, less than 5.25% of Python online submissions for Fibonacci Number. Description: The Fibonacci numbers, commonly d...
''' Title: 637. Average of Levels in Binary Tree (Easy) https://leetcode.com/problems/average-of-levels-in-binary-tree/ Runtime: 60 ms, faster than 21.54% of Python online submissions for Average of Levels in Binary Tree. Memory Usage: 16.5 MB, less than 5.81% of Python online submissions for Average of Levels in Bina...
# a부터 b까지 정수의 합을 구하기(for문)위해 값 정렬 # print('a부터 b까지 정수의 합을 구합니다.') # a = int(input('정수 a를 입력하세요.: ')) # b = int(input('정수 b를 입력하세요.: ')) # if a > b: # a, b = b, a # sum = 0 # for i in range(a, b + 1): # sum += i # print(f'{a}부터 {b}까지 정수의 합은 {sum}입니다.') # +와 -를 번갈아가며 출력하기(내 코드) # print('+와 -를 번갈아 출력합니다.') #...
def selection_sort(arr): smallest = arr[0] smallest_pos = 0 for i in range(len(arr)): for j in range(i, len(arr)): if arr[j] < smallest: smallest = arr[j] smallest_pos = j arr[i], arr[smallest_pos] = arr[smallest_pos], arr[i] smallest = arr[i+1] smallest_pos = i + 1 return ...
# from random import randrange # class Pet(): # sounds="Meow" # def __init__(self, name="kitty"): # self.name=name # self.hunger=randrange(10) # self.boredom=randrange(10) # self.sounds=self.sounds[] # def clock_tick(self): # self.boredom+=1 # self.hunger+=1 # def mood(self): # if ...
import pyglet class Tag(object): def __init__(self, text, font, color=(1,1,1,1)): self.text=pyglet.font.Text(font, text, color=color, halign="left", valign="bottom") @property def left(self): return self.text.x @property def right(self): return self.text.x+...
# coding: utf-8 def find_min_index(number_list): min_index = 0 min_value = number_list[min_index] for i in range(1, len(number_list)): if(number_list[i] < min_value): min_index = i min_value = number_list[min_index] return min_index question = [5, 3, 2, 8, 9, 0, 4, 1, 6...
import os.path import fileinput import sys print(""" Divide Large CSV File in Python - Pass # Of Rows per file - Pass Main File Name - Ctr+C to interrupt at anytime """) filesize = int(input("Enter # of Rows for each file (e.g. 150000):")) if filesize > 150000 or filesize == 0 or filesize < 0: sys.exit(f"\nError:...
def one (name): return "Menin atym "+ name def two (name): return "my name is " + name def caller (assign): a= "Mirlan" b= "Nurken" c= "Suiun" d = "Ainash" return assign( a) print ( caller(two) )
from function_save import save def keluar(user,gadget,consumable,consumable_history,gadget_borrow_history,gadget_return_history): #exit() command. Menggunakan fungsi save(). print("Apakah Anda mau melakukan penyimpanan pada file yang sudah diubah? (y/n): ",end="") choice=str(input()) if choice=="y" ...
a = int(input("Students in Class1:")) b = int(input("Students in Class2:")) c = int(input("Students in Class3:")) # Desks = x1,x2,x3 x1 = a / 2 if x1 % 2 == 0: print(x1) else: print(round(x1)) x2 = b / 2 if x2 % 2 == 0: print(x2) else: print(round(x2)) x3 = c / 2 if x3 % 2 == 0: print(x3) else...
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: MSJ # date: 2021/3/11 # desc:计算字符串或列表中每个字符出现的次数,并打印出现次数最多的字符 def calc_max_string(str): # 将字符串转化成列表 str_list = list(str) # 定义一个空字典,用来存储 字符: 出现次数 str_dict = {} # 遍历列表(字符串) for x in str_list: # 如果该字符没有在字典中出现过,则赋值为1,否则在原来基础上+1 if...
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: MSJ # date: 2021/4/14 # desc: # # 影响因素: # 1. # 2. # 检查点: # 1. # 测试用例: # 0. class Solution(object): def minArray(self, s): """ :type numbers: List[int] :rtype: int """ #numbers.sort() ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: MSJ # date: 2021/3/11 # desc:给定一个字符串,判断字符串中的括号是否成对 def is_valid(str): # 新建括号匹配字典 brackets = { ')': '(', ']': '[', '}': '{' } # 左/右括号 left_brackets = brackets.values() right_brackets = brackets.keys() # 空数组(模拟空栈) stack = [] # 遍历字符串 ...
def is_unique_string(str): dict = {} for s in str: if s not in dict.keys(): dict[s] = True else: return False return True print(is_unique_string("say")) def sort_string(s): return ''.join(sorted(s)) def check_permutation(x, y): if len(x) != len(y): ...
class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ map = {} res = [] for i in range(len(strs)): if map.get(i, False): continue temp = [strs[i]] map[i] = True ...
def lengthOfLongestSubstring(s): has = "" result = 0 temp = 0 i = 0 j = 1 while i < len(s): if s[i] in has: has = s[j:i] temp = len(has) j += 1 else: temp += 1 has += s[i] if temp > result: re...
# A version of linear regression using tensorflow. import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns # We emphasize that this is the stupidest possible neural network-- 1 input, 1 output, with 2 weights. # I mean, this is linear regression after all... # Fi...
''' 6. Implement a function to determine if a string has all unique characters. What if you cannot use additional structures? ''' # HAHAHA! This one was too easy. def hasAllUniqueCharacters(s): return ''.join(sorted(set(s))) == ''.join(sorted(s)) print(hasAllUniqueCharacters('Computer Programmer Numerical Con...
import pandas as pd from sklearn.neighbors import KNeighborsClassifier def locally_weighted(x, y): neigh = KNeighborsClassifier(n_neighbors=3) neigh.fit(x, y) print("Enter X value : ") x_i = int(input()) print("Enter Y value : ") y_i = int(input()) predict = [x_i, y_i] if neigh.pre...
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split df = pd.read_csv('salaries.csv') company_le = LabelEncoder() job_le = LabelEncoder() degree_le = LabelEncoder() df['company'] = company_le.fit_transf...
# Example 1, do not modify! import pandas as pd import matplotlib.pyplot as plt netflix=pd.read_csv("netflix_titles.csv") netflix_by_year=netflix.sort_values("release_year") print(netflix_by_year.isnull().sum()) M_night=netflix[netflix["director"]== "M. Night Shyamalan"] print(M_night) movies=netflix[netflix["type"...
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? # 遍历全部可能,把有重复的剃掉 total = 0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if (i!=j)and(j!=k)and(k!=i): print(i,j,k) total +=1 print(total) # 简便方法 用itertools中的permutations即可 import itertools sum_3 = 0 a ...
import argparse import sys import itertools import pprint def read_points(filename): """ The read_points method reads opens the file with the points and returns them in a list filled with lists of couples with coordinates. input: -filename: string name of the file with the points output: -poi...
class Inventory(object): """ Representation of a inventory """ def __init__(self): """ Initialize inventory """ self.inventory = {} def add(self, item): """ Adds an item to the inventory, and checks that we do not ecounter any KeyErrors ...
"""Stores details of movies and displays them on a website""" import fresh_tomatoes import media def main(): """Creates six Movie objects, initialises the objects alongside the title, storyline, poster image, video trailer """ shock_treatment = media.Movie("Shock Treatment", ...
# ------------------------------------------------------------------ # QuadrupleList object # # Manages the quadruple list. # ------------------------------------------------------------------ class QuadrupleList: def __init__(self): self.list = [] def add(self, quadruple): self.list.append(q...
# ------------------------------------------------------------------ # Stack object # ------------------------------------------------------------------ class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.app...
def area(base, height): '''Compute he are of a triangle with the given base and height''' '''Raises value error if base or height or both are negative''' if base < 0 or height < 0: raise ValueError('Base and height must be positive. \ Was given base: {}, height {}'.format(base, height)) area = base * heigh...
def get_count(word): lower = word.lower() final = "" vowel_counts = {} for vowel in "aeiou": count = lower.count(vowel) vowel_counts[vowel]=count for key in vowel_counts: if vowel_counts[key]: result = ''.join(str(vowel_counts[key])+str(key)) final = f...
# read and prepare n, m, and p n = int(input("Number of jobs: ")) m = int(input("Number of machines: ")) pStr = input("Processing times ") p = pStr.split(" ") for i in range(n): p[i] = int(p[i]) # machine loads and job assignment loads = [0]*m assignment = [0]*n # in iteration j, assign job j to the le...
#https://www.w3resource.com/python-exercises/python-basic-exercises.php #RM 03/22/2018 2022 create a basics.py non Python os, file programs. #1. Write a Python program to print the following string in a specific format: Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so hi...
help() #help() #1. run help(). See help> 2. Type a python command; e.g. print. Information displayed. Press page up and page down. 3. Type q to quit. 4. Type ctrl+c to quit. Perhaps create a help.py file to run help() only? # Welcome to Python 3.5's help utility! # If this is your first time using Python, ...
import os import re import sys import pprint search = raw_input("Enter FileName to search: ") List = [] fcount=0 var = re.compile(search,re.IGNORECASE) rootdir = raw_input("Enter where to search: (To search in present directory leave as it is)") if(rootdir==""): rootdir='.' for root, dirs, files in os.walk(rootdir, to...
def twoNumberSum(array, targetSum): for i in range(len(array) - 1): firstNumber = array[i] for j in range(i + 1,len(array)): secondNumber = array[j] if firstNumber + secondNumber == targetSum: return [firstNumber,secondNumber] return []
var1 = 1+1*2 var2 = (1+1)*2 print(str(var1) + ' ' + str(var2)) #Isso ocorre porque o parenteses muda a ordem que as contas são realizadas, iniciando para o grau mais adentro para mais para fora, # enquanto a outra segue a ordem de preferencia matemática padrão
def work(a,b,c): su = a + b + c pr = a * b * c return su, pr a = int(input("Введите число a: ")) b = int(input("Введите число b: ")) c = int(input("Введите число c: ")) su, pr = work(a,b,c) print("Сумма введенных чисел: ", su) print("Произведение введеных чисел: ", pr)
class demoClass: """demo class""" name = "lance" age = 0 def __init__(self, name): self.name = name age = 10 def demo(self): print "demo" + self.name + str(self.age)
class Time(object): """this will tell the time""" t=Time() t.hour=10 t.minutes=20 t.seconds=30 def print_time(t): print("%.2d:%.2d:%.2d" % (t.hour,t.minutes,t.seconds)) print_time(t)
import math class Point(object): """this is class for point""" point_a = Point() point_b = Point() point_a.x, point_a.y = 2.0, 2.0 point_b.x, point_b.y = 5.0, 3.0 def distance(point_a, point_b): axisx = point_b.x - point_a.x axisy = point_b.y - point_a.y return math.sqrt(axisx ** 2 + axisy ** 2) pr...
# -*- coding: utf-8 -*- # IF/ELSE: TREE WITH TRUE/FALSE BRANCHES age = 20 if age >= 18: print('Your age is {0}'.format(age)) print('You are an adult!') age = 3 if age >= 18: print('Your age is {0}.'.format(age)) print('You are an adult.') elif age >= 10: print('Your age is {0}.'.format(age)) p...
### https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import cmath import time # From stokes parameters, looking to create the ellipse and then animate it on a raspPi #to then be used for the GUI once we sta...
def setbits(n): count=0 while(n>0): n=n&(n-1) count+=1 return count for _ in range(int(input())): n = int(input()) res=0 for i in range(n+1): res+=setbits(i) print(res)
# -*- coding: utf-8 -*- """ Project Euler - Problem 44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not penta...
# -*- coding: utf-8 -*- ''' Project Euler - Problem 25 Calculate first number in Fibonacci sequence to contain 1000 digits F(n) = F(n-1) + F(n-2) F(0) = 0, F(1) = 1, F(2) = 1 ''' # Imports import time # To calculate prorgram run time start = time.time() # Initialise variables num_digits = 1000 a = 1 b = 0 n = 1 # L...
""" File Name: growth.py Author's Name: Tejaswini Jagtap """ from utils import * def sorted_growth_data(data,year1,year2): """ sorts from higher to lower the countries according to the growth in life expectancies from year1 to year2 :param data: data dictionary containing country name as key :param ye...
class Node: def __init__(self, item, left=None, right=None): """(Node, object, Node, Node) -> NoneType""" self.item = item self.left = left self.right = right def depth(self): left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if...
# Python code to listen and send the mail to receiver import speech_recognition as sr import pyttsx3 from pyttsx3 import voice import time import smtplib import getpass as gp # Initialize the recognizer r = sr.Recognizer() # Function to convert text to speech def SpeakText(command): # Initialize the engin...
#! usr/bin/env python3 import numpy as np import sys #define a function that returns a value def expo(x): return np.exp(x)#return the np e^x function #define a subroutine that does not return a value def show_expo(n): for i in range(n): print(expo(float(i)))#call the expo function ensures that it is a float. #defin...
#Number of queens print ("Enter the number of queens") N = int(input()) #chesssol #NxN matrix with all elements 0 sol = [[0 for i in range(N)]for j in range(N)] def is_attack(i, j): #checking if there is a queen in row or column for k in range(0,N): if sol[i][k]==1 or sol[k][j]==1: return ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor data = pd.read_csv("positions.csv") # print(data.columns) levels = data.iloc[:,1].values.reshape(-1,1) salaries = data.iloc[:,2].values.reshape(-1,1) regression = DecisionTreeRegressor() ...
# Displays the game using turtle import turtle class Display: def __init__(self): # Turtle setup # Screen self.wn = turtle.Screen() self.wn.title("Snake") self.wn.bgcolor("black") self.wn.setup(width=800, height=400) self.wn.tracer(0) # Snake head self.head = turtle.Turtle() self.head.turtlesize(0...
import numpy as np import queue import math import time import matplotlib.pyplot as plt import matplotlib as mpl # 新的矩阵可以变成1,也可以变成0 # 写一下不同函数,不同目标的接口 # 把图象写得好看一点, class Maze: def __init__(self,size,prob): """ Create a new maze param size(int): the size of maze par...
# dogru isim ve telefon numaralarini alip ekrana ayzdiran dictionary dic = { }#bos bir dictionary ve liste olusturdum. liste=[] while True : while True: # while True dongusu ile isimler alip eger isimler sadece hadrflerden olusuyorsa kabul eden aksi halde yeni isim isteyen dongu name = input( "Enter n...
#Note that the script below is the module with the functions #That will be used in the interface for the bulls & cows game from random import randint #The command above will import the randint built in Python function #It will be needed in the function defined next def generateSecretNumber (): r = randint...