[Tutor] Assigning range

Donald Wilson donald.ww at me.com
Thu Jul 28 05:16:05 CEST 2011


You could start with an anonymous function using the lambda operator, such as:

------------------------------------------------------------

mid_range = lambda x: x[len(x) // 2]

Note: If you use len(x) / 2 in python 3.x you will get a TypeError because the division operator / returns a float. Floor // returns an int in 2.x and 3.x.

Then use either:

x = range(1000, 4001)
mid_x = mid_range(x) # mid_x == 2500

or…

mid_x = mid_range(range(500, 751)) # mid_x == 625

etc. to retrieve the middle element.

You can extract the mid point of any sequence type, such as a string, using this function.

mid_x = mid_range(‘12345678987654321’) # mid_x == ‘9’

------------------------------------------------------------

middle_number = lambda lo, hi: abs(lo - hi) // 2

will work if you just need the mid point of two numbers; either ints or floats.

mid_x = middle_number(0, 1000) # mid_x = 500

DW

On Jul 27, 2011, at 8:16 PM, Alexander Quest wrote:

> Does anyone know how to assign a certain numerical range to a variable, and then choose the number that is the middle of that range? For example, I want to assign the variable "X" a range between 1 and 50, and then I want to have the middle of that range (25) return with some command when I call it (perhaps rangemid or something like that?). In pseudocode, I am trying to say X = range [1,50], return middle of range (which should return 25) but I don't know how to code it. This is for a basic program I'm trying to write where the player thinks of a number and the computer tries to guess the number in as few tries as possible. Thanks for any help!
> 
> -Alex
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list