blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
f377a1f4fcfd4935fde1612668bf91f07987c9e6 | katesorotos/module2 | /ch11_while_loops/ch11_katesorotos.py | 3,691 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 09:11:36 2018
@author: Kate Sorotos
"""
"""while loops"""
##############################################################################################
### Task 1 - repeated division
x = 33
while x >= 1:
print(x, ':', end='') #end'' is a parameter that prin... |
c5749efaac303d2f5d56dfdcaeadbb52869208c1 | katesorotos/module2 | /coding_bat/parrot_trouble.py | 419 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 12:27:13 2018
@author: Kate Sorotos
"""
We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.
def parrot_trou... |
8a5e362bb9373ae525010647cad68256dd5b5fa6 | katesorotos/module2 | /ch13_oop_project/MovingShapes.py | 2,681 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 17 16:31:34 2018
@author: Kate Sorotos
"""
from shape import *
from pylab import random as r
class MovingShape:
def __init__(self, frame, shape, diameter):
self.shape = shape
self.diameter = diameter
self.figure = Shape(shape, diameter)
... |
414745764aaa0191a4fbc6d86171e3ec14660124 | simonhej1/So4 | /Integral.py | 1,694 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import sympy as sy
import tkinter as tk
from tkinter import ttk
#a = float(input("hvad er a?:"))
#b = float(input("hvad er b?:"))
#c = float(input("hvad er c?:"))
#x = np.linspace(a, b, 100)
#y = np.sin(x)
#plt.figure()
#plt.plot(x, y)
#plt.show()
... |
130f6fcd0668496d386c59b445165adf369c44c0 | fsc2016/LeetCode | /code/36_二叉树最小深度.py | 2,126 | 3.671875 | 4 | '''
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
111. 二叉树的最小深度
'''
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self,root: TreeNode) -> i... |
316fbc12929968851b0b6e4f8054e0c0ef182428 | fsc2016/LeetCode | /code/3_三数之和.py | 1,340 | 3.59375 | 4 | '''
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
'''
from typing import *
def threeSum(nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []
if not nums or n<3:
return []
# 进行排序
nums.sort()
... |
1d8035d57a12007ed578bd052f8b140e1db527c3 | fsc2016/LeetCode | /11_bfs_dfs.py | 3,087 | 3.625 | 4 | from collections import deque
class Graph:
def __init__(self,v):
# 图的顶点数
self.num_v = v
# 使用邻接表来存储图
self.adj = [[] for _ in range(v)]
def add_edge(self,s,t):
self.adj[s].append(t)
self.adj[t].append(s)
def _generate_path(self, s, t, prev):
'''
... |
3dd1c0e006ed59e45039c4b49124ec3307aef4f8 | fsc2016/LeetCode | /code/22_数据流中第K大元素.py | 2,337 | 4.03125 | 4 | '''
设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10);... |
7b376a84ba18c6c6da384100816e6c205980f42d | fsc2016/LeetCode | /code/19_最大子序和.py | 867 | 3.78125 | 4 | '''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
'''
from typing import *
def maxSubArray(nums: List[int]) -> int:
'''
动态规划
:param nums:
:return:
'''
# n = len(nums)
# dp = [float('-inf')] * n
# dp[0] = nums[0]
... |
50df31500f9c57e0e829ea163af7987b93992705 | fsc2016/LeetCode | /code/24_包含min函数的栈.py | 1,935 | 4.09375 | 4 | '''
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
链接:https://leetcode-cn.com/problems/bao... |
13ab84b16c74da6f7f93a033dfb9b2f7c89dab6d | darshanrk18/Algorithms | /CountInversions.py | 903 | 3.828125 | 4 | import random
def merge(A,B):
(C,m,n)=([],len(A),len(B))
(i,j,c)=(0,0,0)
while i+j<m+n:
if i==m:
C.append(B[j])
j+=1
elif j==n:
C.append(A[i])
i+=1
elif A[i]<=B[j]:
C.append(A[i])
i+=1
else:
C... |
d359233240850fbff418284686c8e92a27397b62 | darshanrk18/Algorithms | /BucketSort.py | 1,779 | 3.90625 | 4 | import math
import string
import random
DEFAULT_BUCKET_SIZE = 5
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
while i>0 and arr[i]<arr[i-1]:
(arr[i-1],arr[i],i)=(arr[i],arr[i-1],i-1)
def sort(array, bucketSize=DEFAULT_BUCKET_SIZE):
f=0
if typ... |
e8da0a9a73fd0c0e29eb137c4c842bd002068081 | techphenom/casino-games | /blackjackTable.py | 4,706 | 3.75 | 4 | from random import shuffle
class Card(object):
def __init__(self, rank, suit, value, sort):
self.rank = rank
self.suit = suit
self.value = value
self.sort = sort
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
class Deck(object):
#A deck made of 52 cards.
suits = 'spades diamonds c... |
291abeb393225f43250c332941419b41c2c6a791 | hjpcs/sort_and_search | /algorithm/bubble_sort.py | 581 | 3.796875 | 4 | from algorithm.generate_random_list import generate_random_list
import timeit
# 冒泡排序
def bubble_sort(l):
length = len(l)
# 序列长度为length,需要执行length-1轮交换
for x in range(1, length):
# 对于每一轮交换,都将序列中的左右元素进行比较
# 每轮交换当中,由于序列最后的元素一定是最大的,因此每轮循环到序列未排序的位置即可
for i in range(0, length-x):
if l... |
c02250cb32fdc76bfc9b156893925fa852cafc8f | Robert66764/Task-Manager | /task_manager.py | 5,323 | 4 | 4 | #Displaying a message and prompting the user for information.
print('Welcome to the Task Manager.\n ')
usernames = input('Please enter Username: ')
passwords = input('Please enter Password: ')
#Opening the text file and splitting the username and password.
userfile = open ('user.txt', 'r+')
uselist = userfile.r... |
c6751727d0f6b20e1505c9007f2543a1f3fe108d | JeffCX/LadBoyCoding_leetcode_solution | /DFS/lc_261_graph_valid_tree.py | 1,132 | 3.578125 | 4 | class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
# Create Graph
graph_dic = {}
for start,end in edges:
if start not in graph_dic:
graph_dic[start] = [end]
else:
graph_dic[start].append(end)
... |
98de35a03755ceac1e2917c645df12a5997488cf | JeffCX/LadBoyCoding_leetcode_solution | /BinarySearch/lc_33_search_a_rotatedSorted_array.py | 1,143 | 3.609375 | 4 | class Solution:
def search(self, nums: List[int], target: int) -> int:
"""
O(logn)
"""
if not nums:
return -1
# 1. find where it is rotated, find the smallest element
left = 0
right = len(nums) - 1
while left ... |
418eb29659e375a2c38a3a478791ab71418eec17 | Flood-ctrl/mult_table | /mult_table.py | 2,485 | 3.703125 | 4 | #!/usr/bin/env python3
import sys, getopt, random
elementes = (2, 3, 4, 5, 6, 7, 8, 9)
wrong_answers = 0
re_multiplicable = None
re_multiplier = None
start_multiplicable = int(0)
test_question = int(0)
attempts = len(elementes)
passed_questions = list()
input_attempts = None
input_table = None
# Validate input argum... |
9cd79796786856ba4c4340a48a69f6110dc14a0c | mzmudziak/Programowanie-wysokiego-poziomu | /zajecia_9/zadanie_2.py | 282 | 3.609375 | 4 | import pdb
name = raw_input("Podaj imie: ")
surname = raw_input("Podaj nazwisko: ")
age = raw_input("Podaj wiek: ")
pdb.set_trace()
if age > 18:
ageMessage = 'PELNOLETNI'
else:
ageMessage = 'NIEPELNOLETNI'
print 'Czesc ' + name + ' ' + surname + ', jestes ' + ageMessage |
97a50afd5c942342feb0dbed098807615bf379eb | mzmudziak/Programowanie-wysokiego-poziomu | /zajecia_3/teoria.py | 1,171 | 3.921875 | 4 | # klasy
class Klasa:
def function(self):
print 'metoda'
self.variable = 5
print self.variable
def function2(self, number):
self.function()
print number
obiekt = Klasa()
obiekt.function2(100)
class Klasa2:
atrr1 = None
__attr2 = None
def setAttr2(self, z... |
1bfbc576fa5700f11711f258fb1e3f263d487eae | viharika-22/Python-Practice | /Problem-Set-5/13delcons.py | 189 | 3.78125 | 4 | s=list(input())
l=[]
for i in range(len(s)):
if s[i]=="i" or s[i]=="o" or s[i]=="a" or s[i]=="e" or s[i]=="u":
l.append(s[i])
else:
continue
print("".join(l)) |
7970d490d049a731b124994c9bec798830fd5732 | viharika-22/Python-Practice | /PlacementPractice/12.py | 118 | 3.765625 | 4 | str1="Gecko"
str2="Gemma"
for i in range(len(str1)):
if str1[i]==str2[1]:
print(str1.index(str1[i]))
|
8b822102bc23c07c004987c17718d9ba22347b48 | viharika-22/Python-Practice | /Problem-Set-5/new.py | 80 | 3.625 | 4 | s=input()
s1=""
for i in range(len(s)):
s1=s1+s[i]+"-"
print(s1)
|
0019a653229486d697e69a5a40519ccfa6e93503 | viharika-22/Python-Practice | /Problem Set-1/prob5.py | 153 | 3.828125 | 4 | n=str(input())
li=[]
for i in n:
li.append(i)
if li[::]==li[::-1]:
print("yes it is palindrome ")
else:
print("it isn't palindrome")
|
0b0a7902a8f300b3d73f77ae959ec938250e1744 | viharika-22/Python-Practice | /Problem-Set-5/5dectobinary.py | 82 | 3.5 | 4 | def db(n):
if n>1:
db(n//2)
print(n%2,end='')
db(int(input())) |
6782b6a51666db9062c5446b18dd229aa71041b3 | viharika-22/Python-Practice | /PlacementPractice/11.py | 108 | 3.953125 | 4 | n=input()
if n[::]==n[::-1]:
print("it is a palindrome")
else:
print("it is not a palindrome")
|
51632d0bba9edb151cff567dc5c7144361a9a97f | viharika-22/Python-Practice | /Patterns/7.py | 99 | 3.625 | 4 | n=1
for i in range(5):
for j in range(i):
print(n,end='')
n+=1
print() |
9c5afd492bc5f9a4131d440ce48636ca03fa721c | viharika-22/Python-Practice | /Problem-Set-2/prob1.py | 332 | 4.34375 | 4 | '''1.) Write a Python program to add 'ing' at the end of a given
string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3,
leave it unchanged.'''
n=input()
s=n[len(n)-3:len(n)]
if s=='ing':
print(n[:len(n... |
7503e23122425089e90b6d34ee3a2bf7cef0d51a | viharika-22/Python-Practice | /Problem-Set-6/gh10.py | 365 | 3.546875 | 4 | li1=["Arjun", "Sameeth", "Yogesh", "Vikas" , "Rehman","Mohammad", "Naveen", "Samyuktha", "Rahul","Asifa","Apoorva"]
li2= ["Subramanian", "Aslam", "Ahmed", "Kapoor", "Venkatesh","Thiruchirapalli", "Khan", "Asifa" ,"Byomkesh", "Hadid"]
fname=max(li1,key=len)
lname=max(li2,key=len)
longname=fname+" "+lname
print(long... |
a3f71d9b7b36d057cc1e9aedec93514e7000b682 | viharika-22/Python-Practice | /Problem-Set-6/h1.py | 203 | 3.59375 | 4 | n=int(input())
d={}
l=[]
li=[]
for i in range(n):
key=input()
d[key]=float(input())
for i in d.keys():
l.append([i,d[i]])
for i in range(len(l)):
li.append(l[i][1])
print(li)
|
d31a4b6f5ebbc1c8403d5cd898afb3d0c257b98e | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d62.py | 361 | 3.84375 | 4 | raz = int(input('Digite a razão da sua PA'))
prim = int(input('Digite o primeiro termo da sua PA'))
pa = 0
qnt = 1
recebe = 1
while recebe != 0:
total = recebe +10
while qnt != total:
pa = (prim)+raz*qnt
qnt = qnt + 1
print(pa,end='')
print(' > ',end='')
recebe = int(inpu... |
b61e8d17f1a9efa2909df39f5af3e43ef6314427 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d64.py | 207 | 3.96875 | 4 | soma = opcao = 0
while opcao != 999:
opcao = int(input('Digite um número ou digite 999 para parar'))
if opcao != 999:
soma += opcao
print(f'A soma de todos os números digitados foi {soma}') |
c59e1afb2d8afc09f020531c64fcdd349237aa61 | vitorgabrielmoura/Exercises | /Python 3/Jogos/forca.py | 3,358 | 3.5625 | 4 | import time
from random import randint
import string
def linha():
print(f'{"-"*60}')
def cabecalho(txt):
linha()
print(txt.center(60))
linha()
def criarLista(txt,list):
num = len(txt)
pos = 0
while True:
list.append("_")
pos += 1
if pos == num:
break
de... |
edf3f7438d8bb2fd005c6fec9214dac561de41f5 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d88melhorado.py | 496 | 3.5 | 4 | from random import randint
from time import sleep
print('MEGA SENA')
a1 = int(input('\nDigite quantos jogos você quer sortear'))
lista = []
dados = []
total = 1
while total <= a1:
count = 0
while True:
num = randint(1,60)
if num not in dados:
dados.append(num)
count += ... |
991c1f76de22d933924b507714b8f2046bf841de | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d25.py | 112 | 3.8125 | 4 | a1=input('Digite seu nome completo')
a2=a1.upper()
print(f"""O seu nome tem Silva?
Resposta: {'SILVA' in a2}""") |
f675b7ad77db93b4b4ae9219117d16c89eda4392 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d89.py | 798 | 3.859375 | 4 | lista = []
temp = []
while True:
temp.append(input('Digite o nome do aluno: ').capitalize())
temp.append(float(input('Nota 1: ')))
temp.append(float(input('Nota 2: ')))
lista.append(temp[:])
temp.clear()
resp = ' '
while resp not in 'SN':
resp = input('Quer continuar? [S/N]: ').upper... |
2319918a3682cb32256845bfcbbb09f26107a502 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d40.py | 423 | 3.984375 | 4 | print('ESTOU DE RECUPERAÇÃO?')
a1=float(input('\nDigite sua primeira nota'))
a2=float(input('Digite sua segunda nota'))
if (a1+a2)/2 <5:
print(f'\033[1;31mVocê está reprovado com nota final {(a1+a2)/2}')
elif (a1+a2)/2 >5 and (a1+a2)/2 <=6.9:
print(f'\033[7;30mVocê está de recuperação com nota final {(a1+a2)/2}... |
680a11e966b96a1f473247ff88750046a5aac8e1 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d82.py | 336 | 3.984375 | 4 | lista = []
while True:
lista.append(int(input('Digite um número')))
resp = str(input('Deseja continuar? [S/N]: ')).upper()
if resp == 'N':
break
print(f"""\nA lista completa é {[x for x in lista]}\nA lista de pares é {[x for x in lista if x % 2 == 0]}
A lista de ímpares é {[x for x in lista if x % 3... |
6fd6eca9714a2775c68b90acef5e8c2d8fa1bfd6 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d09.py | 253 | 3.875 | 4 | p1=float(input('Pick a number'))
n1=p1*1
n2=p1*2
n3=p1*3
n4=p1*4
n5=p1*5
n6=p1*6
n7=p1*7
n8=p1*8
n9=p1*9
print('The table of {} is'.format(p1))
print('1:{}\n2: {}\n3: {}\n4: {}\n5: {}\n6: {}\n7: {}\n8: {}\n9: {}\n'.format(n1,n2,n3,n4,n5,n6,n7,n8,n9))
|
5c55e9878f158a8a283d096347a299c185f66c04 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d73.py | 1,316 | 3.921875 | 4 | times = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico-PR', 'São Paulo', 'Internacional', 'Corinthians',
'Fortaleza', 'Goiás', 'Bahia', 'Vasco', 'Atlético-MG', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'CSA',
'Chapecoense', 'Avaí')
print(f"""\n{'='*30}
BRASILEIRÃO 2019 TABELA FINAL
{'='*30}
""")
while ... |
7d7273b8632e1f4d7ac7b9d9a94ae1e0f9b52a96 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d06.py | 154 | 4.15625 | 4 | n1=float(input('Pick a number'))
d=n1*2
t=n1*3
r=n1**(1/2)
print('The double of {} is {} and the triple is {} and the square root is {}'.format(n1,d,t,r)) |
20325275f6f0c1d011dc965f48b9af420ffd2d3f | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d30.py | 158 | 3.875 | 4 | print('### LEITOR DE PAR OU IMPAR ###')
print('\n')
a1=float(input('Digite um número'))
a2=a1%2
if a2 == 0:
print('É PAR!')
else:
print('É ÍMPAR') |
bd512cbe3014297b8a39ab952c143ec153973495 | CarolinaPaulo/CodeWars | /Python/(8 kyu)_Generate_range_of_integers.py | 765 | 4.28125 | 4 | #Collect|
#Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max)
#Task
#Implement a function named
#ge... |
80de26c35904fbd989d94270c407c16312aba74e | snehaldalvi/Stock_Prediction | /stock_price_prediction.py | 1,163 | 3.515625 | 4 | #stock-price-prediction#
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
df = pd.read_csv('infy.csv')
print(df.columns.values)
df['Open']=df['Open Price']
df['High']=df['High Price']
df['Low... |
23071a888fd6d9a059d8f11c3ab040f7bcb4415e | remo-help/Restoring_the_Sister | /concatenate.py | 6,217 | 3.609375 | 4 | # -*- encoding: utf-8 -*-
from itertools import chain, zip_longest
def read_in(textfilename): #this gives us a master read-in function, this reads in the file
file = str(textfilename) + '.txt'# and then splits the file on newline, and then puts that into a list
f = open(file, 'r',encoding='utf-8')# the list is retu... |
51626c3279abb8aa5b46e8815976cf73e61f0cba | Wondae-code/coding_test | /backjoon/정렬/quick_sort.py | 1,196 | 3.890625 | 4 | """
퀵 소트
1. 처음을 피벗으로 설정하고 자신 다음 숫자(왼쪽에서부터) 하나씩 증가하면서 자신보다 높은 숫자를 선택한다.
2. 오른쪽부터 진행하여 피벗보다 작은수를 선택한다.
3. 선택된 두 숫자의 위치를 변환한다.
4. 왼쪽과 오른쪽이 교차 하는 위치에 피벗을 가져다 놓고 왼쪽과 오른쪽을 다시 퀵 소트를 진행한다.
"""
array = [5,7,9,0,3,1,6,2,4,8]
def quick_sort(array, start, end):
if start >= end:
return
pivot = start
left ... |
528d2f290048598d640de14ce92a54c47c09817b | Wondae-code/coding_test | /leetcode/listnode.py | 1,408 | 4.0625 | 4 | class ListNode():
def __init__(self, val = None):
self.val = val
self.next = None
class LinkedList():
def __init__(self):
self.head = ListNode()
def add(self, data):
new_node = ListNode(data)
cur = self.head
while cur.next != None:
cur = cur.next... |
f4d10ed1bcbaef9319250d295668e3980da4230b | Wondae-code/coding_test | /backjoon/재귀함수/(2)(2447) 별찍기.py | 213 | 3.640625 | 4 | """
별찍기 -10
https://www.acmicpc.net/problem/2447
*********
"""
def print(x):
star = "*"
non_star = " "
test = x/3
if test != 1:
x/test
x = int(input())
# for i in range(1, x+1):
|
854f12abc5253e2a06e076cdffb22029208cb285 | ontodev/howl | /ontology/template.py | 755 | 3.71875 | 4 | #!/usr/bin/env python3
# Convert a TSV table into a HOWL file
# consisting of lines
# that append the header to the cell value.
import argparse, csv
def main():
# Parse arguments
parser = argparse.ArgumentParser(
description='Convert table to HOWL stanzas')
parser.add_argument('table',
type=argpar... |
5a3b4e2ca6d496a53b6b8e55c2f06ac1dbdec3aa | Byung-moon/Daily_CodingChallenge | /0418/bj1236.py | 697 | 3.71875 | 4 | #prob.1236 from https://www.acmicpc.net/problem/1236
N, M = map(int, input().split(" "))
array = []
for x in range(N):
array.append(input())
# Row Search
NeedRow = len(array)
for x in range(len(array)):
for y in range(len(array[0])):
if array[x][y] == 'X':
NeedRow -= 1
... |
d9d86188c2f37c16dd1b0a3afdcf03cb5223035c | sakshiguj/list | /list print.py | 67 | 3.59375 | 4 |
list=[15,58,20,2,3]
i=0
while i<len(list):
i=i+1
print(list)
|
adcad46d8b5e27a20b1660861e8316f9c7044eab | zingpython/Common_Sorting_Algorithms | /selection.py | 594 | 4.125 | 4 | def selectionSort():
for element in range(len(alist)-1):
print("element", element)
minimum = element
print("minimum", minimum)
for index in range(element+1,len(alist)):
print("index",index)
if alist[index] < alist[minimum]:
print("alist[index]",alist[index])
print("alist[minimum]",alist[minimum])... |
aedf273538698ee9f6c20eb141afe5e3b81f8742 | xlr10/pyton | /190729/190729_03.py | 1,351 | 3.984375 | 4 | # class
print("class")
print()
class FourCal:
class_num = 1;
def __init__(self, first, second):
self.first = first
self.second = second
# def __init__(self, first, second):
# self.first = first
# self.second = second
# def setNum(self, first, second):
# self.... |
0a2c9e6e590cdcb76d761822d6d9fa92afabf659 | xlr10/pyton | /190729/example_01.py | 1,400 | 3.90625 | 4 | ###################### 01
print()
print("example 01")
def is_odd(num):
if num % 2 == 1:
print("%d is Odd" % num)
else:
print("%d is Even" % num)
is_odd(1)
is_odd(2)
###################### 02
print()
print("example 02")
def average_serial(*args):
result = 0
for i in args:
... |
1c9b024feb7296496fa5fe37b65844895f6d858e | JiangNanYu639/python-project | /Question 2.py | 1,846 | 4.0625 | 4 | class Time():
def __init__(self, hour, minutes):
self.hour = hour
self.minutes = minutes
@property
def hour(self):
return self.__hour
@hour.setter
def hour(self, h):
if h >= 0 and h <= 23:
self.__hour = h
else:
raise Val... |
5b0719eba5b442343ab31e241083ba6cd54c5b9c | JiangNanYu639/python-project | /HM0226.2.py | 439 | 3.59375 | 4 | # 大乐透游戏,给你的6位数,中奖码是958 (9 5 8可以在6位数中任意位置,都存在) ,如何判断自己中奖?
n = input('Pls type your number: ')
a = '9'
b = '5'
c = '8'
length = len(n)
if n.isdigit() and length == 6:
if n.find(a) != -1 and n.find(b) != -1 and n.find(c) != -1:
print('You win!')
else:
print('Sorry.')
else:
pri... |
4473702e806d184a6189e699bb8fc65352640661 | fjnajasm/PLN | /PRACTICA 1/Ejercicio2.py | 741 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:02:32 2020
@author: fran
"""
def listas(a, b):
lista_final = []
for i in a:
if(i not in lista_final) and (i in b):
lista_final.append(i)
return lista_final
def comprueba(a):
try:
for i in a:
... |
614513ba35b93e4c5d2c7a8ee6a22e4ad1f5d424 | Neecolaa/tic-tac-toe | /tictactoe.py | 4,761 | 3.65625 | 4 |
class gameBoard:
def __init__(self, size):
self.size = size
self.board = [[' '] * size for i in range(size)]
self.cellsFilled = 0
def printBoard(self):
rows = list(map(lambda r: " "+" | ".join(r), self.board))#generates list of rows with |
#^idk if this is the b... |
632b8b79e60f6a1ef17c8bc4165fab17b262211c | siddhantpushpraj/Python_Basics- | /reimport.py | 4,109 | 4.1875 | 4 | import re
###
'''
if re.search('hi(pe)*','hidedede'):
print("match found")
else:
print("not found")
'''
###
'''
pattern='she'
string='she sells sea shells on the sea shore'
if re.match(pattern,string):
print("match found")
else:
print("not found")
'''
###
'''
pattern='sea'
string='... |
1395e5ded5679ceb8a5c607b36a04e647a407147 | siddhantpushpraj/Python_Basics- | /class.py | 2,929 | 4.1875 | 4 | '''
class xyz:
var=10
obj1=xyz()
print(obj1.var)
'''
'''
class xyz:
var=10
def display(self):
print("hi")
obj1=xyz()
print(obj1.var)
obj1.display()
'''
##constructor
'''
class xyz:
var=10
def __init__(self,val):
print("hi")
self.val=val
print(val... |
f0229a16a7d08489515081689675a77e2066e348 | siddhantpushpraj/Python_Basics- | /even odd.py | 976 | 4.0625 | 4 | '''
#even odd
a=int(input("enetr a number"))
b=int(input("enetr a number"))
if(a%2==0):
print("even")
for i in range(a,b+1,2):
print(i)
print("odd")
for i in range(a+1,b,2):
print(i)
for i in range(a,b+1):
if(i%2==0):
print(i,"even")
else:
p... |
27bc28f5e960f4fc56360ad19a4f838b06a95813 | Andyporras/portafolio1 | /cantidadDeNumerosPares.py | 1,059 | 3.90625 | 4 | """
nombre:
contadorDepares
entrada:
num: numero entero positivo
salidad:
cantidad de numero pares que tiene el numero digita
restrinciones:
numero entero positivo mayor a cero
"""
def contadorDepares(num):
if(isinstance(num,int) and num>=0):
if(num==0):
return 0
eli... |
f75dbfe00e001bbbebae43f2ed56c4b8d5098028 | ferrakkem/Complete_codingbat_problem_Python | /app.py | 27,994 | 4.25 | 4 | '''
The parameter weekday is True if it is a weekday,
and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation.
Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True
'''
def sleep_in(weekday, vacatio... |
d3b72253c5aad86dcff61d706444521bdf67be76 | Anas2-L/Projects | /2ndhighest.py | 301 | 3.875 | 4 | def secondhigh(list1):
new_list=set(list1)
new_list.remove(max(new_list))
return max(new_list)
list1=[]
n=int(input("enter list size "))
for i in range(n):
x=input("\nenter the element ")
list1.append(x)
print("original list\n",list1)
print(secondhigh(list1))
|
86b4a2b74893cb40f1e19f469d059be178b838cc | Anas2-L/Projects | /extractdigits.py | 176 | 3.984375 | 4 | num=int(input("Enter a number"))
temp=num
while (temp>=1):
if(temp%10==0):
print(0)
else:
print(int(temp%10))
temp=int(temp/10)
print(num) |
600ef001b64ebd30b8687ab622b9e7549f714437 | MaX-Lo/ProjectEuler | /116_red_green_blue_tiles.py | 1,313 | 3.640625 | 4 | """
idea:
"""
import copy
import time
# 122106096, 5453760
def main():
max_row_len = 50
print('row length:', max_row_len)
if max_row_len % 2 == 0:
start = 2
combinations = 1
else:
combinations = 0
start = 1
for gaps in range(start, max_row_len-1, 2): # step 2 beca... |
ff5a073e2083ce23400d787e87907011818b01c6 | MaX-Lo/ProjectEuler | /035_circular_primes.py | 1,284 | 3.75 | 4 | """
Task:
"""
import time
import primesieve as primesieve
def main():
primes = set(primesieve.primes(1000000))
wanted_nums = set()
for prime in primes:
str_prime = str(prime)
all_rotations_are_prime = True
for rotation_num in range(len(str_prime)):
str_prime = str_... |
53161d215504eeb7badb8105197bd926091b971b | MaX-Lo/ProjectEuler | /074_digit_factorial_chains.py | 696 | 3.734375 | 4 | """
idea:
"""
import time
import math
def main():
t0 = time.time()
count = 0
for i in range(1, 1000000):
if i % 10000 == 0:
print('{}%, {}sec'.format(i / 10000, round(time.time() - t0), 3))
if get_chain_len(i) == 60:
count += 1
print('wanted num:', count)
... |
2e9c25015e590a2139ab7e423d23ab8402a941be | MaX-Lo/ProjectEuler | /helpers_inefficient.py | 2,442 | 3.828125 | 4 |
def all_primes(limit):
segment_size = 20000000
if limit <= segment_size:
return primes_euklid(limit)
primes = primes_euklid(segment_size)
iteration = 1
while limit > segment_size * iteration:
print("progress, at:", segment_size * iteration)
start = segment_size*iteration... |
72a56a90e4a26e0f1423c95f5d517a07eade3e5d | MaX-Lo/ProjectEuler | /061_cyclical_figurate_numbers.py | 3,131 | 3.640625 | 4 | """
idea:
"""
import time
def main():
# lists containing 4-digit polygonal numbers as strings
triangles = generate_figurate_nums(1000, 10000, triangle)
squares = generate_figurate_nums(1000, 10000, square)
pentagonals = generate_figurate_nums(1000, 10000, pentagonal)
hexagonals = generate_figurate... |
6f71761903964bc4431f50a80a58665eb926749b | MaX-Lo/ProjectEuler | /549_divisibility_of_factorials.py | 1,718 | 3.671875 | 4 | """
idea:
"""
import time
import math
import primesieve
def main():
limit = 10**8
primes = primesieve.primes(limit)
primes_s = set(primes)
# key: (prime^power), value: s(prime^power)
cache = dict()
for prime in primes:
power = 1
while prime ** power < limit:
fac = ... |
a3bc3257a40b563f88fae09094d1b2de401d4d6f | MaX-Lo/ProjectEuler | /005_evenly_divisible.py | 639 | 3.609375 | 4 | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import time
def main():
start = time.time()
# n=20 > 26.525495767593384, >232792560
n = 969... |
b1631d263871aaeaa21ed313eefa8ab8f9c2326a | MaX-Lo/ProjectEuler | /102_triangle_containment.py | 1,835 | 3.6875 | 4 | """
idea:
"""
import time
def main():
data = read_file('102_triangles.txt')
count = 0
#print(contains_origin([-340, 495, -153, -910, 835, -947]))
for triangle in data:
print(contains_origin(triangle))
if contains_origin(triangle):
count += 1
print('count:', count)
... |
7abf47c117213f72142f2bb9daeaaffe0cf58de4 | MaX-Lo/ProjectEuler | /034_digit_factorials.py | 406 | 3.6875 | 4 | """
Task:
"""
import time
import math
def main():
wanted_nums = []
for i in range(3, 1000000):
num_sum = 0
for digit in str(i):
num_sum += math.factorial(int(digit))
if i == num_sum:
wanted_nums.append(i)
print(wanted_nums)
if __name__ == '__main__':... |
b17f9bb2ee4cc729989a34c3631f53961fc450f8 | MaX-Lo/ProjectEuler | /106_special_subset_sums_meta_testing.py | 2,005 | 3.578125 | 4 | """
idea:
"""
import copy
import time
import itertools
import math
def main():
sets = [
[1], # 1
[1, 2], # 2
[2, 3, 4], # 3
[3, 5, 6, 7], # 4
[6, 9, 11, 12, 13], # 5
[11, 18, 19, 20, 22, 24], # 6
[47, 44, 42, 27, 41, 40, 37], # 7
[81, 88, 75... |
0fe3da6717019161da1ef5c1d3b1bbb451299b30 | MaX-Lo/ProjectEuler | /064_odd_period_square_roots.py | 950 | 3.984375 | 4 | """
idea:
"""
import time
import math
def main():
num_with_odd_periods = 0
for i in range(2, 10001):
if math.sqrt(i) % 1 == 0:
continue
count = continued_fraction(i)
if count % 2 == 1:
num_with_odd_periods += 1
print('rep len for {}: {}'.format(i, count... |
f31fcec47d734feaf6f5d680b6625e88acaa1048 | MaX-Lo/ProjectEuler | /039_integer_right_triangles.py | 1,453 | 3.828125 | 4 | """
idea:
"""
import time
import math
def main():
p_with_max_solutions = -1
max_solutions = -1
for perimeter in range(1, 1001):
print(perimeter)
wanted_nums = []
a = 0
b_and_c = perimeter
while b_and_c >= a:
b_and_c -= 1
a += 1
... |
de55784264f1f52758efe3b09550520df5be25c1 | MaX-Lo/ProjectEuler | /119_digit_power_sum.py | 711 | 3.640625 | 4 | """
idea:
"""
import time
import math
def main():
upper_limit = 10**13
found_nums = []
for x in range(2, int(math.sqrt(upper_limit))):
if x % 100000 == 0:
print('prog:', x)
p = x
while p < upper_limit:
p *= x
if digit_sum(p) == x:
... |
65298718ef4f0c1af6cc574f2d9aba856412af29 | itCatface/idea_python | /py_pure/src/catface/introduction/04_functional_programming/3_lambda.py | 509 | 3.90625 | 4 | # -匿名函数
# --ex1
l = [1, 3, 5, 7, 9]
r = map(lambda x: x * x, l)
print(list(r))
# --ex2
print('匿名函数结果:', list(map((lambda x: x * 2), l)))
# --ex3. 可以把匿名函数作为返回值返回
f = lambda x, y: x * y
print('使用匿名函数计算:', f(2, 3))
# lambda x: x * x --> def f(x): return x * x
# --ex4. 改造以下代码
def is_odd(n):
return n % 2 == 1
L ... |
67d1cde085301b30592e61152369c2609144305a | itCatface/idea_python | /py_pure/src/catface/introduction/06_oo_junior/2_access_restrict.py | 864 | 3.96875 | 4 | # -访问限制
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
# 检查分数
def set_score(self, score):
if 0 <= score <= 100:
... |
b5e51529e0c68b4c5d3879f9c034ce8540fadeab | itCatface/idea_python | /py_pure/src/catface/introduction/07_oo_senior/2_property.py | 1,692 | 3.890625 | 4 | # -@property[既能检查参数,又可以用类似属性这样简单的方式来访问类的变量]
# 常规getter&setter
class Student(object):
def __init__(self):
pass
def set_score(self, score):
if not isinstance(score, int):
raise ValueError('score must be an integer')
if score < 0 or score > 100:
raise ValueError(... |
d2feee5ec35d4bf4575cf61a98bf6d62ef9fb771 | itCatface/idea_python | /py_pure/src/catface/introduction/01_base/5_for.py | 1,222 | 3.765625 | 4 | # -循环
def test_for():
# for
nums = (1, 2, 3, 4, 5)
sum = 0
for x in nums:
sum += x
print(sum) # 15
for i, v in enumerate(nums):
print('第%d个位置的值为%d' % (i, v)) # 第0个位置的值为1\n第1个位置的值为2...
# range
nums = list(range(10)) # range(x): 生成一个整数序列 | list(range(x)): 通过list()将整数序列转... |
262604114db21368103f6c8e670fa17d1b640bed | dante092/Caesar-Cypher | /kassuro.py | 5,718 | 4.3125 | 4 |
#!/usr/bin/python3
def encrypt(string, rotate):
"""
Encrypt given input string with the caeser cypher.
args:
string (str): string to encrypt.
rotate (int): number by whiche the characters are rotated.
returns:
str: encrypted version of the input string.
raises... |
db18e85eb77c5d672ef397b4f21560e92a7ef5ad | johan-eriksson/advent-of-code-2019 | /src/day7.py | 5,242 | 3.5625 | 4 | import itertools
import math
class Computer():
def __init__(self, phase):
self.OPCODES = {
1: self.ADD,
2: self.MUL,
3: self.WRITE,
4: self.READ,
5: self.JNZ,
6: self.JEZ,
7: self.LT,
8: self.EQ,
99: self.EXIT
}
self.input = []
self.input.append(phase)
self.phase = phase
self.la... |
80643111235604455d6372e409fa248db684da97 | s56roy/python_codes | /python_prac/calculator.py | 1,136 | 4.125 | 4 | a = input('Enter the First Number:')
b = input('Enter the Second Number:')
# The entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
sum = float(a)+float(b)
print(sum)
print('The sum of {0} and {1} is {2}'.format(a, b, sum))
print('This is output to the ... |
b55313c576269b2fe93fc708e12bf74966886521 | MColosso/Wesleyan.-Machine-Learning-for-Data-Analysis | /Week 4. Running a k-means Cluster Analysis.py | 7,015 | 3.6875 | 4 | #
# Created on Mon Jan 18 19:51:29 2016
#
# @author: jrose01
# Adapted by: mcolosso
#
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
from sklearn.cluster import KMeans
pl... |
e890b55a98130e34004f3ad15e02b8993aadf55b | eudaimonious/LPTHW | /ex4.py | 1,485 | 4 | 4 | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
pri... |
1aaec58e360a3897542886686250694e7971b308 | yesiamjulie/pyAlgorithm | /AlgoTest/Passing_bridge.py | 617 | 3.53125 | 4 | def solution(bridge_length, weight, truck_weights):
answer =0
waiting = truck_weights
length_truck = len(truck_weights)
passed = []
passing = []
on_bridge = []
while len(passed) != length_truck:
for i in range(len(passing)):
passing[i] += - 1
if passing and pass... |
145a53662de78fc1e68618010034705f73b44d62 | yesiamjulie/pyAlgorithm | /AlgoTest/SumOfTwoN.py | 518 | 3.59375 | 4 | """
서로 다른 자연수들로 이루어진 배열 arr와 숫자 n이 입력으로 주어집니다.
만약 배열 arr에 있는 서로 다른 2개의 자연수를 합하여 숫자 n을 만드는 것이 가능하면 true를, 불가능하면 false를 반환하는 함수를 작성하세요.
"""
def solution(arr, n):
answer = False
length = len(arr)
for i in range(length - 1):
for j in range(i + 1, length):
if arr[i] + arr[j] == n:
... |
d1a4bffe153eaaffde01f1bc0f07bb9fe8646941 | gurralaharika21/toy-problems | /LRU-oops/Lru_cache.py | 1,290 | 3.5625 | 4 | import collections
# import OrderedDict
class LRUCache:
# dict = {}
def __init__(self,capacity :int):
self.capacity = capacity
self.cache = collections.OrderedDict()
def put(self,key:int,value:int):
try:
self.cache.pop(key)
except KeyError:
if len(se... |
3a0af90aa6b19e7c73245e6724db18fb050aef7d | JinhuaShen/Python-Learning | /CalcCount.py | 1,038 | 3.640625 | 4 | import csv
import re
import sqlite3
def genInfos(file):
csvfile = open(file, 'r')
reader = csv.reader(csvfile)
seeds = []
for seed in reader:
seeds.append(seed)
csvfile.close()
return seeds
def showInfos(infos):
result = open("result.txt", 'w')
... |
15b45688390a72bdb74852f76cee51101ef1193e | ykcai/Python_ML | /homework/week11_homework.py | 679 | 3.890625 | 4 | # Machine Learning Class Week 11 Homework
# 1. An isogram is a word that has no repeating letters, consecutive or nonconsecutive. Create a function that takes a string and returns either True or False depending on whether or not it's an "isogram".
# Examples
# is_isogram("Algorism") ➞ True
# is_isogram("PasSword") ➞ F... |
69f49e0d03340dbbe2a4cdf5d489d884d2fe5b53 | ykcai/Python_ML | /homework/week8_homework.py | 599 | 3.890625 | 4 | # Machine Learning Class Week 8 Homework
import numpy as np
# 1. Create an array of 10 zeros
# 2. Create an array of 10 ones
# 3. Create an array of 10 fives
# 4. Create an array of the integers from 10 to 50
# 5. Create an array of all the even integers from 10 to 50
# 6. Create a 3x3 matrix with values ranging... |
9060d68c59660d4ee334ee824eda15cc49519de9 | ykcai/Python_ML | /homework/week5_homework_answers.py | 2,683 | 4.34375 | 4 | # Machine Learning Class Week 5 Homework Answers
# 1.
def count_primes(num):
'''
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25
By convention, 0 and 1 are not prime.
'''
# Write your code here
#... |
0629cc2ce905a9bcb6d02fdf4114394d8e9ab6dc | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/coinimport.py | 599 | 3.8125 | 4 | # This program imports the ocin module and creates an instance of the Coin Class
# needs to be the file name or file path if in a different directory
import coin
def main():
# create an object from the ocin class
# needs the filename.module
my_coin = coin.Coin()
# Display the side of the coin... |
e25a8fc38ef3e98e5dc34aae30fbbea316e709c2 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/3.py | 1,029 | 4.21875 | 4 | # 3. Budget Analysis
# Write a program that asks the user to enter the amount that he or she has budgeted for amonth.
# A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total.
# When the loop finishes, the program should display theamount that the user is ov... |
2b1cf90a6ed89d0f5162114a103397c0f2a211e8 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/iter.py | 612 | 4.25 | 4 | # Python iterators
# mylist = [1, 2, 3, 4]
# for item in mylist:
# print(item)
# def traverse(iterable):
# it = iter(iterable)
# while True:
# try:
# item = next(it)
# print(item)
# except: StopIteration:
# break
l1 = [1, 2, 3]
it ... |
b62ba48d92de96b49332b094f8b34a5f5af4a6cb | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/map.py | 607 | 4.375 | 4 | # The map() function
# Takes in at least 2 args. Can apply a function to every item in a list/iterable quickly
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
squarelist = map(square, numbers)
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(nex... |
8abfe167d6fa9e524df27f0adce9f777f4e2df58 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/5.py | 1,278 | 4.5625 | 5 | # 5. Average Rainfall
# Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years.
# The program should first ask for the number of years. The outer loop will iterate once for each year.
# The inner loop will iterate twelve times, once for each month. Each ite... |
60f890e1dfb13d2bf8071374024ef673509c58b2 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 1.py | 1,870 | 4.59375 | 5 | """
1. Employee and ProductionWorker Classes
Write an Employee class that keeps data attributes for the following pieces of information:
• Employee name
• Employee number
Next, write a class named ProductionWorker that is a subclass of the Employee class. The
ProductionWorker class sho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.