4,305 Posted Topics
Folks have asked numerous times for a code snippet of a binary search of an array. Here is heavily commented code with a few test printf() included to give you a picture of what is going on. | |
Re: A bad mathematics teacher in high school can discourage a lot of young people to go into a scientific career. There are some nice computer programs available to put you back on track with mathematics. Just Google for them. | |
Re: Here is an example how to access one frame from the other via the instance ... [code]# create two frames with wxFrame # access one frame from the other import wx import random class Frame1(wx.Frame): def __init__(self, parent): # self will be the Frame1 instance wx.Frame.__init__(self, parent, wx.ID_ANY, title='Frame1', pos=(50, … | |
Re: Of course numpy limits you to numeric arrays. A dictionary is a very efficient object in Python. The language itself uses it internally. | |
Re: [QUOTE]The reindeer, payload, Santa and sleigh would therefore weigh more than 353,430 tons.[/QUOTE] Reactionless thrusters and time dilation effects explain a lot, but the average roof would have a hard time with this weight! | |
Re: Here is an example ... [code]# show the time in a different time zone # see also: http://worldtimezone.net/ import datetime as dt now = dt.datetime.now() # for instance Los Angeles California # runs 8 hours behind GMT time gmt_offset = -8 gmt = dt.timedelta(hours=gmt_offset) print("Current L.A. time = %s" % … | |
Re: Here is an example ... [code]# show a Tkinter button without border # see also Button at: # http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() root.title("A button without border") # pick a GIF image you have in the … | |
Re: Can you give us an example what object dictionary looks like? | |
Re: You need to indent the statement blocks that belong to the class properly. | |
Re: You got to show some coding efforts. | |
Python does not have a type like struct in C or record in Pascal, but it can be easily implemented with a class. This little code snippet shows you how to do it. | |
I couldn't find a meaningful code sample for the wxPython slider (wx.Slider), so I concocted this one and added a few explanations. It explores two different sliders, one is horizontal, the other vertical. The slider events are then fed to a function that retrieves the position values and displays them … | |
Re: It might be safer to extract the numeric value ... [code]list1= ['NNW 30', 'SE 15', 'SSW 60', 'NNE 70', 'N 10'] list2 = [] for item in list1: s = "" for c in item: # extract numeric value if c in '1234567890.-': s += c if item[0] == 'N': … | |
Re: Here is one way to load a 10x10 list with integers from a text file ... [code]""" assume int10x10.txt looks like this --> 1212000200 1010222122 1100202011 2021112212 0221022122 2012101022 2020021121 0112202210 0122110121 1010102201 """ import pprint infile = open("int10x10.txt", "r") # create a 10x10 list of zeros list10x10 = [[0]*10 … | |
Re: The console environment is in many ways simpler than GUI programming. To illustrate that I will show you two simple programs that do the same chores. First the console program ... [code]# simple console data IO for Python3 # data in ... text = input("Enter your name: ") # process … | |
Re: To align columns in a table you can use the C style format specifiers with Python ... [code]mylist = [2, 5, 7, 4.5] for item in mylist: # experiment with the format specifiers # eg. change 6.3 to 6.2 or 4.4 to see effects print("%6.3f %6.3f" % (item, item*item)) ''' … | |
Re: This might help ... [code]array = ['test123','hallo','ABC','zipcode','Myname','computer','test456'] # sort case insensitive sorted_array = sorted(array, key=str.lower) print(array) print(sorted_array) ''' result --> ['test123', 'hallo', 'ABC', 'zipcode', 'Myname', 'computer', 'test456'] ['ABC', 'computer', 'hallo', 'Myname', 'test123', 'test456', 'zipcode'] ''' [/code] | |
| |
Re: Times are tough and the present lot of presidential hopefuls is the best this great country is able to buy. | |
Re: Python has a some string functions that will help, but you need to add your spaces and periods back in. Experiment a little and have fun ... [code]s = "hello. my name is Joe. what is your name?" sentence_list = s.split('.') print(sentence_list) for sentence in sentence_list: sentence = sentence.strip() print(sentence.capitalize()) … | |
Re: Here is one way to rotate an image with PIL (Python Image Library) ... [code]# rotate an image counter-clockwise using the PIL image library # free from: http://www.pythonware.com/products/pil/index.htm # save the rotated image as a GIF file so Tkinter can read it from PIL import Image import Tkinter as tk … | |
Re: Our snippet examples give you a list of primes. You could get a list of primes in the range of your numbers, and then see if your numbers are in it. For simplicity sake you can use this small function ... [code=python]# prime numbers are only divisible by unity and … | |
Re: For Python code on Daniweb: Please use the [b][noparse][code=python][/noparse][/b] and [b][noparse][/code][/noparse][/b] tag pair to enclose your python code. | |
Converting a decimal integer (denary, base 10) to a binary string (base 2) is amazingly simple. An exception is raised for negative numbers and zero is a special case. To test the result, the binary string is converted back to the decimal value, easily done with the int(bStr, 2) function. | |
Re: You need to observe the line: Copyright 2009 Bert Vermeulen <bert@biot.com> | |
Re: You need a string to split. I updated your code a little ... [code]#import string # old stuff #ofile=open(raw_input("Please enter the name of a text file :")) # open a text file you have for testing ... ofile = open("atest.txt") # read text in as one string s s = … | |
Re: BeautifulSoup requires the sgmllib module, which has been removed in Python 3. | |
I am still trying to take a look at the gtk GUI package and reinstalled the following: gtk-win32-devel-2.8.6-rc3.exe and pygtk-2.8.2-1.win32-py2.4.exe (updated version) I have it down to a simpler error message now. Here are my warnings and errors with the sample file base.py [code]Traceback (most recent call last): File "D:/Python24/Atest/Demo/pyGTK/base.py", … | |
Re: The input has to be in the form last,first,middle. You got to let the user know ... [code]def changeName(name): """ change name of form last,first,middle to first,middle,last """ fields = name.split(",") return fields[1],fields[2],fields[0] # input has to be in the form last,first,middle test_name = 'Staub,Joe,P.' new_name = changeName(test_name) print(new_name) [/code] | |
Is it Mother Date and Father Time? Any way, getting all the different date and time displays working can be imperturbably perplexing at times. You take a look at it in this Windows Console Application. | |
Re: Try ... [code]# cImage.py from: # www.cs.luther.edu/~pythonworks/PythonContext/cImage.py from cImage import* import random #RandomColor = random.random() myImWin = ImageWin("Line Image", 300, 300) lineImage = EmptyImage(300,300) redPixel = Pixel(255,0,0) # random.randint(0,255) picks an integer between 0 and 255 randomRed = Pixel(random.randint(0,255),0,0) for i in range(300): for x in range(250): lineImage.setPixel(50,i,redPixel) lineImage.setPixel(150,x,randomRed) lineImage.draw(myImWin) … | |
Re: What part of OOP don't you understand? | |
Re: What operating system do you have? I think XP and Vista have SAPI builtin? You also need pywin32-212.win32-py2.5.exe installed, the win32 extension package check with [url]http://sourceforge.net/project/platformdownload.php?group_id=78018[/url] Also take a look at: [url]http://www.daniweb.com/code/snippet326.html[/url] [url]http://www.daniweb.com/code/snippet856.html[/url] | |
Re: Just a a quick look. Read the comments ... [code]#the main function def main(): milesObtained = getMiles() #call to get the miles obtained # expect the return of one totalPrice, totalGallons tuple totalPrice, totalGallons = getInput() #calls to collect total prices paid printReport(milesObtained, totalPrice, totalGallons) #call to print the full … | |
Re: Try to save your image drawing to a GIF file and then load that file ... [code]import Tkinter from PIL import Image, ImageTk, ImageDraw image_file = "aatest.gif" #create an image image = Image.new('RGBA', (200, 200)) draw = ImageDraw.Draw(image) ## draw some lines for i in range(1,10): draw.line((0, i * 10) … | |
Re: [QUOTE=jbennet;1048507]Not really, i just dont like moaners in general ;)[/QUOTE]Do I detect a moan? | |
Re: Here is a typical example ... [code]# tk_Listbox_select1.py import Tkinter as tk def on_click_listbox(event): # get selected line index index = listbox1.curselection() # get the line's text seltext = listbox1.get(index) # show slected text in label label1.configure(text=seltext) root = tk.Tk() listbox1 = tk.Listbox(root, width=8, height=7) listbox1.pack() mylist = ['green', 'blue', … | |
Re: Just a few corrections are needed, read the comments ... [code]def percount(myFile): # set period count to zero at start periods = 0 # loop through each character in the text string for char in myFile.read(): #print char, periods # testing if char == '.': periods += 1 # when … | |
Re: IDLE does hang up on some of the computer's firewall settings. My suggestion is to drop the old bird and go with something modern like DrPython, SPE, PyScripter, UliPad and so on. | |
If a word or sentence reads the same way forward and backward, then it is a palindrome. A small admonition is in place, whitespaces and punctuation marks can be ignored. Also, all the letters should be in one case, lower or upper, your choice. Ideal for Python to show off … | |
Re: I have totally switched to Mozilla Firefox. I really like the user interface. | |
Re: [QUOTE=Dan08;1269078]hope you dont mind asking this in your thread, but does anyone know if there is a way to do this with wxpython? Thanks[/QUOTE]For realistic transparency on a wxPython canvas see: [url]http://www.daniweb.com/forums/showthread.php?p=1207924#post1207924[/url] | |
Re: God loves stupid people He made so many | |
Early versions of Python used a hybrid of samplesort (a variant of quicksort with large sample size) and binary insertion sort as the built-in sorting algorithm. This proved to be somewhat unstable, and was replaced in version 2.3 with an adaptive mergesort algorithm. I am comparing several rudimentary sorting routines, … | |
The function Delay() allows access to other events during the delay. For instance a certain key could be used to interrupt a lenghty delay. The Win32 API function Sleep() ignores events, maybe it should be called DeepSleep(). | |
Re: Needs to be moved to csharp snippets. ![]() | |
Re: I get 4 for the sizeof(string), hmmm? I 'd say vectorize! | |
Re: The formula has to follow Python syntax. For example ... [code]from math import * # if the formula is y = 2.5sin(3x) - cos(2x) # the user has to input a string like "2.5*sin(3*x) - cos(2*x)" # so Python can evaluate it correctly input_str = "2.5*sin(3*x) - cos(2*x)" # now … | |
Re: Well, if you have to learn from a book like this, that uses horribly outdated modules, you have to know that gasp is a wrapper using pygame. You need to install pygame to make gasp work. This might solve the problem with cairo. Cairo is normally part of the GTK … | |
Re: Under Windows you associate .py files with python.exe. Actually the Python installer should have done this for you. You can also use IDE's like IDLE to run your code from by pressing the F5 key. |
The End.