Count number of times a list contiguously appears in another list?
For example, function [1; 2] [1; 2; 3; 1; 2] should return 2. function [A; A] [A; A; A; A; A] should return 4.
I know I need a helper function. I'm thinking the function can check to see if the sequence is contiguous. But I'm lost on how to implement. This is what I have so far:
let rec mch (seq: string list) (actlist: string list) : bool =
begin match seq, actlist with
| [], _ -> true
| h1::tl1, h2::tl2 ->
end
The main function should have the header:
let rec function (seq: string list) (actlist: string list) : int =
See also questions close to this topic
-
Using the following code, why can't I use Google trends-api PyTrends with 5 concatenated words element in a list?
For reference, I am using this tutorial: https://towardsdatascience.com/a-very-precise-fast-way-to-pull-google-trends-data-automatically-4c3c431960aa
import pandas as pd import pytrends from pytrends.request import TrendReq pytrend = TrendReq() KEYWORDS=['Nike','Adidas','Under Armour','Zara','H&M','Louis Vuitton'] KEYWORDS_CODES=[pytrend.suggestions(keyword=i)[0] for i in KEYWORDS] df_CODES= pd.DataFrame(KEYWORDS_CODES) df_CODES EXACT_KEYWORDS=df_CODES['mid'].to_list() DATE_INTERVAL='2020-01-01 2020-05-01' COUNTRY=["US","GB","DE"] #Use this link for iso country code CATEGORY=0 # Use this link to select categories SEARCH_TYPE='' #default is 'web searches',others include 'images','news','youtube','froogle' (google shopping) Individual_EXACT_KEYWORD = list(zip(*[iter(EXACT_KEYWORDS)]*1)) Individual_EXACT_KEYWORD = [list(x) for x in Individual_EXACT_KEYWORD] dicti = {} i = 1 for Country in COUNTRY: for keyword in Individual_EXACT_KEYWORD: pytrend.build_payload(kw_list=keyword, timeframe = DATE_INTERVAL, geo = Country, cat=CATEGORY, gprop=SEARCH_TYPE) dicti[i] = pytrend.interest_over_time() i+=1 df_trends = pd.concat(dicti, axis=1) df_trends.columns = df_trends.columns.droplevel(0) #drop outside header df_trends = df_trends.drop('isPartial', axis = 1) #drop "isPartial" df_trends.reset_index(level=0,inplace=True) #reset_index df_trends.columns=['date','Nike-US','Adidas-US','Under Armour-US','Zara-US','H&M-US','Louis Vuitton-US','Nike-UK','Adidas-UK','Under Armour-UK','Zara-UK','H&M-UK','Louis Vuitton-UK', 'Nike-Germany','Adidas-Germany','Under Armour-Germany','Zara-Germany','H&M-Germany','Louis Vuitton-Germany'] #change column names
Why does it give me a list index out of range error when I use multiple words together like this:
KEYWORDS=['Nike + Adidas + Puma','Adidas','Under Armour','Zara','H&M','Louis Vuitton']
When I concat on the Google Trends website and use: 'Nike + Adidas + Puma' it still gives me a map and a historical frequency of that concatenated string. But why does it give a list out of range error when doing it in the KEYWORDS variable?
Thank you
-
Splitting digits only from the list in python and save into CSV
how to split the numbers only from the list its large though and then export into CSV
print(list)
output['id=31535&requestId=16152331&ln=143833'] ['id=31539&requestId=16152331&ln=143833'] ['id=31540&requestId=16152331&ln=143832'] ['id=31541&requestId=16152331&ln=143831'] ['id=31542&requestId=16152331&ln=143845']
-
I get "TypeError: list indices must be integers or slices, not str". How do I fix it?
I am working on some code that will take the data from OpenWeatherMap.org and displays the weather. Here's what I have so far:
import requests, json apikey = "7cb9becaea566cc27d69991c345fa129" base = "http://api.openweathermap.org/data/2.5/onecall?" lat = "censored" lon = "censored" compbase = f"{base}lat={lat}&lon={lon}&exclude=current,minutely,hourly&appid={apikey}" print(compbase) resp = requests.get(compbase) x = resp.json() daily = x["daily"] temp = daily["temp"] des = daily["weather"] currtemp = temp["morn"] currtemp = str(round(float(1.8)*(currtemp - 273) + 32, 1)) currpres = day["pressure"] currpres = str(round(currpres/3386, 1)) currhum = day["humidity"] feelslike = day["feels_like"] feelslike = str(round(float(1.8)*(feelslike - 273) + 32, 1)) winds = str(round(float(y["wind_speed"]), 1)) weatherdes = str(des["description"]) if "alerts" in x: alerts = x["alerts"] aldes = alerts["description"] print() print("ALERT!!!!") print() print(f"Your WeatherWatcher program has been interuppted by {alerts['sender_name']}. Please pay attention closely.") print() print(str(aldes)) print() print(f"It is currently {currtemp} degrees Fahrenheit outside.") print() print(f"It feels like {feelslike} degrees Fahrenheit outside.") print() print(f"The wind is blowing at {winds} MPH.") print() print(f"The pressure is at {currpres} inhg.") print() print(f"The humidity is at %{currhum}.") print() print(f"OpenWeatherMap describes this weather as {weatherdes}.") print() print("This data was brought to you by WeatherWatcher.")
(Sorry, kinda long.)
But when I run it, I get this:
Traceback (most recent call last): File "C:\Users\ron83\OneDrive\Documents\weather.py", line 12, in <module> temp = daily["temp"] TypeError: list indices must be integers or slices, not str
What did I do wrong? I know I didn't make it a string.
-
How to implement recursive method **at** object initialization?
Say I have the following object:
const dog = { sound: 'woof', speak: function() { console.log(this.sound) } }
How could I implement
dog.speak
recursively within the initial object literal declaration?I could accomplish this by defining the
dog.speak
method outside of the initial object literal. E.g.:const dog = { sound: 'woof' } const dog.speak = () => { console.log(dog.sound) window.setTimeout(dog.speak, 1000) }
This works because there is no
this
concept here - thesound
property explicitly belongs todog
. But I would prefer to define this all within the initial object literal.To do so, I would need to preserve the
this
context via.bind()
. But I'm struggling to identify where I would.bind()
dog
asthis
before making the recursive function call. -
All combination for a natural number using recursive methot C#
I have this code:
private static IEnumerable<(string formula, int sum)> GenerateRecursive(int number) { if (number == 1) yield return ("1", 1); else foreach (var pair in GenerateRecursive(number - 1)) { yield return ($"{pair.formula} - {number}", pair.sum - number); yield return ($"{pair.formula} + {number}", pair.sum + number); } } private static IEnumerable<string> SolveFor(int target, int count) { return GenerateRecursive(count) .Where(item => item.sum == target) .Select(item => $"{item.formula} = {item.sum}"); }
which gives you all the combination for a natural number from(1, 2 ,3..... , n) using addition and subtraction.
For input is the number and the length for example:
- length : 6
- Number : 3
And for the output:
- 1 + 2 + 3 - 4 - 5 + 6 = 3
- 1 + 2 - 3 + 4 + 5 - 6 = 3
- 1 - 2 - 3 - 4 + 5 + 6 = 3
I am wondering how can I do this without
LINQ
and Collections Generic and using just recursive method. Thank You. -
count sum 1/1+1/2+1/3+/1/n series C++
I have to count sum 1/1+1/2+1/3+1/4+1/n series using recursion. I have tried this but it does not work. how should I solve it?
#include<iostream> using namespace std; double sum(int n) { if(n==1){return 1;} if(n==0){return 0;} return 1+1/sum(n-1); } int main(){ cout<<sum(2); }
-
Which is better in OCaml pattern matching, `when` or `if-then-else`?
Let's say we have a type called d:
type d = D of int * int
And we want to do some pattern matching over it, is it better to do it this way:
let dcmp = function | D (x, y) when x > y -> 1 | D (x, y) when x < y -> -1 | _ -> 0
or
let dcmp = function | D (x, y) -> if x > y then 1 else if x < y then -1 else 0
Just in general is better to match patterns with many "when" cases or to match one pattern and the put an "if-then-else" in it?
And where can I get more information about such matters, like good practices in OCaml and syntactic sugars and such?
-
OCaml A ref does not change its value despite I instructed it
I have a real code but I made this sample to illustrate my issue. This is the code sample:
let ejem n = let count = ref 0 in let rec aum n = if n = 0 then 0 else (count := !count + 1; n + aum (n-1) ) in (aum n, !count)
I try to change the
count
value insideaum
function but, despite thecount
is outside of this function, its value is always0
once it finishes.Please, help me to get what the issue is
-
OCaml Input types
I am learning OCaml and so far I am having trouble to understand the concepts of types.
For example, if we have this following code:
# let func x = x;; val func : 'a -> 'a = <fun>
From the official website, it tells me that
'a
before the arrow is the unknown input type and'a
after the arrow is the output.However, when I try to use function composition:
# let composition f x = f(x);; val composition : ('a -> 'b) -> 'a -> 'b = <fun>
What
('a -> 'b)
means? Is'a
related tof
and'b
related tox
?Another function composition that made me even more confused is:
# let composition2 f x = f(f(x));; val composition2 : ('a -> 'a) -> 'a -> 'a = <fun>
I don't really understand why we don't have the
'b
in this case.Thank you in advance!