Print array elements in reverse order - arrays

The first line contains an integer N, (the size of our array).
The second line contains N space-separated integers describing array's(A's) elements.
I have tried the following, however I looked at the solution page. However I do not understand how this code works. Can someone please explain it to me. I am pretty new in this coding world.
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
input 1234
output 4 3 2 1

In Python3:
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print(" ".join(str(x) for x in arr[::-1]))
Input:
1 4 3 2
Output:
2 3 4 1

You are creating a list of integer values, by removing spaces and splitting the values at ' '. After obtaining the list of integers, you are iterating over the list and converting the ith element from the back (a negative value of index denotes element with ith index from right and it is 1 based) of arr back to string and printing the number.
Example:
arr = [1,2,3,4]
print(arr[1]) #prints 2 on the console, i.e 2nd element from the left.
print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.

Let's take this code snippet
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
The method input() will take the user input from key board. int(input()) will convert the input into int, if the input is in string format. like "4" instead of 4. The input value stored into variable n.
The Array input will be like this "1 2 3 4". So, we need to separate the string with space delimiter.
The strip() method returns a copy of the string with both leading and trailing characters removed.
The split() method returns a list of strings after breaking the given string by the specified separator.Here the separator is space. So, split(' ')
input().strip().split(' ') will take "1 2 3 4" as input and the output is "1" "2" "3" "4".
Now we need to take each element after separated. And then covert into int and store into array.
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
arr_one is a variable, this variable stores each element after split. For each element, we converted it into int and then storing into a array arr.
In python, array index start from 0. If we want to access from last index in the array, the index will start from -1, -2, -3, and so on.
for i in range(len(arr)): The for loop will iterate from index 0 to length of the array. in this example, size is 4.
printing array elements from index -1. and the end argument is used to end the print statement with given character, here the end character is " ". So the output will be 4 3 2 1.

The above code can be rewritten as below with more readability.
if __name__ == '__main__':
n = int(input())
inp = input("Enter the numbers seperated by spaces:::")
inp = inp.strip() # To remove the leading and trailing spaces
array = []
for item in inp.split(' '): # Splitting the input with space and iterating over each element
array.append(int(item)) # converting the element into integer and appending it to the list
print(array[::-1]) # here -1 says to display the items in the reverse order. Look into list comprehension for more details
For more details on list slicing, look in the python documentation.

Try this!
if __name__ == '__main__':
n = int(input()) # input as int from stream
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
"""
1. asking for input from user
2. strip() function removes leading and trailing characters.
3. split(' ') function split your input on space into list of characters
4. arr_one variable contains yours splited character and your iterating over it using for loop
5. int(arr_one) converts it into integer and [] is nothing just storing everything into another list.
6. In last you are assigning new list to arr variable
"""
for i in reversed(arr): # loop over list in reverse order with built in fucntion
print(i, end = " ") # printing whatever comes in i
It should work like this:
3 # your n
1 2 3 # your input
3 2 1 # output

Related

ruby - How to make an array of arrays of letters (a-z) of varying lengths with maximum length five

So I'm trying to make an array of all possible permutations of the alphabet letters (all lowercase), in which the letters can repeat and vary in length from 1 to 5. So for example these are some possibilities that would be in the array:
['this','is','some','examp','le']
I tried this, and it gets all the variations of words 5 letters long, but I don't know how to find varying length.
("a".."z").to_a.repeated_permutation(5).map(&:join)
EDIT:
I'm trying to do this in order to crack a SHA1 encrypted string:
require 'digest'
def decrypt_string(hash)
("a".."z").to_a.repeated_permutation(5).map(&:join).find {|elem| Digest::SHA1.hexdigest(elem) == hash}
end
Hash being the SHA1 encryption of the word, such as 'e6fb06210fafc02fd7479ddbed2d042cc3a5155e'
You can modify your method slightly.
require 'digest'
def decrypt_string(hash)
arr = ("a".."z").to_a
(1..5).each do |n|
arr.repeated_permutation(n) do |a|
s = a.join
return s if Digest::SHA1.hexdigest(s) == hash
end
end
end
word = "cat"
hash = Digest::SHA1.hexdigest(word)
#=> "9d989e8d27dc9e0ec3389fc855f142c3d40f0c50"
decrypt_string(hash)
#=> "cat"
word = "zebra"
hash = Digest::SHA1.hexdigest(word)
#=> "38aa53de31c04bcfae9163cc23b7963ed9cf90f7"
decrypt_string(hash)
#=> "zebra"
Calculations for "cat" took well under one second on my 2020 Macbook Pro; those for "zebra" took about 15 seconds.
Note that join should be applied within repeated_permutation's block, as repeated_permutation(n).map(&:join) would create a temporary array having as many as 26**5 #=> 11,881,376 elements (for n = 5).
If you do not mind the possibility of repeating strings then
e = Enumerator.new do |y|
r = ('a'..'z').to_a * 5
loop do
y << r.shuffle.take(rand(4)+1).join
end
end
Should work. Then you can call as
e.take(10)
#=> ["bz", "tnld", "jv", "s", "ngrm", "phiy", "ar", "zq", "ajjn", "cn"]
This:
Creates an Array of a through z repeated 5 times
Continually shuffles said Array
Then takes the first 1 to 5 ("random number") elements from the shuffled Array and joins them together

String incrementer codewars (Ruby) problem

I am working on a string incrementer project on codewars.
Basicly,
Writing a function which increments a string, to create a new string.
If the string already ends with a number, the number should be incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
If the number has leading zeros the amount of digits should be considered.
foo -> foo1
foo001 ->foo002
foobar23 -> foobar24
foo099 -> foo100
My code is : input.gsub(/\d/,"")+input.split().map {|x| x[/\d+/].next!}.join(" ")
https://repl.it/#tanilserbes/ViolentNoteworthyDowngrade . It works on this playground
However it doesnt work on codewars. I get this error:
main.rb:5:in block in increment_string': undefined methodnext!' for nil:NilClass (NoMethodError)`
Any idea?
thanks in advance!.
To see what's going on here, it's beneficial to run each of your commands individual and see what the output is to track down the error:
input = "foo"
input.gsub(/\d/, "") # => "foo"
So the left hand side of the + operator is going to become "foo" and now we need to see what the right hand side of the is:
input.split # => ["foo"]
["foo"].map { |x| x[/\d+/].next! }
As seen in the question, this is where the error happens, so let's dig into the code inside the map block, where the error is:
["foo"].map { |x| p x }
# Outputs: "foo"
So, x == "foo" at this point:
["foo"].map { |x| p x[/\d+/] }
# Outputs: nil
Since the string "foo" doesn't have any digits in it, the regex pulling out the digits from it, to increment them returns nil and then, without any safeguarding you increment that. NilClass doesn't have a method next!, so you get your error.
If the string was instead "foo1", though, you'd get:
["foo1"].map { |x| p x[/\d+/] }
# Outputs: "1"
Which returns the matched string, and then allows you to call next! (which is a synonym of the String#succ! method called out in the comments) on it. The reason it works in the playground is because the string has digits in it, and doesn't take into account or test the case where strings don't (the first example in the text of the question where "foo" should become "foo1").
Here are some points to consider in developing your solution.
If your string were:
str = "ca9t00456"
the desired return value would be:
"ca9t00457"
(Note that the OP's solution would return an incorrect result ("cat10") for this string. The Codewars question does not say that the only digits in the string are those at the end; it only mentions the "number" at the end of the string".)
A reasonable first step would be to divide the string into two parts:
n = str.index(/\d+\z/)
#=> 4
prefix = str[0, n]
#=> "ca9t"
suffix = str[n..-1]
#=> "00456"
See String#index. The regular expression, /\d+\z/, reads, "match one or more (+) digits (\d) followed by the end of the string (\z). The digit '9' is skipped over because it is neither followed by a digit nor is at the end of the string. See also See String#[].
The string we return will begin with (the value held by) prefix, so we can set that aside for now and concentrate on modifying suffix.
One approach would be:
((suffix.to_i) + 1).to_s
#=> "457"
but then we would have to add the correct number of leading zeroes. Here that would be the same as the number of leading zeroes in suffix (2), but if suffix were, for example, 00999, it would be only one (01000). That could be done, but it's messy.
An easier way would be to use the method String#succ, as #steenslag suggested in the comments.
new_suffix = suffix.succ
#=> "00457"
"00999".succ
#=> "01000"
Now we need only combine prefix and new_suffix.
Note what happens if we execute succ on the entire string:
"ca9t0456".succ
#=> "ca9t0457" correct
"ca9t0999".succ
#=> "ca9t1000" correct
"ca9t9999".succ
#=> "ca9u0000" incorrect
As you see, there's a problem with the third example. That's why I chose to divide the string into two parts as a first step.
You need to investigate three other cases. The first is when the prefix is an empty string:
str = "00456"
the second is when the suffix is an empty string:
str = "ca9t"
and the third is when the string is empty:
str = ""
You can check if the previous calculations still work in the first case.
In the second case we would find:
n = str.index(/\d+\z/)
#=> "cat9t".index(/\d+\z/) => nil
The nil value for n tells us that the desired return value is:
str + "1"
#=> "ca9t" + "1" => "ca9t1"
Would that work?

Python: Comparing values in one array and replacing that value in another array at the same index from the first array

I’m trying to take user input and compare that input to the values in array B. Should the user input match one of those values in array B, I capture the index it is at and replace array A with the user input at the same index it found it in array B.
In the code example if I enter 11 it finds 11 in array B and inserts it into the same index point in array A. But if I choose 22, 33, or 44 it does not replace anything.
What do you see wrong with the code below? Why does it recognize number 11 in array B and replaces it with 1 in array A, but not the others?
a = [1,2,3,4]
b = [11,22,33,44]
c = input("Enter a Number: ")
for i in b:
if c == i:
x = b.index(i)
a.pop(x)
a.insert(x,c)
break
else:
print "Not in list b"
break
print a
Try this:
a = [1,2,3,4]
b = [11,22,33,44]
c = input("Enter a Number: ")
for i in b:
if c == i:
x = b.index(i)
print x
a.pop(x)
a.insert(x,c)
break
else:
print "Not in list b"
print a
Putting the else statement outside of the for loop should make it work as expected. As it was, the loop would, 100% of the time, break after 1 iteration.

Adding items to a new array with index

Trying to make a method skip_animals that takes an animals array and a skip integer and returns an array of all elements except first skip number of items.
input: skip_animals(['leopard', 'bear', 'fox', 'wolf'], 2)
expected output: ["2:fox", "3:wolf"]
def skip_animals(animals, skip)
arr = Array.new
animals.each_with_index{|animal, index| arr.push("#{animal}:#{index}") }
puts arr.drop(skip)
end
This instead puts each output on a separate line and doesn't add them to the array arr. I thought the arr.push would add them correctly. What do I have to do to get the elements added to the array?
I want to use these methods, not map or something more advanced. I need to tinker with this each_with_index line, not overhaul it.
(This is a challenge on Hackerrank, so it uses STDIN and STDOUT)
EDIT
Here is my updated code with p instead of puts. It's giving me a weird output of two different arrays, not sure why.
def skip_animals(animals, skip)
arr = Array.new
animals.each_with_index{|animal, index| arr.push("#{index}:#{animal}") }
p arr.drop(skip)
end
This gives me two lines of output:
["3:panda", "4:tiger", "5:deer"]
["0:leopard", "1:bear", "2:fox", "3:wolf", "4:dog", "5:cat"]
I'm assuming the top is the correct array, but I don't get why the second is printing also, or why it has a different set of animals.
Use p instead of puts.
irb(main):001:0> puts ['1', '2']
1
2
=> nil
irb(main):002:0> p ['1', '2']
["1", "2"]
According to the documentation, puts:
Writes the given objects to ios as with IO#print. Writes a record
separator (typically a newline) after any that do not already end with
a newline sequence. If called with an array argument, writes each
element on a new line. If called without arguments, outputs a single
record separator.
BTW, I would code like this (using Enumerable#map + returning result instead of printing inside the function):
def skip_animals(animals, skip)
animals.drop(skip).each_with_index.map { |animal, index|
("#{index + skip}:#{animal}")
}
end
p skip_animals(['leopard', 'bear', 'fox', 'wolf'], 2)
just remove puts remove form this line puts arr.drop(skip)
def skip_animals(animals, skip)
arr = Array.new
animals.each_with_index{|animal, index| arr.push("#{animal}:#{index}") }
arr.drop(skip)
end

Find a Duplicate in an array Ruby

I am trying to find the duplicate values in an array of strings between 1 to 1000000.
However, with the code I have, I get the output as all the entries that are doubled.
So for instance, if I have [1,2,3,4,3,4], it gives me the output of 3 4 3 4 instead of 3 4.
Here is my code:
array = [gets]
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}
end
Also, every time I test my code, I have to define the array as array = [1,2,3,4,5,3,5]. The puts works but it does not print when I use array [gets].
Can someone help me how to fix these two problems?
How I wish we had a built-in method Array#difference:
class Array
def difference(other)
h = other.tally
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
though #user123's answer is more straightforward. (Array#difference is probably the more efficient of the two, as it avoids the repeated invocations of count.) See my answer here for a description of the method and links to its use.
In a nutshell, it differs from Array#- as illustrated in the following example:
a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]
a - b #=> [1]
a.difference b #=> [1, 3, 2, 2]
For the present problem, if:
arr = [1,2,3,4,3,4]
the duplicate elements are given by:
arr.difference(arr.uniq).uniq
#=> [3, 4]
For your first problem, you need to uniq function like
array.select{ |x| array.count(x) > 1}.uniq
For your second problem, when you receive a value using array = [gets] it would receive your entire sequence of array numbers as a single string, so everything would be stored in a[0] like ["1, 2 3 4\n"].
puts "Enter array"
array = gets.chomp.split(",").map(&:to_i)
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}.uniq
end
copy this code in ruby file and try to run using
ruby file_name.rb
Coming to your 'gets' problem,
When you are doing a gets, your are basically getting a string as an input but not an array.
2.2.0 :001 > array = [gets]
1,2,1,4,1,2,3
=> ["1,2,1,4,1,2,3\n"]
See the above example, how the ruby interpreter took all your elements as a single string and put it in an array as a single array element. So you need to explicitly convert the input to an array with comma as a delimiter. The below will address both your questions.
array = gets.chomp
array = array.split(',').map(&:to_i)
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}.uniq!
end

Resources