Display data in 2d list in python - arrays

For an assignment in a my python class. I have to take the following list data:
animal = [
('cat', 'meow', 4),
('dog', 'bark', 10),
('bird', 'chirp', 0.5),
('snake', 'hiss', 3),
('cow', 'moo', 250),
('lion', 'roar', 500)
]
And create nested loop statements to display the following:
[1]: https://i.stack.imgur.com/KpPL4.png

I think it won't help you learn if we give you the complete answer, but here are some things that can help:
Do you know that each of those structures (the array, and the tuples in the array) is an iterable? That means you can loop over them without using indexes, the way one might in another language. Check out that link to get some ideas about how you could nest an iterable for your individual animals inside the iterable for the whole list.
If you're using Python 3.6 or newer, you can use f strings for your formatting, which will give you a tidy way to print the values with flexible spacing, so they all line up the way you'd like. There are good examples of the older format for formatting strings with whitespace padding in this SO question: Python spacing and aligning strings
I think you should be able to figure out your answer based on those two pointers.

Related

Sum of elements of two integer array in a single string array in Swift

Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17.
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array.
Examples
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2
Thank you for your help.
The question seems obviously a homework exercise, and as was pointed out in comments that's not what StackOverflow is for; however, I know a lot of students who struggle to know even how to approach a problem. I think helping with that is a good thing, so I won't give a solution to the problem, but rather advice about approaching it.
The general formula that works for most problems is simple: Break the problem into smaller sub-problems, and solve each of those independently, then combine the sub-solutions. If any of those sub-problems are too complicated, repeat the process for those, and so on.
Homework problems, and a lot of real world problems, usually break down into three main sub-problems:
Transform some input into a more conveniently computable form.
Process the transformed input into some computed outputs.
Transform the computed outputs into a specified format.
Applied to your problem, you have:
How to parse a specially formatted string into an array of integers.
How to sum corresponding elements of two arrays, taking into account they may be of different lengths, to produce an array of sums.
How to transform an array of integers into a specially delimited string output.
The solution to your top-level problem will involve applying the sub-solutions in that order, but you don't have to solve them in that order. If you're having difficulty with getting started with the first one, solve one of the easier sub-solutions first to get some momentum. Psychology is actually quite important in problem solving. Believing you can solve it is half of actually solving it, so solve the easier problems first to get that factor working in your favor.
Maybe you regard the sub-problem 3 as the easiest to solve: So write a function place-holder for it (aka, a "stub function"), and make up some input data to test it. This would lead you to write something like this:
func formatOutput(from intArray: [Int]) -> String
{
// Your implementation will go here
}
let actual = formatOutput(from: [1, 2, 3, 4])
let expected = "1-2-3-4"
// If you're doing this in a playground, app, or command line tool
if actual != expected {
fatalError("FAILED: \"\(actual)\" != \"\(expected)\"")
}
else { print("Yay! Passed!") }
// If you're using XCTest
XCTAssertEqual(actual, expected)
That won't even compile yet, because formatOutput has to return something, and it doesn't yet. The key thing is that you've written your usage code first, and expressed in code what you expect. Now focus on the guts of formatOutput. If you want to take a Test Driven Development approach (TDD), maybe at first just return an empty string from formatOutput so you can be sure the code compiles and you see a failing test. Then implement it correctly if you know how, or in small steps if you're not clear on what to do. As you get the exact thing you're testing for working, you can keep adding more tests and improving formatOutput until you've verifiably got it doing everything it's supposed to do. Remember the KISS principle: "Keep It Simple, Stupid!" Don't over-think the solution, and save doing it "cleverly" for another day, which often never comes because the simple thing was sufficient.
At that point you have one of the sub-problems solved, so you move on to the next, following the same pattern. And the next, until all the parts are solved. Then put them together.
You'll note that sub-problem 2 has a bit of an extended description, especially the part specifying that the arrays may be of different lengths. Unless you already know how to solve that problem as stated, that sort of thing indicates it's a good candidate to be broken into yet simpler problems:
2a. How to sum corresponding elements of two arrays of the same length.
2b. How to modify 2a to handle arrays of different lengths.
2b can be done a few different ways:
2.b.1. Apply 2.a to sub-arrays of common length, then handle the remaining part of the longer one separately
OR
2.b.2. Enlarge the shorter array so that it is the same length as the longer one, so 2.a can be applied unmodified.
OR
2.b.3. Modify 2.a so that it can treat the shorter array as though it were the same length as the longer one, without actually copying or adding new elements.
OR
2.b.4. Modify 2.a so that it doesn't have to do anything special for different lengths at all. Hint: think more about the output and its length than the inputs.
When faced with alternatives like that, in the absence of any external constraints that would make one option preferred over the others, pick the one that seems simplest to you (or the most interesting, or the one you think you'd learn the most from). Or if you have time, and want to get the most out of the exercise, implement all of them so you can learn how they are all done, and then pick the one you like best for your final code.
func getResult(strArr: [String]) -> String {
let intArray1 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[0].utf8))) ?? []
let intArray2 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[1].utf8))) ?? []
var arrayResult = zip(intArray1,intArray2).map(+)
let commonCount = arrayResult.count
arrayResult.append(contentsOf: intArray1.dropFirst(commonCount))
arrayResult.append(contentsOf: intArray2.dropFirst(commonCount))
return arrayResult.map(String.init).joined(separator: "-")
}
let result1 = getResult(strArr : ["[5, 2, 3]", "[2, 2, 3, 10, 6]"])
let result2 = getResult(strArr : ["[1, 2, 1]", "[2, 1, 5, 2]"])
You can use this function to get your desired result.

How does Ruby's Combined Comparison Operator work?

First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.

Create generic array from type specific arrays in Clojure

I am working with JFreeChart in clojure and came across a situation I'd like help.
JFreeChart's DefaultXYDataset has a method addSeries which is used to add series to the chart. The data is supposed to be an array containing two arrays which are type specific(Array of doubles). I therefore wrote the following code thinking it would work but i get a
ClassCastException that class [Ljava.lang.Object; cannot be cast to class [[D ([Ljava.lang.Object; and [[D are in module java.base of loader 'bootstrap').
(doto _dataset
(.addSeries "S1" (to-array (conj
[]
(double-array (range 10))
(double-array (range 10))))))
After looking through i realized that to-array converts the two nested arrays to #object["[Ljava.lang.Object;" 0x491223e7 "[Ljava.lang.Object;#491223e7"] instead of the intended #object["[D" 0x4f5cf37 "[D#4f5cf37"] #object["[D" 0x6d895193 "[D#6d895193"]. Is there a way of combining them to a generic array without converting them to arrays of longs? Maybe another method apart from to-array. Any other suggestions are welcome. Thanks.
Edit: #bfabry answer will work, i could use make-array and then use aset-double but this will result in me looping through the two sequences and assign their values to the main array. I am trying to avoid this as the two datasets can be quite big, even up to 300k items each.
That's two dimensional array, not an array of two array objects. You'll need to use make-array and aset-double to make the array you want.
user=> (class (make-array Double/TYPE 2 2))
[[D
https://clojuredocs.org/clojure.core/make-array

How to comunicate between two array lists

I want to compare two array lists, when i press list1 items, open list2 items in new activity.please help me. i have write below code but not working. please solve my problem.I want to compare two array lists, when i press list1 items, open list2 items in new activity.please help me. i have write below code but not working. please solve my problem.
//My String-array
<string-array name="Alphabets1">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>G</item>
<item>H</item>
<item>I</item>
<item>J</item>
</string-array>
<string-array name="Lyrics1">
<item>Aakaashamandunna </item>
<item>Bangaram Adagaledu</item>
<item>Cheyi Pattuko</item>
<item>Devara Nee Devenalu</item>
<item>Ella velalandu kastha</item>
<item>Gaganamu Cheelchukoni</item>
<item>Hallelujah Hallelujah</item>
<item>Ide Naa Korika</item>
<item>Janminchenu Oka Thaara</item>
</string-array>
<!-- begin snippet: js hide: false -->
You actually have a few problems to solve here. One of them is the difference between ArrayLists and arrays - I'm pretty sure you mean arrays here, since ArrayLists only hold objects, and there wouldn't be much point in forcing autoboxing and unboxing for a slower-access collection. But maybe you mean ArrayLists because you want the built-in expandability, I don't know. Something for you to determine.
I'd start with one of the sub-problems: combining two arrays or arraylists, preferring non-zero values. You'll do about the same thing with different syntax in each case.
Write a method int[] combine(int[] firstArray, int[] secondArray) to walk two arrays simultaneously and combine the values you find. You'll have to figure out what the correct behavior is when you have two non-zero values. (or are you simply summing the arrays? that'd be pretty easy)

Explaining nested arrays to a programmer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
How have you explained nested arrays to a programmer. I'm thinking someone that has an entry level understanding of programming, but is trying to do more complicated coding.
The array with array works, but they can't quite get their mind around the idea.
Edit: example of a nested array:
array(
'array1' => array(
'key1' => 'val1',
'key2' => 'val2',
),
'array2' => array(
'key1' => 'val1',
'key2' => 'val2',
),
);
Of course, they are usually more complicated than this and maybe that's the problem.
Tell them to think of an array as a list- it helps to give them something less abstract, like a grocery list. Then, a nested array is simply a list of lists.
Maybe I have a todo list, a grocery list, and a wishlist at amazon.com . Now I have a list of all of my lists, and I can look at all of those elements in each list by stepping through them.
A nested array is a set within a set. So, a library has a set of books, a book has a set of chapters. A chapter has a set of paragraphs, a paragraph has a set of sentences. A sentence has a set of words.
For each book in library
For each chapter in book
For each paragraph in chapter
etc...
How have you explained it? It doesn't seem like a big jump for someone that understands one dimensional arrays to be able to grasp the concept that instead of an int or a string that each array element contains another array instead.
Perhaps an analogy comparing directories will help, a one dimensional array would be analogous to a directory that contains a bunch of files, a two-dimensional array to a directory which contains several other directories, each containing a bunch of files, etc.
Draw it.
A variable is a box
1 dimensional array is a row of boxes.
2 dimensional array is a grid of boxes.
3 dimensional array is a cube of boxes.
If they have having trouble with the general concept, don't attempt to visually explain 4 dimensions.
Use a bitmap as an example. In C, you can make a bitmap of an X like this:
int x[5][5] = {
{ 1,0,0,0,1 },
{ 0,1,0,1,0 },
{ 0,0,1,0,0 },
{ 0,1,0,1,0 },
{ 1,0,0,0,1 }
};
Then show them how to use nested for loops to display the bitmap.
Examples always help, and this also gets them to think of nested arrays as multi-dimensional arrays. Actually it's probably better to understand multi-dimensional arrays in a language like C before learning about the "nested" arrays in languages like Python where you can have different levels of nesting in the same array.
Sports can provide appropriate analogies to describe applying nested arrays. A team is an array of people, a competition is an array of teams that play against each other.
However its a case of finding the analogy that clicks with the learner. Find the right analogy and you'll get even the slowest of learners to understand. Just ensure you're analogies are water tight. Like abstractions, they are leaky.
A concrete example is the index at the back of a book. A list of words, each word associated with a list of page numbers.
apples - 1, 2, 3-4
bears - 32-35, 79, 83
cats - 14, 15
If you are looking at C type, non-ragged, arrays, comparing it to numbers, the base 10 part, and there digits might help. Another good source for this same effect would be time as it has a non uniform base 60s = 1m, 60m = 1h, 24h = 1day, 7day = 1week
2 dimensions is easy to explain. Just think of a table. 3 dimensions just think of a cube or other 3d image. 4 dimensions think of a series of images like a movie with the 4th dimension being time.
4+ dimensions is hard to visualize using that model. But think of it as a filing cabinet with another file cabinet inside helps. You open the drawer and out pops a filing cabinet. You find the drawer you want and open that drawer and out pops another filing cabinet....over and over until finally you get your paper.
Perhaps you are explaining it from the context of someone who understands an array of arrays. I would attempt to trick them into realizing that they already understand them by starting at the smallest(read inner array)...and slowly expanding out, giving them plenty of time to ask questions until they are done.
Drawing helps, but you need to give the student in this case some information and go slowly, most programmers I know tend to go to fast and to like to explain things EVEN when the listener no longer is tracking what is being said.
I am a metaphor guy, so I would probably cook something up about a series of boxes with each one numbered, each box then containing a similiar(but much smaller series) also numbered. I would take this to only two levels get understanding and then perhaps talk about 3 dimensions for confirmation. But I would avoid 4 dimensions on the grounds that they may get hung in the idea that there is no such thing as 4 dimensions, or you can't measure time, or other such metaphorical landmines/distractions...cause that's the other problem, programmers tend to be ADD and enjoy getting side tracked.
Also why aren't you using a hash of hashes, much easier to reference. :)
Bottom line, baby steps.
an array is just an object - a thing. everything should be simple to understand once they get that

Resources