blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f35466067db7d3a3c456b0ec7e533ffd7413c328 | silvuple/w3resource.com-python-exercises | /data_structures_exercises_python.py | 12,850 | 4.78125 | 5 | """
1. Write a Python program to create an Enum object and display a member name
and value.
Sample data :
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
Expected Output :
Member name: Albania
Member value: 355
"""
from enum import Enum
class Country(Enum):
Afghanistan = 9... |
7925ed2b9ad7b2d42081d1d470bb151c1027cb4d | TobiasScholl/tptp | /tptp/utils/concurrent/process.py | 3,009 | 3.578125 | 4 | class NotYetStartedError(Exception):
pass
class Process:
def isStarted(self) -> bool:
"""
Whether to process has already been started.
"""
raise NotImplementedError()
def isRunning(self) -> bool:
"""
Whether the process is currently running.
"""
... |
7fcf9da4f01605dd35684042dfc80f100d1666b0 | TobiasScholl/tptp | /tptp/utils/concurrent/timer.py | 2,887 | 3.609375 | 4 | import time
class Timer:
def __init__(self):
self.scheduledTime = None
self.startTime = None
self.endTime = None
def schedule(self):
if self.scheduledTime is not None:
raise Exception(self.scheduledTime)
if self.startTime is not None:
raise Excep... |
1cbd5a4f962f5896cbd586e30dcc86e26037ee0c | Georycoco/pythonTutorial | /python基础/14.py | 1,221 | 4.28125 | 4 | # student list table
print('--------Student List--------')
print('1: Add a new student')
print('2: Delete a student')
print('3: Edit a student')
print('4: View a student')
print('5: Exit')
print('----------------------------')
student_List = [];
name = ['George','John','Tim'] # add new names
while True:
sele... |
14615930af30f4cf941c075d3f5a1b8aafa2ebe9 | Georycoco/pythonTutorial | /python基础/32.py | 1,639 | 3.828125 | 4 | class Dog(object):
# __init___()方法初始化对象,__new__()方法创建对象
def __init__(self):
pass
def __del__(self):
pass
def __str__(self):
print('string method')
return 'describtion of method'
def __new__(cls):
print('new method...')
return object.__new__(cls)
a... |
8b2629c4cb5a5087ff142d66d857e170ae0cd801 | Georycoco/pythonTutorial | /python基础/09.py | 248 | 3.625 | 4 | #9*9 乘法表格
max = input('please enter a number less than 9: ');
i = 1;
max_Num = int(max);
while i <=max_Num:
j=1;
while j <= i:
print('%d*%d=%d\t'%(j,i,i*j),end='');
j+=1;
print('');
i+=1;
print('end~~'); |
c6e46bda6e2231eaebfcd133090d9b637666f3c4 | yoghurthoek/sunny_storage | /Classes/node.py | 515 | 3.5 | 4 | class Node(object):
"""Node object"""
def __init__(self):
self.batts = [[], [], [], [], []]
self.fill = [[0], [0], [0], [0], [0]]
self.price = 0
self.level = 0
self.lowbound = 0
def fillnode(self, b, h, price):
for battery in b:
self.fill[battery... |
db65bfbe3000002392c784cc8693678381b29191 | andrew-qu2000/Schoolwork | /cs1134/sort_first.py | 351 | 3.515625 | 4 | def sort_first(lst):
first = lst[0]
low = 1
high = 1
count = 0
while(high < len(lst)): #n
if(lst[high] > first):
high += 1
else:
lst[low],lst[high] = lst[high],lst[low]
low += 1
high += 1
count += 1
lst.remove(first) #n
... |
e4e4602945b4d152852ca6d24c746ab039808850 | andrew-qu2000/Schoolwork | /cs1134/product_evens.py | 268 | 3.921875 | 4 | def product_evens(n):
if(n % 2 != 0):
n -= 1;
if(n == 0):
return 0;
if(n == 2):
return 2;
else:
return n * product_evens(n-2);
for i in range(10):
print("n= " + str(i) + " product_evens= " + str(product_evens(i)));
|
951c359501797e91a59f950cd02a4a0ee605cc86 | andrew-qu2000/Schoolwork | /cs1134/is_sum_balanced.py | 419 | 3.5625 | 4 | import LinkedBinaryTree
def is_sum_balanced(bin_tree):
def is_subtree_sum_balanced(subtree_root):
if subtree_root is None:
return True
else:
balanced = abs(subtree_root.left - subtree_root.right) <= 1
return balanced and is_subtree_sum_balanced(subtree.root.left)... |
b8bbae7f49f257c1ef3a583da41882b234861b68 | sudhuke/leetcode | /python/longest_substring.py | 2,058 | 3.71875 | 4 | class Solution:
def lengthOfLongestSubstring(self, str):
mystring = str
length = len(mystring)
print(length)
count = 0
next_count = 1
string_list = list(mystring)
if length == 0:
return 0
substring = mystring[0]
final_list = []
... |
5532f57f7b832d29476cbe4edbb65408340643f7 | summerlinrb/assignment-python-chapter-5 | /assignment-python-chapter-5-summerlinrb/app2.py | 3,751 | 4.40625 | 4 | # Edit this file according to the instructions
# Import various modules needed for this lesson
from random import random
from array import array
from collections import deque
# start coding below this line
# Chapter 5.8 Lambda Functions
print("\n Chapter 5.8 Lambda Functions" + "-" * 20)
items = [
("Pr... |
224107c2251effdd3b4b937365083d22705a3f70 | DineshDowney/NewRep | /bst.py | 1,044 | 3.921875 | 4 | class node1(object):
def __init__(self,data):
self.data=data
self.left=None
self.right=None
class Binary(object):
def __init__(self):
self.root=None
def ins(self,data):
if not self.root:
self.root=node1(data)
else:
self.insertN(data,sel... |
c634fbe856562a98b150ec8eb418a0fdc9dc1d3d | ess-dmsc/just-bin-it | /just_bin_it/utilities/plotter.py | 1,469 | 3.734375 | 4 | import numpy as np
from matplotlib import colors
def plot_histograms(histograms, log_scale_for_2d=False):
"""
Plot the histograms.
:param histograms: The histograms to plot.
"""
import matplotlib
matplotlib.use("Qt5Agg")
from matplotlib import pyplot as plt
fig = plt.figure(1)
... |
1e22027ac15ce4dcf81dba08fc2bd17ac86fdaaa | cronin101/TTS-Assignment-1 | /src/tokenize_test.py | 1,587 | 3.640625 | 4 | from tokenize import StringTokenizer
import unittest
class TestStringTokenizer(unittest.TestCase):
def test_tokenizing_just_words(self):
'''The leading number should become the sample number and
the remaining tokens should be downcased'''
just_words = StringTokenizer('1 The cow jumped over the moon')
... |
ee7bee5907155e85e78eb3959773c51ff017109f | GrahamWhyte/Motor-Project | /inerative_setpoints.py | 4,426 | 4.0625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# PARAMS
DEBUG = True
X_LIM = 26 # this is the number of x positions we have aka x resolution
Y_LIM = 19 # this is the number of y positions we have aka y resolution
MAX_SET_POINTS = np.inf # Max number of set points we want the user to be able t... |
22e05297e8410017c6725b7990c3ad06d167e96f | Rogerc007/Aulas-de-Phyton | /phy_exer7.py | 325 | 4.1875 | 4 | #Exercício 07 do estudo dirigido (calcular o delta).
print("----------CALCULADORA DE DELTA----------")
A = float(input("Digite o primeiro número: "))
B = float(input("Digite o segundo número: "))
C = float(input("Digite o terceiro número: "))
delta = B ** 2 - 4 * A * C
print("O valor do Delta é", delta)
|
459d24f65644b890f91f5df65a29b2b8c405077b | Inc0mple/fcc-mean-var-std | /mean_var_std.py | 979 | 3.796875 | 4 | import numpy as np
def calculate(lst):
if type(lst) is not list:
raise TypeError("Input must be of list type.")
if len(lst) != 9:
raise ValueError("List must contain nine numbers.")
three_by_three = lambda x: [[x[0],x[1],x[2]],[x[3],x[4],x[5]],[x[6],x[7],x[8]]]
data_arr = np.array(... |
07563328e4e6410691c591a6330df5da48703503 | Kavi1808/beginer-1 | /max among 10 numbs.py | 77 | 3.625 | 4 | a=[5,2,1,6,7,8,10,21,4,9]
max=0
for i in a:
if i>max:
max=i
print max
|
09241da92a4ff0052a014b346dd5ebb56b9d72af | Wrongsides/Battleships | /battleships/Battleship.py | 676 | 3.640625 | 4 | from battleships.GameBoard import GameBoard
from battleships.Controller import Controller
print("Let's play Battleship!")
board = GameBoard(5)
control = Controller(board)
board.print_board()
ship = {"row": board.random_row(), "col": board.random_col()}
for turn in range(4):
print("Turn", turn + 1)
guess =... |
7aba5936ee4bc6b2e546ba52473e946798b5d07d | AkitaFriday/dataStructure | /stackAndQueue/stack.py | 1,699 | 4 | 4 | # 自定义异常类
class StackUnderFlowError(ValueError):
def getMessage(self):
print("栈空异常")
# 栈的顺序表实现类
class Stack_lineTable(list):
# 初始化时初始化一个空list, 利用python内置的list实现栈
def __init__(self):
self.stack = list()
# 判断栈空
def is_empty(self):
return self.stack == []
# 入栈操作
def pus... |
20ad19c1d54800a43f61e7a4d758ccfc2e5f9460 | AkitaFriday/dataStructure | /linkedList/josephusByLine.py | 2,195 | 3.703125 | 4 | """
用线性表实现一下约瑟夫环问题,
约瑟夫环问题: n个小朋友围成了一圈,从第k个人报数,类似于击鼓传花,
到第m个人,就把他拉出来挠脚心,然后从下个人继续报数,按照一样的规则退出,
直到所有人都被拉走,这时候列出各个出列的小朋友的编号
解决思路:
1. 建立一个n个元素的表
2. 找到第k个人开始
3. 向后数m个,然后把当前下标元素置0,遇到表的结尾,则从下标0开始循环
4. n个元素都出列,结束循环
"""
from circleLinkList import *
# 基于数组概念的解
def josephus_array(n , k, m):
# n: 总人数 k: 开始的人 m : 弹出操作... |
837c524edaba0bd39e6e307b61245424d5d47339 | AkitaFriday/dataStructure | /tree/huffManTree.py | 1,747 | 3.765625 | 4 | """
哈夫曼树
哈夫曼树构造的思路:
1. 先把指定集合的所有元素建立成单点二叉树,二叉树根节点的权值为元素值
2. 把所有的单点二叉树放到优先队列中,排序规则按照根节点权值大小
3. 从优先队列中出队两个权值最小的二叉树,构建一个新的二叉树,新二叉树根节点的权值为左右子树根节点权值的和
4. 新二叉树入优先队列
5. 重复 3,4步骤直到优先队列中只剩下一个元素
6. 出队元素
"""
from BinTree import *
from priorityQueue import *
# 对二叉树节点类的扩充
cla... |
b32f5e081c39fc3898754084bf6a15df10b5a8c3 | rursvd/pynumerical | /6_10.py | 115 | 3.703125 | 4 | from numpy import array
a = array([1,2,3,4,5])
print('a[1] = ',a[1])
print('a[3] = ',a[3])
print('a[-1] = ',a[-1])
|
d068b655abc1f93d5b3226c90a4cf9512c6f6421 | alastairrushworth/inspectpd | /inspectpd/inspect/inspect_types.py | 1,446 | 3.53125 | 4 | import pandas as pd
import numpy as np
from inspectpd.inspect_object.inspect_object import inspect_object
# inspect_types
def inspect_types(df) :
'''
Summary and comparison of numeric columns
Parameters
----------
df: A pandas dataframe.
Returns
----------
A pandas dataframe with colum... |
7d607417d05d009aef99971f0e5b0cfba43e739a | thalescomp/topcom | /Jardim/gen_in.py | 437 | 3.703125 | 4 | from random import randint
MAX_POINTS = 1000
for i in xrange(0, 500):
N = randint(3, MAX_POINTS)
print N
points = set()
while len(points) < N:
a = randint(0, 2**10)
b = randint(0, 2**10)
points.add((a,b))
for x,y in points:
print x, y
N = MAX_POINTS
print N
points = set()
while len(points)... |
cd81c85e9f136580ff79f658643bbb2d368af91e | JiaxianGu/algorithm-and-data-structure | /leetcode/53/53.py | 437 | 3.859375 | 4 | def maxSubArray(nums):
max_num = max(nums)
if max_num <= 0:
return max_num
else:
max_num = nums[0]
f = [0] * len(nums)
f[0] = nums[0]
max_num = nums[0]
for i in range(1, len(nums)):
if f[i-1] > 0:
f[i] = f[i-1] + nums[i]
else:
f[i] = nu... |
8008f613f67230bc6181d4149a5daa749a9b7e70 | vickytseng0906/Coursera-UMichigh-Python | /py4e/1_5/ex3_3.py | 403 | 3.96875 | 4 | print ("ex3_2.py")
score = input ("Enter Score:") # bwteen 0.0 and 1.0
s = float(score)
try:
if s >= 0.9:
grade = str("A")
elif s >= 0.8:
grade = str("B")
elif s >= 0.7:
grade = str("C")
elif s >= 0.6:
grade = str("D")
elif s < 0.6:
grade = str("F")
except:
... |
1332dde610c2cc36f5fe9ccf9319e1036a517c75 | vickytseng0906/Coursera-UMichigh-Python | /py4e/1_6/ex4_6.py | 190 | 3.953125 | 4 | hour = input("Hours")
rate = input("Rate per hour?")
h = float(hour)
r = float(rate)
diff = h - 40.0
def computepay(h,r):
return diff * 1.5 * r + 40.0 * r
p = computepay(h,r)
print(p)
|
7b73eea2d65a88dda33d660cfd782104911e3daf | yamini-sathukumati/hack | /programs.py | 6,129 | 4.0625 | 4 | '''for letter in "ABCDEFGHIJKLMNOUPQRSTUVWXYZ":
if letter in "AEIOU":
print(letter, "is a vowel")
else:
print(letter, "is not a vowel")'''
'''i=1
while i<6:
print(i)
i += 1'''
'''count = 0
while (count < 9):
print("The count is:", count)
count+=1
print("Good bye!")'''
'''im... |
ef600b07fd01547ef3ca0ee1a31cd63fda831a2f | kdorichev/hackerrank | /dict_phonebook.py | 796 | 3.953125 | 4 | """
The first line contains an integer, N, denoting the number of entries in the phone book.
Each of the N subsequent lines describes an entry in the form of two space-separated values on a single line.
The first value is a friend's name, and the second value is an 8-digit phone number.
After the lines of phone bo... |
2852e62fa188cb705cd4b741dc882a454514d9bd | TanguyColleville/Solved_Games | /Exo_2_Colleville.py | 2,883 | 3.5625 | 4 | """
Solved the magic square problem
"""
import time as time
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from tkinter import *
from z3 import *
__author__ = "Colleville Tanguy"
__copyright__ = "None"
__credits__ = ["None"]
__license__ = "None"
__version__ = "1.0.0"
__maintainer__ = "Co... |
95aa364b993228ff951b1409453796d3b5e66c05 | sgaamuwa/Checkpoint-1 | /app.py | 6,894 | 3.8125 | 4 | """
The Amity Room Allocation application is a system for assigning rooms
to staff and fellows. Rooms are assigned randomly when people are added
to the system.
Usage:
create_room <room_name>...
add_person <first_name> <last_name> <title> [--wa=N]
reallocate_person <person_identifier> <new_room_name>
l... |
34113ef3d14cfa2ee8d13a6c0b8016f45829fd10 | Shushmitha-N/Python | /sentiment analysis.py | 29,413 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# The objective is to detect hate speech in tweets.
# For the sake of simplicity, we say a tweet contains hate speech if it has a racist or sexist sentiment associated with it.
# So, the task is to classify racist or sexist tweets ... |
fc41f84c845b63cc318eefc96d46ea2383d0b3b2 | sh-cmd/Machine-Learning-with-Python | /Introduction toMchine Learning/case_m4_1_5.py | 319 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 18:11:50 2020
@author: shubham
"""
import numpy as np
a = np.array([0,5,4,0,4,4,3,0,0,5,2,1,1,9])
b=[]
c=[]
for i in range(0,10):
if i not in b:
b.append(i)
# print(b)
cnt = list(a).count(i)
c.append(cnt)
print(c) |
c0022a351f24f188e607abd20821e7054352b5de | sh-cmd/Machine-Learning-with-Python | /Basic Python case study/case_4/case_m4_1_6.py | 310 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 13:49:01 2020
@author: shubham
"""
import numpy as np
import pandas as pd
a = np.arange(0,12)
b=np.reshape(a,(4,3),'c')
print(b)
for i in range(0,4):
for j in range(0,3):
if b[i][j]>=5:
b[i][j]=0
print(b)
|
f29d678c7228fa6115e402fd24f872d640ca6cb1 | sh-cmd/Machine-Learning-with-Python | /Basic Python case study/case/case_m3_1_6.py | 239 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 20:04:00 2020
@author: shubham
"""
a=2000
list=[]
#while a<3201:
list=[str(i) for i in range(2000,3201) if(i%5!=0 and i%7==0)]
list1 = ",".join(list)
print (list1)
|
5aa6a49add5b64ccb3e43de21c69a36203938fd2 | jorik041/ShortDataStorage | /main.py | 3,354 | 3.609375 | 4 | import requests
import sys
import urllib
import http.client
import base64
import argparse
session = requests.Session()
# Write the URL shortener's base URL here:
# For example, stefanaleksic.com/
# Make sure to have the / at the end!
SHORTENER_URL = ""
# I am not going to mention any specific website or service
# i... |
25d62013beedf83d538d232e54718781f9b78dd0 | bhatiamanav/TensorFlowBasics | /basics_tf.py | 1,572 | 4.0625 | 4 | import tensorflow as tf
hello = tf.constant("hELLO")#tensor is a name for array,tensor represents a separate data type for array
#print(hello)
world = tf.constant("World") #World is a tensor constant holding a string type of data
#print(type(hello))
with tf.Session() as sess:#Everything in Tensorflow is executed via ... |
0800290a65708ca45a563f3476eec2d94590e832 | Anvita-Reddy/amfoss-tasks | /task-3/Infinity Stones.py | 2,582 | 4 | 4 | '''
Infinity Stones
In a parallel universe there are N infinity stones (not just 6 ;) ).
The infinity stones can only exist inside boxes. There are M boxes in the universe.
It is guaranteed that no infinity stones are outside the M boxes. Thanos is on the search for the infinity stones.
The avengers can protect atmos... |
39a7d9044113f4b9fea054fe98baafb77bdbcbd5 | Anvita-Reddy/amfoss-tasks | /task-15/SmallestMultiple.py | 1,228 | 3.734375 | 4 | '''
Project Euler #5: Smallest multiple
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(divisible with no remainder) by all of the numbers from 1 to N?
Input Format
First line contains T that deno... |
b4484a7816ca6e38e89cc35c166fd1582028a093 | TEAMLAB-Lecture/basic-math-RogerHeederer | /basic_math.py | 893 | 3.96875 | 4 | #######################
# Basic Math #
#######################
"""
여기서 간단한 수학을 하는 프로그램을 만들것입니다.
"""
def get_greatest(number_list):
return max(number_list)
def get_smallest(number_list):
return min(number_list)
def get_mean(number_list):
sum = 0
for num in number_list:
sum += nu... |
92effab711993c35783b35f47177f7083e55c584 | s-heiden/trellop | /date_util.py | 1,057 | 4.0625 | 4 | """Provided utilities in regard to dates"""
import datetime
from datetime import date
def to_earliest_weekday_after(src_date, weekday):
"""Return the date of earliest given weekday after given source date in datetime format"""
return src_date + datetime.timedelta(days=(weekday - src_date.weekday() + 7) % 7)
... |
5e7c3956bc7da6c099b8fdefc025ba2bfb690cd6 | samarthanand12/JuspayHiringChallenge | /solution/Part II/solution.py | 1,378 | 3.515625 | 4 | from threading import Thread, Lock
class Node:
def __init__(self, name, parent = None):
self.name = name
self.children = []
self.parent = parent
self.locked = False
self.locked_child_count = 0
if parent:
parent.addChild(self)
def getChildren(self):
return self.children[:]
def addChild(self, chil... |
f4d1b608dbc8bcdaba7328f8dfe6044f58878be2 | CollinsLiam21/unit6 | /quiz6.py | 1,052 | 3.5625 | 4 | #Liam Collins
#5/21/18
#quiz6.py
file = open('engmix.txt')
#Program 1
letter = input('Enter a letter: ')
for line in file:
line = line.strip()
if line.count(letter) == 4:
print(line)
#Program 2
for line in file:
line = line.strip()
if len(line) >= 9:
if line[0] == line[4] and line[4] ... |
d1539851d2205974bea1e04b4f0253ce666ff54b | andersonresende/problem_solving | /chapter_4/generator_linked_list.py | 515 | 3.921875 | 4 | # -*- coding: utf-8 -*-
from linked_list import UnorderedList
class GenUnorderedList(UnorderedList):
"""It's a UnordereList whith a generetor to loop over."""
def __iter__(self):
"""Generetor thats loop a list"""
current = self.head
while current:
yield current.getData()
... |
04af1ffe6a1b7958f9f5d50a1af7abd72fb0a7a1 | andersonresende/problem_solving | /chapter_4/linked_list.py | 7,867 | 4.5 | 4 | # -*- coding:utf-8 -*-
'''
Propriedades de linked lists:
1. A linked list e criada atraves da ligação entre nos internamente, ou seja,
a classe recebe um nó que esta ligado a outros nós.
2 - A lista não armazena valores. Os valores estão contido nos nós.
'''
class Node(object):
'''
O no e necessa... |
209a426931d5ef732ade84fe8466ab4b05a1783b | andersonresende/problem_solving | /chapter_5/recursion.py | 1,002 | 3.703125 | 4 |
def listSum(numList):
if len(numList) == 1:
return numList[0]
return numList[0] + listSum(numList[1:])
print listSum([1,3,5,7,9])
def factorial(num):
if num <= 1:
return num
return num * factorial(num-1)
print factorial(4)
def convert_base(n, base):
if n < base:
return n
return str(convert_base(n/b... |
bf9e459ec4696dce61e749c71b67445bac481116 | andersonresende/problem_solving | /myscripts/high_order_default.py | 432 | 3.96875 | 4 |
def map(f, lst):
if not lst:
return []
return [f(lst[0])] + map(f, lst[1:])
def filter(f, lst):
if not lst:
return []
if f(lst[0]):
return [lst[0]] + filter(f, lst[1:])
else:
return filter(f, lst[1:])
def fold():
"""Funcao para ser estudada posteriormente, ... |
1e6f25e38c576498b830d9361de810e01ea219e2 | devndevs/crash_course | /Chapter_9/9-3.py | 1,360 | 4 | 4 | class restaurant:
def __init__(self , restaurant_name , cuisine_type):
"""initilizs restaurant"""
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant (self):
""" Display a summary of the rest... |
fbddf087e69d85905882c77f8da14f8c6d088ba9 | devndevs/crash_course | /Chapter_3/Chapter3-3.py | 566 | 3.515625 | 4 | visit = ["new zealand" , "tahiti" , "japan" , "singapore" , "alaska"]
print(visit, "\n")
print(sorted(visit), "\n")
print(visit, "\n")
visit.reverse()
print(visit, "\n")
visit.reverse()
print(visit, "\n")
visit.sort()
print(visit, "\n")
visit.sort(reverse=True)
guest_list= ["Marcus Aurelius" , "Martin Luther Ki... |
a1ee54e5683c682d89179d279cd04640fbb631f2 | devndevs/crash_course | /Chapter_4/4-3.py | 308 | 4.34375 | 4 | odd_numbers = range(1, 21, 2)
for odd in odd_numbers:
print(odd)
print()
by_three = range(3, 31, 3)
for three in by_three:
print(three)
print()
squares = []
for value in range(1, 11):
squares.append(value ** 3)
print(squares)
print()
cubes = [value ** 3 for value in range(1, 11)]
print(cubes) |
b896b3707c1f28d86fba13bb57724d0a95e9e767 | devndevs/crash_course | /Chapter_4/4-1.py | 420 | 3.71875 | 4 | pizza = [ "buffalo Chicken" , "sausage" , "hawaiian"]
for za in pizza:
print(f"I really love" , (za.title()), "pizza.\n")
print("I Really love pizza.\n")
animals = [ "dog" , "cat", "raccoon"]
for pets in animals:
print(f"A",pets.title() ,"would make a great pet.\n")
print(f"What a" , pets.title() , "has in... |
ea41ee34cbff1cd724c9721eedbd2d736003d363 | yunjin-cloud/2020-winter | /OOP_Variable/set&get.py | 497 | 3.875 | 4 | class C: #괄호 열고 (object) 해줄 수 O
def __init__(self, v):
self.value = v
def show(self):
print(self.value)
def getValue(self):
return self.value
def setValue(self, v):
self.value = v
# c1 = C(10)
# print(c1.value)
# c1.value = 20 #instance value에 접근해서 쓰기
# pr... |
23ac692a1f9311f299d82ce15b57579cea0398ea | yunjin-cloud/2020-winter | /Logical/or.py | 197 | 3.765625 | 4 | in_str = input("아이디를 입력해주세요.\n")
real_yunjin = "jin"
real_urim = "chu"
if real_yunjin == in_str or real_urim == in_str:
print("Hello!")
else:
print("Who are you?")
|
3b94e0b7e4779b9008b5b0dacadde06c6b49b01a | yunjin-cloud/2020-winter | /Variable/variable.py | 144 | 3.703125 | 4 | print(10+5)
x = 10
print(x + 5)
y = 5
print(x + y)
title = "Python & Ruby" #문자를 변수에 넣음
print("Title is " + title)
|
2d65a6804c89c216240c962d14f5221fd4fc1c71 | yunjin-cloud/2020-winter | /String/string_control.py | 971 | 4.0625 | 4 | print('Hello ' + 'World')
print('Hello ' *3)
print('Hello'[0]) # 0번째 위치에 있는 H를 가져오기
print('Hello'[1]) # 1번째 위치에 있는 e를 가져오기
print('Hello'[2]) # 2번째 위치에 있는 l를 가져오기
print('hello world'.capitalize()) #첫 글자만 대문자화
print('hello world'.upper()) #모든 글자 대문자화
print('hello world'.__len__()) # 문자 개수 세기
print(le... |
89535656f05799027fa2fe353840aefcb7fe2d68 | Ansijax/udacityMachineLearning | /datasets_questions/explore_enron_data.py | 3,224 | 3.53125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
23876aba521bce0ead3845a6ec98c0e4c9d26948 | sai-varshith/Hacktoberfest21-letshack | /Python Programs/anagrams.py | 279 | 4.09375 | 4 | def validate(word1,word2):
word1=word1.lower()
word2==word2.lower()
if sorted(word1)==sorted(word2):
print("anagrams")
else:
print("not anagrams")
print("enter the words\n")
word1=input("word1 is ")
word2=input("word2 is ")
validate(word1,word2)
|
a229cbc1422914ab773002672893df846ed3cb7c | sai-varshith/Hacktoberfest21-letshack | /Python Programs/AddTwoNumbers.py | 253 | 4.0625 | 4 |
#input the first number
num1 = int(input("Enter First Number:"))
#input the second number
num2 = int(input("Enter Second Number:"))
#Finding sum
sum = num1 + num2
#Displaying the result
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
|
42cda8c6179eb2e7e88830c4e9381652fedc5097 | aumkar22/Indoor-Location-Navigation | /src/scripts/fix_data.py | 1,691 | 4.03125 | 4 | from typing import List, Tuple
from src.util.definitions import SENSORS
def line_check(line: List[str]) -> List[List[str]]:
"""
Function to check if length of line exceeds 10 (max sensor line length). If it does,
split the line.
:param line: List of sensor strings (can contain multiple sensors whic... |
78f458129103d78cd0309ca21de13e3754b9d003 | nisha253/python | /alpha.py | 173 | 4.0625 | 4 | a=input("enter the string=")
for i in a:
if (i=='a' or i=='e' or i=='i' or i=='o' or i=='u'):
print(i,"it is vowels")
else:
print(i,"it is consecutive")
|
1ef5bac9ec85ad456f0e1f0c10293d3e613deb56 | kgv7/calculator-2 | /calculator.py | 2,175 | 3.984375 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic_fs import (add, subtract, multiply, divide, square, cube,
power, mod, )
# Replace this with your code
OPERATORS = ["+", "-", "*", "/", "pow", "mod", "square", "cube"]
# LETTERS = ["a", "b", "c", "d", "e", "f", "g", "h", ... |
992ff8d571c60fe85828c21e99a77ef5d399d9b2 | anatolykobzisty/algorithms | /10-Dynamic_programming/dinamic_fibonachi.py | 405 | 3.90625 | 4 | '''
Вычисление чисел Фибоначчи и проблема перевычислений
Динамическое программирование (рекурсия вывернутая наоборот)
https://youtu.be/EdhN_gEDfUM?t=1542
'''
n = int(input())
def fib(n):
f = [0, 1]
for i in range(2, n):
f.append(f[i-1] + f[i-2])
print(*f)
fib(n)
|
4bee6576d7ff6820d3bcd32a2678c212d9fc49ef | anatolykobzisty/algorithms | /08-Generate/generate_permutations.py | 1,387 | 3.984375 | 4 | '''
Рекурсивная генерация всех перестановок N чисел
в M позициях с префиксом
https://youtu.be/2XFaK3bgT7w?t=2327
'''
def find(number, A):
'''
ищет number в A и возвращает True, если такой есть
False если такого нет
'''
flag = False
for x in A:
if number == x:
... |
7ab7ff49fa710cdf8018a98644f1e121a71af71b | anatolykobzisty/algorithms | /07-Recursion/factorial.py | 328 | 3.609375 | 4 | '''
Алгоритм нахождения факториала числа для положительных чисел
https://youtu.be/0Bc8zLURY-c?t=2450
'''
def f(n:int):
assert n >= 0, "Факториал отрицательного не определен"
if n == 0:
return 1
return f(n-1)*n |
6ef5e13cb1102beda0bb5421daf8c0c0493d4595 | anatolykobzisty/algorithms | /25-BFS/bfs.py | 917 | 4 | 4 | '''
Алгоритм поиска кратчайшего пути в незвешанном графе от одной вершины
до всех остальных, методом BFS (Breadth-First Search) - обхода графа в ширину
теория
https://youtu.be/S-hjsamsK8U?t=448
реализация
https://youtu.be/S-hjsamsK8U?t=1089
'''
N, M = map(int,input().split())
graph = {i: set... |
afd7178e7d2562694d690bc8d2f48fb3507689bc | birendra7654/python_design_pattern | /Creation/FactoryPattern/simpleFactory.py | 509 | 3.6875 | 4 | from enum import Enum
from math import *
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'x: {self.x}, y: {self.y}'
@staticmethod
def new_cartesian_point(x, y):
return Point(x, y)
@staticmethod
def new_polar_point(rho, t... |
bfddf8cb1aa48364b9157a191ccc21684dddd025 | elenaoat/automate | /comprehensions.py | 2,284 | 4.375 | 4 | # Comprehensions offer a flexible and more performant way to do some operations,
# that would require otherwise much longer code, and their computational cost would be higher
# There exist list, dictionary, set comprehensions and the value generator expressions.
# Definition: a comprehension applies a statement to an... |
ec0124a401f16edd7677323f4d49da1076e381b0 | python-basic/sem3-t2-nanashinogonbee | /vartask2.3.py | 335 | 3.65625 | 4 | import random
abs = lambda x: (x - 2 * x) if x < 0 else x
srclist = [rand(-1000, 1001) for i in range(random.randint(10, 51))]
reslist = [abs(i) for i in srclist]
print('Source list:\n{}\n\nResulting list:\n{}'.format(srclist, leslist))
if __name__ == '__main__':
assert abs(-5) > 0, 'Error while caculating an abs... |
c5d34e61e3e716f0f7249da1335972f9749aa4bf | amitkvikram/AILAb | /Lab1_to_Lab6/Lab2/lab2_withVaryingSpeed.py | 5,872 | 3.53125 | 4 | # Name : Kuldeep Singh Bhandari
# Roll No. : 111601009
# Aim : To implement Simple Traffic Simulator with varying speed
import numpy as np
import sys
# to load Road text file
def loadRoad() :
print("Loading road...")
# return pickle.load(open('road', 'r'))
return np.array(np.loadtxt('road.txt'))
#... |
5fead6b87e8a86c03d0a0c5f25c86626df639415 | amitkvikram/AILAb | /Lab1_to_Lab6/Lab5/puzzle.py | 5,794 | 3.90625 | 4 | # Name : Kuldeep Singh Bhandari (111601009)
# : Amit Vikram Singh (111601001)
from __future__ import print_function
import numpy as np
from Queue import Queue
import copy
# class <Node> represents a state which possess informations like
# <M> which is matrix of the current state,
# <pos> which i... |
1c9a926da4cd9f8971d43fabe5af9c76aef0ec68 | Karthk03/stdHW | /stdHW.py | 342 | 3.78125 | 4 | import csv
import math
with open('stdData.csv') as f:
reader = csv.reader(f)
data = list(reader)
data.pop(0)
sum = 0
length = len(data)
for i in data:
sum+=int(i[0])
mean = sum/length
sumSTD = 0
a = 0
for x in data:
a = float(x[0])
sumSTD+=(a-mean)^2
std = math.sqrt(sumS... |
96a54eaba77216043bd3ad54d89160b989cf29ea | sonvt8/Gigacover-Internship | /week04_hackerrank/day6.py | 433 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
lst_of_lists = []
for line in sys.stdin:
lst_of_lists.append(line.rstrip('\n'))
for ele in lst_of_lists[1:]:
lst = list(ele)
even_str = ''
odd_str = ''
for count,ele in enumerate(lst):
if count % 2:
... |
64d5794a34c08298076f7322d5b85502a72031e1 | sonvt8/Gigacover-Internship | /week04_hackerrank/day20.py | 783 | 3.65625 | 4 | #!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# Write Your Code Here
numberOfSwaps = 0
def swap(idx,lst):
lst[idx], lst[idx+1] = lst[idx+1], lst[idx]
return lst
def arrange_num(lst,count):
for i in range(len(lst)):
for j in range(len(lst) - 1):... |
b4e349cbb1faaf0210814f3a4830ed436b260f36 | PDMacDonald/TextFile_DataExtraction | /Court_Calendar.py | 6,979 | 3.703125 | 4 | #!/usr/bin/env python3
"""
Court_Calendar.py: application that is designed to process Watauga County
Court Calendar documents to produce a csv representation of the data.
CIS3680-101
Programming Assignment
"""
__author__ = "Preston MacDonald"
__copyright__ = "Copyright 2019, Preston MacDonald"
__credit... |
e61d4df7cd2ba60d1ba833f96461b6ab6417a18c | takenobu-hs/pixel-manipulation-examples | /python_pillow/232.alpha.brend.py | 591 | 3.625 | 4 |
from PIL import Image
#-- read pixels
im1 = Image.open('../images/img001.png').convert('RGB')
width, height = im1.size
im2 = Image.open('../images/img002.png').convert('RGB')
im3 = Image.new('RGB', (width, height))
#-- pixel operation
for y in range(height):
for x in range(width):
r1, g1, b1 = im1.getp... |
5bd31364bf0c12a2d5d5b56371200158a3db999b | takenobu-hs/pixel-manipulation-examples | /python_pillow/210.convert.gray.py | 404 | 3.734375 | 4 |
from PIL import Image
#-- read pixels
im = Image.open('../images/img001.png').convert('RGB')
width, height = im.size
#-- pixel operation
for y in range(height):
for x in range(width):
r, g, b = im.getpixel((x, y))
gray = int((r + g + b) / 3)
r2 = gray
g2 = gray
b2 = gra... |
48fc2c90c968b57b13443b7747cdedf35203c832 | wiwa1978/blog-hugo-netlify-code | /Parse_JSON_Python/parseOrders.py | 549 | 3.65625 | 4 | import json
with open('sample.json') as f:
json_content = f.read()
json_dict = json.loads(json_content)
customers = json_dict['Customers']
orders = json_dict['Orders']
#print(customers)
customer_list = []
for customer in customers['Customer']:
customer_list.append(customer['@CustomerID'])
for customer in cust... |
c0972c4982784fc16fc69f3b3abe7290e002f3db | vbitjp/Python | /Numpy/ndarray02.py | 2,372 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
'''
Numpyの高速な処理の体験
自機Macでの実行結果
Python組み込みモジュールのみでの実行時間:1.26[sec]
Numpyを使った場合の実行時間:0.00[sec]
'''
# 必要なライブラリをimport
import numpy as np
import time
from numpy.random import rand
# 行、列の大きさ
N = 100
# 行列の初期化
matA = np.array(rand(N, N))
matB = np.array(rand(N, N))
matC = np.array([[0] *... |
598a4220390f758639e83c9df4c9d099c183be7a | Riko164/alpropython | /Loop2/soal2A.py | 351 | 3.8125 | 4 | angka=int(input("input bilangan: "))
counter1=angka*2-1
counter2=counter1
for i in range(0,angka*2):
for j in range(0,angka*4-1):
if i==angka*2-1:
print("*", end='')
elif j==counter1 or j==counter2:
print("*",end='')
else:
print(" ",end='')
print("")
... |
47420826f657b1a849772baa828eb761e8ad2f57 | Riko164/alpropython | /Loop2/soal1A.py | 288 | 3.515625 | 4 | def cek(angka):
counter=0
for i in range(2,angka):
if(angka%i==0):
counter=1
if(counter==0):
return True
else:
return False
banyak=int(input("Masukkan bilangan: "))
for i in range (2,banyak):
if cek(i):
print(i, end=" ")
|
05271e04f70c933dac8b7fb6cbe15fbb37c93a8b | Riko164/alpropython | /uts/little_duck.py | 268 | 4 | 4 | def little_duck(n):
for i in range(n,0,-1):
if i==1:
print(i, "little duck went out one day, 1 was missing")
else:
print(i, "little ducks went out one day, 1 was missing")
print("all ducks were missing")
little_duck(3)
|
e852002846b0fdef89f7f4f452a31d869714103d | lawfets/codewars | /K7_CountTheDivisorsOfANumber.py | 460 | 3.984375 | 4 | def divisors(n):
list = []
print(range(1, n))
for i in range(1, n + 1):
if n % i == 0:
list.append(i)
return len(list)
def divisors1(n):
return len([l_div for l_div in range(1, n + 1) if n % l_div == 0]);
#above functions find the amount of divisors from the int n
'''
divis... |
e4452442d9b2ac58a549aa943ed0d5e91f8babea | SmokinCaterpillar/pypet | /pypet/slots.py | 2,400 | 3.578125 | 4 | """Module containing the superclass having slots"""
__author__ = 'Robert Meyer'
def get_all_slots(cls):
"""Iterates through a class' (`cls`) mro to get all slots as a set."""
slots_iterator = (getattr(c, '__slots__', ()) for c in cls.__mro__)
# `__slots__` might only be a single string,
# so we need ... |
18ebb63ecef19b188e18831fa38b3b723e1f4f59 | xingzhong/leetcode-python | /130.py | 1,007 | 3.703125 | 4 | class Solution:
# @param board, a 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
m = len(board)
if m < 3 : return
n = len(board[0])
if n < 3 : return
def setB(x, y):
i... |
a964e061e01b251c191f8415578a862fd5309ae5 | xingzhong/leetcode-python | /36.py | 802 | 3.546875 | 4 | class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
def test(xs):
t = [False]*9
for x in xs:
if x == '.': continue
elif t[int(x)-1]:
return False
else:
... |
ee80948bf145312860867b875725ab50b6dd2948 | Ankush-Anku/Tranning | /38_simple_interest.py | 298 | 3.875 | 4 | #Assignment
"""
Accept p,n and r
si = pnr/100
print si
"""
def print_interest(n,p,r):
si = (p*n*r)/100
print(f"Simple interest is = {si}")
def main():
n = float(input("Enter n: "))
p = float(input("Enter p: "))
r = float(input("Enter r: "))
print_interest(n ,p,r)
main() |
747914dc704e08fe074d9c8dc1dc3a73eb42d485 | Ankush-Anku/Tranning | /46_first_n_natural_while.py | 65 | 3.75 | 4 | n = int(input("Enter n:"))
i=1
while i<=n:
print(i)
i=i+1 |
611ad237002fbd691127c3af4365eea12e64ff39 | Ankush-Anku/Tranning | /27_Print_odd_till_n_iterations.py | 154 | 4.0625 | 4 | n = int(input("Enter n: "))
for i in range(1,n+1):
if i%2 ==1:
print(i)
n = int(input("Enter n: "))
for i in range(1,n+1,2):
print(i)
|
e4bb28f44d958e0e1d96fe1587c4d9f1927270cb | Ankush-Anku/Tranning | /74_is_strong_number.py | 622 | 4.28125 | 4 | """
Strong number is a special number whose sum of factorial of digits is equal to the original number.
for example: 145 is strong number.Since,1! + 4! + 5! =145
"""
def get_factorial(n):
fact =1
for i in range(n,0,-1):
fact = fact *1
return fact
def is_strong(n):
i=n
sum = 0
while i... |
f0e668190bceb847c7860e836b16c613d0dfb4fd | Ankush-Anku/Tranning | /42_First_n_natural_print_while.py | 69 | 3.75 | 4 | n = int(input("Enter n: "))
i = 1
while i<= n:
print(i)
i=i+1 |
ff6c0eb492bebcf87bdef98d2659c4753a44a7ca | elip12/machine_learning | /k_n_n/masyu_solver.py | 5,806 | 4.09375 | 4 | # Masyu Strip Data
# author: Eli Pandolfo
#
# Strips data from an input masyu board and puts it into a dataframe
# dataframe has a row for every square on the board, and strips data for:
# board corner: 0, 1 (yes or no)
# board edge (not corner): 0, 1
# top left: 0, 1, 2, 3 (off board, black, white, neither)
# top mid:... |
2534b3eb9c1bc9e37355f85562aa9850772fcf1f | Zealoter/zz_no_leetcode | /[513]找树左下角的值.py | 1,232 | 3.84375 | 4 | # 给定一个二叉树,在树的最后一行找到最左边的值。
#
# 示例 1:
#
#
# 输入:
#
# 2
# / \
# 1 3
#
# 输出:
# 1
#
#
#
#
# 示例 2:
#
#
# 输入:
#
# 1
# / \
# 2 3
# / / \
# 4 5 6
# /
# 7
#
# 输出:
# 7
#
#
#
#
# 注意: 您可以假设树(即给定的根节点)不为 NULL。
# Related Topics 树 深度优先搜索 广度优先搜索 ... |
cb2e749ad5c9c1f26889c422797a45b31cb0aa93 | agolla0440/my_python_workbook | /my_for_loop_assingment.py | 1,329 | 4.375 | 4 | # This is the part where I contain the strings in a variable in a list format.
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
vegetables = ["broccoli", "tomato", "cabbage", "carrot", "lettuce", "celery", "potato",
"spinach", "ginger", "oni... |
769374aa11ebcc09a046d88c9455224eb3efcc2e | Roses124/Folderthing | /chatbot2.py | 1,598 | 3.953125 | 4 | # --- Define your functions below! ---
import random
sports = ["tennis", "baseball", "softball", "basketball", "track", "swim", "dance", "soccer", "football", "field hockey", "lacrosse"]
answer = random.choice(sports)
answer = answer.lower()
valid_greetings = ["hi", "hey", "hello", "sup", "howdy"]
goodbyes = ["see ya",... |
e53bc24f44863cb3ee48c19bb7bd05f626cca570 | Roses124/Folderthing | /chatbot.py | 1,592 | 3.90625 | 4 | # --- Define your functions below! ---
import random
sports = ["tennis", "baseball", "softball", "basketball", "track", "swim", "dance", "soccer", "football", "field hockey", "lacrosse"]
answer = random.choice(sports)
answer = answer.lower()
def goodbye():
print("It was nice to talk to you!")
print("I'll talk t... |
7eb77129b29bc9cf717e89044defeb021c4fc174 | SlyFawkes/MyEuler | /Project_Euler/Solutions/Project_Euler_012_Highly_divisible_triangular_number.py | 508 | 3.828125 | 4 | import math
def get_tri_number(n):
i = 1
total = 0
most_factors = 1
while most_factors < n:
total += i
check = get_num_of_factors(total)
if check > most_factors:
most_factors = check
print most_factors
i += 1
return total
def get_num_of_fac... |
4cc521f5afb688c68132a2a440597460ed52e964 | SlyFawkes/MyEuler | /Project_Euler/Solutions/Project_Euler_020_Factorial_digit_sum.py | 245 | 3.921875 | 4 | '''
Created on 9 Dec 2014
@author: vera
'''
from math import factorial
def addDigitsOfNum(number):
strNumber = str(number)
total = 0
for char in strNumber:
total += int(char)
print total
addDigitsOfNum(factorial(100)) |
7e4b4e24824e68f1c173772ee1a4ae5ed7ea0ac3 | RetroMelon/SAStronauts | /djangobackend/api/wikiapi.py | 3,596 | 3.515625 | 4 | import wikipedia
import urllib2
import json
import string
import random
# count how many times a kewyword appears on a website
def count(text, link, keywords):
data = {}
text = text.split()
for kw in keywords:
for word in text:
if kw in word or kw.lower() in word:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.