Skip to content

Commit f18ba6d

Browse files
authored
Merge pull request #322 from adityajai25/new
Solutions for hackerrank problems python
2 parents e32d300 + e62db2e commit f18ba6d

File tree

12 files changed

+365
-0
lines changed

12 files changed

+365
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
## Get Started
3+
4+
Tweepy:
5+
Tweepy is the python client for the official Twitter API. Install it using following pip command:
6+
7+
```bash
8+
pip install tweepy
9+
```
10+
11+
TextBlob: textblob is the python library for processing textual data. Install it using following pip command:
12+
13+
```bash
14+
pip install textblob
15+
```
16+
17+
Install some NLTK corpora using following command:
18+
19+
```bash
20+
python -m textblob.download_corpora
21+
```
22+
## Authentication:
23+
In order to fetch tweets through Twitter API, one needs to register an App through their twitter account. Follow these steps for the same:
24+
25+
1. Open developer.twitter.com/apps and click the button: ‘Create New App’
26+
2. Fill the application details. You can leave the callback url field empty.
27+
3. Once the app is created, you will be redirected to the app page.
28+
4. Open the ‘Keys and Access Tokens’ tab.
29+
5. Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import re
2+
import tweepy
3+
from tweepy import OAuthHandler
4+
from textblob import TextBlob
5+
6+
class TwitterClient(object):
7+
def __init__(self):
8+
# keys and tokens from the Twitter Dev Console
9+
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
10+
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
11+
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
12+
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
13+
14+
# attempt authentication
15+
try:
16+
# create OAuthHandler object
17+
self.auth = OAuthHandler(consumer_key, consumer_secret)
18+
# set access token and secret
19+
self.auth.set_access_token(access_token, access_token_secret)
20+
# create tweepy API object to fetch tweets
21+
self.api = tweepy.API(self.auth)
22+
except:
23+
print("Error: Authentication Failed")
24+
25+
def clean_tweet(self, tweet):
26+
'''
27+
Utility function to clean tweet text by removing links, special characters
28+
using simple regex statements.
29+
'''
30+
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
31+
|(\w+:\/\/\S+)", " ", tweet).split())
32+
33+
def get_tweet_sentiment(self, tweet):
34+
'''
35+
Utility function to classify sentiment of passed tweet
36+
using textblob's sentiment method
37+
'''
38+
# create TextBlob object of passed tweet text
39+
analysis = TextBlob(self.clean_tweet(tweet))
40+
# set sentiment
41+
if analysis.sentiment.polarity > 0:
42+
return 'positive'
43+
elif analysis.sentiment.polarity == 0:
44+
return 'neutral'
45+
else:
46+
return 'negative'
47+
48+
def get_tweets(self, query, count = 10):
49+
'''
50+
Main function to fetch tweets and parse them.
51+
'''
52+
# empty list to store parsed tweets
53+
tweets = []
54+
55+
try:
56+
# call twitter api to fetch tweets
57+
fetched_tweets = self.api.search(q = query, count = count)
58+
59+
# parsing tweets one by one
60+
for tweet in fetched_tweets:
61+
# empty dictionary to store required params of a tweet
62+
parsed_tweet = {}
63+
64+
# saving text of tweet
65+
parsed_tweet['text'] = tweet.text
66+
# saving sentiment of tweet
67+
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
68+
69+
# appending parsed tweet to tweets list
70+
if tweet.retweet_count > 0:
71+
# if tweet has retweets, ensure that it is appended only once
72+
if parsed_tweet not in tweets:
73+
tweets.append(parsed_tweet)
74+
else:
75+
tweets.append(parsed_tweet)
76+
77+
# return parsed tweets
78+
return tweets
79+
80+
except tweepy.TweepError as e:
81+
# print error (if any)
82+
print("Error : " + str(e))
83+
84+
def main():
85+
# creating object of TwitterClient Class
86+
api = TwitterClient()
87+
# calling function to get tweets
88+
tweets = api.get_tweets(query = 'Donald Trump', count = 200)
89+
90+
# picking positive tweets from tweets
91+
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
92+
# percentage of positive tweets
93+
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
94+
# picking negative tweets from tweets
95+
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
96+
# percentage of negative tweets
97+
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
98+
# percentage of neutral tweets
99+
print("Neutral tweets percentage: {} % \
100+
".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))
101+
102+
# printing first 5 positive tweets
103+
print("\n\nPositive tweets:")
104+
for tweet in ptweets[:10]:
105+
print(tweet['text'])
106+
107+
# printing first 5 negative tweets
108+
print("\n\nNegative tweets:")
109+
for tweet in ntweets[:10]:
110+
print(tweet['text'])
111+
112+
if __name__ == "__main__":
113+
# calling main function
114+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
## Get Started
3+
4+
Tweepy:
5+
Tweepy is the python client for the official Twitter API. Install it using following pip command:
6+
7+
```bash
8+
pip install tweepy
9+
```
10+
11+
TextBlob: textblob is the python library for processing textual data. Install it using following pip command:
12+
13+
```bash
14+
pip install textblob
15+
```
16+
17+
Install some NLTK corpora using following command:
18+
19+
```bash
20+
python -m textblob.download_corpora
21+
```
22+
## Authentication:
23+
In order to fetch tweets through Twitter API, one needs to register an App through their twitter account. Follow these steps for the same:
24+
25+
1. Open developer.twitter.com/apps and click the button: ‘Create New App’
26+
2. Fill the application details. You can leave the callback url field empty.
27+
3. Once the app is created, you will be redirected to the app page.
28+
4. Open the ‘Keys and Access Tokens’ tab.
29+
5. Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import re
2+
import tweepy
3+
from tweepy import OAuthHandler
4+
from textblob import TextBlob
5+
6+
class TwitterClient(object):
7+
def __init__(self):
8+
# keys and tokens from the Twitter Dev Console
9+
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
10+
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
11+
access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
12+
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
13+
14+
# attempt authentication
15+
try:
16+
# create OAuthHandler object
17+
self.auth = OAuthHandler(consumer_key, consumer_secret)
18+
# set access token and secret
19+
self.auth.set_access_token(access_token, access_token_secret)
20+
# create tweepy API object to fetch tweets
21+
self.api = tweepy.API(self.auth)
22+
except:
23+
print("Error: Authentication Failed")
24+
25+
def clean_tweet(self, tweet):
26+
'''
27+
Utility function to clean tweet text by removing links, special characters
28+
using simple regex statements.
29+
'''
30+
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
31+
|(\w+:\/\/\S+)", " ", tweet).split())
32+
33+
def get_tweet_sentiment(self, tweet):
34+
'''
35+
Utility function to classify sentiment of passed tweet
36+
using textblob's sentiment method
37+
'''
38+
# create TextBlob object of passed tweet text
39+
analysis = TextBlob(self.clean_tweet(tweet))
40+
# set sentiment
41+
if analysis.sentiment.polarity > 0:
42+
return 'positive'
43+
elif analysis.sentiment.polarity == 0:
44+
return 'neutral'
45+
else:
46+
return 'negative'
47+
48+
def get_tweets(self, query, count = 10):
49+
'''
50+
Main function to fetch tweets and parse them.
51+
'''
52+
# empty list to store parsed tweets
53+
tweets = []
54+
55+
try:
56+
# call twitter api to fetch tweets
57+
fetched_tweets = self.api.search(q = query, count = count)
58+
59+
# parsing tweets one by one
60+
for tweet in fetched_tweets:
61+
# empty dictionary to store required params of a tweet
62+
parsed_tweet = {}
63+
64+
# saving text of tweet
65+
parsed_tweet['text'] = tweet.text
66+
# saving sentiment of tweet
67+
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
68+
69+
# appending parsed tweet to tweets list
70+
if tweet.retweet_count > 0:
71+
# if tweet has retweets, ensure that it is appended only once
72+
if parsed_tweet not in tweets:
73+
tweets.append(parsed_tweet)
74+
else:
75+
tweets.append(parsed_tweet)
76+
77+
# return parsed tweets
78+
return tweets
79+
80+
except tweepy.TweepError as e:
81+
# print error (if any)
82+
print("Error : " + str(e))
83+
84+
def main():
85+
# creating object of TwitterClient Class
86+
api = TwitterClient()
87+
# calling function to get tweets
88+
tweets = api.get_tweets(query = 'Donald Trump', count = 200)
89+
90+
# picking positive tweets from tweets
91+
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
92+
# percentage of positive tweets
93+
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
94+
# picking negative tweets from tweets
95+
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
96+
# percentage of negative tweets
97+
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
98+
# percentage of neutral tweets
99+
print("Neutral tweets percentage: {} % \
100+
".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))
101+
102+
# printing first 5 positive tweets
103+
print("\n\nPositive tweets:")
104+
for tweet in ptweets[:10]:
105+
print(tweet['text'])
106+
107+
# printing first 5 negative tweets
108+
print("\n\nNegative tweets:")
109+
for tweet in ntweets[:10]:
110+
print(tweet['text'])
111+
112+
if __name__ == "__main__":
113+
# calling main function
114+
main()

OTHERS/Hackerrank/exception.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
list_a = [1,2,3,4,5]
2+
3+
try:
4+
index = int(input("Enter the index: "))
5+
6+
try:
7+
print(list_a[index])
8+
except IndexError:
9+
print("The index {} is incorrect and index should lie between -5 and 4".format(index))
10+
11+
except ValueError:
12+
print("Use an integer as an input")

OTHERS/Hackerrank/frozensets.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
set1 = {'A','B','C','D'}
2+
set2 = {'A',2,'C',4}
3+
frozen_set_1 = frozenset(set1)
4+
frozen_set_2 = frozenset(set2)
5+
6+
frozenset_union = frozen_set_1.union(frozen_set_2)
7+
frozenset_common = frozen_set_1.intersection(frozen_set_2)
8+
frozenset_difference = frozen_set_1.difference(frozen_set_2)
9+
frozenset_distinct = frozen_set_1.symmetric_difference(frozen_set_2)
10+
11+
print("frozen_set_1:",frozen_set_1)
12+
print("frozen_set_2:",frozen_set_2)
13+
print("frozenset_union:",frozenset_union)
14+
print("frozenset_common:",frozenset_common)
15+
print("frozenset_difference:",frozenset_difference)
16+
print("frozenset_distinct:",frozenset_distinct)

OTHERS/Hackerrank/immutable.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
tuple1 = (1,2,3,4,5,6,7,8,9,10)
2+
3+
tuple1[5] = 100
4+
5+
print(tuple1)
6+
7+
# Tuples are immutable because the tuple object doesnot support assignment of any elements to any particular index
8+
# 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
9+
10+
# 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.
11+
# Immutable objects include sets and tuples.

OTHERS/Hackerrank/list-removal.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
list_a = ["car", "place", "tree", "under", "grass", "price"]
2+
3+
remove_items_containing_a_or_A = lambda list_1 : [item for item in list_1 if "a" not in item.lower()]
4+
5+
print(remove_items_containing_a_or_A(list_a))

OTHERS/Hackerrank/pattern.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
user_input = int(input("Enter a number of your choice : "))
2+
3+
if(user_input == 1):
4+
for i in range(5,0,-1):
5+
print("*"*i)
6+
7+
elif(user_input == 2):
8+
for i in range(5,0,-1):
9+
print("*"*i)
10+
for j in range(2,6):
11+
print("-"*j)
12+
13+
else:
14+
print("Invalid input")

OTHERS/Hackerrank/sequence.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
A = [1,2,3,4,5,6]
2+
3+
for element in A:
4+
print(element**2)
5+
else:
6+
print("The sequence has ended")
+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
list_a = ["car", "place", "tree", "under", "grass", "price"]
2+
3+
remove_items_containing_a_or_A = lambda list_1 : [item for item in list_1 if "a" not in item.lower()]
4+
5+
print(remove_items_containing_a_or_A(list_a))

OTHERS/Hackerrank/tuples.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
t_1 = (1,4,9,16,25,36)
2+
3+
t_modified = tuple(i**2 for i in t_1)
4+
5+
print("t_modified:",t_modified)
6+
7+
print("Element at index postion 4 of t_modified:",t_modified[4])
8+
9+
t_sliced = t_modified[1:4]
10+
print("t_sliced:",t_sliced)

0 commit comments

Comments
 (0)