Monday, July 31, 2017
Sunday, July 23, 2017
Friday, March 24, 2017
W3 SCHOOL OFFLINE WEBSITE
Download The w3 offline website for free .....
<h1 color="red" align="center"><a href=" https://drive.google.com/file/d/0B0Yilec_Zy5HNUl4SXdzVG9kMEU/view">DOWNLOAD</a></h1>
After downloading extract the zip file and you can enjoy offline website...
NOTE : you can run both on your PC or on your phone...
IF YOU RUN THIS ON YOUR PHONE
THE RUN THE DEFAULT.htm with YOUR HTML VIEWER
<h1 align="center"> SCREEN SHOT'S </h1>
$-> IF THE LINK IS NOT WORK THEN INFORM ME BY COMMENT OR E-Mail
Random Circle Programme In C++
#include"stdio.h"
#include"graphics.h"
#include"dos.h"
#include"stdlib.h"
void main()
{
int gd = DETECT , gm;
initgraph(&gd , &gm ,"c:\\tc\\bgi"); while(!kbhit())
{
setcolor(rand() % 16);
circle(rand() % 600 , rand() % 400 , rand() % 50); delay(10);
}
closegraph();
}
<h1 align="center"> NOTE : USE <> INSTEAD OF " " OTHERWISE THIS WILL NOT WORK
</h1>
<h2>send me your questions and Querries On My Email</h2>
E-mail : spy91919@gmail.com
<h3>NOTE : USE TURBO BORLAND C/C++ Compiler</h3>
Turbo C++ Compiler for Android
Here you will get step by step guide to download and install Turbo C++ for Android platform.
If you are from India and have started learning C/C++ programming from your school days then you have definitely used Turbo C++ compiler. Still many schools, colleges and institutions in India prefer Turbo C++ for teaching students (don’t know about other countries).
I am writing this article. In windows we use DosBox Emulator for running Turbo C++ for Android, in the same way we need an emulator for android platform which is known as AnDosBox. So without wasting much time lets take a look how we can use Turbo C++ for android platform.
Turbo C++ for Android –Steps to Download and Install
1. First of all download Turbo C++ for Android from link: http://sh.st/r5mBt
2. It is compressed so you need to extract it. This can be done by any compression tool like Easy Unrar. You can download it from play store for free.
3. Now after extracting you will get a folder TC and an apk file AnDosBox.
4. Install AnDosBox and move TC folder in your sd card, remember that TC folder must be in sd card not in any other subfolder.
5. Now open AnDosBox that you have already installed. It will look same as like DoxBox that is used in windows.
6. Enter below lines or commands and press enter after each line. You can get the keyboard by pressing the option button situated at left side of your device.
____________
cd tc
cd bin
tc
_____________
<h1 align="center"><a href="http://sh.st/r5mBt">DOWNLOAD </a></h1>
AND ENJOY.........
School Management Programme In C/C++
#include <iostream>
#include <fstream>
#include < string >
#include <conio.h>
#include <windows.h>
using namespace std ;
//Structure defining
//For students
struct student
{
string fname ;//for student first name
string lname ;//for student last name
string Registration ;//for Registration No number
string classes ;//for class info
}studentData ;//Variable of student type
//For teachers
struct teacher
{
string fst_name ; //first name of teacher
string lst_name ; //last nameof teacher
string qualification ;//Qualification of teacher
string exp ;//Experiance of the person
string pay ;//Pay of the Teacher
string subj ;//subject whos he/she teach
string lec ;//Lecture per Week
string addrs ;//Adders of teacher home
string cel_no ;//Phone number
string blod_grp ; //Bool Group
string serves ; //Number of serves in School
}tech[ 50 ];//Variable of teacher type
/////////////////////////////////////////////////// //Main function
void main() {
int i =0 ,j ;//for processing usage
char choice ; //for getting choice
string find ; //for sorting
string srch ;
while( 1) //outer loop
{ system ( "cls" );//Clear screen
//Level 1-Display process
cout<< "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" ;
cout<< "\n\n\t\t\tSCHOOL MANAGEMENT PROGRAM\n\n" ;
cout<< "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" ;
cout<< "\n\n\t\t\tMAIN SCREEN\n\n" ;
cout<< "Enter your choice: "
<< endl;
cout<< "1.Students information" <<endl;
cout<< "2.Teacher information" <<endl;
cout<< "3.Exit program" <<
endl ;
cin >>choice ;
system ("cls" ); //Clear screen
switch (choice )//First switch
{ case '1' : //Student
{ while( 1) //inner loop-1
{ system ("cls" ); //Clear screen //Level-2 display
cout<< "\t\t\tSTUDENTS INFORMATION AND BIO DATA SECTION\n\n\n" ;
cout<< "Enter your choice: "
<< endl;
cout<< "1.Create new entry\n"
;
cout<< "2.Find and display entry\n" ;
cout<< "3.Jump to main\n" ;
cin >> choice ;
switch ( choice) //Second switch
{
case '1' ://Insert data
{ ofstream f1 ( "student.txt"
,ios ::app );
for ( i= 0; choice!= 'n' ; i++) {
if (( choice== 'y' )||(choice == 'Y' )||(choice =='1' )) {
cout<< "Enter First name: " ;
cin >>studentData .fname;
cout<< "Enter Last name: " ;
cin >>studentData .lname;
cout<< "Enter Registration number: " ;
cin >>studentData .
Registration ;
cout<< "Enter class: " ;
cin >>studentData .classes ; f1 << studentData . fname<< endl
<< studentData .lname << endl<<
studentData . Registration<<
endl <<studentData .classes <<
endl ;
cout<< "Do you want to enterdata: " ;
cout<< "Press Y for Continueand N to Finish: " ;
cin >>choice ; } } f1 .close (); }
continue;//control back to inner loop -1
case '2' ://Display data
{ ifstream f2 ( "student.txt"
);
cout<< "Enter First name to be displayed: " ;
cin >> find;
cout<< endl;
int notFound = 0 ;
for ( j= 0;( j< i)||(! f2. eof ());
j++) {
getline ( f2, studentData .fname
);
if (studentData . fname== find) {
notFound = 1 ;
cout<< "First Name: " <<
studentData . fname<< endl;
cout<< "Last Name: " <<
studentData . lname<< endl;
getline (f2 ,studentData .
Registration);
cout<< "Registration No number: " << studentData .
Registration <<endl;
getline (f2 ,studentData .
classes );
cout<< "Class: " <<
studentData . classes << endl<<
endl ; }
}
if (notFound == 0 ){
cout<< "No Record Found" <<
endl ; }
f2 .close ();
cout<< "Press any key two times to proceed" ;
getch(); //To hold data on screen
getch(); //To hold data on screen
}
continue;//control back to inner loop -1
case '3' ://Jump to main
{
break; //inner switch breaking
} }
break; //inner loop-1 breaking
}
continue;//Control pass to 1st loop
}
case '2' ://Teachers biodata
{ while( 1) //inner loop-2
{ system ("cls" ); //Clear screen //Level-2 Display process
cout<< "\t\t\tTEACHERS INFORMATION AND BIODATA SECTION\n\n\n" ;
cout<< "Enter your choice: "
<< endl;
cout<< "1.Create new entry\n"
;
cout<< "2.Find and display\n"
;
cout<< "3.Jump to main\n" ;
cin >> choice ;
switch ( choice) //Third switch
{
case '1' ://Insert data
{ ofstream t1 ( "teacher.txt" ,
ios :: app );
for ( i=0 ;choice != 'n' && choice
!= 'N' ;i ++) { if (( choice == 'y' )||(choice ==
'Y' )||(choice == '1' )) {
cout << "Enter First name: "
;
cin >> tech[i ].fst_name ;
cout << "Enter Last name:: "
;
cin >> tech[i ].lst_name ;
cout << "Enter qualification: " ;
cin >> tech[i ].qualification
;
cout << "Enter experiance(year): " ;
cin >> tech[i ].exp ;
cout << "Enter number of year in this School: " ;
cin >> tech[i ].serves ;
cout << "Enter Subject whos teach: " ;
cin >> tech[i ].subj;
cout << "Enter Lecture(per Week): " ;
cin >> tech[i ].lec ;
cout << "Enter pay: " ;
cin >> tech[i ].pay ;
cout << "Enter Phone Number:" ;
cin >> tech[i ].cel_no ;
cout << "Enter Blood Group: ";
cin >> tech[i ].blod_grp ; t1 <<tech[ i]. fst_name <<endl
<< tech[i ].lst_name << endl << tech[i ]. qualification<<
endl<< tech[i ].exp <<endl
<< tech[i ]. serves<< endl<<
tech [i]. subj<< endl<< tech[i ].
lec
<< endl<< tech[i ].pay <<endl
<< tech[i ].cel_no << endl<<tech
[i ]. blod_grp << endl;
cout << "Do you want to enter data: " ;
cin >> choice ; } //if
}//for loop //for finding through name
system ("cls" );
t1 .close (); }//case 1
continue;//Control pass to inner loop-2
case '2' ://Display data
{ ifstream t2 ( "teacher.txt" );
cout<< "Enter name to be displayed: " ;
cin >> find;
cout<< endl;
int notFound = 0 ;
for ( j= 0;(( j <i )||(!t2 .eof
())); j++) { getline (t2 ,tech[ j]. fst_name
); if ( tech[j]. fst_name == find) {
notFound = 1;
cout << "First name: " << tech
[j ]. fst_name << endl;
getline (t2 , tech[j]. lst_name );
cout << "Last name: " <<tech[
j]. lst_name << endl;
getline (t2 , tech[j].
qualification );
cout << "Qualification: " <<
tech [j]. qualification <<endl;
getline (t2 , tech[j]. exp );
cout << "Experience: " << tech
[j ]. exp << endl;
getline (t2 , tech[j]. serves
);
cout << " number of year in this School: " << tech[ j].
serves << endl;
getline (t2 , tech[j]. subj);
cout << "Subject whos teach:" << tech[j]. subj<< endl;
getline (t2 , tech[j]. lec );
cout << "Enter Lecture(per Week): " << tech[j ]. lec << endl;
getline (t2 , tech[j]. pay );
cout << "pay: " << tech[ j]. pay
<< endl;
getline (t2 , tech[j]. addrs );
cout << "Address: " << tech[ j].addrs << endl;
getline (t2 , tech[j]. cel_no
);
cout << "Phone Number: " <<
tech [j]. cel_no <<endl;
getline (t2 , tech[j]. blod_grp );
cout << "Bool Group: " << tech
[j ]. blod_grp << endl; } //if }//for loop
t2 .close ();
if (notFound == 0 ){
cout<< "No Record Found" <<
endl ; }
cout<< "Press any key two times to proceed" ;
getch(); //To hold data on screen
getch(); //To hold data on screen
}//case 2
continue;//Control pass to inner loop-2
case '3' ://Jump to main
{
break; //inner switch
}//case 3
}//inner switch
break; //inner while
}//inner loop
continue;//control pass to 1st loop
}//outer case 2
case '3' : {
break; //outer case 3
}//outer case 3
} break; //outer loop
}
}
<h3>NOTE : USE TURBO BORLAND C/C++ Compiler</h3>
<h3>Share This Post To More and More People To Help Others</h3>
What is Wi-Fi And How Its Work
<h1 align="center">Wi-Fi </h1>
WiFi is a technology that uses radio waves to provide network
connectivity. A WiFi connection is established using a wireless adapter to create hotspots - areas in the vicinity of a wireless router that are connected to the network and allow users to access internet services. Once configured, WiFi provides wireless connectivity to your devices by emitting frequencies between 2.4GHz - 5GHz, based on the amount of data on the network.
This article will introduce you to the basics of WiFi so that you may have a better understanding of the worldwide phenomenon that provides you with your internet access.
1. What Does WiFi Stand For?
2. An Introduction to WiFi
3. How WiFi Works
4. WiFi Frequencies
5. What are Hotspots?
6. Connect To WiFi Via Modem
7. Related: What is wifi
What Does WiFi Stand For?
You may be surprised to hear that many people don't actually know that WiFi is an abbreviated term. Even those who do don't always know what WiFi stands for. There are a number of theories about what the term means, but the most widely accepted definition for the term in the tech community is Wireless Fidelity.
An Introduction to WiFi
Wireless technology has widely spread lately and you can get connected almost anywhere; at home, at work, in libraries, schools, airports, hotels and even in some restaurants.
Wireless networking is known as WiFi or 802.11 networking as it covers the IEEE 802.11 technologies. The major advantage of WiFi is that it is compatible with almost every operating system, game device, and advanced printer.
How WiFi Works
Like mobile phones, a WiFi network makes use of radio waves to transmit information across a network. The computer should include a wireless adapter that will translate data sent into a radio signal. This same signal will be transmitted, via an antenna, to a decoder known as the router . Once decoded, the data will be sent to the Internet through a wired Ethernet connection.
As the wireless network works as a two-way traffic, the data received from the internet will also pass through the router to be coded into a radio signal that will be received by the computer's wireless adapter.
WiFi Frequencies
A wireless network will transmit at a frequency level of 2.4 GHz or 5GHz to adapt to the amount of data that is being sent by the user. The 802.11 networking standards will somewhat vary depending mostly on the user's needs.
The 802.11a will transmit data at a frequency level of 5GHz. The Orthogonal Frequency-Division Multiplexing (OFDM) used enhances reception by dividing the radio signals into smaller signals before reaching the router. You can transmit a maximum of 54 megabits of data per second.
The 802.11b will transmit data at a frequency level of 2.4GHz, which is a relatively slow speed. You can transmit a maximum of 11 megabits of data per second.
The 802.11g will transmit data at 2.4GHz but can transmit a maximum of 54 megabits of data per second as it also uses an OFDM coding.
The more advanced 802.11n can transmit a maximum of 140 megabits of data per second and uses a frequency level of 5GHz.
What are Hotspots?
The term hotspot is used to define an area where WiFi access is available. It can either be through a closed wireless network at home or in public places such as restaurants or airports.
In order to access hotspots, your computer should include a wireless adapter. If you are using an advanced laptop model, it will probably include a built-in wireless transmitter already. If it doesn't, you can purchase a wireless adapter that will plug into the PCI slot or USB port. Once installed, your system should automatically detect the WiFi hotspots and request connection. If not, you should use a software to handle this task for you.
Atomic Hard Drive
A view of a single atom of Holmium, a rare earth element used as a magnet to store one bit of data. IBM scientists used its scanning tunneling microscope to demonstrate technology that could someday store all 35 million songs on iTunes library on the area of a credit card. Photo: Stan Olswekski for IBM
There’s only so much data that can be stored on silicon-based integrated circuits (as predicted by the so-called “Moore’s law”). That is why, computer scientists have — especially over the past decade — been experimenting with viable alternatives such as
synthetic-DNA based systems and
quantum computers.
Now, in another huge step toward making these storage media smaller, researchers at IBM announced Wednesday that they had managed to store a single bit of data — a 1 or a 0 — on one atom. Compare this to the hard drives currently in use, which require up to 100,000 atoms to store an equivalent amount of data.
Read : World’s First Artificial Neuron: IBM’s Breakthrough Uses Phase-Change Material
“The ability to read and write one bit on one atom creates new possibilities for developing significantly smaller and denser storage devices, that could someday, for example, enable storing the entire iTunes library of 35 million songs on a device the size of a credit card,” IBM said in a press release.
In order to achieve this breakthrough, described in a study published in the latest edition of the journal Nature, the researchers first had to create the world’s smallest magnet — one that consists of a single atom of the rare-earth mineral Holmium. This was done using a scanning tunneling microscope, which uses liquid helium to cool the atoms to such low temperatures that the atoms' magnetic orientations remain stable long enough to be written and read reliably.
Given that all magnets have two poles, their orientation can be used to determine whether an atom is a 0 or a 1. Moreover, this orientation can even be flipped around using an electric current to represent a different value.
“Magnetic bits lie at the heart of hard-disk drives, tape and next-generation magnetic memory,” Christopher Lutz, lead nanoscience researcher at IBM Research in Almaden, San Jose, California, said in the statement. “We conducted this research to understand what happens when you shrink technology down to the most fundamental extreme — the atomic scale.”
Read : IBM Brings Quantum Computing To Everyone With Cloud Service
Although atomic-scale storage devices are still decades away from being commercially viable, the research demonstrates that reading and writing information on an atom is theoretically possible — the first step toward the creation of storage devices not circumscribed by Moore’s law.
“Future applications of nanostructures built with control over the position of every atom could allow people and businesses to store 1,000 times more information in the same space, someday making data centers, computers and personal devices radically smaller and more powerful,” IBM said in the statement.
Thursday, March 16, 2017
Friday, March 3, 2017
soccerway.com App in Python
This Find All Match Detail Related To soccerway.com....…………………
1. # This spider extracts the info (teams, date-time, score) related to soccer matches from soccerway.com,
2.
3. """ soccerway.com spider to scrape soccer matches info """
4.
5. from datetime import datetime
6.
7. from scrapy.http import Request
8. from scrapy.selector import HtmlXPathSelector
9. from scrapy.contrib.spiders import CrawlSpider
10. from scrapy.item import Item, Field
11. from scrapy.contrib.loader import XPathItemLoader
12. from scrapy.contrib.loader.processor import TakeFirst, MapCompose
13.
14.
15. class Match( Item):
16. """ Item to load with scraped data """
17. cup = Field ()
18. team1 = Field ()
19. team2 = Field ()
20. goals1 = Field ()
21. goals2 = Field ()
22. date = Field ()
23. time = Field ()
24.
25.
26. class MatchLoader ( XPathItemLoader ):
27. """ Loader to make the exctraction easier """
28. default_item_class = Match
29. default_output_processor = TakeFirst ()
30. team1_in = MapCompose (lambda x:x.strip ())
31. team2_in = MapCompose (lambda x:x.strip ())
32.
33.
34. class SoccerwaySpider ( CrawlSpider ):
35. """ The spider, you can define the cups you want to exctract """
36. name = 'soccerway'
37. allowed_domains = [ 'soccerway.com' ]
38. cups = [
39. ( 'brazil-2010' ,
40. 'national/brazil/serie-a/2010/regular-season/matches/' ),
41. ]
42.
43. def start_requests (self):
44. for cup, url in self.cups:
45. yield Request ( 'http://www.soccerway.com/%s' % url,
46. self.parse_matches, meta= {'cup' : cup })
47.
48. def parse_matches (self, response ):
49. """ Parse the matches in a fixture listing """
50. cup = response.request.meta ['cup' ]
51.
52. xs, dt, dat = HtmlXPathSelector ( response), None, None
53.
54. for tr in xs. select ( '//table[starts-with(@class,"matches")]'
55. '/tbody/tr[not(contains(@class,"aggr"))]' ):
56. mi = MatchLoader ( selector=tr, response=response )
57. mi.add_value ( 'cup' , cup )
58. mi.add_xpath ( 'team1' , 'td[3]/a/text()' )
59. mi.add_xpath ( 'team2' , 'td[5]/a/text()' )
60.
61. # Match status info
62. sct = [x.strip () for x in tr. select ('td[4]//text()' ).extract () \
63. if x.strip ()]
64. sct = sct [1 ] if len (sct ) > 1 else sct [ 0]
65.
66. # Extract timestamp info
67. day = tr. select ('td[1]/span/text()' ) .extract ()
68. if day:
69. dat = datetime.strptime('%s %s' % ( day [0 ], tr. select (
70. 'td[2]/span/text()' ).extract ()[ 0]) , '%a %d/%m/%y' )
71. if dat:
72. mi.add_value ( 'date' , dat.strftime ('%Y-%m-%d' ))
73.
74. # If not postponed, take the time
75. if sct not in ('PSTP' , '-' ):
76. dt = datetime.fromtimestamp (float (
77. tr. select ( 'td[1]/span/@data-value' ) .extract ()[ 0]))
78. else:
79. dt = None
80. if dt:
81. mi.replace_value ( 'date' , dt.strftime ('%Y-%m-%d' ))
82. mi.add_value ( 'time' , dt.strftime ('%H:%M' ))
83.
84. # If played, scrape the result
85. if '-' in sct:
86. goals = [s.strip () for s in sct.split ( '-' )] # 1) strip
87. goals = [int ( s) for s in goals if s ] # 2) convert to int
88. if len (goals) == 2 :
89. mi.add_value ( 'goals1' , str ( goals[ 0]))
90. mi.add_value ( 'goals2' , str ( goals[ 1]))
91.
92. yield mi.load_item ()
93.
94. SPIDER = SoccerwaySpider ()
95.
96. # Snippet imported from snippets.scrapy.org (which no longer works)
97. # author: vivek kumar
98. # date : Aug 10, 2017
Display the download percentage of a file In Python
def report (count, blockSize, totalSize ):
percent = int (count*blockSize* 100 /totalSize )
sys .stdout.write ("\r%d%%" % percent + ' complete' )
sys.stdout.flush ()
sys .stdout.write ( '\rFetching ' + name + '...\n' )
urllib .urlretrieve (getFile, saveFile, reporthook=report )
sys .stdout.write ( "\rDownload complete, saved as %s" % (fileName) + '\n\n' )
sys .stdout.flush ()
Share This To Help More Peoples Like Us........……………………………………
How To Start A Process In C#
Use Below Code
System.Diagnostics.Process.St art("explorer.exe",@"c:\teste ");
____________________________________
Top 10 best applications written in C/C++
I have compiled a list of famous applications and software packages written in C or C++ programming languages. I have included both C and C++ programming languages due to the fact that most of the programs are partially or completely written in C or C++. Apart from these applications there some operating systems written in C++ programming language. These include Windows 95, 98, 2000, XP, Apple OS X, Symbian OS and BeOS.
Adobe Systems
All major applications of adobe systems are developed in C++ programming language. These applications include Photoshop & ImageReady, Illustrator and Adobe Premier.
Some of the Google applications are also written in C++, including Google file system and Google Chromium.
Mozilla
Internet browser Firefox and email client Thunderbird are written in C++ programming language and they are also open source projects.
MySQL
MySQL is the world’s most popular open source database software, with over 100 million copies of its software downloaded or distributed throughout its history. Many of the world’s largest and fastest-growing organizations use MySQL to save time and money powering their high-volume Web sites, critical business systems, and packaged software — including industry leaders such as Yahoo!, Alcatel-Lucent, Google, Nokia, YouTube, Wikipedia, and Booking.com.
Alias System
– Autodesk Maya
Maya 3D software was originally developed by Alias System Corporation and was later carried over by Autodesk. Maya 3D software, now a days is widely used in computers, video games, television. It is a powerful, integrated 3D modelling, animation, visual effects, and rendering solution.
Winamp Media Player
Winamp is the ultimate media player, allows you to manage audio and video files, rip and burn CDs, enjoy free music, access and share your music and videos remotely, and sync your music to your iPod , Creative, and Microsoft Plays for Sure devices . Winamp features album art support, streams audio and video content, and provides access to thousands of internet radio stations and podcasts.
12D Solutions
12D Solutions Pty Ltd is an Australian software developer specialising in civil engineering and surveying applications. Computer Aided Design system for surveying, civil engineering, and more. 12D Solutions clients include civil and water engineering consultants, environmental consultants, surveyors, local, state and national government departments and authorities, research institutes, construction companies and mining consultants.
Bloomberg
Providing real-time financial information to investors.
callas software develops pdf creation, optmisation, updation and pdf form creation tools and plugins.
Image Systems
These are the world leading motion analysys programs and film scanner systems.
Operating systems written in C++ programming language.
Apple – OS X
Few parts of apple OS X are written in C++ programming language. Also few application for iPod are written in C++.
Microsoft
Literally most of the software are developed using various flavors of Visual C++ or simply C++. Most of the big applications like Windows 95, 98, Me, 200 and XP are also written in C++. Also Microsoft Office, Internet Explorer and Visual Studio are written in Visual C++.
Symbian OS
Symbian OS is also developed using C++. This is one of the most widespread OS’s for cellular phones.
Save File Dialog Tutorial In C#
Save File Dialog Tutorial
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter wText =new StreamWriter(myStream);
Thanks For Visiting
If You Find This Topic Useful Then Share It To Help Other People
PHP - Code to find the Duration of a Video file using FFMPEG (WAMP5)
PHP - Code to find the Duration of a Video file using FFMPEG (WAMP5)
function getVideoLength
( $file_path)
{
extension_loaded ('ffmpeg' );
// F: Mv 1.wmv video file path.
$ffmpegInstance = new ffmpeg_movie ($file_path );
return $ffmpegInstance>getDuration();
}
Area Of Rectangle In JavaScript
Name: Area of a Rectangle in JavaScript '
Description:A program in JavaScript that will ask input value from If you have some questions please send me an email : spy91919@gmail.com' By: Vivek Kumar
____________________________________
<html>
<head>
<title>Area of Rectangle</title>
</head>
<style>
h3 { font-family:arial; };
</style>
<body>
<script>
var length = parseInt(prompt("Enter length of Rectangle : ")
var width = parseInt(prompt("Enter width of Rectangle : "));
var solving_area = (length * width);
document.write("<br>");
document.write("<h3> Area of Rectangle</h3>");
document.write("<font face='arial' size='3'>")
document.write(" The Length of Rectangle is " + length + ".
</font>
<br>
document.write("<font face='arial' size='3'>")
document.write(" The Width of Rectangle is " + width + ".
</font>
<br>
document.write("<font face='arial' size='3'>")
document.write(" The Area of Rectangle is " + solving_area + ".</fon
document.write("<h3> End of Program </h3>");
</script>
</body>
</html>
____________________________________
Play Sound In Python
Hi friends this time i gave you a source code that play sound in python.........
1. # Autthors: Vivek Kumar.
2. # Due Wednesday October 12th
3. import sound
4. import time
5.
6. def rem_vocals ( snd ):
7. #Return a copy of sound with vocals removed
8.
9. new_snd = sound. copy(snd )
10. for sample in new_snd:
11. left = sound.get_left (sample )
12. right = sound.get_right (sample )
13. delete_vocals = ( left - right ) /2.0
14. sound.set_left (sample, int ( delete_vocals ))
15. sound.set_right (sample, int (delete_vocals ))
16. return new_snd
17. def fade_in ( snd, fade_length ):
18. #Return a copy of sound with the beginning faded. Number of samples fa
19.
20. '''Return original sound snd with selected number of samples faded in
21. new_snd2 = sound. copy( snd )
22. samps_to_fade = fade_length - 1
23. #required due to samples starting at 0, not 1
24. index = 0
25. for samp in new_snd2:
26. index = sound.get_index (samp)
27. if index <= samps_to_fade:
28. fade_factor = 1.0 *index/fade_length
29. #Tracks number of samples done, is also used as the fade factor
30. left2 = (sound.get_left (samp)) *fade_factor
31. right2 = ( sound.get_right ( samp)) *fade_factor
32. sound.set_left (samp, int (left2 ))
33. sound.set_right (samp, int (right2 ))
34. return new_snd2
35. def fade_out (snd,fade_length ):
36. #Return a copy of sound with the end faded. Number of samples faded is
37.
38. '''Return original sound snd with selected number of samples faded out
39. new_snd=sound. copy( snd )
40. fade_point= len (snd )-fade_length- 1
41. #where to start fading
42. samp_todo = fade_length
43. #tracks the number of untouched samples
44. fade_factor= 1.0
45. samp_index=0
46. for samp in new_snd:
47. samp_index=sound.get_index ( samp)
48. if samp_index>=fade_point:
49. # if we have reached the point to begin fading,then below
50. if samp_index == len (snd )-1 :
51. fade_factor = 0
52. #if at last sample, fade factor is set to zero
53. fade_factor= (( samp_todo* 1.0 )/fade_length )
54. left = int ((sound.get_left (samp)) *fade_factor )
55. right = int (( sound.get_right (samp)) *fade_factor )
56. sound.set_left (samp, int (left))
57. sound.set_right (samp, int (right ))
58. samp_todo-= 1
59.
60. #Tracks number of samples done,starts at one and ends at zero
61. return new_snd
62. def fade (snd, fade_length ) :
63. #Returns a copy of sound with the beginning and ending faded.Number of
64.
65. new_snd=sound. copy( snd )
66. new_snd=fade_in (new_snd,fade_length )
67. new_snd=fade_out (new_snd,fade_length )
68. return new_snd
69. '''Return original sound snd with selected number of samples
70. faded in and out via new_snd'''
71. #new_snd = sound.copy(snd)
72. #samps_to_fade_in = fade_length - 1
73. #samp_todo = fade_length
74. ##tracks the number of untouched samples
75. #fade_point_fade_out= len(snd)-fade_length
76. #index = 0
77. #fade_factor = 1.0
78. #for samp in new_snd:
79. #samp_index=sound.get_index(samp)
80. #if samp_index <= samps_to_fade_in:
81. #fade_factor = 1.0 *samp_index/fade_length
82. #left2 = (sound.get_left(samp))*fade_factor
83. #right2 = (sound.get_right(samp))*fade_factor
84. #sound.set_left(samp, int(left2))
85. #sound.set_right(samp,int(right2))
86. #if samp_index>=fade_point_fade_out :
87. #if samp_index == len(snd)-1:
88. #fade_factor = 0
89. #left = int((sound.get_left(samp))*fade_factor)
90. #right = int((sound.get_right(samp))*fade_factor)
91. #sound.set_left(samp, int(left))
92. #sound.set_right(samp,int(right))
93. #samp_todo-=1
94. #fade_factor= ((samp_todo*1.0)/fade_length)
95. #return new_snd
96.
97. def left_to_right ( snd, pan_length ):
98. #Returns a copy of sound with panning applied to it. Left starts at 0,
99. '''Return original sound snd with selected samples panned to the right
00. and others to the left via new_snd'''
01. new_snd= sound. copy(snd )
02. samps_to_pan = pan_length - 1
03. index = 0
04. fade_factor_left = 0.0
05. fade_factor_right= 0.0
06. for samp in new_snd :
07. if index <= samps_to_pan :
08. left = sound.get_left (samp)
09. right = sound.get_right (samp)
10. avg= ( left+right) /2.0
11. fade_factor_left = (( index* 1.0 )/samps_to_pan )
12. fade_factor_right= 1-fade_factor_left
13. left = int (avg*fade_factor_left )
14. right = int (avg*fade_factor_right )
15. sound.set_values ( samp,left,right )
16. index+= 1
17. return new_snd
18.
19. if __name__ == "__main__" :
20. snd = sound.load_sound ( "love.wav" )
21. #sound.play(snd)
22. #sound.play(rem_vocals(snd))
23. #sound.play(fade_in(snd, 50000))
24. #sound.play(fade_out(snd, 70000))
25. #sound.play(left_to_right(snd, 500000))
26. sound.play (fade( snd, 50000 ))
if you find this title helpful then share it on fb or google+ for helping more people......Thank you
How To Change Text Color of C/C++ Console Application
Color Codes:
0 = Black
1 = Blue
2 = Green
3 = Aqua
4 = Red
5 = Purple
6 = Yellow
7 = White
8 = Gray
9 = Light Blue
A = Light Green
B = Light Aqua
C = Light Red
D = Light Purple
E = Light Yellow
F = Bright White
Example Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("COLOR FC"); printf("Welcome to the color changing application!\n"); printf("Press any key to change the background color!\n");
getch();
system("COLOR 6C");
printf("Now the background color is Yellow and Text Color is light Red\n");
printf("Press any key to exit..."); getch();
return 0;
}
Thanks For Visiting..........
Typing Tutor Source Code in C++
//this is typing tutor app made by me vivek ....
/*
TYPING TUTOR
*/
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<dos.h>
#include<time.h>
#include<fstream.h>
#include<graphics.h>
#include<process.h>
void basics();
void letters();
void sentence();
void main()
{
clrscr();
int opt;
menu:
clrscr();
cout<<"\n\n\t\t\t =====TYPING TUTOR =====";
cout<<"\n\n\n\t\t ::MAIN MENU::";
cout<<"\n\n\t\t1.Learn basics";
cout<<"\n\n\t\t2.Type the letters";
cout<<"\n\n\t\t3.Type the sentence";
cout<<"\n\n\t\t0.Exit";
cout<<"\n\n\n\t\tEnter your chice : ";
cin>>opt;
switch(opt)
{
case 1: basics();
goto menu;
break;
case 2: letters();
goto menu;
break;
case 3: sentence();
goto menu;
break;
case 0: exit(0);
break;
default: goto menu;
break;
}
}
void basics()
{
clrscr();
int rep;
char choice1,choice2;
char key;
char mid[]="asdfgf ;lkjhj";
char top[]="qwertr poiuyu";
char bot[]="zxcvbv /.,mnm";
cout<<"\n\nHello! I think you are new dude to the world of fast typing.";
delay(1000);
cout<<"\n\nAnd as I have now agreed to teach you how to be fast in typing......";
delay(1000);
cout<<"\n\nLet us start.Are you ready ?(y/n)";
cin>>choice1;
if(choice1=='y'||choice1=='Y')
{
clrscr();
cout<<"\n\nUnderstand, it is very to do this....";
delay(1000);
cout<<"\n\nFollow me.......";
delay(1000);
cout<<"\n\nPress any key to start.";
getch();
cout<<"\n\nLet us study the basics....";
delay(1000);
cout<<"\n\nFirst you have to learn the mid row.....";
cout<<"\n\nHow many times do you want to practice : ";
cin>>rep;
cout<<"\n\nDo you want to see the finger positioning ?(y/n)";
cin>>choice2;
if(choice2=='y'||choice2=='Y')
{
/************************************/
cout<<"\n\nUnder development..........";
getch();
}
cout<<"\n\nType what you see on the screen...";
for(int i=0;i<rep;++i)
{
for(int j=0;j<13;++j)
{
cout<<"\n\nEnter this:"<<mid[j];
cout<<"\tYou entered:";
key=getche();
if(key==mid[j])
{
cout<<"\tCorrect..";
sound(300);
delay(200);
nosound();
}
else
{
cout<<"\tWrong";
sound(600);
delay(100);
nosound();
sound(700);
delay(100);
nosound();
}
}
}
//Top row
cout<<"\n\nNow you have to learn the top row.....";
cout<<"\n\nHow many times do you want to practice : ";
cin>>rep;
cout<<"\n\nDo you want to see the finger positioning ?(y/n)";
cin>>choice2;
if(choice2=='y'||choice2=='Y')
{
/************************************/
cout<<"\n\nUnder development..........";
getch();
}
cout<<"\n\nType what you see on the screen...";
for(i=0;i<rep;++i)
{
for(int j=0;j<13;++j)
{
cout<<"\n\nEnter this:"<<top[j];
cout<<"\tYou entered:";
key=getche();
if(key==top[j])
{
cout<<"\tCorrect..";
sound(300);
delay(200);
nosound();
}
else
{
cout<<"\tWrong";
sound(600);
delay(100);
nosound();
sound(700);
delay(100);
nosound();
}
}
}
//Bottom Row
cout<<"\n\nFirst you have to learn the bottom row.....";
cout<<"\n\nHow many times do you want to practice : ";
cin>>rep;
cout<<"\n\nDo you want to see the finger positioning ?(y/n)";
cin>>choice2;
if(choice2=='y'||choice2=='Y')
{
/************************************/
cout<<"\n\nUnder development..........";
getch();
}
cout<<"\n\nType what you see on the screen...";
for(i=0;i<rep;++i)
{
for(int j=0;j<13;++j)
{
cout<<"\n\nEnter this:"<<bot[j];
cout<<"\tYou entered:";
key=getche();
if(key==bot[j])
{
cout<<"\tCorrect..";
sound(300);
delay(200);
nosound();
}
else
{
cout<<"\tWrong";
sound(600);
delay(100);
nosound();
sound(700);
delay(100);
nosound();
}
}
}
} //wanna learn
else
{
cout<<"\n\nOh! I think you are busy. OK See you later.......";
delay(3000);
}
}
void letters()
{
randomize();
char choice;
int num;
int score=0,randnum;
char letter,key;
clrscr();
cout<<"In this test you will have to type the letters you see on the screen.";
delay(1000);
cout<<"\n\nDo you want to see the help menu ?(y/n)";
choice=getche();
if(choice=='y'||choice=='Y')
{
cout<<"\n\n1.You are to type the random letters you see on the screen.";
delay(2000);
cout<<"\n\n2.If your answer is correct you can hear this beep.";
while(!kbhit())
{
sound(300);
delay(200);
nosound();
}
getch();
cout<<"\n\n3.If your answer is wrong you will hear this";
while(!kbhit())
{
sound(600);
delay(100);
nosound();
sound(700);
delay(100);
nosound();
}
}
cout<<"\n\nPress any key when you are ready.";
getch();
int number;
cout<<"\n\nWhat should be the max score:";
cin>>number;
for(int i=0;i<number;i++)
{
clrscr();
randnum=random(25);
for(int j=0;j<randnum;j++)
cout<<"\n";
randnum=random(25);
for(j=0;j<randnum;j++)
cout<<"\t";
num=65+random(25);
letter=(char)num;
cout<<letter;
key=getch();
if(key==letter)
{
sound(300);
delay(200);
nosound();
score++;
}
else
{
sound(600);
delay(200);
nosound();
sound(700);
delay(200);
nosound();
}
}
cout<<"\n\n\nYour total score is "<<score;
getch();
}
void sentence()
{
clrscr();
time_t t1,t2;
char line[300];
cout<<"This is spped test to try your speed.\n";
delay(1000);
type:
cout<<"\nYou will have to type the sentence given.\n";
delay(1000);
cout<<"\n\nPress any key to start.";
getch();
clrscr();
t1 = time(NULL);
cout<<"I am learning to type.";
cout<<"\n\nEnter the sentence:";
gets(line);
t2 = time(NULL);
if(!strcmp(line,"I am learning to type."))
{
cout<<"\n\nYou could type the sentence in "<<t2-t1<<" seconds.";
getch();
}
else
{
cout<<"\n\nThe sentence you typed was wrong..";
getch();
goto type;
}
}
Creating Virtual File System Using Python Document
If you are writing an application of any size, it will most likely require a number of files to run – files which could be stored in a variety of possible locations. Furthermore, you will probably want to be able to change the location of those files when debugging and testing. You may even want to store those files somewhere other than the user's hard drive.
Any engineer worth his salt will recognise that the file locations should be stored in some kind of configuration file and the code to read the files in question should be factored out so that it isn't just scattered at points where data is read or written. In this post I'll present a way of doing just that by creating a virtual filesystem with PyFilesystem.
You'll need the most recent version of PyFilesystem from SVN to run this code.
We're going to create a virtual filesystem for a fictitious application that requires per-application and per-user resources, as well as a location for cache and log files. I'll also demonstrate how to mount files located on a web server. Here's the code:
from fs.opener import
fsopendir
app_fs = fsopendir( 'mount://fs.ini' , create_dir =True)
That's, all there is to it; two lines of code (one if you don't count the import). Obviously there is quite a bit going on under the hood here, which I'll explain below, but lets see what this code gives you…
The app_fs object is an interface to a single filesystem that contains all the file locations our application will use. For example, the path /user/app.ini references a per-user file, whereas /resources/logo.png references a per application file. The actual physical location of the data is irrelevant because as far as your application is concerned the paths never change. This abstraction is useful because the real path for such files varies according to the platform the code is running on; Windows, Mac and Linux all have different conventions, and if you put your files in the wrong place, your app will likely break on one platform or another.
Here's how a per-user configuration file might be opened:
from ConfigParser import
ConfigParser
# The 'safeopen' method works like 'open', but will return an
# empty file-like object if the path does not exist
with app_fs .safeopen('/user/app.ini' ) as ini_file:
cfg = ConfigParser()
cfg .readfp(ini_file)
# ... do something with cfg
The files in our virtual filesystem don't even have to reside on the local filesystem. For instance, /live/ may actually reference a location on the web, where the version of the current release and a short ‘message of the day’ is stored.
Here's how the version number and MOTD might be read:
def get_application_version ():
"""Get the version numberof the most up to date version of the application,
as a tuple of three integers"""
with app_fs .safeopen('live/version.txt' ) as version_file:
version_text = version_file. read(). rstrip()
if not version_text:
# Empty file or unableto read
return None
return tuple( int (v) for v
in version_text .split( '.' , 3
))
def get_motd ():
"""Get a welcome message"""
with app_fs .safeopen("live/motd.txt" ) as motd_file:
return motd_file. read
() .rstrip()
You'll notice that even though the actual data is retrieved over HTTP (the files are located here and here), the code would be no different if the files were stored locally.
So how is all this behaviour created from a single line of code? The line
fsopendir("mount://fs.ini", create_dir=True)
opens a
MountFS from the information contained within an INI file ( create_dir=True will create specified directories if they don't exist). Here's an example of an INI file that could be used during development:
[fs]
user=./user
resources=./resources
logs=./logs
cache=./user/cache
live=./live
The INI file is used to construct a MountFS, where the keys in the [fs] section are the top level directory names and the values are the real locations of the files. In above example, /user/ maps on to a directory called user relative to the current directory – but it could be changed to an absolute path or to a location on a server (e.g. FTP, SFTP, HTTP, DAV), or even to a directory within a zip file.
You can change the section to use in a mount opener by specifying it after a # symbol, i.e.
mount://fs.ini#mysection
There are a few changes to this INI file we will need to make when our application is ready for release. User data, site data, logs and cache all have canonical locations that are derived from the name of the application (and the author on Windows). PyFilesystem contains handy openers for these special locations. For example,
appuser://examplesoft:myapp detects the appropriate per-user data location for an application called “myapp” developed by “examplesoft”. Ditto for the other per-application directories. e.g.
[fs]
user=appuser://examplesoft:myapp
resources=appsite://examplesoft:myapp
logs=applog://examplesoft:myapp
cache=appcache://examplesoft:myapp
The /live/ path is different in that it needs to point to a web server:
live=http://www.willmcgugan.com/static/cfg/
Of course, you don't need to use the canonical locations. For instance, let's say you want to store all your static resources in a zip file. No problem:
resources=zip://./resources.zip
Or you want to keep your user data on a SFTP (Secure FTP) server:
user=sftp://username:password@example.org/home/will/
Perhaps you don't want to preserve the cache across sessions, for security reasons. The temp opener creates files in a temp directory and deletes them on close:
cache=temp://
Although, if you are really paranoid you can store the cache files in memory without ever writing them to disk:
cache=mem://
Setting /user/ to mem:// is a useful way of simulating a fresh install when debugging.
Spread Virus By Pen drive Inserting in Computer
If you like this post, Then please share it with your friends, so that they can also enjoy the article:
In below tutorial I'M going to share how to attackers Spreading batch viruses through pen drive .
Step 1 :
Open notepad and write
Save file as autorun.inf
Step 2:
_=_=_=_=_=_=_=_=_=_=_=_=_=_=_=_=
[autorun]
open=anything.bat
Icon=anything.ico
_=_=_=_=_=_=_=_=_=_=_=_=_=_=_=_=
Put this autorun.inf and your actual batch virus
anything.bat in pendrive .
When the victim would plug in pen drive,the autorun.inf will launch anything.bat and commands in batch file virus would executed.
* If this Helped you! Please take a Second to like and share it.
Python Exercises 100+
100+ Python challenging programming exercises
1. Level description
Level Description
Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve s
Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong pr
Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries function
2. Problem template
#----------------------------------------#
Question
Hints
Solution
3. Questions
#----------------------------------------#
Question 1
Level 1
Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
Solution:
l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print ','.join(l)
#----------------------------------------#
#----------------------------------------#
Question 2
Level 1
Question:
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x=int(raw_input())
print fact(x)
#----------------------------------------#
#----------------------------------------#
Question 3
Level 1
Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such th
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Consider use dict()
Solution:
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
#----------------------------------------#
#----------------------------------------#
Question 4
Level 1
Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list an
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
tuple() method can convert list to tuple
Solution:
values=raw_input()
l=values.split(",")
t=tuple(l)
print l
print t
#----------------------------------------#
#----------------------------------------#
Question 5
Level 1
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
Hints:
Use __init__ method to construct some parameters
Solution:
class InputOutString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = raw_input()
def printString(self):
print self.s.upper()
strObj = InputOutString()
strObj.getString()
strObj.printString()
#----------------------------------------#
#----------------------------------------#
Question 6
Level 2
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example,
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
#!/usr/bin/env python
import math
c=50
h=30
value = []
items=[x for x in raw_input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print ','.join(value)
#----------------------------------------#
#----------------------------------------#
Question 7
Level 2
Question:
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element va
Note: i=0,1.., X-1; j=0,1,¡-1.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Hints:
Note: In case of input data being supplied to the question, it should be assumed to be a console input
Solution:
input_str = raw_input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
for row in range(rowNum):
for col in range(colNum):
multilist[row][col]= row*col
print multilist
#----------------------------------------#
#----------------------------------------#
Question 8
Level 2
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a com
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
items=[x for x in raw_input().split(',')]
items.sort()
print ','.join(items)
#----------------------------------------#
#----------------------------------------#
Question 9
Level 2
Question£º
Write a program that accepts sequence of lines as input and prints the lines after making all character
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence
#----------------------------------------#
#----------------------------------------#
Question 10
Level 2
Question:
Write a program that accepts a sequence of whitespace separated words as input and prints the words aft
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use set container to remove duplicated data automatically and then use sorted() to sort the data.
Solution:
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
#----------------------------------------#
#----------------------------------------#
Question 11
Level 2
Question:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and the
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)
print ','.join(value)
#----------------------------------------#
#----------------------------------------#
Question 12
Level 2
Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print ",".join(values)
#----------------------------------------#
#----------------------------------------#
Question 13
Level 2
Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"DIGITS":0, "LETTERS":0}
for c in s:
if c.isdigit():
d["DIGITS"]+=1
elif c.isalpha():
d["LETTERS"]+=1
else:
pass
print "LETTERS", d["LETTERS"]
print "DIGITS", d["DIGITS"]
#----------------------------------------#
#----------------------------------------#
Question 14
Level 2
Question:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case l
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
s = raw_input()
d={"UPPER CASE":0, "LOWER CASE":0}
for c in s:
if c.isupper():
d["UPPER CASE"]+=1
elif c.islower():
d["LOWER CASE"]+=1
else:
pass
print "UPPER CASE", d["UPPER CASE"]
print "LOWER CASE", d["LOWER CASE"]
#----------------------------------------#
#----------------------------------------#
Question 15
Level 2
Question:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4
#----------------------------------------#
#----------------------------------------#
Question 16
Level 2
Question:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
values = raw_input()
numbers = [x for x in values.split(",") if int(x)%2!=0]
print ",".join(numbers)
#----------------------------------------#
Question 17
Level 2
Question:
Write a program that computes the net amount of a bank account based a transaction log from console inp
D 100
W 200
¡
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import sys
netAmount = 0
while True:
s = raw_input()
if not s:
break
values = s.split(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print netAmount
#----------------------------------------#
#----------------------------------------#
Question 18
Level 3
Question:
A website requires the users to input username and password to register. Write a program to check the v
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solutions:
import re
value = []
items=[x for x in raw_input().split(',')]
for p in items:
if len(p)<6 or len(p)>12:
continue
else:
pass
if not re.search("[a-z]",p):
continue
elif not re.search("[0-9]",p):
continue
elif not re.search("[A-Z]",p):
continue
elif not re.search("[$#@]",p):
continue
elif re.search("\s",p):
continue
else:
pass
value.append(p)
print ",".join(value)
#----------------------------------------#
#----------------------------------------#
Question 19
Level 3
Question:
You are required to write a program to sort the (name, age, height) tuples by ascending order where na
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19'
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use itemgetter to enable multiple sort keys.
Solutions:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))
#----------------------------------------#
#----------------------------------------#
Question 20
Level 3
Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a giv
Hints:
Consider use yield
Solution:
def putNumbers(n):
i = 0
while i<n:
j=i
i=i+1
if j%7==0:
yield j
for i in reverse(100):
print i
#----------------------------------------#
#----------------------------------------#
Question 21
Level 3
Question£º
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, L
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡
The numbers after the direction are steps. Please write a program to compute the distance from current
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
import math
pos = [0,0]
while True:
s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction=="UP":
pos[0]+=steps
elif direction=="DOWN":
pos[0]-=steps
elif direction=="LEFT":
pos[1]-=steps
elif direction=="RIGHT":
pos[1]+=steps
else:
pass
print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
#----------------------------------------#
#----------------------------------------#
Question 22
Level 3
Question:
Write a program to compute the frequency of the words from the input. The output should output after s
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
Hints
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
freq = {} # frequency of words in text
line = raw_input()
for word in line.split():
freq[word] = freq.get(word,0)+1
words = freq.keys()
words.sort()
for w in words:
print "%s:%d" % (w,freq[w])
#----------------------------------------#
#----------------------------------------#
Question 23
level 1
Question:
Write a method which can calculate square value of number
Hints:
Using the ** operator
Solution:
def square(num):
return num ** 2
print square(2)
print square(3)
#----------------------------------------#
#----------------------------------------#
Question 24
Level 1
Question:
Python has many built-in functions, and if you do not know how to use it, you can read document on
Please write a program to print some Python built-in functions documents, such as abs(), int(), raw
And add document for your own function
Hints:
The built-in document method is __doc__
Solution:
print abs.__doc__
print int.__doc__
print raw_input.__doc__
def square(num):
'''Return the square value of the input number.
The input number must be integer.
'''
return num ** 2
print square(2)
print square.__doc__
#----------------------------------------#
#----------------------------------------#
Question 25
Level 1
Question:
Define a class, which have a class parameter and have a same instance parameter.
Hints:
Define a instance parameter, need add it in __init__ method
You can init a object with construct parameter or set the value later
Solution:
class Person:
# Define the class parameter "name"
name = "Person"
def __init__(self, name = None):
# self.name is the instance parameter
self.name = name
jeffrey = Person("Jeffrey")
print "%s name is %s" % (Person.name, jeffrey.name)
nico = Person()
nico.name = "Nico"
print "%s name is %s" % (Person.name, nico.name)
#----------------------------------------#
#----------------------------------------#
Question:
Define a function which can compute the sum of two numbers.
Hints:
Define a function with two numbers as arguments. You can compute the sum in the function and return th
Solution
def SumFunction(number1, number2):
return number1+number2
print SumFunction(1,2)
#----------------------------------------#
Question:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
Solution
def printValue(n):
print str(n)
printValue(3)
#----------------------------------------#
Question:
Define a function that can convert a integer into a string and print it in console.
Hints:
Use str() to convert a number to string.
Solution
def printValue(n):
print str(n)
printValue(3)
#----------------------------------------#
2.10
Question:
Define a function that can receive two integral numbers in string form and compute their sum and then
Hints:
Use int() to convert a string to integer.
Solution
def printValue(s1,s2):
print int(s1)+int(s2)
printValue("3","4") #7
#----------------------------------------#
2.10
Question:
Define a function that can accept two strings as input and concatenate them and then print it in conso
Hints:
Use + to concatenate the strings
Solution
def printValue(s1,s2):
print s1+s2
printValue("3","4") #34
#----------------------------------------#
2.10
Question:
Define a function that can accept two strings as input and print the string with maximum length in con
Hints:
Use len() function to get the length of a string
Solution
def printValue(s1,s2):
len1 = len(s1)
len2 = len(s2)
if len1>len2:
print s1
elif len2>len1:
print s2
else:
print s1
print s2
printValue("one","three")
#----------------------------------------#
2.10
Question:
Define a function that can accept an integer number as input and print the "It is an even number" if t
Hints:
Use % operator to check if a number is even or odd.
Solution
def checkValue(n):
if n%2 == 0:
print "It is an even number"
else:
print "It is an odd number"
checkValue(7)
#----------------------------------------#
2.10
Question:
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both include
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Solution
def printDict():
d=dict()
d[1]=1
d[2]=2**2
d[3]=3**2
print d
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both inclu
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
print d
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both inc
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for (k,v) in d.items():
print v
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both inc
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for k in d.keys():
print k
printDict()
#----------------------------------------#
2.10
Question:
Define a function which can generate and print a list where the values are square of numbers between 1
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (b
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[:5]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (b
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[-5:]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate a list where the values are square of numbers between 1 and 20 (b
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[5:]
printList()
#----------------------------------------#
2.10
Question:
Define a function which can generate and print a tuple where the value are square of numbers between 1
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
Use tuple() to get a tuple from a list.
Solution
def printTuple():
li=list()
for i in range(1,21):
li.append(i**2)
print tuple(li)
printTuple()
#----------------------------------------#
2.10
Question:
With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line
Hints:
Use [n1:n2] notation to get a slice from a tuple.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
tp2=tp[5:]
print tp1
print tp2
#----------------------------------------#
2.10
Question:
Write a program to generate and print another tuple whose values are even numbers in the given tuple (
Hints:
Use "for" to iterate the tuple
Use tuple() to generate a tuple from a list.
Solution
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
if tp[i]%2==0:
li.append(tp[i])
tp2=tuple(li)
print tp2
#----------------------------------------#
2.14
Question:
Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes
Hints:
Use if statement to judge condition.
Solution
s= raw_input()
if s=="yes" or s=="YES" or s=="Yes":
print "Yes"
else:
print "No"
#----------------------------------------#
3.4
Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,
Hints:
Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print evenNumbers
#----------------------------------------#
3.4
Question:
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print squaredNumbers
#----------------------------------------#
3.5
Question:
Write a program which can map() and filter() to make a list whose elements are square of even number i
Hints:
Use map() to generate a list.
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
#----------------------------------------#
3.5
Question:
Write a program which can filter() to make a list whose elements are even number between 1 and 20 (bot
Hints:
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
Solution
evenNumbers = filter(lambda x: x%2==0, range(1,21))
print evenNumbers
#----------------------------------------#
3.5
Question:
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
Solution
squaredNumbers = map(lambda x: x**2, range(1,21))
print squaredNumbers
#----------------------------------------#
7.2
Question:
Define a class named American which has a static method called printNationality.
Hints:
Use @staticmethod decorator to define class static method.
Solution
class American(object):
@staticmethod
def printNationality():
print "America"
anAmerican = American()
anAmerican.printNationality()
American.printNationality()
#----------------------------------------#
7.2
Question:
Define a class named American and its subclass NewYorker.
Hints:
Use class Subclass(ParentClass) to define a subclass.
Solution:
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
print anAmerican
print aNewYorker
#----------------------------------------#
7.2
Question:
Define a class named Circle which can be constructed by a radius. The Circle class has a method which
Hints:
Use def methodName(self) to define a method.
Solution:
class Circle(object):
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
aCircle = Circle(2)
print aCircle.area()
#----------------------------------------#
7.2
Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has
Hints:
Use def methodName(self) to define a method.
Solution:
class Rectangle(object):
def __init__(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
aRectangle = Rectangle(2,10)
print aRectangle.area()
#----------------------------------------#
7.2
Define a class named Shape and its subclass Square. The Square class has an init function which takes a
Hints:
To override a method in super class, we can define a method with the same name in the super class.
Solution:
class Shape(object):
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, l):
Shape.__init__(self)
self.length = l
def area(self):
return self.length*self.length
aSquare= Square(3)
print aSquare.area()
#----------------------------------------#
Please raise a RuntimeError exception.
Hints:
Use raise() to raise an exception.
Solution:
raise RuntimeError('something wrong')
#----------------------------------------#
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints:
Use try/except to catch exceptions.
Solution:
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print "division by zero!"
except Exception, err:
print 'Caught an exception'
finally:
print 'In finally block for cleanup'
#----------------------------------------#
Define a custom exception class which takes a string message as attribute.
Hints:
To define a custom exception, we need to define a class inherited from Exception.
Solution:
class MyError(Exception):
"""My own exception class
Attributes:
msg -- explanation of the error
"""
def __init__(self, msg):
self.msg = msg
error = MyError("something wrong")
#----------------------------------------#
Question:
Assuming that we have some email addresses in the "username@companyname.com" format, please write progr
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
john
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print r2.group(1)
#----------------------------------------#
Question:
Assuming that we have some email addresses in the "username@companyname.com" format, please write progr
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
google
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use \w to match letters.
Solution:
import re
emailAddress = raw_input()
pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print r2.group(2)
#----------------------------------------#
Question:
Write a program which accepts a sequence of words separated by whitespace as input to print the words c
Example:
If the following words is given as input to the program:
2 cats and 3 dogs.
Then, the output of the program should be:
['2', '3']
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use re.findall() to find all substring using regex.
Solution:
import re
s = raw_input()
print re.findall("\d+",s)
#----------------------------------------#
Question:
Print a unicode string "hello world".
Hints:
Use u'strings' format to define unicode string.
Solution:
unicodeString = u"hello world!"
print unicodeString
#----------------------------------------#
Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
Hints:
Use unicode() function to convert.
Solution:
s = raw_input()
u = unicode( s ,"utf-8")
print u
#----------------------------------------#
Question:
Write a special comment to indicate a Python source code file is in unicode.
Hints:
Solution:
# -*- coding: utf-8 -*-
#----------------------------------------#
Question:
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use float() to convert an integer to a float
Solution:
n=int(raw_input())
sum=0.0
for i in range(1,n+1):
sum += float(float(i)/(i+1))
print sum
#----------------------------------------#
Question:
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
500
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
We can define recursive function in Python.
Solution:
def f(n):
if n==0:
return 0
else:
return f(n-1)+100
n=int(raw_input())
print f(n)
#----------------------------------------#
Question:
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program to compute the value of f(n) with a given n input by console.
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
13
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
We can define recursive function in Python.
Solution:
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(raw_input())
print f(n)
#----------------------------------------#
#----------------------------------------#
Question:
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
0,1,1,2,3,5,8,13
Hints:
We can define recursive function in Python.
Use list comprehension to generate a list from an existing list.
Use string.join() to join a list of strings.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(raw_input())
values = [str(f(x)) for x in range(0, n+1)]
print ",".join(values)
#----------------------------------------#
Question:
Please write a program using generator to print the even numbers between 0 and n in comma separated for
Example:
If the following n is given as input to the program:
10
Then, the output of the program should be:
0,2,4,6,8,10
Hints:
Use yield to produce the next value in generator.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def EvenGenerator(n):
i=0
while i<=n:
if i%2==0:
yield i
i+=1
n=int(raw_input())
values = []
for i in EvenGenerator(n):
values.append(str(i))
print ",".join(values)
#----------------------------------------#
Question:
Please write a program using generator to print the numbers which can be divisible by 5 and 7 between
Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
Hints:
Use yield to produce the next value in generator.
In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:
def NumGenerator(n):
for i in range(n+1):
if i%5==0 and i%7==0:
yield i
n=int(raw_input())
values = []
for i in NumGenerator(n):
values.append(str(i))
print ",".join(values)
#----------------------------------------#
Question:
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
Hints:
Use "assert expression" to make assertion.
Solution:
li = [2,4,6,8]
for i in li:
assert i%2==0
#----------------------------------------#
Question:
Please write a program which accepts basic mathematic expression from console and print the evaluation
Example:
If the following string is given as input to the program:
35+3
Then, the output of the program should be:
38
Hints:
Use eval() to evaluate an expression.
Solution:
expression = raw_input()
print eval(expression)
#----------------------------------------#
Question:
Please write a binary search function which searches an item in a sorted list. The function should retu
Hints:
Use if/elif to deal with conditions.
Solution:
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
#----------------------------------------#
Question:
Please write a binary search function which searches an item in a sorted list. The function should retu
Hints:
Use if/elif to deal with conditions.
Solution:
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
#----------------------------------------#
Question:
Please generate a random float where the value is between 10 and 100 using Python math module.
Hints:
Use random.random() to generate a random float in [0,1].
Solution:
import random
print random.random()*100
#----------------------------------------#
Question:
Please generate a random float where the value is between 5 and 95 using Python math module.
Hints:
Use random.random() to generate a random float in [0,1].
Solution:
import random
print random.random()*100-5
#----------------------------------------#
Question:
Please write a program to output a random even number between 0 and 10 inclusive using random module a
Hints:
Use random.choice() to a random element from a list.
Solution:
import random
print random.choice([i for i in range(11) if i%2==0])
#----------------------------------------#
Question:
Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 incl
Hints:
Use random.choice() to a random element from a list.
Solution:
import random
print random.choice([i for i in range(201) if i%5==0 and i%7==0])
#----------------------------------------#
Question:
Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample(range(100), 5)
#----------------------------------------#
Question:
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample([i for i in range(100,201) if i%2==0], 5)
#----------------------------------------#
Question:
Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , bet
Hints:
Use random.sample() to generate a list of random values.
Solution:
import random
print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)
#----------------------------------------#
Question:
Please write a program to randomly print a integer number between 7 and 15 inclusive.
Hints:
Use random.randrange() to a random integer in a given range.
Solution:
import random
print random.randrange(7,16)
#----------------------------------------#
Question:
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello
Hints:
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
Solution:
import zlib
s = 'hello world!hello world!hello world!hello world!'
t = zlib.compress(s)
print t
print zlib.decompress(t)
#----------------------------------------#
Question:
Please write a program to print the running time of execution of "1+1" for 100 times.
Hints:
Use timeit() function to measure the running time.
Solution:
from timeit import Timer
t = Timer("for i in range(100):1+1")
print t.timeit()
#----------------------------------------#
Question:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
Solution:
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
#----------------------------------------#
Question:
Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
Solution:
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
#----------------------------------------#
Question:
Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Pla
Hints:
Use list[index] notation to get a element from a list.
Solution:
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
for i in range(len(subjects)):
for j in range(len(verbs)):
for k in range(len(objects)):
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print sentence
#----------------------------------------#
Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
Hints:
Use list comprehension to delete a bunch of element from a list.
Solution:
li = [5,6,77,45,22,12,24]
li = [x for x in li if x%2!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing delete numbers whi
Hints:
Use list comprehension to delete a bunch of element from a list.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for x in li if x%5!=0 and x%7!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i%2!=0]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
Hints:
Use list comprehension to make an array.
Solution:
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
print array
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the 0th,4th,5th n
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
Solution:
li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i not in (0,4,5)]
print li
#----------------------------------------#
Question:
By using list comprehension, please write a program to print the list after removing the value 24 in [1
Hints:
Use list's remove method to delete a value.
Solution:
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print li
#----------------------------------------#
Question:
With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list who
Hints:
Use set() and "&=" to do set intersection operation.
Solution:
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
set1 &= set2
li=list(set1)
print li
#----------------------------------------#
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removi
Hints:
Use set() to store a number of values without duplicate.
Solution:
def removeDuplicate( li ):
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.append(item)
return newli
li=[12,24,35,24,88,120,155,88,120,155]
print removeDuplicate(li)
#----------------------------------------#
Question:
Define a class Person and its two child classes: Male and Female. All classes have a method "getGender
Hints:
Use Subclass(Parentclass) to define a child class.
Solution:
class Person(object):
def getGender( self ):
return "Unknown"
class Male( Person ):
def getGender( self ):
return "Male"
class Female( Person ):
def getGender( self ):
return "Female"
aMale = Male()
aFemale= Female()
print aMale.getGender()
print aFemale.getGender()
#----------------------------------------#
Question:
Please write a program which count and print the numbers of each character in a string input by console
Example:
If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a,2
c,2
b,2
e,1
d,1
g,1
f,1
Hints:
Use dict to store key/value pairs.
Use dict.get() method to lookup a key with default value.
Solution:
dic = {}
s=raw_input()
for s in s:
dic[s] = dic.get(s,0)+1
print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
#----------------------------------------#
Question:
Please write a program which accepts a string from console and print it in reverse order.
Example:
If the following string is given as input to the program:
rise to vote sir
Then, the output of the program should be:
ris etov ot esir
Hints:
Use list[::-1] to iterate a list in a reverse order.
Solution:
s=raw_input()
s = s[::-1]
print s
#----------------------------------------#
Question:
Please write a program which accepts a string from console and print the characters that have even inde
Example:
If the following string is given as input to the program:
H1e2l3l4o5w6o7r8l9d
Then, the output of the program should be:
Helloworld
Hints:
Use list[::2] to iterate a list by step 2.
Solution:
s=raw_input()
s = s[::2]
print s
#----------------------------------------#
Question:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
Solution:
import itertools
print list(itertools.permutations([1,2,3]))
#----------------------------------------#
Question:
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many
Hint:
Use for loop to iterate all possible solutions.
Solution:
def solve(numheads,numlegs):
ns='No solutions!'
for i in range(numheads+1):
j=numheads-i
if 2*i+4*j==numlegs:
return i,j
return ns,ns
numheads=35
numlegs=94
solutions=solve(numheads,numlegs)
print solutions
#----------------------------------------#