## fibonacci sequence works, but returns results I do not expect

nterms = int(input("How many terms? ")) n1 = 0 n2 = 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence upto",n...
more »

## Length of the longest sub-array which consists of all '1'

suppose i have a list say x=[1,0,0,1,0,1,1,1,0,1,1,0].Here longest sub-array which have continuous 1 is of length 3. I have a o(n) approach but can it be done in o(logn) using segment tree and how? I am practicing problems based on segment tree and a...
more »

## Python - Confused about inheritance

I write the test code with 3 classes , and using Chain of Responsibility design pattern , the code below and I print print(c._abc is b._abc), the answer is True , but my original think is that the two are different. Then , Round 2 , I uncomment sel...
more »

## Sphinx and inherited functions

I'm trying to use Sphinx to document my Python code and I'm new to Sphinx. I'm in the following situation: from abc import ABCMeta from abc import abstractmethod class AbstractClass1(): __metaclass__ = ABCMeta def __init__(self): ...
more »

## How to split a list-of-strings into sublists-of-strings by a specific string element

I have a word list like below. I want to split the list by .. Is there any better or useful code in Python 3? a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.'] result = [] tmp = [] for elm in a: if elm is not '.': ...
more »

## How to make a grid with integers in python?

I have the following code which has to print out a board with numbers according to the size the user specified (for instance 3 means a 3 x 3 board): n = d * d count = 1 board = [] for i in range(d): for j in range(d): ...
more »

## How to separate out nested json values in pandas dataframe column?

I have data in Pandas dataframe where certain fields have nested JSONs in them: As visible in the sample data, the post_likes field has nested JSON and is sometimes blank as well. post_shares has JSON format, but just one value and it is sometimes...
more »

## append new data to json file in python

I have bellow json array in a data.json file [{"type": "Even", "id": 1}, {"type": "Odd", "id": 2}, {"type": "Even", "id": 3}] and i was trying to append new data to this json file using this code def foo(filename, dict_data): with open(fi...
more »

## Printing to NamedTemporaryFile on Windows

The original Problem - MCVE The following script should use chrome headless, to print to pdf (I am running windows 10, and python 3.6): import subprocess from tempfile import NamedTemporaryFile output = NamedTemporaryFile() CHROME_PATH=r'"C:\Prog...
more »

I have a Odoo 10 cron xml, which looks like this: <record forcecreate="True" id="saas_portal_suspend_expired" model="ir.cron"> <field name="name">Saas portal - suspend expired clients</field> <field eval="Tru...
more »

## How i can get access for '~/Applications' of iOS?

I'm trying to enter to this folder using: import os location=os.chdir('/Applications') for file in os.listdir(location): print(file) RETURN: 'Opesation not permitted' When i run this, in the pythonista app, appears an alert message B...
more »

## Django save blank value

I have a number of unknown values in a df, where the cells are filled with the chars '---' I would like to tell Django that, if it finds something that is not a number of any kind (int / decimal / floating point) to leave the value of that field bla...
more »

## Running C extension in Python faster than plain C

I have implemented a Python extension in C and found that executing a C function inside of Python to be 2x faster than just executing the C code from a C main. But why is this faster? I would expect the plain C to be exactly the same performance whe...
more »

## Create password protected zip file Python

I'm using following code to create password protected zip file, from a file uploaded by user, in my Python34 application using zipFile. But when I open the zip file from windows, it doesn't ask for the password. I will be using the same password to r...
more »

## Filter Django queryset for a dict value

I have a queryset of Products with JSONField attributes containing dict class Product(models.Model): attributes = JSONField( pgettext_lazy('Product field', 'attributes'), encoder=DjangoJSONEncoder, default={}) I want to filter Products wh...
more »

## Is there a way to set a list value in a range of integer in python

I want to perform the following: >>> [0-2, 4] #case 1 [-2, 4] #I want the output to be [0, 1, 2, 4] I know I can perform the same in this way: >>> list(range(3)) + [4] #case 2 [0, 1, 2, 4] But I am curious is there any ...
more »

## Filter list of dict based on values from another dict

I have a list of dictionaries list_of_dict, a set of keys set_of_keys and another dictionary dict_to_compare. I need to filter the list of dicts if the values of any two of the three possible keys matches the values from dict_to_compare. Input: s...
more »

## OSError: [WinError 6] The handle is invalid when calling subprocess from Python 3.6

I'm porting a project to Python3 and I'm running into a unexpected error on Windows: Basically on Python 3.6 on Windows, each time a process is being created with subprocess, I have this exception: d:\temp\backpack\venv\myvenv_py3.6\lib\site-packag...
more »

## Save sentence as server filename

I'm saving the recording of a set of sentences to a corresponding set of audio files. Sentences include: Ich weiß es nicht! ¡No lo sé! Ég veit ekki! How would you recommend I convert the sentence to a human readable filename which will later...
more »

## How to loop through multiple lists sequentially with one loop?

In Python 3.6.3 Is there a way to loop though one list after another? For example: deck = [(value, suit) for value in range(2, 11) + ["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]] (In this case, I want to loop through the face...
more »

## How to check if elements in list 'a' meet conditions in list 'b'?

I have a list of numbers: a = [3, 6, 20, 24, 36, 92, 130] And a list of conditions: b = ["2", "5", "20", "range(50,100)", ">120"] I want to check if a number in 'a' meets one of the conditions in 'b' and if yes, put these numbers in list 'c'...
more »

## Python 3 - convert the staircase from right-aligned to LEFT ALIGNED, composed of # symbols and spaces

sc = [] n = 6 for i in range(n): sc.append("#") scstr = ''.join(map(str, sc)) print(scstr) I tried to use the code below to reverse the output by adding padding white spaces but it prints out a distorted staircase. # print(scstr.rjust(...
more »

## convert a dict field to **list** for use in **enumarate**

I have an object which can be either JSON or dict (I dont know which one will happen): type 1 : q = {result : {"info" : "info"}} or type 2 : q = {result : [{"info" : "info"} , {"info" : "info"}]} I want to iterate a procees for each result. for ...
more »

## Why is a compiled python regex slower?

In another SO question, the performance of regexes and Python's in operator were compared. However, the accepted answer uses re.match, which only matches the beginning of a string, and thus behaves completely different to in. Also, I wanted to see th...
more »

## Error Message "Xcode alone is not sufficient on Sierra"

I'd like to install openCV to vectorize image, but there's a series error message regarding Xcode and Ruby. First, I use terminal to install openCV, brew install opencv. Then, I got error message indicating that the system doesn't like my ruby ver...
more »

## Catch exception while reading file line by line in Python 3

Consider the following code: with open('file.txt', 'r') as f: for line in f: print(line) In Python 3, the interpreter tries to decode the strings it reads, which might lead to exceptions like UnicodeDecodeError. These can of course be ...
more »

## Search for particular text in txt file and print next line

I am trying to read a text file that contains BEGIN frequently but only once in a line. I have been able to search for it however unable to print the line next to it if someone could guide me or help me on how to go about this. Below is the code Cod...
more »

## Flatten multi dimensional array in python 3

I have a list of numbers: testList = [1, [1], [12], 2, 3] I want it to become: flatList = [1, 1, 12, 2, 3] Using a typical list comprehension such as below is not working. flatList = [val for sublist in testList for val in sublist] TypeError: 'i...
more »

## UnicodeDecodeError: 'utf-8' codec can't decode - Python3

Im writing a django site which grabs json data from several URLS (i'm using python3). Im getting "UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 0: invalid start byte" I've looked around and it seems to be because of one or mor...
more »

## How to find out if two elements belong to the same list

I have a few lists, each containing several cities. I need to check for any two random elements if they belong to the same list. Simple example: list1 = ['London', 'Manchester', 'Liverpool', 'Edimburgh'] list2 = ['Dublin', 'Cork', 'Galway'] list3 =...
more »

## When to use multiple event loops?

I have a web app built on a Python 3.5+ async framework (apistar, sanic, etc). The app makes various IO calls - to a database, Redis, etc - which are also async. Some docs recommend using an additional event loop: import asyncio import peewee from ...
more »

## Calculating Big O Notation with Recursion

I have try to understand the Big O Notation worst case runtime. But I still don't quite understand it. This is some code that I wrote recently: def g(n): if n==0: return 1 elif n==1: return 2 else: n_div=n//2 ...
more »

## Python3: Parsing text using dynamic variable and search the section …

I have text file which is made up with several sections. Sections always started with non-space. And sub-section always started with space. Based on input.txt, following is my expected result. in this example i am trying to search for “101” and i...
more »

## Why can't I 'yield from' inside an async function?

In Python 3.6, I am able to use yield inside a coroutine. However I am not able to use yield from. Below is my code. On line 3 I await another coroutine. On line 4 I try to yield from a file. Why won't Python 3.6 allow me to do that? async def rea...
more »