text
stringlengths
37
1.41M
import time def convert_timestamp(time_string): """ Convert a string timestamp to a python time object. :param time_string: Timestamp from 'time' column in data_raw sheet. :return: Time object representing provided timestamp. """ return time.strptime(time_string, '%H:%M:%S.%f') def compose_t...
# !/bin/python3 import os import sys # Problem taken from hackerrank # Link: https://www.hackerrank.com/challenges/drawing-book/problem # # Complete the pageCount function below. # def pageCount(n, p): page_turns = 0 if n in [2, 3]: return page_turns page_turns = n // 2 + 1 pt_from_start_un...
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): sea_level = 0 valleys_crossed = 0 is_in_valley = False for char in s: if char == 'D': sea_level -= 1 else: sea_lev...
# input n = 10 x = "3 7 8 5 12 14 21 13 50 18".split(" ") # Step 1: get the input # n = int(input()) # x = input().split(" ") # Step 2: transform and sort values xlist = [int(i) for i in x] xlist.sort() # Step 3: find the median def findm(lval): if lval: if len(lval) % 2 == 1: return lval[le...
def swap_case(s): output = [] if 0 < len(s) <= 1000: for c in s: if c.isalpha() and c.isupper(): output.append(c.lower()) elif c.isalpha and c.islower(): output.append(c.upper()) else: output.append(c) return ''.join...
if __name__ == '__main__': N = int(input()) data = [] commands = ['insert', 'print', 'remove', 'append', 'sort', 'pop', 'reverse',] for _ in range(N): com = input().split() if com[0] in commands and len(com) == 3: eval("data."+ com[0] + "(" + com[1] + "," + com[2] +")" ) ...
def first_not_repeating_character(s): d = {} for char in s: if char not in d: d[char] = 0 d[char] += 1 for key in d: if d[key] == 1: return key return "_"
import math def distance(a=(0, 0), b=(0, 0)): """Returns the distance between two points""" return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
import numpy as np import matplotlib.pyplot as plt def plotMeanVsN(): """ For different values of N, sample N uniformly random numbers in [0, 1) and plot their mean. Demonstrates the central limit theorem, which says that as N gets larger, the distribution of the sum (or mean) of the variables approach ...
import sys def add(a, b): try: a = int(a) b = int(b) return a + b except ValueError: return "Invalid arguments" try: print(add(sys.argv[1], sys.argv[2])) except IndexError: print("Not enough arguments")
# avery cunningham # Scrooge McDuck's Bank class Bank: def __init__(self, name, accounts, owner): self.name = name self.accounts = accounts self.owner = owner def withdraw(self, account, amount): print(f"{account.name} is withdrawing ${amount}") if amount > 0.1 * accou...
""" Description: - A class to define its structure - A class to define its functionality """ from builtins import len class Node: def __init__(self, data=None, prev=None, next=None): self.prev = prev self.data = data self.next = next class LinkedList: def __init__(self): ...
N = int(input()) S = input() count = 0 ans = 0 for n in S: if n == "A": count = 1 elif count == 1 and n == "B": count += 1 elif count == 2 and n == "C": ans += 1 count = 0 else: count = 0 print(ans)
print("hello world good good study day day up") # 注释:int整数类型:不带引号的阿拉伯数字的整数 作用:可以做数学运算 # num1=10 # num2=22 # print(num1+num2+12) # float字符数
def product(par1, par2): a = 1 b = 2 # print("-" * a) c = par1(a, b) d = par2(a, b) result = c * d print(result) # print("-" * b) product(lambda a, b: a + b, lambda a, b: a ** b) product(lambda a, b: a - b, lambda a, b: a / b) product(lambda a, b: a ^ b, lambda a, b: a % b)
# i = 0 # while i <= 3: # print(i) # i += 1 # i = 0 # result = 0 # while i <= 10: # result = result + 2 # i += 1 # print(result) # i = 1 # result = 0 # while i <= 10: # result = result + 2 # i += 2 # print(result)
def bubbleSort(array): """冒泡排序""" for i in range(len(array) - 1, -1, -1): for j in range(i): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return[array] array1 = [2, 1, 5, 3, 8, 1, 2, 3, 9, 4, 2] print(bubbleSort(array1)) def FindSmall(li...
class Dog: name = "旺财" def __init__(self): self.name = "来福" @staticmethod def eat(): print("牛来福在吃东西") # 无法调用类属性 @staticmethod def eat(): print("牛来福在吃旺财!") @classmethod def eat(cls): print(f"{cls.name}在吃东西") dog1 = Dog print(dog1.name) dog1.eat() do...
""" 1、青蛙跳台阶问题 一只青蛙要跳上 n 层高的台阶,一次能跳一级,也可以跳两级,请问这只青蛙有多少种跳上这个 n 层高台阶的方法? 思路分析: 方法 1:递归 设青蛙跳上 n 级台阶有 f(n)种方法,把这 n 种方法分为两大类,第一种最后一次跳了一级台阶,这 类方法共有 f(n-1)种,第二种最后一次跳了两级台阶,这种方法共有 f(n-2)种,则得出递推公式 f(n)=f(n-1)+f(n-2),显然,f(1)=1,f(2)=2,递推公式如下: * 这种方法虽然代码简单,但效率低,会超出时间上限* 代码实现如下: """ class Solution(object): # @param:{integer} n ...
# .定义一个Person类 # # ​ 1)属性:姓名name,体重weight # # ​ 2)方法:init方法 # # 2.创建四个对象("牛一",60 ; "陈二",55 ; "张三",70 ; "王五",65 ),将这四个对象添加到列表。 # # 3.获取60-70之间的随机数作为体重标准线(包含60和70),遍历列表将体重大于等于体重标准线的元素写入健康体重名单health.txt。格式如下: # # 姓名:牛一 体重:60 状态:健康 # 姓名:张三 体重:70 状态:健康 # # 姓名:王五 体重:65 状态:健康 import random class Person: def __init__(s...
# [[0~10] * 10] print([x * 11 for x in range(10)]) """Python一行代码实现九九乘法表""" print('\n'.join(' '.join(['%sX%s=%-2s' % (y, x, x * y) for y in range(1, x + 1)]) for x in range(1, 10))) """[0~10]以索引分别打印奇偶数列表""" a = [i for i in range(10)] print(f"原数列:{a}\n偶数列:{a[::2]}\n奇数列:{a[1::2]}") """一行打印[[1, 2, 3]...[100, 101, 102...
# 生成器 # <class 'generator'> x = (x for x in range(10)) print(f"{x}\n{type(x)}") # # create a generator def createGenerator(): mylist = range(4) for i in mylist: yield i * i mygenerator = createGenerator() # create a generator print(mygenerator) # mygenerator is an generator object for i in mygene...
""" 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 """ sort = input("input a string:\n") letters = 0 space = 0 digit = 0 others = 0 for c in sort: if c.isalpha(): letters += 1 elif c.isspace(): space += 1 elif c.isdigit(): digit += 1 else: others += 1 print(f"char:{letters}\nspace:{s...
# encoding:utf-8 def my_function(func): a = 100 b = 200 # 把 cucalate_rule 当做函数来调用 result = func(a, b) print('result:', result) my_function(lambda a, b: a / b) my_function(lambda a, b: a // b) my_function(lambda a, b: a % b) # --- import functools list2 = [] list2.append(functools.reduce(lambd...
import numpy as np import matplotlib.pyplot as plt import pandas as pd # read csv file dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2] y = dataset.iloc[:, 2] # linear regression classifier from sklearn.linear_model import LinearRegression linear_reg = LinearRegression() linear_reg.fit(X, y) ...
d={'name': 'ahsan', 'job': 'pythonista', 'level': 'intermediate'} if 'name' in d: print("Name exists in dictionary with value : ", d.get('name', ''))
d={'english':0, 'urdu': 0, 'computer science': 0, 'geography': 0, 'history': 0} for k in d: marks=int(input(f"Enter marks for {k}: ")) d[k]= marks print("Results") for k in d: print(f"{k} : {d[k]}") print("Total :", sum(d.values(1)) )
from functions import square for i in range(10): print("The square of", i, "is", square(i))
class Game: player_choice = int(input("Enter your choice ")) def __init__(self,name,health,attack,heal): self.name = name self.health = health self.attack = attack self.heal = heal def player_action(self): print("Rock...") print("Paper...") print("Scissors") return ("--" * 7) def player_info(...
import math def is_prime(number): #small_number = int(math.ceil(number**.5)) small_number = number i=2 while i<small_number: if (number%i==0): return False i = i + 1 return True def next_prime(number): it = number+1 while not(is_prime(it)): it = it + 1 return it def primes_before(number): cont = 3 ...
"""import pyxel import random pyxel.cls(0) HEIGHT = 256 WIDTH = 256 lemmings = [] #ver si dejar o no timer = 8 #ver si dejar o no interval = 10 # The first thing to do is to create the screen, see API for more parameters pyxel.init(HEIGHT, WIDTH, caption="Lemmings Game",scale=2) pyxel.load("assets/my_resource.pyxres") ...
""" To run this script: python shoppingCost.py If you run the above script, a correct calculateShoppingCost function should return: The final cost for our shopping cart is 35.58 """ import csv def calculateShoppingCost(productPrices, shoppingCart): finalCost = 0 "*** Add your code in here **...
game_chosen=0 begin_game=0 running=0 while True: while begin_game!=1: print("play (1) motorman(one player) (2) Dungeon(one player) (3) Shop'n'Stab(one player) (4)Duel(two player)") game_chosen=input("what to play... ") if game_chosen==1 or 2: begin_game=1 running=1 if game_chosen==1: import s...
### Two Sum ### # Given an array of integers nums and an integer target, # return indices of the two numbers such that they add up to target. def findTwoSum(nums, target): # Create hashmap hashmap = {} for i in range(len(nums)): # Create a complement complement = target - nums[i] #...
# #1 # def biggie(x): # newArr=[] # for i in range(len(x)): # if x[i]>= 0: # newArr.append("Big") # else: # newArr.append(x[i]) # return newArr # print(biggie([-1,-4,5,-3,2,1,-1,0])) # 2 # def count_pos(x): # counter = 0 # for i in range(len(x)): # ...
items1 = dict({"key1" : 1,"key2" : 2,"key3" : "three","key4" : 4,}) print(items1) items2 = {} items2["key1"] = 1 items2["key2"] = 2 items2["key3"] = 3 print(items2) # print(items1["key6"]) items2["key2"] = "two" print(items2) for key, value in items2.items(): print("Key: ", key, " value:", value)
def generate_concept_HTML(concept_title, concept_description): html_text_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_text_2 = ''' </div> <div class="concept-description"> ''' + concept_description html_text_3 = ''' </div> </div>''' full_html_text = html_text_1 + html_...
# import turtle # t = turtle.Turtle() # shapeInput = input('circle and square or triangle, what is your favorite shape?:') # colorInput = input('What color will it be? :') # t.fillcolor(colorInput) # t.begin_fill() # if shapeInput == 'circle': # r=float(input("radius :")) # t.circle(r) # elif shapeInput == 'squ...
################################################ # CS 21B Intermediate Python Programming Lab #1 # Topics: Arithmetic, Data Types, User Input, # Formatting Output, Importing Modules # Description: To evaluate arithmetic expressions # using Python. # User Input: student ID, name, various other var...
""" Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the tree. This part of the project comprises two days: 1. Implement the methods `insert`, `contains`, `get_max`, and `for...
def menu(conn): option = "" while option != "return": print("") print("Please select from one of the following options:") print("view users") print("add admin") print("remove user") print("return") option = input("> ") if(option == "view users")...
""" http://practice.geeksforgeeks.org/problems/minimum-platforms/0 Author : Salman Ahmad """ def min_platforms(arrival,exits): time_adds = {} for i in range(len(arrival)): if exits[i] <= arrival[i]: exits[i]+=2400 for t in arrival: time_adds[t] = time_adds.get(t,0)+1 for t in exits: time_adds[t] = tim...
''' Created on 2018年8月4日 https://www.geeksforgeeks.org/level-order-tree-traversal/ @author: Viking ''' # python3 orgram to print level order traversal using queue class Node: def __init__(self, data): self.data = data self.left = self.right = None def printLevelOrder(root): if root is None: ...
import turtle def POSICIONAR(): """Cambia el onscreenclick para que lea donde posicionar a Karel""" global kl wn.title("HAGA CLICK DONDE QUIERA INICIAR A KAREL") bep.ht() kl.ht() wn.onscreenclick(FACING) def FACING(x,y): """Recibe unas coordenadas y posiciona a karel en el centro del cuadr...
from tkinter import * import sqlite3 as db from tkcalendar import DateEntry def submit(): # connect to a database conn = db.connect('expense.db') #Create cursor for db c = conn.cursor() # Insert into Table c.execute("INSERT INTO expenses VALUES (:date, :amount, :name, :pai...
from datetime import date todays_date = date.today() birth_year = input("what is your birth year : ",) your_age = int(todays_date.year) - int(birth_year) print(your_age)
collageCode="333" collageName ="Global Collage of Engineering" # it works on index values print("my collage cosde is {0} ,and name is {1}".format(collageCode,collageName)) print("my collage cosde is {0} ,and name is {0}".format(collageCode,collageName)) print("my collage cosde is {1} ,and name is {0}".format(collageC...
import sys def is_int(s): try: int(s) return True except ValueError: return False def eval(exp, stack): # print(exp, stack) if len(exp) == 0: return if exp[-1] in ['+', "*", "-"]: symbol = exp.pop() ex1 = stack.pop() ex2 = stack.pop() ...
cases = int(input()) def check(path): bag = [] for c in path: if c == ".": pass elif c == "$": bag.append("$") pass elif c == "|": bag.append("|") pass elif c == "*": bag.append("*") pass ...
from Classify import Classify from Fetch import Fetch import json, requests # Main class to fetch one tweet and classify class Main(): url = None tweets = None fetch = None parse = None classifier = Classify("trainSet.json", "dictionary.json", "./liveTrain.json", "./pastTrain.json", "./liveTrainDic...
from typing import List import numpy as np from collections import Counter class IntroGates: # 8 problems def __init__(self): self.mintTwoDigits = self.addTwoDigits(n=15) self.mintMaxMultiple=self.maxMultiple(divisor=3,bound=10) self.miLateRide=self.lateRide(n=1439) def addTwoDigi...
"""CSP (Constraint Satisfaction Problems) problems and solver.""" from filecmp import cmp from search import Problem from utils import DefaultDict, product, argmin_list, update, count_if, argmin_random_tie, every import itertools class CSP(Problem): """This class describes finite-domain Constraint Satisfa...
list1 = [int(x) for x in input().split()] list2 = [int(x) for x in input().split()] common =list(set(list1).intersection(list2)) print(common) l1ntl2 = [] for i in list1: if i not in(common): l1ntl2.append(i) print(l1ntl2)
def modInverse(a, m) : a = a % m; for x in range(1, m) : if ((a * x) % m == 1) : # print(f"({a} * {x}) % {m}") return x return 1 # Driver Program for a in range(0,90): k = modInverse(a, 91) if k != 0 and k != 1: print(a) print("____________________...
''' # 4195 : 친구 네트워크 # Union-find ''' # 부모 찾기 def find(x): if x == parent[x]: return x else: # 재귀적으로 최상위 부모 찾기 p = find(parent[x]) parent[x] = p return parent[x] # 부모값 반환 # 합집합 def union(x, y): x = find(x) y = find(y) if x != y: parent[y] = x ...
from nltk.corpus import stopwords stops = set(stopwords.words("english")) fin = open('out_posts_20000.txt', 'r') import re from nltk.stem.wordnet import WordNetLemmatizer lmtzr = WordNetLemmatizer() def fix_line(line): line = line.lower() line = re.sub(r"[^ a-zA-Z\n]"," ",line) line = line.replace("\n"," ") words...
import cv2 as cv #haar cascade are not used in advanced levels becuase they are not that accurate they are very senstive img = cv.imread('C:/Users/karim.salim/Desktop/car/group2.jpg') #shows the image cv.imshow("Image", img) gray= cv.cvtColor(img,cv.COLOR_BGR2GRAY) cv.imshow('Gray person',gray) ...
def digits(n) : if abs(n) < 10 : return 1 else : num = 0 while abs(n) >= 10: num = num + 1 n = n // 10 return num+1 print(digits(12345))
import numpy as np import matplotlib.pyplot as plt x= np.arange(-10,11,1) y = x*x plt.plot(x,y) # 加入注释 plt.annotate("this is the bottom",xy = (0,1),xytext=(0,20), arrowprops = dict(facecolor = 'r',headlength=20,headwidth =20,width=30)) plt.show()
def quick_sort(arr): _quick_sort(arr, 0, len(arr) - 1) def _quick_sort(arr, first, last): if first < last: split_point = partition(arr, first, last) _quick_sort(arr, first, split_point - 1) _quick_sort(arr, split_point + 1, last) def partition(arr, first, last): pivot_value = arr...
def insertion_sort(arr): for i in range(1, len(arr)): cur_val = arr[i] pos = i while pos > 0 and arr[pos - 1] > cur_val: arr[pos] = arr[pos - 1] pos = pos - 1 arr[pos] = cur_val array = [20, 10, 40, 30, 60, 50, 70] insertion_sort(array) print(array) # [10, 2...
def coin_change(target, coins, known_results): min_coins = target if target in coins: known_results[target] = 1 return 1 elif known_results[target] > 0: return known_results[target] else: for i in [c for c in coins if c <= target]: num_coins = 1 + coin_ch...
import math import os def get_square_root(items): square = [math.sqrt(x) for x in items] return square def get_square_root_loop(items): square = [] for x in items: square.append(math.sqrt(x)) return square external_items = [1, 4, 9] def get_square_root_external_variable(): square...
#DataFrame is a 2-dimensional labeled data structure. import numpy as np import pandas as pd #From dict of Series or dicts a = {'data' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'Scientist' : pd.Series([11., 12., 13., 14.], index=['a', 'b', 'c', 'd'])} type(a) b = pd.DataFrame(a) type(b) b a #To g...
""" Functions as Variables You can assign functions to variables in python. We can use this to leverage some "shell" organization in your main program of the shell assignment. You could obviously use a huge `if then else` statement to achieve the same thing, but this will look cleaner. Each function below is fake wi...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #The Class is the building block of Object oriented programming. #A class is like a blueprint for an object #An obejct is an instance of a class. #When a class is defined it takes up no memory until it is instantiated. class BrickHouse: ...
# from string import ascii_lowercase # lettermap = {c: k for k, c in enumerate(ascii_lowercase, 1)} # print(lettermap) """ lettermap = dict((c, k) for k, c in enumerate(ascii_lowercase, 1)) print(lettermap) """ """ word = 'Hello' swaps = {c: c.swapcase() for c in word} print(swaps) positions = {c: k for k, c in en...
# late = True # if late: # print('Vou ligar para o meu gerente!') # else: # print('Não preciso ligar para meu gerente') # chovendo = False # if chovendo: # print('Vou pegar o guarda-chuva!') # else: # print('Vou deixa-lo em casa!') # dependents = 0 # dependent_value = 189.59 # if dependents == 1: # ...
# loop enquanto # n = 42 # remainders = [] # while n > 0: # remainder = n % 2 # restos da divisão por 2 # remainders.insert(0, remainder) # mantemos registro dos restos # n //= 2 # dividimos n por 2 # print(remainders) # n = 42 # remainders = [] # while ...
from typing import List, NamedTuple from os import path class Node(NamedTuple): id: int name: str is_dir: bool children: dict[str, NamedTuple] size: int parent: NamedTuple def id_gen(): id = 0 while True: yield id id += 1 def build_tree(i: List[str]) -> dict: id = ...
from itertools import chain from typing import List, Tuple from os import path def find_start(i: List[str]) -> Tuple[int, int]: for y, row in enumerate(i): for x, c in enumerate(row): if c == "S": return (x, y) raise ValueError("no start node") def neighbours(p: Tuple[int, ...
from collections import namedtuple from itertools import product from typing import Dict, Iterable, List, Set, Tuple from os import path from re import split Point = namedtuple("Point", "x y") Left = Point(-1, 0) Right = Point(1, 0) Up = Point(0, -1) Down = Point(0, 1) Directions = [Right, Down, Left, Up] def add(p...
""" this module takes care of all the task that has to with delivering the lessons to the user The format of the lesson should be as shown below when it is to be configured with a sound control object [ { "caption":"Name of file to speak the caption of the lesson to be delivered", "lesson":{ "A key to be used i...
from math import sqrt l = [] def lagrange(n): i = 0 while not i == 4: rad = sqrt(n)//1 n = n - (rad * rad) l.append(rad*rad) i=i+1 return l n = input('Introduceti N: ') print(lagrange(n))
'''resolvi comentar o codigo em ingles para treinar ''' import pygame pygame.init() window = pygame.display.set_mode((500,480)) pygame.display.set_caption("First game project") clock = pygame.time.Clock() class player(object): def __init__(self,x,y,width,height): self.x = x self.y = y self...
class Point(object): def __init__(self, x, y) self.x, self.y = x, y @staticmethod def from_point(other): return Point(other.x, other.y) class Rect(object): def __init__(self, x1, y1, x2, y2): xl, xh = (x1,x2) if x1 < x2 else (x2,x1) yl, yh = (y1,y2) if y1 < y2 else (y2,y1) self.min, self.max = Point(xl...
# -*- coding: utf-8 -*- data = (2, 45, 55, 200, -100, 99, 37, 10284) for i in data: if i % 3 == 0: print i
arr=[2,42,13,67,34,255,7,1,13,55] def merge(arr,start,mid,end): temp=[] left=start center=mid right=end while left<mid and center<end: if arr[left]<=arr[center]: temp.append(arr[left]) left+=1 else: temp.append(arr[center]) ...
import sys import getpass print ("Welcome to the game of Rock Paper Scissors") def PlayerNames(): global player1 global player2 player1 = input("Please enter your name:") player2 = input("Please enter your name:") menu() def menu(): choice = input("\nwhat do you want to do? \n" ...
import re import urllib.request import json API_conversion = "https://api.exchangerate-api.com/v4/latest/" def page_exists(page): try: urllib.request.urlopen(page) return True except: return False def currenct_conversion( convert_from, convert_to): try: if(page_exists(API_conversion+conv...
import pyautogui import time print("Welcome to autoType!\n") message = input("Enter the text you want to type:-\n") number = int(input("Enter how many times you would like the program to type and send the message:-\n")) timeDelay = int(input("Enter how long you would like the program to wait before typing in seconds:...
#!/usr/bin/python # -*- coding: utf-8 -*- # Введите с кла­ви­а­ту­ры 5 по­ло­жи­тель­ных целых чисел. # Вы­чис­ли­те сумму тех из них, ко­то­рые де­лят­ся на 4 # и при этом за­кан­чи­ва­ют­ся на 6. Про­грам­ма долж­на # вы­ве­сти одно число: сумму чисел, вве­ден­ных с # клавиатуры, крат­ных 4 и окан­чи­ва­...
# A starter program for Python with Tkinter from tkinter import * # import Tkinter library from tkinter.ttk import * from tkinter import Menu from tkinter.ttk import Progressbar from tkinter import ttk window = Tk() # Create the application window # Add a label with the text "Hello" lbl = Label(window, text="...
#计算for break 语句 print('----------------------') print('1.for语句程序正常循环') for i in range(10): print('当前执行:',i) print('----------------------') print('2.for语句程序break中断') for i in range(10): if(i>=5): break print('当前执行:',i) print('----------------------') print('3.for语句程序continue跳过') for i in...
# Towers of Hanoi ''' You have three disks of varying sizes (large, medium, small) - these disks are stacked on top of one another on a single tower/rod. Problem Rules: 1. Only one disk can be moved at a time 2. Each move consists of taking the upper disk from one of the stacks and placing it atop another stacks 3. No...
import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") tess = turtle.Turtle() tess.pensize(3) def drawBar(t, height): for i in height: t.begin_fill() if i >= 200: t.fillcolor("red") elif i >= 100 and i < 200: t.fillcolor("yellow") elif i < 100: ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 12 16:54:08 2021 Q asked in Microsft interview @author: Ashish """ def removeZeros(ip): # splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string new_i...
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 09:02:51 2021 Objective: To generate a random list of email addresses and write to file Reference: https://codereview.stackexchange.com/questions/58269/generating-random-email-addresses @author: Ashish """ import random, string domains = ["hotmail.com", "gmail...
# -*- coding: utf-8 -*- """ Created on Sat Nov 21 10:11:18 2020 The given program will transform a single column containing categorical vars into boolean values @author: Ashish """ import pandas as pd from sklearn.preprocessing import OneHotEncoder df = pd.DataFrame({'EDUCATION':['high school','high school','high sch...
def som(getal1, getal2, getal3): return getal1 + getal2 + getal3 getal1 = float(input('voer een getal in: ')) getal2 = float(input('voer een tweede getal in: ')) getal3 = float(input('voer een derde getal in: ')) print(som(getal1, getal2, getal3))
import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 5 + rng.randn(50) plt.scatter(x, y); plt.show() from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(x[:, np.newaxi...
def dependencia(input): dicionario = {} for classe in input: c = classe.pop(0) deps = classe dicionario[c].append(deps) result = set() for k, v in dicionario: recurseDependency(set, dicionario, k, v) return result def recurseDependency(set, dicionario, classe, dependencias): if !dicio...
class Alphabet: def getCharCode(self, letter): return ord(letter.lower()) def isInRange(self, letter): beginIndex = self.getCharCode('a') endIndex = self.getCharCode('z') charIndex = self.getCharCode(letter) return 1 if charIndex >= beginIndex and charIndex <= endIndex else 0 def isInOrder(self, first...
# --------------------------- # Sogol Moshtaghi # Oscar chavarria # PFD # --------------------------- import Queue # ------------ # PFD_read # ------------ def PFD_read (r, a) : """ reads one line of the input and populates the list of predecessors r is a reader a is a list of predecessors return true if th...
#x,y and z representing the dimensions of a cuboid along with an integer n. #print a list of all possible coordinates given by (i,j,k) on a 3D grid #where the sum of i+j+k is not equal to n. #print the list in lexicographic increasing order. x,y,z,n = (int(input()) for _ in range(4)) coordinates = [[i,j,k] for i in ran...
"""Create files and symbolic links in a way that appears to be an atomic file-system operation. It is sometimes useful that files and symbolic links are created with the intermediate write operations hidden. Temporary files and symbolic links are used and the final update operation is atomic. """ import errno import ...
__author__ = "Sylvain Dangin" __licence__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "Sylvain Dangin" __email__ = "sylvain.dangin@gmail.com" __status__ = "Development" from datetime import datetime class date_format(): def action(input_data, params, current_row, current_index): """Convert date fr...
# -*- coding: utf-8 -*- import datetime def calcular_tiempo_recorrido(distancias, velocidad): """ Definicion de la funcion calcular_tiempo_recorrido: Funcion de calculo del tiempo de recorrido Parametros ---------- distancias: Pandas Dataframe Dataframe que co...
# I understood the task as creating a dictionary and then getting a user to enter a sentence to count the amount of # times that it occured in your dictionary. Taking a look at the solution I noticed it was different. dictionary = {"a": 0, "be": 0, "car": 0, "drive": 0, "cat": 0, "fun": 0, "dog": 0, "alpha": 0, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ######### library ########## import time import datetime ################################## Fonction Gestion ################################ def find_list(l1,l2): # cherche si un argument de "l1" et dans "l2" et retourne sont n'indice i = 0 while i < len(l1): j = 0 ...