text
stringlengths
37
1.41M
#In this recipe, we'll create a spatial index for a point layer and then we'll use it to perform a spatial query, as follows: #Function Name: idToGeom() #Arguments: list of feature ids #Return: list of point features #This function prints point features of the given list of feature ids def idToGeom(ids): points =...
class Worker: name = 'some_name' surname = 'some_surname' position = 'some_position' __income = {'wage': 1000, 'bonus': 200} class Position(Worker): def __init__(self, name, surname, position, income): self.name = name self.surname = surname self.position = position ...
with open("my_file.txt", 'w', encoding='utf-8') as fi: while True: string_1 = input('Введите первую строку и нажмите enter. Для выхода введите пустую строку. ') if string_1 == '': break else: fi.write(f'{string_1}\n')
class Matrix: def __init__(self, matrix): self.matrix = matrix def __str__(self): self.new_one = str('\n'.join(['\t'.join([str(j) for j in i]) for i in self.matrix])) return self.new_one def __add__(self, other): for i in range(len(self.matrix)): for j in range(...
result_1 = 0 def sum_numbers(list_numbers): """Возвращает сумму элементов, после преобразования из str.""" result = (int(item) for item in list_numbers) return sum(result) while True: number_str = input('Введите числа через пробел ') number_list = number_str.split() if 'q' in number_list: ...
def user_data(name, surname, birthday, city, email, phone): print(f'{name} {surname} {birthday} {city} {email} {phone}') user_data(name=input('Введите имя '), surname=input('Фамилию '), birthday=input('День рождения '), city=input('Город '), email=input('Электронную почту '), phone=input('Телефонный ном...
print "The animal at 1 is the second animal and it's python" print "The 3rd animal is a peacock and it's at 2" print "The 1st animal is at 0 and is a bear" print "The animal at 3 is a kangaroo and it's the fourth animal" print "The fifth animal is at 4 and it's a whale" print "The animal at 2 is a peacock and it's the ...
"""Script to help user pair executives and employees for lunch""" import csv import os import random from datetime import date import pyinputplus as pyip def assign_level(): return pyip.inputYesNo("is this employee an executive (yes or no): ") def avoid_duplicate_email_addresses(): email_addresses = build_...
import random def display_instruct(): """Display Game Instructions""" def ask_yes_no(question): print "Answer 'yes' or 'no'" answer = raw_input(question) return answer.strip() def ask_number(): print "Select the difficulty setting" print "1) Completely Random" print "2) Goes fo...
#!/usr/bin/env python import bnfo1 def main(): problem1_2_10() def problem1_3_2(): seq = line_to_params('Data/bnfo1_week1/dataset_3_2.txt')[0] print bnfo1.reverse_complement(seq) def problem1_2_10(): text, k = lines_to_params('Data/bnfo1_week1/dataset_2_10.txt') print_list(bnfo1.most_frequent_km...
class Node: def __init__(self, val): self.right = None self.left = None self.val = val def set_left(self, left): self.left = left return self def set_right(self, right): self.right = right return self def to_string(self): i...
def parse(song_text): """ Parses the text of a song that is using a precise notation for notes and gamakams. Returns the string corresponding to the note, along with a list of (note_fraction, wavelength_fraction) tuples, indicating the exact gamakam for that note. Examples: s Sa, f...
first_name=input("enter first name") last_name=input("enter last name") r1=''.join(reversed(first_name)) r2=''.join(reversed(last_name)) print(str(r1)+" "+str(r2))
#VARIABLES d1={'full_name':'Carlos Santos', 'donations': [25.00, 50.00, 100.00]} d2={'full_name':'Esperanza Gomez', 'donations': [10.00, 20.00, 30.00]} d3={'full_name':'Paul Jackson', 'donations': [5.00, 10.00, 15.00]} d4={'full_name': 'Karl Black', 'donations': [100.00, 200.00, 300.00]} d5={'full_name':'Charles Exx',...
import math def l(x1,x2,y1,y2): resultado=math.sqrt((x2-x1)**2+(y2-y1)**2) return resultado x1=int(input("Dime cual es la x en el punto 1")) y1=int(input("Dime cual es la y en el punto 1")) x2=int(input("Dime cual es la x en el punto 2")) y2=int(input("Dime cual es la y en el punto 2")) print(l(x1,x2,y1,y2))
n = int(input("cantidad numeros? =")) j=0 for i in range(1, n+1): x = int(input("dime el " + str(i) + "ºnumero")) if (x==0): j=j+1 print("+un 0") else: print("no es 0") print(j)
i = 0 for numero in 1,2,3,4,5,6,7,8,9,10: i = i+numero print("#",i, "suma de los numeros es", numero)
import time class Node: def __init__(self, data = None, left = None, right = None): self.data = data self.left = left self.right = right def __str__(self): return str(self.data) class BinarySearchTree: def __init__(self, root = None): self.root = root ...
I couldn't seem to find out how to do these, I tried for multiple hours and couldn't seem to find anything online either, so i'm not sure if i was searching for the wrong code but this was probably the closest i could seem to get without using code from more advanced tutorials i watched to try and figure it out. Nev...
#リストLを昇順(小さい順)にソートした結果を返す関数sorted(L)を定義してください #定義もできてません。ギブアップしてしまいまいました。 numberList = [1,2,3,4,5] numberList .reverse() print(numberList)
class TreeNode: """ Definition of TreeNode: """ def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: An object of TreeNode, denote the root of the binary tree. This method will be invoked first, you should design your o...
import time from random import randint from insertion_sort import insertion_sort from shell_sort import shell_sort from merge_sort import merge_sort from selection_sort import selection_sort start = time.time() function_lst = [insertion_sort, shell_sort, merge_sort, selection_sort] sizes = [2 ** i for i in range(7, 16...
from collections import namedtuple, OrderedDict from .pipe import func_pipe @func_pipe def dict_to_object(a_dict, type_name='NamedTuple'): ''' This function converts a dictionary into a namedtuple object. ''' return namedtuple(type_name, a_dict.keys())(**a_dict) @func_pipe def vars_to_object(*ar...
""" Quick & dirt script to convert a Word Docx file to HTML. Requires pypandoc pytidylib (see requirements.txt) """ import argparse import os import sys try: import pypandoc from tidylib import tidy_document except ImportError: print("\n\nRequires pypandoc and pytidylib. See requirements.txt\n\n") def...
''' Generates the fabonacii sequence whoes first term starts with 1 ''' def generate_fabonacii_sequence(upper_limit): f_one = 1 f_two = 2 f_prev_minus_one = f_two f_prev_minus_two = f_one fabonacii = [] if (upper_limit == 1): fabonacii.append(f_one) else: fabonacii.append(...
from numpy import random import string import pandas as pd from general import * NUM_OF_CHARS = 36 #create file random chars def create_file_of_random_chars(size): with open("random_string.txt", "w") as file: for x in range(size): y = random.randint(NUM_OF_CHARS) y =...
class Memoize(object): """ Use as a decorator to cache the results of a function. The function must have the following properties: * No side effects. * Referentially transparent: (see: http://tinyurl.com/reftrans ). * No keyword arguments. While the following are not required for proper behavior, memoiza...
""" Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.""" import time #there must be a pattern that allows more efficient discovery of factors. # Maybe some gains from saving previous numbers and factoring in their multiples? def list_divisors(num): divisors = [] ...
import math primes = {2,3,5,7,11,13} def primechecker(number): global primes for i in range(3, int(math.sqrt(number)) + 1, 2): if number % i == 0: break else: print(number) primes.add(number) def pg_range(m,n): global primes for num in range(m,n+1): if ...
import xmlrpc.client proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") multicall = xmlrpc.client.MultiCall(proxy) n1=float(input("Enter number 1:")) n2=float(input("Enter number 2:")) op=input("Enter the operation(+,-, *,/):") if(op=='+'): multicall.add(n1, n2) elif(op=='-'): multicall.subtract(n1, n...
list = [] while True: num = input("Enter a number: ") if num == "done": break try: val = float(num) list.append(val) except: print('Invalid input') print(list) smallest = list[0] largest = list[0] for x in list: if x > largest: largest = x ...
fname = input("Enter file name: ") if len(fname) < 1: fname = "mbox-short.txt" fh = open(fname) count = 0 for line in fh: line = line.rstrip() print(line) word = line.split() if len(word)<3 or word[0]!='From': print(word[1]) print("There were", count, "lines in the file wit...
s = set() n=int(input('Enter the number of elements')) i = 0 for i in range(n): v=input('Enter the elements') s.add(v) print(s) s=sorted(s) print(s) for x in s:
x=[1,9,5,7,4] print("Entered list :",x) x.sort() print("Sorted list : ",x) y=len(x) print("length of the string : ",y)
n = int(input("Enter the number")) terms = int(input("Enter the power")) result = list(map(lambda x: n ** x, range(terms))) print("The total terms is:", terms) for i in range(terms): print(n," raised to power", i, "is", result[i]) ''' Output: c:\Users\MOHD ZAKI\Desktop\Sem4\python\college\exp3>py lamda.py E...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'rotateLeft' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER d # 2. INTEGER_ARRAY arr # def rotateLeft(d, arr): for i in range(0, d): ...
#!/usr/bin/env python3 import sys from copy import deepcopy def findNextSmallest(cost): _min = sys.maxsize row_col = () for row_num, row in enumerate(cost): for col, num in enumerate(row): if num <= _min: _min = num row_col = (row_num, col) return row_col def lcm(demand, supply, c...
# ###################################################################### # # Unicode & Character Encodings in Python: A Painless Guide # Advanced Python - Brad Solomon May 20, 2019 # https://realpython.com/python-encodings-guide/ # # course_info = """Unicode & Character Encodings in Python: A Painless Guide Advanced Py...
import re # # Part 1: Introduction # # Corey Schafer # Python Tutorial: re Module - How to Write & Match Regular Expressions (Regex) # https://www.youtube.com/watch?v=K8L6KVGG-7o # text_to_search = ''' abcdefghijklmnopqurtuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 Ha HaHa MetaCharacters (Need to be escaped): . ^...
# python strip method import re my_str = "0000000this is string example....wow!!!0000000"; pattern = re.compile(r'0') # matches = pattern.finditer(my_str) # matches = pattern.findall(my_str) matches = pattern.match(my_str) print(matches) # print(matches.strip(0)) # count = 0 # for match in matches: # count += 1 ...
""" CCN.py Version 1.3 - WORKING Script Description : This script runs a simulation of a packet switched network running a flood routing algorithm to deliver packets. Language: Python (3.5.x) Libraries: matplotlib (Please refer to readme...
""" Description Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). """ class ...
""" Descriptioon 347.Top K Frequent Elements Given a non_empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] """ class Solution: def topKFrequent(self, nums, k): """ :type nums: L...
""" No.19 Remove Nth Node From End of List Description Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. """ class Solution: def def removeNthFrom...
""" Description Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5 """ #Definition for singly-linked list. #class ListNode(object): # def __init__(self, x): # self.val = x # self.next = N...
#!/bin/python3 input() num = input() numlist = list(map(int, num.split())) start = numlist[0] rest = numlist[1:] largest = start large = -100 for x in rest: if x == largest: pass elif x > largest: large = largest largest = x elif x > large: large = x else: p...
""" n = int (input("enter any no.")) for i in range(1,11): print(n,"*",i,"=",i*n) """ """ i=0 while (i<=100): print (i) i=i+1 if(i==50): break """ """ def exp(): print("helloworld jsiem imsk xdkci skcnkjfn mcidm") exp() """ """ def add(a,b): print(a+b) add(4,30) """ """...
print "Enter the string" a = raw_input() for i in range(len(a)): for j in range(len(a)): print a[i:j+1]
__author__ = 'anthonylim' ## Anthony Lim # alim4@ucsc.edu # # CMPS 5P, Spring 2014 # Assignment 4=6 # # Frequency # ## from collections import Counter from collections import defaultdict import operator import re alphabet = "abcdefghijklmnopqrstuvwxyz" text_file = open("Output.txt", "w") def main(): # input = ...
# Gradient Descent application for Optimization Problem # using Rosenbrock Function # we ask help for mathematics calculation import numpy as np # First case: we set a=0 and b=100 def DerrivRosenbrock0 ( point ): dx = 2*point[0] - 400*point[0]*(point[1] - (point[0]**2)) dy = 200*(point[1] - (point[0]**2)) ...
# -*- coding: utf-8 -*- class ListNode(object): def __init__(self, val): self.val = val self.next = None def reverse_list(head): reversed_head, prev_node, p = None, None, head while p is not None: p_next = p.next if p_next is None: reversed_head = p ...
# Lambda function to break line l_break = lambda : print('') # Function to add value of its two parameter def add(a, b): return a + b # Call fun add and print result result = add(5, 8) print(result) l_break() # Reference in function def captilize(x): x.capitalize # Test reference value change name = 'R...
def addNumber(x,y): print("Result:", x+y) def minusNumber(x,y): print("Result:", x-y) def multipleNumber(x,y): print("Result:", x*y) def devideNumber(x,y): print("Result:", x/y) addNumber(5,9) minusNumber(3,7) multipleNumber(15,3) devideNumber(100,25)
x = 2 y = 5 if(x < y): print("x was less than y") else: print("x was NOT less than y")
word = "Hypothetically" print(len(word)) print("The second character is: " + word[2])
animals = "dog,cat,bird,turtle,rabbit" animalsList = animals.split(',') print(animalsList)
# получим медиану случайного списка import random import statistics x = random.randint(1, 10) # Добавь N-ое количество элементов numbers = [] for _ in range(x): # Нижнее подчеркивание говорит о том, что нам не интересно # что содержит переменная. Только важно, чтобы цикл отработал # N-ое количество раз n...
# ДЕСКРИПТОРЫ # С помощью дескрипторов мы можем переопределить, что будет происходить с # атрибутами класса class Descriptor: # Что делать при обращении к атрибуту def __get__(self, obj, obj_type): print('get') # Что делать при внесении изменении в атрибут def __set__(self, obj, obj_type): ...
num = int(input()) while num > 1: num /= 2 if num == 1: print("YES") else: print("NO")
n = int(input()) if n % 3 == 0 or n % 5 == 0: print("YES") elif n > 10: print("YES") else: print("NO")
# классы class Human: pass class Robot: """Данный класс позволяет создавать роботов""" class Planet: """Классы Планета""" def __init__(self, name): self.name = name # этот метод не обязательный. Он говорит о том, что если идет обращение # к экземпляру класса, без указания атрибу,...
# Вызов методов из методов class Human: def __init__(self, name, age=0): # Общепринятое соглашение. Если атрибут начинается с нижнего # подчеркивания, значит пользоваться им не рекомендуется. Программист # написал их для себя self._name = name self._age = age def _say(...
# МАГИЧЕСКИЕ МЕТОДЫ class User: def __init__(self, name, email): self.name = name self.email = email def get_email_data(self): return { 'name': self.name, 'email': self.email } jane = User('Jane Doe', 'janedoe@example.com') print(jane.get_email_data(...
a, b, c = (int(input()) for _ in range(3)) print(min(a, b, c), a + b + c - max(a, b, c) - min(a, b, c), max(a, b, c))
# ФУНКЦИИ from datetime import datetime def get_second(): # Начало функции """Return current second""" # Строка документации return datetime.now().second # Что функция будет возвращать x = get_second() # Вызов функции y = get_second.__doc__ # Вызов документации функции z = get_second.__name__ # Вызов...
# СТАТИЧЕСКИЙ МЕТОД class Human: def __init__(self, name, age=0): self.name = name self.age = age @staticmethod def is_age_valid(age): # Статический метод принимает только те аргументы # которые ему передадут. Здесь нет cls или self return 0 < age < 150 # Обращаться к ...
# Операции с числами # Сложение print(1 + 1) # При операции будет целое число print(1 + 2.0) # При операции будет вещественное число # Вычитание print(2 - 1) print(2 - 1.0) # Деление print(10 / 5) # При делении всегда будет вещественное число # Умножение print(2 * 2) # Возведение в степень print(2 ** 3) # Целочислен...
n = int(input()) for i in range(n): for j in range(1, i + 2): print(j, end='') print()
my_text = input() print(my_text[2]) print(my_text[-2]) print(my_text[0:5]) x = len(my_text) print(my_text[0:x - 2]) print(my_text[::2]) print(my_text[1::2]) print(my_text[::-1]) print(my_text[::-2]) print(x)
# Классы. Урок с ютуб class Dog(): """Простая модель собаки""" # Инициализация класса. Задаем атрибуты класса def __init__(self, name, age): """Инициализируем атрибуты. Имя и возраст""" self.name = name self.age = age print("Собака создана") # Объявляем методы класса ...
import argparse parser = argparse.ArgumentParser( description="Prints words with the most anagrams, given list of words.") parser.add_argument('input', default="", help="text file with list of line-delineated words") parser.add_argument('threshold', default=5, help="minimum number of anagrams needed to be pri...
# -*- coding: utf-8 -*- """ Created on Thu Sep 7 10:58:45 2017 @author: ZHENGHAN ZHANG """ #Obtain the date print('Please enter the date') day=int(input('day: ')) month=int(input('month: ')) year=int(input('year: ')) #get the date for today import datetime today=datetime.datetime.today() anotherDate=datetime.datetim...
""" Example of how to use SimAuto methods in Python Developed by PowerWorld 2019, created by Mayank Hirani Script #1: Basic setup and different script commands Includes: Setup, OpenCase(), RunScriptCommand(), CloseCase() """ # Import the win32com library to connect to SimAuto import win32com.client SimAuto ...
""" Program: CS 115 Project 1 Author: Eduardo Roman Description: Using input from the user, this program will calculate the (WCT) of a location using temperature (T) and wind velocity (V). """ import sys def main(): print('==> Windchill Temperature (WTC) Weather Report Calculator <==') num_locations= i...
def solution1(): first_name = input("What is your first name?\n") last_name = input("What is your last name?\n") full_name = f"{first_name} {last_name}" print(f"Your full name is {full_name}") def solution2(): a = 1 b = 2 a, b = b, a print(f"a is {a}, b is {b}") class Actor: def...
def drawboard(kamal): kamal = int(kamal) i = 0 ho = "--- " ve = "| " ho = ho * kamal ve = ve * (kamal+1) while i < kamal+1: print ho if not (i == kamal): print ve i += 1 def checkGrid(grid): # rows for x in range(0,3): row = set([grid[x][0],grid[x][...
#I understood the question differently, yet, this solution is much more complex. a = [1,1,1,2,2,3,3,4,5,6,7,8,9,10,5,5,6] def removeDuplicates(l): b = [] for el in l: count = 0 for check in l: if el == check: count = count + 1 if count > 1: pass ...
import speech_recognition as sr import os import sys import webbrowser def talk(words): print(words) os.system("say " + words) talk("Привет, Я Владислава Масленникова, вы можете спросить меня о чем либо") def command(): r = sr.Recognizer() with sr.Microphone() as source: print("Говорите.....
from turtle import * import random colors = ['red', 'blue', 'green', 'brown'] def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) def gen(): i = 1 while True: yield fib(i) i += 1 def circles(length): if length > 0: circle(length) right(90) ...
import random class Cat: def __init__(self, name="Nyanko", age=1, hair_color="Black"): self.name = name self.age = age self.hair_color = hair_color def ask(self, question): answers = ["The cat doesn't care.","The cat purrs.","The cat walks away.","The cat sleeps."] retu...
import os import argparse def get_file_names(folder_path,out='output.txt'): """Takes a path to a folder and writes all filenames in the folder to a specified output file Parameters: folder_path: The path to the folder out: The name of the output file. Default output.txt """ files = os.lis...
#!/usr/bin/python #Author: Benjamin Ross #Date: 11/15/10, Rev B 2/1/11 """ This is the schedule class, used to schedule the classes. The schedule is a list of lists of chromosomes The length of the list is the number of rooms*number of days*number of hours Each chromosome has a fitness, which is determined like this...
#!/usr/local/bin/python #Author: Benjamin Ross(bpross) #Date: 10/22 """ This file creates a room table for each class. The table is layed out as follows: Time|Room1|.....|RoomN| ---------------------- 8AM | | | | . . . . . 12AM| | | | The first row and column are not used to store fitness val...
user = [] class Account: def __init__(self,number="", name="", balance=0): if(number == ""): self.number = int(input("계좌번호: ")) self.name = input("이름: ") self.balance = int(input("예금: ")) else: self.number = number ...
sum = 0 def substring(s, n): w = 1 sum = 0 while w <= n: i=0 while i <= n-w: print (s[i:(i+w)]) sum += int(s[i:(i+w)]) i += 1 w += 1 return sum # Solving using dynamic programming # Let total number of substrings for a string is # S = s1, s2, ...
import sqlite3 connection = sqlite3.connect("db.sqlite") sql = "INSERT INTO contacts (name, email, phone, address) VALUES (?, ?, ?, ?)" data = ("One", "Two", "Three", "Four") # https://docs.python.org/3.7/library/sqlite3.html with connection: connection.execute(sql, data) # roll back automatically connecti...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def bubble_sort(sequence): for i in range(len(sequence) - 1):# just consider the worst case for j in range(len(sequence) - (i + 1)): if sequence[j + 1] < sequence[j]:# swap position tmp = sequence[j + 1] ...
""" Create a list of vocabs (unique words) from a list of words (wordstream) Also outputs the frequency of words to freqwords.txt Usage: Makevocab.py <wordstream> <output dir> <freq_threshold> [ascii,symbol (filters)] Stdin: N/A Stdout: N/A Other input: wordstream Other output: vocabs, f...
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') df = pd.DataFrame({'Day': [1,2,3,4,5,6], "visitors":[1000, 2000, 5000, 3000, 2000, 4500], "Bounce_rate":[20, 30, 25, 45, 30, 20]}) #df.set_index("Day", inplace...
class Employee: no_of_leaves=8 def printDetails(self): return f"Name is:{self.name}.\nSalary is:{self.salary}.\nRole is:{self.role}." def __init__(self,name,salary,role): self.name=name self.salary=salary self.role=role @classmethod def change_leaves(cls,leaves): ...
f1=open("inputfile.txt") try: f2=open("does.txt") except EOFError as e: print("End of file aagyi bhai") except IOError as e: print("IO error aagyi bhai") except Exception as e: print(e) else: print("This will run only when except isnt running") finally: print("Run this anyway") f1.close() ...
class Employee: no_of_leaves=8 def printDetails(self): return f"Name is:{self.name}.\nSalary is:{self.salary}.\nRole is:{self.role}." def __init__(self,name,salary,role): self.name=name self.salary=salary self.role=role @classmethod def change_leaves(cls,leaves): ...
""" List methods append clear copy count extend index insert pop remove reverse sort """ myList=[2,5,3,4,1,6,7,1,9,0] myList.append("hello") print(myList) print(myList.clear()) myList=[2,5,3,4,1,6,7,1,9,0] print(myList.copy()) print(myList.count(3)) myList.extend([1,2,3,4]) print(myList) print(myList.index(3)) myList.i...
""" Create a library class - displayBook - lend Book - add Book - return Book objectName=Library(listOfBooks,libraryName) """ # can be done """ maintain a dict to associate a book with whom its issued dict-{book,nameOfPerson} """ class Library(): def __init__(self,listOfBooks,libraryName): # super().__init...
# matmat_kij.py # # Daniel R. Reynolds # SMU Mathematics # Math 5316 # Spring 2019 def matmat_kij(A,X): """ Usage: B = matmat_kij(A,X) Function to perform matrix-matrix multiplication with "kij" loop ordering. Inputs: A is a matrix (m x n numpy matrix) X is a matrix (n x p numpy matrix) ...
# matvec_col.py # # Daniel R. Reynolds # SMU Mathematics # Math 5316 # Spring 2019 def matvec_col(A, x): """ Usage: b = matvec_col(A, x) Function to perform column-oriented matrix multiplication Inputs: A is a matrix (m x n numpy matrix) x is a vector (n numpy array) Outputs: ...
user_input=input("Enter a random string: ") print("The first character is: {}".format(user_input[0])) print("The last character is: {}".format(user_input[len(user_input)-1])) print("The middle character is: {}".format(user_input[int(len(user_input)/2)])) print("The even characters are: {}".format(user_input[0::2])) p...
""" Human resources (HR) module Data table structure: - id (string) - name (string) - birth date (string): in ISO 8601 format (like 1989-03-21) - department (string) - clearance level (int): from 0 (lowest) to 7 (highest) """ from model import data_manager DATAFILE = "model/hr/hr.csv" HEADERS = [...
#Guess import random no_guess = 0 name = input("Hi, What's your name?") number = random.randint(1,100) print("Well " + name + " Guess the number I'm thinking of between 1 and 100") while no_guess < 6: print("Take a guess") guess = input() guess = int(guess) no_guess = no_guess + 1 if guess < number: print...
# Q5 check arrays are disjoint or not def are_disjoint(arr1, arr2): for i in range(0, len(arr1)): for j in range(0, len(arr2)): if arr1[i] == arr2[j]: return False return True arr1 = [int(arr1_ele) for arr1_ele in input("Enter array elements separated by ...