How to use arrays/lists and loops in Python - arrays

Ok so this is my first question here. I am currently an IT student and I am taking a fundamentals of programming class. I seem to be spending more time lost and confused than I feel as if I should. We are using Python as the programming language. The topic for this week is arrays and lists. From what I have gathered through reading many other forums, Python does not use array but lists. Therefore the assignment does not make since to me. Any help or guidance would be greatly appreciated.
Create a FLOWCHART and a STORYBOARD for each problem.
Use the information below to create a storyboard (which can be a text based description for solving the problems) and a flowchart (using flowchart symbols to illustrate how you would program) to solve each problem. You may use Microsoft Word® for your Storyboard and Microsoft PowerPoint® for your flowchart.
Problem 1: Create an array that contains the days of the week.
Problem 2: Create a loop to print the content above.
So what would the flowchart for this look like? The assignment next week builds on this by actually writing the program in Python. What would the script look like? Thanks for any help.

This is just for hinting, I won't write your program for you. In your comment, you assigned to the list (you're right, they're not called "arrays" in Python) correctly. Now you need to iterate over it to print each item individually. I'd suggest you refresh your memory in the Python Tutorial on how to control program flow, especially the for statement. Remember, the general idea is:
for item in collection_of_items:
do_something_with(item)

days = ['monday','tuesday','wednessday','thursday','friday','saturday','sunday']
for day in days:
print(day)
Edit:
what would the flowchart for this look like?
This problem is quite simple, try to make your own flowchart. Try to practice thinking at the very first lesson of programming course.
What would the script look like?
It would look like above code. But you can do it better and more professional, try to figure it out.

Related

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

ANTLR and arrays

I have question relating to implementation of arrays with Java+ANTLR combo. (I'm mainly talking about java/c style arrays).
So basically I'm asking how do you implement such feature, if there is such example already available or if someone could point me to anything that may point to solve it.
On other hand, I've searched a bit how would possible solution be. Main problem that I see
is that user may create arrays of various dimensions, even go crazy if he or she wants (like creating 5 dimension arrays or worse).
While grammar for something like this is fairly simple, like
new ID (INT (',' INT)* )
back end really gets involved a bit. As I said, user may input any number of dimensions, so array dimensions should be dynamically created. (at least as I see it, maybe I'm over complicating things?)
After searching I did found something that pretty much solves this problem perfectly, here is link to the question:
Is it possible to dynamically build a multi-dimensional array in Java?
Of course, my question is, is this viable example, it is a bit (to say at least), complicated? Is there more elegant solution to it?
Having that in mind, I was thinking maybe answer might be in the grounds of somehow transforming multidimensions
into more linear structure ? Could something like that be useful ? Simple search on stackoverflow pointed many solutions
to this, like:
Algorithm to convert a multi-dimensional array to a one-dimensional array
Would it be worth to search in that direction ?
Now, at the end, having in mind that arrays are really common feature in many languages, I must find it surprising that after searching ANTLR mailing list there is no similar question, which as I previously said leads me to believe that I'm maybe over complicating things ? (Unless I really suck at search?) I would really appreciate feedback.
Your syntax, if I'm not mistaken, corresponds to something like
new char 4,5,6,7
which is kind of strange. I expect that you really meant
new char[4,5,6,7]
However from a purely syntactic point of view, there's no reason not to just store the indices in an array and let the semantic analysis pass worry about it.

Dynamic Programming resources in C?

I'll be writing the online Google test tomorrow as a fresher. Apparently, they definitely ask one problem on Dynamic Programming?
Does anyone know of a good resource for collection of DP problems in C along with solutions? I know what DP is & have used it on an occasion or twice. However I feel to crack a DP problem in test, prior practice of typical problems will make it easier to approach.
Any good resources or problem sets with solutions in C will be highly appreciated. Thanks.
Okay, so I really hope this doesn't count as "shameless self-promotion," since all of these links are to code snippets I've posted on my personal site. If this is inappropriate, please let me know and I can take them down.
Here are a few fun DP problems that are pretty much classics:
Minimum edit distance: Given two strings A and B, find the shortest number of edits (insertions, deletions, or substitutions) necessary to convert A into B. This is called the Levenshtein distance. (My solution)
Optimal sequence alignment: Given two strings A and B, find the minimum number of gaps that must be inserted into the sequence to align A and B. This is called the Needleman-Wunsch algorithm. (My solution)
Single-source shortest paths: Given a directed graph G and a single node s, find the lengths of the shortest paths from s to each other node in the graph, assuming edges can be positive or negative but that no cycles exist. This is the Bellman-Ford algorithm. (My solution)
All-pairs shortest paths: Given a directed graph G, find the minimum distances between all pairs of nodes. This is the Floyd-Warshall algorithm. (My solution)
Hopefully this is somewhat useful, and best of luck tomorrow!
The Topcoder website is amazing. Not all of the problems use DP, but many do. Free full access to all problems from past competitions, which are at 3 different difficulty levels, as well as after-match explanations of every single problem from the problem author. Not only that, but you can quickly dig up the source code solution submitted by any coder in the competition.
Haven't been back there for a while, but they allow at least C++, Java, C# and I believe several other languages now.
I suggest u,collect a book "An Introduction to Bioinformatics Algorithms".This has a chapter fully on DP.As #templatetypedef mentioned Minimum edit distance,Optimal sequence alignment it has other problem with them.Though there is no implementation in it.You have to do it on your own.But you will find pretty interesting reading them.
To practice you can take one of the available problems at SPOJ. To recognize DP ones easily you can check at Problems Classifier (keyword: dp).

FizzBuzz comment that confused me - are hard coded conditions wrong?

I discovered the "FizzBuzz" question today at coding horror. Great article. However, something in one of the user-comments confused me -- here's the quote:
Geez guys - EVERY ONE of you who gave
example code - EVERY ONE - hard coded
the FIZZ and BUZZ conditions...
It sounds to me like this poster is ridiculing people for "hard-coding" conditions, ie :
if(i % 3 == 0)
...
What is point the poster is trying to make? Is there another way to specify conditions in a program?
Thanks for taking the time!
Dan
the FIZZ and BUZZ conditions...
The point of Fizz Buzz is to quickly weed out non-programmers, not find the best programmer. Any reasonable function that meets the specification is acceptable for this test.
If you don't hardcode, great, you extra-pass. But, that doesn't get you out of the hard questions that are following. I usually increase the difficulty with each question, but I don't want to waste time if the candidate totally can't answer simple questions.
There's nothing wrong with hardcoding some conditions.
In the context of an interview, when I know that I'm coding FizzBuzz.java and not Enterprise Fizz Buzz with a database and 1000+ simultaneous users requiring five-nines uptime, it's ideal to hardcode these conditions.
Entry-level programmers, the ones you ask FizzBuzz at least, are to follow specifications and make solutions as simple and elegant as possible. If you're an agile software house, including such features goes against YAGNI and should be discouraged. If the interviewer doesn't ask the ability to use other factors besides three and five, then it wasn't in the spec and therefore isn't needed.
It's meant as a joke.

Most difficult programming explanation

Recently I tried to explain some poorly designed code to my project manager. All of the manager classes are singletons ("and that's why I can't easily change this") and the code uses event dispatching everywhere that a function call would have sufficed ("and that's why it's so hard to debug"). Sadly it just came out as a fumbling mess of English.
Whats the most difficult thing you've had to convey to a non-technical person as a programmer? Did you find any analogies or ways of explaining that made it clearer?
Thread Synchronization and Dead-Locking.
Spending time on design, and spending time on refactoring.
Refactoring produces no client-visible work at all, which makes it the hardest thing in the project to justify working on.
As a second "not client-visible" problem, unit testing.
I was asked how the internet worked - I responded with "SYN, ACK, ACK". Keep forgetting it's SYN, SYN-ACK, ACK..
(source: inetdaemon.com)
My most difficult question began innocently enough: my girlfriend asked how text is rendered in Firefox. I answered simply with something along the lines of "rendering engine, Gecko, HTML parser, blah blah blah."
Then it went downhill. "Well how does Gecko know what to display then?"
It spiraled from there quite literally down to the graphics drivers, operating system, compilers, hardware archiectures, and the raw 1s and 0s. I not only realized there were significant gaps in my own knowledge of the layering hierarchy, but also how, in the end, I had left her (and me!) more confused than when I began.
I should've initially answered "turtles all the way down" and stuck with that. :P
I had a fun case of trying to explain why a program wasn't behaving as expected when some records in a database had empty strings and some were NULL. I think their head just about exploded when I told them empty string is just a string with 0 bytes in it while NULL means unknown value and so you can't actually compare it to anything.
Afterward I had one nasty headache.
1.) SQL: Thinking in sets, rather than procedurally (it's hard enough for us programmers to grasp!).
2.) ...and here's a great example of demystifing technical concepts:
How I explained REST to my wife
A lot of statements starting with "It's because in Oracle, ..." come to my mind.
The biggest hurdles are around "technological debt", especially about how the architecture was correct for this version but needs to be changed for next version. This is similar to the problem of explaining "prototype versus production" and "version 1.0 versus version 2.0".
Worst mistake I ever made was doing a UI mockup in NeXT steps UI Builder. It looked exactly like the end product would look and had some behaviour. Trying to explain that there was 6 months of work remaining after that was very difficult.
How recursion works...
Why code like this is bad:
private void button1_Click(object sender, EventArgs e)
{
System.Threading.ThreadStart start =
new System.Threading.ThreadStart(SomeFunction);
System.Threading.Thread thread = new System.Threading.Thread(start);
_SomeFunctionFinished = false;
thread.Start();
while (!_SomeFunctionFinished)
{
System.Threading.Thread.Sleep(1000);
}
// do something else that can only be done after SomeFunction() is finished
}
private bool _SomeFunctionFinished;
private void SomeFunction()
{
// do some elaborate $##%#
_SomeFunctionFinished = true;
}
Update: what this code should be:
private void button1_Click(object sender, EventArgs e)
{
SomeFunction();
// do something else that can only be done after SomeFunction() is finished
}
private void SomeFunction()
{
// do some elaborate $##%#
}
The importance of unit tests.
"Adding a new programmer a month to this late task will make it ship later. Never mind, read this book." (The Mythical Man-Month.) Managers still don't quite get it.
The concept of recursion - some people get it really hard.
I sometimes really have hard time explaining the concept of covariance/contravariance and the problems related to them to fellow programmers.
Convincing a friend that the Facebook application I developed really doesn't store her personal data (e.g. name) even though still displays it.
Why it'll take another four weeks to put this app into production. After all, it only took a week to do the rapid prototype. It "works" (or at least looks like it does) so I should be pretty much finished, shouldn't I?
Explanations that involve security, code quality (maintainability), normalized DB schemas, testing, etc. usually come off as a list of abstractions that don't have any visible effect on the app, so it's hard to explain what they really contribute to the project and why they're necessary. Sometimes analogies can only take you so far.
C pointers
*i
&i
Avoiding Dead-Locking in a multi-threaded environment.
I cleared confusion by explaining it visually on a white-board, drawing out two parallel lines and showing what happens when the reach the same points at the same time.
Also role-playing two threads with the person I was explaining it to, and using physical objects (book, coffee mug, etc) to show what happens when we both try to use something at once.
There's really no right or wrong answer-proper for this... it's all experiences.
The hardest thing I have had to explain to a non-tech person was why he couldn't get to his website when traveling abroad but his family member that lived there (with a totally different provider) could get to it. Somehow, "Fail in Finland" wasn't good enough.
The most difficult concepts to explain to people I would label programmers as opposed to developers are some of the most core paradigms of object orientated design. Most specifically abstraction, encapsulation and the king, polymorphism and how to use them correctly.
Expanding on that is the level of complexity of explaining what Inversion of Control is and why it is an absolute need and not just extra layers of code that doesn't do anything.
I was going to comment on Mikael's post, that some people just take the sequential programming and unfortunately just stay with that.
But that really means: two seriously hard to explain concepts:
monads in haskell (usually starting with: "That's like a function that returns a function that does what you really wanted to do, but ...")
deferreds in twisted/python ("That's like... ehhh... Just use it for a year or so and you'll get it" ;) )
Trying to explain why code was executed sequentially at all. Seemingly this is not at all intuitive for some non-programmers (i.e. my girlfriend).
Why you do not need character correct index handling in most cases when you use UTF-8 strings.
It's hard to explain why most software has bugs. Many non-technical people have no idea how complex software is, and how easy it is to overlook unexpected conditions. They think we are just too lazy to fix stuff that we know is broken.
There are 10 different types of people in the world.
The people who understand Binary and the people who dont....
To put it plainly, why development is the most difficult concept ever exposed to man kind. Not related to any programming language, but in general. And no I am not trying to provide myself or you with an ego boost, the only real limitations to this field is your mind.
Why? We don't work with constants and there are no boundaries, the only reason an AI that thinks like a human being doesn't exist yet is due to our own limitations. All other aspects need to adhere to some sort of law, development doesn't care about the laws of physics or any law for that matter hence the term development... evolution.

Resources