I need ideas!

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

34 Replies - 3486 Views - Last Post: 24 May 2012 - 08:14 AM Rate Topic: -----

#1 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

I need ideas!

Posted 04 May 2012 - 08:34 AM

I wish to train my python skills, yet I have absolutely no idea what I could make :/
is there anyone out here who might help me out with this?

^= I want to apologise for placing this post between code tags, this was my first post and I was sort of confused with the instructions...

This post has been edited by Curtis Rutland: 09 May 2012 - 08:17 AM
Reason for edit:: edited for formatting

Is This A Good Question/Topic? 0
  • +

Replies To: I need ideas!

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9572
  • View blog
  • Posts: 36,253
  • Joined: 12-June 08

Re: I need ideas!

Posted 04 May 2012 - 08:35 AM

Standard project lists we have;

Project Ideas

Martyr2 Mega Project List
Was This Post Helpful? 2
  • +
  • -

#3 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 04 May 2012 - 08:50 AM

*
POPULAR

I'll tell you a project that is simple, but doing it right *and efficiently* takes a little more thought.

Write me a program that will take 1 command line argument. This command line argument should be an integer (n). The program will then create a list of random numbers of size n. Then, report the range, mode, median, and mean of that list. When you've done that, report your answers in a well formatted manner.

At the end, give the user the option to output the results to a file.

Be sure to use good programming practices, particularly modularity and proper use of commenting (including docstrings).

That oughta be a good project. Post your results when you're ready for review.

P.S. At my last job, this was the weed-out test I designed for programmers looking for an interview. Before anyone could get through the door, they HAD to send me a program fulfilling these requirements (although I never mentioned docstrings or modularity, that was up to the applicant).

This post has been edited by atraub: 04 May 2012 - 08:53 AM

Was This Post Helpful? 5
  • +
  • -

#4 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 04 May 2012 - 08:55 AM

View Postatraub, on 04 May 2012 - 04:50 PM, said:

I'll tell you a project that is simple, but doing it right *and efficiently* takes a little more thought.

Write me a program that will take 1 command line argument. This command line argument should be an integer (n). The program will then create a list of random numbers of size n. Then, report the range, mode, median, and mean of that list. When you've done that, report your answers in a well formatted manner.

At the end, give the user the option to output the results to a file.

Be sure to use good programming practices, particularly modularity and proper use of commenting (including docstrings).

That oughta be a good project. Post your results when you're ready for review.

P.S. At my last job, this was the weed-out test I designed for programmers looking for an interview. Before anyone could get through the door, they HAD to send me a program fulfilling these requirements (although I never mentioned docstrings or modularity, that was up to the applicant).


well, I feel sort of stupid now, since I don't completely understand the assignment (my native language is dutch) so would you mind rephrasing your assignment with other words?
my apologies for my bad english understanding. I'll improve
Was This Post Helpful? 0
  • +
  • -

#5 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 04 May 2012 - 09:06 AM

Get a value from the user that we'll refer to as N (you can ask the user for the number, or utilize command line arguments)

create a list that holds N random numbers

From that list, find the range, mode, median, and mean. For a good explanation as to what these values are, go to this website.

When you find these results, communicate it back to the user in a way that's easy to read and looks good. Then, ask the user if he wants the program to write the results to a file.

Make sure your program is broken up into functions, and make sure you make good use of commenting.

This post has been edited by atraub: 04 May 2012 - 09:10 AM

Was This Post Helpful? 1
  • +
  • -

#6 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 04 May 2012 - 11:28 AM

well I (sort off) finished the code, yet I just don't seem to be able to fix the write to file part :( I have failed at already my first challenge... that sucks. and altough I really know how to write to files (f = open([path],[mode]) followed by f.write(content) ) I just write empty files or the file writes the \n along -_-
if you want to see the code anyway, here it is:
import random
import math
import os
numbers = []
avr = 0
med = 0
mode = 0
def collect(cypher): #this function creates a list with all the numbers in
     '''this function collects the numbers'''
     numbers.append(cypher)
     if len(numbers) == n: #when all numbers are listed
         print('range: 0-100')
         print('length of list:',n)
         average()
         median()
         mode(numbers)
         if permission():
              print('writing')
              #I couldn't get the writing part to work :(/>
         else:
              print('results not written to file')
              print('press enter to exit')
              input()
              exit()
def average(): #this function will calculate the average of the gathered list
     '''calculates the average'''
    avr = sum(numbers)/len(numbers) #<=calulates the average or mean
    print('mean:',round(avr,2)) #this returns the mean, with two cyphers after the comma
    return avr
def median():
     '''calculates the median'''
    numbers.sort() #orders all of the numbers from low to high
    mid = math.ceil(len(numbers)/2) #calculates the number in the middle
    med = numbers[mid] #selects the number in the middle
def mode(li):
     '''calculates the mode'''
    li.sort()
    numbers = {}
    for x in li:
        num = li.count(x)
        numbers[x] = num
    highest = max(numbers.values())
    for m in numbers.keys():
        if numbers[m] == highest:
            mode = m
    print('mode:',mode)
def permission():
     '''checks wether the user gives permission to write'''
     
    print('write results to textfile? (y/n)')
    permission = input()
    if permission is not "y" or permission is not "n" or permission is not "yes" or permission is not "no": #checks wether a correct answer is given
        if permission == 'y' or permission == 'yes':
            return True
        else:
            return False
    else:
        print('invalid answer, try again')
        permission()
n = input('enter a number:')
try:
    n = int(n) #tries to make n a number
except:
    print('entered value is not an integer, or cannot be converted like one') #if n can't be converted to a number it gives this error message
    exit()
for x in range(0,n): #for as many numbers 'n' it sends a random number to collect() which makes it a list
    cijfer = random.randrange(0,100)
    collect(cijfer)



Was This Post Helpful? 0
  • +
  • -

#7 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 04 May 2012 - 11:55 AM

correction (geesh I don't wanna be someone who posts the most on his own comments D:)
import random
import math
import os
numbers = []
avr = 0
med = 0
mode = 0
def collect(cypher): #this function creates a list with all the numbers in
     '''this function collects the numbers'''
     numbers.append(cypher)
     if len(numbers) == n: #when all numbers are listed
         print('range: 0-100')
         print('length of list:',n)
         average() #call the functions
         median()
         mode(numbers)
         if permission():
              print('writing')
              write(average(),median(),mode(numbers),100) #call the functions to transfer the data to the write function
              #I couldn't get the writing part to work :(/>
         else:
              print('results not written to file')
              print('press enter to exit')
              input()
              exit()
def average(): #this function will calculate the average of the gathered list
    '''calculates the average'''
    avr = sum(numbers)/len(numbers) #<=calulates the average or mean
    print('mean:',round(avr,2)) #this returns the mean, with two cyphers after the comma
    return avr
def median():
    '''calculates the median'''
    numbers.sort() #orders all of the numbers from low to high
    mid = math.ceil(len(numbers)/2) #calculates the number in the middle
    med = numbers[mid] #selects the number in the middle
    print('mediaan:',med)
    return med
def mode(li):
    '''calculates the mode'''
    li.sort()
    numbers = {}
    for x in li:
        num = li.count(x)
        numbers[x] = num
    highest = max(numbers.values())
    for m in numbers.keys():
        if numbers[m] == highest:
            mode = m
    print('mode:',mode)
    return mode
def permission():
    '''checks wether the user gives permission to write'''
     
    print('write results to textfile? (y/n)')
    permission = input()
    if permission is not "y" or permission is not "n" or permission is not "yes" or permission is not "no": #checks wether a correct answer is given
        if permission == 'y' or permission == 'yes':
            return True
        else:
            return False
    else:
        print('invalid answer, try again')
        permission()
def write(average,median,mode,rang):
     print(average,median,mode,rang)
     f = open("numbers.txt","w")
     f.close()
     f = open("numbers.txt","a")
     average = 'average:',average
     median = 'median:',median
     mode = 'mode:',mode
     rang = 'range:',rang
     rang = str(rang)
     average = str(average)
     mode = str(mode)
     median = str(median)
     f.write(rang)
     f.write("\n")
     f.write(average)
     f.write("\n")
     f.write(median)
     f.write("\n")
     f.write(mode)
     f.close()
     print('results written')
     input()
n = input('enter a number:')
try:
    n = int(n) #tries to make n a number
except:
    print('entered value is not an integer, or cannot be converted like one') #if n can't be converted to a number it gives this error message
    exit()
for x in range(0,n): #for as many numbers 'n' it sends a random number to collect() which makes it a list
    cijfer = random.randrange(0,100)
    collect(cijfer)



Was This Post Helpful? 2
  • +
  • -

#8 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 04 May 2012 - 03:15 PM

Hey this is great! I'll look at it in a little while and get back to you. It's nice to see programmers enthusiastic about improving their skills.
Was This Post Helpful? 0
  • +
  • -

#9 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 05 May 2012 - 01:13 AM

thanks, altough I only started a week ago in python I really enjoy this language! yet a friend of mine (who is a real genius in python, no doubting it) says it is not pythonic. which he means with that is is not a short and effective as it could be. honestly I must say he is right, (what I am about to do is not smart but I am gonna do it anyway: pointing out my faults)
the writing function is way to long and not efficient enough, and I am pretty sure the code can be shortened with about 10 lines. but he also told me (just before I got depressed :P) that he found it impressive that I already managed to build this so far.
Was This Post Helpful? 0
  • +
  • -

#10 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 05 May 2012 - 10:59 AM

*
POPULAR

Alright, so I just ran your program.


Functionality
I ran your program without looking at the code at all. Here was the output in my terminal

enter a number:12
range: 0-100
length of list: 12
mean: 59.33
mediaan: 60
mode: 95
write results to textfile? (y/n)
n
results not written to file
press enter to exit



The first thing I noticed was "Where's the list?" I can't see what the numbers were, so there's no way for me to actually confirm the values. I did a quick edit to your program and printed the list.

enter a number:5

[83,36,43,1,12]

range: 0-100
length of list: 5
mean: 35.0
mediaan: 43
mode: 36
write results to textfile? (y/n)
n
results not written to file
press enter to exit



On the next run, my list was [83,36,43,1,12]. Your program first reported that the length of the list is 5, this is true. your program then claimed the mean was 35, I have confirmed this is true. It then claimed the median was 43, this is false, the median is 36. It claims that the mode is 36, this is also false. Because the numbers all appear once and only once, there is no mode.

I think there was a minor misunderstanding about range. The range of possible random numbers that could go in your list were the values 0 - 100, this is true. However, the range of numbers that appeared in your list were 1 - 83, thus making your list have a range of 82 (the biggest value minus the smallest value).

Next, I tested out the file writing. Your program does correctly write data to a file, and the data looks like this:
('range:', 100)
('average:', 42.8)
('median:', 71)
('mode:', 71)

I bet you could make this look prettier if you wanted to.

Code
At this point, I decided to take a look at your code. Your import statements are at the top of the module, which is exactly where they should be. The first thing I noticed is that your script uses some global values. This is typically something we try to avoid, when possible, we want Everything to be in a function.

Your functions all have proper docstrings, this is good. Your algorithm is interesting. You create the numbers, 1 value at a time, and then call collect(). Collect adds the number to a list, and if the list has the right amount of numbers in it, it proceeds with the math functions. This is very clever, but we could make it a little simpler.

instead, why not do this?
for x in range(n): #for as many numbers 'n' it sends a random number to collect() which makes it a list
    cijfer = random.randrange(0,100)
    numbers.append(cijfer)
collect(cijfer)



Notice that I just added the number to your numbers list, and then I called collect after all of the numbers were added. This makes things a little easier. Then, you could get rid of a few things at the top of collect

def collect(cypher): #this function creates a list with all the numbers in
     '''this function collects the numbers'''
     print('range: 0-100')
     print('length of list:',n)
     average() #call the functions
     median()
     mode(numbers)
     if permission():
          print('writing')
          write(average(),median(),mode(numbers),100) #call the functions to transfer the data to the write function
          #I couldn't get the writing part to work :(/>
     else:
          print('results not written to file')
          print('press enter to exit')
          input()



When we do it like this, collect only needs to be called once because we KNOW all the values have already been added to your list. I'm going to teach you a trick called list comprehensions. This is a really cool Python tool and it will help you with similar programs in the future.

I'm running this code in IDLE:

>>> x = [i for i in range(10)]
>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


I was able to make a list holding 10 numbers, 0 - 10 really fast and easy. here's how you read it. Start with the word 'for'

   "For each number 'i' in the range of of 10"
[i for i in range(10)]
 ^
 Add i to the list


We can make it more interesting if we want to. Here's another example:
>>> x = [i*10 for i in range(10)]
>>> x
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> 


Which can be read as:
   "For each number 'i' in the range of of 10"
[i*10 for i in range(10)]
 ^
 Add i*10 to the list


we can add anything we want into our list, here's one more for you:
>>> import random
>>> x = [random.randint(0,100) for i in range(10)]
>>> print(x)
[5, 18, 98, 89, 7, 83, 98, 98, 100, 36]



Which can be read as:
   "For each number 'i' in the range of of 10"
[random.randint(0,100) for i in range(10)]
 ^
 Add a random number from 0 to 100 to the list


I'm sure you already see where I'm going with this. You could modify your code to say:

n = input('enter a number:')
try:
    n = int(n) #tries to make n a number
except:
    print('entered value is not an integer, or cannot be converted like one') #if n can't be converted to a number it gives this error message
    exit()

numbers = [random.randint(0,100) for x in range(n)]
collect()



Pretty cool, right? For more information on List Comprehensions, check this link.

your average function works correctly!
Your median function has a problem where it actually finds the number 1 spot after the median. If you subtract 1 from your value mid it will work with lists that have an odd number of elements. However, what if you have a list with an even number of elements?
For example, the list [2,4,6,8] has 4 elements. There is no exact 'middle number'. Instead, we have to take the two numbers in the middle 4 and 6, and find their average, which is 5. To check if a list has an even number of elements, you would say
if len(myList) % 2 == 0: #Even
if len(myList) % 2 == 1: #Odd

The modulo operator (%) gets the remainder when two numbers are divided, for example 10 % 3 = 1 because 10 / 3 = 3 with a remainder of 1.

mode is good, but it doesn't take into account what happens if there is no mode or if there are multiple modes. Don't lose too much sleep over this one, mode IS the hardest part of this program.

There's plenty more we can talk about, but I think I've given you some stuff to think about. Before we go any future, I'm going to challenge you to edit your program so that ALL your code is inside of functions except for your import statements. This is a great attempt, and I think we can do a lot to improve it and help you become a really good programmer. I know English isn't your first language. If you need help understanding anything I said, just copy and paste it into quote tags and we'll help you understand it.

TO THE OTHER MEMBERS OF DIC
Yes, I realize that there's plenty more we can talk about. Don't worry, we will, but let's not overload the guy on his first submission. If he's dedicated and interested in learning to be a great programmer, we WILL cover everything he needs to know. I want to work with him to improve this program incrementally, covering new topics and concepts as we go. I'm asking you not to post completed versions of this assignment until we're further along.

This post has been edited by atraub: 05 May 2012 - 11:39 AM
Reason for edit:: found a typo

Was This Post Helpful? 9
  • +
  • -

#11 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,661
  • Joined: 23-August 08

Re: I need ideas!

Posted 05 May 2012 - 11:26 AM

atraub needs an editor! :bigsmile:

J/K, what a great response!
Was This Post Helpful? 0
  • +
  • -

#12 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 05 May 2012 - 11:31 AM

Haha thanks man, it took a while! I know it's pretty long, and to be honest, I could have written about double that if I didn't have a 6 page essay due yesterday and a take home exam due tomorrow.

Incidentally, if there are a lot of typos I didn't notice, I'm blaming the keyboard! lol I just got a new one because a few of the keys died in my old one. When I lost, 'x', 'c', and 'esc' I knew it was time. Anywho, the new one is a funny "ergonomic" shape and is taking some getting use to.

Also, while writing that, it did occur to me how awesome a text editor that could also show BB markup would be. :)

This post has been edited by atraub: 05 May 2012 - 11:41 AM

Was This Post Helpful? 0
  • +
  • -

#13 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 05 May 2012 - 12:08 PM

wow, this is indeed quite a lot to read. and indeed now you mention it the things you suggested are indeed more efficient. altough some things I never had seen some things, like this:
x = [i for i in range(10)]


probably that's just because I just started out in python. for the rest, I'll try improving my script and I honestly thank you for your kind words and your believe in me. also I want to wish you luck with your exam and paper. also (wow a lot of also in this comment) I want to say LoL @JackOfAllTrades
also I know that the writing part which returns:
(^a wild also appeared :P )
('range:', 100)
2
('average:', 42.8)
3
('median:', 71)
4
('mode:', 71)



was gonna look a lot better, but the original code for writing I wrote returned this text. also the global variables, I know it is not good (my friend, the python genius, nearly killed me for using it in one of my first scripts @ level: hello world) but in earlier stages of my script I tried writing the content in that global variables to avoid getting this.
short:
thank you, good luck and I will improve this script. could you give this a rating (so at the end when a corrected version statisfies you I can compare the levels)
Was This Post Helpful? 0
  • +
  • -

#14 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: I need ideas!

Posted 05 May 2012 - 12:20 PM

To be honest, I've been using Python for about 6 years give or take, and I only learned about List Comprehensions a little over a year ago. It's a really cool trick that impresses people who've never seen it before. You'll find a lot of programmers don't know what they are :)

P.S. I'm not sure if you knew this, but you can 'rate' my posts! just click on the Posted Image if my post was helpful to you :) You'll notice that I clicked on Posted Image on the post where you submitted your code because I was impressed by the effort you put into it. If anyone ever writes a post that is really negative and doesn't help at all, you can also click on the Posted Image but we usually only do that for REALLY bad posts.

This post has been edited by atraub: 17 May 2012 - 09:15 AM

Was This Post Helpful? 1
  • +
  • -

#15 digitaldevelopment  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 168
  • Joined: 30-April 12

Re: I need ideas!

Posted 05 May 2012 - 12:43 PM

oh I hadn't noticed them before, I will certainly like that long post since it was very helpful, and about the rating;
you can do it when you have time, since I could see at your (long) post you have it quite busy. anyway good luck (again)
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3