text
stringlengths
37
1.41M
def main_before(a: int, b: int) -> None: c = 1 s = 0 for i in range(a, b, c): if i % 2 == 0: s += i print(s) if __name__ == '__main__': main_before(10, 99)
import math class Comp: def __init__(self, real: float, imag: float): self.real: float = real self.imag: float = imag def __add__(self, other: 'Comp'): return Comp( self.real + other.real, self.imag + other.imag ) def __sub__(self, other: 'Comp'): ...
''' inputDetails = [3, 4, 6, 6, 7, 7, "Hello", "abc", "Hello", 3.4, 5.6, 3.4] myUniqueList = [] for i in range(len(inputDetails)): #print(inputDetails[i]) if inputDetails[i] not in myUniqueList: myUniqueList.append(inputDetails[i]) print(myUniqueList) # The unique list of numbers is as follows :[...
''' Created on Nov 23, 2019 @author: ITAUser ''' #import the random library #def a function called pick_random_word(): #open and read word dictionary/list(words.txt) #create variable called index = select random word from words.txt #create variable called word = strip the randomly selected word ...
a = int(input("Enter 1st number to compare : ")) b = int(input("Enter 2nd number to compare : ")) c = int(input("Enter 3rd number to compare : ")) if a > b and a > c: print("a is the greatest number") elif b > a and b > c: print("b is the greatest number") else: print("c is the greatest number")
l = ['The', 'truth', 'is', 'that', 'I', 'am', 'Ironman'] print(l) print(l[3]) print(l[3:6]) print(l[:-4]) l[5] = 'am not' print(l) for i in l: print(i, end=" ")
# 5. lst1 = [3, 6, 9, 12, 15, 18, 20, 32] counts, Sum = 0, 0 for num in lst1: if num % 3 == 0: Sum += num counts += 1 print("주어진 리스트에서 3의 배수의 개수 => {}".format(counts)) print("주어진 리스트에서 3의 배수의 합 => {}".format(Sum))
# coding=utf-8 """ # 3 if you have time, try recursive, should work too. """ def biggest_seq1(l): current = 0 best = float('-inf') for i in l: current += i if current > best: best = current if current < 0: current = 0 return best def main(): print ...
''' Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. ''' class Solution: # @param board, a 9x9 2D array # Solve the Sudoku by modifying the input board in-place. # Do not retur...
def binary_string(n): if n >= 1 or n <= 0: return 'error' current = 0 res = "" for i in range(32): # print res current += .5 ** (i + 1) if current > n: res += "0" current -= .5 ** (i + 1) elif current < n: res += "1" el...
""" Alpha Beta Search Algorithm """ import random from datetime import datetime def alphabeta_search(state, game, move, robot_level=1, progress=None): """ Alpha Beta Search Algorithm """ # record the start time _absearch_starttime = datetime.now() # set the player player = state.to_move ...
""" common ancestor """ import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from structs import binary_tree def common_ancestor(node1, node2): deep1 = 0 deep2 = 0 tmp1 = node1 tmp2 = node2 while tmp1.parent: deep1 += 1 tmp1 = tmp1.paren...
#coding=utf-8 """ implement a myqueue class which implements a queue using two stacks """ class Myqueue(): stack1 = [] stack2 = [] def push(self,data): self.stack1.append(data) def pop(self): if not self.stack2: while self.stack1: self.stack2.append(self.s...
class PowerSet(): def powerset(self, A): if A is None: return [] if len(A) == 0: return [A] res = [] ps = self.powerset(A[1:]) for i in ps: res.append(i) res.append([A[0]] + i) return res ps = PowerSet() print ps.powers...
def sqrt(n): def sqrt_helper(start, end, step): # print start, end, step if step < .000001: return start, end, step for i in range(10): r = (start + i * step) if r ** 2 == n: return r, r, 0 elif r ** 2 > n: retu...
#coding=utf-8 """ To partition a linked list around a value x Such that all nodes less than x come before all nodes greater than or equal to x """ import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from structs import linkedlist def partition(node, x): r = None he...
# coding=utf-8 # AC Rate: 13.7% # SOURCE URL: https://oj.leetcode.com/problems/wildcard-matching/ # # Implement wildcard pattern matching with support for '?' and '*'. # # '?' Matches any single character. # '*' Matches any sequence of characters (including the empty sequence). # # The matching should cover the entire ...
class Node(): def __init__(self, key, value=float('inf')): self.key = key self.value = value self.left = None self.right = None def inorder(self): if self.left: for i in self.left.inorder(): yield i yield (self.key, self.value) ...
import random # class Agent(): # def __init__(self, capability): # self.capability = capability # class Task(): # def __init__(self, difficulty): # self.difficulty = difficulty def main(agents, tasks, budget): tasks_count = len(tasks) tasks = sorted(tasks) agents = sorted(age...
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a lis...
# 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 # @return a list of lists of integers def levelOrder(self, root): '''bfs''' if not r...
# coding=utf-8 def reverse(A, start, end): # for reverse in place n = end - start for i in range(n / 2): A[start + i], A[end - 1 - i] = A[end - 1 - i], A[start + i] def reverse_word(A): ''' for John ''' reverse(A, 0, len(A)) last_space = 0 for i in range(len(A)): ...
# 65, 20 # 35, 8 # 245, 60 # 195, 55 # 65, 40 # 150, 70 # 275, 85 # 155, 25 import unittest class Solution1: # time complexity # for each clock there is two situation # look at dp really! it's nw # n is the clocks number # w is the weight # because it's int, which won't be a lot # if witho...
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): if not digits: return [''] d2l = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz'} res = [] i = digits[0] res...
def sum_square_difference(n): s1 = 0 s2 = 0 for i in range(n + 1): s1 += i ** 2 s2 += i s2 = s2 ** 2 return s2 - s1 if __name__ == '__main__': print sum_square_difference(100)
def find_left_right(array, start, end, mid): x = array[mid] left = mid while left >= 0: left -= 1 if not array[left] == x: break right = mid while right < len(array): right += 1 if not array[right] == x: break return (left + 1, right - 1) ...
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:,1:2].values # Writing '1:2' instead of '1' because weant X to be a matrix and not an array y = dataset.iloc[:, 2:3].values # Featur...
class Node: def __init__(self, val = 0): self.val = val self.right = None self.down = None class Skiplist: def __init__(self): left = [Node(-1) for _ in range(16)] right = [Node(20001) for _ in range(16)] for i in range(15): left[i].right...
#Vision API Example 1 - Label Return #This code will display a GUI interface asking for #the filename of an image. It will be sent and #processed by the Vision API. A list of potential #labels will be returned import io import os # Imports the GUI library import Tkinter as tkinter # Imports the Google Cloud client l...
#!/bin/python # Data types are of two types # Implicit # primitive type # Numbers # int # float # complex # long # Non-Number # str # unicode # bool # byte ...
#!/usr/bin/env python3 # # machinePrecision will find the minimum float value that can be # represented in the machine running this code # # the program will take a command line argument to allow double or # single precision floating point numbers to be used. if double # precision is desired, pass "double" as the fi...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy import dot #梯度下降 #归一化 def normalization(data): _range = np.max(data) - np.min(data) return (data - np.min(data)) / _range X = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013] Y = [2.000, ...
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def top(self): return self.items[len(self.items)-1] def size(se...
import math import warnings import numpy as np def is_float(inn): """check if the input is float, or castable to float""" try: float(inn) return True except: return False def safe_log(val, max_l=20): """a logarithm function that returns max_l for tiny or huge numbers instead o...
# mergesort.py """Sorting an array with merge sort.""" import numpy as np # calls recursive sort_array method to begin merge sorting def merge_sort(data): sort_array(data, 0, len(data) - 1) def sort_array(data, low, high): """Split data, sort subarrays and merge them into sorted array.""" # test base cas...
# Section 11.3 snippets # Note that the self check #5 is included here as it # continues the section's IPython session. def factorial(number): """Return factorial of number.""" if number <= 1: return 1 return number * factorial(number - 1) # recursive call for i in range(11): print(f'{i}!...
import random random.seed() arr=[] def sel_sort(arr1): for i in range(len(arr1)): min=arr1[i] for j in range (i,len(arr1)): if min>arr1[j]: min=arr1[j] k=j tmp=arr1[i] arr1[i]=min arr1[k]=tmp return(arr1) def ins_sort(arr2): ...
from random import randint TIE = 'Empate!' WIN = 'Ganaste!' LOSE = 'Perdiste!' options = ["Piedra", "Papel", "Tijeras"] player_option = { 'Piedra' : {'Piedra': TIE, 'Papel': LOSE, 'Tijeras': WIN}, 'Papel': {'Piedra': WIN, 'Papel': TIE, 'Tijeras': LOSE}, 'Tijeras': {'Piedra': LOSE, 'Papel': WIN, 'Tijeras'...
attendees = ['Shannon', 'Tammy', 'Rachel'] """ print attendees[0] print attendees[1] print attendees[2] print attendees[0:2] print len(attendees) number_of_attendees = len(attendees) print number_of_attendees """ """ attendees_ages = [] attendees_ages.append(28) attendees_ages.append(27) print att...
# I accidentally overwrote this file while playing around with an interview question for Girls Who Code. # This actually determines whether any 2 numbers in an array add to 100 import random """ Creates a list (array) of random numbers from 0 to 99 """ myArray = [] foundMatch = 0 for i in range(0, 10)...
s = "pwwkew" char = [] l = len(s) temp = 0 end = 0 while(end < l): word = s[end:] print(word) for i, c in enumerate(word): if c not in char: char.append(c) word = "".join(char) else: char.clear() break new_length ...
import re def validate(arg_type: dict, value: any) -> bool: """ Validates any known argument type. :param arg_type: argument type from api.arg_type :param value: the value to validate for this argument :return: True if the value if valid for the given argument type, else False """ if arg_...
import matplotlib.pyplot as plt x = [x for x in range(100)] y = [x for x in range(100)] y_2 = [x * x for x in range(100)] plt.plot(x, y, x, y_2) plt.title("My plot") plt.show()
data = [2, 3, 5, 7, 54] summa = 0 for number in data: print(number) summa += number print(summa) print(sum(data)) zeros = [0, 0] * 15 print(zeros) print(zeros + data) # посчитать кол-во положительных элементов в списке # [1, -3, 2, -3] -> 2 data = [1, -3, 2, -3, 2, 1, 67] positive = 0 for number in data:...
class PlayerCharacter: # Class Object membership = True def __init__(self, name, energy): """ This is my docstring """ self.name = name self.is_tired = False self.energy = energy def __repr__(self): return {'name':{self.name}, 'is_tired':{self.i...
''' Create a function that accepts 3 parameters and checks for equality between any two of them. Your function should return True if 2 or more of the parameters are equal, and false if none of them are equal to any of the others. ''' # Initialize the 3 variables a = 3 b = 3 c = 5 # The If statement: if a == b or...
def createScoreOrderList(pairList): whoJustScored = [] prev = [0,0] for pair in pairList: if pair[0]!=prev[0]: whoJustScored.append("team1") elif pair[1]!=prev[1]: whoJustScored.append("team2") prev = pair return whoJustScored def calculateBo...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # Function # * add ==> sum # In[5]: a = np.char.add(["Hani ","Ali "],["Ash","Mohmmed"]) # In[6]: print(a) # Function # * multiply ==> cross # In[11]: b= np.char.multiply("Hani ", 4) # In[12]: print (b) # Function # # * capitaliz...
class Lagrange: def __init__(self): self.value = float(input("Qual valor será calculado pelo polinômio? ")) self.values = { "x": [ -1, 0, 3 ], "y": [ 15, 8, -1 ] } print("X: ", self.values["x"]) ...
class RungeKutta: def __init__(self): self.intervalo = [] self.y = [] self.intervalo.append( float(input("Ínicio do intervalo: ")) ) self.intervalo.append( float(input("Final do intervalo: ")) ) self.intervalo.append( fl...
__author__ = 'Jeremy Chen' import sqlite3 from _config import DATABASE_PATH with sqlite3.connect(DATABASE_PATH) as conn: c = conn.cursor() c.execute('''CREATE TABLE tasks ( task_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, due_date TEXT NOT NULL, ...
#!/usr/bin/python3 """ Names: James Rasekoala Student Number: RSKJAM001 Prac: EEE3095S Prac 1 Date: 22/07/2019 """ # import Relevant Librares import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) #button setup GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(16, GPIO.IN, pu...
import re import argparse from datetime import datetime # Hardcoding first confession number in file # number = 20584 # raw = 'mit_confessions.txt' def parse_confessions(raw, confessed, confession_number): confessions = [] with open(raw, "r") as f: lines = f.readlines() in_confession = False ...
""" This is a set of "unit tests" for the file point.py, which you will write. We will use this style of testing extensively in CIS 211. You should use the provided unit tests to check your progress frequently as you work through a project. If you work for an hour or more writing code without testing it, you are doi...
# Задача № 2_1 # Сформировать из введенного числа обратное по порядку входящих в него цифр и # вывести на экран. Например, если введено число 3486, то надо вывести число 6843. def func_reverse(num): reverse = '' if num != 0: while num != 0: reverse = reverse + str(num % 10) nu...
# Задача № 3 # По введенным пользователем координатам двух точек вывести уравнение прямой вида # y = kx + b​ , проходящей через эти точки. print("Введите координаты двух точек A(x1,y1) и B(x2,y2)") x1 = int(input("Введите координату x1 точки A: ")) y1 = int(input("Введите координату y1 точки A: ")) x2 = int(input("Вве...
# Задача № 5 # В программе генерируется случайное целое число от 0 до 100. # Пользователь должен его отгадать не более чем за 10 попыток. # После каждой неудачной попытки должно сообщаться больше или # меньше введенное пользователем число, чем то, что загадано. # Если за 10 попыток число не отгадано, то вывести загадан...
#!/usr/bin/env python3 ''' Example on how to do TCP port scanner in Python ''' import socket def scan(address, port, timeout=3): '''TCP Port Scanner''' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) try: ip = socket.gethostbyname(address) sock.connec...
from src.tools.text_manipulation import text_split_in_order alphabets = ['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'] def get_key(item): return item[0] year = '2018' question = '10a' file = open('../../../questions/...
import math import re alphabet = ['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'] def extract_text(): file = open('./questions/2017/3a.txt', 'r') text = file.read() file.close() return text def frequency(tex...
"""Calender to show, add, delete events""" from time import sleep, strftime user_name = "JOHN" calender = {} def welcome(): print("Welcome! "+ user_name) print("Calender is opening...") sleep(1) print("Today is: "+strftime("%A %B %d, %Y")) print("Time: "+strftime("%H:%M:%S")) sleep(1) pri...
d = float(input('Uma distância em metros:')) print('A medida de {}m corresponde a: \n{}km \n{}hm \n{}dam \n{}dm\n{}cm\n{}mm'.format(d,(d/1000),(d/100),(d/10),(d*10),(d*100),(d*1000)))
n = float(input('digite um valor:')) n2 = float(input('digite outro valor:')) s = n + n2 print('a soma ente {} e {} é {}'.format(n,n2,s)) m = input('digite algo:') print(type(m))
din = float(input('Quanto dinheiro você tem na carteira? R$:')) us = din / 3.27 print("Com R$ {:.2f} você pode comprar U$ {:.2f}".format(din, us))
import string import time import timeit import collections import random from threading import Thread fila = collections.deque([]) tamanho = len(fila) def gerarCliente(size=5, chars=string.ascii_uppercase + string.digits): nome = ''.join(random.choice(chars) for _ in range(size)) idade = random....
def word_count(file_name): # counts the amount of each word in the txt file text = open(file_name) big_text = [] for line in text: line = line.strip() text_list = line.split(" ") big_text.extend(text_list) my_dict = {} for word in big_text: my_dic...
# /////////////////////////////////EJERCISIO 1 ////////////////////////////////// # numeros = [1, 6, 8, 3, 5, 4, 7, 2] # def recorrer(): # print("lista de numeros") # for i in numeros: # print(i) # recorrer() # numeros.sort() # print(f"lista ordenada: {numeros}") # print(f"la longitud de la lista es...
def cakes(recipe, available): tot = list() for ing,cant in recipe.items(): tot.append(available.get(ing,0)//cant) return min(tot) if tot else 0 recipe = {"flour": 500, "sugar": 200, "eggs": 1} available = {"flour": 1200, "sugar": 1200, "eggs": 5, "milk": 200} assert (cakes(recipe, availab...
def matrixinterpreter(M): ''' This function interpretes a matrix in form of a string and returns the matrix as a list of lists (rows) paramters: - M : Matrix in form of string ''' output = M.split(", ") output = [line.split(" ") for line in output] for lineindex in range(len(outp...
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) sums = n*(n + 1)/2 for v in nums: sums = sums - v return sums sol = Solution() print sol.missingNumber([0,1,3])
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ s = "".join((lambda x:(x.sort(),x)[1])(list(s))) t = "".join((lambda x:(x.sort(),x)[1])(list(t))) if s == t: return True else: ...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ first = 1 second = 2 ret = n count = 2 while (count < n): count = count + 1 if count == n: ret = first + second ...
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ curvalue = 0 lennums = len(nums) i = 0 while i < lennums: if curvalue == 2: ...
# -*- coding:utf-8 -*- class Solution: def jumpFloor(self, number): # write code here if number <= 2: return number else: a = list([1,2,4]) for i in range(3,number,1): sum = 0 for j in range(i): sum += a[...
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ numbers = [] numbers.append(n) ret = True while True: strn = str(n) result = 0 for v in strn: result = result + pow(int(...
class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ res = 0 curcount = 1 while True: if n >= pow(5,curcount): res = res + n / pow(5,curcount) else: break curc...
# creating slice players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) print(players[1:4]) print(players[-3:]) # from begin print(players[:4]) # till the end print(players[0:]) print("First three players:") for player in players[:3]: print(player.title()) # COPYING THE LIST [:] my_f...
cities = { 'Odesa': { 'country': 'Ukraine', 'population': 900000, }, 'Dublin': { 'country': 'Ireland', 'population': 500000, }, } for city, city_info in cities.items(): print(city + ': ') for key, value in city_info.items(): print('\t' + key + ': ' + str(...
# Create list colors = ['blue', 'yellow', 'white'] # Aces list print(colors) print(colors[0]) # -1 = Always last item, -2 = last item - 1 print(colors[-1]) # Change item in list colors[0] = 'blue_ch' print(colors) # Add item to list # append item to end of list colors.append('black') print(colors) # insert item to...
person_1 = {'name': 'john', 'age': 16} person_2 = {'name': 'jaden', 'age': 17} people = [person_1, person_2] for person in people: print(person['name'] + ' ' + str(person['age']))
from random import choice from time import sleep from simpleeval import simple_eval from termcolor import colored class Bot: # Wait 1 second before bot say anything. wait = 1 def __init__(self, cycle = "once"): self.cycle = cycle self._question() def _question(self): self.q =...
# Task01 - Create a vehicle class that makes use of encapsulation with the correct naming # conventions. It should contain the following: # - Accessors: wheels, doors, fuel, temperature # - Mutators: fuel # car.get_wheels() 4 # car.get_wheels(100) import time class Car: def __ini...
# This is the minimal import for a Flask app but there # are numerous more important imports to make an actual # app with multiple parts that will be introduced later. from flask import Flask # Just something you need to include up top: app = Flask(__name__) # To run this Flask app, activate your virtual environment ...
# newtons_method.py """Volume 1: Newton's Method. <Name> <Class> <Date> """ import sympy as sy from autograd import grad import numpy as np from autograd import jacobian import autograd.numpy as anp from matplotlib import pyplot as plt # Problems 1, 3, and 5 def newton(f, x0, Df, tol=1e-5, maxiter=15, alpha=1.): "...
#!/usr/bin/python3 """ Author: RZFeeser Learning to parse log files with python """ def main(): totalfail = 0 # parse keystone.common.wsgi and return number of failed login attempts loginfail = 0 # counter for fails listOfailedIPs = [] # store the failed IPs in here # open the file for reading with...
def longest_consec(strarr, k): indarr = [] for j in range(0, len(strarr)): indarr.append(strarr[j]) if len(strarr) ==0 or k > len(strarr) or k <= 0: print("") return "" else: final_string = "" for i in range (0, k): final_string += strarr[i] print(final_string) return final_string
# Exercise: # 1. Create a new Java class called PracticeFunctions # 2. Write equivalent Java functions to the following three functions # complete with good Javadoc descriptions (see Course Notes 1.7) # for the two "mystery" functions # method 1 def get_num(i): """ Return twice the given integer if...
class tree: operators = [')','(','and','or'] def __init__(self,value): self.left = None self.right = None self.parent = None self.operator = False if(value == None): self.value=None else: self.value = value def addChild(self,c...
def print_heading(symbol,mul,heading): print(symbol * mul) print(heading) print(symbol * mul) #functio that convert decimal to binary def decimal_binary(decimal): binary = list() while(decimal >=2): if decimal%2 != 0: binary.append(1) else: binary.append(0) de...
print('*' * 40) print('Check Number is Multiple of 89 or not') print('*' * 40) var = int(input("Enter the Number : ")) if (var % 89 == 0): print("Number is Multiple of 89 ") else: print("Number is Not Multiple of 89")
def isPrime(num): check = 0 for i in range(2,num): if num %i == 0: check += 1 if check > 0: return False else: return True for i in range(1, 40): if isPrime(i + 1): print(i + 1, end=" ") print()
def question_posted(down_votes,up_votes): down_points = down_votes * (-2) up_points = up_votes * 10 return down_points + up_points def answers(accept,down_votes,up_votes): if accept == 'accepted': accepted_points = 15 else: accepted_points = 0 down_points = down_votes * (-2) up_points = up_votes...
from Employee import Employee class FullTimeEmployee(Employee): def __init__(self, name, family, salary, department): #defining the default constructor for the child class Employee.__init__(self, name, family, salary, department) #Referencing the base class constructor self.name = name self...
mydict ={} inp = input(" Enter the sentence") words = inp.split() #split the sentence into a list of words mywords = sorted(words) #sort the list for word in mywords: mydict[word] = words.count(word) # find count of each word and add it to dict print(mydict)
""" Using NumPy create random vector of size 15 having only Integers in the range 0-20. Write a program to find the most frequent item/value in the vector list. Sample input:[1,2,16,14,6,5,9,9,20,19,18] Sample output:Most frequent item in the list is 9 """ import numpy as np print(np.arange(9).reshape(3,3)) array = np....
#BFS def BFS(start): visited = [] queue = [] queue.append(start) visited.append(start) while len(queue) != 0: print queue[0] nodeArr = graphMap[queue[0]] del queue[0] for i in nodeArr: if i not in visited: visited.append(i) queue.append(i) #Create Graph graphMap = ...
#!/usr/bin/python def check(king, queen): """Given a chessboard with one K and one Q, see if the K can attack the Q. This function is given coordinates for the king and queen on a chessboard. These coordinates are given as a letter A-H for the columns and 1-8 for the row, like "D6" and "B7": >>> ...
# -*- coding = utf-8 -*- # @Time : 2021/1/29 15:54 # @Author: 肖兴 # @File : swap.py # @Software : PyCharm def swap(x): a = min(x) a1 = x.index(a) x[-1], x[a1] = x[a1], x[-1] b = max(x) b1 = x.index(b) x[0], x[b1] = x[b1], x[0] for item in x: print(item, end=",") if __name__ == '__...
'''2) Pide al usuario 5 números y di si estos estaba en orden decreciente, creciente o desordenados.''' num1=float(input("Introduzca el primer número: ")) num2=float(input("Introduzca el segundo número: ")) num3=float(input("Introduzca el tercer número: ")) num4=float(input("Introduzca el cuarto número: ")) num5=floa...
# Complete the function solveMeFirst to compute the sum of two integers. # Function prototype: # int solveMeFirst(int x, int y); # where, # x is the first integer input. # y is the second integer input # Return values # sum of the above two integers # Sample Input # x = 2 # y = 3 # Sample Output # # 5 def so...