The goal of this function is to flip a matrix-like string horizontally.
For example the string: '100010001' with 2 rows and three columns would look like:
1 0 0
0 1 0
0 0 1
but when flipped should look like:
0 0 1
0 1 0
1 0 0
So the function would return the following output:
'001010100'
The caveat, I cannot use lists or arrays. only strings.
The current code I have written up, I believe, should work, however it is returning an empty string.
def flip_horizontal(image, rows, column):
horizontal_image = ''
for i in range(rows):
#This should slice the image string, and map image(the last element in the
#column : to the first element of the column) onto horizontal_image.
#this will repeat for the given amount of rows
horizontal_image = horizontal_image + image[(i+1)*column-1:i*column]
return horizontal_image
Again this returns an empty string. Any clue what the issue is?
Use [::-1] to reverse each row of the image.
def flip(im, w):
return ''.join(im[i:i+w][::-1] for i in range(0, len(im), w))
>>> im = '100010001'
>>> flip(im, 3)
'001010100'
The range function can be used to isolate your string into steps that represent rows. While iterating through the string you can use [::-1] to reverse each row to achieve the horizontal flip.
string = '100010001'
output = ''
prev = 0
# Iterate through string in steps of 3
for i in range(3, len(string) + 1, 3):
# Isolate and reverse row of string
row = string[prev:i]
row = row[::-1]
output = output + row
prev = i
Input:
'100
010
001'
Output:
'001
010
100'
Related
I got a "input.txt" file that contains lines like:
1 66.3548 1011100110110010 25
Then i apply some functions column by column:
column stays the same,
column is rounding in a spesific way,
column is converted from binary to decimal,
column is converted from hexadecimal to binary.
And finaly i get this:
[1.0000000e+00 6.6340000e+01 4.7538000e+04 1.0010100e+05]
Then i write this to "fall.txt".
All the operations is working correctly. But i want to see the numbers like:
1 66.34 47538 100101
I placed the columns of the relevant rows in list_for_1. Then i applied the functions to indexes and put them to another list list_for_11. Finally i put all the answers in a matrix. I wrote the matrix to the "fall.txt".
Here's what i did:
with open("input.txt", "r") as file:
#1. TİP SATIRLAR İÇİN GEREKLİ OBJELER
list_for_1 = list()
list_for_11 = list()
#list_final_1 = list()
for line in file:
#EĞER SATIR TİPİ 1 İSE
if line.startswith("1"):
line = line[:-1]
list_for_1 = line.split(" ") #tüm elemanları 1 listede toplama
#1. tip satır için elemanlara gerekli işlemlerin yapılması
list_for_11.append(list_for_1[0]) #ilk satır 1 kalacak
list_for_11.append(float_yuvarla(float(list_for_1[1]))) #float yuvarlama
list_for_11.append(binary_decimal(list_for_1[2])) #binary'den decimal'e
list_for_11.append(hexa_binary(list_for_1[3])) #hexa'dan binary'e
m = 0
n = 0
array1 = np.zeros((6,4))
for i in list_for_11: #listedeki elemanları matrise yerleştirme
if(m > 5):
break
if(isinstance(i, str)):
x = int(i, 2)
array1[m][n] = float(i)
n += 1
if(n == 4):
n = 0
m += 1
with open("fall.txt","w") as ff:
ff.write(str(array1))
ff.write("\n")
Over here i actually send float type to matrix but it's not working:
if(isinstance(i, str)):
x = int(i, 2)
array1[m][n] = float(i)
I'm sort of a new python user, so i might write unnecessarily long and complex codes. If there's any shorter way to do what i did, i would like to get opinions for that as well.
Here's a function to format your numbers the way you want them:
def formatNumber(num):
if num % 1 == 0:
return int(num)
else:
return num
Your list of numbers:
l = [1.0000000e+00, 6.6340000e+01, 4.7538000e+04, 1.0010100e+05]
Reformatting your list of numbers:
for x in l:
print(formatNumber(x))
Output:
1
66.34
47538
100101
The input for the code is supposed to be something like
10
1 0 1 0 1 0
and the output is supposed to be the absolute value difference of the number of 1s and 0s. The code works when I enter just the 2nd line but when I enter the first line the array is only [1, 0] so the output doesn't work either. How can I make it so both lines are registered?
array = input()
array = array.replace(" ","")
array = [int(x) for x in str(array)]
one = (array.count(1))
zero = (array.count(0))
output = zero - one
if output < 0:
#output = output * -1
print(output)
You want to take 2 lines of input from the user. But input always only reads 1 line. However, you may make 2 calls to input, one for each line, then join the two lines. E.g.
array = input() # line 1
array += input() # line 2
The rest of your code could be written as follows:
array = array.replace(" ","")
array = [int(x) for x in array]
one = array.count(1)
zero = array.count(0)
output = zero - one
print(output)
I was tasked with creating a function that looks for the unique char in a string and from there add the value of that to 10. For this specific scenario dice_str will always have a len of 3, and there will always be a unique char within that str. This is my code so far:
def get_point_score(dice_str):
unique = ""
i = 0
while len(unique) != 1:
if dice_str[i] not in dice_str[i+1:]:
unique += dice_str[i]
sum = 10 + int(unique)
else:
i += 1
unique += unique
return sum
Expected output:
dice_str = "141"
value = 14
Got:
value = 11
We were asked to solve this using while loops, indexing and find().
I was thinking of iterating through every element in the string and using indexing to see if it is repeated, and if it is repeated to increment i by 1 and continue checking until this is no longer the case. From the output it looks like I have failed to implement this properly, so then I was thinking of using find() and once find() returns -1, add the element to the empty string, but I also am not sure how to implement that properly. Any help would be appreciated
Your problem is your check if dice_str[i] not in dice_str[i + 1:]:.
Take note of this example "116"
On your first time through you will check if 1 is in 16. Which it is.
Then you check if 1 is in 6 which it is not. But then you perform this operation:
unique += dice_str[i]
However in this case, your unique value is 6 (index i + 1) not 1 (index i).
You were really close in your implementation. Instead of testing if a value is not in the next slice up, you can build a list that excludes the current index, and test against that instead:
def get_point_score(dice_str):
i = 0
unique = None
while not unique:
if dice_str[i] not in (dice_str[:i] + dice_str[i + 1:]):
unique = dice_str[i]
i += 1
return 10 + int(unique)
*Warning this will raise an error if your list does not contain at least one unique value.
Given that you're guaranteed a length 3 string with a single unique character, you can just do left/right comparison.
def get_point_score(dice_str):
left_match = dice_str[0] == dice_str[1] # Do 0 and 1 Match?
right_match = dice_str[1] == dice_str[2] # Do 1 and 2 Match?
if not left_match and not right_match:
# Neither Match (Middle Unique)
unique = dice_str[1]
elif left_match:
# 0 and 1 Match, but 1 and 2 don't (Right Unique)
unique = dice_str[2]
else:
# 0 and 1 Don't Match, but 1 and 2 do (Left Unique)
unique = dice_str[0]
return 10 + int(unique)
print(get_point_score("116"))
print(get_point_score("141"))
print(get_point_score("722"))
Output:
16
14
17
Given a list of numbers containing either 0's, 1's, or -1's, how can I find the longest portion of the list that starts with a +1 and ends with a -1.
For example, [0,0,1,1,1,-1,-1,-1,0] : The longest portion is 6 due to the portion of the list [1,1,1,-1,-1,-1].
For example, [1,-1,0,1,-1,-1,-1] : The longest portion is 4 due to the portion of the list [1,-1,-1,-1]. Note that had the original list only been the first 3 elements (e.g., [1,-1,0]), then the correct answer would have been 2 [1,-1].
Also, the list cannot be broken with a 0 and it can only alternate from +1 to -1 once. In other words [+1,-1,+1,-1] is still only 2.
Thank you
You need has two bool(previous_has_one exist, previous_has_neg_one) to record them exist or not.
def getLongestPortion(l):
maxx = 0
curMax = 0
JustHadOne = False
JustHadNeg = False
for i in range(len(l)):
if(l[i]==1):
if(JustHadNeg):
curMax = 0
curMax += 1
JustHadOne = True
JustHadNeg = False
elif(l[i]==-1 and JustHadOne):
curMax += 1
maxx = max(maxx,curMax)
JustHadNeg = True
else:
JustHadOne = False
JustHadNeg = False
curMax=0
return maxx
l = [1,-1,-1,0,1,1,-1,-1]
print(getLongestPortion(l))
Here's a regex solution. First I change a list like [1, -1, 0, 1, -1, -1, -1] to a string like 'ab abbb', then I search for 'a+b+', then take the maximum length of the matches:
import re
max(map(len, re.findall('a+b+', ''.join(' ab'[i] for i in l))))
I'm trying to understand why I'm having the same index again when I apply .index or .find
why I'm getting the same index '2' again why not '3'? when a letter is repeated, and what is the alternative way to get an index 3 for the second 'l'
text = 'Hello'
for i in text:
print(text.index(i))
the output is:
0
1
2
2
4
It's because .index() returns the lowest or first index of the substring within the string. Since the first occurrence of l in hello is at index 2, you'll always get 2 for "hello".index("l").
So when you're iterating through the characters of hello, you get 2 twice and never 3 (for the second l). Expanded into separate lines, it looks like this:
"hello".index("h") # = 0
"hello".index("e") # = 1
"hello".index("l") # = 2
"hello".index("l") # = 2
"hello".index("o") # = 4
Edit: Alternative way to get all indices:
One way to print all the indices (although not sure how useful this is since it just prints consecutive numbers) is to remove the character you just read from the string:
removed = 0
string = "hello world" # original string
for char in string:
print("{} at index {}".format(char, string.index(char) + removed)) # index is index() + how many chars we've removed
string = string[1:] # remove the char we just read
removed +=1 # increment removed count
text = 'Hello'
for idx, ch in enumerate(text):
print(f'char {ch} at index {idx}')
output
char H at index 0
char e at index 1
char l at index 2
char l at index 3
char o at index 4
If you want to find the second occurance, you should search in the substring after the first occurance
text = 'Hello'
first_index = text.index('l')
print('First index:', first_index)
second_index = text.index('l', first_index+1) # Search in the substring after the first occurance
print('Second index:', second_index)
The output is:
First index: 2
Second index: 3