text
stringlengths
37
1.41M
''' -Medium- *Backtracking* *Bit Manipulation* A word's generalized abbreviation can be constructed by taking any number of non-overlapping substrings and replacing them with their respective lengths. For example, "abcde" can be abbreviated into "a3e" ("bcd" turned into "3"), "1bcd1" ("a" and "e" both turned into "1...
''' -Medium- You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer. The ith player can match with the jth trainer if the player's ability ...
''' -Medium- Given a list of words and two words word1 and word2 , return the shortest distance between these two words in the list. word1 and word2 may be the same and they represent two individual words in the list. Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Input: _...
''' -Easy- You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An in...
''' -Medium- You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. Th...
''' -Hard- Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alt...
''' -Medium- You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the...
''' -Medium- *BFS* Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values. Two nodes of a binary tree are cousins if they have the same depth with different parents. Return the root of the modified tree. Note that the depth of a node is the number of edg...
''' -Easy- Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each...
''' -Medium- *Prefix Sum* You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2. Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times. ...
''' -Hard- $$$ *BFS* Design the basic function of Excel and implement the function of the sum formula. Implement the Excel class: Excel(int height, char width) Initializes the object with the height and the width of the sheet. The sheet is an integer matrix mat of size height x width with the row index in the ra...
''' -Medium- A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equ...
''' -Medium- You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums...
''' -Medium- You are given a 0-indexed 2D integer array peaks where peaks[i] = [xi, yi] states that mountain i has a peak at coordinates (xi, yi). A mountain can be described as a right-angled isosceles triangle, with its base along the x-axis and a right angle at its peak. More formally, the gradients of ascending an...
''' -Medium- *DP* *Prefix Sum* Given an array of integers arr, return the number of subarrays with an odd sum. Since the answer can be very large, return it modulo 109 + 7. Example 1: Input: arr = [1,3,5] Output: 4 Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,...
''' Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,...
# -*- coding: utf-8 -*- """ Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? H...
''' -Medium- Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes...
''' -Medium- *Greedy* *Set* You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be in the range [1, n]. Each integer can be chosen at most once. The chosen integers should not be in the array banned. The s...
''' -Medium- *Reservoir sampling* Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note: The array size can be very large. Solution that uses too much extra space will not pass the judge. ...
''' -Medium- *DFS* *Backtracking* Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All nu...
''' -Medium- *Topological Sort* There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi. For example, the pair [0, 1] indicates that y...
''' -Hard- *DP* A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences t...
''' -Medium- Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the max...
def median(lst): new_lst = sorted(lst) half_loc = len(new_lst) // 2 if len(lst) % 2 != 0: result = new_lst[half_loc] else: result = (new_lst[half_loc] + new_lst[half_loc - 1]) / 2.0 print (new_lst) return result print(median([7, 12, 3, 1, 6, 8, 9, 10]))
def make_word_dict(): t = {} fin = open('words.txt') for line in fin: word = line.strip().lower() key = tuple(sorted(tuple(word))) if key in t: pass else: t[key] = [] return t def make_word_list(): t = [] fin = open('words.txt') for li...
from inlist import* def reverse_pair(word_list,word): rev_word = word[::-1] return in_bisect(word_list,rev_word) for word in fin: if word[::-1] in d.keys(): rev_words.append(word) return rev_words def make_word_list(): stuff = list(open('words.txt')) fin = map(str.strip, ...
# import our required packages from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import UserMixin, LoginManager from werkzeug.security import generate_password_hash # import python modules for our database models # we'll talk about security in a minute login = LoginManager() ...
#!/usr/bin/python3 Rectangle = __import__('3-rectangle').Rectangle def main(): my_rectangle = Rectangle(2, 4) print("Area: {} - Perimeter: {}".format(my_rectangle.area(), my_rectangle.perimeter())) print(str(my_rectangle)) print(repr(my_rectangle)) print("--") my_rectangle.width = 10 my_...
#!/usr/bin/python3 safe_print_list_integers = \ __import__('2-safe_print_list_integers').safe_print_list_integers my_list = [1, 2, 3, 4, 5] nb_print = safe_print_list_integers(my_list, 2) print("nb_print: {:d}".format(nb_print)) my_list = [1, 2, 3, "Holberton", 4, 5, [1, 2, 3]] nb_print = safe_print_list_integer...
class GameState(object): def __init__(self): self.Board = Gameboard() self.Players = self.initialize_players() def initialize_players(self): positions = [(0, 0), (0, 3), (0, 6), (0, 9), (9, 0), (9, 3), (9, 6), (9, 9)] Players = [] for pos in positions: Players.append(new Player(pos, 10, 1...
import heapq class Node(): def __init__(self, weight, label=None, left_child=None, right_child=None): self.weight = weight self.label = label self.left_child = left_child self.right_child = right_child def merge(self, other): parent_weight = self.weight + other.weight ...
import os from collections import defaultdict import heapq def create_list(file_name): this_folder = os.path.dirname(os.path.abspath(__file__)) my_file = os.path.join(this_folder, file_name) list = [] with open(my_file) as f: for line in f: list.append(int(line.strip())) r...
# Optional Parameteres Tutorial #1 def func1(x=5): return x **2 def func2(word,add=5,freq=2): print(word*(freq+add)) call = func2("indra",0,1) class car(object): def __init__(self,make,model,year,condition="New",kms=0): self.make = make self.model = model self.year = year ...
# Functions def addTwo(x): return x + 2 def subtractTwo(number): return number - 2 def accel(mass,force): a = mass * force return a newNumber = addTwo(7) print(newNumber) def printString(string): print(string) printString("My name is Indra") y = accel(2,3) print(y)
# .strip(), len(), lower(), .upper(), .split() text = input("Please input something :") print(text.split()) # split the string deafult by space print(text.strip()) # clear the last space print(len(text)) print(text.lower()) print(text.upper()) print(text.split(". "))
""" Distribution Plots - Using Seaborn and Python to Visualize Datasets ----------------------------------------------------------------------------- Gianluca Capraro Created: April 2019 ----------------------------------------------------------------------------- This script will demonstrate the use of the Seaborn, Ma...
import string def print_rangoli(size): width = 4 * size - 3 alpha = string.ascii_lowercase print(alpha) for i in list(range(size))[::-1] + list(range(1, size)): print('-'.join(alpha[size-1:i:-1] + alpha[i:size]).center(width, '-')) if __name__ == '__main__': n = int(input()) print_ra...
n = int(input().strip()) if not (n % 2 == 0): print("Weird") elif (2 <= n <= 5): print("Not Weird") elif (6 <= n <= 20): print("Weird") else: print("Not Weird")
from collections import deque d = deque() for i in range(int(input())): command = input().split() if command[0] == 'append': d.append(command[1]) elif command[0] == 'appendleft': d.appendleft(command[1]) elif command[0] == 'pop': d.pop() else: d.popleft() print(' '.j...
def remove(str,start,num): str3="" str1=list(str) for all in range(0,num): for each in range(0,len(str)): if each==start: del str1[each] break for i in str1: str3+=i prin...
# get and print the string in X format for row in range(7): for col in range(7): if row==0 and col==0 or row==0 and col==6: print("a",end="") elif row==1 and col==1 or row==1 and col==5: print("n",end="") elif row==2 and...
def solve(s): s = s.capitalize() kt = False for i in range(len(s)): if (s[i] == " "): kt = True else: if (kt): s = s[:i] + s[i:].capitalize() kt = False return s s = "chris alan 12 alo" print (solve(s))
def split_and_join(line): s = line.split(' ') s1 = "-".join(s) return s1 print (split_and_join('this is a string'))
if __name__ == '__main__': N = int(input()) result = [] for i in range(N): doing, *arr = input().split() arr = list(map(int, arr)) if (doing == "insert"): result.insert(arr[0], arr[1]) elif (doing == "print"): print (result) elif (doing == "rem...
import math ''' convert given latitude or longitude in decimal to radians input params: deg returns coordinates in radians ''' def deg2rad(deg): return float(deg) * (math.pi/180) ''' calculate the distance between dublin and the customer input params: lat1, lon1 (dublin coordinates), lat2, lon2 (customer coo...
def multiply(a, b): return (float(a) * float(b)) def divide(a, b): return (float(a) / float(b)) expr_map = { '*': multiply, '/': divide } def evaluate(routes, route, value): if route not in routes: print 'route: ' + str(route) + ' is not configured in routes' exp = routes[route]...
arr = [2, 1, 3, 13, 5, 17, 67, 1] def change(first, sec): tmp = arr[first] arr[first] = arr[sec] arr[sec] = tmp if __name__ == '__main__': for i in range(1, len(arr)): for j in range(i, 0, -1): if arr[j] < arr[j-1]: change(j-1, j) print('отсортированный массив:...
def centuryFromYear(year): s = str(year) if len(s) == 3 res = int(s[0]) else res = int(s[0:2]) if s[-1] + s[-2] = '00' res += 1 return res
for i in range(3): print(f"to jest iteracja numer {i}") i += 1 film = "Matrix" licznik = 0 for i in film: if licznik % 2: print(i) if i == "i": continue #break# print(i) for index, literka in enumerate(film): print(index, literka) for krotka in enumerate(film, start=...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @return {boolean} def isBalanced(self, root): def getDepth(node): if node == None: ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): if l1 == None: return l2 if l2 ==...
def fibonacci(): x, y = 1, 1 sums = 0 while x <= 4000000: if x % 2 == 0: sums += x x, y = y, x+y return sums print fibonacci()
# csvからデータをとりこんで、コース番号を入力するとそのコースの特定の商品の合計値の10%を計算。 #csvを読み込んで出力する import csv file_path = "コース別商品売上管理表.csv" class itaku_bonus: def __init__(self,course): self.name = course def course_num(self): return self.name def sum(self): with open(file_path, newline='', encoding='utf-8') as...
#!/usr/bin python2.7 # -*- coding:utf-8 -*- # 1观察作用域 '''a = "this is a golbal variable" def foo(): print locals() print globals() foo() ''' # 2命名空间 '''a = "this is a golbal variable" def foo(): #a = "text" #函数内的变量是局部变量是单独定义的新变量和全局变量不是同一个 print locals() print a foo() print a ''' # 3变量生存周期 ''...
game_input = ['Default','-','-','-','-','-','-','-','-','-'] winner = None game_running = True # print(type(game_input)) # ----------------Functions---------------- def gameBoard(): print(game_input[7] + " | " + game_input[8] + " | " + game_input[9] + "\t\t7 | 8 | 9") print("-------------") print(g...
# CURRENTLY EXCLUSIVELY SEARCHES FOR PROPERTIES IN GLASGOW. NEED TO FIND WAY TO DYNAMICALLY GENERATE URL FOR OTHER # LOCATIONS # TODO: Find full post code for property then use that to find price of sold properties for DUV # TODO: Do analysis and write to excel file using openpyxl to automate import requests from requ...
vel = float(input('Qual a velocidade do carro? (km/h): ')) if vel > 80: print('\033[31mVocê foi multado em {:.2f} reais por exceder a velocidade em {} km.\033[m'.format((vel - 80) * 7, vel - 80)) else: print('\033[36mVocê não foi multado.\033[36m')
media = 0 mais_velho = ' ' idade_pessoa = 0 total_mulheres = 0 idade_mulheres = 0 for pessoa in range(1,5): print('----- PESSOA {} -----'.format(pessoa)) nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).strip().upper() if pessoa == 1 and sexo == '...
maior = 0 menor = 0 for c in range(1,6): peso = float(input(f'Digite o peso da {c} pessoa: ')) if c == 1: maior = peso menor = peso else: if peso > maior: maior = peso if peso < menor: menor = peso print(f'O maior peso encontrado foi {maior}Kg;') pr...
nome = str(input('Digite seu nome: ')).upper().strip() nome = ''.join(nome.split()) nomerev = nome[::-1] '''contador = 0 for c in range(len(nome), 0, -1): print(nome[contador], end='') contador += 1''' print(f'O reverso de {nome} é {nomerev}.') if nome == nomerev: print('O nome É um PALÍNDROMO.') else...
nome = str(input('Qual seu nome completo? ')).strip() n = nome.upper().split() print('O seu nome tem Silva? {}'.format('SILVA' in n))
""" This program acts like a sketchbook. Drag the turtle to draw freely on the window. """ import turtle # This function jumps the turtle to the place clicked on the screen. def jump(x, y): turtle.up() turtle.goto(x, y) turtle.down() turtle.reset() turtle.shape("turtle") turtle.pencolor("blue") ...
import tkinter import webbrowser app = tkinter.Tk() # create windows app.title("google finder") # get name search_label = tkinter.Label(app, text="search") # add search text search_label.grid(row=0, column=0) # set search position on grid text_field = tkinter.Entry(app, width=25) # add enter text text_field....
def quickSort(arrList): performQuickSort(arrList,0,len(arrList)-1) def performQuickSort(arrList,start,end): if start<end: splitPoint = partition(arrList,start,end) performQuickSort(arrList,start,splitPoint-1) performQuickSort(arrList,splitPoint+1,end) def partition(arrList,start,end): ...
from QueueApplicationPrograms.RadixSort import RadxiSort class SortingClass: def BubbleSortComplete(self,arrList): for x in range(0,len(arrList)-1): for y in range(0,len(arrList)-x-1): if arrList[y] >= arrList[y+1]: arrList[y],arrList[y+1] = arrList[y+1],arrL...
#!python3 # Python Database API import sqlite3 con = sqlite3.connect('D:\SQL\Ex_Files_SQL_EssT\Exercise Files\db\world.db') cursor = con.cursor() sql1 = 'DROP TABLE IF EXISTS EMPLOYEE' sql2 = ''' CREATE TABLE EMPLOYEE ( EMPID INT(6) NOT NULL, NAME CHAR(20) NOT NULL, AGE INT, SE...
#!python3 import time import calendar ticks = time.time() print("No of ticks since 12:00 am January 1st, 1970 : ",ticks ) print(time.localtime()) local_time = time.localtime(time.time()) print(local_time) # convert time in readable format print(time.asctime(local_time)) # calender related functions calc = cale...
from credentials import Credential class User: """ this class generates new instances of users """ pass users_array = [] def __init__(self, first_name, last_name, phone_number, email, ): self.first_name = first_name self.last_name = last_name self.phone_number = phone...
######################################################## class Node(object): ''' Node object used to create Linked list ''' def __init__(self, data): self.data = data self.next = None def __str__(self): nstr = 'Data:' + str(self.data) nstr += '\n' if (self.next != None): nstr += 'Ne...
# if False: # pass # else: # print("ok") # print("hao") # for i in range(0,10,2): # print(i) # 换行输出 # print(i, end="") # 不换行输出 # print(i, end="|") # 不换行输出,每个字符之间用|隔开 # for j in range(10,0,-2): # print(j,end=",") # 输出 10,8,6,4,2, a=[1,2,0,4,5,6,7,8,9] for i in range(0,len(...
# a=1 # b=0 # c=a/b # 出现异常 # print("haha") # 代码不会被执行 # a=1 # b=0 # try: # c=a/b # except ZeroDivisionError : # print("除数不能为0") # print("haha") # 抛出了异常,代码会被执行 # # # a=1 # b=0 # try: # c=a/b # print(c) # except Exception as e: # print("除数不能为0") # print(e) # division by zero # else: # ...
# # map(func, seq1[, seq2...]) # map()函数是将func作用于seq中的每一个元素, # 并用一个列表给出返回值,如果func为 None,作用同zip()。 # def f(x): return x*x res = map(f, range(10)) mres = list(res) print("map:", mres) # # reduce(func, seq[, init]) # reduce函数即为化简,它是这样一个过程: # 每次迭代,将上一次的迭代结果(第一次时为init的元素, # 如没有init则为seq的第一个元素)与下一个元素一同执行一个二元的func函数。 # fro...
a=int(raw_input()) g=raw_input() #print len(g) b=g.lower() c=set(b) #print len(c),len(b) if len(g)<26: print "NO" if len(g)>=26: if len(c)==26: print "YES" else: print "NO"
import calendar print('Welcome to the Calendar application!') year = int(input('Please enter any year:')) month = int(input('Please enter any month number:')) print(calendar.month(year, month)) print('Have a nice day!')
import itertools as it import math as m def get_next_squared_number(n): # Easy case if n == 1: return 1 # Toggle directions directions = it.cycle([ (+1, 0), # right (0, +1), # up (-1, 0), # left (0, -1) # down ]) neighbors = [ (+1, 0), # ri...
def solve(file): with open(file, 'r') as f: content = f.read() content = content.rstrip('\n') n_digits = len(content) n_digits_half = int(n_digits/2) total = 0 for i in range(0, n_digits_half): if content[i] == content[n_digits_half + i]: ...
import numpy as np def factorial(n): num = 1 if (n != 0): num = n * factorial(n-1) return(num) print(factorial(3))
def sum_n(n): s = 0 for i in range(1,n+1): s+=i return s def sum(n): return n*(n+1)//2 #슬래시 두개는 정수 나눗셈 print(sum_n(10)) print(sum(10))
def hanoi(n, from_pos, to_pos, aux_pos): if n == 1: print(from_pos, "->", to_pos) return else: hanoi(n-1, from_pos, aux_pos, to_pos) print(from_pos, "->", to_pos) hanoi(n-1, aux_pos, to_pos, from_pos) print("n=1") print(hanoi(1,1,3,2)) print("n=2") print(hanoi(2,1,3,2))...
def max_val(a): m = 0 for i in range(len(a)): if m < a[i]: m = a[i] return m def max_index(a): max_idx = 0 for i in range(len(a)): if a[i] > a[max_idx]: max_idx = i return max_idx a = [5, 7, 9, 10, 2, 12, 20, 0] print(max_val(a)) print(max_index(a))
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np ### y = 3x_1 - 2x_2 + 1 데이터 생성 x1 = np.random.rand(100, 1) # 0~1까지 난수를 100개 만든다 x1 = x1 * 4 - 2 # 값의 범위를 -2~2로 변경 x2 = np.random.rand(100, 1) # x2에 대해서도 같게 x2 = x2 * 4 - 2 y = 3 * x1 - 2 * x2 + 1 ### 학습 from sklearn impo...
def makeMatrix(): row = int(input("행의 수 입력 : ")) col = int(input("열의 수 입력 : ")) print() mat = list() for i in range(0, row): tmp = list() tmp = input(str(i+1)+'행의 값을 입력하세요(예, 1 2 3) : \n') tmp = list(map(int, tmp.split(' '))) mat.append(tmp) return mat def pr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 22 10:46:14 2019 @author: markashworth """ """ Program to answer Q's 2 - 6 of Homework 6. """ import matplotlib.pyplot as plt import numpy as np import urllib.request import pandas as pd class NL_linearRegression(object): """ Linear regres...
#2-2) Byte, Kilobyte, Megabyte, Gigabyte converter #Insert bytes and then your program shows many bytes in a kilobyte, megabyte and gigabyte. #You must real mega, giga and tera definations (so for example 2^20 or 2^30) #background information http://www.whatsabyte.com/ #Example output: #Give your input in bytes: 156...
#4-3) list calculation with type detection #calculate sum and average of elements in the list #ignore all values in the list that are not numbers #initializing the list with the following values #list = [1,2,3,4,5,6,7,8,9,20,30, "aa", "bee", 11, "test", 51, 63] #Example Output: #Sum 220/14 and average 15.71 list ...
from important_objects import * import re def tokenize_file(file): file = open(file, "r") result = [] left_parens = 0 right_parens = 0 tmp_lst = [] for line in file: if not line or line[0] == '#' or line[0] == '\n': continue tmp_str = "" ...
from poker_game.config import SetOfCard class Card(SetOfCard): """ mark and number input in Card Attributes ---------- card_mark : int mark(♠︎❤︎♦︎♣️) card_number : int card number """ def __init__(self, card_mark, card_number): """ Parameters ---...
#Tweets lines from a text file #started 26/08/13 #by iceteawithlemon #using python-twitter & python 2.7 import twitter import login #Logs in with your developer credentials c_k, c_s, a_t_k, a_t_s = login.credentials() api = twitter.Api(c_k, c_s, a_t_k, a_t_s) print "\nSuccesfully authentificated.\n" #Opens text file...
""" Utility functions which may be useful for clients. """ import json import Crypto from Crypto.PublicKey import RSA def to_json_string(obj): """Convert basic Python objects into a JSON-serialized string. This can be useful for converting objects like lists or dictionaries into string format, instead o...
again=1 while again==1: arr=["1","2","3","4","5","6","7","8","9"] count=0 while count<9: print "\n ",arr[0]," | ",arr[1]," | ",arr[2]," \n" print " -----|-----|------\n" print " ",arr[3]," | ",arr[4]," | ",arr[5]," \n" print " -----|-----|------\n" print " ",arr[6]," | ",arr[7]," | ",arr[...
import random class GuessGame: def __init__(self, difficulty, user_name): self.difficulty = difficulty self.user_name = user_name self.generated_secret_number = self.generate_number() self.user_input_value = 0 self.result = False def compare_results(self): retu...
import re import sys import random import vector_utils def bool_dist_generator(n): """ Generates a 'n' element vector following uniform boolean distribution Generates random n bit data of count following uniform distribution :param n: number of inputs :return: returns a 'n' element boolean vector ...
#! Python 3 #this program will allow you to enter any block of text and will tweeze out the #phone numbers, the emails, or both depending on what you want import pyperclip, re, os which_thing = input("would you like me to find, email, phone numbers, or both? (P for phonenumbers, E for email, and B for both)") p...
#!/usr/bin/env python # coding: utf-8 # **HR EMPLOYEE ATTRITION DATASET.** # # This is a fictional data set created by IBM data scientists. We need to explore the dataset, understanding the algorithms and techniques which can be applied on it. We' ll try to gain meaningful insights from the dataset, like what are the...
#!/usr/bin/env python # coding: utf-8 # # Predicting Heart Disease # # 1. Data Description # The dataset contains many medical indicators , the goal is to do exploratory data analysis on the status of heart disease. The dataset contains medical history of patients of Hungarian and Switzerland origin. # Its a classif...
#!/usr/bin/env python # coding: utf-8 # # Predicting Health Insurance Costs # ## Introduction # # In this project, we are assigned data about health insurance contractors, and we aim to construct a model that could predict a given contractor's insurance charges. # # ## Exploratory Analysis # # To start, we will pe...
#!/usr/bin/env python # coding: utf-8 # # Analyzing Student's Behavior and Model suggestion for classification levels # ### Marlon Ferrari # > #### This Data Science project was made under Capstone Data Science IBM Certification Program. # ## Table of contents # * [Introduction: Business Problem](#introduction) # * [...
def sumSimple(num1, num2): return num1 + num2 def restSimple(num1, num2): return num1 - num2 def multSimple(num1, num2): return num1 * num2
rows = 50 cols = 50 width = 800 / cols height = 800 / rows # Helper function to determine if given point is in range of grid def in_range(x, y): return 0 <= x < cols and 0 <= y < rows class DFS(): def __init__(self, grid, start_x, start_y, end_x, end_y, screen): self.grid = grid ...