text
stringlengths
37
1.41M
import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':1...
def test(): print "bloodCalc OK!" def main(x): print "Valid signs are Aries, Taurus, Gemini, Cancer, Leo, Virgo,\n Libra, Scorpio, Sagittarius, Capricorn, Aquarius,and Pisces." sun = raw_input("Enter Sun sign: ") moon = raw_input("Enter Moon sign:") if x == False: print "Your blood color is...
sentence = input("Enter a sentence : ") def reverse(): p = sentence[::-1] # Reversing the given sentence and storing it in 'p' q = p.split() r = [] x = len(q) - 1 # Splitted sentence obtained then reduced it's length while x >= 0: r.append(q[x]) # putting x words into r ...
''' PyBank challenge Your task is to create a Python script that analyzes the records to calculate each of the following: -The total number of months included in the dataset -The net total amount of "Profit/Losses" over the entire period -The average of the changes in "Profit/Losses" over the entire period -The great...
def count_positives_sum_negatives(arr): if arr == []: return [] first = 0 second = 0 for i in arr: if i > 0: first += 1 if i < 0: second += i return [first, second]
import re def is_valid(email): pattern = re.compile(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\.-]+\.[a-zA-Z]*$") if re.match(pattern,email): return "Email is valid" else: raise ValueError("Email is not valid") def valid_email(email): try: return is_valid(email) except ValueError as...
def compare(a, b): """This function returns the largest number of two numbers""" if a > b: return a return b value_1 = 45 value_2 = 20 print(compare(value_1, value_2))
import re m = input("Please enter your password: ") x = True while x: if (len(m)<6 or len(m)>16): break elif not re.search("[a-z]",m): break elif not re.search("[A-Z]",m): break elif not re.search("[0-9]",m): break elif not re.search("[$#@]",m): break els...
class Vertex: def __init__(self, num): self.empty = True self.num = 0 self.connected_edge = [] self.connected_distance = [] self.num = num self.reached = False self.square = 0 self.x = 0 self.y = 0 self.back_pointer = None sel...
""" Запишите букву 'A' (латинскую, заглавную) 100 раз подряд. Сдайте на проверку программу, которая выводит эту строчку (только буквы, без кавычек или пробелов). """ a = 'A' print(a * 100)
##### # Python Examples: # linked_list.py # # Linked list implementation in Python. # # Xavier Torrent Gorjon ##### class Element(object): """Class that represents nodes on the linked list.""" def __init__(self, data): """Class constructor. Sets the data variable.""" self.__data = data ...
# Fibonacci starting at 0 def fib_at_zero(n): if n < 2: return n return fib_at_zero(n-1) + fib_at_zero(n-2) # Fibonacci starting at 1 def fib_at_one(n): if n == 1: return 0 elif n == 2: return 1 return fib_at_one(n-1) + fib_at_one(n-2) print(fib_at_zero(0)) print(fib_at_ze...
import sys def collatz(number): if (number%2==0): print(str(number//2)) return number//2 elif (number%2==1): print(str(3*number+1)) return 3*number+1 while True: try: num=int(input('imput a number pleease:')) break except ValueError: print('u shoul...
from typing import List from typing import Dict """expliquez pourquoi un des Modifier marche et un ne marche pas""" def step1(): class Modifier1: def __init__(self, liste: List, otherListe: List): self.liste = liste self.otherListe = otherListe def changeArray(self): ...
import random from time import sleep snakes = {32:10, 36:6, 48:26, 62:18, 88:24, 95:56, 97:78} ladders = {1:38, 4:14, 8:30, 21:42, 28:76, 50:67, 71:92, 80:99} def roll_dice(): return random.randint(1,6) win = 100 player = 0 counter = 0 while True: steps = roll_dice() print("You Got:", steps) if player + steps =...
import csv import numpy as np import pandas as pd ##########################old logic to be reomoved ################### #file_name = sys.argv[1] #fp = open(file_name) #contents = fp.read() #f = open('data.csv') #f is instance of file being opened #csv_f = csv.reader(f) # we are trying to loop over every row #...
#Uses python3 #Pierce Lovesee #July 2nd, 2021 #Good job! (Max time used: 0.27/10.00, max memory used: 39157760/536870912.) import sys def toposort(adj, visitedNodes): postOrdering = [] #keep track of the post ordering of the graph def explore(v): if visitedNodes[v]: #if the vertex has been visted, ...
#python3 #Pierce Lovesee #June 22nd, 2021 import sys def number_of_components(adj, nodeTruth): """ Input: Takes a graph adjacency list as input with a truth table to track what nodes have been visited. Output: Returns the number of seperetly connected components in the graph (i.e. if the graph is...
#Uses python3 #Pierce Lovesee #July 3rd, 2021 #Good job! (Max time used: 0.37/10.00, max memory used: 46055424/536870912.) import sys import queue def distance(adj, s, t, dist, prev): """ Input: adjacency list, start node int, target node int, distance list, and prev node list. Output: (int) the shor...
#python3 # Pierce Lovesee # Janurary 2nd, 2021 import sys class StackWithMax(): def __init__(self): self.__stack = [] # two stacks need to be maintained; one as stack self.MaxStack = [] # and one to keep track of how many elemts can # be removed and have the current...
class Car: """Классификатор легковых автомобилей""" def __init__(self, brand, year, volume, price, mileage): """"Инициализация атрибутов класса Car""" self.brand = brand # марка авто self.year = year # год выпуска self.volume = volume # объем двигателя self.price = pr...
# a = 10 # while a > 1: # a -= 1 # print(a * '*') # # for i in range(10): # print(i**2) a = int(input()) while a >= 0: print(a) a -= 1
# @Time : 20190704 # @Author : lzh def counting_sort(nums): min_value = min(nums) max_value = max(nums) counting_arr_len = max_value - min_value + 1 counting_arr = [0] * counting_arr_len for num in nums: counting_arr[num-min_value] += 1 sorted_index = 0 for j in range(counting_a...
# @Time : 20190704 # @Author : lzh def heap_sort(nums): global length length = len(nums) build_max_heap(nums) for i in range(len(nums)-1, 0, -1): nums[0], nums[i] = nums[i], nums[0] length -= 1 heapify(nums, 0) return nums def heapify(nums, i): left = 2 * i + 1 ...
#!/usr/bin/python # -*- coding: utf-8 -*- import collections import math import bitarray def solveIt(inputData): # Modify this code to run your optimization algorithm # parse the input lines = inputData.split('\n') firstLine = lines[0].split() items = int(firstLine[0]) capacity = int(firstLi...
# define a function with the name favorite city that will print out # "One of my favorite cities is" + name of that city at least 3 different times! def favorite_city(name): print("One of my favorite cities is", name) favorite_city("Ashburn, Virginia") favorite_city("Overland Park, Kansas") favorite_city("Pla...
from Array import remove_element def test_remove_element(): arr = [1, 1, 3, 2] assert 3 == remove_element.remove_element(arr, 3) assert arr[0:3] == [1, 1, 2] arr = [1, 2, 2, 1, 3, 4, 3, 5] assert 6 == remove_element.remove_element(arr, 3) assert arr[0:6] == [1, 2, 2, 1, 4, 5]
def search_insert_position(arr, value): left = 0 right = len(arr) - 1 if value > arr[right]: return right + 1 if value < arr[left]: return left return _search_binary_search(arr, value, left, right) def _search_binary_search(arr, value, low, high): if high - low <= 0: ...
class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def convert(head: ListNode): if head is None: return None l...
# a palindrome reads the same from left to right # convert into a string # use 2 pointers left, right # false if pointers dont match def is_palindrome(num): if num < 0: return False num_str = str(num) left = 0 right = len(num_str) - 1 while left < right: if num_str[left] != num_str...
def find_element(sorted_arr, el): low = 0 high = len(sorted_arr) - 1 if len(sorted_arr) == 0: return -1 while low >= 0 and high <= len(sorted_arr) and low <= high: mid = low + int((high - low) / 2) if sorted_arr[mid] > el: # search in lower half high = ...
from Number import roman_to_int def test_roman_to_int(): num = 'MCMXCIV' assert 1994 == roman_to_int.convert_roman_to_int(num) num = 'XXVII' assert 27 == roman_to_int.convert_roman_to_int(num) num = 'LVIII' assert 58 == roman_to_int.convert_roman_to_int(num) num = 'MDCCCXC' assert 18...
def string_to_integer(str): str_arr = list(str) right = len(str) - 1 sum = 0 while right > 0: num = convert_string_to_integer(str_arr, right) print(num) sum = sum + num right -= 1 char = convert_string_to_integer(str_arr, 0) if char == '-': sum *= -1 ...
from String import first_occurence_substr def test_find_first_occurrence(): str = 'hello' needle = 'll' assert 2 == first_occurence_substr.find_first_occurrence_substr(str, needle) haystack = "aaaaa" needle = "bba" assert -1 == first_occurence_substr.find_first_occurrence_substr(str, needle) ...
def one_away(str1, str2): # same length or abs(diff(length1, length2)) <= 1 diff = abs(len(str2) - len(str1)) length = len(str1) if len(str1) > len(str2): length = len(str2) if diff > 1: return False odd = False index1 = 0 index2 = 0 for i in range(length): ...
from String import is_unique def test_is_unique(): str = 'excuse moi' assert is_unique.is_unique(str) == False str = 'excus moi' assert is_unique.is_unique(str) == True str = 'e' assert is_unique.is_unique(str) == True str = 'EXCUSe moi' assert is_unique.is_unique(str) == False def...
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def sorted_array_to_bst(arr): return bst(arr, 0, len(arr) - 1) def bst(arr, low, high): if high - low == 1: root = TreeNode(arr[high]) root.left = TreeNode(arr[low]) ...
# evaluate each roman char # add left with right # if left is less, then subtraction def convert_roman_to_int(roman_num): sum = 0 roman_int_dict = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } return convert_seq(sum, 0, 1, r...
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def is_same_tree(root1, root2): if root1 is None and root2 is None: return True if not root1 or not root2 or root1.val != root2.val: return False return is_same_tree(root...
from Tree import delete_node_bst def test_delete_bst(): five = delete_node_bst.TreeNode(5) two = delete_node_bst.TreeNode(2) five.left = two three = delete_node_bst.TreeNode(3) two.right = three four = delete_node_bst.TreeNode(4) two.left = four root = delete_node_bst.delete(five, 5) ...
class telephone_util: def __init__(self): self.keys = { 0: [], 1: [], 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: ['m', 'n', 'o'], 7: ['p', 'r', 's'], 8: ['t', '...
from String import longest_common_prefix_binary_search def test_longest_common_prefix(): input = ['flower', 'flo', 'flow', 'flock'] assert 'flo' == longest_common_prefix_binary_search.longest_common_prefix_binary_search(input) input = ['flower', 'flo', 'flow', 'flock', 'flight'] assert 'fl' == longes...
i = 1 j = 2 while j <= 12: print("\n multiple of ",j,"\n") i=1 while i<=12: print (i," x ",j," = ",i*j) i +=1 j += 1
#Area of a Square """lenght=input("Enter the lenght of the square\n") lenght=int(lenght) area=lenght*lenght print(area)""" #Area of a Triangle """base=input("Enter the base of the triangle") height=input("Enter the height of the triangle") base=int(base) height=int(height) area=(base/2*height) print(area)""" """base...
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' from prime import primes def p7(): return primes(150000)[10000] print p7()
import http.client import json from urllib import parse from urllib import request from uszipcode import SearchEngine KEY="d417eac4aaa24bc082c1581ef13783ea&api" def get_stores_list(): """ Queries Wegman's api for the information on their stores and reads the response :return: list of wegmans stores and t...
d = {'a':3, 'b':6, 'c':2, 'd':32, 'e':21, 'f':2} def replace_dict_value(d, bad_value, good_value): for key,value in d.items(): if value == bad_value: d[key] = good_value return d def main(): print(replace_dict_value(d, 2, 7)) if __name__ == "__main__": main()
num_list = [] while True: num = input(f"Ievadiet skaitli: ") if num == 'q' or num == 'Q': break else: num = float(num) num_list += [num] print(num_list) print(f"Top 3 min numbers are: {sorted(num_list)[:3]}") print(f"Top 3 max numbers are: {sorted(num_list, re...
def number(num): is_number = isinstance(num, int) print(isnumber) # if is_number == False: # print("False") # num = input("Number?") # number(num) # else: # print("Skaitlis " + num + " ir ok.") num = input("Number?") number(num)
class Rotinas(object): @staticmethod def add(a, b): print("add: ", a, "+", b, "=", a + b) return a + b @staticmethod def subtract(a, b): print("subtract: ", a, "-", b, "=", a - b) return a - b @staticmethod def multiply(a, b): print("multiply: ", a, "x...
class Node: #constructor to initalize the node object def __init__(self, data=None, next=None): self.data = data self.next = None class LinkedList: #function to initialize the head def __init__(self): self.head = None #function to reverse the linked list def rev...
# paresoimpares.py print("Calcular si un número es par o impar") print("José Moya -- GDS0151 \n") def main(): numero_1 = int(input("Escriba un número entero: ")) if numero_1 % 2 == 0: print("El número es par.") else: print("El número es impar.") if __name__ == "__main__": ...
import unittest class animal: def __init__(self, vivo): self.vivo = vivo def esta_vivo(self): print("Esta vivo: " + self.vivo) class gato(animal): def correr(self): print("El gato esta corriendo") def dormir(self): print("ZZZZzzzzz ZZZZZZzzzzz") def ronronear(s...
print('''=== AGENDA TELEFONICA ===''') cont = 1 agenda = {} while cont == 1: opcao = int(input("[1] - INSERIR\n[2] - REMOVER\n[3] - PESQUISAR\n[4] - SAIR\nDigite a opção desejada:\n")) if opcao == 1: nome = input("nome:\n") email = input("email:\n") telefone = int(input("telefone:\n")) ...
''' Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple sp...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import neighbors, metrics from sklearn.preprocessing import LabelEncoder # reading dataset df = pd.read_csv('car.data') # extracting columns and attributes x = df[['buying', 'maint', 'safety']].values # extractin...
# B_R_R # M_S_A_W """ It stores and retrieves books from the JSON file. Format of JSON file: [ { "name": 'Clean Code', "author": "Robert", 'read': True } ] """ from typing import List, Dict, Union from .database_connection import DatabaseConnection Book=Dict(str, Union(str, int)) book...
# B_R_R # M_S_A_W """ Coding Problem on Regular expressions: In order to work with regular expressions or we can say regex too, we have to import its module which is called re Specifically we use findall method of regex library findall returns a list containing all matches """ import re email='abdumaliksharipov@...
# B_R_R # M_S_A_W """ It stores and retrieves books from the CSV file. Format of CSV file: name,author,read\n name,author,read\n name,author,read\n name,author,read\n # comma would not be good idea to separate if comma is part of the name of the book """ books_file="books.txt" def create_book_table(): with ope...
""" So this would be program for movie collection, which has several functions such as adding new movies to the existing collection, listing all movies in the collection, finding some specific movie with details, and finally exiting from the programm. """ # Still working on it. Need to fully grasp lambda function in or...
oldlist = [1,2,3,4,2,12,3,14,3,2,12,3,14,3,21,2,2,3,4111,22,3333,4] newlist = [] for i in oldlist: if i not in newlist: newlist.append(i) print newlist
d = {'k1':'v1','k2':'v2','k3':'v3'} l = [] for i in d: l.append(i) print l
while True: year = raw_input('input the year: ') if not year: print 'bye' break elif int(year) % 100 == 0: if int(year) % 400 == 0: print '%s is runnian' % year else: print '%s is not runnian' % year elif int(year) % 4 == 0: print '%s is ru...
mylist = [65555,1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,45,33,45] least = mylist[0] for l in mylist: if l < least: least = l first = second = least for element in mylist: if element >= first: second = first first = element print 'the max num %s,the second num %s' % (...
#!/usr/bin/python ######################### # python script 17 ######################## #defining a class class Class_name(): def function1(self): name = lambda a: a+5 print(name(10)) #creating a object class_object = Class_name() #calling a def in class class_object.function1()
print("what is ur name") nameUser = input() print("How pld r u?") ageUser = input() print("Where r u live?") cityUser = input() print("This is {0}.".format(nameUser)) print("It is {0}.".format(ageUser)) print("(S)He live in {0}.".format(cityUser))
#!/usr/bin/python # # Simple XOR brute-force Key recovery script - given a cipher text, plain text and key length # it searches for proper key that could decrypt cipher into text. # # Mariusz Banach, 2016 # import sys def xorstring(s, k): out = [0 for c in range(len(s))] key = [] if type(k) == type(int): ...
'''Write a recursive function to count the number of times the integer n appears in the input array ex 1. n = 2 [2, 34, 54, 2, 3] should return 2 ex 2. n = 2 [12, 34, 54, 21, 3] ''' def count(arr, n): if len(arr) < 1: return 0 if arr[0] == n: return 1 + count(arr[1:], n) else: ...
import math import mathutils class _Point: def __init__(self, x, y): self.x = x self.y = y def dist(self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 def dx2(self, other): return (self.x - other.x)**2 def dy2(self, other): return (sel...
def main(): emails_dict = {} email_lengths = [] name_lengths = [] new_email = str(input("Email: ")) while new_email != "": name = get_name_from_email(new_email) emails_dict[new_email] = name name_lengths.append(len(name)) email_lengths.append(len(new_email)) ...
import sys sys.stdin = open("input.txt") T = int(input()) for tc in range(1, T+1): string = input() bracket = ['(', ')', '{', '}'] stack = [] # 스트링에서 하나하나꺼내와서 for s in string: # 괄호만 간추린다 if s in bracket: # 스택에 있으면 if stack: # 아스키 코드 표를 보면 ...
# a = [[1, 2, 3], # [4, 5, 6], # [7, 8, 9]] # # for i in range(len(a)): # for j in range(len(a[0])): # if i > j : # a[i][j],a[j][i] = a[j][i],a[i][j] # # print(a) a = [1, 2, 3, 4] for i in range(1<<len(a)): print('******',i,end='\n') for j in range(len(a)): if i & (1...
__author__ = 'xyang' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def loop(self, root): i...
def insertion_sort(arr): """ 算法思想: 每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。 时间复杂度: O(n²) 空间复杂度: O(1) 稳定性: 稳定 :param arr: List[int] :return: arr """ n = len(arr) for i in range(1, n): element = arr[i] pos = i while pos >= 1 and arr[pos - 1] > ...
def fib(N): """ 问题描述:斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。 该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,   F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 给定 N,计算 F(N)。 解决思路: 可使用递归, 但运行时间长。使用下面这种方法可大大减少时间复杂度 :param N: :return: """ a, b = 0, 1 for _ in range(N): a, b =...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def maxDepth1(root): """ 问题描述:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到 最远叶子节点的最长路径上的节点数。 解决思路:借助栈实现DFS 说明: 叶子节点是指没有子节点的节点。 :param root:TreeNode ...
def singleNumber(nums): """ 问题描述:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均 出现两次。找出那个只出现了一次的元素。 说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 解决思路:使用异或运算符,对于^异或运算来说,有以下几个规则 0 ^ N = N N ^ N = 0 N1^N2^N3 = N1^N3^N2=N2^N3^N1=N2^N1^N3 所以,N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N = N :param nums:Lis...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 1 21:07:55 2020 @author: viktor """ def contar_digito (a): """ """ m=0 while a>0: b=a%10 a=a//10 if b==7: m=m+1 return (m) a=int(input("")) m=contar_digito (a) print(m)
# -*- coding: utf-8 -*- """ Created on Tue Nov 10 21:23:10 2020 @author: vikto """ a=int(input()) b=int(input()) count=0 c=1 while count!=b: c=c*a count=count+1 print(c)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 18 17:41:17 2020 @author: viktor """ a=float(input("")) b=float(input("")) c=float(input("")) if a<b<c: print("True") else: print(False)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 18 19:26:53 2020 @author: viktor """ a=int(input("")) if a>100 and a<1000: primero=a%10 a=a-primero a=a/10 segundo=a%10 tercero=(a-segundo)/10 suma=primero+segundo+tercero if (suma%5==0): print("True") else: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 2 18:23:16 2020 @author: viktor """ a=int(input("")) n=a c=0 if n<=0: print("False") else: while (c+2)<n: c=c+2 print(c)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 3 22:57:08 2020 @author: viktor """ n=int(input("")) x=1 c=1 print(1) if n>1: while x<n: b=c+x+1 c=b x=x+1 print(b)
__author__ = 'Michael Isik' from numpy import Infinity class Population: """ Abstract template for a minimal Population. Implement just the methods you need. """ def __init__(self):pass def getIndividuals(self): """ Should return a shallow copy of the individuals container, so that ...
import numpy as np LEFT =1 RIGHT = 2 STRAIGHT = 0 ACCELERATE =3 BRAKE = 4 RIGHT_AND_BRAKE = 5 RIGHT_AND_ACC = 6 LEFT_AND_BRAKE = 7 LEFT_AND_ACC = 8 def one_hot(labels): """ this creates a one hot encoding from a flat vector: i.e. given y = [0,2,1] it creates y_one_hot = [[1,0,0], [0,0,1], [0,1,0]] ...
array = [10, 3, 16, 99, 22, 100, 44, 22, -12, 33, 21] def for_uneven_item(array): if len(array) == 0: return None, 'Short array. Try again' for index, item in enumerate(array): if index % 2 != 0: print(item, end = ' ') return True, None list_of_array, error = for_even_item(a...
array = [10, 3, 16, 99, 22, 100, 44, 22, -12, 33, 21] def array_with_even_items(array): if len(array) == 0: return None, 'Short array. Try again' B = [] for index, item in enumerate(array): if index % 2 != 0: B.append(item) return B, None result, error = array_with_eve...
def Quick_sort(list,low,high): if low >= high: return pivot = partition(list,low,high) Quick_sort(list,low,pivot-1) Quick_sort(list,pivot+1,high) return list def partition(list,low,high): pivot = (low + high) // 2 swap(list,pivot,high) i = low for j in range(low,...
n1 = input() n2 = input() list1 = list(n1) list1.sort() list2 = list(n2) list2.sort() if list1 == list2: print("Anagram") else: print("Not")
####Percentiles in PY### import numpy as np import matplotlib.pyplot as plt ages = [5, 31, 43, 48, 50, 41, 7, 11, 15, 39, 80, 82, 32, 2, 8, 6, 25, 36, 27, 61, 31] x = np.percentile(ages, 75) y = np.percentile(ages, 90) # get the percentile value of the ages which are lower than the 75 % or 90% print(...
def volume(r): return 4/3*3.14*r*r*r r=int(input('Enter the radius of sphere : ')) print("Volume of Sphere : ",volume(r))
#David Justice #9-29-16 #Bubble Sort #Defines function called bubbleSort def bubbleSort(myList): #Creates counter variable to count number of comparisons counter = 0 #Creates boolean moreSwaps to contorl while loop runs moreSwaps = True #while loop checks to see if variable moreSwaps is...
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import copy import itertools def get_maximums(numbers): result = [max(l) for l in numbers] return result def join_integers(numbers): return int("".join([str(n) for n in numbers])) def generate_prime_numbers(limit): primes = [] nombre = [i for i in ran...
#AUTHOR: BABATUNDE IDAHOR #COURSE: CS133 #TERM : FALL 2015 #DATE : 11/3/2015 #This program checks if two user input strings are anagrams of each other. print('Project_3: Q1') print('----------------------------------------------') print('----------------------------------------------') #Input values word1 = str...
#Rakshith Raghu(rrde) code = str(input("Enter your cipher text:")).lower() decoded = "" regular = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",".", "!", "?", "0","1","2","3","4","5","6","7","8","9", " ","@","#","$","%","&",",","/",";",":",...
""" Module for time conversion """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['oeb2utc'] def oeb2utc(systime_array, seconds_of_gps_delay=6): """Converts 6-byte system time (AKA gondola time) to UTC during the flight. Note that the detectors report a high...
#!/usr/bin/env python3 import os this_dir = os.path.dirname(__file__) with open(this_dir + "/input", mode='r') as file: input_ = [line.strip() for line in file.readlines() if line] length = len(input_[0]) height = len(input_) slopes = [ (1, 1), (3, 1), (5, 1), (7, 1), (1, 2) ] def count_t...
from vehicle import Vehicle class Car(Vehicle): default_tire = 'tire' def __init__(self, engine, tires=[], distance_traveled=0, unit='miles', **kwargs): print(f'__init__ from Car with distance_traveled: {distance_traveled} and {unit}') #pass values to parent constructor super()._...
class Vehicle: ''' Vehicle models with tyres and engine ''' default_tire = 'tire' #class level variable def __init__(self,engine, tires): ''' Vehcile class default constructor ''' self.engine = engine self.tires = tires @classmethod def bicycle(cls...
#-*-coding:utf-8-*- class Solution(object): ''' 题意:求数列中三个数之和为0的三元组有多少个,需去重 暴力枚举三个数复杂度为O(N^3) 先考虑2Sum的做法,假设升序数列a,对于一组解ai,aj, 另一组解ak,al 必然满足 i<k j>l 或 i>k j<l, 因此我们可以用两个指针,初始时指向数列两端 指向数之和大于目标值时,右指针向左移使得总和减小,反之左指针向右移 由此可以用O(N)的复杂度解决2Sum问题,3Sum则枚举第一个数O(N^2) 使...