Python – Pro9ramming https://pro9ramming.com Software craftsman's blog Wed, 15 Apr 2020 17:51:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 Python Windows API calls https://pro9ramming.com/python-windows-api-calls/ Sun, 10 Sep 2017 14:59:00 +0000 http://pro9ramming.com/blog/?p=491 Continue reading Python Windows API calls]]> This link will allow you to install python that has win32api
http://sourceforge.net/projects/pywin32/files/

This is a example that gets the computer name.

import win32api
[code]
print(win32api.GetComputerName());
win32api.MessageBox(0,'hello world','api example');

if you do dir(win32api) you can see a list of api calls you can do. Here is my output.
>>> for x in dir(win32api):
… print(x);

AbortSystemShutdown
Apply
Beep
BeginUpdateResource
ChangeDisplaySettings
ChangeDisplaySettingsEx
ClipCursor
CloseHandle
CopyFile
DebugBreak
DeleteFile
DragFinish
DragQueryFile
DuplicateHandle
EndUpdateResource
EnumDisplayDevices
EnumDisplayMonitors
EnumDisplaySettings
EnumDisplaySettingsEx
EnumResourceLanguages
EnumResourceNames
EnumResourceTypes
ExitWindows
ExitWindowsEx
ExpandEnvironmentStrings
FindCloseChangeNotification
FindExecutable
FindFiles
FindFirstChangeNotification
FindNextChangeNotification
FormatMessage
FormatMessageW
FreeLibrary
GenerateConsoleCtrlEvent
GetAsyncKeyState
GetCommandLine
GetComputerName
GetComputerNameEx
GetComputerObjectName
GetConsoleTitle
GetCurrentProcess
GetCurrentProcessId
GetCurrentThread
GetCurrentThreadId
GetCursorPos
GetDateFormat
GetDiskFreeSpace
GetDiskFreeSpaceEx
GetDllDirectory
GetDomainName
GetEnvironmentVariable
GetFileAttributes
GetFileVersionInfo
GetFocus
GetFullPathName
GetHandleInformation
GetKeyState
GetKeyboardLayout
GetKeyboardLayoutList
GetKeyboardState
GetLastError
GetLastInputInfo
GetLocalTime
GetLogicalDriveStrings
GetLogicalDrives
GetLongPathName
GetLongPathNameW
GetModuleFileName
GetModuleFileNameW
GetModuleHandle
GetMonitorInfo
GetNativeSystemInfo
GetProcAddress
GetProfileSection
GetProfileVal
GetPwrCapabilities
GetShortPathName
GetStdHandle
GetSysColor
GetSystemDefaultLCID
GetSystemDefaultLangID
GetSystemDirectory
GetSystemFileCacheSize
GetSystemInfo
GetSystemMetrics
GetSystemTime
GetTempFileName
GetTempPath
GetThreadLocale
GetTickCount
GetTimeFormat
GetTimeZoneInformation
GetUserDefaultLCID
GetUserDefaultLangID
GetUserName
GetUserNameEx
GetVersion
GetVersionEx
GetVolumeInformation
GetWindowLong
GetWindowsDirectory
GlobalMemoryStatus
GlobalMemoryStatusEx
HIBYTE
HIWORD
InitiateSystemShutdown
LOBYTE
LOWORD
LoadCursor
LoadKeyboardLayout
LoadLibrary
LoadLibraryEx
LoadResource
LoadString
MAKELANGID
MAKELONG
MAKEWORD
MessageBeep
MessageBox
MessageBoxEx
MonitorFromPoint
MonitorFromRect
MonitorFromWindow
MoveFile
MoveFileEx
NameCanonical
NameCanonicalEx
NameDisplay
NameFullyQualifiedDN
NameSamCompatible
NameServicePrincipal
NameUniqueId
NameUnknown
NameUserPrincipal
OpenProcess
OutputDebugString
PostMessage
PostQuitMessage
PostThreadMessage
PyDISPLAY_DEVICEType
REG_NOTIFY_CHANGE_ATTRIBUTES
REG_NOTIFY_CHANGE_LAST_SET
REG_NOTIFY_CHANGE_NAME
REG_NOTIFY_CHANGE_SECURITY
RGB
RegCloseKey
RegConnectRegistry
RegCopyTree
RegCreateKey
RegCreateKeyEx
RegDeleteKey
RegDeleteKeyEx
RegDeleteTree
RegDeleteValue
RegEnumKey
RegEnumKeyEx
RegEnumKeyExW
RegEnumValue
RegFlushKey
RegGetKeySecurity
RegLoadKey
RegNotifyChangeKeyValue
RegOpenCurrentUser
RegOpenKey
RegOpenKeyEx
RegOpenKeyTransacted
RegOverridePredefKey
RegQueryInfoKey
RegQueryInfoKeyW
RegQueryValue
RegQueryValueEx
RegRestoreKey
RegSaveKey
RegSaveKeyEx
RegSetKeySecurity
RegSetValue
RegSetValueEx
RegUnLoadKey
RegisterWindowMessage
STD_ERROR_HANDLE
STD_INPUT_HANDLE
STD_OUTPUT_HANDLE
SearchPath
SendMessage
SetClassLong
SetClassWord
SetConsoleCtrlHandler
SetConsoleTitle
SetCursor
SetCursorPos
SetDllDirectory
SetEnvironmentVariable
SetErrorMode
SetFileAttributes
SetHandleInformation
SetLastError
SetLocalTime
SetStdHandle
SetSysColors
SetSystemFileCacheSize
SetSystemPowerState
SetSystemTime
SetThreadLocale
SetTimeZoneInformation
SetWindowLong
ShellExecute
ShowCursor
Sleep
SleepEx
TerminateProcess
Unicode
UpdateResource
VFT_APP
VFT_DLL
VFT_DRV
VFT_FONT
VFT_STATIC_LIB
VFT_UNKNOWN
VFT_VXD
VOS_DOS
VOS_DOS_WINDOWS16
VOS_DOS_WINDOWS32
VOS_NT
VOS_NT_WINDOWS32
VOS_OS216
VOS_OS216_PM16
VOS_OS232
VOS_OS232_PM32
VOS_UNKNOWN
VOS__PM16
VOS__PM32
VOS__WINDOWS16
VOS__WINDOWS32
VS_FF_DEBUG
VS_FF_INFOINFERRED
VS_FF_PATCHED
VS_FF_PRERELEASE
VS_FF_PRIVATEBUILD
VS_FF_SPECIALBUILD
VkKeyScan
VkKeyScanEx
WinExec
WinHelp
WriteProfileSection
WriteProfileVal
__doc__
__file__
__name__
__package__
error
keybd_event
mouse_event
>>>


If you don’t want to type win32 for the api calls you can do this.

from win32api *;
MessageBox(0,"Example of win32 api messagebox","Example");

There are other modules for win32 api When you install it there there is a huge help file. there are units for mmsystem, win32gui, etc…


All the windows api are a lot easier in python. You don’t have to worry about pointers etc… For example the GetSystemInfo api is very easy to use.

win32api.GetSystemInfo
tuple = GetSystemInfo()

Retrieves information about the current system.

Win32 API References

Search for GetSystemInfo at msdn, google or google groups.

Return Value
The return value is a tuple of 9 values, which corresponds to the Win32 SYSTEM_INFO structure. The element names are:
wProcessorArchitecture
dwPageSize
lpMinimumApplicationAddress
lpMaximumApplicationAddress
dwActiveProcessorMask
dwNumberOfProcessors
dwProcessorType
dwAllocationGranularity
(wProcessorLevel,wProcessorRevision)

from win32api import GetSystemInfo;
info = GetSystemInfo();
nProcessors = info[5];
print('Number of processors: ' + str(nProcessor));
]]>
Python Powerball number generator https://pro9ramming.com/python-powerball-number-generator/ Wed, 16 Aug 2017 14:51:40 +0000 http://pro9ramming.com/blog/?p=489 Continue reading Python Powerball number generator]]> http://openbookproject.net/pybiblio/practice/wilson/powerball.php

Description
To win the Powerball lottery (an extremely unlikely event so don’t waste your time) you have to pick six numbers correctly. The first five numbers are drawn from a drum containing 53 balls and the sixth is drawn from a drum containing 42 balls. The chances of doing this are 1 in 120,526,770. Write a program to generate a set of Powerball numbers by utilizing the choice function in Python’s random module.

Input
Ask the user how many sets of Powerball numbers he or she would like.

Output
The program will print each set of Powerball numbers in numeric order.

Sample session
Official (but fruitless) Powerball number generator

How many sets of numbers? 3

Your numbers: 3 12 14 26 47 Powerball: 2
Your numbers: 1 4 31 34 51 Powerball: 17
Your numbers: 10 12 49 50 53 Powerball: 35

from random import randint
def BubbleSort(l):
    e=0
    for i in range(len(l)-1):
        for j in range(len(l)-1):
            if l[j]>l[j+1]:
                e=l[j+1]
                l[j+1]=l[j]
                l[j]=e
    return l
def MyPrint(L,pb):
        BubbleSort(L)
        print "Your numbers: %d %d %d %d %d Powerball: %d"%(L[0],L[1],L[2],L[3],L[4],pb)

print "Official (but fruitless) Powerball number generator"
No=int(raw_input("How many sets of numbers? "))
for i in range(No):
    numbers=[]
    powerball=randint(1,42)
    i=0
    while (i!=5):
        numbers.append(randint(1,53))
        i+=1
    for i in range(len(numbers)-1):
        for j in range(len(numbers)-1):
            if i==j:
                j+=1
            if numbers[i]==numbers[j] or powerball==numbers[j]:
                numbers[j]=randint(1,53)
                j-=1
    MyPrint(numbers,powerball)

Few notes:
After you choose how many sets of numbers you want, the first ‘while’ loop gives some random numbers to our powerball list. After that, the 2 ‘for’ loops check if we have double numbers in our list. Because after we draw one ball, that one cannot be chosen again and it is out of the game.

Then the process repeats for the rest of the sets.

]]>
Big Mod algorithm and decomposition of factors https://pro9ramming.com/big-mod-algorithm-factors/ Wed, 21 May 2014 19:43:27 +0000 http://pro9ramming.com/blog/?p=38 Continue reading Big Mod algorithm and decomposition of factors]]> This is very interesting number theory. It is called “Big Mod”, and it can be used for different things, but the main reason it exists is that you don’t get overflow while you calculate module.
Mathematical definition: Module of the number that is decomposed to factors equals to module of the product of the module of every factor.
This sounds really difficult to understand, but here is the formula :
bigmod1
So you need to have factors of a number and to find partial module and multiply them all and find module at the end. That’s how you can easily manipulate with big numbers module.
To understand this easily i will give the formula for 3 factors, like here :

bigmod2

That is easier to understand than the formula above.
While creating this program i used an algorithm for decomposition of the factors which you can find here .
Pascal code:

program factors;
uses wincrt;
var
n,i,k,p:longint;
begin
readln(n);
readln(k);
i:=2;
p:=1;
while (n>1) do
begin
   if n mod i = 0 then
     begin
       n:=n div i;
       p:=p*(i mod k);
       i:=1;
     end;
     i:=i+1;
end;
writeln(p mod k);
end.

And in C++:

# include <iostream>
# include <cstdio>

using namespace std;

int main()
{
    int i,n,k,p;
    cin>>n;
    cin>>k;
    i=2;
    p=1;
    while (n > 1)
    {
        if (n % i == 0)
           {
              n=n/i;
              p=p*(i % k);
              i=1;   
           }
        i++;
    }
    cout<<(p % k)<<endl;
    system("pause");
}

And in Python:

i, n, k, p = (0,0,0,0);
n = int(raw_input(""));
k = int(raw_input(""));
i = 2;
p = 1;
while n > 1:
    if (n%i) == 0:
        n=n/i;
        p=p*(i % k);
        i=1;
    i = i + 1;
print(p % k);

 

]]>
Day in week https://pro9ramming.com/day-in-week/ Mon, 31 Mar 2014 11:43:27 +0000 http://pro9ramming.com/blog/?p=103

program day_in_week;
uses wincrt;
var
day,month,year:integer;
s:string;
function numcheck(s:string):boolean;
var
  x:integer;
  begin
   numcheck:=true;
    for x:=1 to length(s) do
     if (ord(s[x])<48) or (ord(s[x])>57) then
      if s[x]<>'' then
       numcheck:=false;
  end;
function strtoint(s:string):integer;
var
   check:integer;
   i:integer;
  begin
   if numcheck(s) then
    val(s,i,check);
     strtoint := i;
end;
function week_day(n:integer):string;
var
   k:array[0..6] of string;
begin
  k[0]:='Sunday';
  k[1]:='Monday';
  k[2]:='Thursday';
  k[3]:='Wednesday';
  k[4]:='Tuesday';
  k[5]:='Friday';
  k[6]:='Saturday';
  week_day:=k[n];
end;
function week(d,m,y:integer):integer;
var
   g,v,main:integer;
begin
   g:=y mod 100;
   v:=y div 100;
   m:=m-2;
   if m=-1 then
     begin
       m:=11;
       g:=g-1;
     end;
   if m=0 then
     begin
       m:=12;
       g:=g-1;
     end;
  main:=(d+trunc(2.6*m-0.2)-2*v+g+trunc(g/4)+trunc(v/4)) mod 7;
  week:=main;
end;
begin
writeln('Enter date ! (dd.mm.yyyy)');
readln(s);
day:=strtoint(copy(s,1,pos('.',s)-1));
s:=copy(s,pos('.',s)+1,length(s));
month:=strtoint(copy(s,1,pos('.',s)-1));
s:=copy(s,pos('.',s)+1,length(s));
year:=strtoint(s);
writeln(week_day(week(day,month,year)));
end.

Formula for this is:

D=( d + [2.6*m + 0.2] - 2*v + g + [g/4] + [v/4] ) (mod 7)

Explanation:

D - Day in week that you want to get (0=Sunday, 1=Monday . . .6=Saturday)
m - month (1=March, 2=April . . . 10=December,11=January,12=February) As you can see January and February are like months of year before !
g - years (for 1995 year is 95, except for January and February where year is 94 so g=94) (mod 7) - Rest after division with 7 ! (you know mod in Pascal)
d - Day in month (1..31)
[x] - the biggest integer number that is not bigger than x (trunc() function in Pascal !)
v - number of centuries (for 1995 number of centuries is 19 so v=19)

 

]]>
Sum of prime numbers https://pro9ramming.com/sum-of-prime-numbers/ Thu, 30 Jan 2014 16:43:27 +0000 http://pro9ramming.com/blog/?p=14 More about prime numbers can be found here.

If you want to find sum of first n prime numbers (for example, sum of first 5 prime numbers is 28), than you can use next algorithm:

program sum_of_prime_numbers;
uses wincrt;
var
i,n,k:integer;
s:longint;
function prime(a:integer):boolean;
var
i:integer;
b:boolean;
begin
if a=2 then
prime:=true
else
if a mod 2 = 0 then
prime:=false
else
begin
b:=true;
for i:=2 to trunc(sqrt(a))+1 do
if (a mod i = 0) and (b=true) then
b:=false;
if b=true then
prime:=true
else
prime:=false;
end;
end;
begin
readln(n);
s:=0;
k:=0;
for i:=2 to n do
if prime(i) then
begin
s:=s+i;
k:=k+1;
end;
writeln('Sum of first ',k,' prime numbers is : ',s);
end.

Sum of first 5000 prime numbers in Python example (answer is 1548136):

#returns true if number is prime else false
def is_prime(num):
tempnum = 0;
if num == 2:
return True;
if num < 2:
return False;
for x in range(3,num,2):
tempnum = num % x;
if tempnum == 0:
return False;
return True;

#sum starts with the value of 2 because 2 is a prime number
sum = 2;

#skip al even numbers because non are prime except 2
for num in range(1, 5001, 2):
#add number to sum if the number is prime
if is_prime(num):
sum = sum + num;
print('Prime sum: ' + str(sum));

 

]]>
String character sorting problem https://pro9ramming.com/string-character-sorting-problem/ Tue, 21 Jan 2014 18:43:27 +0000 http://pro9ramming.com/blog/?p=86 Continue reading String character sorting problem]]> Task is to sort characters in one string in alphabetical order.
Input
One string variable form standard input.
Output
One string in one line which represents solution.
Sample Input
abcbca
Sample Output
aabbcc
Sample Input
pro9ramming
Sample Output
9agimmnoprr
Solution
Bubble sort algorithm to sort characters in string depending on ord() function return of each character. ord() function returns ASCII value of character.
So here is the code in TPW:

program string_problem;
uses wincrt;
var
s:string;
k:char;
i,j:integer;
begin
  readln(s);
for i:=1 to length(s) do
   for j:=i+1 to length(s) do
     if ord(s[i])>ord(s[j]) then
       begin
         k:=s[i];
         s[i]:=s[j];
         s[j]:=k;
       end;
writeln(s);
end.

And solution using library in Python:

name = raw_input("Enter in a string: ");
nameList = list(name);
nameList.sort();
name = ''.join(nameList);
print(name);

 

]]>