blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2cabdbd1f2459f739b09fcbe1102593e6853e40a | scienceman44/SAVY | /proj04/proj04.py | 1,232 | 4.15625 | 4 | # Name:
# Date:
"""
proj04
Asks the user for a string and prints out whether or not the string is a palindrome.
"""
loop_control = True
g = []
p = []
j = raw_input('I am the computer')
h = raw_input('I calculate palindromes')
k = raw_input('I know all')
while loop_control == True:
d = raw_input('type a word for ... |
be4ee1d1480f235b52c96c8aa291c81e68a934c9 | impradeeparya/python-getting-started | /string/LongestPalindrom.py | 1,227 | 4 | 4 | def init_2d_matrix(matrix, input_str):
input_chars = list(input_str)
for row in range(len(input_chars)):
matrix[row][row] = 1
start_index = 0
max_length = 1
for row in range(len(input_chars) - 1):
if input_chars[row] == input_chars[row + 1]:
matrix[row][row + 1] = 1
... |
767caa6244993880a18ab0632da2326d2ddd4c4f | chowdhurykaushiki/python-exercise | /PracticePython/Exercise5.py | 750 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program w... |
6ad25abd1e5f37d8926c6f293a9dd3941025a96b | gitdog01/AlgoPratice | /programmers/main.py | 257 | 3.515625 | 4 | def pre(root) :
if root == '.':
return
print(root,end='')
pre(tree[root][0])
pre(tree[root][1])
n = int(input())
tree = {}
for i in range(n):
root,left,right = input().split()
tree[root] = (left,right)
print(preorder('A')) |
768167284e15bfbb5fd79991a9ad1c9642e3cf43 | imbaxl/- | /psychologistic/data_input.py | 754 | 3.59375 | 4 | import pandas as pd
columns_list = ['Name','O','C','E','A','N']
#df = pd.DataFrame(columns=columns_list)
df1 = pd.DataFrame(columns=columns_list)
df = pd.read_excel('psychologistic/data.xlsx',index_col=0)
print(df)
#转成dataframe类型,再用append方法合并
def input_data():
list = [0,0,0,0,0,0]
for i in range(6):
pri... |
f60d596420574ed39c5530ea5f66cfe6fb34d88b | liuya2360/H2-Computing | /Practical Practice/SH2/T1W1_Revision_LY/6.py | 356 | 3.734375 | 4 | #T1W1
# quick sort
def qsort(l):
if len(l) < 2:
return l
else:
less = []
more = []
pivot = l[0]
for i in range(1, len(l)):
if l[i] <= pivot:
less.append(l[i])
else:
more.append(l[i])
return qs... |
49c982f1ad3a4fcb41c7cac709ad8c116efe4e3e | TahaAlTamimi/python | /temp.py | 2,678 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#name=input('tell me')
#age=input('your age:')
#print('hello',name,'your age',age)
#raduis=input('raduis please:')
#results=3.14*int(raduis)**2
#print('the',raduis,'area equal',results)
#st='heello'
#print(st)#
#print('hello', 'world')
#X... |
a6364fdb9a9f9d56775a8edde6909bf76d94586e | Tabish13/nltknlp-NaiveBayesClassifier | /replaceSlang.py | 413 | 3.875 | 4 | lookup_dict = {'liv':'liva', 'fabrik':'fabric', "fab" : "fabric", "by" :"buy","bye":"buy"}
def _lookup_words(input_text):
#words = input_text.split()
words = input_text
new_words = []
for word in words:
if word.lower() in lookup_dict:
word = lookup_dict[word.lower()]
... |
c690f30cebe89da7b70798af022b4009115ede90 | XTmingyue/Algorithm | /探索/数组与字符串/035_SearchInsert.py | 899 | 4.03125 | 4 | #!/usr/bin python
# -*- coding: utf-8 -*-
# @Time : 2020/8/18 12:01 上午
# @Author : xiongtao
# @File : 035_SearchInsert.py
'''
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
'''
import math
class SearchInsert():
def searchInsert(self, nums, target):
left = 0
right = l... |
b1919154290d9035ff4fbc16270f76c0c7e00381 | kcc3/hackerrank-solutions | /problem_solving/python/algorithms/strings/camel_case.py | 810 | 4.625 | 5 | def camel_case(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/camelcase/problem
Alice wrote a sequence of words in CamelCase as a string of letters, s, having the following properties:
- It is a concatenation of one or more words consisting of English letters.
- All letters in the fi... |
df36da421a071eb4af3da89d1358a9a717bb21b2 | smazzone/python_playground | /inherit_composition_car.py | 1,177 | 4.125 | 4 | from random import randint
from classes_car import Car
from battery_composition import Battery as Battery
# When you create a child class, the parent class
# must be either part of the current file and must appear
# before the child class in the file
# or you can import it from another module
class ElectricCar(C... |
15a7548d57ce051c16e27dbb4f7000ebc24a3918 | sagarrjadhav/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /Stack/TwoStack.py | 1,256 | 3.90625 | 4 | #!/usr/bin/env python
from collections import deque
class TwoStack(object):
def __init__(self):
self.data = deque([])
self.size1 = 0
self.size2 = 0
def StackPush1(self, value):
self.data.appendleft(value)
self.size1 += 1
def StackPop1(self):
... |
eae1f215371bb136f5a8b594cc0a961dc711ab6a | bknie1/String-CRC | /StringtoBinary.py | 1,088 | 4.03125 | 4 | # String to Binary
# Assignment 2
# Brandon Knieriem
# Files: StringtoBinary.py, stb_fx.py
# Goals:
# - Generate bit sequence based on input.
# - Query loop to generate 1+ bit sequence.
# - Process input as string.
# - fx1: Takes single char. Returns binary.
# - ord() function returns index in ASCII code.
# - G... |
0420d77bff71ac06a2eea6d07fd9d515b7fb5cf0 | CrazyCoder4Carrot/lintcode | /python/Merge k Sorted Lists.py | 2,198 | 4.0625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
"""
Naive version failed.
O(N*N) complexity
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLi... |
a51aec784a31f3fcf4a13dde48e753f9688dee03 | kilura69/softuni_proj | /0_admission_prep/03_for_loops/01_tennis_ranklist.py | 581 | 3.640625 | 4 |
# ************** 05.tennis ranklist (for loop) ********************************
tournaments = int(input())
starting_points = int(input())
points = 0
wins = 0
for tournament in range(tournaments):
reached = input()
if reached == 'W':
points += 2000
wins += 1
elif reached == 'F':
... |
4aa20445a08a13b844be5e1802b0e9a4a0167446 | tuckerrking/intro_to_cs_projects | /Chap-2-Lab.py | 219 | 4.1875 | 4 | # Program takes input on command line,
# saves that input to a variable,
# and prints it out.
favorite_movie = input ("What is your favorite movie? ")
print ("So, your favorite movie is " + favorite_movie + "? Nice!")
|
f01b03382d41bfb9a5652baabca2e10e47ca555b | sahana-bs/Aggression-Detection-1 | /src/model/pickle_.py | 430 | 3.765625 | 4 | import os
import pickle
from abc import ABCMeta, abstractmethod
class Pickle_(metaclass=ABCMeta):
def __init__(self,path_):
pass
@abstractmethod
def save_model(self):
"""This takes the path variable and saves the model."""
@abstractmethod
def load_model(self):
"""loads th... |
c04553b33a32999e281c7ea0b0774585003d6019 | stalkerchok/PVDM | /practical_lesson_2/task_3.py | 1,612 | 3.890625 | 4 | # coding=utf-8
import unittest
from practical_lesson_1 import task_1, task_2, task_3
class TestTasks(unittest.TestCase):
# --------------------
# Реализовать юнит-тесты с использованием пакета unittest для задач первой лекции (1,2,3).
# --------------------
def test_task_1(self):
input_array =... |
bbd856b9febb78c1af984d10d2ad12c15b227e44 | PetarSP/TicTacToe | /winning_condition.py | 937 | 3.71875 | 4 | from drawings import *
from console_board import *
def winning_condition(player):
# vertical condition
for col in range(BOARD_COLS):
if board[0][col] == player and board[1][col] == player and board[2][col] == player:
draw_vertical_winning_line(col, player)
return True
... |
e2c74a72046e7d0486496d33163cb79c586dd150 | hustrmcv/hustrmcv.github.io | /submit/perceptron/CXY/matplotlib_visual/感知机.py | 2,549 | 3.53125 | 4 | # 符号函数
import numpy as np
import random
import matplotlib.pyplot as plt
def sign(v):
if v > 0:
return 1
else:
return -1
'''
def test():
(weight, bias) = training()
while True:
test_data = []
data = input('enter test data (x1, x2): ')
if data == ... |
4791e817b54888a74a9f4b942aa72fd4f7abddd4 | khmahmud101/CodingBat_problem_solve | /Logic-1/love6.py | 157 | 3.921875 | 4 | def love6(a, b):
res = a+b
sub = a-b
sub2 = b-a
if (a is 6 or b is 6) or res == 6 or sub == 6 or sub2 == 6:
return True
else:
return False
|
6016b5ffe563a5d8fc70fa28df2f809b5f6af412 | Abhiram1214/ML_Learning | /game.py | 5,546 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 9 04:31:02 2019
@author: abhiram_ch_v_n_s
Intro: practising python classes by creating a address book
"""
from tkinter import *
class address_book:
def __init__(self, master):
self.phone_book = {}
self.master = master
self.frame_he... |
2e88e71a0e3a579e5da38535e2431ae99bac13b7 | yanolsh/dev-sprint4 | /chap11.py | 973 | 3.71875 | 4 | import string
#11.9
'''
def has_duplicates(strt):
return len(set(t)) < len(t)
'''
#11.10
def rotate_letter(letter, n):
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return letter
c = ord(letter) - start
i = (c + n) % 26 + st... |
8df6d87471ce6357ff7f1909b5f7ffbac97fec09 | matheusb432/hello-world | /Learning Python/string2.py | 192 | 3.578125 | 4 | first = 'John'
last = 'Smith'
message = first + ' [' + last + '] is a coder'
msg = f'{first} [{last}] is a coder' # Uma string formatada ( f'' ), as variaveis estao em {}
print(message) |
1a778894406bebf17186f441c812ee3b7729e0ff | pyasger/python | /p/Correctedinclass_graderPJY.py | 406 | 3.875 | 4 | #
#
#
A_SCORE = 100
B_SCORE = 50
C_SCORE = 20
D_SCORE = 10
def main():
#
score = int(input('Please enter your quantity: '))
#
if score >= A_SCORE:
print('Take a 50% discount.')
elif score >= B_SCORE:
print('Take a 40% discount.')
elif score >= C_SCORE:
print('Take a 30% discount.')
elif score >= D_SCO... |
4a9a06c0cf81ae2268b5bb1f69ae3b3a0fd5f1d5 | Bl41r/code-katas | /simple_graph.py | 11,523 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""Simple graph implementation.
Simple edge-weighted graph data type which contains a dict of nodes. Nodes are a
class, which makes them adaptable for additional attributes to be added.
In this implementation, weight is a positive integer directional edge.
This branch features two shortest pa... |
6e28b346693fe8c2c77cd8b747d734a4ab59a90c | GeekChao/Coding | /Educative/coding/dfs/ex2.py | 1,027 | 3.671875 | 4 | """
Problem:
Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’.
Difficulty: Medium
"""
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_p... |
006a8f23943437105848c2898d816e2465982b91 | tushartyagi/algorithms | /python/algorithms/binarysearchtree.py | 4,991 | 4.28125 | 4 | import pdb
class Node:
def __init__(self, value, parent=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def __str__(self):
return 'Node({self.value})'.format(self=self)
__repr__ = __str__
def inorder_walk(... |
6385f9ef0152ddad63a1abe5550d7d4eeea1ebf6 | armaanlalani/NLP-Sentence-Objectivity | /subjective_bot.py | 2,399 | 3.53125 | 4 | """
6. Testing on Your Own Sentence.
You will write a python script that prompts the user for a sentence input on the command line, and prints the
classification from each of the three models, as well as the probability that this sentence is subjective.
An example console output:
Enter a sent... |
6e098a2b74567abe16b24b8505d4b14d4ff10a8b | master-sandman/python-stuff | /functional_test.py | 812 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import unittest
import functional
class TestFunctional(unittest.TestCase):
def test_sum(self):
r1 = 1 + 2 + 3 + 4 - 5
r2 = functional.sum(1, 2, 3, 4, -5)
self.assertEqual(r1, r2)
def test_mul(self):
r1 = 1 * 2 * 3 * 4 * -5
r2 = fu... |
e0c5a3ef497f1578f94566b379c7d879ec4ebe37 | M-Quadra/LeetCode-problems | /Algorithms/10/spfa.py | 1,208 | 3.671875 | 4 | from queue import Queue
from typing import Tuple
class Solution:
dp = {(0, 0): True}
q: Queue[Tuple[int, int]] = Queue()
def addNext(self, next: Tuple[int, int]) -> None:
if self.dp.get(next, False): return
self.dp[next] = True
self.q.put(next)
def isMatch(self, s: str, p: str... |
127e800726bf4d12c8589962a9e18a4f8ac23a0b | vpc20/python-basics | /WhileLoops.py | 157 | 3.515625 | 4 | s1 = 'abcdefghij'
i = 0
while i < len(s1):
print(s1[i], end=' ')
i += 1
print(' ')
i = len(s1)
while i > 0:
i -= 1
print(s1[i], end=' ')
|
82554340f959d03be39b4749085a237a6c609dc4 | sambapython/rajyalakshmi | /a.py | 247 | 3.609375 | 4 | x=1000
y=2000
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
if __name__ == "__main__":# name block.
hidden1=10000
print("this is a")
print("__name__:",__name__)
print(x,y)
print(add(100,200))
print("a ended") |
3ae6c3e149cfb892f25868902604d8d3863db017 | fangzli/Leetcode | /src/RotateArray.py | 861 | 4.125 | 4 | def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums2 = [None] * len(nums)
for i in range(len(nums)):
nums2[(i + k) % len(nums)] = nums[i] # this make sure it works even if k > n
return nums2
... |
ab64a3d0e29440ab5b325025b00880d781a2f816 | Mister905/flask_api_21 | /python_review/12_destructuring/code.py | 255 | 4.125 | 4 | tuple = 5, 11
# Destructure tuple
x, y = tuple
print(x, y)
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}
print(list(student_attendance.items()))
for student, attendance in student_attendance.items():
print(f"{student}: {attendance}") |
17f6bac554e7ac10148ec268a77ed73a3d744468 | welydharmaputra/ITP-lab | /tugas2.py | 238 | 3.703125 | 4 | def main():
for x in range(1,6):
for y in range(1,6-int(x)):
print(" ",end="")
for z in range(1,int(x)+1,1):
print("*",end="")
print()
if __name__=="__main__":
main()
|
8f92deda4b23e4426ee08b663d9fce79576379a6 | XMK233/Leetcode-Journey | /py-Jindian/17.11.py | 1,401 | 3.578125 | 4 | '''
[面试题 17.11. 单词距离 - 力扣(LeetCode)](https://leetcode-cn.com/problems/find-closest-lcci)
有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
示例:
输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
输出:1
提示:
words.length <= ... |
e8a4165f429040e509efc752d9f7dd9e3b3943fd | H1tman1978/GranthamUniversity | /Python/BMI Calculator/BMI_Calculator.py | 1,461 | 4.34375 | 4 | #!/usr/bin/python
#-*-coding: utf-8 -*-
#This program obtains date on height and weight from the user and then calculates the BMI based on that data.
#Methods
#This method obtains the name of the person from the user.
# NOTE: This method should be run before the getWeight and getHeight methods
def getName()... |
93d2039e686aa7f9dc539cf5c10cd01822acf7a8 | siddhism/leetcode | /leetcode/743.network-delay-time.py | 3,084 | 3.515625 | 4 | #
# @lc app=leetcode id=743 lang=python
#
# [743] Network Delay Time
#
# @lc code=start
class DSU(object):
def __init__(self, N):
from collections import defaultdict
self.N = N
self.parent = defaultdict(int)
# initialize parent to self
for i in range(N+1):
sel... |
68abea18e03293ec346e1792fee235b78392adfe | vetlelode/machinelearning_exam | /src/comparison.py | 3,160 | 3.546875 | 4 | from sklearn.metrics import classification_report, confusion_matrix
import sys
import numpy as np
import pandas as pd
from preprocessing import get_dataset
from knn import runKNN, knnGridSearch, knn_NCA, dim_reduc, knn_PCA
import seaborn as sn
import matplotlib.pyplot as plt
"""
Compare various methods and paramaters ... |
3ac84af623457715856f68cc29887455ab1a9213 | Valeriya-VZ/SkillfactoryQAP-7 | /Модуль 14/Возведение в квадрат.py | 1,129 | 4.3125 | 4 | # функция, которая возводит любое число в квадрат
# Устанавливает аргумент фукнции и когда вызываем функцию, то вводим аргумент.
def pow_func(base):
print(base ** 2)
pow_func(3) # 9
pow_func(5) # 25
# функция, которая возводит любое число в степень n, но по умолчанию в квадрат
# теперь два аргумента. один обязат... |
d67a3cc1361eb4712f1507636ca8833c0cb20f77 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2687/60790/271410.py | 288 | 3.6875 | 4 | t=int(input())
for time in range(0,t):
n=int(input())
if(n==11 or n==10):
print("1 2 5 10")
elif(n==151):
print("1 2 5 10 21 42 85")
elif(n==15):
print("1 2 5 10")
elif(n==50):
print("1 2 5 10 21 42")
else:
print(n)
|
d7d52a631fdce3cf2a8e80cb235b27bd3db3e129 | jamesliao2016/HCDR2018 | /LT2018/top_problems/5_BST/5_2_Depth-first Search/98. Validate Binary Search Tree.py | 3,147 | 3.96875 | 4 | #!/usr/bin/env python2
# coding:utf-8
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
... |
804bb8b7cce57ef4f91cd40d8de879391876228a | phillips0616/euler100 | /cdc/problem4.py | 615 | 3.875 | 4 | import math
def isPalindrome(num):
half_num = math.floor(len(str(num)) / 2)
str_num = str(num)
rev_str = ''.join(reversed(str_num[half_num: ]))
if (len(str(num)) % 2 != 0):
half_num += 1
if (str_num[0 : half_num] == rev_str):
return True
else:
return False
... |
b02ac253739d22ae0adec54259754c3c35623bd4 | toprakm/ProjectEulerSolutionsWithPython | /problem0009.py | 614 | 3.96875 | 4 | # =============================================================================
#
# Problem 9
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Fi... |
5d318bf9567ffee5a036bdd4d1758321f04a1d67 | Maximedu13/Help-MacGyver-to-escape-from-the-Red-Keep- | /maze.py | 4,545 | 3.8125 | 4 | #! /usr/bin/env python3
# -*- coding: Utf-8 -*
"""It is the maze and items (design) game page."""
import random
import pygame
from constants import (TILESIZE, WALL_IMG, FLOOR_IMG, FINISH_LINE_IMG,
START_LINE_IMG, NBCASES)
class Maze:
"""Class to create the maze"""
# CONSTRUCTOR
def ... |
df8a79029d19d19edcf34bfbc835804a6efe7a27 | caelan-smyth/CA117-Programming-2 | /Bucketlist/lcsub_122.py | 637 | 3.671875 | 4 | import sys
def longestSubstringFinder(s1, s2):
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in range(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_lon... |
740b941feb6bde0a01718faed00932f25a7921a7 | ANDROID564/speech_recognition | /speech_recognise.py | 1,096 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 22 20:51:51 2018
@author: TANVEER_MUSTAFA
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 22 20:36:22 2018
@author: TANVEER_MUSTAFA
"""
import speech_recognition as sr # import the library
r = sr.Recognizer() # initialize recogn... |
6d9c6c01175994f9295cbbcf79b2f17924d341f1 | jlinkemeyer/MLinPractice | /test/feature_extraction/sentiment_test.py | 1,852 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test class to test the Sentiment feature functionality.
Created on Sun Oct 10 18:56:13 2021
@author: lmasch
"""
import unittest
import pandas as pd
from code.feature_extraction.sentiment import Sentiment
class SentimentTest(unittest.TestCase):
"""Test class to ... |
c14616ab58db5148a9326afc8a3aa02f051569f5 | alecerodrigues/Load-Balancing-DNS-Server-Project | /ls.py | 4,758 | 3.78125 | 4 | import threading
import time
import random
import socket
import sys
dict = {}
def ls_listen_port():
"""
This function is used to parse the ls port number argument from the console command.
:return: int - The return is an integer that represents the port number to bind to the port
"""
fullar... |
fec015fea54dc8fe0dd0d535c9d524a5b5c3abe1 | sallymroberts/coding_exercises | /print_mult_tbl.py | 528 | 4.1875 | 4 | def print_mult():
''' Print multiplication tables
'''
# Formatted string with layout for each row
layout = "{:>4}{:>6}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}{:>4}"
# Print column heading rows
print(layout.format("",1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
under = " :" + 50 * "-"... |
14dab2bc101cf9ca83a36acef647d9ae0638aa01 | noopurphalak/algorithms | /sorting/bubble_sort.py | 488 | 4.15625 | 4 | def swap(li, i, j):
temp = li[i]
li[i] = li[j]
li[j] = temp
def bubbleSort(li):
while True: # Can also do for j in range(1, len(li)) instead of while True
swapped = False
for i in range(1, len(li)):
if li[i - 1] > li[i]:
swap(li, i - 1, i)
s... |
47b0e7468c99d9997798b13b74e0345673412a7a | excelexcavator/MyLeetCode | /medium/61.py | 744 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
... |
0d945d47417aece5fa6db1245154f261b09a1c6a | BereketFeyissa/android_amharic_custom_keyboard | /code_key.py | 248 | 3.515625 | 4 | def convert_code():
for i in ('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'):
x = "120" + str(i)
print("<item name=\"\"> "+ str(int(x,16)) + " </item> <!--" + x + "--->")
if __name__ == "__main__":
convert_code()
|
aa6ae6bd9d7b2f6f1ce0946712c44638a3b7e251 | marsbarmania/ghub_py | /codingbat/List-1/common_end.py | 491 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Given 2 arrays of ints, a and b,
# return True if they have the same first element
# or they have the same last element.
# Both arrays will be length 1 or more.
# common_end([1, 2, 3], [7, 3]) → True
# common_end([1, 2, 3], [7, 3, 2]) → False
# common_end([1, 2, 3], [1, 3]) → True
def common... |
58df714142bc8b34b29e30a57f33a9a9cdc9faf6 | Esaslow/ChurnCaseStudy | /src/cleaning.py | 6,312 | 3.5625 | 4 | import pandas as pd
import numpy as np
from datetime import timedelta
import matplotlib.pyplot as plt
from importlib import reload
from src import cleaning as C
from sklearn.preprocessing import StandardScaler
def clean_city(df):
"""
Input: DataFrame
New columns, the 'city' column to dummy values
Ne... |
35a8070cc7f7629250f1136c572cabb6a4d13e92 | myusko/algosproblems | /algos/strings/count_valleys.py | 286 | 3.921875 | 4 | # https://www.hackerrank.com/challenges/counting-valleys/problem
def count_valley(s):
level = valley = 0
for x in s:
if x == 'U':
level += 1
else:
level -= 1
if x == 'U' and level == 0:
valley += 1
return valley
|
1980a56af42ff2fe4d2c6db07e41a3ffcd971355 | axme100/wordGame | /wordgame.py | 898 | 3.890625 | 4 | import word
import time
class WordGame:
def __init__(self, numberOfWords):
self.numberOfWords = numberOfWords
self.gameWords = []
self.createWords()
self.play_game()
def createWords(self):
num = 1
while num < self.numberOfWords:
myWord = self.solicitWord()
gameWord = word.Word(myWord)
... |
2e773ab229531b1b2fad7a50eb70866f962c4d9d | m-note/100knock2015 | /SatoTaka/set9/knock080.py | 981 | 3.921875 | 4 | #!/usr/bin/python
# _*_ coding:utf-8 _*_
import sys
def delete_symbol_first(word):
if not word:
return word
if word[0] not in removelist:
return word
else:
word = word[1:]
return delete_symbol_first(word)
def delete_symbol_last(word):
if word[-1] not in removelist:
... |
e39df15b560ce6fac01831f725510b42b794d718 | mmizin/42_django | /day01/ex04/state.py | 602 | 3.78125 | 4 | import sys
from pprint import pprint
states = {
"Oregon" : "OR",
"Alabama" : "AL",
"New Jersey": "NJ",
"Colorado" : "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
"NJ": "Trenton",
"CO": "Denver"
}
def get_state(capital):
if capital in capital_cities.values():
capital = [key for key, value ... |
3eae46d7950df1ea9b1cd0f4944b701d9d0d936c | Tbeaumont79/Python | /python/les_classes/class_entrainement.py | 11,864 | 3.5 | 4 | import os
import time
import random
class Mage:
def __init__(self):
self.mana = 100
self.spell_use()
dammage = self.dammage
def spell_use(self):
#cast du mage différent sort:
print("type pass if your don't want to use spell")
self.spell = ["firebolt","icebolt","a... |
5fd0aebafda1dc31198a6b9a506d78f7ef34eda0 | linhto1211/Learning-Python | /greetings.py | 245 | 3.5 | 4 | #Define function:
def add_greetings(names):
greetings=["Hello, " + name for name in names ]
return greetings
#Check if function works
print(add_greetings(["Owen", "Max", "Sophie"]))
#Answer: ['Hello, Owen', 'Hello, Max', 'Hello, Sophie']
|
56f495b32b1635e39ca706090be8063c307d9345 | tjoker1212/SI206 | /dinopygame.py | 6,319 | 3.796875 | 4 | #### I want to create game where a player runs forward and then obstacles get in his way and
# the player needs to avoid getting hit by jumping over the obstacle.
# If the player fails to jump over it and collides with the obstacle, then the player loses.
# Each time the player successfully jumps over the obstacle, ... |
2e482dad2c636279f435d3b01c69184162c9f5d1 | gabriellaec/desoft-analise-exercicios | /backup/user_325/ch35_2020_03_27_21_13_23_762912.py | 122 | 4 | 4 | p = int(input("digite um numero: "))
s = 0
while p != 0:
p = int(input("digite um numero: "))
s += p
print(s)
|
1a1d04dd6ffca1a321ff0c0109b1fbb669272bbe | ypyao77/python-startup | /deep-python/03.inner-data-type/02-bool.py | 326 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def Bool(cond):
if cond:
print("{0}: is true".format(cond))
else:
print("{0}: is false".format(cond))
if __name__ == "__main__":
Bool(None)
Bool("")
Bool("abc")
Bool([])
Bool([1,2,3])
Bool({})
Bool({"a": 1, "b": 2, "c":... |
8101e87086a4d6b0df03ee9fa9c474f6d5df8203 | gourav47/Let-us-learn-python | /31 while3.py | 329 | 4.09375 | 4 | #program 1
x = 'abcd'
for i in range(len(x)):
x[i].upper()
print (x)
'''program 2:
x = 'abcd'
for i in range(len(x)):
i[x].upper()
print (x)'''
#program 3:
x = 'abcd'
for i in range(len(x)):
x = 'e'
print(x)
#program 4:
x = 'abcd'
for i in range(len(x)):
print(x,end='')
... |
565d7804abd61e815e631af0e044646bed5198a7 | EnderCaster/MyGitExperimentSpace | /python_path/python3_brief_tutorial/7_palindrome.py | 114 | 3.890625 | 4 | #!/usr/bin/env python3
#-*- utf-8 -*-
s = input("input:")
z = s[::-1]
if z == s:
print("yes")
else:
print("no")
|
719a17468681ad73eb7153fc57879b2c852b914e | PythonAberdeen/talks | /2020-Feb/pytests/fizzbuzz.py | 822 | 3.640625 | 4 | class FizzBuzz():
fizz, buzz = 'Fizz', 'Buzz'
@staticmethod
def is_mod_three_true(number):
return number % 3 == 0
@staticmethod
def is_mod_five_true(number):
return number % 5 == 0
def is_mod_three_and_five_true(self, number):
return self.is_mod_five_true(number) and s... |
43c6f2eaed8994a5e1c5c338a0a924d8efeef860 | ShrutiGupta867/Python-Execrises | /Mongo_task_2.py | 587 | 3.65625 | 4 | import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/") # Python platform Create connection with Mongodb Compass
mydb=myclient['School']
mycol = mydb["Student"]
#2) Finding the deatils of any one student by his roll_no.
# for x in mycol.find({'Roll_No':2}):
# print(x)
# # 3) delete a... |
cf2e6f42f7894903e5f96d13d1db75912e9a9fb2 | sathya-sai/Selenium | /UnitTestFramework/SkippingTest.py | 884 | 3.71875 | 4 | """
:Summary This is python 3.7 supported usage of skipping of test cases,
:Since January 2020
:Author Sathya Sai M
:keyword Python, Selenium, Unittesting
"""
import unittest
class AppTest(unittest.TestCase):
@unittest.SkipTest # by decorator
def test_firstTest(self):
print("This... |
a71dccf9eb4512b0f22c9dcba5ae280cf073f77f | diegogcc/py-pluralsight | /advanced/advanced-python/1-advanced_flow_control/while_else.py | 3,127 | 4.28125 | 4 | '''
While-Else
while condition:
execute_condition_is_true()
else:
execute_condition_is_false()
For a simple case, it's the same as putting the false block after the while block
because eventually the condition will be 'falsy'.
while condition:
execute_condition_is_true()
execu... |
591364b01d031a7e6d62c294ea4a7f872d07f69f | ryanyun2010/home.html | /index.py | 985 | 3.640625 | 4 | from Tkinter import *
from tkFileDialog import *
filename=None
def newFile():
global filename
filename = "Untitled"
text.delete(0.0, END)
def saveAs():
f=asksaveasfile(mode='w',defaultextension='.txt')
t=text.get(0.0,END)
try:
f.write(t.rstrip())
except:
showerror(title="O... |
28caeabfc4d24d5ccb1a80f65c94c6bde6f58af8 | D4nfire/Dissertation | /Python_Code/Calculator.py | 747 | 4.15625 | 4 |
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
opperation = input("What do you want to do? (+,-,*,/): ")
if ((opperation != '+')&(opperation != '-')&(opperation != '*'... |
ef57ae22792de32da35a96cb53a0727e3259aa60 | bfarr/exocartographer | /exocartographer/util.py | 1,760 | 3.90625 | 4 | import numpy as np
def logit(x, low=0, high=1):
r"""Returns the logit function at ``x``. Logit is defined as
.. math::
\mathrm{logit}\, x \equiv \log(x - \mathrm{low}) - \log(\mathrm{high} - x)
"""
return np.log(x-low) - np.log(high-x)
def inv_logit(y, low=0, high=1):
"""Returns the ``x`... |
a15c3d682182ccad824bcb28dc177945c1378249 | akhiyarwaladi/ml_pr1 | /perceptron.py | 2,365 | 3.84375 | 4 | # Make a prediction with weights
def predict(row, weights):
#print(len(row))
activation = weights[0]
for i in range(len(row)-1):
activation += weights[i + 1] * row[i]
#print (activation)
return 1.0 if activation > 0.0 else 0.0
# Estimate Perceptron weights using stochastic gradient descent
def train_weights(tra... |
e01cfbfb0055607cceb6a6191c5ecbd80e245c32 | JosephCline/Golfclubfee | /Golfclubfee.py | 682 | 4.03125 | 4 | sClubmember = str(input("Are you a member or a non-member, type M for member or N for non-member?\n")).upper()
sDayorend = str(input("Do you practice golf on the weekend or weekday, type W for weekend or D for weekday?\n")).upper()
if sClubmember == "M":
print("You are a member of our golf club, the fee for a membe... |
83a2bab5d1c9489cd4494a5753ae73ab274a88a4 | paralex23/Calculadora2017 | /Calculadora.py | 525 | 3.59375 | 4 | # Carlos A. Hernandez
class Calculadora():
def __init__(self):
self.resultado= 0
try:
def obtener_resultado(self):
return self.resultado
def suma (self, num1, num2):
self.resultado = num1 + num2
def resta (self, num1 , num2):
self.resultado = num1 - num2
def multiplicacion (self, num1 , ... |
0fc4f859e6d60da22006879b49579dbeb0dd8f6c | noahtigner/InterviewPrep | /CrackingTheCodingInterview/2-LinkedLists/2.4-partition.py | 1,449 | 4.25 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Singly Linked
def __init__(self):
self.head = None
def insert(self, data):
# O(1)
if not self.head:
self.head = Node(data)
else:
n = self... |
21302c08b1164b1b1bbe0403be62dea9b9efe096 | alejandrobrusco/interprete-python | /Compilador/tests/test_error_return_fuera_de_funcion.py | 111 | 3.859375 | 4 | a = 0
if (a):
print "Nunca ejecuto"
a=a+5*3
break
else:
print "Entro a ELSE"
return "nunca se devuelve" |
091ed4581163402252b07d761ee4011ae923ff04 | AratiBudihale/Ball-Predicator-case-study-Machine-Learning- | /Ball1.py | 800 | 3.859375 | 4 | #Decision tree algorithm
from sklearn import tree
# Rough 1 # Smooth 0 # Tennis 1 # Cricket 2
def MarvellousDecision(weight,surface):
Features=[[35,1],[40,1],[90,0],[100,0],[20,1],[36,1],[99,0],[110,0]]
Label=[1,1,2,2,1,1,2,2]
dobj=tree.DecisionTreeClassifier()
dobj.fit(Features,Label)
Result... |
82e7e661f86118a8b6e2c70a6af0d3b653ba964f | clarkwkw/GEStatProj | /nn_grade_prediction/neural_network.py | 10,157 | 3.796875 | 4 | '''
This file defines:
1. The way to import csv files (Dataset class)
2. The way to train neural network (Neural_Network class)
3. When to stop training (Train_decider class)
4. Other utilities functions
'''
import csv
import numpy as np
import tensorflow as tf
import random
import sys
import signal
import visualizati... |
8dfb2776266944db7b3a90d097736f88b7ed0a4f | heshida01/MRMD2.0 | /feature_rank/PageRank/PageRank.py | 2,406 | 3.59375 | 4 | import math
import numpy as np
from feature_rank.PageRank.graphs import plotGraph
class PageRank:
"""PageRank of pages visualized as a graph.
Contains function to calculate the rank of pages using the Google's
PageRank Algorithm. The set of web-pages is visulaized as a directed
graph where a directed edge between... |
791345732b5b63c4575dea7ae46c8236d91d81ba | WeeJang/basic_algorithm | /IsSubTree.py | 1,335 | 3.609375 | 4 | #!/usr/bin/env python2
#-*- coding:utf-8 -*-
class Node:
def __init__(self,value):
self.value = value
self.left,self.right = None,None
def is_sub_tree(large_tree,small_tree):
""" 判断是否是子树
我当时用的是BFS搜索,其实没必要。直接递归就好。
"""
def is_same(large_tree,small_tree):
""" 是否相同 """
if large_tree is None and small_... |
a6c6c80bf6abc2bffd3c9d8d0a9bbf063aa1f075 | lxdeng/sandbox | /dev/python/closure/closure.py | 840 | 4.0625 | 4 | # a closure is a record storing a function together with an environment
# see the following two examples:
# "anonymous closure"
# lambda here defines an anonymous function
# it can access the "x" from the enclosing function startAt()
def startAt(x):
return (lambda y: x + y)
# the value of s1 is closure: the nested ... |
785cc411b175301043eb2aeb07748e804dfe89e7 | Alejo195/BasicsPython | /breakcontinue.py | 694 | 3.71875 | 4 | def run():
# for contador in range(1000):
# if contador % 2 != 0:
# continue
# print(contador)
# for i in range(10000):
# print(i)
# if i == 5678:
# break
# texto = input("Escribe un texto: ")
# for letra in texto:
# if letra == "o":
... |
10013dda201b5d359d23a5267a2eae492dd19ad2 | EvgenijHyva/python_basics | /Tasks2/1.py | 688 | 3.875 | 4 | # 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных
# каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя,
# а указать явно, в программе.
my_list = [7, 7.77, "some_string", None, True, [2, [2, "H... |
18e6238a54f65c383b26fe054a9f5d93685abe40 | lloyd-dong/lab | /think_stats/excercise/e3-1.py | 832 | 3.5 | 4 |
def get_stu_num_of_each_class(dst):
pmf={}
for i in dst:
for j in i:
# if pmf.has_key(j):
# pmf[j] += 1
# else:
# pmf[j]=1
pmf[j] = pmf.get(j,0) +1
return pmf
def get_avg_stu(pmf):
class_num = len(pmf)
avg= float(sum(pmf.values())) /class_num
return avg
def list_dict(pmf):
for k,v in pmf.i... |
16971cbd6d666cd37b33803f08c0c4af22ac3730 | thatDaiwikKashyap/Face-Recognition-With_Pic | /facereco.py | 723 | 3.859375 | 4 | #import CV2 https://pypi.org/project/opencv-python/
import cv2
#Train the code
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Choose an image to detectfaces in
#img = cv2.imread('pic1.jpg')
img = cv2.imread('pic2.jpg')
# Must Convert to grey scale
grayscaled_img = cv2.cvtColor(... |
6a2f6813eccf9dd00d971072b67aed7709ec5a3e | iammiguelmx/course-python | /Module 2/students.py | 342 | 3.890625 | 4 | # L I S T O F S T U D E N T S
# L I S T O F O B J E C T S ✨
students = [
"Luis",
"Miguel",
"Liz",
"Abril"
]
#insert element
students.append("Señora")
# ORDER BY ASC
#students.sort()
# ORDER BY DESC
print("Student 4:", students[0:2])
print("Slicing 4:", students[0:5:2])
# LISTA FULL STUDENT 🤟🏻
... |
ebd0e4edb6555b7fc70f42e70c470abad7b4e76e | allisgao/pcc-study | /Section1_Getting_started/Chapter10/10.4/10-11/10-11_favorite_num-fun.py | 665 | 3.796875 | 4 | # coding=utf-8
import json
""" get and store the number"""
def get_and_store_num():
filename = 'f_num.json'
try:
with open(filename) as f_obj:
f_num = json.load(f_obj)
except FileNotFoundError:
return None
else:
return f_num
""" fetche the number"""
def fetch_num... |
e0d7a8497a6728e2bdd39782a246db5fb1a42927 | hsantillanf/TAREA-1 | /Ejercicios18-20Arreglos.py | 3,156 | 3.9375 | 4 | class arreglos():
def __init__(self):
pass
# Ejercicio18
def ejer18(self):
notas = []
for i in range(10):
datonuev = int( input( "Escribe el dato {}: ".format(i)))
notas.append(datonuev)
print("Las calificaciones son: {}".format(notas))
... |
4f7095c2461810e4a0ff8b7cc8fed51771810854 | NeonedOne/Basic-Python | /Second Lab (2)/17.2. Телефонная книга.py | 369 | 3.65625 | 4 | # Алексей Головлев, группа БСБО-07-19
phone_book = {}
for i in range(int(input())):
data = input().split()
if data[1] not in phone_book:
phone_book[data[1]] = [data[0]]
else:
phone_book[data[1]].append(data[0])
for i in range(int(input())):
name = input()
print(*phone_book.get(name,... |
77073a40b8b371a545c460824854e7cf9ccea4a8 | made-ml-in-prod-2021/mrtimmy89 | /online_inference/src/data/preprocess_data.py | 367 | 3.5 | 4 | """
A small script to make from a .csv file with given data the similar but without a column "target"
"""
import pandas as pd
SOURCE_FILEPATH = "data/raw/heart.csv"
PROCESSED_FILEPATH = "data/processed/data_without_prediction.csv"
df = pd.read_csv(SOURCE_FILEPATH, index_col=["age"])
df_modified = df.drop([... |
96490e9000c6037ec89a467288449281ee12b409 | Gabe1912/pythonForUniYear1 | /Week 1- Question 4.py | 129 | 3.78125 | 4 | x = input("Please enter a sequence of comma-separated numbers: ")
x = x.split(',')
print(x)
x = tuple(x)
print(x)
|
4a2820109fbda493a181284c6daaa1f481c8597a | hackrush01/La-Z-Boy | /La-Z-Boy/updateDB.py | 833 | 3.59375 | 4 | import sqlite3
def updateDB(channel, movieName, timeF, timeT, rating):
sqlite_file ='database/InfoBase.sqlite'
tableName = 'MovieInfo'
#Opening a connection to db
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
#Creates a new db if it doesn't exist
try:
c.execute("CREATE TABLE IF NOT EXISTS `MovieIn... |
f3fa84ce1ebddaf24a95fba75d9dc20bc330bb4e | sagarnikam123/learnNPractice | /pluralSight/pythonBeyondTheBasics/3_beyondBasicFunctions/7_extendedFormalArgumentSyntax.py | 1,563 | 3.84375 | 4 | # 03_07-Extended Formal Argument Syntax
print()
print("one")
print("one", "two")
print("one", "two", "three")
"{a}<===>{b}".format(a="Oslo", b="Stavanger")
def hypervolume(*args):
print(args)
print(type(args))
hypervolume(3,4)
hypervolume(3,4, 5)
def hypervolume(*lengths):
i = iter(lengths)
v = next... |
920622fc11dd9569192287f3d399f3047d068cac | suhasini-viswanadha/basic-programs | /venv/relational_ops.py | 156 | 4.0625 | 4 | a=10
if (a%2==0):
print("a is an even number number")
print("checking if a is an even or odd number")
if (a%2==1):
print("a is an odd number")
|
d78ffd6adb9947ae059a24a5a01c780bac873651 | BCookies222/Python-Codes | /ch11_creating_screen.py | 719 | 3.65625 | 4 | # Create a Screen: FROM HERE ON USING Pyhton 3.1 Earlier Codes Chapter 1-10 are using Python2.7
from livewires import games,color # livewires is a pygame wrapper and games is a module
SCREEN_WIDTH=680
SCREEN_HEIGHT=480
games.init(SCREEN_WIDTH,SCREEN_HEIGHT,fps=50)# games is a module and init is for initialization o... |
3f9b6b7b6f29e9d45bb4869dcbdc68caa1750f15 | STisbi/Python | /GreedyAlgorithms/Dijkstra.py | 9,737 | 3.828125 | 4 | import sys
import re
# Nearly all functions use this
global edgeWeights
# @brief The main algorithm for finding the shortest path
def Dijkstra(source):
# Giant value to simulate infinity
infinity = sys.maxsize
vertexList = CreateVertexList()
# Create the queue with the source as the first e... |
191244c86b7f1c92a3d73b702e4094ba93c716d0 | Asigi/tkinter-in-Python | /tkinterGUI.py | 4,040 | 4.3125 | 4 | from tkinter import *
def doNothing():
print("OK I wont")
root = Tk() # constructor that creates a blank window.
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu) #subMenu is within menu
menu.add_cascade(label="File", menu = subMenu) #gives dropdown functionality to File button
subMenu.add_comma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.