text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 Robin Wen <blockxyz@gmail.com> # # Distributed under terms of the MIT license. # twitter-opml # - lists all of a given user's following to opml format from twitter import * # load our API credentials import sys sys.path.append(".") ...
def staircase(n): for i in range(n): s = "#" * (i+1) print s.rjust(n) return n = int(raw_input()) staircase(n)
import collections import copy import itertools ''' Contains the apriori algorithm for finding patterns TODO: implementing the support funcion for patterns with more than two elements ''' def apriori(data, threshold ): # some random control stuff if threshold > len(data): return "You can't have a supp...
ONES = ["", "one", "two", "three", "four", "five", "six","seven","eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] TENS = ["","","Twenty", "Thirty", "forty", "fifty", "sixty", "seventy", "eighty" ,"ninety"] def num_to_words(n): ...
num_array = [] for i in range(1000): if i % 3 == 0 or i % 5 == 0: num_array.append(i) print(sum(num_array))
items=["build","exaid","zio"] # for i in range(3): # print(i+1, items[i]) # in items o vi tri i #print(i) for i in range(len(items)): # vs len thi them bn phan tu thi tu cap nhat ben duoi print(i+1, items[i])
from turtle import * for k in range(20): speed(10000) for i in range(400): speed(100) forward(2) left(1) left(40) mainloop()
yob = int(input("your year of birth = ")) age= 2018- yob print(age) if age <10: print(" auto di tu") elif age <18:# viet tat cua else va if #chi co 1 if va 1 else nhung elif thi bao nhieu cung duoc print(" xac con me m dinh nhe , au dam") else: print(" khong di tu")
from turtle import * for i in range (50): forward(i*5) left(90) mainloop() #or #from turtle import * #s=30 #for i in range (50): #forward(s) #left(90) #s= s+10# s+=10 #mainloop() #https://vietjack.com/python/toan_tu_trong_python.jsp dấu python += là gì
list1=[10,12,-7,5,64,-14,-1] for num in list1 : if num>=0: print(num,end=" ")
import math from sympy import * #we have to create a "symbol" called x #De bai x=Symbol('x') f=exp(x)+2**-x + 2*cos(x)-6 a= 1 b= 2 #Chon x0 temp=f f1=f.diff() f2=f1.diff() f=lambdify(x,f) f1=lambdify(x,f1) f2=lambdify(x,f2) if f(a)*f2(a)>=0: x0=a if f(b)*f2(b)>=0: x0=b #xac dinh m if abs...
#This is the step - 1 of the DSND project Disaster response pipeline' #To execute this code, you simply need to type the following statement in the command window - #python ./data/process_data.py ./data/disaster_messages.csv ./data/disaster_categories.csv DisasterResponse.db' #All import statements necessary for the ...
class Queue: """A Queue class. add: add the item to the last level of the stack. remove: get the last item from the top of the stack. its_empty: test if the stack is empty. length: return the number of levels of the stack. first_item: return the element from the top of the st...
def search_unordered_list(list1, searched_value): """Search an unordered list Complexity for the algorithm is 'O(n)' and it is resulted from the 'for loop' and the length 'n' of the list. """ for i in range(len(list1)): if searched_value == list1[i]: return i return None def s...
import pandas as pd # read csv df = pd.read_csv('data_scientist_duplicate_detection.csv') # find duplicate rows duplicate_rows = df[df.duplicated()] # show rows print("\n\nDuplicate Rows : \n {}".format(duplicate_rows)) # save them to csv file duplicate_rows.to_csv("duplicates.csv")
import sys from copy import deepcopy from queue import PriorityQueue MAX_INT = 0x3f3f3f3f def print_arr(arr): """ Print arr (4*4) """ if arr == None: print(arr) else: for i in range(4): print(*(arr[i])) print() def get_target_pos(num): """ Get target position of num """ return ((num-1) // 4, (num-1)...
#lists.py def generateNumberList(): '''(NoneType) -> list Returns a list of numbers from "0001" to "0399" ''' numberList = [] for x in xrange(1,400): s = str(x) #print s if x in xrange(1,10): number = "000" + s numberList.append(number) if x in xrange(10,100): number = "00" + s numberList.ap...
import math from numpy import * import numpy as np from num2words import num2words #Multipurpose functions def isEven(x): if x%2==0: return True else: return False def isPrime(n): if n<=1: return False if n==2: return True if n%2==0: return False ...
# Question 8: Longest Repetition # Define a procedure, longest_repetition, that takes as input a # list, and returns the element in the list that has the most # consecutive repetitions. If there are multiple elements that # have the same number of longest repetitions, the result should # be the one that appears first....
>>> x1=100 >>> print(x1) 100 >>> print(type(x1)) <class 'int'> >>> x=120.45 >>> print(x) 120.45 >>> print(type(x)) <class 'float'> >>> str1='hello' >>> print(str1) hello >>> print(type(str1)) <class 'str'> >>> str2="hello" >>> print(str2) hello >>> print(type(str2)) <class 'str'> >>> str3='''hello''' >>> print(str3) he...
import array import math import csv import numpy as np import random import matplotlib.pyplot as plt import matplotlib.ticker as tck def display_statistics(clusters): # We take in a parameter of a list of all the clusters and display the statistics of each cluster x = 0 # x will just be our iterab...
numero= int(input("ingrese un numero: ")) i=0 while numero > 0: i= i + 1 resto= numero % 10 numero = int (numero/10) print ("%d" % (resto), end = "")
# I need to display "What type of night be it tonight?" # I need to give them a imput at set it to a verible i can later call on print("What type of night be it tonight?") var = input() if var == "lightening": print("It is time to be ALIVE!") elif var == "cloudy": print("The sky is stirring but we must wait.") ...
import numpy as np import matplotlib.pyplot as plt #the function that needs to be minimised def function(X): return np.sum(np.square(X-2),axis=1,keepdims=True) #hyperparameters num_feat=int(input("Enter the number of co-ordinates each point has:")) num_units=int(input("Enter the number of points:")) c1=float(in...
""" Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. American keyboard Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more than once. You m...
""" Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (d...
import math a,b,c = input().split() a = float(a) b = float(b) c = float(c) try: bhaskara1 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) bhaskara2 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) print("R1 = %.5f"% bhaskara1) print("R2 = %.5f"% bhaskara2) except: print("Impossivel calcular")
A = int(input()) B = int(input()) C = float(input()) NUMBER = A SALARY = B*C print("NUMBER = %i" % NUMBER) print("SALARY = U$ %.2f" % SALARY)
R = int(input()) n = 3.14159 VOLUME = (4/3.0)*n*(R**3) print("VOLUME = %.3f" % VOLUME)
import csv import sys def main(): print "This algorithm should parse a log file." #print out only the lines that contain a certain string infile = open("log.txt", "r"); outfile = open("output.txt", "w"); lines = infile.readlines() countLines = 0; print ( "Printing FMT lines into output.txt...
import socket # Create a TCP/IP socket sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('localhost', 8080) sck.connect(server_address) url = input("URL: ") url += "\r\n" #bytes and utf-8 is necessary for python 3.5 ...
from discord.ext import commands import random def setup(bot): bot.add_cog(Minesweeper(bot)) class Minesweeper(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=["ms","minesweep","msweep","msweeper"]) async def minesweeper(self, ctx, grid_size = 5):...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import threading import time exitFlag = 0 count = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run...
print("Jhonatan Roopnarine") #Input a word containing 5 characters #Test Truck and Right word=input("Enter a word that is 5 characters long:") #Initialize the length of the word length=len(word) #Create a for loop for the rows and columns required to print the characters for row in range(length): for col in...
print("Jhonatan Roopnarine") #Enter -2 or any other number when there is no saved number and you will get a response of there is no input with sum of 0 #Enter 25 or any other number and then a negative and it should return the number as its average with sum of 25 or number that was entered #Enter 10,30,50,8,7 or any...
print("Jhonatan Roopnarine") print() #Test (remove([1,2,3,4,5,6,7,8,9],True)) with result [2, 4, 6, 8] #Test (remove([1,2,3,4,5,6,7,8,9],False)) with result [1, 3, 5, 7, 9] #Define a function to run the situation def remove(list,isOdd): #Set the result as an open list result=[] #Check each number ...
print("Jhonatan Roopnarine") #Test List1 with output [1,3,5,7,9] #Set the list to List1 List1=[1,2,3,4,5,6,7,8,9] #Define a function for removing the even numbers def remove_even_numbers(List1): no_even_numbers=[] for x in List1: if x%2: no_even_numbers.append(x) #Print the res...
print("Jhonatan Roopnarine") #Password checker for password having at least 6 characters and at most 20// #with at least one lowercase letter, one uppercase, and one number #Get password from user psw = input("Enter a password to be checked:") #Initialize variables valid = False length = False lowercase = False...
print("Jhonatan Roopnarine") #Input salary of 3000 with any name and rating of 1, output should be "On probation" #Input salary of 2000 with any name and rating of 2, output should be "Fair job, work harder and your new salary is: 2020" #Input salary of 2500 with any name and rating of 3, output should be "Good job ...
print("Jhonatan Roopnarine") #Enter -2 or any other number when there is no saved number and you will get a response of there is no input with sum of 0 #Enter 25 or any other number and then a negative and it should return the number as its average with sum of 25 or number that was entered #Enter 10,30,50,8,7 or any...
# Similar to problem 7, we need to find prime numbers, and those # can sometimes be tricky to locate. However, using another # sieve of Eratosthenes, this process can be expedited versus # checking each individual number to see if it is prime. # A lot (most) of this code is taken from prob7.py, check out # that probl...
""" pythag_tree.py A Lindenmayer system for drawing a Pythagorean tree. Adapted from https://www.wikipedia.com/wiki/L-system. author: Daman Morris <damanm72@gmail.com> """ from lindenmayer import Lindenmayer, prompt import turtle class PythagTree(Lindenmayer): def __init__(self): rules = {'1': '11', '0...
# John Loeber | contact@johnloeber.com | Sep 12 2015 | Python 2.7.10 from time import sleep from copy import deepcopy def game_not_over(board): """ -1: player loses. 0: tie. 1: player wins. 1000: game not over. """ wins = [[(0,0), (1,0), (2,0)], [(0,1), (1,1), (2,1)], [(0,2), (1,2), (2,2)], ...
import random mas = [] sum = 0 # Генерируем массив из 10 чисел от 1 до 10: mas = [random.randint(1,10) for i in range(1,10)] print(mas) # Проходим в цикле по массиву и все четные числа суммируем: for i in mas: if (i%2) == 0: sum += i print(sum) input ("\nДля выхода, нажмите Ввод...")
# p79 unnescessary work demonstration: Print all positive integer solutions # to the equation a^3 + b^3 = c^3 + d^3 # time complexity: 1st ex. O(n^4), 2nd ex. O(n^3), 3rd ex. O(n^2) def abcd1(n): for a in range(1, n): for b in range(1, n): for c in range(1, n): for d in range(1...
''' Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. lf x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition...
''' You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (7-) 1 -) 6) + (5 -) 9 -) 2).Thatis...
''' Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? ''' def removeDups(lst): if lst == None: return temp = lst.head prev = None tracker = [] while temp: if temp.data in tracker: ...
import streamlit as st import numpy as np import pandas as p import matplotlib.pyplot as plt import seaborn as sns import folium def calculateinterest(salary,rate): interest = salary* rate print("The interest is %d :" % interest ) calculateinterest(44,10) #hello world commentttt #hello world commentttt...
import turtle ''' def line_without_moving(): turtle.forward(50) turtle.backward(50) ''' def line_without_moving(length): turtle.forward(length) turtle.backward(length) def tilted_line_without_moving(length, angle): turtle.left(angle) turtle.forward(length) turtle.backward(lengt...
""" CS 486 Assignment 2 Question 1 Author: Isaac Chang Date: Nov 3, 2019 """ import sys import math import matplotlib.pyplot as plt import random import time import pdb class TSPSimAnneal: def __init__(self): self.data_dir = '../data/randTSP' def main(self): lowest_cost = float('inf') ...
# coding=utf-8 # 3▹ Napisać funkcję, która przyjmuje listę liczb i zwraca sumę wszystki elementów na liście. def sum(numbers): init_sum = 0 for number in numbers: init_sum += number return init_sum result = sum([1,2]) print(result)
# coding=utf-8 # Napisać funkcję, która sprawdza czy liczba jest parzysta. def is_even_number(n): if n%2 ==0: a= "Liczba jest liczbą parzystą" else: a="Liczba nie jest liczbą parzystą" return a print(is_even_number(5))
# Pobierz od użytkownika parzystą listę elementów. Sprawdź czy 2 środkowe elementy są takie same. counter = int(input('Podaj przysta liczbe cyfr: ')) numbers = [] for number in range(counter): number = int(input('Podaj kolejna liczbe: ')) numbers.append(number) if numbers[int(counter/2-1)] == numbers[int(cou...
import argparse import sys # Usage # Locate this file in directory with your script where you use argparse # import statement - from colored_argparse import ColoredArgParser # replace argparse.ArgumentParser() with ColoredArgParser() in your script # Original code # https://stackoverflow.com/questions/47155189/how-t...
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? import time import math start = time.time() # function to check if a number is prime def is_prime(x): for i in range(2, int(math.sqrt(x)) + 1): if x % i == ...
from math import sqrt def is_square(n): return int(sqrt(n))**2 == n def diophantine(limit): seq = [] d = 1 while d < limit: d += 1 if is_square(d): continue x = 2 while True: y = sqrt((1 - x**2) / -d) if abs(int(y) ...
##asymptotic Analaysis ## Linear search Algo ## Does not depend other constant ## depends on size of array ## worst case [element is not exist] -- o(n) if n is very high than worst and average case running time is asymptotic ## best case [element found at first position] ## average case [element ...
def counterr(a, b): c = 0 new = [] for i in str(b): if i in str(a) and i not in new: c += 1 new.append(str(i)) return c print(counterr(12345, 567)) print(counterr(1233211, 12128)) print(counterr(123, 45))
##################################### ######## EXERCICIS DE REPAS ######## ##################################### ################ ## Exercici 1 ## ################ # Donat el string: s = 'django' # Utilitzar indixos per mostrar els siguents elements de el string: # 'd' print(s[0]) # 'o' print(s[-1]) # 'djan' prin...
def area(width, height): result = width * height return result result = area(5, 6) print(result) area(6,7) area(9,5) def subtract(num1, num2): result = num1 - num2 return result print(subtract(10,5)) print(subtract(15,7)) def add(num1, num2): sum = num1 + num2 return sum print(add(5,14)) print(add...
''' creator:obeng william description:even and odd numbers ''' theInput = raw_input("Enter an integer: ") if int(theInput)%2==0: print "The input is even" elif int(theInput)%2==1: print "The input is odd" for i in range(39,-1,-3): ... print i primarysch_age=6 voting_age=18 president_age...
import math import os import random import re import sys #understand: # inputs: # we are given an array of binary numbers 0's and 1's # we have to traverse through the array while avoiding the 1's # we can jump one or two indices at a time # we want to return the minimum number of jumps required to make it to the ...
from decimal import Decimal import numpy as np import matplotlib.pyplot as plt import math #окружность x0 = 3 y0 = 8 r = 3 angle = np.linspace(0, 2 * np.pi, 1000) x = r * np.cos(angle) + x0 y = r * np.sin(angle) + y0 plt.plot(x, y) #эллипс x0 = 1 y0 = -2 a = 8 b = 4 angle = np.linspace(0, 2*np.pi, 1000) x1 = a * np....
""" Program: Student.py Author: Andy Volesky Last date modified: 11/03/2021 The purpose of this program: create a student class for unit testing. """ class Student: """Student class""" def __init__(self, lname, fname, major, gpa=0.0): name_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq...
for i in range(1,6): print(i) Change range of the output The nex part of the demonstration
def create_board (): board = [] for i in range(8): board.append([]) for j in range(8): board[i].append(0) board[3][3] = 1 board[3][4] = 2 board[4][3] = 2 board[4][4] = 1 return board def print_board(board): for row in range(len(board)): print(*board[...
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_withdrawal(self, amount): self.account_balance -= amount return self def make_deposit(self, amount): self.account_balance += amount ret...
#__________________________________________________________________ #notice the variable bill is inside the parenthesis. def FindSalary(): hours = 40 rate = 15 bills = 2100 salary = hours * rate * 4 #4 weeks in a month return round((salary - bills),2) #________________________________________...
def gen_students(tutors, klasses): for i in range(len(tutors)): result = (tutors[i], (klasses[i] if i < len(klasses) else None)) yield result tutors = ['Иван', 'Анастасия', 'Петр', 'Сергей', 'Дмитрий', 'Борис', 'Елена'] klasses = ['9А', '7В', '9Б', '9В', '8Б'] # , '10А', '10Б', '9А'] student = g...
blockchain =[] def get_last_value(): return(blockchain[-1]) def add_value(transaction_amount, last_transaction=[1]): blockchain.append([last_transaction, transaction_amount]) def get_transaction_value(): user_value = float(input('Enter your transaction amount ')) return user_value def get_user_choice():...
""" Module represents Hash Table """ class HashTable: """ Class represents logic of Hash Table """ def __init__(self): """ Initializes list that contains couples key - value """ self.hash_list = [[] for i in range(30)] @staticmethod def hash_function(key): ...
from data_structures_module.structures.linked_list import LinkedList class Queue(LinkedList): def __init__(self): super().__init__() def enqueue(self, element): self.add_last(element) def dequeue(self): if self.head is None: raise Exception("Queue is empty") e...
""" Module represents Hash Table on Linked List """ from data_structures_module.structures.linked_list import LinkedList class HashTableLinked: """ Class represents Hash Table on Linked List """ def __init__(self, size): """ Initialized Linked List :param size: amount of nodes ...
print('Calculadora do Indice de Massa Corporal (IMC)') nome=input('Qual o seu nome?') print('Olá,'+nome+'. Seja bem vindo(a)!') peso=input('Qual o seu peso corporal?') peso=float (peso) altura=input('Qual sua altura em metros?') altura=float (altura) dados= ('Digite a tecla Enter para saber seu IMC') print('Seu IMC, é:...
import math from math import factorial as fac import scipy.stats as ss #factorial function # fac(n) / (fac(k) * fac(n - k)) * p**k * (1-p)**(n-k) #caculate binominal probability def binominal(k,n,p): return ss.binom.pmf(k,n,p) #caculate_right or left bondary, which is the sum of binominal probs def cal_bond(bond, to...
from collections import Counter class Solution: def removeDuplicateLetters(self, s: str) -> str: c = Counter(s) visited = dict() stack = [] for char in s: visited[char] = False for char in s: c[char] -= 1 if visited[char]:...
import math import time def _logtime(start, comment): """ measures and prints the elapsed time Print the elapsed time (in seconds) between 'now' and 'start', and reurns 'now', where : - 'now' is the time _log_logtime is calles - 'start' is a parameter to the function Example: "Real Time : Start ...
from units import * from unitcreator import * from time import sleep number = (2, 7) level = (1, 10) # Let's make some goblins! goblins = spawnGoblins(number[0], number[1], level[0], level[1]) # This is just a list of the goblins in this particular field. print "There are %s goblins" % (len(goblins)) print "" print...
"""Task 2 - write a function (sum_all) that computes an average of grades from all lectures. Examples of calls: compute_average("Ania",math=5,biology=5,polish=4,physics=1,history=5)->Student Ania, grade avg: 4.0 compute_average(math=5, student_name="Basia") -> Student Basia, grade avg: 5.0 compute_average("Krysia", ph...
''' Zadanie 9 W systemie blogowym potrzebna są funkcje, które skrócą tekst do pierwszych n znaków i dodadzą do niego "... czytaj dalej". Napisz funkcję generującą lambdy spełniające te wymagania dla danego n. * Dla chętnych: Sprawdź czy twoja funkcja działa z tekstem krótszym od n i ew. popraw jej działanie. ''' def c...
""" Zadanie 6. Zmodyfikuj funkcję z zadania 4. by przyjmowała dowolną liczbę argumentów. Przetestuj wywołanie dla różnych długości listy. """ a = [*range(100)] def zadanie4(*args): d = 0 return sum(args), sum(0-i for i in args) print(zadanie4(*a))
# for x in range(0,30,2): # print(x) # # for x in range(1,30,2): # print(x) for x in range(1,10,-4): print(x)
""" SDA - PYTwro11 - blok Testowanie oprogramowania i TDD - Mateusz Z. Dzień 8 - 27-09-2020r Zadanie 1: Utwórz dwie klasy. Pierwsza klasa o nazwie 'Produkt', przyjmująca za argument 'nazwa (str)' i 'objętość (float)'. Druga klasa o nazwie 'Magazyn', przyjmująca za argument 'pojemność (float)'. Klasa 'Magazyn' ma posiad...
# Enkapsulacja, gettery i settery class Computer: number = 4 def __init__(self): self.__max_price = 900 def get_max_price(self): return self.__max_price def set_max_price(self, price): self.__max_price = price @property def max_price(self): return self.__max_pr...
from math import sqrt def is_prime(n): if n == 1: return False for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True def get_n_primes(n): primes = [] i = 2 while len(primes) != n: if is_prime(i): primes.append(i) i...
def sum_all(*args) -> float: ret = 0.0 for number in args: ret += number return ret print(sum_all(1, 5, 35, 3.32, 1.42)) def sum_all_2(*args) -> float: return sum(args) print(sum_all_2(1, 5, 35, 3.32, 1.42))
data = [5,8,2,4,7,9,3] def bubbleSort(alist): length = len(alist) for i in range(length): first = alist[i] second = alist[i + 1] if first > second: a, b = alist.index(first), alist.index(second) alist[b], alist[a] = alist[a], alist[b] return data print(bubble...
# https://www.codewars.com/kata/5202ef17a402dd033c000009 # Best Solution def title_case(title, minor_words=''): title = title.capitalize().split() minor_words = minor_words.lower().split() return ' '.join([word if word in minor_words else word.capitalize() for word in title]) # My Solution import string de...
""" This is my game classes which I will use for game_interface. """ from typing import Any, List class ChopsticksState: """ A game state of Chopsticks. is_p1_turn - whether it is Player A's turn left_num_a - the number of left hand of Player A right_num_a - the number of right hand of Player A ...
# 'with' statement helps you write file that closes without writting close() method with open("write2.txt",'a+') as file: # part of with block file.seek(0) content = file.read() file.write("\nLine 5: With statement using 'a+'")
# If/ Else conditions are used to decide to do something based on something being true or false x = 15 y = 16 # Comparison Operators (==, !=, >, <, >=, <=) - Used to compare values # Simple if #if x>y: # print(f'{x} is greater than {y}') # if/else #if x>y: # print(f'{x} is greater than {y}') #else: # print(f...
# alternative: low, high = (a, b) if a < b else (b, a) # alternative: put the while in a range def get_sum(a, b): if a == b: return a low, high = (a, b) if a < b else (b, a) return sum(range(low, high + 1)) def main(): print(get_sum(10, 20)) #165 print(get_sum(35, 15)) #525 if __name__ ...
def minAddToMakeValid(S): ''' Input: "())" Output: 1 the 3rd position ")" has not been closed therefore 1 is the answer ''' count = 0 stack = [] for b in S: if b == ')': if len(stack)>0 and stack[len(stack)-1] == '(': del stack[len(stack)-1] ...
# importing libraries to help us do math things and socket things import socket, ping from struct import unpack, pack # if any of these functions are confusing, read the socket documentation: # https://docs.python.org/2.7/library/socket.html?highlight=socket#module-socket my_ip = socket.gethostbyname(socket.gethostna...
""" A base class and exceptions for proxies. """ from collections import defaultdict from inspect import getmembers, isclass, isfunction, ismethod, isroutine from nio.util.logging import get_nio_logger class ProxyNotProxied(Exception): """ Exception raised when an operation takes place on an unproxied proxy....
#!/usr/bin/python3 import random messages = ['It is certain', 'It is decidedly so', 'Yes definitely', 'Reply hazy try again', 'Ask again later', 'Concentrate and ask again', 'My reply is no', 'Outlook not so good', 'Very doubtful'] print(messages[random.randint(0, len(messages) -1 )]) # produces a random number which...
''' subsets dataframes into smaller sets for testing net ''' import numpy as np import pandas as pd from sklearn.cross_validation import train_test_split path_to_project_data = '/home/ubuntu/DSI-Capstone-Project/data/' galaxy_types = ['edge_on_disk', 'elliptical', 'face_on_spiral', 'merger'] def subset_df(infile, ou...
import os import argparse my_parser = argparse.ArgumentParser(description='List the content of a folder') my_parser.add_argument('--path', type=str) args = my_parser.parse_args() ROOT_PATH = args.path COUNT_TYPE = ['py'] if __name__ == '__main__': lines = 0 for filepath, dirnames, fi...
file = open('08.ex.txt', 'r') lines = [] total = 0 count = 0 for line in file: lines.append( line.rstrip() ) file.close() for line in lines: ll = len(line) total += ll line = line[1:ll-1] print line i = 0 while i < len(line): c = line[i] if c == '\\': n = line[i+1] if n == '\\' or ...