Listenin İçinde Aralık Belirleme

Soru: Tam sayılardan oluşan bir liste verilecek.Bizden istenen liste içindeki ardışık elemanları belirlemek eğer 3 veya daha fazla ardışık sayı varsa bu bir aralık belirtir ve aralık belirtilirken ilk ve son elamanları yazılır.Diğer elemanlar aynen aılınır.
Örnek:

solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
def solution(liste: list):
    control = []
    result = []
    for i in range(len(liste)):
        last = 0
        for j in range(i + 1, len(liste)):
            if liste[i:j] == list(range(liste[i], liste[j])):
                last = liste[j]
        if last:
            if last not in control:
                if len(range(liste[i], last)) > 1:                
                    control += [liste[i], last]
                    result += [f"{liste[i]}-{last}"]
                else:
                    control += [liste[i]]
                    result += [f"{liste[i]}"]
        else:
            if liste[i] not in control:
                control += [liste[i]]
                result += [f"{liste[i]}"]
    return ", ".join(result)


x = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
print(solution(x))

Çıktı:

-6, -3-1, 3-5, 7-11, 14, 15, 17-20
1 Beğeni
/*


   ***   	         *
    *                  *
    *                  *
    *	 ****	 ****  *****    ****   *   *
    *	*   *   *      *   *    *  *   *   *
    *	*   *   *      *   *    *  *   *   *
*   *	*   *   *      *   *    *  *   *****
*   *	*   *   *      *   *    *  *       *
 ***	 *** *  *      *****    *** *      *
                                           *
********************************************

*/

/*ya parçalayacam ya parçalayacam ya da parçalayacammm :)*/


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define rep(i, n) for(ll i = 0; i < n; i++)
#define ceza(i, n) for(ll i = n - 1; i >= 0; i--)
#define RUN_JARBAY_RUN ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define vll vector<ll>
#define deql deque<ll>
#define vi vector<int>
#define sll stack<ll>
#define pqueue priority_queue
#define pll pair<ll, ll>
#define mp make_pair
#define ff first
#define ss second
#define mete make_tuple
#define pb push_back
#define pf push_front
#define popf pop_front
#define popb pop_back

#define gcd __gcd
#define lcm(x, y) x * y / gcd(x, y)
#define get_digit(a) a - '0'
#define tos(x, y) string x; stringstream strstream; strstream << y; strstream >> x; 
#define all(a) a.begin(), a.end()
#define dbg_list(a)  cout<<"debug: "<<#a<<" "; for(ll i : a) { cout<<i<<" ";} cout<<endl;
#define dbg(a) cout<<"debug: "<<#a<<" : "<<a<<endl;
#define dbg2(a, b) cout<<"debug: "<<#a<<" : "<<a<<" || "<<#b<<" : "<<b<<endl;
#define inf 1000000009 // 10^9 + 9
#define mod 1000000007 // 10^9 + 7

// WARNING: only for int, not long long
#define clz(x) __builtin_clz(x) // the number of zeros at the beginning of the number
#define ctz(x) __builtin_ctz(x) // the number of zeros at the end of the number
#define popcount(x) __builtin_popcount(x) // the number of ones in the number
#define parity(x) __builtin_parity(x) // the parity (even or odd) of the number of ones

// for long long
#define clzll(x) __builtin_clzll(x) // the number of zeros at the beginning of the number
#define ctzll(x) __builtin_ctzll(x) // the number of zeros at the end of the number
#define popcountll(x) __builtin_popcountll(x) // the number of ones in the number
#define parityll(x) __builtin_parityll(x) // the parity (even or odd) of the number of ones

//node definition
struct node
{
  ll data;
  struct node *next;
};

typedef struct node Node;

//linked list definition
struct LinkedList
{
  Node *head;
  Node *tail;
};

typedef struct LinkedList LinkedList;

// definitions for problems
ll n;

void solve()
{
  cin>>n;
  vll a(n);
  rep(i, n) cin>>a[i];
  
  bool start = false;
  rep(i, n - 2)
  {
    if( (a[i+1] == a[i] + 1) && (a[i+2] == a[i] + 2))
    { 
      if(!start) cout<<"("<<a[i]<<" ", start=true;
    }
    else
    {
      if(start) cout<<a[i + 1]<<") ", start = false, i++;
      else cout<<a[i]<<" ";
    }
  }
  if(start) cout<<a[n - 1]<<")";
  cout<<endl;
}


int main()
{
  RUN_JARBAY_RUN
  
  #ifdef JARBAY_DEBUG
    clock_t start = clock();
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
  #endif
  
  ll t = 1;
  //cin>>t;
  rep(i, t)
    solve();
	
	#ifdef JARBAY_DEBUG
    double EXECUTION_TIME = (double(clock()) - double(start)) / double(CLOCKS_PER_SEC);
    cout<<"*******************************************"<<endl;
    cout<<"EXECUTION TIME: "<<EXECUTION_TIME<<endl;
  #endif
		
}

Bu kod da benden gelsin.
input:

20
-6 -3 -2 -1 0 1 3 4 5 7 8 9 10 11 14 15 17 18 19 20

output:

-6 (-3 1) (3 5) (7 11) 14 15 (17 20)
def solution(liste):
    istenen=''
    sınırlar=[]
    aralıklar=[]
    for i in range(len(liste)-1):
        if liste[i]+1!=liste[i+1]:
            sınırlar.append(liste[i+1])

    for i in sınırlar:
        aralıklar.append(liste[:liste.index(i)])
        del liste[:liste.index(i)]
    aralıklar.append(liste)
    for i in aralıklar:
        if len(i)==1:
            istenen+=str(i[0])+','
        if len(i)==2:
            istenen+=str(i[0])+','+str(i[1])+','
        if len(i)>2:
            istenen+= str(i[0]) + '-' + str(i[-1])+','
    return istenen.strip(',')

benim yazdığım koda bakabilirmisiniz aralıkları belirlemek tamam ama bunu str ye çevirirken yaptığım işten hoşlanmadım daha başka alternatifi olabilirmi o kısmın?

Şöyle de yazılabilirdi, ama işlem olarak aynı işlem.

    return ", ".join(
        [
            f"{i[0]}" if len(i) == 1 
            else f"{i[0]}-{i[-1]}" if len(i) > 2 
            else f"{i[0]}, {i[1]}" for i in aralıklar
        ]
    )
1 Beğeni

Listenin küçükten büyüğe sıralanmış sayılardan oluştuğunu varsayıyorum:

// Rust
fn print_items(seen: &Vec<i32>) {
    if seen.len() >= 3 {
        println!("({}: {}) ", seen[0], seen.last().unwrap());
    } else {
        for i in seen {
            println!("{} ", i);
        }
    }
}

fn solution(list: &[i32]) {
    let mut seen = Vec::new();
    for &i in list {
        match seen.last() {
            Some(&last) => {
                if i != last + 1 {
                    print_items(&seen);
                    seen.clear();
                }
                seen.push(i);
            }
            None => seen.push(i),
        }
    }
    print_items(&seen);
}

fn main() {
    solution(&[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}

Bu daha iyi:

fn print_items(slice: &[i32], from: usize, to: usize) {
    if to-from >= 2 {
        println!("({}: {}) ", slice[from], slice[to]);
    } else {
        for i in &slice[from..=to] {
            println!("{} ", i);
        }
    }
}

fn solution(list: &[i32]) {
    let (mut from, mut to) = (0, 0);
    for &i in &list[1..] {
        if list[to]+1 != i {
            print_items(list, from, to);
            from = to+1;
        }
        to += 1;
    }
    print_items(list, from, to);
}

fn main() {
    solution(&[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
}

Sanırım forum Rust kodu için renklendirmeye sahip değil @ismailarilik.

1 Beğeni

Soruda öyle bir durumdan söz edilmemişti ama mantıklı olan dediğiniz gibi olması
istenenlerde belirtmediği için ben küçükten büyüğe sıralı olmasını gözetmeksizin yazdım kodu

hmm… well…

1 Beğeni

Sahip. Zaten renklendirme yapmış. Bu arada 4 tik (`) yerine 3 tik kullanın.

1 Beğeni

from değişkenini kalın yazması ilginç gelmişti ama haklısınız sanırım.