empty list when cycling in a tuple - python

def calcCandidates(str):
TOKEN_CONFIG = [
("Mor", af.automata_Mor(str))]
for (TokenKind, automata) in TOKEN_CONFIG:
candidates.append(TokenKind)
return (allTrapped, candidates)
I do get a reply and is this:
(False, [])
But I'm expecting to have something inside [], for example ["mor"]
If you need the full code of that function:
def calcCandidates(str):
TOKEN_CONFIG = [
("Mor", af.automata_Mor(str)),
("Si", af.automata_Si(str)),
("Hacer", af.automata_Hacer(str)),
("OpenC", af.automata_OpenC(str)),
("CloseC", af.automata_CloseC(str)),
]
allTrapped = True
candidates = []
for (TokenKind, automata) in TOKEN_CONFIG:
res = automata
if res == RESULT_ACCEPTED:
allTrapped = False
candidates.append(TokenKind)
if res == RESULT_NOT_ACCEPTED:
allTrapped = False
return (allTrapped, candidates)

Related

What's the best method to create a dictionary from outputs of multiple for loops

This is my code:
def get_coin_tickers(url):
req = requests.get(url)
# print(req.text)
resp = json.loads(req.text)
# print(resp.text)
return resp
pair_a_list = ["BTC_USDT", "EOS_USDT", "ETH_USDT"]
pair_b_list = ["SOL_USDT", "MATIC_USDT", "SUSHI_USDT"]
for pair_a in pair_a_list:
orderbook_url = f'https://api.pionex.com/api/v1/market/depth?symbol={pair_a}&limit=5'
pair_a_prices_json = get_coin_tickers(orderbook_url)
pair_a_ask = pair_a_prices_json['data']['asks'][0][0]
pair_a_bid = pair_a_prices_json['data']['bids'][0][0]
for pair_b in pair_b_list:
orderbook_url = f'https://api.pionex.com/api/v1/market/depth?symbol={pair_b}&limit=5'
pair_a_prices_json = get_coin_tickers(orderbook_url)
pair_b_ask = pair_a_prices_json['data']['asks'][0][0]
pair_b_bid = pair_a_prices_json['data']['bids'][0][0]
keys = ['pair_a', 'pair_a_ask', 'pair_a_bid', 'pair_b', 'pair_b_ask', 'pair_b_bid']
values = [pair_a, pair_a_ask, pair_a_bid, pair_b, pair_b_ask, pair_b_bid]
mydict = {k: v for (k, v) in zip(keys, values)}
print(mydict)
I'm able to create a Dictionary but with only one Symbol-Pairs from each list. Which seems to be outputs from only the last symbol pairs of both the lists:
{'pair_a': 'ETH_USDT', 'pair_a_ask': '1254.18', 'pair_a_bid': '1253.51', 'pair_b': 'SUSHI_USDT', 'pair_b_ask': '0.9815', 'pair_b_bid': '0.9795'}
I'm expecting to see a combined dictionary with values of both lists as keys (with their API-Values) in the final list (after) iterating through both lists using for Loops
Found a solution to my question based on suggestion from #JonSG, plus adapted to the suggestion. I've included the code below for others to use as and if the need arises.
for pair_a_list, pair_b_list, pair_c_list in zip(pair_a_list, pair_b_list, pair_c_list):
orderbook_a_url = f'https://api.pionex.com/api/v1/market/depth?symbol={pair_a_list}&limit=1'
pair_a_prices_json = get_coin_tickers(orderbook_a_url)
pair_a_ask = pair_a_prices_json['data']['asks'][0][0]
pair_a_bid = pair_a_prices_json['data']['bids'][0][0]
my_dict_a = {
'pair_a_ask': pair_a_ask,
'pair_a_bid': pair_a_bid
}
orderbook_b_url = f'https://api.pionex.com/api/v1/market/depth?symbol={pair_b_list}&limit=1'
pair_b_prices_json = get_coin_tickers(orderbook_b_url)
pair_b_ask = pair_b_prices_json['data']['asks'][0][0]
pair_b_bid = pair_b_prices_json['data']['bids'][0][0]
my_dict_b = {
'pair_b_ask': pair_b_ask,
'pair_b_bid': pair_b_bid
}
orderbook_c_url = f'https://api.pionex.com/api/v1/market/depth?symbol={pair_c_list}&limit=1'
pair_c_prices_json = get_coin_tickers(orderbook_c_url)
pair_c_ask = pair_c_prices_json['data']['asks'][0][0]
pair_c_bid = pair_c_prices_json['data']['bids'][0][0]
my_dict_c = {
'pair_c_ask': pair_c_ask,
'pair_c_bid': pair_c_bid
}
# (Use either option below.)
# my_dict = {**my_dict_a, **my_dict_b, **my_dict_c}
# my_dict = my_dict_a | my_dict_b | my_dict_c

Python Order Dictionary in Chronological Order even if keys are different

I am trying to make an RSS feed composed of different sources and I would like them to be sorted by newest date, rather than the source itself. I store all of my news in one python dictionary, regardless of its source:
feed = None
if sports['nhl'] == 1:
feed = newsParse('nhl')
allOff = False
if sports['nba'] == 1:
feed = newsParse('nba')
allOff = False
if sports['nfl'] == 1:
feed = newsParse('nfl')
allOff = False
if sports['mlb'] == 1:
feed = newsParse('mlb')
allOff = False
The function looks like this:
def newsParse(league):
rss_url = 'https://www.espn.com/espn/rss/' + league + '/news'
parser = feedparser.parse(rss_url)
newsInfo = {
'title': [],
'link': [],
'description': [],
'date': []
}
for entry in parser.entries:
newsInfo['title'].append(entry.title)
newsInfo['description'].append(entry.description)
newsInfo['link'].append(entry.links[0].href)
newsInfo['date'].append(entry.published)
return newsInfo
If I print out 'feed' I get all of the titles sorted by source, then all of the descriptions sorted by source, and etc. The ['date'] data looks like this:
Fri, 24 Jul 2020 09:35:08 EST'
How can I sort all of my values in chronological order, whilst keeping the titles, descriptions, and links together?
Why not save the entries as a list of dictionaries ?
For example:
def newsParse(league):
rss_url = 'https://www.espn.com/espn/rss/' + league + '/news'
parser = feedparser.parse(rss_url)
newsInfo = []
for entry in parser.entries:
newEntry = {'title': entry.title,
'description': entry.description,
'link': entry.link,
'date': entry.date}
newsInfo.append(newEntry)
return newsInfo
newsInfo will be a list of dictionaries,
and you can sort that list using this line of code:
sorted(newsInfo, key=lambda k: k['date'])
If the date from the RSS feed is a string,
I think you should convert it to python's datetime type for the sorting to work.
Edit (answer for comment):
If you need a single list with all the leagues,
you can use this code:
feed = []
if sports['nhl'] == 1:
feed.extend(newsParse('nhl'))
allOff = False
if sports['nba'] == 1:
feed.extend(newsParse('nba'))
allOff = False
if sports['nfl'] == 1:
feed.extend(newsParse('nfl'))
allOff = False
if sports['mlb'] == 1:
feed.extend(newsParse('mlb'))
allOff = False
After feed contains all the data you need,
you can sort it by date:
sorted(feed, key=lambda k: k['date'])

List index errror

I have created a program which reads a file line into a list. When i run the code below, i see that there is a list with elements inside it.
dogs_list_player = []
dogs_list_computer = []
with open("dogs.txt") as f:
for i in range(Y):
dogs_list_player.append(f.readline().splitlines())
print(dogs_list_player)
for i in range(Z):
dogs_list_computer.append(f.readline().splitlines())
print(dogs_list_computer)
The result is:
[['Tim']]
[['Tim'], ['Bob']]
[['Tim'], ['Bob'], ['Jess']]
[['Tim'], ['Bob'], ['Jess'], ['Bess']]
[['Tim'], ['Bob'], ['Jess'], ['Bess'], ['Tess']]
[['Dom']]
[['Dom'], ['Tom']]
[['Dom'], ['Tom'], ['Will']]
[['Dom'], ['Tom'], ['Will'], ['Ben']]
[['Dom'], ['Tom'], ['Will'], ['Ben'], ['Joe']]
But the issue arises when i add this part of code:
dogs_list_player = []
dogs_list_computer = []
with open("dogs.txt") as f:
for i in range(Y):
dogs_list_player.append(f.readline().splitlines())
print(dogs_list_player)
for i in range(Z):
dogs_list_computer.append(f.readline().splitlines())
print(dogs_list_computer)
class Dog_card:
name = ""
friendliness = ""
intelligence = ""
exercise = ""
drool = ""
def printing_card(self):
prnt_str = "Name:%s \nIntelligence:%s \nExercise:%s \nDrool:%s" %(self.name, self.friendliness, self.intelligence, self.exercise, self.drool)
return prnt_str
player_card = Dog_card()
card_count = 0
player.name = dogs_list_player[0]#i think this is where the issue is happening
the result of this code is:
IndexError: list index out of range
Any help would be appreciated
your Dog_card class has some errors :
you forget "friendliness" parameter in the string that is in printing_card method and also you have not any constructor in your class .
class Dog_card:
def __init__(self):
self.name = ""
self.friendliness = ""
self.intelligence = ""
self.exercise = ""
self.drool = ""
def printing_card(self):
prnt_str = "Name:%s \nIntelligence:%s friendliness:%s \nExercise:%s \nDrool:%s" %(self.name, self.friendliness, self.intelligence, self.exercise, self.drool)
return prnt_str
this shoud be work .

python list of dictionaries only updating 1 attribute and skipping others

I have a list of lists containing company objects:
companies_list = [companies1, companies2]
I have the following function:
def get_fund_amount_by_year(companies_list):
companies_length = len(companies_list)
for idx, companies in enumerate(companies_list):
companies1 = companies.values_list('id', flat=True)
funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')
amount_per_year_list = []
for fr in funding_rounds:
fr_year = fr.announced_on.year
fr_amount = fr.raised_amount_usd
if not any(d['year'] == fr_year for d in amount_per_year_list):
year_amount = {}
year_amount['year'] = fr_year
for companies_idx in range(companies_length):
year_amount['amount'+str(companies_idx)] = 0
if companies_idx == idx:
year_amount['amount'+str(companies_idx)] = fr_amount
amount_per_year_list.append(year_amount)
else:
for year_amount in amount_per_year_list:
if year_amount['year'] == fr_year:
year_amount['amount'+str(idx)] += fr_amount
return amount_per_year_list
The problem is the resulting list of dictionaries has only one amount attribute updated.
As you can see "amount0" contains all "0" amounts:
[{'amount1': 12100000L, 'amount0': 0, 'year': 1999}, {'amount1':
8900000L, 'amount0': 0, 'year': 2000}]
What am I doing wrong?
I put list of dictionaries being built in the loop and so when it iterated it overwrote the last input. I changed it to look like:
def get_fund_amount_by_year(companies_list):
companies_length = len(companies_list)
**amount_per_year_list = []**
for idx, companies in enumerate(companies_list):
companies1 = companies.values_list('id', flat=True)
funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')

For loop did't working in view.py Django?

in view.py
Id = [2,3,4,5,6,7,8]
for w in Id:
A = w
Pending = pending(A)
data = {
'Pending': Pending,
}
return render_to_response('dialer_campaign/campaign/list.html', data, context_instance=RequestContext(request))
def pending(campaign_id):
A = Campaign_phonebook.objects.values_list('phonebook_id').filter(campaign_id = campaign_id)
B = Contact.objects.filter(phonebook_id__in=A).count()
C = Subscriber.objects.filter(campaign_id = campaign_id).exclude(status = 1).count()
Result = B - C
return Result
When i add manual value instead of A it gives result,but now i want to give value by for loop it is not working.Why ? Can anybody Help me ?
Want changes should i do in templates ?
Thanks in Advance..
Take your data object in list and render to the template
Refer following code
Id = [2,3,4,5,6,7,8]
pending_list = []
for w in Id:
pending = pending(w)
pending_list.append({'pending': pending})
return render_to_response('dialer_campaign/campaign/list.html', pending_list, context_instance=RequestContext(request))
def pending(campaign_id):
A = Campaign_phonebook.objects.values_list('phonebook_id').filter(campaign_id = campaign_id)
B = Contact.objects.filter(phonebook_id__in=A).count()
C = Subscriber.objects.filter(campaign_id = campaign_id).exclude(status = 1).count()
Result = B - C
return Result
Use pending_list in your template. In pending_list list you get all the pending objects.

Categories

Resources