blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9c267d0719ead2128ee936ff5ae59fcc96269886 | kylem4523/OOP_Project2 | /RoamStrategy.py | 704 | 3.765625 | 4 | """This class will serve as the Strategy template for the roam behavior. Code in this module has been taken from
https://medium.com/@sheikhsajid/design-patterns-in-python-part-1-the-strategy-pattern-54b24897233e """
import abc
class RoamStrategy(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmetho... |
b1a8140a0f8f0f8b9dcbd4d876e1b67e0306a130 | pisoc/pisoc-presents-python-demos | /data-structures/lists.py | 333 | 3.65625 | 4 | """lists"""
assorted_things = ['A string!', 1337, 3.141, True, [1, 2, 3]]
for things in assorted_things:
print(things)
# It's the same number
print()
print(id(assorted_things))
assorted_things.append('Another string!')
print(assorted_things)
print(id(assorted_things), '\n')
# No hashing here!
print(hash(assor... |
b3bcacf451bc98b0974e3d2211a10131d7887355 | nikhilbommu/DS-PS-Algorithms | /SortingAlgorithms/selection-sort.py | 320 | 3.859375 | 4 | class Sorting:
def selectionsort(arr):
for i in range(len(arr)-1):
iMin=i
for j in range(i+1,len(arr)):
if arr[j]<arr[iMin]:
iMin=j
arr[i],arr[iMin]=arr[iMin],arr[i]
return arr
s=Sorting
print(s.selectionsort([4,5,6,7,3,2,1])) |
c7945a323829d75c782cb04d6a5717de59385c35 | Pisceszaiby/first_semester | /LAB 10 i.py | 2,161 | 4.3125 | 4 | num=int(input("Enter Number of elements in the list: "))
num_list=[] #For NewNumList() function, numbers will be stored here
frequency=list() #Initializing lists
sorted_frequency=list()
def NewNumList():
print("Enter Numbers after each line")
for i in range(num):
element=int(input(''))
n... |
10d4cb227efc255c0fa7122a641e94560f9214df | shruti-nahar14/Python | /numeric pyramid.py | 365 | 3.796875 | 4 | '''input:--
output:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
description:numeric Pyramid pattern
date: 30-08-2021
Author name: Shruti Nahar'''
x=5
n=1
m=(2*x)-2
for i in range(0,x):
for j in range(0,m):
print(end=" ")
m=m-1
for j in range(0,i+1):
... |
bf03229720347849eae0d8218549d6b1827ef7c7 | russianbigbear/WarnockMethod | /Gr_L2.py | 9,583 | 3.53125 | 4 | """Пакеты"""
import librosa
import os
import numpy as np
from graphics import *
from shapely.geometry.polygon import Polygon as Pol
from shapely.geometry import Point as Po
class MyPoint(object):
"""Точка - """
def __init__(self, x, y=0, z=0):
if type(x) is list:
self.x = x[0]
... |
b84b09e2306c44eb2fab91919fa77516fa849779 | kolavcic/Basic-Python_Code | /Code Academy/3. cas/zadatak6.py | 99 | 3.765625 | 4 | n = int(input("Unesite broj n: "))
m = int(input("Unesite broj m: "))
for i in range(n,m+1):
|
35b7dfcce6cefb6322061a48eb87eb208fec434f | Dengdi21/Fluent-Python | /1/1.1.py | 1,911 | 3.984375 | 4 | # 示例1.1 一摞有序的纸牌
import collections
# collections.namedtuple构建了一个简单的类(少量属性没有方法的对象)来表示一张纸牌
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split() # 把一个字符串分割成字符串数组。
def __init__(self):
... |
e2e8b0b8ce0c95cc7fded018d24d9f3b8e1a96b8 | CNZedChou/ReviewCode | /pythoncode/montecarlo.py | 577 | 3.578125 | 4 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : Zed
@Version : V1.0.0
------------------------------------
@File : montecarlo.py
@Description :
@CreateTime : 2021-1-15 14:50
------------------------------------
@ModifyTime :
"""
import random
NUMBER_OF_TRIALS = 1000... |
0bd96efa2ce03e73249c4150888987a38af2f7f3 | oribro/IntroToCS | /ex4/ex4.py | 11,839 | 3.765625 | 4 | #############################################################
# FILE: ex4.py
# WRITER: Ori Broda, orib, 308043447
# EXERCISE : intro2cs ex4 2013-2014
# Description : This ex is a continuation of ex3 and as such,
# it uses functions from ex3 to implement more functions
# regarding our pension
####################... |
e5f2647ea083ea4f67b1310152761cf7c7f4b52a | mnguyen0226/network_from_scratch | /testNet2.py | 1,339 | 3.5 | 4 | """
Program that load trained model net2
Command: python ./testNet2.py on terminal
"""
import pickle
import numpy
import matplotlib.pyplot as plt
import matplotlib as mpl
import mnist_official_loader
from mnist_official_loader import processData
def main():
training_data, testing_data = mnist_official... |
fb0eb542dcec1250ad6b4b4006c5dcd19ee5e1cb | happyssun96/Python_Algorithm | /2장 재귀 호출/2.py | 374 | 3.59375 | 4 | def find_max(a):
n = len(a)
max_index = 0
for i in range(1, n):
if a[i] > a[max_index]:
max_index = i
return max_index
def find_min(b):
n = len(b)
min_b = b[0]
for i in range(1, n):
if b[i] < min_b:
min_b = b[i]
return min_b
v = [17, 92, 18, 33, ... |
c5bfbca53e2877f47534e78bb10b536c5bd70af7 | muyisanshuiliang/python | /leet_code/1647. 字符频次唯一的最小删除次数.py | 1,995 | 3.625 | 4 | """
如果字符串 s 中 不存在 两个不同字符 频次 相同的情况,就称 s 是 优质字符串 。
给你一个字符串 s,返回使 s 成为 优质字符串 需要删除的 最小 字符数。
字符串中字符的 频次 是该字符在字符串中的出现次数。例如,在字符串 "aab" 中,'a' 的频次是 2,而 'b' 的频次是 1 。
示例 1:
输入:s = "aab"
输出:0
解释:s 已经是优质字符串。
示例 2:
输入:s = "aaabbbcc"
输出:2
解释:可以删除两个 'b' , 得到优质字符串 "aaabcc" 。
另一种方式是删除一个 'b' 和一个 'c' ,得到优质字符串 "aaabbc" 。
示例 3:
输入:s = "c... |
cba1fa28de9a2c352666a591041a4479716feed2 | dudwns9331/PythonStudy | /BaekJoon/Bronze2/4458.py | 615 | 3.625 | 4 | # 첫 글자를 대문자로
"""
2021-01-23 오후 3:48
안영준
문제
문장을 읽은 뒤, 줄의 첫 글자를 대문자로 바꾸는 프로그램을 작성하시오.
입력
첫째 줄에 줄의 수 N이 주어진다. 다음 N개의 줄에는 문장이 주어진다.
각 문장에 들어있는 글자의 수는 30을 넘지 않는다. 모든 줄의 첫 번째 글자는 알파벳이다.
출력
각 줄의 첫글자를 대문자로 바꾼뒤 출력한다.
"""
N = int(input())
for i in range(N):
String = list(map(str, input()))
String[0] = String[0].up... |
6d258805a9d3f29488ff0a21189325ef189ae6f2 | hexinuser/Machine-learning-study | /algorithm/KNN.py | 8,222 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
KNN Classification
Created on Tue Apr 17 13:16:47 2018
@author: hexin
"""
import numpy as np
import operator
import matplotlib.pyplot as plt
from os import listdir
def classify0(inX, dataSet, labels, k):
""" input: inX: test data,1*N
dataSet: training data M*N... |
a816eb902ea5aedc8a80f06cfb247c0a532e76a9 | camillemura100t/DevOps_training | /python_training/boucle_while.py | 348 | 3.75 | 4 | #!/usr/bin/env python3.8
n = 10
while n >= 1:
if n == 1:
print("C'est dans %d an je m'en irai, j'entends le loup et le renard chanter" %n)
else:
print("C'est dans %d ans je m'en irai, j'entends le loup et le renard chanter" %n)
n = n - 1
#Affiche la phrase de 10 à 1 an en tenant compte de ... |
fa694eadace99ee491d76f2c7598e7e12e7e3662 | 1050669722/LeetCode-Answers | /Python/problem0145.py | 2,521 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 18:59:29 2019
@author: Administrator
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> list:
... |
4743460adf2feec2c411f9b90ef43c4d79c47cbd | waltercueva/CLRS | /C09-Medians-and-Order-Statistics/problems/i-largest.py | 420 | 4.0625 | 4 | #!/usr/bin/env python
# coding=utf-8
from Queue import PriorityQueue
def sort1(items, i):
items = sorted(items,reverse=True)
return items[:i]
def sort2(items, i):
pq = PriorityQueue()
for element in items:
pq.put((-element, element))
array = []
for k in range(i):
array.append(... |
93a85abcc0dfd4e73cbd551f6ccbbca822f14f55 | max-orhai/tictactoe | /tictactoe.py | 5,946 | 3.5 | 4 |
# A tic-tac-toe player by Max Orhai, 2016 January 28 -- 30.
#
# Goal: Play to win, and put up a good fight in any case.
# Secondary goal: reach every nonlosing path in the game tree.
# Strategy:
# Build the entire game tree,
# mark its losing and winning paths, then prune losing paths from tree,
# preferr... |
3065da134cb0ce0da0528b50f7e816821de49c29 | f-sena6/CS451 | /CS451-HW3/Source_Code/senaf-hw2.py | 769 | 4.125 | 4 | #Fred Sena 2-10-17
#CS 451 Homework 2
from Crypto.Cipher import DES #Imports pycrypto
import random
def encrypt_string(string1):
while len(string1) % 8 != 0: #If string1 mod 8 does not equal zero, add in empty spaces
string1 = string1 + " "
key = "" #Creates the key
for i in range(0,8):
... |
6cab6f122a0b6407de06115946e93160469eac39 | pomelloyellow/D-django | /lab1/lab1_1.py | 830 | 4.125 | 4 | import math
print(" a:")
a = float(input())
print(" b:")
b = float(input())
print(" c:")
c = float(input())
print(" k:")
k = float(input())
if(b == 0 or a == 0):
print("\n !")
else:
temp = (a+b+c*((k-a)/math.pow(b, 3)))
if(temp == 0):
print("\n !")
else:
... |
35a486aab749e8750bff5dc925fc158761f0e45d | seekpinky/python_fundamental_2 | /02_basic_datatypes/2_strings/02_07_replace.py | 539 | 4.25 | 4 | '''
Write a script that takes a string of words and a symbol from the user.
Replace all occurrences of the first letter with the symbol. For example:
String input: more python programming please
Symbol input: #
Result: #ore python progra##ing please
'''
# get input sentence
sentence=input("please enter a sentence: ")... |
53b950746f5337330594d532109d500fa6443c4b | JinSeungHo/Code | /Python/mymath/stats/average.py | 446 | 3.671875 | 4 | # 데이터의 평균을 구해주는 함수
def data_mean(data):
return sum(data) / len(data)
def data_median(data):
data.sort()
n = len(data)
if n % 2 == 0:
# 데이터의 개스가 짝수면 중앙에 위치한 두 값의 평균을 구함
# [a, b, c, d, e, f] -->median = (c+d)/2
return (data[n/2] + data[(n/2)-1]) / 2
else:
# [a, b, c, ... |
0691e8c746580434d0c3d106734e4f95975ce27f | H4rliquinn/Algorithm-Solutions | /LeetCode/reorganize-string.py | 1,717 | 3.828125 | 4 | """
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
"""
class Solution... |
33412c346ccdf3c9872bb7a1f3b69a5c6ad06540 | okeycsy/Coding-Test | /Palindrome Linked List.py | 686 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head:ListNode)->bool:
q:list=[]
#만약 비어있는 linked list라면 팰린드롬 성립
if head is None:
return True
... |
4aea9cd5ab2dacedcefa1f3449971f2556090e54 | rkkothandaraman/Python-mathematics | /sqaureofalldigits.py | 133 | 3.75 | 4 | N=input()
product=0
N1=(str(m) for m in str(N))
N2=(int(x) for x in N1)
for i in N2:
product+=(i**2)
print(product)
|
db860ef870f759c60c786b7724c3807e694c2771 | altoid/hackerrank | /primality/solution.py | 1,389 | 3.671875 | 4 | #!/usr/bin/env python
# https://www.hackerrank.com/challenges/ctci-big-o/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=miscellaneous
import fileinput
import math
import unittest
def isprime(p):
# we know 1 <= p <= 10 ** 9
if p == 1:
return False
if p... |
37966fd71944b45592024c65da7f70cdc5c52f7a | chrisjdavie/compsci_basics | /number_theory/modular_exponentiation/recursive.py | 870 | 4.15625 | 4 | """
Given three numbers x, y and p, compute (x^y) % p.
https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/
This is showing how to do maths with large numbers, minimising the large
numbers. Is interesting to play with - shows the difference in thinking/
training between compsci folks and... |
44bb77f93dc4ad3a52e9273bc2811670d37613a5 | fregataa/Algorithm-Python | /Baekjoon/PrintStar-21_10996.py | 163 | 3.859375 | 4 | n = int(input())
for i in range(n*2):
if i%2 == 0:
print("{0}{1}".format('* '*((n - 1)//2), '*') )
else:
print("{0}".format(' *'*(n//2)) ) |
381c8ea82663424c54597ff8208c619bd92254a3 | j3ffyang/ai | /scripts/basic/regex_match_group_adv.py | 157 | 3.65625 | 4 | import re
pattern = r"(?P<first>abc)(?:def)(ghi)"
match = re.match(pattern, "abcdefghi")
if match:
print(match.group("first"))
print(match.group()) |
8544ca4fa1bb591f4e534cc3992b2683f4d9b2ea | seanchen513/leetcode | /dp/1411_num_ways_to_paint_n_by_3_grid.py | 17,680 | 4.21875 | 4 | """
1411. Number of Ways to Paint N × 3 Grid
Hard
You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colours: Red, Yellow or Green while making sure that no two adjacent cells have the same colour (i.e no two cells that share vertical or horizontal sides have the sa... |
4281541c0d5f76750d944ba1c182026e833f0321 | hitesh-92/hackerRank | /diagonalDifference.py | 654 | 4.34375 | 4 | """
arr1= [1, 2, 3]
arr2= [4, 5, 6]
arr3= [9, 8, 9]
The left-to-right diagonal: 1+5+9 = 15
The right-to-left diagonal: 3+5+9 = 17
Their absolute difference: 15-17 = 2
"""
def diagonalDifference(arr):
def leftPass():
result = 0
size = len(arr[0]) - 1
for i in range(len(arr)):
result += arr[i][size]
size ... |
c94a11adac232b9b7053fcf2d6a88968fa6d90af | DengYiping/ADS-2018 | /hw6/word_sort.py | 1,064 | 3.828125 | 4 | from collections import deque
def find_max_length(words):
lens = map(len, words)
return max(lens)
def find_bucket(word, idx):
if(idx > len(word) - 1):
# it is out of bound, count it as a very small number
return 0
else:
# return the ascii code
return ord(word[idx])
def... |
fb6096fe11e3f5c53e38ee7893045903d9c92c87 | jos-frye/TestingPythonWithZeb | /app/classes/text.py | 309 | 4.125 | 4 | # when given a string, determine its lentgh
def stringlength(a):
return len(a)
# When given a string and a number, return the character
def character(a, n):
return a[n]
print("The string length is:", stringlength("0123456"))
print("The character number you entered is:", character("0123456", 2)) |
6455c77445caf1c8d2c4d29fdd4aa14322b00baf | pkvinhu/algorithm-dict | /utils/python/bstTreeNode.py | 738 | 3.921875 | 4 | # BinaryTree class
class BinaryTree:
def __init__(self, value, parent=None):
self.value = value
self.left = None
self.right = None
self.parent = parent
def insert(self, values, i = 0):
if i >= len(values):
return
queue = [self]
while len(queu... |
07c0c595f2412d38e77ca0e76afed776648cff03 | ibukamshindi/Password-Locker | /user_test.py | 827 | 3.71875 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase) :
"""
Test class that defines test cases for the user class behaviours
"""
def setUp(self):
"""
Set up method to run before each test case
"""
self.new_user = User("Juma","12345")
def test... |
883a65318810789bd0ff0cc7b09d8d77b1f0b0ad | prahaladvathsan/cricket-project | /cricket league.py | 11,558 | 3.578125 | 4 | import auction
import cricket as cric
import copy
import csv
# added to github
def instruction():
print("\t\t T20 Cricket league simulator\n ".capitalize())
print("\n\ninstructions".capitalize())
print("1.the game has 2 stages\n\ti.the auction\n\tii.the league\nsimilair to the structure of the ipl\n... |
0fe814141944ffdc203443bf5f71e2f6f1947037 | Team-on/works | /0_homeworks/Python/Console/2/List.py | 1,234 | 3.953125 | 4 | # List with cubes
n = (int)(input("N: "))
list1 = [x**3 for x in range(n+1) if x % 2 == 1]
for i in range(n + 1):
if i % 2 == 1:
list1.append(i**3)
print(list1)
# List from n-1 to n+1
n = 0
while n < 3:
try:
n = int(input("n: "))
except:
n = 0
list2 = [i for i in range(n-1, n+1)... |
77f8340ef149c9ae11ff756444aea29acef9653a | cookie-rabbit/LeetCode_practice | /easy/1112/1.py | 883 | 3.78125 | 4 | # 给你两个数组,arr1 和 arr2,
# arr2 中的元素各不相同
# arr2 中的每个元素都出现在 arr1 中
# 对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。
# https://leetcode-cn.com/problems/relative-sort-array/
from copy import deepcopy
from typing import List
arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19]
arr2 = [2, 1, 4, 3, 9, 6... |
e1d20e7b117f76c4c247bca8b1614df9bd79e8d0 | stopraining/LearningNote | /HW5/BFS_06170117.py | 1,842 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[15]:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
state1=[s] #state1為暫時存放,先把頂點丟進去
... |
d2c99083295e11c29409334ac11c1c4c4f55a2e1 | KennethStreet/Data_Structures | /Module_2/Assignment_2/queue_from_stacks.py | 2,941 | 4.21875 | 4 | # Course: CS261 - Data Structures
# Student Name: Kenneth Street
# Assignment: Project 2 - Your Very Own Dynamic Array
# Description: Max Stack data structure and it's methods
from max_stack_da import *
class QueueException(Exception):
"""
Custom exception to be used by Queue class
DO NOT CHANGE THIS CLA... |
75ed7a66f45f2f8933e2857a61a943dc1fc65d36 | rodrigomart1nez/cdin2021 | /Modulo3/Code/regresion_lineal.py | 2,567 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 9 06:53:19 2020
@author: deloga
"""
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Salarios segun el nivel del empleado dentro de una empresa
datos = pd.read_csv('../Data/Position_Sala... |
5129725716eb53eddfc4fdd5b31043cd07f277b6 | abhimita/udacity-datastructure | /active_directory/src/group.py | 2,657 | 4.03125 | 4 |
"""
Class to implement entity: group
Users or other groups can belong to a group
"""
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = [] # list storing the groups that belong to this group
self.users = [] # list of users who are part of this group
# Meth... |
7859704f339bc36fdef0b1a61a6f8d945e1aca13 | justinuzoije/List_exercises | /de_dup.py | 129 | 3.9375 | 4 | theList = [1,4,4,5,4,4,11,11]
newList = []
for i in theList:
if i not in newList:
newList.append(i)
print newList
|
87da529660f036d48801185d5daf7eab08667651 | EDU-FRANCK-JUBIN/exercices-revisions-1-Fantemis | /scene_velo_arbre.py | 1,048 | 3.921875 | 4 | import turtle
turtle.left(90)
turtle.speed(25)
def dessin_triangle (angle_triangle, couleur, angle, taille, x, y):
turtle.color(couleur)
turtle.up()
turtle.goto(x, y)
turtle.left(angle_triangle)
turtle.down()
turtle.forward(taille) # draw base
turtle.left(angle)
turtle.forward(taille)
... |
bcf3087cfbf7d27fa1daf47ac623f48b8f51102d | jmathes/projecteuler | /python/p40.py | 956 | 4 | 4 | """
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 d10 d100 d1000 d10000... |
8f6f69759b732e5a99e3fa283e5fd66f43dc2089 | chadheyne/project-euler | /problem100.py | 710 | 3.90625 | 4 | #!/usr/bin/env python
def buckets(target=1000000000000):
"""
Base equation for choosing two successive elements of the same type
from N is (b/N) * (b-1/N-1) which we need equal to 1/2.
Factoring gives us the equation:
2b**2 - 2b - n ** 2 + n = 0 and we need the first b that solves ... |
f3a1ea47856d819e78c78ec93c21042dd778b0f0 | rajdharmkar/pythoncode | /sqlitedb1.py | 1,820 | 4.5 | 4 | '''To query data in an SQLite database from Python, you use these steps:
First, establish a connection to the SQLite database by creating a Connection object.
Next, create a Cursor object using the cursor method of the Connection object.
Then, execute a SELECT statement.
After that, call the fetchall() method of the ... |
1152cbe6081fcc67ba7cc9108442d7598112aab4 | Chahat2609/radiobutton | /list.py | 148 | 4.21875 | 4 | list=[]
num=int(input("how many no. of element is entered"))
for i in range(num):
num1=input("enter numbers")
list.append(num1)
print(list)
|
6f0d4636fb3584009119d8a50c25c04464a11316 | jdrusso/reu2016 | /dev/gillespie.py | 2,433 | 4.3125 | 4 | #!/usr/bin/env python
# Proof-of-concept Python implementation of Gillespie algorithm
# for results dynamics simulation.
# - https://people.maths.ox.ac.uk/erban/Education/StochReacDiff.pdf
# - Heiko Reiger "Kinetic Monte Carlo" slides
import numpy as np
from matplotlib import pyplot as plt
# Time to run
# This blo... |
0737299cc50458ad65d2b939a44b7e3dac5b0be5 | mahshana/python-co1 | /7.py | 410 | 3.796875 | 4 | list1=[1,5,3,4]
list2=[3,5,2,4]
l1=len(list1)
l2=len(list2)
sum1=0
sum2=0
if l1==l2 :
print("both are in same length")
else :
print("both are in different length")
for i in list1 :
sum1=sum1+i
for j in list2 :
sum2=sum2+j
if sum1==sum2 :
print("sum are equal")
else :
print("sum are not equal")
f... |
66146d0f5ce4e241b4cdcbed9a85718afb3093a0 | LikeLionSCH/9th_ASSIGNMENT | /17_채희찬/session3/code1.py | 259 | 3.78125 | 4 | userInput = int(input("숫자를 입력하세요 >> "))
sumNumber = 1
print(str(userInput) + "! = ", end="")
for count in reversed(range(1, userInput+1)):
print(str(count) + "x", end="")
sumNumber = sumNumber * count
print("\b = " + str(sumNumber)) |
938ba749207db2a59c3f0fb73efeb4d50ff6ae67 | Joelsondrigu/CursoPython | /Nova pasta/desafio34-35-36.py | 957 | 4.03125 | 4 | """
salario = float(input('DIGITE SEU ATUAL SALÁRIO: '))
if salario > 3000:
aumento = salario + (salario * 10 / 100)
print('PARABÉNS! VC GANHOU AUMENTO DE 10%''. Seu novo salário é de: R$ {:.2f}'.format(aumento))
else:
aumento = salario + (salario * 15 /100)
print('PARABÉNS! VC GANHOU AUMENTO DE 15%''. ... |
097035a94d73faced123262f9a8cd1696562cab4 | Tuchev/Python-Fundamentals---january---2021 | /03.Lists_Basics/02.Exercise/02. Multiples List.py | 225 | 3.703125 | 4 | factor = int(input())
count = int(input())
number_list = []
number_list.append(factor)
new_number = factor
for num in range(1, count):
new_number += factor
number_list.append(new_number)
print(number_list) |
54cf7744132d36e8d20d8d662a2bdf1e123f8758 | KaranDar/Binary-Search-1 | /problem_2.py | 1,214 | 4.21875 | 4 | # Time Complexity : O(log N)
# Space Complexity : O(1)
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach:
# Since its an infinite sorted array I try to find the upper bound
# for the binary search. And then call binary search on just those index
def binary_s... |
f80eaff59f57e713ac764fa9d8651238d750c9d7 | zagbapu/Algorithm_Project | /Reference Code/Output/movingCircle.py | 2,355 | 3.515625 | 4 | import pygame
# --- constants ---
#grid
W = 25
H = 25
M = 2
SIZE = (550, 700)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
FPS = 25
# --- classes ---
class Player:
def __init__(self):
# to keep position and size
self.rect = pygame.Rect(0, 0, 20, 20)
# set s... |
a0d9b41cb5dc158e4d8613d869727a78bc7f8146 | ScottNg49/Practice_Python_Complete | /Practice 12 - List Staggering.py | 246 | 4.0625 | 4 | #Write a program that takes the beginning element and a end element fo a list
#A list will be predefined
def stagger(lists):
newList = (lists[0], lists[-1])
return newList
x = [5, 10, 15, 20, 25]
x = stagger(x)
print(x)
|
222649212af7ecba7626edc992c379c2e27fb840 | jpatton770/objective6-josh-patton | /obj6/try2.py | 447 | 4 | 4 | #Condition-controlled iterations
# Subroutine to show spread of a virus
def ModelVirus(Day,CurrentCases,R,Target):
PopulationInfected = CurrentCases
while PopulationInfected < Target:
PopulationInfected = int(CurrentCases * (2.718 ** (R * Day)))
print("People infected on day {}: {}".format(Day , Population... |
ee7201e9ba61313fdc4562b3d3f40189fe9c3d45 | acarter881/exercismExercises | /pythagorean-triplet/pythagorean_triplet.py | 335 | 3.625 | 4 | def triplets_with_sum(number):
tripList = []
for i in range(1, int(number / 2)):
for j in range(i + 1, int(number / 2)):
for k in range(j + 1, int(number / 2)):
if (i ** 2 + j ** 2) == (k ** 2) and i + j + k == number:
tripList.extend([[i,j,k]])
... |
59a082deaad82292254da1b517e7f02d1c2c180c | ZhangZero1/MechWarfare | /mech_warfare/mech_server/RotationalMath.py | 3,130 | 3.515625 | 4 | import math
import numpy as np
class Radius(object):
def __init__(self, pivot, end_position):
super(Radius, self).__init__()
self.pivot = pivot
self.end_position = end_position
self.radius = self.end_position - self.pivot
def getVector(self):
return self.radius
... |
e1b354e37ea622c7b7977ad0a2e47d56dd14346b | Buffer0x7cd/competiitve_programming | /codechef/NW1.py | 645 | 3.59375 | 4 |
day_index = {"mon":0, "tues":1,"wed":2, "thurs":3, "fri":4, "sat": 5, "sun": 6}
def main():
t = int(input())
for i in range(t):
days = [4]*7
#print(days)
inputstr = input().split()
totaldays = int(inputstr[0])
#print(inputstr[0], inputstr[1])
day_index_value =... |
3e5413f0c058329707ef0d0f25b3510ca039c6df | ahmed82/Python-for-Data-Science | /lab_files/lab_panda.py | 861 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 03:14:56 2020
@author: 1426391
Writing Files
We can open a file object using the method write() to save the text file to a list.
To write the mode, argument must be set to write w.
Let’s write a file Example2.txt with the line: “This is line A”
"""
#you will need th... |
436068ad8e28c9172936287e27731f08cdc1c0d4 | Venekathas/Python-Sophomore-Year | /Assignment 5/exceptions.py | 842 | 4.3125 | 4 | # Exception handling examples
# Adopted from www.python-course.eu
# Repeatedly prompt the user for input until they enter an integer
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
# if the previous statement executes without error, loop terminates
break
exce... |
dac0d5faf32adec2b3a78f229bdbb3d6ccca3f6c | dragonesse/aoc | /2016/day14.py | 2,436 | 3.75 | 4 | import hashlib;
import re;
import sys;
print("Day 14 puzzle: One-Time Pad");
if(len(sys.argv) == 1):
print ("Please provide salt as argument!");
sys.exit();
else:
salt = sys.argv[1];
int_index = 0;
num_found = 0;
max_num_keys = 64;
def generate_md5 (input):
hash_vault = hashlib.md5(str.encode(inpu... |
d61f1b46829bd04bc4ce75b63bf50af6c76a49de | webturing/PythonProgramming_20DS123 | /lec02-branch/rank.py | 143 | 3.625 | 4 | n=int(input().strip())
rank="F"
if n>=90 and n<=100:
rank='A'
if n>=80 and n<90:
rank='B'
if n>=70 and n<80:
rank='C'
print(rank)
|
f558539269d847d2c23d9d61e2111e470803cc64 | DamiSoh/DE-code-study | /ThisIsCodingTest/4_sequentialSearch.py | 1,930 | 3.625 | 4 | # 이진탐색 (binary Search) - 1
"""
n = 원소갯수 (10)
target = 찾고자하는 값 (7)
array = 숫자 리스트 (1 3 5 7 9 11 13 15 17 19)
"""
#재귀함수 이용
def binary_search(array, target, start, end):
if start > end:
return None
mid = (start+end)//2
if array[mid] == target:
return mid
elif array[mid] > targe... |
e08b0802428b25f3d6c3aec4a833073998ef9818 | pathtara/CP3-Pathtara-Tungcharoen | /Lecture54_Pathtara_T.py | 1,782 | 3.984375 | 4 | def login():
for chance in range(3):
chance = 2 - chance
usernameInput = input("Username : ")
passwordInput = input("Password : ")
if usernameInput == "admin" and passwordInput == "1234":
print("Login Success")
print(showMenu())
... |
c1cfd3ae5ecd7b782d7132aeb486ceb5a5798fcf | dsahney/Restaurant-Recommendations | /restaurants.py | 6,653 | 4.46875 | 4 | """
A restaurant recommendation system.
Here are some example dictionaries. These correspond to the information in
restaurants_small.txt.
Restaurant name to rating:
# dict of {str: int}
{'Georgie Porgie': 87,
'Queen St. Cafe': 82,
'Dumplings R Us': 71,
'Mexican Grill': 85,
'Deep Fried Everything': 52}
Price to ... |
ba256af20235349fa0cdffd57784318953f574c9 | hat20/Python-programs | /function_max3.py | 311 | 4.25 | 4 | print("Prints the largest of three numbers")
a = int(input("Enter 1st number "))
b = int(input("Enter 2nd number "))
c = int(input("Enter 3rd number "))
if a>b:
if a>c:
print("The largest no. is",a)
if b>a:
if b>c:
print("The largest no. is",b)
if c>a:
if c>b:
print("The largest no. is",c) |
aabf3799ac62475d62d599045d14a56e93e8aa4b | AlejandroGarcia95/TDA_TP2 | /FlujoRedes/flujoRedes.py | 9,948 | 3.75 | 4 | class Arista(object):
''' Clase Arista. Se crea con un nodo fuente u, un nodo sumidero v y la capacidad
de la arista w. RevArista es la arista que va de v hacia u. '''
def __init__(self,u,v,w):
self.fuente = u
self.sumidero = v
self.capacidad = w
self.revArista = None
def __str__(self):
return "%s -> ... |
65e52c26bb052a542a8daa9f1f88781055a39bfc | harshitkandhway/learning_python | /assignments/Section02.py | 1,042 | 4.1875 | 4 | # Assignment 1
my_list = [{'Tom': 20000, 'Bill': 12000}, ['car', 'laptop', 'TV']]
print(my_list[0]["Bill"])
print(my_list[0].get("Bill"))
# Assignment 2
"""
Tom has a salary of 20000 and is 22 years old. He owns a few items such as
a jacket, a car, and TV. Mike is another person who makes 24000 and is 27 years old
who... |
5668d9edb51acf779190e40a3f18db259bcd5e6a | AE789/CG120 | /picture.py | 3,686 | 3.71875 | 4 | ###########################################################################
# Bill Cypher #
# #
# Programmed by Alvaro Espinoza #
# Class: ... |
fef5dd3e3d3356847003a298eacad95f33550770 | ly21st/my-algorithm | /python-vsc/geekbangtrain/week04/my_exerise/job/pandas_sql.py | 3,129 | 3.53125 | 4 | # 1. SELECT * FROM data;
# 2. SELECT * FROM data LIMIT 10;
# 3. SELECT id FROM data; //id 是 data 表的特定一列
# 4. SELECT COUNT(id) FROM data;
# 5. SELECT * FROM data WHERE id<1000 AND age>30;
# 6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;
# 7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = ... |
a41bf985266b33532c178401f57d4d6dbaed5c7c | albertopul/kurs | /cars.py | 2,938 | 3.984375 | 4 | class Car:
def __init__(self, make, model_name, top_speed, color):
self.make = make
self.model_name = model_name
self.top_speed = top_speed
self.color = color
# Variables
self._current_speed = 0
def accelerate(self, step=10):
self.current_speed += step
... |
ef8b9904bbaf95f0ee8e7b53ecff67ae4b2593c9 | huboa/xuexi | /oldboy-python18/day04-函数嵌套-装饰器-生成器/00-study/00-day4/生成器/生成器.py | 1,807 | 4.28125 | 4 | #生成器:在函数内部包含yield关键,那么该函数执行的结果是生成器
#生成器就是迭代器
#yield的功能:
# 1 把函数的结果做生迭代器(以一种优雅的方式封装好__iter__,__next__)
# 2 函数暂停与再继续运行的状态是由yield
# def func():
# print('first')
# yield 11111111
# print('second')
# yield 2222222
# print('third')
# yield 33333333
# print('fourth')
#
#
# g=func()
# print(g)
#... |
73462af511aa4af666b0c854ef9f94cc80248e01 | PMiskew/codingbat_solutions_python | /warmup1/monkey_trouble.py | 1,921 | 4.34375 | 4 | '''
QUESTION:
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
monkey_trouble(True, True) → True
monkey_trouble(False, False) → True
monkey_trouble(True, Fal... |
329a0d96209046262335e90b284539de4d08347c | wojtez/ThePythonWorkbook | /034.EvenOrOdd.py | 315 | 4.5625 | 5 | # Write a program that reads an integer from the user. Then your program
# should display a message indicating whether the integer is even or odd.
number = int(input('Enter integer number: '))
if number % 2 == 1:
number = 'Number you enter is even'
else:
number = 'Number you enter is odd'
print(number) |
c68be91dd32b0f755922029736a71f4efa2903f8 | cued-ia-computing/flood-ckh31-cwl46 | /floodsystem/analysis.py | 1,208 | 3.890625 | 4 | """ This module contains functions to computer least-square fit
of a polynomial to water level data.
"""
from matplotlib import dates as mpldates
import numpy as np
import datetime
def polyfit(dates, levels, p):
"""Take lists of dates and levels, and an integer p as the
degree of polynomial. Compute least-s... |
86f403a80436610ccd3d5611f6cd306d10ae1ece | lavindiuss/Algorithms | /linear_search.py | 454 | 4.03125 | 4 |
def search(arr,x):
"""
here we use linear search algorithm to get x index from our array
arr = array
x = our search key
algorithm complexity = O(n)
"""
for i in range(0,len(arr)):
if arr[i] == x:
return i
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = sea... |
b54bc19fe691503520123e4d04c356bb77f0db77 | NicolasRoss/CP460-Cryptography | /A5/utilities.py | 7,162 | 3.6875 | 4 | import random
import string
import math
# 1- get_lower()
# 2- shift_string(s,n,d)
# 3- get_B6Code()
# 4- bin_to_dec(b)
# 5- is_binary(b)
# 6- dec_to_bin(decimal,size)
# 7- xor(a,b)
# 8- get_undefined(text,base)
# 9- insert_undefinedList(text, undefinedList)
# 10- remove_undefined(text,base)
#------------... |
a4747041e7d45c816782bc2b23cc8b26d5cbadb7 | subhash4061/Trees-3 | /path sum-ii.py | 1,103 | 3.65625 | 4 | # TC-O(n**2)
# SC-O(n)n=height
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[in... |
31197f2386691bc730598c1c740dda0ec4649d71 | BjossiBongo/Verk5 | /Verk5/Verkefni5_2.py | 451 | 3.953125 | 4 | n = int(input("Enter the length of the sequence: ")) # Do not change this line
for i in range(1,n+1):
if i==1:
first_num=1
print(first_num)
elif i==2:
second_num=2
print(second_num)
elif i==3:
third_num=3
print(third_num)
else:
next_num=first_num+... |
6fca052582ac09cbaf8bc91a3956853f59efd0c6 | fabriciolelis/python_studying | /Curso em Video/ex029.py | 215 | 3.671875 | 4 | vel = float(input('Qual é a velocidade atual do carro? '))
if vel > 80:
print('Você foi multado!!! A multa vai custar R${:.2f}'.format((vel - 80) * 7))
else:
print('Continue assim!!! Tenha um bom dia!!')
|
d10171ce3c8e152934ca584569ec3cd2bdeeed97 | yWolfBR/Python-CursoEmVideo | /Mundo 2/Exercicios/Desafio048.py | 204 | 3.734375 | 4 | cc = 0
s = 0
for c in range(0, 501, 3):
if c % 2 != 0:
s = c + s
cc = cc + 1
print('O total de soma de todos os {} números ímpares multiplos de 3 entre 1 e 500 é {}'.format(cc, s))
|
207d0106163fd43124e359fdfcfe14af16020683 | 19-1-skku-oss/2019-1-OSS-L1 | /testing_martina/ex7_martina.py | 169 | 3.9375 | 4 | userinput=input("Enter a sentence : ")
word=userinput.split()
print("First word: ",word[0])
print("Last word: ",word[-1][ :-1])
print("Number of words:",len(word))
|
1789ce34e96beb1cb7ea22e8eb2bc5a337c04024 | JoTaijiquan/Python | /Python101-New130519/gui/2-1-2.py | 897 | 3.765625 | 4 | #Python 3.7.3
#Example 2-1-2
import tkinter as tk
import time
import math
class View(tk.Tk):
'Initializer หรือ Constructor'
def __init__(self,width=800,height=400,title=""):
tk.Tk.__init__(self)
self.title (title)
self.canvas = tk.Canvas(self,width=width,height=height)
self.can... |
8414ea4f07baa47e2e9296903a9325388a221c56 | cailloux/AoC-2020 | /day1b.py | 522 | 3.640625 | 4 | targetValue = 2020
expenses = []
total = 0
f = open("./input/day1.in","r")
for x in f:
x = x.rstrip()
expenses.append(x)
for i in expenses:
for j in expenses:
for k in expenses:
answer = 0
a = int(i)
b = int(j)
c = int(k)
total = a + b + c
if total == targetValue:
answer = a * b * c
pr... |
8df0c8e5d0047fa5c4e72dfcca56dede4196850d | imsunnyjha/python-tutorial | /sample1.py | 446 | 3.734375 | 4 | count=0
for a in range(1,1001):
if (a%2==0) | (a%3==0):
count+=1
print(count)
counti=0
for a in range(1,1001):
if (a%2!=0) & (a%3!=0):
counti+=1
print(counti)
#Here is the code printing all 3-permutations of letters a, b, c, d, e, f.
#Run the code and observe the result for better ... |
f8f6c07caf1d2e8646aa99ece197e0f29c62ef27 | thoth-ky/algorithms-and-data-structures | /search/sequential.py | 1,063 | 3.71875 | 4 | def sequential_search(item_list, item):
for index, value in enumerate(item_list):
if value == item:
return True
return False
def alt_seq_search(item_list,item):
n = len(item_list)
pos = 0
while pos < n:
if item_list[pos] == item:
return True
pos += 1
return False
data = [1,2,3,4,'... |
ca51172a5ec9a04f09bce946cf84f7211b882d34 | abbottwhitley/autonomous_vehicle_design | /python_practice/file_operations/lesson2.py | 1,081 | 4.125 | 4 | # Random number file writer
# 1. Write random integers to a file named randData.txt
# 2. Range of random numbers: [1, 100]
# 3. User specifies quantity of random numbers to store in file
import random
def generateRandomNumber(min, max):
randomValue = random.randint(min, max)
return randomValue
def ma... |
e0fa482d099ee090c77b68b37f6d1182016269cc | L200184137/praktikumAlgopro | /coba 7.4.py | 667 | 3.921875 | 4 | from datetime import datetime
import time
print ('program menampilkan waktu komputer')
while int(datetime(). strftime('%S'))>0:
print (datetime.now().strftime('%H:%M:%S'))
int (datetime.now().strftime('%S'))
time.sleep(1)
print ('jam praktikum sudah habis. silahkan pulang.')
print (datetime.now(... |
61cbae7ca04eec4966fdebe5e751db2802068a98 | srk-ajjay/Python_Exercises_Jan2020 | /list_for_shashi.py | 103 | 3.75 | 4 | num_list = [1, 3, 5.6, 72]
#for var in num_list:
# print(var)
for var in num_list:
print(var * var)
|
9443825a661d11310d53d57dbfa7d3164ac293dc | netotz/codecamp | /misc/avg_words_len.py | 319 | 4.0625 | 4 | # For a given sentence, return the average word length.
# Note: Remember to remove punctuation first.
from statistics import mean
sentence = input()
for char in ',.;:?!-':
if char in sentence:
sentence = sentence.replace(char, '')
lengths = (len(word) for word in sentence.split())
print(mean(lengths))
|
ed8609f16c15d6590ce44871e3a755493056efa7 | Divij-berry14/Python-with-Data-Structures | /Lexicographically largest string.py | 1,833 | 3.75 | 4 | """Given a string S and an integer K, the task is to generate lexicographically the largest string
possible from the given string, by removing characters also,
that consists of at most K consecutive similar characters.
Input: S = “baccc”, K = 2
Output: ccbca
Input: S = “ccbbb”, K = 2
Output: ccbb
"""
def next_avail... |
1da4709f81afcb13cb64d06e34d7561c68cb69ed | dmic7995/IntroToPythonLL | /Ch2 Importing and Using Modules.py | 390 | 3.640625 | 4 | #
# Example file on working with modules
#
# import the math module, which contains features for working with math calculations
import math
# The math module contains lots of pre-built functions
print("The square root of 16 is: ", math.sqrt(16))
# In addition to functions, some modules consist of useful constants
pr... |
6a2efdd1ae12902d163d387d8268625492fa4fa6 | naflymim/python-exercises | /Fundamental/Objects/type.py | 520 | 3.546875 | 4 | num1 = 496
num2 = 285
print(id(num1))
print(id(num2))
num1 = num2
print(id(num1) == id(num2)) #True
numList = [2, 4 ,6 ,8]
numList1 = numList
print(id(numList) == id(numList1)) #True
m = [9, 15, 24]
def modify_list(k):
k.append(39)
print("K=", k)
modify_list(m)
print("m=", m)
f = [25, 28, 78]
def replace(... |
943fa17a6561d1d122a5b8475584081e641cecf1 | KwSun/LearnPython | /IO/stringio_test.py | 322 | 3.53125 | 4 | '''
Created on 2015年10月17日
@author: apple
'''
from io import StringIO
# write to StringIO:
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
# read from StringIO:
f = StringIO('L \n O \n V \n E')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
|
5d8ba443d022052f87eb041628b431ac87dc506a | teodorklaus/PyStudy | /additional/day2.Additional.7.py | 406 | 4.1875 | 4 | num = int(input('Enter numeral range of from 1 to 12: '))
if num >= 1 and num <= 2 or num == 12:
print ('Winter month: ' + str(num))
elif num >= 3 and num <= 5:
print ('Spring month: ' + str(num))
elif num >= 6 and num <= 8:
print ('Summer month: ' + str(num))
elif num >= 9 and num <= 11:
print ('Autum... |
c5909565546a0d9ea8ec6986622593aefa00652e | TrendingTechnology/Nertivia.py | /nertivia/user.py | 1,761 | 3.5 | 4 | class User(object):
"""
Object representing a user
"""
def __init__(self, user, **kwargs):
"""
Instantiate variables to be used later on
"""
# If the user is not cached
if "user" not in user:
user = {"user": user}
# Check whether the user ID i... |
4f11262207a82310195931e0a3d6e5213cf0273d | ihernandezvelarde/Python_exercises | /Ejercicios basicos/exercici7.py | 288 | 3.828125 | 4 | print("Introduce tu edad para saber si tienes que tributar este año: ")
edad= int(input())
print("Introduce tus ingresos mensuales: ")
ingresos= int(input())
if edad>16 and ingresos>=1000:
print("Este año si que tienes que tributar!")
else:
print("Aun no tienes que tributar!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.