text
stringlengths
5
121k
from typing import List class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: odd = [] insert_index = 0 for i in A: if i%2 == 0: A[insert_index] = i insert_index += 1 else: ...
import sys import math lines = iter(sys.stdin) n = int(next(lines)) mean = float(next(lines)) std = float(next(lines)) p = float(next(lines)) z = float(next(lines)) mean_clt = mean std_clt = std/math.sqrt(n) a = mean_clt + 1.96*std_clt b = mean_clt - 1.96*std_clt print(round(b,2)) print(round(a,2))
from functools import reduce from math import prod class ProductOfNumbers: def __init__(self): self.nums=list() def add(self, num: int) -> None: self.nums.append(num) return if not self.nums: self.nums.append(num) return last_number = self.nums[-...
import mysql.connector conn = mysql.connector.connect(user='root', password='admin_zzc', host='127.0.0.1', database='test') cursor = conn.cursor() cursor.execute('create table user2 (id varchar(20) primary key, name varc...
''' Created on Apr 9, 2017 @author: luke ''' from Coordinate import Coordinate from KingPiece import KingPiece class Move(object): def __init__(self, piece, board, moveFrom, moveTo): self.piece = piece self.board = board self.moveFrom = moveFrom self.moveTo = moveTo d...
class Node: def __init__(self, timestamp, message): self.timestamp = timestamp self.message = message self.prev = None self.next = None class Logger: def __init__(self): self.head = Node(0, "") self.tail = Node(0, "") self.head.next = sel...
num = int(input("Digite o valor de n: ")) if num != 0: fat = num else: fat = 1 while num > 1: num = num - 1 fat = fat * num print(fat)
def main(): x = int(input("Digite um número: ")) lista = [] while x != 0: lista.append(x) x = int(input("Digite um número: ")) for y in range(len(lista) - 1, -1, -1): print(lista[y]) main()
def count_substring(string,sub_string): l=len(sub_string) count=0 for i in range(0,len(string)): if(string[i:i+len(sub_string)] == sub_string ): count+=1 return count str=input() if(1<=len(str)<=200): substr=input() print(count_substring(str,substr)) else: print("string ...
i = 0 numbers = [] while i<6: print("At the top i is %d" %i) numbers.append(i) i += 1 print("Numbers now:", numbers) print("At bottom i is %d" %i) print("The number :") for num in numbers: print(num)
from sys import argv script, filename = argv txt = open(filename) print("Here's your file %s" %filename) print(txt.read()) print("Type filname again :") file_again = input("$") txt_again = open(file_again) print(txt_again.read()) print("We're going to erase %r" %filename) print("If you don't wa...
def fab(n): res = [] a, b = 0,1 while a<n: res.append(a) a,b = b, a+b return res fa = fab(100)
def greet(name,msg): """ this function is for basic use of function.""" print("hello", name + ',', msg) greet("sachin","good morning!")
vowel = "aeiouAEIOU" while True: v = input("enter a vowel :") if v in vowel: break print("this in not a vowel ! try again !!") print("thank you")
P = int(input("Enter Amount : ")) R = int(input("Enter Rate : ")) r = float(R / 100) t = int(input("Enter Time Period : ")) A = P * (1 + (r*t)) print (A)
""" 三个门后边有两个门空的,一个有奖 要求: 选择一个门,争取获得奖品 你选中一个门,还没有打开门。 然后主持人打开另一个空的门。 此时你换一个门会得到更大的概率吗? """ import random def DoorAndPrizeSim(switch, loopNum): """ 模拟各种情况下的中奖概率 :param switch: :param loopNum: :return: """ win = 0 total = 0 for loop in range(loopNum): prize = ...
import tensorflow as tf def _variable(name, shape, initializer): """Helper to create a Variable stored on CPU memory. Args: name: name of the Variable shape: list of ints initializer: initializer of Variable Returns: Variable Tensor """ var = tf.get_variable(name, shape, ...
from unittest import TestCase """ Example code to demonstrate Sphinx capabilities. Sphinx uses reStructuredText as its markup language, and many of its strengths come from the power and straightforwardness of reStructuredText and its parsing and translating suite, the Docutils. """ class Math: """ Methods for ar...
n = int(input()) x = list(map(float, input().split())) w = list(map(float, input().split())) weighted = sum(i*j for i, j in zip(x, w)) avg = weighted/sum(w) print('%.1f' % avg)
""" Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if AT LEAST one of the following conditions satisfy: 1. S is a palindrome and of length S >= 2 2. S1 is a halindrome 3. S2 is a halindrome In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1] Example 1: input: harshk ou...
import math import os import random import re import sys """ A widget manufacturer is facing unexpectedly high demand for its new product,. They would like to satisfy as many customers as possible. Given a number of widgets available and a list of customer orders, what is the maximum number of orders the ...
def solution(A): if len(A) == 0: return 0 else: longest = 0 for i in range(len(A)): length = 1 start = A[i] while A[start] != A[i]: length += 1 start = A[start] if leng...
import math import os import random import re import sys def minimumNumber(n, password): count = 0 numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" criteria = [False] * 4 for i in range(n)...
def isSorted(num): digits = list(str(num)) unique = list(set(digits)) if digits != unique: return False else: return digits == list(sorted(digits)) def findLargestNumber(num): if num < 10: return num while num > 9: if not isSorted(num): num -= 1 ...
def computeAxBy(a, b): upperBound = 9223372036854775806 result = [] x = 1 y = 1 while x <= upperBound: while y <= upperBound: if x + y <= upperBound: result.append(x + y) y *= b x *= a y = 1 return result def co...
import math import os import random import re import sys def findSubstrings(s): s.lower() vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" result = [] for i in range(len(s)): if s[i] in list(vowels): for j in range(i+1, len(s)): ...
import math import os import random import re import sys def fib(t1, t2, n, dp): if dp[n] != None: return dp[n] result = 0 if n == 1: result = t1 elif n == 2: result = t2 else: result = fib(t1,t2,n-2,dp) + (fib(t1,t2,n-1,dp) ** 2) dp[n] = result return re...
import math maxWt = float(input()) n = float(input()) mean = float(input()) std = float(input()) mean *= n std = std * math.sqrt(n) phi = lambda m, v, val : 0.5 * (1+math.erf((val-m)/(v*math.sqrt(2)))) print(round(phi(mean, std, maxWt), 4))
""" Utily functions to process audio files """ import os import sys import wave def pcm_to_wave(pcm_file_path, num_channels=1, num_bytes=2, frame_rate=16000, nframes=0, comp_type="NONE", comp_name="NONE"): """ Converts a raw .pcm file to .wav file Args: pcm_file_path (str): Fu...
import os import csv csvpath = os.path.join("Resources", "election_data.csv") output_file = os.path.join("analysis", "PyPoll.txt") Total_vote = 0 Newlist =[] Newlist2=[] voterID_List = [] Location_List = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = ne...
""" Company Name : DropBox Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6] secondlargestelement >>> [5] """ def findSecondLargestNum(arr:list): max = arr[0] for num in arr: if num > max: max = num secondlargest = 0 f...
from src.DNA import DNA from matplotlib import pyplot as plt import random class population: def __init__(self, d, amount, cluster1, cluster2,mutation): self.d = d self.amount = amount self.cluster1 = cluster1 self.cluster2 = cluster2 self.generations = 0 self.muta...
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression temperatures = np.array([29,28,34,31, 25,29,32,31, 24,33,25,31, 26,30]) drink_sales = np.array([7.7,6.2,9.3,8.4, 5.9,6.4,8....
""" name_game.py Translate the input name to the Name song """ import sys while True: try: name = input("Please type a name: ") except EOFError: sys.exit(0) rest = name[1:] nameGame = name + "," + name + ",bo-b" + rest + "\n" nameGame += "Banana-fana fo-f" + rest + "\n" name...
print("You were having a great summer by yourself alone in the middle of the ocean on a boat. You take a little nap to take a break from your self pity session. When you wake up, you find yourself on an island and your boat is broken. You are really hungry but you also need shelter. Will you find food or shelter?") ...
import sys from computer import Computer def solve(intcode): total = 0 results = [] for y in range(50): row = [] results.append(row) for x in range(50): computer = Computer(intcode) computer.push_input(y) computer.p...
def part1(line): visits = {} (x,y) = (0,0) visits[(x,y)] = 1 for move in line: if move == 'v': y -= 1 elif move == '^': y += 1 elif move == '<': x -= 1 elif move == '>': x += 1 else: print(f'unexpec...
"""A solution to an Advent of Code puzzle.""" import os.path INPUT = "input.txt" def part1(lines): """Solve part 1 of the problem.""" totals = totalize_calories(lines) return max(totals) def part2(lines): """Solve part 2 of the problem.""" totals = totalize_calories(lines) total...
"""A solution to an Advent of Code puzzle.""" def part1(lines): """Solve part 1 of the problem.""" total = 0 for line in lines: total += to_decimal(line.strip()) return to_snafu(total) SNAFU = {"2": 2, "1": 1, "0": 0, "-": -1, "=": -2} DECIMAL = {2: "2", 1: "1", 0: "0", -1: "-", -2: "="} ...
""" The main file of the BlockBuster. Run it to play and have fun! """ from gamedata import Assets from gameclock import GameClock from pygame import init from pygame.display import set_caption, set_icon, set_mode, get_surface, flip from pygame.event import get from constants import LEVEL_WIDTH, LEVEL_HEIGHT from GameS...
num =10 if num == 8: print("8") elif num == 6: print("6") else: print("10") print("end")
import sqlite3 con = sqlite3.connect('data.db') cur = con.cursor() cur.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY ASC, name TEXT UNIQUE, price REAL)') cur.execute('INSERT INTO items VALUES (null, "chair", 1500)') cur.execute('INSERT INTO items VALUES (null, "cupboard", 3000)') cur.execute('CREATE...
class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if len(intervals) == 0: return [] intervals.sort(key=lambda item: item.start) ret = [] l = intervals[0].start r = inter...
class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ i = l1 prei = i j = l2 prej = j head = tmp = ListNode(0) while i != None and j != None: ...
class Solution(object): def reverse(self, nums, l, r): while(l < r): nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nu...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ arr = [] for i in s: if i == '(' or i == '[' or i == '{': arr.append(i) elif i == ')': if len(arr) > 0 and arr[-1] == '(': ...
print('introduce la altura de tu trianuglo') altura = int(input()) anchura = altura for i in range(altura): print() anchura = altura-(1*i) for i in range(anchura): print('*', end='')
import unittest from unittest.mock import * from sample.friendships import FriendShips class TestFriendships(unittest.TestCase): def test_make_friends(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") self.assertEqual(temp.data, {"Kowalski": ["Nowak"], "Nowak": ["Kowalsk...
"""Cannon, hitting targets with projectiles. Exercises 1. Keep score by counting target hits. 2. Vary the effect of gravity. 3. Apply gravity to the targets. 4. Change the speed of the ball. Integrantes: Karen Lizette Rodríguez Hernández - A01197734 Jorge Eduardo Arias Arias - A01570549 Hernán Salinas Ibarra - A0157...
import keywords_dict as kd keywords = kd.get_keywords() def key_replace(x): if isinstance(x, str): for k in keywords: if str.lower(x).strip() in keywords[k]: return k return x else: return '' def clean_data(x): if isinstance(x, list): return [s...
import encryption e_key = input("Key: ").upper() e_msg = input("Messege: ").upper() print("\nPress 1 for Encryption.") print("Press 2 for Decryption.") e_d = input("\nSelect: ") if e_d == "1": print("\nEncrypted Message: ", encryption.encrypt(e_key,e_msg)) elif e_d == "2": print("\nDecrypted Messag...
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') print('Reverse: ') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) main()
card = {} for letter in ["A", "B", "C", "D", "E"]: card[letter] = [] print(card)
def main(): name_list = [] again = 'y' while again == 'y': name = input("Enter a name : ") name_list.append(name) print('Do you want to add another name ?') again = input('y = yes, anything else = no: ') print() print('The names you have liste...
list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print(list3) days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday'] mid_days = days[2:5] print(mid_days)
number = int(input("How long you want to add?: ")) sum = 0 for i in range(0,number+1): sum = sum + i print(sum)
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') N = reverse_name(first_name, last_name) print('Reverse: '+str(N)) def reverse_name(first, last): name = last+' '+ first return name main()
def main(): get_name() print('Hi, ', name) print('welcome') def get_name(): name = input('enter your name: ') main()
r=int(input()) h=int(input()) pi=r**2*h print(pi)
import numpy as np '''integers = np.array([x for x in range(2,21,2)]) ## gives even number (third values means steps of 2) print(integers) two_dim = np.array([[1,2,3],[4,5,6]]) ## dont forget inital [] around the two sets of bracketed lists print(two_dim) ## Find the type fo elements in array print(integers.dtype)...
import json import random import constants class Board: def __init__(self, file): self.file = file self.category = "" self.phrase = "" self.guessed_letters = [] def get_phrases(self): with open(self.file, "r") as f: phrases = json.loads(f.read()) ...
""" Displaying the filters of a convolutional layer Arash Saber Tehrani """ import numpy as np import tflearn import matplotlib.pyplot as plt def filter_displayer(model, layer, padding=1): """ The function displays the filters of layer :param model: tflearn obj, DNN model of tflearn :param layer: stri...
def hourglassSum(arr): count=0 for i in range(len(arr)-2): for j in range(len(arr)-2): sum= arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] if sum>count: count = sum return count arr = [] for _ in range(6)...
class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] stack = [root] ans = [] reverser = -1 while stack: reverser = -reverser cu...
class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ def dfs(root, target): if not root: return None if root == target: return [roo...
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ zero_boarder = 0 two_boarder = len(nums) - 1 i = 0 while i <= two_boarder: while i < tw...
class Solution: def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: rmax, cmax = len(maze), len(maze[0]) visited = set([]) q = [(start[0], start[1])] while q: r, c = q.pop() if r == destination[0] and c == destination[1...
class Solution: def numSteps(self, s: str) -> int: carry = 0 step = 0 for i in xrange(len(s) - 1, 0, -1): if int(s[i]) + carry == 1: carry = 1 step += 2 else: step += 1 return step + carry
from collections import namedtuple class BoardGame: BOARD_X = None BOARD_Y = None SQUARE_TYPES = {} SQUARE_COORDS = {} TILES = {} Square = namedtuple("Square", "tile type") SquareMultiplier = namedtuple("SquareMultiplier", "letter word") Tile = namedtuple("Tile", "count value")...
def greedyChange(coin, money): count = 0 i = 0 while(money != 0): if(coin[i] <= money): money -= coin[i] count += 1 else: i += 1 return count count = 0 coin = [500, 100, 50, 10, 5, 1] price = int(input("")) money = 1000-price print(greedyChange(...
""" Created on Sat Sep 12 11:23:08 2020 @author: pi """ try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) except: pass from time import sleep class FloatSwitch(): """a class to handle the float switch pin, integer - the pin on the GPIO board that float switch is connected to switch, ...
def doit(func): result = func() print(result) def hello(): return "HELLO" doit(hello) doit(lambda : "wombats!") fruits = ["pomegranate", "cherry", "apricot", "apple", "lemon", "kiwi", "orange", "lime", "watermelon", "guava", "papaya", "fig", "pear", "banana", "tamarind", "persi...
person = 'Bill', 'Gates', 'Microsoft' junk1 = 'hello' junk2 = 'hello', print(person, len(person), person[0]) def greet(whom): print("Hello,", whom[0]) greet(person) first_name, last_name, product = person print(first_name, last_name, '\n') people = [ ('Melinda', 'Gates', 'Gates Found...
import getpass name = 'Anne' color = 'red' value = 27 print(name, color, value) print(name, color, value, sep='/') print('name', end="=>") print(name) with open('DATA/mary.txt') as mary_in: for raw_line in mary_in: line = raw_line.rstrip() print(line) with open('DATA/mary.txt'...
""" @author: jstrick Created on Sun Jun 9 21:36:10 2013 """ from pandas.core.frame import DataFrame from printheader import print_header cols = ['alpha','beta','gamma','delta','epsilon'] index = ['a','b','c','d','e','f'] values = [ [100, 110, 120, 130, 140], [200, 210, 220, 230, 240], [30...
import sys import datetime if len(sys.argv) < 3: print("Please enter two dates in format YYYY-MM-DD") sys.exit(1) year, month, day = sys.argv[1].split("-") this_date = datetime.date(int(year), int(month), int(day)) year, month, day = sys.argv[2].split("-") that_date = datetime.date(int(year), i...
from datetime import datetime,date,time,timedelta print("date.today():",date.today()) now = datetime.now() print("now.day:",now.day) print("now.month:",now.month) print("now.year:",now.year) print("now.hour:",now.hour) print("now.minute:",now.minute) print("now.second:",now.second) d1 = datetime(2007,...
import csv with open('DATA/presidents.csv') as pres_in: rdr = csv.reader(pres_in) for row in rdr: term, first_name, last_name, birthplace, birth_state, party = row term = int(term) print(last_name, party) print('-' * 60) with open('DATA/presidents.tsv') as pres_in: rd...
import re s1 = sum([x*x for x in range(10)]) s2 = sum(x*x for x in range(10)) print(s1,s2) print() pg = open("../DATA/mary.txt") s = set(word.lower() for line in pg for word in re.split(r'\W+',line)) pg.close() print(s) print() keylist = ['OWL','Badger','bushbaby','Tiger','GORILLA','AARDVARK'] ...
import sys import time right_now = time.time() print("It is {0} seconds since 1/1/70".format(right_now)) time.sleep(5) now_asc = time.asctime() print("it is now",now_asc) now_ctime = time.ctime() print("it is now",now_ctime) time_str = "Jan 14, 1971" print('Time string:',time_str) parsed_time ...
fruits = ['watermelon', 'apple', 'kiwi', 'lime', 'orange', 'cherry', 'banana', 'raspberry', 'grape', 'lemon', 'durian', 'guava', 'mango', 'papaya', 'mangosteen', 'breadfruit'] s = slice(5) print(fruits[s]) print() s = slice(-5,None) print(fruits[s]) print() s = slice(3,8) print(fruits[s]) print()...
def binarySearch(N, A, key): lt, rt = 0, N-1 while lt <= rt: mid = (lt + rt) / 2 if A[mid] == key: return 1 elif A[mid] > key: rt = mid - 1 else: lt = mid + 1 return 0 N = int(input()) A = list(map(int, input().split())) M = input() B =...
import argparse parser = argparse.ArgumentParser(description='Add two numbers') parser.add_argument('--a', type = int ,metavar = '',required=True, help = 'First Number') parser.add_argument('--b', type = int ,metavar = '',required=True, help = 'Second Number') args = parser.parse_args() def myAdd(a,b): re...
import unittest from number import Number class decimalTestCase(unittest.TestCase): def test_1_is_roman_numeral_I(self): test_num = Number(1) self.assertTrue(test_num.convert_to_roman() == 'I') def test_2000_is_roman_numeral_MM(self): test_num = Number(2000) self.assertTrue(te...
import random print('Here is one random number between 1 and 3!') print(1 + 2 * random.random()) print('You\'re welcome!')
n = int(input()) sum_sq = 0 while n != 0: sum_sq += n ** 2 n -= 1 print(sum_sq)
n = int(input()) i = 1 counter = 0 while i <= n: int_to_str = str(i) reverse_num = (int_to_str[::-1]) if i == int(reverse_num): counter += 1 i += 1 print(counter)
n = int(input()) total = 0 while n != 0: total += n n = int(input()) print(total)
""" https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/546/ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice...
import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt labels = 'Reading', 'Sleeping', 'Others', 'Chatting' sizes = [15, 30.0, 45.0, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'red'] explode = (0, 0.1, 0, 0) plt.pie(sizes, explode = explode, labels = labels, colors = colors, auto...
import Data import random class Initial: def __init__(self): self.chromosome = "" self.cost = 0 def set_height(self): h = random.randint(0, 3) self.chromosome = self.chromosome + Data.height[h][1] self.cost += Data.height[h][2] def set_width(self): w = ra...
def main(): N = int(input()) num_list = list(input()) total = 0 for num in num_list: total += int(num) print(total) if __name__ == "__main__": main()
def groupword_checker(word): for i in range(len(word) - 1): if word[i] != word[i + 1]: if word[i] in word[i + 1:]: return False return True def count_group_words(word_list): groupword_cnt = 0 for word in word_list: if groupword_checker(word): grou...
def count_croatia_alpha(word): croatia_alpha_list = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='] croatia_alpha_cnt = 0 idx = 0 while len(word) > idx: if word[idx : idx + 2] in croatia_alpha_list: idx += 2 elif word[idx : idx + 3] in croatia_alpha_list: idx +=...
from itertools import combinations def solution(relation): rows = len(relation) cols = len(relation[0]) candidates = [] for i in range(1, cols + 1): candidates.extend(combinations(range(cols), i)) final = [] for keys in candidates: tmp = [tuple([item[key] for key i...
def check(x,y,n): if n == 1: return True for i in range(n): for j in range(n): if board[x+i][y+j] != board[x][y]: return False return True def divide(node): global blue global white x,y,size = node if check(x,y,size): if board[x][y] ==...
""" caesar.py Encrypt or decrypt text based from caesar cipher Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python """ def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift if stayI...
""" kasir.py The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. """ from math import floor uang = int(input("Masukkan uang (Rp): ")) harga = int(input("Masukkan harga barang (Rp): ")) if (uang <...
import requests import json import random def SearchRestaurant() : params = { 'entity_id' : city_id, 'entity_type' : 'city', } response = requests.get('https://developers.zomato.com/api/v2.1/search', headers=headers, params=params) data = json.loads(r...
import os def list_files(path): return [name for name in os.listdir(path) if (os.path.isfile("{}/{}".format(path,name)))] def list_folders(path): return [name for name in os.listdir(path) if (os.path.isdir("{}/{}".format(path,name)))]