Skip to content

Solutions for hackerrank problems python #322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions MachineLearning Projects/Twitter-sentiment-analysis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

## Get Started

Tweepy:
Tweepy is the python client for the official Twitter API. Install it using following pip command:

```bash
pip install tweepy
```

TextBlob: textblob is the python library for processing textual data. Install it using following pip command:

```bash
pip install textblob
```

Install some NLTK corpora using following command:

```bash
python -m textblob.download_corpora
```
## Authentication:
In order to fetch tweets through Twitter API, one needs to register an App through their twitter account. Follow these steps for the same:

1. Open developer.twitter.com/apps and click the button: ‘Create New App’
2. Fill the application details. You can leave the callback url field empty.
3. Once the app is created, you will be redirected to the app page.
4. Open the ‘Keys and Access Tokens’ tab.
5. Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob

class TwitterClient(object):
def __init__(self):
# keys and tokens from the Twitter Dev Console
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'

# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")

def clean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
|(\w+:\/\/\S+)", " ", tweet).split())

def get_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
using textblob's sentiment method
'''
# create TextBlob object of passed tweet text
analysis = TextBlob(self.clean_tweet(tweet))
# set sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'

def get_tweets(self, query, count = 10):
'''
Main function to fetch tweets and parse them.
'''
# empty list to store parsed tweets
tweets = []

try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search(q = query, count = count)

# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}

# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)

# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)

# return parsed tweets
return tweets

except tweepy.TweepError as e:
# print error (if any)
print("Error : " + str(e))

def main():
# creating object of TwitterClient Class
api = TwitterClient()
# calling function to get tweets
tweets = api.get_tweets(query = 'Donald Trump', count = 200)

# picking positive tweets from tweets
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
# percentage of positive tweets
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
# picking negative tweets from tweets
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
# percentage of negative tweets
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
# percentage of neutral tweets
print("Neutral tweets percentage: {} % \
".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))

# printing first 5 positive tweets
print("\n\nPositive tweets:")
for tweet in ptweets[:10]:
print(tweet['text'])

# printing first 5 negative tweets
print("\n\nNegative tweets:")
for tweet in ntweets[:10]:
print(tweet['text'])

if __name__ == "__main__":
# calling main function
main()
29 changes: 29 additions & 0 deletions MachineLearning Projects/Twitter-sentiments-analysis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

## Get Started

Tweepy:
Tweepy is the python client for the official Twitter API. Install it using following pip command:

```bash
pip install tweepy
```

TextBlob: textblob is the python library for processing textual data. Install it using following pip command:

```bash
pip install textblob
```

Install some NLTK corpora using following command:

```bash
python -m textblob.download_corpora
```
## Authentication:
In order to fetch tweets through Twitter API, one needs to register an App through their twitter account. Follow these steps for the same:

1. Open developer.twitter.com/apps and click the button: ‘Create New App’
2. Fill the application details. You can leave the callback url field empty.
3. Once the app is created, you will be redirected to the app page.
4. Open the ‘Keys and Access Tokens’ tab.
5. Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob

class TwitterClient(object):
def __init__(self):
# keys and tokens from the Twitter Dev Console
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'

# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")

def clean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
|(\w+:\/\/\S+)", " ", tweet).split())

def get_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
using textblob's sentiment method
'''
# create TextBlob object of passed tweet text
analysis = TextBlob(self.clean_tweet(tweet))
# set sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'

def get_tweets(self, query, count = 10):
'''
Main function to fetch tweets and parse them.
'''
# empty list to store parsed tweets
tweets = []

try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search(q = query, count = count)

# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}

# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)

# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)

# return parsed tweets
return tweets

except tweepy.TweepError as e:
# print error (if any)
print("Error : " + str(e))

def main():
# creating object of TwitterClient Class
api = TwitterClient()
# calling function to get tweets
tweets = api.get_tweets(query = 'Donald Trump', count = 200)

# picking positive tweets from tweets
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
# percentage of positive tweets
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
# picking negative tweets from tweets
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
# percentage of negative tweets
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
# percentage of neutral tweets
print("Neutral tweets percentage: {} % \
".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))

# printing first 5 positive tweets
print("\n\nPositive tweets:")
for tweet in ptweets[:10]:
print(tweet['text'])

# printing first 5 negative tweets
print("\n\nNegative tweets:")
for tweet in ntweets[:10]:
print(tweet['text'])

if __name__ == "__main__":
# calling main function
main()
12 changes: 12 additions & 0 deletions OTHERS/Hackerrank/exception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
list_a = [1,2,3,4,5]

try:
index = int(input("Enter the index: "))

try:
print(list_a[index])
except IndexError:
print("The index {} is incorrect and index should lie between -5 and 4".format(index))

except ValueError:
print("Use an integer as an input")
16 changes: 16 additions & 0 deletions OTHERS/Hackerrank/frozensets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
set1 = {'A','B','C','D'}
set2 = {'A',2,'C',4}
frozen_set_1 = frozenset(set1)
frozen_set_2 = frozenset(set2)

frozenset_union = frozen_set_1.union(frozen_set_2)
frozenset_common = frozen_set_1.intersection(frozen_set_2)
frozenset_difference = frozen_set_1.difference(frozen_set_2)
frozenset_distinct = frozen_set_1.symmetric_difference(frozen_set_2)

print("frozen_set_1:",frozen_set_1)
print("frozen_set_2:",frozen_set_2)
print("frozenset_union:",frozenset_union)
print("frozenset_common:",frozenset_common)
print("frozenset_difference:",frozenset_difference)
print("frozenset_distinct:",frozenset_distinct)
11 changes: 11 additions & 0 deletions OTHERS/Hackerrank/immutable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
tuple1 = (1,2,3,4,5,6,7,8,9,10)

tuple1[5] = 100

print(tuple1)

# Tuples are immutable because the tuple object doesnot support assignment of any elements to any particular index
# inorder to change the value of a particular index we need to create a new tuple object and assign it to the old tuple object

# Immutable is a property of an object that cannot be changed once it is created. to change the value of a particular index we need to reassign the tuple to same tuple object.
# Immutable objects include sets and tuples.
5 changes: 5 additions & 0 deletions OTHERS/Hackerrank/list-removal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
list_a = ["car", "place", "tree", "under", "grass", "price"]

remove_items_containing_a_or_A = lambda list_1 : [item for item in list_1 if "a" not in item.lower()]

print(remove_items_containing_a_or_A(list_a))
14 changes: 14 additions & 0 deletions OTHERS/Hackerrank/pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
user_input = int(input("Enter a number of your choice : "))

if(user_input == 1):
for i in range(5,0,-1):
print("*"*i)

elif(user_input == 2):
for i in range(5,0,-1):
print("*"*i)
for j in range(2,6):
print("-"*j)

else:
print("Invalid input")
6 changes: 6 additions & 0 deletions OTHERS/Hackerrank/sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
A = [1,2,3,4,5,6]

for element in A:
print(element**2)
else:
print("The sequence has ended")
5 changes: 5 additions & 0 deletions OTHERS/Hackerrank/tempCodeRunnerFile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
list_a = ["car", "place", "tree", "under", "grass", "price"]

remove_items_containing_a_or_A = lambda list_1 : [item for item in list_1 if "a" not in item.lower()]

print(remove_items_containing_a_or_A(list_a))
10 changes: 10 additions & 0 deletions OTHERS/Hackerrank/tuples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
t_1 = (1,4,9,16,25,36)

t_modified = tuple(i**2 for i in t_1)

print("t_modified:",t_modified)

print("Element at index postion 4 of t_modified:",t_modified[4])

t_sliced = t_modified[1:4]
print("t_sliced:",t_sliced)