Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

03-28-2016 , 03:46 PM
to start with, you can replace "hourly_temperature[i]" with "temp"
Programming homework and newbie help thread Quote
03-28-2016 , 04:08 PM
What I originally had was something like this:

hourly_temperature = [90, 92, 94, 95]

for temp in hourly_temperature:
print(temp, '->', end=' ')

print()


...but I don't know how to get rid of the last arrow at the end doing it that way.
The output has to have the arrow after every number except the last.
Programming homework and newbie help thread Quote
03-28-2016 , 04:11 PM
one strategy would be to build up a string that looks like

'90 -> 92 -> 94 -> 95 -> '

and then print all but the last 4 characters of the string
Programming homework and newbie help thread Quote
03-28-2016 , 04:17 PM
It's kind of non-pythony. I'd do this

Code:
hourly_temperature = [90, 92, 94, 95]
print ' -> '.join([str(x) for x in hourly_temperature])
Programming homework and newbie help thread Quote
03-28-2016 , 04:24 PM
Quote:
Originally Posted by LBloom
What I originally had was something like this:

hourly_temperature = [90, 92, 94, 95]

for temp in hourly_temperature:
print(temp, '->', end=' ')

print()


...but I don't know how to get rid of the last arrow at the end doing it that way.
The output has to have the arrow after every number except the last.
You could do like econophile said and build a string, then remove the last 4 elements. Another option is to still use the if/else to compare the value of temp to the last element in the hourly_temperature array, like this:
Code:
for temp in hourly_temperature:
  if temp == hourly_temperature[-1]:
    # do something
  else:
    # do something else
Programming homework and newbie help thread Quote
03-28-2016 , 04:25 PM
Also, in answer to the general problem you mentioned, where you are trying to avoid adding -> at the end, you can do something like this...

Code:
out = ""
for temp in hourly_temperature[:-1]:
    out += str(temp) + ' -> '

out += str(temp)
print out
This is much simpler than trying to compare the current element to the end element, etc.
Programming homework and newbie help thread Quote
03-28-2016 , 04:33 PM
Quote:
Originally Posted by fredd-bird
Code:
for temp in hourly_temperature:
  if temp == hourly_temperature[-1]:
    # do something
  else:
    # do something else
This would break if the last and 2nd to last element had the same value. To use this paradigm, I'd use enumerate(hourly_temperature) which returns tuples of index and the list value, and compare the index to len(hourly_temperatures) - 1
Programming homework and newbie help thread Quote
03-28-2016 , 05:39 PM
Doh!
Programming homework and newbie help thread Quote
03-28-2016 , 07:13 PM
Thanks guys. Some of the ideas and concepts you've suggested are things I haven't gotten to yet, but it has been very helpful to read the suggestions and look up the aspects of them I don't understand, while having a mini program to mess around with them in.

I may post a similar problem later where I had a similar issue (could get the output almost right, but had one extra character getting printed at the end). I again found a solution that works but I'm not sure how "good" it is. I'm going to try to incorporate some of your suggestions with it though, first. Thanks again.
Programming homework and newbie help thread Quote
03-29-2016 , 05:50 PM
Question about some Codingbat problems I've been doing:

Although familiar with the concept of Boolean expressions, I haven't really been exposed to them formally. I've started to work through codingbat problems on my own, and have picked up some of the basics that way, but there is a lot I don't know, and I have a general question about how to best write my functions.

PROBLEM:
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.

MY SOLUTION:
def near_hundred(n):
if abs(n - 100) <= 10 or abs(n - 200) <= 10:
return True
else:
return False

Codingbat counts this as correct.

CODINGBAT'S GIVEN SOLUTION:

def near_hundred(n):
return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))


So I'm assuming that if you just use return on an expression, if the expression evaluates to True, True is returned, else False is returned? If I'm right about that, does that mean it's preferable to just use return for functions like this one, and skip the if/else?

One other, even more general, question: I'm trying to learn a lot on my own, and I'm often confronted with concepts in Python that I'm unfamiliar with, and I do my best to figure out how to make it work on my own. I'm sure that a lot of my solutions while doing so are extremely inelegant. Should I be concerned by this, and try to focus on things more to my speed, or is challenging myself to successfully solve programming problems I may not fully understand going to be beneficial? More to the point, how much should I worry about my style while I'm learning?
Programming homework and newbie help thread Quote
03-29-2016 , 06:03 PM
In Python, Boolean expressions evaluate to one of two Boolean values: True or False.

So the given solution is equivalent to yours, but more concise.

A related concept is that it is preferable to write code like
Code:
if [BOOLEAN_EXPRESSION]:
    some_function()
instead of
Code:
if [BOOLEAN_EXPRESSION] == True:
    some_function()
It is helpful to learn good style, but it is more important to learn why good style is better than bad style. To do this, you may want to use some intro programming text that uses Python. Think Python is one that is available for free.
Programming homework and newbie help thread Quote
03-29-2016 , 06:19 PM
I think any compiler will optimize statements like that so there is no real "difference" performance wise but one makes you look redundant and one makes you look like you've been doing this for a little while. IMO that's important. and readability, even for yourself. looking back at code you wrote 2+ weeks ago may seem alien to you if you did something in an unconventional way, at least in my experience, so the simpler the statements the better.

i think in the above solution, neither one is more "elegant" than the other algorithmically. One just looks nicer. If you're beginning I wouldn't stress too much about that stuff because what matters at that point are being able to solve problems, not being able to solve them perfectly.
Programming homework and newbie help thread Quote
03-29-2016 , 06:23 PM
I tried to find a good example on codingbat and found this right off the bat:


Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.

my solution:

Code:
 public boolean firstLast6(int[] nums) {
  return (nums[0] == 6 || nums[nums.length-1] == 6);
}
their solution:

Code:
public boolean firstLast6(int[] nums) {
  if (nums[0] == 6) {
    return true;
  }
  if (nums[nums.length - 1] == 6) {
    return true;
  }
  return false;

}
i think mine looks nicer and makes more sense but you'll find many disagreements between any 2 people about this stuff.
Programming homework and newbie help thread Quote
03-29-2016 , 06:31 PM
Apparently even between people doing codingbat solutions.
Programming homework and newbie help thread Quote
03-29-2016 , 11:43 PM
Not saying speed is the end-all be-all, but pretty interesting results here:

Code:
def f():
    n = []
    for i in range(101):
        if (i%5 == 0) == True:
            n.append(i)

def g():
    n = []
    for i in range(101):
        if i%5 == 0:
            n.append(i)

def h():
    n = []
    for i in range(101):
        if i%5 == 0 is True:
            n.append(i)

if __name__ == '__main__':
    import timeit
    print("time of f()")
    print(timeit.timeit("f()", setup="from __main__ import f"))
    print("time of g()")
    print(timeit.timeit("g()", setup="from __main__ import g"))
    print("time of h()")
    print(timeit.timeit("h()", setup="from __main__ import h"))
Code:
time of f()
20.914788356999907
time of g()
15.691095159000042
time of h()
14.912919614999964
Programming homework and newbie help thread Quote
03-30-2016 , 09:01 AM
Hi guys. basic SQL question

Look a the same id with different colors. This is a composite key correct? It's ok to repeat the id if the corresponding colors are different?


Last edited by mackeleven; 03-30-2016 at 09:15 AM.
Programming homework and newbie help thread Quote
03-30-2016 , 09:40 AM
Quote:
Originally Posted by daveT
Not saying speed is the end-all be-all, but pretty interesting results here:

Code:
def f():
    n = []
    for i in range(101):
        if (i%5 == 0) == True:
            n.append(i)

def g():
    n = []
    for i in range(101):
        if i%5 == 0:
            n.append(i)

def h():
    n = []
    for i in range(101):
        if i%5 == 0 is True:
            n.append(i)

if __name__ == '__main__':
    import timeit
    print("time of f()")
    print(timeit.timeit("f()", setup="from __main__ import f"))
    print("time of g()")
    print(timeit.timeit("g()", setup="from __main__ import g"))
    print("time of h()")
    print(timeit.timeit("h()", setup="from __main__ import h"))
Code:
time of f()
20.914788356999907
time of g()
15.691095159000042
time of h()
14.912919614999964
Very strange if h() actually generates faster code than g(), but I strongly suspect its just variance. Wouldn't be surprised if the extra "== True" in f() also gets optimized out, and this is all variance.
Programming homework and newbie help thread Quote
03-30-2016 , 09:55 AM
Ok I ran it five times. f() is definitely slower, just variance between g() and h(). We don't have to start adding "is True" to the end of every conditional for the speed boost.

Code:
time of f()
10.5015571117
time of g()
7.53890514374
time of h()
7.57018399239

time of f()
10.3168020248
time of g()
7.42059087753
time of h()
7.48808908463

time of f()
10.3302388191
time of g()
7.49171996117
time of h()
7.41190600395

time of f()
10.3346700668
time of g()
7.39410185814
time of h()
7.37979912758

time of f()
10.3475000858
time of g()
7.44040989876
time of h()
7.45592093468
Programming homework and newbie help thread Quote
03-30-2016 , 10:01 AM
Yeah it's a fluke. If you run the timeits a few times in my case it settles out with g being faster than h by a little most of the time. I found another minor improvement, there may be more also.

ETA: actually, I've run it a few times now and h does come out faster pretty often. I suppose they're pretty close.

Code:
def f():
    n = []
    for i in range(101):
        if (i%5 == 0) == True:
            n.append(i)

def g():
    n = []
    for i in range(101):
        if i%5 == 0:
            n.append(i)

def h():
    n = []
    for i in range(101):
        if i%5 == 0 is True:
            n.append(i)

def i():
    n = [x for x in range(101) if not x % 5]

def j():
    n = range(0, 101, 5)
Code:
time of f()
15.9861290455
time of g()
12.2365651131
time of h()
11.1904981136
time of i()
9.35484814644
time of j()
0.545165061951
I threw in "j" to try to get an idea of how much room for improvement there was.

I think it's interesting to note that we can get almost a 2x speedup just by being careful with how we construct a list. A general rule of thumb in python is that if you can do something in a single statement, it'll be faster than the equivalent in multiple statements.
Programming homework and newbie help thread Quote
03-30-2016 , 10:18 AM
Quote:
Originally Posted by RustyBrooks
ETA: actually, I've run it a few times now and h does come out faster pretty often. I suppose they're pretty close.
I would guess "<boolean expression> is True" gets optimized down to <boolean expression>, so there's no difference between g() and h(). But apparently this isn't happening with "<boolean expression> == True".
Programming homework and newbie help thread Quote
03-30-2016 , 10:33 AM
Although adding extra "is True" layers does seem to slow things down. Maybe just the outermost "is True" gets optimized out?

Code:
def f():
    n = []
    for i in range(101):
        if (i%5 == 0) == True:
            n.append(i)

def g():
    n = []
    for i in range(101):
        if i%5 == 0:
            n.append(i)

def h():
    n = []
    for i in range(101):
        if i%5 == 0 is True:
            n.append(i)

def j():
    n = []
    for i in range(101):
        if ((i%5 == 0 is True) is True) is True:
            n.append(i)

if __name__ == '__main__':
    import timeit
    print("time of f()")
    print(timeit.timeit("f()", setup="from __main__ import f"))
    print("time of g()")
    print(timeit.timeit("g()", setup="from __main__ import g"))
    print("time of h()")
    print(timeit.timeit("h()", setup="from __main__ import h"))
    print("time of j()")
    print(timeit.timeit("j()", setup="from __main__ import j"))
Code:
time of f()
10.4061429501
time of g()
7.39219403267
time of h()
7.44672012329
time of j()
11.1730470657
Programming homework and newbie help thread Quote
03-30-2016 , 10:39 AM
You're gonna have to run them a 1000 times and take the average and standard deviation
Programming homework and newbie help thread Quote
03-30-2016 , 10:42 AM
timeit runs the function many many times, I don't know how many.

ETA: looks like the default is 1 million times
Programming homework and newbie help thread Quote
03-30-2016 , 10:58 AM
In that case it would be interesting if timeit also returned the standard deviation so you could get an idea if the difference in time between two functions is significant
Programming homework and newbie help thread Quote
03-30-2016 , 11:09 AM
There might be a bigger issue with h(), though (which I was not previously aware of):

Code:
>>> 5%5 == 0
True
>>> 5%5 == 0 is True
False
>>> (5%5 == 0) is True
True
Edit: And indeed at the end of the loop in h(), n remains empty.

Last edited by JSLigon; 03-30-2016 at 11:21 AM.
Programming homework and newbie help thread Quote

      
m