Posts

Showing posts with the label programming

What is the difference between iostream and iostream.h in cpp?

In C++, there are two seemingly similar headers for input/output operations: iostream and iostream.h. However, they have key differences you should be aware of: 1. Standard vs. Non-Standard: **iostream** is the standard header for input/output operations in C++. It is part of the C++ Standard Library and is guaranteed to be available and consistent across different compilers. **iostream.h** is a non-standard header . It was used in pre-standard C++ and some early compilers. It is not part of the C++ Standard Library and its availability and behavior might vary depending on the compiler. 2. Namespace: **iostream** defines everything within the **std** namespace. This helps avoid naming conflicts with other libraries or user-defined functions. **iostream.h** does not use namespaces. This means all its elements are directly available in the global namespace, which can lead to potential naming conflicts and is generally considered less modern practice. 3. Recommendations: Always use iostr

Deleting a file in Python

We need os module to delete a file on hard drive import os if os.path.exists("myfile.txt"): os.remove("myfile.txt") print("Deleted successfully") else: print("No such file exists")

Copying contents of one file into another file in Python

File handling in Python try: with open("myfile.txt", "r") as f1: with open("newfile.txt", "w") as f2: for i in f1: # print(type(f2)) f2.write(i) except: print("Sorry! The file does not exist. Plz create first.") else: print("Contents of file copied successfully.")

Finding out next palindrome of numbers in a given list?

 The following program will find out the palindrome of numbers in a given list. If the number in the list is less than or equal to 10, it will be printed as such; if the number in the list is greater than 10, the next palindrome of that number will be calculated. But if the number greater than 10 is already a palindrome, then 1 will be added to it and then the next palindrome of that number will be found. mylist = [1, 6, 10, 11, 88, 535, 5439] plist = [] for number in mylist: if number <= 10: plist.append(number) elif number > 10: # comment out the following if block if palindrome in list to be written as such if str(number) == str(number)[::-1]: number += 1 while str(number) != str(number)[::-1]: number += 1 plist.append(number) print(plist)

The next palindrome for given number(s)

 The following program takes user input as number(s) and tells whether the input is a palindrome. If it is not, it will return the next palindrome for that number. ncases = int(input("How many cases: ")) for i in range(ncases): case = input(f"Enter your case {i+1}: ") if case == case[::-1]: print("This is a palindrome") else: pali = case[:] while pali != pali[::-1]: pali = int(pali) + 1 pali = str(pali) if pali == pali[::-1]: print(f"The next palindrome for case {case} is {pali}")

Palindrome or NOT a Palindrome ?

 The following program takes a user input, be it a number or any word, and tells whether the input is a palindrome or not. ''' Whether a given word or number is a palindrome or not? ''' while True: word = input("Enter a word or number:\n") if word == word[::-1]: print(f"{word} is a palindrome") else: print(f"{word} is not a palindrome")

3 Methods of Reversing a User Input List in Python

  # defining empty list uList = [] # defining the number of elements in the list nList = int(input("List of how many elements? ")) print("Now enter the elements of your list one by one.") # taking elements of the list as user input for i in range(0,nList): element = int(input()) uList.append(element) print(f"The original list is {uList}") # taking copy of the list, storing it in variable, then reversing it reverse1 = uList[:] reverse1.reverse() print(f"The first reverse of the original list {uList} is {reverse1}") reverse2 = uList[::-1] print(f"The second reverse of the original list {uList} is {reverse2}") reverse3 = uList[:] for i in range(len(reverse3)//2): reverse3[i], reverse3[len(reverse3)-i-1] = reverse3[len(reverse3)-i-1], reverse3[i] print(f"The third reverse of the original list {uList} is {reverse3}") if reverse1 == reverse2 and reverse2 == reverse3: print("All the three meth

Function in Python that Reverse a given List

 The following function in python will return the reverse of the given list. def reverseList(n): reverseL = uList[:] for i in range(len(reverseL)//2): reverseL[i], reverseL[len(reverseL)-i-1] = reverseL[len(reverseL)-i-1], reverseL[i] print(f"The reverse of the original list {uList} is {reverseL}") uList = [45,66,7,1,333] reverseList(uList)

Calculate user age and when will they turn 100

The following Python program calculates 2 things; 1. when will the user turn 100 2. what will be the user's age in a certain year  # when will I be 100 years old age_yob = input("Plz enter your age or year of birth: ") # my age in the future year age_in_year = input("You age in a certain year: ") current_year = 2022 # age_in_year = float(age_in_year) # dealing age try: if len(age_yob) < 4: if len(age_yob) == 3: print("You are already 100 years old.") elif len(age_yob) < 3: age_100 = 100 - float(age_yob) print(f"You will turn 100 in {current_year + age_100}") add_to_age = float(age_in_year) - current_year age_asked = float(age_yob) + add_to_age print(f"You age in {age_in_year} will be {age_asked}") else: # dealing yob age_100 = float(age_yob) + 100 print(f"You will turn 100

Extract Emails from a rough string using Regular Expressions

import re str = """A Better Fake Name Generator FAKE NAME MORE TOOLS ABOUT CONTACT US Tools: IDENTITY GENERATOR RANDOM TEXT FAKE EMAIL FAKE CREDIT CARD GENERATOR FAKE CREDIT CARD VALIDATOR FAKE DRIVER'S LICENSE FAKE COMPANY FAKE PHONE NUMBER FAKE SOCIAL SECURITY NUMBER VIEW ALL TOOLS » More: ABOUT CONTACT US HOME TOOLS FAKE EMAIL GENERATOR ×FauxID.com is a free service and we rely on ad revenue. Please consider disabling your ad blocker on this site. Create List of Fake Emails Free Email List Generator Simple Fake Email List Generator. Select how many email addresses you are looking for and click "generate". Number of Email to Generate 10 Number between 1-1000 fiona.krajcik@padberg.biz bberge@gmail.com kaden.brown@schmidt.com lschinner@hotmail.com naomi.stamm@hotmail.com klein.katrina@larson.net qbailey@robel.com lina.hessel@bosco.com dfranecki@strosin.biz juanita.becker@schuster.com Fake Identity • Fake Name • Fake SSN • Fake Address • F

Saving Web dataset into a file, Pickling that file, then Unpickling it

import pickle import requests # getting iris dataset from a web address resp = requests.get("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data") # saving the web data into a text file with open("iris.txt", "w") as f: f.write(resp.text) # reading the created text file containing the web data with open("iris.txt", "r") as f: dataset = f.read() # splitting the web data in text file listof = dataset.split("\n") # converting list into list of lists lol = [[item] for item in listof] # pickling the data pickleed = open("irislists.pkl", "wb") pickle.dump(file=pickleed, obj=lol) pickleed.close() # unpickling the data unpickleed = open("irislists.pkl", "rb") pythonobj = pickle.load(file=unpickleed) print(pythonobj) unpickleed.close()

Pickle Module in Python

import pickle # pickling a python object mylist = ["waqas", "sheeraz",{"sheeraz": "haroon", "sheer": "veer"}, "haroon", "farrukh"] file_object = open("mylist.pkl", "wb") # write as binary file pickle.dump(file=file_object, obj=mylist) file_object.close() # unpickling into python object fileb = open("mylist.pkl", "rb") # read binary file python_obj = pickle.load(file=fileb) print(python_obj) fileb.close()

News API Client in Python

from newsapi import NewsApiClient news_api = NewsApiClient(api_key="YOURAPIKEY") # YOURAPIKEY get from https://newsapi.org/ by making an account first top_headlines = news_api.get_top_headlines(q="amazon") # q represents keywords or phrases that NEWS must contain print(top_headlines) all_articles = news_api.get_everything(q="amazon") print(all_articles) sources = news_api.get_sources() print(sources)

Get and Read top NEWS Headlines in Python

import json import requests def newsreader(string): from win32com.client import Dispatch speak_it = Dispatch("SAPI.SpVoice") speak_it.Speak(string) response = requests.get("https://newsapi.org/v2/top-headlines?country=in&category=general&apiKey=YOURAPIKEY") # YOURAPIKEY get from https://newsapi.org/ by making an account first news = json.loads(response.text) # print(news) for i in range(5): breaking_news = news["articles"][i]["description"] print(breaking_news) if i==0: newsreader("Welcome to Breaking news for this hour.") newsreader("the first breaking news for this hour is, ") newsreader(breaking_news) elif i==4: newsreader("the last breaking news for this hour is, ") newsreader(breaking_news) newsreader("Thanks for listening. Plz come again for next round of updates.") else: newsreader("the ne

Text to Speech conversion in Python

from win32com.client import Dispatch speak_it = Dispatch("SAPI.SpVoice") string = input("Enter the text and we will speak it: ") speak_it.Speak(string)

JSON module in Python

import json # Converting python object and writing into json file data = { "name": "Satyam kumar", "place": "patna", "skills": ["Raspberry pi", "Machine Learning", "Web Development"], "email": "xyz@gmail.com", "projects": ["Python Data Mining", "Python Data Science"], "player": True} with open("data2.json", "w") as f: json.dump(data, f) # Converting python object into json string. res = json.dumps(data) print(res) # loads the created json file with open("data.json", "r") as f: print(json.load(f)) # json string, after parsing becomes a python dict data = """{ "name" : "abdur", "natur" : "space", "favterm" : "infinity", "lvoe" : true }""" pasa = js

Coroutines in Python

Note: Get your free API key at https://newsapi.org/ by first making your account. from urllib.request import urlopen from bs4 import BeautifulSoup def searcher(): url = "https://en.wikipedia.org/wiki/Kabul#Toponymy_and_etymology" page = urlopen(url) html = page.read().decode("utf-8") soup = BeautifulSoup(html, "html.parser") article1 = soup.get_text() url = "https://en.wikipedia.org/wiki/Python_(programming_language)" page = urlopen(url) html = page.read().decode("utf-8") soup = BeautifulSoup(html, "html.parser") article2 = soup.get_text() url = "https://en.wikipedia.org/wiki/Amoeba_(operating_system)" page = urlopen(url) html = page.read().decode("utf-8") soup = BeautifulSoup(html, "html.parser") article3 = soup.get_text() article = article1 + article2 + article3 while True: word = (yield)

Extract text only from a webpage through "html.parser"

from bs4 import BeautifulSoup from urllib.request import urlopen url = "https://en.wikipedia.org/wiki/Kabul#Toponymy_and_etymology" page = urlopen(url) html = page.read().decode("utf-8") soup = BeautifulSoup(html, "html.parser") print(soup.get_text())

Extracting Text From HTML (Web Pages) in Python

  from urllib . request import urlopen # scenario 1: html with proper <title> tags url = "http://olympus.realpython.org/profiles/aphrodite" page = urlopen ( url ) html_bytes = page .read() html = html_bytes .decode( "utf-8" ) # OR replace the above 4 lines with the following 1 line html = urlopen ( "http://olympus.realpython.org/profiles/aphrodite" ).read().decode( "utf-8" ) # Extract Title Text From HTML With String Methods title_index = html .find( "<title>" ) start_index = title_index + len ( "<title>" ) end_index = html .find( "</title>" ) title = html [ start_index : end_index ] print ( title ) # scenario 2: html with improper <title > tags url = "http://olympus.realpython.org/profiles/poseidon" page = urlopen ( url ) html = page .read().decode( "utf-8" ) start_index = html .find( "<title>" ) + len ( "<title>" ) en

Function Caching in Python

import time from functools import lru_cache @lru_cache(maxsize=1) def add_work(n, m): time.sleep(3) return n + m print(add_work(3,4)) # takes 3 secs to print print(add_work(3,5)) # takes 3 secs to print print(add_work(3,4)) # takes 3 secs to print print(add_work(3,5)) # takes 3 secs to print print(add_work(3,5)) # this and rest takes no time to print print(add_work(3,5)) print(add_work(3,5)) print(add_work(3,5)) ###############################################3 # Following takes user input for defining maxsize import time from functools import lru_cache @lru_cache(maxsize=int(input("Enter maxsize for lru_cache: "))) def some_work(n, m): time.sleep(3) return n + m print(some_work(3,4)) print(some_work(3,5)) print(some_work(3,4)) print(some_work(3,5)) print(some_work(3,4)) print(some_work(3,5))