473,385 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

histogram in python

I want to draw a histogram of 2-11 and each bar of the number would reach up to the chain length of that number.
I have a hailstone sequence as given below

Expand|Select|Wrap|Line Numbers
  1. import string
  2. # from graphics import *
  3. from graphics import *
  4.  
  5. #Constant
  6. MAX = 10000
  7.  
  8. # printing functions
  9.  
  10. # this function prints a brief description of the program to the user
  11. # Inputs: none
  12. # Outputs : none
  13. def printGreeting():
  14.     print ""
  15.     print " This program finds hailstones sequences of numbers"
  16.     print " you choose. The next number in the sequence if found by"
  17.     print " either dividing it by two(if even) or multiplying by 3"
  18.     print " and adding 1(if odd).The program quits when the last"
  19.     print " number in the sequence is 1\n"
  20.  
  21. # this functions prints the menu for the user 
  22. # Inputs: none
  23. # Outputs : none
  24. def printMenu():
  25.     print "\n\tHere are your menu choices:"
  26.     print "\n\tI - view squence for an individual value\n"
  27.     print "\tR - veiw sequence for range of values\n"
  28.     print "\tL - Find the longest chain\n"
  29.     print "\tH - Print out the histogram\n"
  30.     print "\tQ - Quit\n\n"
  31.  
  32. # end of printing funtions
  33.  
  34.  
  35. # hailstone(number) prints the hailstone sequence
  36. # Inputs: number
  37. # Outputs: none
  38. def hailstone(n):
  39.  
  40.     length = 1
  41.     print n,
  42.     # checks if n is not sential 
  43.     while n != 1:
  44.  
  45.         # if even, divide by 2 (rule). add 1 to length
  46.         if n % 2 == 0:
  47.             n = n / 2
  48.             print "->",n,
  49.             length = length + 1
  50.  
  51.         # if odd, multiply by 3, add 1 (rule). add 1 to length
  52.         elif n % 2 != 0:
  53.             n = ( 3 * n ) + 1
  54.             print "->",n,
  55.             length = length + 1
  56.  
  57.     # print the length at the end of each chain
  58.     print "; length =",length
  59.     print "----------------------------------------------------------------",
  60.     print "--------------\n"
  61.     return length
  62.  
  63. # this function returns the length of each chain from the starting number, n
  64. # Inputs : n
  65. # Outputs : none
  66. def chain(n):
  67.  
  68.     length = 1
  69.     while n != 1:
  70.  
  71.         # if even, divide by 2 (rule). add 1 to length
  72.         if n % 2 == 0:
  73.             n = n / 2
  74.             length  = length + 1
  75.  
  76.         # if even, divide by 2 (rule). add 1 to length
  77.         elif n % 2 != 0:
  78.             n = ( 3 * n ) + 1
  79.             length = length + 1
  80.     return length
  81.  
  82. # getValidInt() prompts the user to enter an integer in the specified range,
  83. # rejects values not in that range by requiring new input, and only returns
  84. # a valid integer.
  85. # Inputs: the question of the prompt,
  86. #         the minimum value in the range
  87. #         and the maximum value in the range
  88. # Output: an integer in the specified range
  89. def getValidInt(question, min, max):
  90.  
  91.     # use a bad value to enter the loop
  92.     value = max + 1
  93.  
  94.     # compose the prompt 
  95.     prompt = question + " (" + str(min) + "-" + str(max) + "): "
  96.  
  97.     # continue to get values until the user enters a valid one
  98.     while value == "" or value < min or value > max:
  99.         value = raw_input(prompt)
  100.         if len(value) != 0:
  101.             value = int(value)
  102.  
  103.     # return a valid value
  104.     return value
  105.  
  106.  
  107. # this function finds the longest chain
  108. # Inputs: none
  109. # Outputs : none
  110. def longChain():
  111.      begin = "Please enter the begining integer for the range"
  112.      end = "Please enter the ending integer for the range"
  113.  
  114.      # calls to getValidInt for starting and ending values
  115.      beginNum = getValidInt(begin, 1, MAX)
  116.      endNum = getValidInt(end, beginNum + 1, MAX)
  117.  
  118.      largestChain = beginNum
  119.  
  120.      for i in range(beginNum, endNum+1):
  121.          if largestChain <= chain(i):
  122.              largestChain = i
  123.              length = chain(i)
  124.  
  125.      print largestChain, " had the longest chain ", length
  126.  
  127. # this function finds the longest chain***************************8
  128. # Inputs: none*************
  129. # Outputs : none    
  130. def histogram():
  131.     # initialize variables  
  132.     longestLength = 1
  133.     list = []
  134.  
  135.     start = input("Please enter the begining integer for the range: ")
  136.     for n in range (start, start + 10):
  137.         length = chain(n)
  138.         list.append(length)
  139.         if longestLength <= chain(n):
  140.             longestLength = n
  141.             length = chain(n)
  142.         print longestLength
  143.         print list
  144.  
  145. def main():
  146.  
  147.     # prints the greeting to the user
  148.     printGreeting()
  149.  
  150.     # prints the menu to the user
  151.     printMenu()
  152.  
  153.     # asks user the menu choice
  154.     choice = raw_input("Please enter your choice : ").upper()
  155.  
  156.     # checks to see if choice entered is from the menu
  157.     while choice != 'Q': 
  158.  
  159.         # if choice is "I" or "i", proceeds to follow the individual steps
  160.         if choice == 'I':
  161.             n = input("Please enter your integer (1-10000):")
  162.             hailstone(n)
  163.  
  164.         # if choice is "R" or "r", proceds print each number and its sequence
  165.         # until the last number is 1, uses getValidInt to get valid integers
  166.         # for the function
  167.         elif choice == 'R':
  168.  
  169.             begin = "Please enter the begining integer for the range"
  170.             end = "Please enter the ending integer for the range"
  171.  
  172.             # calls to getValidInt for starting and ending values
  173.             beginNum = getValidInt(begin, 1, MAX)
  174.             endNum = getValidInt(end, beginNum + 1, MAX)
  175.  
  176.             # for loop to get the values between starting and ending value
  177.             for n in range(beginNum,endNum+1):
  178.  
  179.                 #call to the hailstone function
  180.                 hailstone(n)
  181.  
  182.         # if choice is "L" or "l", proceeds to use getValidInt again to get the
  183.         # range, error checks on the range, and then calls the function chain
  184.         # to determine the length. 
  185.         elif choice == 'L':
  186.             # call to function longchain
  187.             longChain()
  188.  
  189.         elif choice == 'H':
  190.             histogram()
  191.  
  192.         # if niether of the menu choices, then it prints that the
  193.         # entered text is not a valid choices
  194.         else:
  195.             print choice, "is not a valid choice"
  196.  
  197.         # prints the menu to the user
  198.         printMenu()
  199.  
  200.         # asks user the menu choice
  201.         choice = raw_input("Please enter your choice : ").upper()
  202.  
  203. main()
but how can i draw a histogram of 2-11 and each bar of the number would reach up to the chain length of that number inside this hailstone sequence.
Nov 1 '11 #1
7 4668
Glenton
391 Expert 256MB
Using matplotlib is probably the best way to do graphing including histograms.
Nov 2 '11 #2
bvdet
2,851 Expert Mod 2GB
Calculate the chains for each number 2 through 11 and save in a dictionary. In Tkinter, you could create a canvas with an X and Y axis on the bottom and left respectively. The X axis would be labeled 2 through 11 and the Y axis would be labeled to match the height of the longest chain. Create rectangles for each number 2 through 11 with an appropriate width for display and height to match the chain length (obtained from the dictionary) multiplied by a factor for an appropriate display.
Nov 2 '11 #3
Glenton
391 Expert 256MB
You could do it that way, but matplotlib is an excellent way to plot graphs. It's used for publications and is very flexible. Here's a link to a histogram demo.

There is another possibility which is to use gnuplot, and gnuplot.py to control it from your programme.
Nov 3 '11 #4
we want to allow the user to draw histograms for more than one range of numbers during the running of the program, we'll want to close the window after having enough time to view it. You should close the window after 10 seconds. You'll need to use sleep() to do this.
All handling of the graphics window should be done within the drawHistogram() function. In fact, since the window is opened in this function, it is local to this function. Trying to close the window in main() will cause an error when run.
http://www.cs.umbc.edu/courses/201/f...ges/histo2.jpg
Nov 3 '11 #5
bvdet
2,851 Expert Mod 2GB
Glenton - I'm sure you are right, but I wanted to outline how I would do it in Tkinter. I know about matplotlib but have never used it.

asong84 - If using Tkinter, I recommend using widget method after() instead of time.sleep().
Nov 3 '11 #6
dwblas
626 Expert 512MB
A histogram is just rectangles, usually with different fill colors. The following code does not make sense, at least to me, so take a look at the comments.
Expand|Select|Wrap|Line Numbers
  1. def histogram():
  2.      # initialize variables  
  3.      longestLength = 1
  4.      ## list is already used by python to convert something to 
  5.      ## a list, so always use another name
  6.      list = []           
  7.      start = input("Please enter the begining integer for the range: ")
  8.      for n in range (start, start + 10):
  9.  
  10.          ## You call the same chain(n) 3 times in this function
  11.          ## which doesn't make much sense.  Use "length" instead
  12.          length = chain(n)
  13.          list.append(length)
  14.          if longestLength <= chain(n): # chain(n)=length so longestLength <= length
  15.              longestLength = n
  16.              length = chain(n)    ## you already did this
  17.          print longestLength
  18.          print list 
Nov 3 '11 #7
dwblas i have already made that changes already, i am now trying to figure out how to make a histogram of chainlength n.
Glenton- am still trying out the matplotlib.will get back to you if i have a problem.
Nov 3 '11 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Oracle3001 | last post by:
Hi All, I am trying to use JAI to build a histogram of an image i have. I have posted the code below, and the error I get at runtime. I have taken the code from the offical java examples, so I am...
1
by: bleh | last post by:
....to include a removeData(datatoremove) function, to mirror the existing addData(datatoadd) function. If anybody knows of somewhere where this has been done already, if you could point me in...
27
by: ext_u | last post by:
Ok I thought I would try to take the program one thing at a time. (If you remember my last post I am trying to make a histogram with data on the size of each word) Anways first .. I obviously...
12
by: KraftDiner | last post by:
Hi, I wrote a C++ class that implements an n dimensional histogram in C++, using stl maps and vectors. I want to code this up now in Python and would like some input from this group. The C++...
5
by: Enigma Curry | last post by:
I'm playing around with matplotlib for the first time. I'm trying to make a very simple histogram of values 1-6 and how many times they occur in a sequence. However, after about an hour of...
2
by: Daniel Nogradi | last post by:
How does one do a histogram on only a part of an image? This is what I found in the PIL documentation about histogram( ): """ im.histogram(mask) =list Returns a histogram for those parts of...
5
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any...
12
by: arnuld | last post by:
i was able to create a solution for a Horizontal-Histogram. i was completely unable to understand this Vertical-Histogram phenomenon. even though i have looked at the solution at this page: ...
1
by: avenger3200 | last post by:
Hello everyone, I am trying to make a histogram for a project in my class and I really need some help. Here is the question that my instructor provided: Create 1000 Random numbers between...
0
by: Kurt Smith | last post by:
On Fri, Jul 25, 2008 at 5:02 PM, aditya shukla <adityashukla1983@gmail.comwrote: the 'bins' argument to pylab.hist() is supposed to be an integer or a list of the bins' lower edges. The default...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.