text
stringlengths
37
1.41M
def heightChecker(a) -> int: count = 0 c = [h1!=h2 for h1,h2 in zip(a,sorted(a))] for i in c : if i: count+=1 return count heights = [1,1,4,2,1,3] lenght= heightChecker(heights) print(lenght) """ Output: 3 Explanation: Current array : [1,1,4,2,1,3] Target array : [1,1,1,2,3,4] O...
#!/usr/bin/env python3 import os def remove_spaces_from_filenames(directory_path): # Check if the provided directory exists if not os.path.exists(directory_path): print(f"Directory '{directory_path}' does not exist.") return # Get a list of all files in the directory files = os.listdi...
import math def suma(a,b): return a + b def resta (a,b): return a - b def multiplicacion(a,b): return a*b def division(a,b): return a/b def potencia(x,y): return pow(x, y) def raiz(x): return math.sqrt(x) def logarit(x): return math.log10(x) def menu(): pr...
# Strategy: keep maps of how many letters are in different conditions and go from there result = 0 word_counts = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4} teen_counts = {10: 3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8} tens_counts = {0:0, 1:3, 2:6, 3:6, 4:5, 5:5, 6:5, 7:7, 8:6, 9:6} for i in range...
# Strategy: get next triangle number, find the number of factors by parsing the numbers until its square root` import math triangle_number = 1 triangle_incrementer = 1 while True: to_be_divided = triangle_number num_factors = 0 potential_factor = 1 while potential_factor <= math.sqrt(triangle_number): ...
#!/usr/bin/env python # coding: utf-8 # ASSIGNMENT SUM OF ADD N NUMBERS USING WHILE LOOP # # In[4]: num=15 sum=0 while(num>0): sum=sum+num num=num-1 print("the sum is",sum) # prime numbers in python # # In[78]: number=int(input("enter num:")) if number > 1: for i in range(2, number): ...
name = 'Arthur' age = 37 # console.log print('Hello I am ' + name + ' and I am ' + str(age)) # String Formatting # Arguments by position # print('{1}, {2}, {3}'.format('a','b','c')) # string methods s = 'hello there world' # capitalize first letter print(s.capitalize()) # Make all uppercase print(s.upper()) # m...
def scores_to_dict(): ''' Parses the given tab-delimited text file, and returns a dictionary of words mapped to sentiment scores (as integers). accused -2 assured 2 returns: {accused:-2, assured:2} ''' with open("AFINN-111.txt", 'r') as afinnfile: scores = {} for lin...
import random def load_word(): ''' A function that reads a text file of words and randomly selects one to use as the secret word from the list. Returns: string: The secret word to be used in the spaceman guessing game ''' f = open('/usr/share/dict/words', 'r') words_list =...
import collections """ collections Counter """ counter = {} for person in persons: name = person.name counter.setdefault(name, 0) counter[name] += 1 counter = collections.Counter() for person in persons: name = person.name counter[name] += 1 """ collections namedtuple """ """ functools...
class Team: def __init__(self,name,league,manager_name,points): self.name = name self.league = league self.manager_name = manager_name self.points = points self.players = [] def add_player(self,player): self.players.append(player) def __str__(self): ...
#Slices work the same between strings and lists def first_4(shopping): return (shopping[0:4]) def first_and_last_4(shopping): items = (shopping [0:4]) + (shopping [-4:]) return(items) def odds (shopping): return (shopping[1::2]) def reverse_evens (shopping): print (shopping) evens = shopping[...
# Calculate hold for American odds # Takes 2 command-line arguments - Favourite and Underdog American odds import sys # Convert Decimal to American odds (amount to bet to win) # e.g. 1.91 -> -110 # e.g. 2.35 -> +135 def convert_to_american(decimal_odds): if decimal_odds < 2: return round(100 / (1 - decim...
# empty class class Person: """ this class represents a person """ pass # variable num = 100 print(type(num)) # p1 is a reference which stores an object of Person p1 = Person() print(type(p1))
class Person: def __init__(self, name): self._name = name def __str__(self): return 'Person[name: {}]'.format(self._name) class Employee(Person): def __init__(self, name, empId): Person.__init__(self, name) self.__empId = empId def __str__(self): return 'Employ...
def outer(): print('inside outer') # local variable outer num1 = 100 print('before inner() num1: {}'.format(num1)) def inner(): print('inside inner') nonlocal num1 print('before modifying num1: {}'.format(num1)) # local num1 num1 = 200 print('after m...
class Person: def __init__(self, name, age): self.__name = name self.__age = age def __str__(self): return 'Person[name: {}, age: {}]'.format(self.__name, self.__age) if __name__ == '__main__': p1 = Person('person1', 45) print(p1) print('person: __name__ -> {}'.format(__nam...
def add(p1, p2): print('addition = {}'.format(p1 + p2)) def multiply(p1, p2): print('multiplication = {}'.format(p1 * p2)) def divide(p1, p2): print('division = {}'.format(p1 / p2)) def subtract(p1, p2): print('subtraction = {}'.format(p1 - p2)) # myAdd = add # myAdd1 = myAdd # myAdd2 = myAdd1 # my...
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def function1(): evenNumbers = [] for number in numbers: if number % 2 == 0: evenNumbers.append(number) print(numbers) print(evenNumbers) # function1() def isEven(number): return number % 2 == 0 # if number % 2 == 0: # retu...
print ( "Ingrese 3 Numeros ") N1 = int(input("Ingrese : ")) N2 = int(input("Ingrese : ")) N3 = int(input("Ingrese : ")) L = [N1,N2,N3] print (L[-1]) print(L[-2]) print (L[0])
''' 1. The EXPLAIN Query ''' # import psycopg2 # conn = psycopg2.connect(dbname="hud", user="hud_admin", password="hud123") # cur = conn.cursor() # cur.execute(""" # EXPLAIN # SELECT * FROM homeless_by_coc # """) # print(cur.fetchall()) ''' 2. The Path of a Query ''' # import psycopg2 # conn = psycopg2.connect(dbname=...
# # 1.Introduction to the Data # raw_hamlet = sc.textFile("hamlet.txt") # raw_hamlet.take(5) # 2.The Map Method split_hamlet = raw_hamlet.map(lambda line: line.split('\t')) split_hamlet.take(5) # 3.Beyond Lambda Functions # 4.The FlatMap Method hamlet_spoken_lines = split_hamlet.filter(lambda line: filter_hamlet_s...
#### 1 # l = [1, 2, 3] # s = "string" # d = {"a": 1, "b": 2} # my_set = {2, 3, 5} # print(d) # print(type(l)) # print(type(s)) # print(type(d)) # print(type(my_set)) #### 2 # tri_num_sequence = [1, 3, 6, 10, 15, 10, 6, 3, 1] # odd_numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] # trinum_5 = set(tri_num_sequence) # odd...
class Node: def __init__(self, value): self.value = value self.left_child = None self.right_child = None class BST: def __init__(self): self.root = None def add(self, value): self.root = self._add_recursive(self.root, value) def _add_recursive(self, current_...
#### 1 # print(2 ** 32) #### 2 #645321 # weight_digit_2 = 10 ** 2 # value_digit_2 = 2 * weight_digit_2 # weight_digit_5 = 10 ** 3 # value_digit_5 = 5 * weight_digit_5 #### 3 # #11001 in binary to decimal # decimal_1 = 1 * (2 ** 4) + 1 * (2 ** 3) + 0 * (2 ** 2) + 0 * (2 ** 1) + 1 * (2 ** 0) # #1110 in binary to decima...
# 14. Write a function that reads a CSV file. It should return a list of dictionaries, using the first row as key # names, and each subsequent row as values for those keys. For the data in the previous example it would return: [{ # 'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name': 'John', 'address': ...
# 15. Imagine you are designing a banking application. What would a customer look like? What attributes would she # have? What methods would she have? class Customer: def __init__(self,c_id,name,account_no,balance): self.c_id = c_id self.name = name self.account = account_no self....
from cs50 import get_string import sys def main(): if len(sys.argv) != 2: print("Usando ./caesar") sys.exit(1) llave = int(sys.argv[1]) if llave < 0: print("Error") sys.exit(1) plaintext = get_string("Plaintext: ") print("ciphertext: ", end="") for chr_txt in pla...
# -*- coding: utf-8 -*- __author__ = 'Sivasubramanian Chandrasegarampillai, Walter Curnow' __email__ = 'rchandra@uci.edu,wcurnow@uci.edu' from assignment2 import Player, State, Action class AlphaBetaPlayer(Player): def move(self, state): """Calculates the best move from the given board using the minimax a...
"""@package DESKeygen Documentation for this module. """ from copy import copy ## This is an implementation of DES Cipher Algorithm # DES = Data Encryption Standard # STEP 1: create all constants first ## The follow lists are values used for encryption EXPANSION = [ 31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7,...
""" Helper functions """ import numpy as np def format_size(num, suffix='B'): """Human readable bytesizes. """ for unit in ['','Ki','Mi','Gi','TBi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def uni...
class Solution: def detectCapitalUse(self, word: str) -> bool: n = len(word) if len(word) == 1: return True if word[0].isupper() and word[1].isupper(): for i in range(2,n): if not word[i].isupper(): return False ...
# 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: num1,num2 = 0,0 while l1 or l2: ...
# coding: utf-8 # # CAIS++ Logistic Regression Workshop! # # Before you go through this code, make sure you read [lesson 3]('http://caisplusplus.usc.edu/blog/curriculum/lesson3') from our curriculum # ## Part 1: Import Dataset & Preprocessing # In[1]: # Import Statemements import random import pickle # used to...
dict = {'Joe':14,'Adam':26,'Emily':52} print(dict['Joe']) dict['Joe'] = 15 #dict.clear() print(dict.items()) print(dict.keys()) #del dict print(dict.values())
class Node: def __init__(self,data): self.data = data self.height = 0 self.leftChild = None self.rightChild = None #create AVL class class AVL: def __init__(self): self.root = None def calcHeight(self,node): if not node: return -...
# 1) Create a Cricle class and intialize it with radius. Make two methods getArea and getCircumference inside this class class circle: def __init__(self,radius): self.radius=radius print("creating a circle with radius: ",self.radius) def getarea(self): area=3.14*(self.radius**2) ...
numone = input("Give me a number: ") numtwo = input("Give me another number: ") expression = input("To multiply enter mul, to divide enter div and for Modulo enter mod: ") if (expression == "mul"): output = int(numone)*int(numtwo) print("The answer is: " + str(output)) elif (expression == "div"): output = int(numo...
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n == 0: return 0 elif n <= 2: return 1 first = 1 second = 1 for i in range(3, n + 1): third = first + second first, second = second, thi...
# -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None # ๅ‡่ฎพๅŽŸ้“พ่กจไธบ 1 -> 2 -> 3 -> 4 # ๅˆ†ไธ‰ๆญฅ๏ผš # ็ฌฌไธ€ๆญฅ๏ผšๆŠŠๆฏไธช้“พ่กจ่Š‚็‚นๅคๅˆถไธ€ไปฝๆŽฅๅˆฐๅŽŸ่Š‚็‚นๅŽ1 -> 1 -> 2 -> 2 -> 3 -> 3 -> 4 -> 4 # ็ฌฌไบŒๆญฅ๏ผš่ฎพ็ฝฎๆ–ฐๅŠ ๅ…ฅ่Š‚็‚น็š„random่Š‚็‚น๏ผŒๅ…ณ้”ฎๆญฅ้ชคไธบ๏ผšnode.next.random = node.random.next # ็ฌฌไธ‰ๆญฅ๏ผšๅฐ†ๆ–ฐๅŠ ๅ…ฅ่Š‚็‚นๆŠฝ็ฆป...
# -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # write code here if not rotateArray: return 0 left = 0 right = len(rotateArray) - 1 target = rotateArray[-1] while left + 1 < right: mid = left + (right - le...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/31 8:14 # @Author : leehour """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Postorder in ArrayL...
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here if not pRoot1 or not pRoot2: return False return self.is_sub...
mport sys def main(): """ <p> Simulates trading using a mean-reverting-esque strategy. The strategy is basically this: <ol> <li> There is probably an average number of days that a stock trends down and a number of days that a stock trends up. <li> Theoretically, you could buy ...
class TradeAlgorithm: def __init__(self): raise NotImplementedError("TradeAlgorithm is an abstract base class and should not be instantiated") def run(self, today_price, context): raise NotImplementedError("TradeAlgorithm is an abstract base class and should not be instantiated") def aver...
import math import numpy as np import sympy as sp def f(x): #dica: potencia -> ** return x**3-9*x+3 #escreva aqui a funcao desejada def g(xk, xk1): ans = (xk1*f(xk) - xk*f(xk1))/(f(xk)-f(xk1)) return ans def secante(e, x0,x1): xk = x1 xk1 = x0 print('|k|xk|flinha(xk)|f(xk...
class Game(): def __init__(self, name): self.name = name self.end = False def start(self): print("""You run into the building, and spot a body in the middle of the room. Out of the corner of your eye, you spot a figure scrambling out the window...
#File: sorting.py #Descriptiong: HW 9 #Student's Name: Lisa Chu #Student's UT EID: tc29328 #Course Name: CS 313E #Unique Number: 50739 # #Date Created: 4/25/19 #Date Last Modified: 4/26/19 ############################################################################# #Start of given code import random im...
''' C301 Lesson 2 Program 2 helper library Name: Tic Tac Toe helper library Description: Functions to suppose the tic tac toe starter file. Students aren't expected to know how each function work. ''' # Function for formatting and displaying game board with current state def display_board(game_boa...
""" C301 Lesson 4/5 Name: MineCrisis! Description: The tunnel wall before you has a 3x3 grid of blocks to mine. One of these blocks has valuable red ore, but beware! Monsters are hiding behind the other blocks, just waiting to ruin your mine. Whenever you click on the ore, you'll collect it...
# 49 # Group Anagrams # https://leetcode.com/problems/group-anagrams/ # python # medium # O(k*n^2) # O(k*n) # string # Initial slow solution # time: O(k*n^2) where n is the length of the list and k is the max length of the strings # space: O(k*n) class Solution: def groupAnagrams(self, strs: List[str]) -> List[Lis...
# 74 # Search 2D Matrix # https://leetcode.com/problems/search-a-2d-matrix/submissions/ # python # medium # O(log m + log n) # O(1) # array binary_search matrix # double binary search class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: ...
# 73 # Set Matrix Zeroes # https://leetcode.com/problems/set-matrix-zeroes/ # python # medium # O(m*n) # O(1) # array class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rb = 0 in matrix[0] cb...
"""Test functions in server.py""" import unittest from server import app import model from test_data import test_data from datetime import datetime class BookAppTests(unittest.TestCase): """Testing intergration of Flask server""" def setUp(self): """Do before every test.""" self.client = ap...
class Inventory: def __init__(self): self.slots = [] def add_item(self, item): self.slots.append(item) # 1.Great! Now override the add_item method. # Use super() in it to make sure the item # still gets added to the list. # 2.Sorted inventories should be just that: # sorted. Right now, we just...
# -*- coding: utf-8 -*- """ Created on Tue Nov 20 18:38:08 2018 @author: AmyJade """ #Basic pyplot plot of a straight line #Changed tools>preferences so it prints in a new screen not inline, #this is useful because you can save it, zoom etc. import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.show(...
import random board = ['-' for x in range(9)] def show_board(): print("\n") print(board[0] + "|" + board[1] + "|" + board[2] + " 1|2|3") print("------") print(board[3] + "|" + board[4] + "|" + board[5] + " 4|5|6") print("------") print(board[6] + "|" + board[7] + "|" + board[8] + " ...
""" https://www.codewars.com/kata/52597aa56021e91c93000cb0 """ def move_zeros(array): for i in range(len(array)): for j in range(i+1,len(array)): if array[i] == 0 and array[i] is not False: array[j],array[i]=array[i],array[j] return array
""" Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print โ€œFizzโ€ instead of the number and for the multiples of 5 print โ€œBuzzโ€. Also for number which are multiple of 3 and 5, prints โ€œFizzBuzzโ€. """ def fizzBuzz(A): arr = [] for i in range(1,A+1): if i % 3 == 0 an...
# -*- coding: utf-8 -*- """ Created on Wed Sep 24 18:07:05 2014 @author: augustin """ for i in range(ord('a'), ord('z')+1): for j in range(ord('a'), ord('z')+1): if i != j: print(chr(i) + chr(j)) else: continue
import sys import random if len(sys.argv) != 3: print("Usage: python3 {} [chapters] [days]".format(sys.argv[0])) print("Generate input values with uniform distributions") print("days must be less than or equal to chapters") sys.exit() chapters, days = [ int(num) for num in sys.argv[1:] ] minVerse = 1...
import numpy as np import pandas as pd import matplotlib.pyplot as plt # function definition that takes Temp_xAxis and Mean_yAxis values as input and plot graph using pyplot def plot_graph(Temp_xAxis, Mean_yAxis): plt.bar(Temp_xAxis, Mean_yAxis) plt.title('Mean') plt.xticks(rotation=10) plt.show() ...
#Generate a random number between 1 and 9 (including 1 and 9). # Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. import random a=random.randint(1,9) i=True count=0 while i==True: n = int(input("Guess the number:\n")) print(a) if n==a: ...
#!/usr/bin/env python3 """ Project Euler: https://projecteuler.net/problem=5 Smallest multiple Problem 5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ __auth...
from flask_login import UserMixin from app import db ### # The following file contains our database definition. This is where we indicate what tables we have # and what field they each contain. # Note: We would normally use a hash for the password with a salt but for the purpose # of this demo, we intentionally remov...
class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ # sort the list by height in ascending order # in-place sorting people.sort(key=lambda x: x[0]) queue = self._reconstruc...
# __description__: Given a singly linked list of integers l and an integer k, remove all elements from list # l that have a value equal to k. # Definition for singly-linked list: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def removeKFromList(l, k): # case whe...
def pos_neg(a,b,negative): if negative: return (a < 0 and b <0) else: return ((a < 0 and b > 0) or (a > 0 and b < 0)) print(pos_neg(-5,-6,True))
class Flames: ''' class containing attributes and methods required to play flames game. Attributes : name1 - string with name of first person name2 - string with name of second person n1 - list of letters in name1 after removing common letters n2 - list of letters in name2 after removing common letters expansi...
from collections import defaultdict debug_print = False class RestaurantAnalytics: """ Provides methods to analyse the list of restaurants and their locations. """ @staticmethod def top_restaurant_types(restaurant_list): """ Calculates the most favourable types of restaurants in ...
''' The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. What is the value of the first triangle number to have over five hundred divisors? ''' from math import sqrt def number_factors(n): large_divisors = [] for i in...
'''In this assignment you will implement one or more algorithms for the traveling salesman problem, such as the dynamic programming algorithm covered in the video lectures. Here is a data file describing a TSP instance. The first line indicates the number of cities. Each city is a point in the plane, and each subsequen...
# The following iterative sequence is defined for the set of positive integers: # n = n/2 (n is even) # n = 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # It can be seen that this sequence (starting at 13 and fi...
# -*- coding: UTF-8 -*- ##property()ๅ‡ฝๆ•ฐ๏ผŒๆœ‰get๏ผŒset๏ผŒdelไปฅๅŠๆ—ฅๅฟ—ๅ››ไธชๅ‚ๆ•ฐ๏ผŒ ##ๅˆ†ๅˆซ็”จไบŽๅฏน่ฑก็š„ๆŸฅ่ฏขใ€่ฎพ็ฝฎไปฅๅŠๅˆ ้™ค class Number(object): def __init__(self, value): print "$$$ calling init" self.value = value def getNeg(self): print "$$$ calling get" return self.value def setNeg(self, value): print "$$...
# -*- coding: UTF-8 -*- """ 1. zip 2. lambda 3. map() 4. filter() 5. generator """ """ zip """ a = [1, 2, 3, 4] b = [1.1, 2.1, 3.1, 4.1] c = ['a', 'b', 'c', 'd'] abc = zip(a, b, c) # ta, tb, tc, td = zip(a, b, c) print "zip(a, b, s) = %s" % abc print "the type of abc is %s" % type(abc) print "the type of...
nums = [4,8,5,2,1] #1 sorted() (Returns sorted list) sorted_nums = sorted(nums) print(sorted_nums)#[1,2,4,5,8] print(nums)#[4,8,5,2,1] #2 .sort() (Changes original list) nums.sort() print(nums)#[1,2,4,5,8]
import socket """ If you know the port number of a network service, you can find the service name using the getservbyport()socket class functionfrom the socket library. You can optionally give the protocol name when calling this function. Let us define a find_service_name()function, where the getservbyport()socket ...
# -*- coding: utf-8 -*- import time, os import pyautogui from pynput.mouse import Listener banner = ''' โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘...
i = 3 j = 2 k = i + j print ("k: " + str(k))
""" In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process! """ import threading import time def handler(start=0, finish =0): result = 0 for i in range(...
# Last modified: July 8th '21 # Fetch Reinforcement Learning # Fetch Reinforcement Learning is an AI module and class for a SPIKE running micropython. import random from random import randint class Fetch_ReLearn(): """This is the class for reinforcement learning. The idea is to train the puppy accuratel...
# The data we need to retrieve # 1. the total # of votes cast # 2. a complete list of candidates who receied votes # 3. The % of votes each candidate won # 4. The total # of votes each candidate won # 5. the winner of the election based on popular votes # Add dependecies import csv import os # Assigning variable to ...
#!/usr/bin/env python3 import sqlite3 def getConn(): conn = sqlite3.connect("appdb.db") return conn def addUser(): conn = getConn() cursor = conn.cursor() cursor.execute('create table users (id int primary key,name varchar(20) not null)') cursor.execute('insert into users (id,name) values (1,...
#time complexity O(n^2) def insertion_sort(li): for i in range(1,len(li)): x = li[i] j = i-1 while(j>=0) and (li[j]>x): li[j+1]=li[j] j-=1 li[j+1]=x return li if __name__ == "__main__": arr = [2,5,4,3,2,1,6] print('Original Array: ', arr) arr = insertion_sort(arr) print('Sorted array: ',arr)
#!/bin/python3 import math import os import random import re import sys # Complete the timeInWords function below. def timeInWords(h, m): time = '' words = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve', 'thirteen','fourteen','fifteen','sixteen','seventeen','eightee...
ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = {10: 'ten',11: 'eleven',12: 'twelve',13: 'thirteen',14: 'fourteen',15: 'fifteen',16: 'sixteen',17: 'seventeen',18: 'eighteen',19: 'nineteen'} tens = ['', 'ten','twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', ...
#!/usr/bin/env python # reference speed test for searching wordlist import sys wordlist = open('word.list').read().split() found = False counter = 0 for word in wordlist: if word == sys.argv[1]: found = True counter += 1 if found: print 'found!' else: print 'not found!' print counter
# Python 3 program to # check the number is # divisible by all # digits are not. # Function to check # the divisibility # of the number by # its digit. def checkDivisibility(n, digit) : # If the digit divides the # number then return true # else return false. return (digit != 0 and n % digit == ...
# 4. Go through the string below and if the length of a word is even print "even!" # st = 'Print every word in this sentence that has an even number of letters' # #Code in this cell st = 'Print every word in this sentence that has an even number of letters' mylist = [word for word in st.split() if len(word) % 2 ...
# 5. Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". # #Code in this cell for num in range(1, 101): out = "" if num % 3 ...
# the Tic Tac Toe Milestone Project game! from random import random def display_board(board): # clear output print('\n' * 100) print('|{}|{}|{}|'.format(board[0], board[1], board[2])) print('-------') print('|{}|{}|{}|'.format(board[3], board[4], board[5])) print('-------') print('|{}|{}|{...
class Cylinder: pi = 3.14 def __init__(self, height=1, radius=1): self.height = height self.radius = radius def volume(self): area = self.pi * (self.radius ** 2) return self.height * area def surface_area(self): area_circumference = 2 * self.pi * self.radius * ...
Equality of 3 Values Create a function that takes three integer arguments (a, b, c) and returns the amount of integers which are of equal value. Examples equal(3, 4, 3) โžž 2 equal(1, 1, 1) โžž 3 equal(3, 4, 1) โžž 0 Notes Your function must return 0, 2 or 3. def equal(a, b, c): uniq= set([a,b,c]) if len(uniq)==3: ...
#https://edabit.com/challenge/rSa8y4gxJtBqbMrPW # # # #LCM of Two Numbers #Write a function that returns the least common multiple (LCM) of two integers. # #Examples #lcm(9, 18) โžž 18 # #lcm(8, 5) โžž 40 # #lcm(17, 11) โžž 187 #Notes #Both values will be positive. #The LCM is the smallest integer that divides both numbers s...
Is the Number a Repdigit A repdigit is a positive number composed out of the same digit. Create a function that takes an integer and returns whether it's a repdigit or not. Examples is_repdigit(66) โžž True is_repdigit(0) โžž True is_repdigit(-11) โžž False Notes The number 0 should return True (even though it's not a po...
ERROR: type should be string, got "https://edabit.com/challenge/RB6iWFrCd6rXWH3vi\n\nLongest Alternating Substring\nGiven a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.\n\nExamples\nlongest_substring(\"225424272163254474441338664823\") โžž \"272163254\"\n# substrings = 254, 272163254, 474, 41, 38, 23\n\nlongest_substring(\"594127169973391692147228678476\") โžž \"16921472\"\n# substrings = 94127, 169, 16921472, 678, 476\n\nlongest_substring(\"721449827599186159274227324466\") โžž \"7214\"\n# substrings = 7214, 498, 27, 18, 61, 9274, 27, 32\n# 7214 and 9274 have same length, but 7214 occurs first.\nNotes\nThe minimum alternating substring size is 2.\n\n\nA=754388489999793138912431545258\nC=str(A)+str(A)[-1]\nK, lengh=[], []\nfor i in range(len(C)-1):\n if int(C[i])%2!=int(C[i+1])%2: K.append(C[i])\n else:\n K.append(C[i])\n print(K)\n if len(K)>len(lengh): lengh=K\n K=[]\nprint(int(''.join(lengh)))\n\n\n\ndef longest_substring ( n ):\n txt=''\n for i in range(len(n)-1):\n if int(n[i])%2==int(n[i+1])%2:\n txt=txt[:-1]+n[i]+\" \"+n[i+1]\n else: txt=txt[:-1]+n[i]+n[i+1]\n return sorted(txt.split(),key=len,reverse=True)[0]\nprint(longest_substring ( \"844929328912985315632725682153\" )) # 56327256\n\n\ndef longest_substring(digits):\n res = digits[0]\n for i in digits[1:]:\n if int(i)%2 != int(res[-1])%2:\n res += i\n else:\n res += ' ' + i\n return max(res.split(), key=len)\n"
ERROR: type should be string, got "\nhttps://edabit.com/challenge/PxxZprxCjDrzaTcLQ\n\nVowel to Vowel Links\nGiven a sentence as txt, return True if any two adjacent words have this property: One word ends with a vowel, while the word immediately after begins with a vowel.\n\nExamples\nvowel_links(\"a very large appliance\") โžž True\n\nvowel_links(\"go to edabit\") โžž True\n\nvowel_links(\"an open fire\") โžž False\n\nvowel_links(\"a sudden applause\") โžž False\nNotes\nYou can expect sentences in only lowercase.\n\n\nA=\"a sudden applause\"\nB=A.split()\nC=[]\nprint([True for i in range(len(B)-1) if B[i][-1] in 'aeiou' and B[i+1][0] in 'aeiou'])\n\nimport re\ndef vowel_links(txt):\n\treturn bool(re.findall('[aeiou] [aeiou]', txt))\n\n\n\ndef vowel_links(txt):\n\ttxt= txt.split()\n\tfor i in range(len(txt) - 1):\n\t\tif txt[i][-1] in 'aeiou' and txt[i+1][0] in 'aeiou': return True\n\treturn False\n\n\n\ndef vowel_links(txt):\n lov = 'aeiou'\n low = (txt + ' x').split()\n for i in range(len(low)-1):\n if low[i][-1] in lov and low[i+1][0] in lov:\n return True\n return False\n\n\ndef vowel_links(txt):\n\ttxt = txt.split()\n\treturn any(x[-1] in 'aeiou' and y[0] in 'aeiou' for x, y\n\n\n\ndef vowel_links(txt):\n words = txt.split()\n vowel1 = (\"a\",\"e\",\"i\",\"o\",\"u\")\n for i in range(len(words)):\n if words[i].endswith(vowel1) and words[i+1].\nstartswith(vowel1):\n return True\n else: False\nprint(vowel_links(\"a very large appliance\"))\n"
#number = int(input()) #binary = bin(number) #binary_1 = binary[2:] #bin_list = list(binary_1) ##toplam = sum(bin_list) #n = 0 #for i in bin_list: # n += int(i) #print(n) #toplam = sum(bin_list[2:]) #print(toplam) #toplam = sum(bin_list[2:]) #number = int(input()) #binary = bin(number) #binary_1 = list(binar...
ERROR: type should be string, got "\nhttps://edabit.com/challenge/frRRffQGSrPTknfxY\n\nKeeping Count\nGiven a number, create a function that returns a new number based on these rules:\n\nFor each digit, replace it by the number of times it appears in the number.\nThe final instance of the number will be an integer, not as a string.\nWorked Example\ndigit_count(136116) โžž 312332\n# The number 1 appears thrice, so replace all 1s with 3s.\n# The number 3 appears only once, so replace all 3s with 1s.\n# The number 6 appears twice, so replace all 6s with 2s.\n# Return as an integer.\nExamples\ndigit_count(221333) โžž 221333\n\ndigit_count(136116) โžž 312332\n\ndigit_count(2) โžž 1\nNotes\nAll test input will be positive whole numbers.\n\n\nA=136116\nprint(int(''.join([n.replace(str(n), str(list(str(A)).count(n))) for i,n in enumerate(list(str(A)))])))\n\ndef digit_count(n):\n\tn = str(n)\n\treturn int(''.join(str(n.count(k)) for k in n))\n\n\ndef digit_count(n):\n\ttempString = str(n)\n\tresult = \"\"\n\tfor i in range( len(tempString) ):\n\t\tresult += str(tempString.count(tempString[i]))\n\treturn int(result)\n\n\n\ndef digit_count(n):\n\tnew_txt = ''\n\t\n\tfor i in str(n):\n\t\tnew_txt += str(str(n).count(i))\n\t\n\treturn int(new_txt)\n\n"
https://edabit.com/challenge/vTGXrd5ntYRk3t6Ma Is the Word an Isogram? An isogram is a word that has no repeating letters, consecutive or nonconsecutive. Create a function that takes a string and returns either True or False depending on whether or not it's an "isogram". Examples is_isogram("Algorism") โžž True is_iso...