text
stringlengths
37
1.41M
from primes import is_prime x = True y = False z = 0 if z: print("x is false") if x and y or (z and y): print("hello") i = 0 l = [x for x in range(10000) if is_prime(x)] s = "Hello" print(s[::-1]) def fib(n): if n <= 0: return 0 if n == 1 : return 1 if n == 2: return 1 r...
def fib(n): a, b = 1, 1 if n <= 0: return 0 if n == 1 or n == 2: return 1 for i in range(n - 2): temp = b b = a+b a = temp return b
import string def ispanagram(str,alphabet=string.ascii_lowercase): alphaset=set(alphabet) return alphaset<=set(str.lower()) ans=ispanagram('the quick brown fox jumps over the lazy dog') print(ans) #ANOTHER METHOD def panagram(str): alphabet=['a','b','c','d','e','f','g','h','i','j','k','...
import re # string = '*' # match = re.search('*CONUTS', 'COCONUTS') # print(match) txt = "*" # x = re.search("a*", txt) # match = re.search('COCONUTS', '*CONUTS') match = re.search('CA', 'CAT') print(match) x = re.split('(\W*)', '*A*B**CD') string = "*A*B**CD" a = string.split('*') print(a) # *CONUTS # *COCONUTS # *...
# Write a class to hold player information, e.g. what room they are in currently. from item import Item class Player: def __init__(self, name, current_room, inventory=[]): self.name = name self.current_room = current_room self.inventory = inventory # List player's inventory def pr...
from collections import Counter import math def load_data(): with open("inputs/day_3_input.txt") as f: return [item.strip() for item in f.readlines()] def get_column_multiplier(row_size, column_size, row_step_size, column_step_size): steps_to_bottom = math.ceil(row_size / row_step_size) minimum_...
from typing import Dict, List import math def load_data() -> List[str]: with open("inputs/day_5_input.txt", "r") as f: return [item.strip() for item in f.readlines()] def binary_partition(instruction: str, bottom: int, top: int) -> Dict[str, int]: if instruction in ["F", "L"]: return {"top":...
import numpy as np import matplotlib.pyplot as plt def plotLineGraph(stat,iterations): x = np.arange(iterations) plt.plot(x,stat[:,0]) plt.plot(x,stat[:,1]) plt.plot(x,stat[:,2]) plt.legend([str(stat[-1,0])+' Games Won By Bot 1', str(stat[-1,1])+' Games Won By Bot 2', str(stat[-1,2])+' Games Draw'], loc='upper le...
def print_name(x): name=input("your name:") print(name*x)
import speech_recognition as sr r = sr.Recognizer() # Works as a recognizer to recognize our audio with sr.Microphone(device_index = None) as source: # Initializing our source to sr.Microphone() print('Speak Anything : ') r.adjust_for_ambient_noise(source, duration = 5) # Using the ambient noise suppre...
# # # def test(x,y): #define function # # # print(x,y) # # # test(10,20) #calling function # # # def users(name,age): # # # get_name=f'your name is {name}' # # # get_age=f'age {age}' # # # return [get_name, get_age] # # # data = users('ram', 20) # # # print(data[0]) # # # print(data[1]) # # # #lambd...
import sys digit_string = sys.argv[1] count = 0 for i in range(0, len(digit_string)): count += int(digit_string[i]) print(count) # tutors' solution # import sys # print(sum([int(x) for x in sys.argv[1]]))
# ํ•™์ƒ 5๋ช…์˜ ์ˆ˜ํ•™ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅ ํ›„ ํ‰๊ท  ๊ฐ’์ด 80์  ์ด์ƒ์ด๋ผ๋ฉด PASS, ์•„๋‹ˆ๋ผ๋ฉด Try Again์„ ์ž…๋ ฅํ•˜๊ธฐ total = 0 studentList = {} print("์ฒซ ๋ฒˆ์จฐ ํ•™์ƒ์˜ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”") studentList[0] = int(input()) print("๋‘ ๋ฒˆ์จฐ ํ•™์ƒ์˜ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”") studentList[2] = int(input()) print("์„ธ ๋ฒˆ์จฐ ํ•™์ƒ์˜ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”") studentList[3] = int(input()) print("๋„ค ๋ฒˆ์จฐ ํ•™์ƒ์˜ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”") studentList[4] = int(input(...
# ํ˜•๋ณ€ํ™˜ # ๋ณ€์ˆ˜๋ฅผ ๋ฌธ์ž์™€ ์ •์ˆ˜๋กœ ์ดˆ๊ธฐํ™” var1 = '123' var2 = 123 # ๋ฌธ์ž์™€ ์ •์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ง์…ˆ ์—ฐ์‚ฐ์„ ์‹œ๋„ํ•˜๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค # print(var1+var2) # ๋ฌธ์ž(์—ด)๋ฅผ ์ •์ˆ˜๋กœ ๋ณ€๊ฒฝ # ๋ฌธ์ž(์—ด)๋ฅผ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด ์ •์ˆ˜์˜ ๋ง์…ˆ ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. print(int(var1)+var2) # ์ •์ˆ˜๋ฅผ ๋ฌธ์ž(์—ด)๋กœ ๋ณ€๊ฒฝ # ์ •์ˆ˜๋ฅผ ๋ฌธ์ž(์—ด)๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด ๋ฌธ์ž์˜ ๋ง์…ˆ ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. print(var1+str(var2)) # 'hello'๋Š” ์ •์ˆ˜๋กœ ํ˜•๋ณ€ํ™˜๋ ์ˆ˜์—†๋‹ค. # print(int('hello'))
#Find all occurences of a single lowercase letter inbetween 3 uppercase letters import re pattern = re.compile('[a-z]+[A-Z]{3}[a-z]{1}[A-Z]{3}[a-z]+') junkfile = open("ch3_junk.txt", "r") junk = junkfile.read() junkfile.close() result = pattern.finditer(junk) if result: for match in result: pri...
#!/usr/bin/env python # -*- coding: utf8 -*- import re FILE = r'examples.txt' utfCheck = re.compile('[^\d]') f = open(FILE, 'r') msg = f.read().strip() msgList = list(msg) words = [] tmp = [] cnt = 0 for i in range(len(msgList)): if utfCheck.search(msgList[i]): tmp.append(msgList[i]) cnt += 1 if cnt ==...
# Enter your code here. Read input from STDIN. Print output to STDOUT t=int(input()) while t>0: t -=1 ss=input() x="" y="" for i in range(len(ss)): if(i%2==0): x += ss[i] else: y += ss[i] print(x, y, end=" ") print()
# General implementation for Knuth Morris Pratt Pattern Searching algorithm. # This algorithm is used to find a pattern or substring in an array/string def kmp(s): """ Given a concatenated string s with unique identifier, return a table F such that F[i] is the longest proper prefix of s[0..i] as well as ...
class Solution(object): def minDistance(self, word1, word2): m, n = len(word1), len(word2) # initialize dp matrix dp = [[0 for i in range(n + 1)] for j in range(m + 1)] # Build up dp bottom up for i in range(m + 1): for j in range(n + 1): ...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
import time import random import timeit def sequential_search (a_list, item): start_time = time.time() pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos+1 return found, (time.time() - start_time)...
""" The Partition Table encoding method is used for a segment that appears in the URI as a pair of variable-length numeric fields separated by a dot (โ€œ.โ€) character, and in the binary encoding as a 3-bit โ€œpartitionโ€ field followed by two variable length binary integers. The number of characters in the two URI fields a...
#Purpose: function to make question into tags #Joe Burg import string def parse_question(question): get_tags = question.strip().split() parsed_question = [] for tag in get_tags: clean_tag = tag.translate(string.maketrans("",""),string.punctuation) parsed_question.append(clean_tag) ...
#Purpose: check question's tags against users list to see who it's relevant to #Joe Burg from parse_question import parse_question from import_data import import_data ################################################################### question = raw_input('What is your question: ') #import the user IDs user_IDs = []...
#Purpose: parse a wiki page for tags #Joe Burg import re ############################################################################ def digit_check(word): for i in range(len(word)): if word[i] in '0123456789': return False else: return True ############################...
#Purpose: parse a wiki page for tag; filter common words #Joe Burg import re ############################################################################ number = input('What number file is this? ') all_words = [] for i in range(100): print 'Scanning page '+str(i) if i<10: filename = 'wiki_0'+str(i) ...
""" An Doan Lopez Gerardo CECS 575 - Assignment 1 September 17, 2021 """ # Node class class Node: def __init__(self, data_value = 0): self.data = data_value self.left_child = None self.right_child = None # accessor funtions for Node class def get_data(self): return self.data def g...
class Stack: def __init__(self): self.len = 0 self.list = [] def push(self, num): self.list.append(num) self.len += 1 def pop(self): if self.size() == 0: return -1 pop_result = self.list[self.len - 1] del self.list[self.len - ...
# S3C2 Laurel Kuang def Events(): print("A:PressStartButton B:EnterPin C:ActivateSensor") def PressStartButton(state): if state==SystemInactive: state=SystemActive print(state) return state def EnterPin(state, timer): if state==SystemActive: state=SystemInactive elif state...
# S3C2 Laurel Kuang def BubbleSort(List): while len(List)>0: for i in range(len(List)-1): if List[i]>List[i+1]: List[i],List[i+1]=List[i+1],List[i] len(List)=len(List)-1 return List
import json # Python script showing use of json package def get_string(): # Creating and initializing variables file = "myScript.py" name = "Osebi Adams" Id = "HNG-04874" email = "ijese.company@gmail.com" language = "Python" status = "Pass" output = ("Hello World, this is %s with HNGi...
temp = eval(input('Enter a temperature in Celsius: ')) fr = 9/5*temp +32 print("test input",fr) print("test if") if fr > 10: print('fr>10',fr) elif fr < 10: print('fr<10',fr)
import time import os prime_numbers = [2] number_to_check = 3 not_prime = False start_time_again = True number_of_prime = 0 primes_a_second = 0 print("Prime --> 1") print("Prime --> 2") while True: #os.system("clear") if start_time_again == True: start = time.time() start_time_again = False f...
#!/usr/bin/env python test_string = [ "foo", "bar", "baz", "quux" ] #print("\t".join( test_string)) def print_sep( a_string, sep = "\t" ): print( sep.join( a_string ) ) print_sep( test_string ) print_sep( test_string, " - " )
from sys import argv #list container lista = ["Red", "Black", "White", "Gray", "Green" ] ##List Comp. lista2 = [i for i in range(1, 101) if i%2==0 ] listaEvenOdd = [ [i for i in range(1, 101) if i%2==0 ], [i for i in range(1, 101) if i%2!=0 ] ] print(listaEvenOdd) if __name__ == "__main__": ...
#Image Processing Module #Task1:Access Pixels #28/09/2020 #Laura Whelan ######### import the necessary packages: ######### import cv2 import numpy as np from matplotlib import pyplot as plt from matplotlib import image as image import easygui ######### Task ######### #1.Read in any image (this is...
import numpy as np class Ordered_Vector: def __init__(self, capacity): self.capacity = capacity self.last_position = -1 self.vals = np.empty(self.capacity, dtype=int) # O(n) def display(self): if self.last_position == -1: print('The vector is empty') e...
def hist(sample): """Plots a histogram based on a user specified origin and bandwidth. Plots a histogram, a jagged density estimator, of a given sample with a user specified origin and bandwidth, after checking if the sample is valid. ARGS: sample: data desired to create a histogram fo...
import math import time def timing_average(func): def wrapper(x, y): t0 = time.time() res = func(x, y) t1 = time.time() print("It took {} seconds for {} to calculate the average".format(t1-t0, func.__name__)) return res return wrapper def check_positive(func): def f...
class Tile(object): """Class for map Tiles""" width = 70 # tile width in pixels def __init__(self, x, y, height, fixed): super(Tile, self).__init__() # self.rotate = rotate self.speed = speed self.x = x self.y = y self.height = height self.fixed = fixed def getCollision(self): """Summary Retur...
# -*- coding: utf-8 -*- __author__ = "karnikamit" import re def replace1(match): return match.group(1)+'_'+match.group(2).lower() def convert_to_snake_case(var): return re.sub(r'(.)([A-Z])', replace1, var) def replace2(match): return match.group(2).upper() def cov_back_to_camel_case(var_name): s...
__author__ = 'karnikamit' ''' Move spaces in a given string to the front ''' def move(string): count = 0 for character in string: if character == ' ': count += 1 string = string.replace(" ", "") spaces = " "*count # This is done because 'str' object does not support item...
# -*- coding: utf-8 -*- __author__ = 'karnikamit' ''' given an array, find the largest good subset. A good subset is when the integers in the selected subset, divides every other number. ie array[i]%array[j] == 0 or array[j]%array[i] == 0 ''' size_of_array = input("Size of array") array = [] for i in xrange(size_of_ar...
# -*- coding: utf-8 -*- __author__ = 'karnikamit' cases = int(raw_input()) for _ in xrange(cases): ip_string = raw_input() if ip_string == ip_string[::-1]: print 'YES {}'.format('EVEN' if len(ip_string) % 2 == 0 else 'ODD') else: print 'NO'
__author__ = 'karnikamit' def merge(x, y): """ :param x: sorted list :param y: sorted list :return: merge both sorted list to one new list """ result = [] i = 0 j = 0 while True: if i >= len(x): # If xs list is finished, result.extend(y[j:]) # Add re...
# -*- coding: utf-8 -*- __author__ = 'karnikamit' ''' https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/pair-sums/ ''' N, K = map(int, raw_input().split(' ')) array = map(int, raw_input().split(' ')) assert len(array) == N def pair_sum(array, k): ""...
# -*- coding: utf-8 -*- __author__ = 'karnikamit' def find_max_sub_array_sum(array, mod_operand): current, result = array[0], 0 for i in xrange(1, len(array)-1): current = max(array[i], current+array[i]) mod_sum = current % mod_operand if mod_sum > result: result = mod_sum ...
__author__ = 'karnikamit' a1 = [1, 2, 3, 4, 5] b1 = ['a', 'b', 'c', 'd', 'e'] def create_dict(a, b): """ :param a: :param b: :return:this function creates a dictionary from given two lists, it prepares a dict by considering the length of the lists. it prepares the dict only to the items pres...
__author__ = 'karnikamit' import sys from time import sleep def stack(): work = ['1. Add to Stack', '2. Pop from stack', '3. Print stack', '4. Exit'] stack_list = list() flag = True while flag: for w in work: print w q = int(raw_input('What do you want to do? ')) if...
# -*- coding: utf-8 -*- __author__ = 'karnikamit' ''' https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/xsquare-and-double-strings-1/ ''' def is_double_string(s): """ :param s: special string S consisting of lower case English letters. :retu...
# import os # list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] # tuple1=tuple(list1) # print(list1) # print(tuple1) # basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} # print(type(baske # !/usr/bin/python3 # -*- coding: UTF-8 -*- # Filename : test.py # author by : www.runoob.com # Python ๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ—ๅฎž็Žฐ # ่Žท...
#1.1 ็Žฐๆœ‰ๅญ—ๅ…ธ dict={โ€˜aโ€™:24๏ผŒโ€˜gโ€™:52๏ผŒโ€˜iโ€™:12๏ผŒโ€˜kโ€™:33}่ฏทๆŒ‰ๅญ—ๅ…ธไธญ็š„ value ๅ€ผ่ฟ›่กŒๆŽ’ๅบ๏ผŸ dict={'a':'24','g':'52','i':'12','k':'33'} print(sorted(dict.items(),key=lambda x:x[1])) #่ฏทๅ่ฝฌๅญ—็ฌฆไธฒโ€œsStrโ€ print("sStr"[::-1]) # ๅฐ†ๅญ—็ฌฆไธฒโ€k:1|k1:2|k2:3|k3:4โ€๏ผŒๅค„็†ๆˆPythonๅญ—ๅ…ธ๏ผš{k:1๏ผŒ k1:2๏ผŒ โ€ฆ } # ๅญ— ๅ…ธ้‡Œ็š„Kไฝœไธบๅญ—็ฌฆไธฒๅค„็† str1 = "k:1|k1:2|k2:3|k3:4" def srt2dict(str1): dict={} ...
ipk = float(input("Masukkan IPK: ")) if (ipk>3.51 and ipk<4.00): print("Dengan pujian") elif (ipk>2.76 and ipk<3.50): print("Sangat memuaskan") elif (ipk>2.00 and ipk<2.75): print("Memuaskan") 1.start 2.input (ipk) 3.if ipk>3.51 and ipk<4.00: 4. output (Dengan pujian) 5.elif ipk>2.76 and ipk<3.50: ...
import numpy as np numeros = np.array([1, 3.5]) print(numeros) numeros += 3 print(numeros)
idades = [15, 87, 32, 65, 56, 32, 49, 37] #idades = sorted(idades) #print(sorted(idades, reverse=True)) # print(list(reversed(idades))) idades.sort() idades= list(reversed(idades)) print(idades)
def cons(x,xs=None): return(x,xs) def lista(*xs): if not xs: return None return cons(xs[0],lista(*xs[1:])) def head(xs): return xs[0] def tail(xs): return xs[1:] def is_empty(xs): return xs is None def last(xs): if is_empty(tail(xs)): return cons(head(xs)) return last(tail(xs)) def concat(xs,yx): if is_emp...
def triplets(arr): n = len(arr) sum,sum2,count=0,0,0 for i in range(n): sum = arr[0] arr.pop(0) for j in range(n-1): sum2 = arr[j]+arr[j-1] if(sum2 == sum): count +=1 arr.append(sum) return count T = int(input()) lst = [] for i in r...
#Sฤƒ se afiลŸeze cel mai mare numฤƒr par dintre doua numere introduse รฎn calculator. n1=int(input("introduceti nr 1: ")) n2=int(input("introduceti nr 2: ")) if ((n1%2==0)and(n2%2==0)): if (n1>n2): print(n1) else: print(n2) if ((n1%2==0)and(n2%2!=0)): print(n1) if ((n1%2!=0)and(n2%2==0...
#Se introduc trei date de forma numฤƒr curent elev, punctaj. AfiลŸaลฃi numฤƒrul elevului cu cel mai mare punctaj. e1=int(input("nr. elev")) e2=int(input("nr. elev")) e3=int(input("nr. elev")) p1=int(input("introduceti punctajul primului elev")) p2=int(input("introduceti punctajul elevului al doilea")) p3=int(input("i...
# Small exercise 5 numbers = [-2, -1, 0, 1, 2, 3, 4, 5, 6] for value in numbers: if value > 0: print(value) #Small exercise 6 new_list = [] for value in numbers: if value > 0: new_list.append(value) print(new_list)
""" You work on a team whose job is to understand the most sought after toys for the holiday season. A teammate of yours has built a webcrawler that extracts a list of quotes about toys from different articles. You need to take these quotes and identify which toys are mentioned most frequently. Write an...
# Google Question # Given an array = [2,5,1,2,3,5,1,2,4]: # It should return 2 # Given an array = [2,1,1,2,3,5,1,2,4]: # It should return 1 # Given an array = [2,3,4,5]: # It should return undefined #function firstRecurringCharacter(input) #} # Bonus... What if we had this: # [2,5,5,2,3,5,1,2,4] # return 5 becaus...
# Different way to traversal a matrix with equal # LEFT TO RIGHT ---> # Left to Right equals row, than column def matrix_traversals_left_to_right(matrix): arr = [] for row in range(len(matrix)): for column in range(len(matrix[0])): value = matrix[row][column] arr.append(value) ...
def is_palindrome(string): reversed_string = string[::-1] if string == reversed_string: return True return False if __name__ == '__main__': results = is_palindrome("abcdcbad") print(results)
# Given two strings s and t , write a function to determine if t is an anagram of s. def is_valid_anagram(s, t): if len(s) != len(t): return False s_dict = {} t_dict = {} for i in range(len(s)): char = s[i] if char not in s_dict: s_dict[char] = 1 else: ...
def initialize_union(my_dict, x, y): if x not in my_dict: my_dict[x] = x if y not in my_dict: my_dict[y] = y def initialize_size(my_dict, x, y): if x not in my_dict: my_dict[x] = 1 if y not in my_dict: my_dict[y] = 1 def get_root(arr, i): while arr[i] != i: ...
def spiralMatrixPrint(row, col, arr): # Defining the boundaries of the matrix. top = 0 bottom = row-1 left = 0 right = col - 1 # Defining the direction in which the array is to be traversed. dir = 0 while (top <= bottom and left <=right): if dir ==0: for i in range(...
""" Write a function that takes in a "special" array and returns its product sum. A "special" array is a non-empty array that contains either integers or other "special" arrays. The product sum of a "special" array is the sum of its elements, where "special" arrays inside it should be summed themselves and then multip...
""" Given a 2D grid, each cell is either a zombie or a human. Zombies can turn adjacent (up/down/left/right) human beings into zombies every day. Find out how many days does it take to infect all humans? Input: matrix, a 2D integer array where a[i][j] = 1 represents a zombie on the cell and a[i][j]...
""" You're given a <span>Node</span> class that has a <span>name</span> and an array of optional <span>children</span> nodes. When put together, nodes form a simple tree-like structure. Implement the <span>depthFirstSearch</span> method on the <span>Node</span> class, which takes in an empty array, traverse...
# Peak Valley Approach # initial index, peak, valley, max_profit variables # iterate over prices # iterate to find peaks and valleys # while if price[i] >= price[i + 1] increment index by one # define valley based off the condition # while if price[i] <= price[i + 1] increment index by one # define peak based off th...
class AIBoard: def __init__(self, board): self.board = board def make_move(self): # assuming this is legal move if not self.board.is_board_full(): # get all value with dashes. print() else: raise Exception('Can not make move') ...
""" You are on a flight and wanna watch two movies during this flight. You are given int[] movie_duration which includes all the movie durations. You are also given the duration of the flight which is d in minutes. Now, you need to pick two movies and the total duration of the two movies is less than or equal to (d - 3...
# Quick script to parse nmap (.gnmap) files: IP/Port -> URL # Normally this gets leveraged as input to another tool like -> whatweb # # Example: ~$ python parse_nmap.py nmap_results.gnmap # https://10.10.146.1 # http://10.10.146.1 # https://10.10.146.67 # http://10.10.146.75:8080 # https://10.10.146.100 # http://10.10....
from tkinter import * from time import strftime window = Tk() window.geometry("300x75") window.configure(bg="black") space = " " window.title(space+"DIGITAL CLOCK") def clock(): time = strftime('%H:%M:%S %p') label = Label(frame, font=('arial', 20, 'bold'), text=time, fg="white", bg=...
# Implementation of heap from list in Python class Heap(object): def __init__(self): self.list = [] self.last_index = -1 def insert(self, x): self.last_index += 1 if not self.list: self.list.append(x) return self.list.append(x) index = s...
import pandas as pd from nba_api.stats.endpoints import boxscoretraditionalv2, teamgamelog def get_team_info(game_id, season, season_type): # Create Box Score Traditional Object and get DataFrame # print(type(game_id)) traditional = boxscoretraditionalv2.BoxScoreTraditionalV2(game_id=game_id) teams_df...
import pandas as pd import pdb # Blocks Value Structure block_before_turnover = .5 block_with_rebound = .9 #defense_value = 2.2 # Possession value can be subtracted by this for an alternate way of evaluating. This makes the assumption that blocking something is stopping a field goal that is likely to go in, rather th...
'''This is a solution to a given Problem statement: Write a function record_notes() that does the following A. First asks the user's name. B. Asks the user to enter a single-line note. After the user enters the note, it is stored in USERNAME_notes.txt on a newline. C. Keeps asking the user to enter a note in a loo...
# my_stuff={"key1":123,'key2':"value2","key3":{'123':[1,2,"grabme"]}} # print(my_stuff["key3"]['123'][2].upper()) mystuff={'lunch':'puri','bfast':'eggs'}
import turtle from math import sqrt, sin, cos, pi tela = turtle.Screen() eletron = turtle.Turtle() eletron.shape('circle') eletron2 = turtle.Turtle() eletron2.shape('circle') a = 100 a2 = 50 b = a/2 b2 = a2*2 eletron.up() eletron.setpos(a,0) eletron.down() eletron2.up() eletron2.setpos(a2,0) eletron2.down() '''whil...
with open('../resources/input_day_2.txt', 'r') as input_file: entries = [] for line in input_file.readlines(): character_condition = line.split(':')[0] entries.append({ 'password': line.split(':')[1].strip(), 'needed_character': character_condition.split(' ')[1], ...
""" Created on 16/12/2019 @author: Sunny Raj """ """ problem statement: Write a program to multiply matrices """ #method to setup the value of row and column for input matrices def criteria_setup(): while True: try: value=int(input()) break except ValueError: pri...
#importing necessarry libraries #importing flask , jsonify,request from flask import Flask, jsonify, request import pymongo #seeting name to run this file as flask app app = Flask(__name__) #making a mongo db client to interact eith mongodb server myclient = pymongo.MongoClient("mongodb://localhost:27017/") #making a...
tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5]) tup1 = (12, 34.56) tup2 = ('abc', 'xyz') # Following action is not valid for tuples # tup1[0] = 100; # So let's create a new tuple as follows tup3 = tup1 + tup2 pri...
def is_ugly(num, divisor): print(f"Divisor is {divisor}") if(divisor <= 1 ): return True if( (num % divisor == 0 and divisor not in [2,3,5]) or (divisor in [2,3,4] and num % divisor != 0) ): return False return is_ugly(num, divisor-1); number = int(in...
degreeF = float(input("Enter temperature in degree F ")) degreeC = (5/9)*(degreeF - 32) print(f" Converted value is {degreeC} ")
import sqlite3 class database: def __init__(self, db_name): self.conn = sqlite3.connect(db_name) self.cur = self.conn.cursor() def create_table(self, table_name, cols): if len(cols) > 0 and bool(table_name): command = f'create table if not exists {table_name}(' ...
# # import libraries from urllib.request import urlopen from bs4 import BeautifulSoup quote_page = "https://en.wikipedia.org/wiki/Ada_Lovelace" # # query the website and return the html to the variable page page = urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') name = soup.find(attrs={'id': 'firstHead...
""" Implementation of Sequential Backward Selection Python Machine Learning Ch 4 """ import numpy as np from sklearn.base import clone from itertools import combinations from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score class SBS(): def __init__(self, estimator, k_feat...
# Convert WAV file(s) to MP3 using Pydub (http://pydub.com/) # Imports import os import pydub import glob # Load local WAV files(s) wav_files = glob.glob('../test/*.wav') # Iterate and convert for wav_file in wav_files: mp3_file = os.path.splitext(wav_file)[0] + '.mp3' sound = pydub.AudioSegment.from_wav(wav...
import numpy as np contador = np.arange(10) km2 = np.array([44410., 5712., 37123., 0., 25757.]) anos2 = np.array([2003, 1991, 1990, 2019, 2006]) dados = np.array([km2, anos2]) item = 6 index = item - 1 print(contador[index]) print(dados[1][2]) # array[linha][coluna]
class Stack: def __init__(self): self.items = [] self.length = 0 def push(self, val): self.items.append(val) self.length += 1 def pop(self): if self.empty(): return None self.length -= 1 return self.items.pop() ...
# Joshua Chan # 1588459 import datetime items_list = [] manufacturer_file = input("Enter the filename of Manufacturers List") with open(manufacturer_file) as file: data = file.readlines() for row in data: row_dict = dict() fields = row.split(',') row_dict['item_id'] = fields[...
'''Python file for the pre_order traversal This is a helper class used to generate the pre-order traversal of a given ast ''' from ...nodes import AST from ...nodes import Number_Node, String_Node, UnaryOp_Node, BinaryOp_Node, Function_Node from .traversal import Traversal class PreOrderTraversal(Traversal): def...
'''Python file for common algorithms Mainly used to store algorithms written to make usage more convenient ''' def bin_to_decimal(s: str): ''' Helper function that takes in a binary string and returns the converted decimal number ''' for c in s: assert c in set(['.', '1', '0']) decimal_val...
'''Python file for compiler's lexer This contains the Lexer class which handles turning the input text(raw expression) into a series of tokens ''' # Importing token types from ..tokens import Token from ..tokens.token_type import PLUS, MINUS, MUL, DIV, MODULUS, INT_DIV, POWER, LPARAM, RPARAM, COMMA, EOF from ..tokens...
""" # ะ—ะะ”ะะงะ ะ q = int(input()) w = int(input()) e = int(input()) r = int(input()) t = (min(q,w,e,r)) print(t) """ """ # ะ—ะะ”ะะงะ B w = int(input()) s = int(input()) print(w**s) """ """ # ะ—ะะ”ะะงะ C r = int(input()) e = int(input()) f = r ^ e print(f) """
import math import random #### Section 1: Measures of Variance and Central Tendancy ## mean, median, mode, standard variance, standard deviation, and confidence interval def mean(data): """The mean or average of a set of data is the sum of all data points divided by the amount of data points. """ i...
# Official Name: Janet Lee # Lab section: M3 # email: jlee67@syr.edu # Assignment: Assignment 2, problem 1. # Date: September 10, 2019 # Compute a receipt for Gracie's Garden Store print("Welcome to Gracie's!") print("Let the sun shine in!") print() print("For each item, enter the quantity, then press ENTER"...