python – Do I have to repeat the useless condition?

I would like to know what is the best way to handle a situation in which I repeatedly check a condition in a function using an if-elif-else string, and if the condition is different, I throw an exception. Is it better to repeat exactly the same if-elif-else string, knowing that the else condition will never occur, or, since I know it, to change the last elif to another? My question is probably better explained by an example.

One option is to repeat the entire if-elif-else string, knowing that the last other the conditions will never be reached. For example:

a = 5
if case == "case1":
a + = 5
case elif == & # 39; cas2 & # 39 ;:
a - = 5
other:
raise Exception ('unrecognized case')
# do a bunch of other steps
# then, later ...
if case == "case1":
a * = 5
case elif == & # 39; cas2 & # 39 ;:
a / = 5
else: # this will never happen, should I remove it?
raise Exception ('unrecognized case')

Another option is to replace the last final elif with another, as follows:

a = 5
if case == "case1":
a + = 5
case elif == & # 39; cas2 & # 39 ;:
a - = 5
other:
raise Exception ('unrecognized case')
# do a bunch of other steps
# then, later ...
if case == "case1":
a * = 5
else: # I know that's the case 2
a / = 5

My goal is to make the code correct and expandable. There are many cases, although I only implemented the code for two of them. I would like to be able to implement them one by one when I need them. For the moment, I need only these two cases, but in a month, I may need two more. I will implement them when I do it and I want the code to make sense with any reasonable number (<= 8) of cases.

In the first example, have a other condition that is never used seems like a waste. In the second example, the last other works more like a "I know that's the case 2", which is fine for the moment, but when I get into the case3, I have to remember that this is not really the "other" situation, but the "case 2" situation. A third option is to completely delete the last other of the first example, but then there is only one if and elif, and it seems like a typo or an error is created to create a hard-to-find bug.

python – How to add characters to a string according to a predefined condition?

My question is this, after receiving a string (which can be composed of numbers or letters), return this string with the addition of an SE character in this string. Characters are repeated in SEQUENCE.

Using Python I know that there are modules such as the counter that returns the number of repetitions of a character in a string, but I need to know if this character is repeated N times in a row.

I thought I would solve my problem by browsing the user input, turning it into a list and adding the character after the sequence, but I do not know if it's the most pythonic way of do it.

Example:

If the user provides input "abaabaaaabab".

After the letter "a" repeats 4 times in succession, add the letter "c" after that.

The output would be:

"Abaabaaaacbab"

Python Development Services – Everything Else

Python is a general language, which means that you can develop anything with the right tools and libraries. It is a dynamic, object-oriented, and versatile programming language designed to learn, use, and easily apply clean, uniform syntax. Professionally, Python is ideal for web development structure, data analysis and artificial intelligence. Many developers choose the Python framework to create productivity tools, games and desktop applications. Many companies are advised to develop their application using the python framework. What are the advantages of python: –

It's free: – Python is an open-source framework. It has a very wide range of features, but it's still free. Reduced costs are always good for your business.

All types of companies can afford it: – As a free platform, it is available to all small and medium businesses that can use it. Growing companies can use the Python development platform and start their operations with cost-effective software. The development process is fast, which makes it ideal for startups.

The big giants use it: – Python is not only suitable for small and medium businesses, but it is also used by leading companies such as Google, Spotify, Instagram and Dropbox, which also guarantee the development of Python compared to other languages.

Python is for everyone involved in software development: – Python is a development framework that would make great software. Python has all the features that make it a true language accepted and appreciated around the world.

In the digital world, companies depend on the software and its features, but especially on the way the software is coded. Programming languages ​​help you develop well-coded software that will eventually lead to a large enterprise. Mobiloitte is a Python development company, which provides flexible web application development with enhanced features to keep your business on track.

.

Python 3.x – How to make curls in scrapy?

I scrape a Dmoz website. I want to make a loop in the functions because the for the loop that I use in each function, I will have to put it again and again in each function. Although their functionality is the same. The second thing I want to solve is to make a loop in performance response. because if I scratched more pages, I should write this again and again. Is there a way to my two problems. I have tried several times but I have failed.

                                # save and call the request on another page
return response.follow (self.about_page, self.parse_about, meta = {items: items})
return response.follow (self.editor, self.parse_editor, meta = {items: items})

def parse_about (self, response):
# do your business on the second page
items = response.meta['items']
        names = {'name1': 'Headings',
& # 39; name2 & # 39 ;: Paragraphs & # 39;
& # 39; name3 & # 39; 3 projects & # 39;
& # 39; name4 & # 39 ;: About Dmoz & # 39;
& # 39; name5 & # 39; Languages ​​& # 39;
& # 39; name6: & quot; You can make a difference & # 39;
& # 39; name7: & # 39; Additional Information & # 39;
}

finder = {# 1}: h2 :: text, #mainContent h1 :: text & # 39;
& # 39; find2 & # 39; p :: text & # 39 ;,
& # 39; find3 & quot ;: li ~ li + li b a :: text, li: n-child (1) b a :: text & # 39 ;,
& # 39; find4 & # 39; .nav ul a :: text, li: nth-child (2) b a :: text & # 39;
& # 39; find5 & # 39; .nav ~ .nav a :: text & # 39;
& # 39 ;: but & # 39 ;: dd :: text, # about-contrib :: :: text & # 39;
& # 39; find7: li :: text, # about-more-info a :: text & # 39;
}
for name, find in the zip (names.values ​​(), finder.values ​​()):
goods[name] = response.css (find) .extract ()
performance articles

Validation of date (tests) with python

Hello

I'm trying to do a date validation with Python. My exercise requires validation of months to 31 days and leap year

`def date_value (date):
Date of Valida. Receives a string in the format dd / mm / yyyy and informs
# a logical value indicating whether the date is valid or not.

day, month, year = data.split ("/")

months_31 = ("01", "02", 03 ", 05", 07 & # 39; & # 39; & # 39; 39; 08 & quot ;, & quot; 10 & # 39 ;, & quot; 12 & # 39;)

if year> 0001 & # 39; and & # 39; 12 & # 39; <= mes >= & # 39; 01 & # 39; and & # 39; 31 & # 39; <= dia >= & # 39; 01 & # 39 ;:

if int (year)% 4 == 0 and month == 2:
if day <= & # 39; 29 & # 39 ;:
returns True
if not:
returns False
elif my ==> 2 & # 39 ;:
if day <29>:
returns True
if not:
returns False

if my == meses_31 and day <=> 31:
returns True
day elif <= & # 39; 31 & # 39;
returns False

if not:
return False`

tests

def ():
print (& # 39; Valid Dates: & # 39;)
test (date_valida ("01/01/2014"), True)
test (date_valida ("31/01/2014"), True)
test (date_valida ("00/00/0000"), False)
test (date_valida ("04/30/2014"), True)
test (date_valida ("31/04/2014"), False)
test (date_valida ("30/09/2014"), True)
test (date_valida ("31/09/2014"), False)
test (date_valida ("06/30/2014"), True)
test (date_valida ("31/06/2014"), False)
test (date_valida ("30/11/2014"), True)
test (date_valida ("31/11/2014"), False)
test (date_valida ("31/01/2014"), False)
test (date_valida ("01/01/0000"), False)
test (date_valida ("13/01/2014"), False)
test (date_valida ("01/00/2014"), False)
test (date_valida ("02/29/2014"), False)
test (date_valida ("02/29/2016"), True)

I've already tried to find content and even the closest to me was in the current algorithm. Whenever I arrive in the leap year, I can not fix it and this time the code looks ok, it returns False for everything.

python – Pyfirmata Arduino: can not open port (exception in series)

I am always new to Python and I am trying to create some kind of installation monitor using an Arduino. The problem is that my program can not connect to the COM4 serial port.

of pyfirmata import Arduino
of pyfirmata import util
board = Arduino ("COM4")
it = user.Iterator (board)
it begins()

from Sensors.sensor import sensorBase
soilSensor = sensorBase ('a: 0: o')

He is wrong on the Arduino part with this error:

SerialException ("Could not open port" COM4: PermissionError (13, "Access is denied.", None, 5) ")
  • I went to the device manager and disabled the port, and then reactivated.
  • I have also stopped and restarted my PC, that does not help either.
  • I have tried running Visual Studio 2017 with administrator privileges.
  • It is possible that the port is used by another program, but I do not know how to check that. (Although I do not see why the port would be used since I rebooted cold)

python – OpenAI Gym customized approx. Example of a multi-action space or tuple space

I'm trying to implement my custom env. in the open-air gym

Until now, I use a continuous action space (6 ch)

the input dimension can therefore be used with env.action_space.shape[0]

But I found that it is not stable in my env. I decided to move to several discrete spaces, as with limited whole values ​​(100, 100, 10, 5, 6, 100).

But when I could not find an example using a multidiscret or tuple space to properly manage my actions.

Everyone knows an example that I can try for my env. Custom?

python 3.x – Pandas: Calculate the difference between a line and all other lines

I'm trying to create new columns corresponding to each date in my date column. Each column must contain the difference between the date and all other dates.

Contribution:

date
Sep 11, 18
June 8, 18
Sep 12, 17
June 12 17

The output must be:

date Diff_date1 Diff_date2 Diff_date3 Diff_date4
Sep 11, 18 0 -95 -364 -456
June 8, 18 95 0 -269 -361
Sep 12 17 364 269 0 -92
June 12 17 456 361 92 0

python – Iterate on a board and record in a dict

Given this table:

board ([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
...
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype = uint8)

I want to iterate to count the values ​​on each line, then save them per line.
The code below is a general sum. I would like to have the account per line.

number of def (image):
array = np.array (image)
board[[ array == 0 ]]= 1
board[[ array == 255 ]]= 0
for the line in the table:
single, count = np.unique (table[row,] , return_counts = True)
d = dict (zip (unique, account))
return again

The result:

{0: 234710, 1: 515}

python – Allow only the call of a class via a constructor

Suppose I have a class foo:

Foo class (object):
def __init __ (auto):
...

Now, I want to add different builders for this class. But this class should not be called directly EVER without a builder.

Foo class (object):
def __init __ (auto):
...
@classmethod
def fromSource1 (cls, source1Data, paramA, paramB):
returns cls (processData (sourceData))

@classmethod
def fromSource2 (cls, source2Data, paramC, paramD, paramE):
self = cls (processData2 (sourceData))
self.var + = paramE
return yourself

Should be called this way:

foo1 = Foo.fromSource1 (source1Data, paramA, paramB)
foo2 = Foo.fromSource2 (source2Data, paramC, paramD, paramE)

I want to prevent any user of my code from calling the Foo class this way:

foo = foo ()

Is there anything I can do to ban it?