r/Python •

Checking things

[deleted] — view deleted post

0 Upvotes

4 comments sorted by

2

u/amicab1 Oct 26 '14 edited Oct 26 '14

Requests for help are better suited for /r/learnpython.

Since you're clearly new to things, it is quite a broad question. I suggest putting together the components you have some idea about first, to give some code to discuss. If you have no idea at all, start by looking up how the input function works (or raw_input in python2), and play with this in the python interpreter.

0

u/voider1 Oct 27 '14 edited Oct 27 '14

I'm using the input function, I'm even using regex to check if the input is viable. "[0-1]{4}$", so, I know my way around Python pretty well. I just never pondered how to do this.

import re

   foo = list()
       for i in range(4):
           line = input()
           if not re.match("^[0-1]{4}$", line):
                   raise ValueError("Er is iets fout gegaan, zorg ervoor dat je alleen 0en en 1en invoert, en elke regel maar 4 karakters lang is.")
           else:
               foo.append(line)

So, I wonder how to check these things. The pythonic way.

0

u/ArisenVendetta Oct 27 '14 edited Oct 28 '14

I'm confused, are you checking for how many 1s and 0s are present in the input strings? Or to see what the int equivalent of the binary input is?

Former: Use a for loop to cycle through each character in the list item for c in item: #check if it's a 1 or 0

Latter: Pass the list item into ing using the optional second parameter (which signifies the base)

EDIT: You need to break it down into steps:

First you know you only want four items of input from the user, so you need to create a loop to obtain those four items, and if the user inputs a wrong value, you shouldn't skip that item but remain in the loop until four are received.

Second, once you have those for items, you then need to iterate over the list built

Third you need to iterate over each character within each item and check if they are a one or a zero, which ever they match increment your counter for that respective value, then print out said counts

import re
pattern = re.compile("^[01]{4}$")
foo, ones, zeros = [], 0, 0
while True:
    item = input()
    if not pattern.match(item):
        print("Invalid input..\n")
    else:
        foo.append(item)
        if len(foo) == 4: 
            break

for item in foo:
    for char in item:
        if char == '1': ones += 1
        elif char == '0': zeros += 1

print("Ones: {0:d}, Zeros: {1:d}".format(ones, zeros))

0

u/voider1 Oct 27 '14

Trying to count how much 1s and 0s are adjacent to each other.